Skip to content

feat: add minimal implementation of changesStream for registry mirroring #1025

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 16 additions & 0 deletions api/migrations/20250402220510_changes.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
CREATE TYPE change_type AS ENUM (
'PACKAGE_VERSION_ADDED',
'PACKAGE_TAG_ADDED'
);

CREATE TABLE changes (
seq BIGSERIAL PRIMARY KEY,
change_type change_type NOT NULL,
scope_name text NOT NULL,
package_name text NOT NULL,
data TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX changes_scope_name_idx ON changes (scope_name, package_name);
CREATE INDEX changes_created_at_idx ON changes (created_at);
165 changes: 165 additions & 0 deletions api/src/api/changes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
// Copyright 2024 the JSR authors. All rights reserved. MIT license.
use hyper::{Body, Request};
use routerify::prelude::*;
use serde::{Deserialize, Serialize};
use tracing::instrument;

use crate::{
db::{Change, Database},
util::{pagination, ApiResult},
};

#[derive(Serialize, Deserialize)]
pub struct ApiChange {
pub seq: i64,
pub r#type: String,
pub id: String,
pub changes: serde_json::Value,
}

impl From<Change> for ApiChange {
fn from(change: Change) -> Self {
Self {
seq: change.seq,
r#type: change.change_type.to_string(),
id: format!("@jsr/{}__{}", change.scope_name, change.package_name),
changes: serde_json::from_str(&change.data).unwrap(),
}
}
}

#[instrument(name = "GET /api/_changes", skip(req), err)]
pub async fn list_changes(req: Request<Body>) -> ApiResult<Vec<ApiChange>> {
let db = req.data::<Database>().unwrap();
let (start, limit) = pagination(&req);
let changes = db.list_changes(start, limit).await?;
Ok(changes.into_iter().map(ApiChange::from).collect())
}

#[cfg(test)]
mod tests {
use super::ApiChange;
use crate::db::ChangeType;
use crate::ids::PackageName;
use crate::ids::ScopeName;
use crate::util::test::ApiResultExt;
use crate::util::test::TestSetup;
use serde_json::json;

#[tokio::test]
async fn list_empty_changes() {
let mut t = TestSetup::new().await;

let changes = t
.http()
.get("/api/_changes")
.call()
.await
.unwrap()
.expect_ok::<Vec<ApiChange>>()
.await;

assert!(changes.is_empty());
}

#[tokio::test]
async fn list_single_change() {
let mut t = TestSetup::new().await;

t.ephemeral_database
.create_change(
ChangeType::PackageVersionAdded,
&ScopeName::new("test-scope".to_string()).unwrap(),
&PackageName::new("test-package".to_string()).unwrap(),
json!({
"version": "1.0.0"
}),
)
.await
.unwrap();

let changes = t
.http()
.get("/api/_changes")
.call()
.await
.unwrap()
.expect_ok::<Vec<ApiChange>>()
.await;

assert_eq!(changes.len(), 1);
let change = &changes[0];
assert_eq!(change.r#type, ChangeType::PackageVersionAdded.to_string());
assert_eq!(change.id, "@jsr/test-scope__test-package");
assert_eq!(change.changes["version"], "1.0.0");
}

#[tokio::test]
async fn list_changes_pagination() {
let mut t = TestSetup::new().await;

// Create two changes
t.ephemeral_database
.create_change(
ChangeType::PackageVersionAdded,
&ScopeName::new("test-scope".to_string()).unwrap(),
&PackageName::new("test-package-1".to_string()).unwrap(),
json!({
"name": "test-package-1",
}),
)
.await
.unwrap();

t.ephemeral_database
.create_change(
ChangeType::PackageVersionAdded,
&ScopeName::new("test-scope".to_string()).unwrap(),
&PackageName::new("test-package-2".to_string()).unwrap(),
json!({
"version": "1.0.0",
}),
)
.await
.unwrap();

// Test limit parameter
let changes = t
.http()
.get("/api/_changes?limit=1&since=0")
.call()
.await
.unwrap()
.expect_ok::<Vec<ApiChange>>()
.await;

assert_eq!(changes.len(), 1);
assert_eq!(changes[0].id, "@jsr/test-scope__test-package-1");

// Test since parameter
let changes = t
.http()
.get(format!("/api/_changes?since={}", changes[0].seq))
.call()
.await
.unwrap()
.expect_ok::<Vec<ApiChange>>()
.await;

assert_eq!(changes.len(), 1);
assert_eq!(changes[0].id, "@jsr/test-scope__test-package-2");

// Test since + limit combination
let changes = t
.http()
.get("/api/_changes?since=0&limit=1")
.call()
.await
.unwrap()
.expect_ok::<Vec<ApiChange>>()
.await;

assert_eq!(changes.len(), 1);
assert_eq!(changes[0].id, "@jsr/test-scope__test-package-1");
}
}
3 changes: 3 additions & 0 deletions api/src/api/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright 2024 the JSR authors. All rights reserved. MIT license.
mod admin;
mod authorization;
mod changes;
mod errors;
mod package;
mod publishing_task;
Expand All @@ -9,6 +10,7 @@ mod self_user;
mod types;
mod users;

use changes::list_changes;
use hyper::Body;
use hyper::Response;
use package::global_list_handler;
Expand Down Expand Up @@ -40,6 +42,7 @@ pub fn api_router() -> Router<Body, ApiError> {
util::json(global_metrics_handler),
),
)
.get("/_changes", util::json(list_changes))
.middleware(Middleware::pre(util::auth_middleware))
.scope("/admin", admin_router())
.scope("/scopes", scope_router())
Expand Down
Loading