diff --git a/crates/utopia-server/src/api/google_drive_routes_tests.rs b/crates/utopia-server/src/api/google_drive_routes_tests.rs index 504fc8378..73ff520fd 100644 --- a/crates/utopia-server/src/api/google_drive_routes_tests.rs +++ b/crates/utopia-server/src/api/google_drive_routes_tests.rs @@ -402,10 +402,12 @@ async fn a_sync_stops_once_the_connected_person_is_no_longer_an_editor() -> anyh let reason = |e: anyhow::Error| format!("{e:#}"); let while_editor = crate::ingest_sources::sync_source(&fx.state, fx.source) .await + .map(|_| ()) .map_err(reason); fx.demote_connector().await?; let after = crate::ingest_sources::sync_source(&fx.state, fx.source) .await + .map(|_| ()) .map_err(reason); let says_reconnect = |r: &Result<(), String>| { r.as_ref() diff --git a/crates/utopia-server/src/ingest_sources.rs b/crates/utopia-server/src/ingest_sources.rs index 17b97891c..a9cf842f7 100644 --- a/crates/utopia-server/src/ingest_sources.rs +++ b/crates/utopia-server/src/ingest_sources.rs @@ -43,6 +43,13 @@ pub struct SyncStats { pub discovered: usize, pub queued_for_content: usize, pub content_terminal: usize, + /// 这一轮因为触顶而没走完,`since` 不能前进(#1212 / ADR 0072 的 Custom) + /// + /// 上一条成功那一轮的 `started_at` 是下一次的下界;本轮要是记 `ok`,下界就跨过了 + /// 这批还没读到的条目,之后每一轮都够不着它们。这里标出来,`sync_source` 据此把 + /// 游标留在原处,本轮的 created / updated 照旧记进审计。 + pub incomplete: bool, + /// 这一轮读到的位置(GitHub / Jira 的更新时刻,ADR 0072) pub checkpoint: Option>, } @@ -79,18 +86,31 @@ fn reads_by_timestamp(kind: SourceKind) -> bool { ) } -pub async fn sync_source(state: &AppState, source_id: Uuid) -> anyhow::Result<()> { +pub async fn sync_source(state: &AppState, source_id: Uuid) -> anyhow::Result { let source = utopia_store::sources::get(&state.pool, source_id).await?; let kind = SourceKind::parse(&source.kind); + // #1212 / ADR 0072:下界取自**这个来源自己的游标**。 + // + // - 工单来源(GitHub / Jira):游标是消费到的更新时刻,且那一刻的整组都读完了。 + // - custom:游标是**这一轮整条响应走完时**推进到的时刻(见下面 `round_started_at`)。 + // + // **游标是源自己的一列,不是从跑次推出来的。** 早先的下界取自「上一条 `ok` 跑次的 + // `started_at`」——那说的是「上一轮什么时候开始」,不是「上一轮读到哪」;一轮没读完 + // 的时候,两者不是一回事,而下界一旦越过没读到的条目,之后每一轮都够不着它们。 + // + // 游标存在源上,于是它能被**一次性清空**(ADR 0072 的 Recovery 一节):老来源的 + // 游标是 NULL,它们从头再来一遍,靠文档、版本与处理任务的去重,未变的内容不会 + // 变成新版本。 let since = match kind { - Some(SourceKind::Custom) => { - utopia_store::sources::last_successful_sync_start(&state.pool, source_id).await? - } - Some(kind) if reads_by_timestamp(kind) => { + Some(kind) if kind == SourceKind::Custom || reads_by_timestamp(kind) => { utopia_store::sources::sync_checkpoint(&state.pool, source_id).await? } _ => None, }; + // **这一轮开始的时刻。** custom 的游标推进到这里,而不是推进到「现在」: + // 运行期间到达的改动必须留在下一轮的窗口里(ADR 0072 的 Custom 一节 + // 「preserving the existing protection for changes during the run」)。 + let round_started_at = Utc::now(); utopia_store::sources::mark_running(&state.pool, source_id).await?; let run_id = utopia_store::sources::start_run(&state.pool, source_id).await?; state.emit_source(source.kb_id); @@ -122,7 +142,62 @@ pub async fn sync_source(state: &AppState, source_id: Uuid) -> anyhow::Result<() None => Err(anyhow::anyhow!("unknown source kind `{}`", source.kind)), }; + // 没走完这一轮:游标留在原处,但这一轮已经做成的部分照旧记进审计 + // (ADR 0072 的「Keep the committed counts visible for incomplete runs」)。 + // run 写 `failed` 而不是 `ok`:游标只在这一轮整条响应都走完时才前进, + // 所以这一轮没走完,下一轮就从原处接着读。 + if let Ok(stats) = &outcome { + if stats.incomplete { + let err = format!( + "changed {MAX_NEW_PER_SYNC} items and stopped with more behind; \ + the checkpoint stays where it was, so the next sync resumes here" + ); + utopia_store::sources::finish_run( + &state.pool, + run_id, + source_id, + Some(&err), + stats.created as i32, + stats.updated as i32, + ) + .await?; + utopia_store::sources::finish_sync_quiet( + &state.pool, + source_id, + &err, + stats.total() as i32, + ) + .await?; + state.emit_source(source.kb_id); + tracing::warn!( + %source_id, + kind = %source.kind, + created = stats.created, + updated = stats.updated, + discovered = stats.discovered, + "来源同步未读完,游标不前进" + ); + return Ok(*stats); + } + } let outcome = match outcome { + // custom:这一轮把**整条响应**都走完了,游标推进到**这一轮开始的时刻**。 + // 不是推进到现在——运行期间到达的改动还在下一轮的窗口里,它们还没被走过。 + // 触顶那一轮(`incomplete`)走不到这里:游标留在原处,下一轮从那儿接着读。 + Ok(stats) if matches!(kind, Some(SourceKind::Custom)) => { + utopia_store::sources::finish_timestamp_sync( + &state.pool, + run_id, + source_id, + since, + Some(round_started_at), + stats.created as i32, + stats.updated as i32, + ) + .await + .map(|()| stats) + .map_err(anyhow::Error::from) + } Ok(stats) if kind.is_some_and(reads_by_timestamp) => { utopia_store::sources::finish_timestamp_sync( &state.pool, @@ -141,7 +216,7 @@ pub async fn sync_source(state: &AppState, source_id: Uuid) -> anyhow::Result<() }; match outcome { Ok(stats) => { - if !kind.is_some_and(reads_by_timestamp) { + if !kind.is_some_and(|k| k == SourceKind::Custom || reads_by_timestamp(k)) { utopia_store::sources::finish_run( &state.pool, run_id, @@ -170,7 +245,7 @@ pub async fn sync_source(state: &AppState, source_id: Uuid) -> anyhow::Result<() content_terminal = stats.content_terminal, "来源同步完成" ); - Ok(()) + Ok(stats) } Err(e) => { utopia_store::sources::finish_run( @@ -1453,9 +1528,30 @@ async fn sync_custom( .as_array() .ok_or_else(|| anyhow::anyhow!("Response is missing the items[] array"))?; - let mut stats = SyncStats::default(); + // `discovered` 记响应里的条数,不是跑进来的条数——否则日志与警告会读成 `(0 > 200)` + let mut stats = SyncStats { + discovered: items.len(), + ..Default::default() + }; let mut seen_keys: Vec = Vec::new(); - for item in items.iter().take(MAX_NEW_PER_SYNC) { + // **走完整个响应,只把有变的条目记在预算上**(ADR 0072 的 Custom 一节)。 + // `take(MAX_NEW_PER_SYNC)` 是 ADR 明写在 Rejected 里的那条:它取走的永远是同样的 + // 前 200 条,重试一万次也够不到第 201 条。这里每条都先问 `ingest_item`,只有 + // `Created` / `Updated` 才计入 `changed`;`Unchanged` / `Moved` / `Duplicate` + // 让预算不被消耗,于是重试能把没变的前缀让过去、走到剩下的那几条。 + let mut changed = 0usize; + for item in items.iter() { + // 预算满了就不再往下走——剩下的留在下一轮,且本轮 `incomplete` 让游标留在原处 + if changed >= MAX_NEW_PER_SYNC { + stats.incomplete = true; + tracing::warn!( + source_id = %source.id, + imported = changed, + remaining = items.len().saturating_sub(seen_keys.len()), + "custom 本轮用满 {MAX_NEW_PER_SYNC} 条预算,还有条目没读到;游标不前进,下一轮接着走" + ); + break; + } let Some(id) = item["id"].as_str().map(str::trim).filter(|s| !s.is_empty()) else { tracing::warn!(source_id = %source.id, "custom item 缺少 id,跳过"); continue; @@ -1487,6 +1583,10 @@ async fn sync_custom( doc_time, ) .await?; + match action { + IngestAction::Created | IngestAction::Updated => changed += 1, + _ => {} + } stats.absorb(action); seen_keys.push(key); } diff --git a/crates/utopia-server/src/main.rs b/crates/utopia-server/src/main.rs index f916f4507..0fc82fb08 100644 --- a/crates/utopia-server/src/main.rs +++ b/crates/utopia-server/src/main.rs @@ -679,7 +679,7 @@ async fn dispatch(st: &state::AppState, job: &utopia_store::jobs::Job) -> anyhow .and_then(|v| v.as_str()) .and_then(|s| s.parse().ok()) .ok_or_else(|| anyhow::anyhow!("payload 缺少 source_id"))?; - ingest_sources::sync_source(st, source_id).await + ingest_sources::sync_source(st, source_id).await.map(|_| ()) } "hydrate_rss_entry" => { let source_id: Uuid = job diff --git a/crates/utopia-server/src/source_checkpoint_tests.rs b/crates/utopia-server/src/source_checkpoint_tests.rs index 805e12115..7155c37ea 100644 --- a/crates/utopia-server/src/source_checkpoint_tests.rs +++ b/crates/utopia-server/src/source_checkpoint_tests.rs @@ -54,6 +54,16 @@ async fn retry_reads_the_uncovered_window( .bind(started + chrono::Duration::hours(1)) .execute(&pool) .await?; + // **源自己的游标落在那一刻**(ADR 0072)。 + // + // 从前下界是从跑次推出来的——上一条 `ok` 的 `started_at`。那有两个问题: + // 它证不了那个窗口被读完(触顶那一轮也记过 `ok`),而且它没法清空,所以 + // 老来源没法一次性从头再来一遍(0072 的 Recovery 一节)。 + sqlx::query("UPDATE sources SET sync_checkpoint=$2 WHERE id=$1") + .bind(source) + .bind(started) + .execute(&pool) + .await?; utopia_store::sources::touch_sync_time(&pool, source, started + chrono::Duration::hours(1)) .await?; } @@ -100,7 +110,7 @@ async fn retry_reads_the_uncovered_window( let last = last.expect("没有带下界:增量拉取整个没了"); assert!( (last - started).num_seconds().abs() <= 1, - "下界应当是上一次成功那轮的开始 {started},实得 {last}" + "下界应当是源自己的游标(上一轮成功那轮的开始){started},实得 {last}" ); assert!(last < changed, "下界晚于那次改动,漏掉的窗口又被跳过了"); } else { @@ -135,3 +145,464 @@ async fn retry_keeps_updates_from_the_previous_successful_run_window() -> anyhow async fn updates_during_a_successful_sync_remain_in_the_next_window() -> anyhow::Result<()> { retry_reads_the_uncovered_window(true, false).await } + +/// #1212 / ADR 0072(Custom 一节):201 条全都变了,第一轮装下 200 条就停, +/// 第二轮把没变的前缀让过去、走到第 201 条。 +/// +/// 关键的两条性质都在这里: +/// +/// 1. 触顶那一轮 `incomplete` → run 写 `failed` → 下界不前进 → 第二轮拿到的还是同一条 +/// since,因此前 200 条原样回来、但它们现在都是 `Unchanged` 不占预算,第 201 条 +/// 这次够得着了。ADR 把「取走同样的前 200 条」列在 Rejected 里说的就是这条。 +/// 2. `stats.discovered` 记的是响应里的条数(201),不是跑进来的条数(200)—— +/// 否则日志与那条警告会读成 `(0 > 200)`。 +#[tokio::test] +async fn a_truncated_custom_batch_resumes_on_the_next_run() -> anyhow::Result<()> { + let Some(url) = utopia_store::test_db::url() else { + return Ok(()); + }; + let pool = sqlx::PgPool::connect(&url).await?; + let (org, ws, kb, source) = ( + Uuid::now_v7(), + Uuid::now_v7(), + Uuid::now_v7(), + Uuid::now_v7(), + ); + sqlx::query("INSERT INTO organizations(id,name) VALUES($1,'truncation-test')") + .bind(org) + .execute(&pool) + .await?; + sqlx::query("INSERT INTO workspaces(id,org_id,name) VALUES($1,$2,'truncation-test')") + .bind(ws) + .bind(org) + .execute(&pool) + .await?; + sqlx::query( + "INSERT INTO knowledge_bases(id,workspace_id,name) VALUES($1,$2,'truncation-test')", + ) + .bind(kb) + .bind(ws) + .execute(&pool) + .await?; + + // **来源先插,`start_run` 后跑**:source_sync_runs.source_id 上有外键, + // 反过来插会以 `source_sync_runs_source_id_fkey` 失败。 + let server = MockServer::start().await; + sqlx::query( + "INSERT INTO sources(id,kb_id,kind,name,config) VALUES($1,$2,'custom','fixture',$3)", + ) + .bind(source) + .bind(kb) + .bind(serde_json::json!({ "endpoint": server.uri() })) + .execute(&pool) + .await?; + + // 201 条,全部是新的:每一轮都会重新拿到它们 + let all: Vec = (0..201u32) + .map(|i| { + serde_json::json!({ + "id": format!("item-{i}"), + "title": format!("Item {i}"), + "content": format!("Body {i}"), + }) + }) + .collect(); + let served = all.clone(); + Mock::given(method("GET")) + .respond_with(move |_req: &Request| { + ResponseTemplate::new(200).set_body_json(serde_json::json!({ "items": served })) + }) + .mount(&server) + .await; + + let dir = std::env::temp_dir().join(format!("utopia-truncation-{source}")); + let cfg = utopia_core::config::AppConfig { + data_dir: dir.to_string_lossy().into_owned(), + ..Default::default() + }; + let search = Arc::new(utopia_search::SearchIndex::open(&dir.join("search"))?); + let state = crate::state::AppState::new(pool.clone(), &cfg, search, "test-only".into()); + + let result = async { + // 第一轮:201 > 200,触顶 + let stats = sync_source(&state, source).await?; + assert_eq!( + stats.discovered, 201, + "整条响应都读了,不是只读到预算那一段" + ); + let first = utopia_store::sources::get(&pool, source).await?; + assert_eq!( + first.last_sync_status, "failed", + "触顶的那一轮不能记为 'ok',否则下界会越过还没读到的条目" + ); + assert!( + first + .last_sync_error + .as_deref() + .unwrap_or_default() + .contains("stopped with more"), + "错误要说明为什么停:{:?}", + first.last_sync_error + ); + let imported: i64 = sqlx::query_scalar( + "SELECT count(*) FROM documents WHERE source_id=$1 AND deleted_at IS NULL", + ) + .bind(source) + .fetch_one(&pool) + .await?; + assert_eq!(imported, 200, "第一轮装得下 200 条,第 201 条得等下一轮"); + + // 第二轮:同一批原样回来,前 200 条是 Unchanged 不占预算,第 201 条这次够得着 + let stats = sync_source(&state, source).await?; + assert_eq!( + stats.discovered, 201, + "整条响应都读了,不是只读到预算那一段" + ); + let imported: i64 = sqlx::query_scalar( + "SELECT count(*) FROM documents WHERE source_id=$1 AND deleted_at IS NULL", + ) + .bind(source) + .fetch_one(&pool) + .await?; + assert_eq!(imported, 201, "第二轮之后 201 条都在库里了"); + let last = utopia_store::sources::get(&pool, source).await?; + assert_eq!( + last.last_sync_status, "ok", + "这一轮走完了,可以记 ok 让游标前进" + ); + Ok::<_, anyhow::Error>(()) + } + .await; + + sqlx::query("DELETE FROM knowledge_bases WHERE id=$1") + .bind(kb) + .execute(&pool) + .await?; + sqlx::query("DELETE FROM organizations WHERE id=$1") + .bind(org) + .execute(&pool) + .await?; + drop(state); + let _ = std::fs::remove_dir_all(dir); + result +} + +/// **450 条分三轮读完**(0072 的验收项)。 +/// +/// 预算 200,而没变的条目不占预算:所以第二轮能把前 200 条当没变的前缀让过去, +/// 第三轮把剩下的 50 条收掉。每一轮都读了整条响应——`discovered` 一直是 450, +/// 不是预算那一段。 +#[tokio::test] +async fn a_capped_custom_batch_is_read_whole_over_three_rounds() -> anyhow::Result<()> { + let Some(url) = utopia_store::test_db::url() else { + return Ok(()); + }; + let pool = sqlx::PgPool::connect(&url).await?; + let (org, ws, kb, source) = ( + Uuid::now_v7(), + Uuid::now_v7(), + Uuid::now_v7(), + Uuid::now_v7(), + ); + sqlx::query("INSERT INTO organizations(id,name) VALUES($1,'three-round-test')") + .bind(org) + .execute(&pool) + .await?; + sqlx::query("INSERT INTO workspaces(id,org_id,name) VALUES($1,$2,'three-round-test')") + .bind(ws) + .bind(org) + .execute(&pool) + .await?; + sqlx::query( + "INSERT INTO knowledge_bases(id,workspace_id,name) VALUES($1,$2,'three-round-test')", + ) + .bind(kb) + .bind(ws) + .execute(&pool) + .await?; + + // **来源先插,`start_run` 后跑**:source_sync_runs.source_id 上有外键, + // 反过来插会以 `source_sync_runs_source_id_fkey` 失败。 + let server = MockServer::start().await; + sqlx::query( + "INSERT INTO sources(id,kb_id,kind,name,config) VALUES($1,$2,'custom','fixture',$3)", + ) + .bind(source) + .bind(kb) + .bind(serde_json::json!({ "endpoint": server.uri() })) + .execute(&pool) + .await?; + + // 450 条,全部是新的:每一轮都会重新拿到它们 + let all: Vec = (0..450u32) + .map(|i| { + serde_json::json!({ + "id": format!("item-{i}"), + "title": format!("Item {i}"), + "content": format!("Body {i}"), + }) + }) + .collect(); + let served = all.clone(); + Mock::given(method("GET")) + .respond_with(move |_req: &Request| { + ResponseTemplate::new(200).set_body_json(serde_json::json!({ "items": served })) + }) + .mount(&server) + .await; + + let dir = std::env::temp_dir().join(format!("utopia-three-round-{source}")); + let cfg = utopia_core::config::AppConfig { + data_dir: dir.to_string_lossy().into_owned(), + ..Default::default() + }; + let search = Arc::new(utopia_search::SearchIndex::open(&dir.join("search"))?); + let state = crate::state::AppState::new(pool.clone(), &cfg, search, "test-only".into()); + + let result = async { + // 第一轮:装下 200 条,触顶,游标留在原处 + let stats = sync_source(&state, source).await?; + assert_eq!( + stats.discovered, 450, + "整条响应都读了,不是只读到预算那一段" + ); + let imported: i64 = sqlx::query_scalar( + "SELECT count(*) FROM documents WHERE source_id=$1 AND deleted_at IS NULL", + ) + .bind(source) + .fetch_one(&pool) + .await?; + assert_eq!(imported, 200, "第一轮装得下 200 条,剩下的留给下一轮"); + let first = utopia_store::sources::get(&pool, source).await?; + assert_eq!( + first.last_sync_status, "failed", + "触顶的那一轮不能记为 'ok',否则游标会越过还没读到的条目" + ); + assert!( + utopia_store::sources::sync_checkpoint(&pool, source) + .await? + .is_none(), + "触顶那一轮游标留在原处,下一轮从那儿接着读" + ); + // 触顶不是连接坏了:这一轮记成 `failed`,但**不发** source.sync_failed 告警 + // (同一件事天天报,#1212)。 + let alerts: i64 = sqlx::query_scalar( + "SELECT count(*) FROM alerts WHERE subject_id=$1 AND kind='source.sync_failed'", + ) + .bind(source) + .fetch_one(&pool) + .await?; + assert_eq!(alerts, 0, "触顶的那一轮不该发同步失败告警"); + + // 第二轮:前 200 条原样回来(Unchanged,不占预算),再装下 200 条,又触顶 + let stats = sync_source(&state, source).await?; + assert_eq!( + stats.discovered, 450, + "整条响应都读了,不是只读到预算那一段" + ); + let imported: i64 = sqlx::query_scalar( + "SELECT count(*) FROM documents WHERE source_id=$1 AND deleted_at IS NULL", + ) + .bind(source) + .fetch_one(&pool) + .await?; + assert_eq!(imported, 400, "第二轮之后 400 条都在库里了"); + let second = utopia_store::sources::get(&pool, source).await?; + assert_eq!( + second.last_sync_status, "failed", + "第二轮又触顶,游标仍然不前进" + ); + assert!( + utopia_store::sources::sync_checkpoint(&pool, source) + .await? + .is_none(), + "触顶那一轮游标留在原处,下一轮从那儿接着读" + ); + + // 第三轮:前 400 条原样回来,把剩下的 50 条收掉,这一轮走完了 + let stats = sync_source(&state, source).await?; + assert_eq!( + stats.discovered, 450, + "整条响应都读了,不是只读到预算那一段" + ); + let imported: i64 = sqlx::query_scalar( + "SELECT count(*) FROM documents WHERE source_id=$1 AND deleted_at IS NULL", + ) + .bind(source) + .fetch_one(&pool) + .await?; + assert_eq!(imported, 450, "第三轮之后 450 条都在库里了"); + let third = utopia_store::sources::get(&pool, source).await?; + assert_eq!( + third.last_sync_status, "ok", + "这一轮走完了,可以记 ok 让游标前进" + ); + assert!( + utopia_store::sources::sync_checkpoint(&pool, source) + .await? + .is_some(), + "走完的那一轮把游标推进了" + ); + Ok::<_, anyhow::Error>(()) + } + .await; + + sqlx::query("DELETE FROM knowledge_bases WHERE id=$1") + .bind(kb) + .execute(&pool) + .await?; + sqlx::query("DELETE FROM organizations WHERE id=$1") + .bind(org) + .execute(&pool) + .await?; + drop(state); + let _ = std::fs::remove_dir_all(dir); + result +} + +/// **端点自己记的账**:每条工单的 id、正文、它是什么时候改的。协议里没有这个 +/// 字段——这是端点自己的账,用来决定回哪几条。 +type Feed = Arc)>>>; + +/// **运行期间到达的改动,下一轮还够得着**(ADR 0072 的 Custom 一节: +/// "preserving the existing protection for changes during the run")。 +/// +/// 游标推进到**这一轮开始的时刻**,不是推进到现在:端点在第一轮被问的时候改了 +/// 一条工单(更新时刻在那一轮开始之后),第二轮的下界必须还在那条改动之前, +/// 否则它就永远读不到了。 +/// +/// 这条断言有牙:把游标改成「推进到现在」,端点就会因为下界太晚而什么都不给, +/// 这条工单也就永远进不来。 +#[tokio::test] +async fn an_item_changed_during_a_round_is_still_read_by_the_next_one() -> anyhow::Result<()> { + let Some(url) = utopia_store::test_db::url() else { + return Ok(()); + }; + let pool = sqlx::PgPool::connect(&url).await?; + let (org, ws, kb, source) = ( + Uuid::now_v7(), + Uuid::now_v7(), + Uuid::now_v7(), + Uuid::now_v7(), + ); + sqlx::query("INSERT INTO organizations(id,name) VALUES($1,'concurrent-test')") + .bind(org) + .execute(&pool) + .await?; + sqlx::query("INSERT INTO workspaces(id,org_id,name) VALUES($1,$2,'concurrent-test')") + .bind(ws) + .bind(org) + .execute(&pool) + .await?; + sqlx::query( + "INSERT INTO knowledge_bases(id,workspace_id,name) VALUES($1,$2,'concurrent-test')", + ) + .bind(kb) + .bind(ws) + .execute(&pool) + .await?; + let server = MockServer::start().await; + sqlx::query( + "INSERT INTO sources(id,kb_id,kind,name,config) VALUES($1,$2,'custom','fixture',$3)", + ) + .bind(source) + .bind(kb) + .bind(serde_json::json!({ "endpoint": server.uri() })) + .execute(&pool) + .await?; + + // **端点自己记着每条工单是什么时候改的**(协议里没有这个字段,是端点自己的账)。 + // 第一次被问的时候,它顺手把一条改了、又添了一条——改动时刻落在这一轮开始之后。 + let feed: Feed = Arc::new(std::sync::Mutex::new(vec![( + "item-0".to_string(), + "Body 0".to_string(), + chrono::Utc::now() - chrono::Duration::hours(1), + )])); + let served = feed.clone(); + let asked = Arc::new(std::sync::Mutex::new(Vec::< + Option>, + >::new())); + let seen = asked.clone(); + Mock::given(method("GET")) + .respond_with(move |req: &Request| { + let since = req + .url + .query_pairs() + .find(|(k, _)| k == "since") + .map(|(_, v)| { + chrono::DateTime::parse_from_rfc3339(&v) + .unwrap() + .with_timezone(&chrono::Utc) + }); + seen.lock().unwrap().push(since); + let mut feed = served.lock().unwrap(); + // 端点只给「下界之后改过的」那些(custom 协议:下界由端点自己解释) + let items: Vec = feed + .iter() + .filter(|(_, _, changed_at)| since.is_none_or(|s| *changed_at > s)) + .map(|(id, content, changed_at)| { + serde_json::json!({ + "id": id, + "title": format!("Item {id}"), + "content": content, + "doc_time": changed_at.to_rfc3339(), + }) + }) + .collect(); + // 答完这一轮顺手改一条、添一条——改动时刻落在这一轮开始之后, + // 所以**下一轮**才看得到(这一轮答的是改动之前的样子) + if feed.len() == 1 { + let now = chrono::Utc::now(); + feed[0].1 = "Body 0, changed".to_string(); + feed[0].2 = now; + feed.push(("item-1".to_string(), "Body 1".to_string(), now)); + } + ResponseTemplate::new(200).set_body_json(serde_json::json!({ "items": items })) + }) + .mount(&server) + .await; + + let dir = std::env::temp_dir().join(format!("utopia-concurrent-{source}")); + let cfg = utopia_core::config::AppConfig { + data_dir: dir.to_string_lossy().into_owned(), + ..Default::default() + }; + let search = Arc::new(utopia_search::SearchIndex::open(&dir.join("search"))?); + let state = crate::state::AppState::new(pool.clone(), &cfg, search, "test-only".into()); + + let result = async { + // 第一轮:只有 item-0,读完就走完了 + let first = sync_source(&state, source).await?; + assert_eq!(first.created, 1, "第一轮只有 item-0"); + let checkpoint = utopia_store::sources::sync_checkpoint(&pool, source).await?; + assert!(checkpoint.is_some(), "这一轮走完了,游标该落下来"); + + // 第二轮:端点现在有两条改过的,下界必须还在它们的改动之前 + let second = sync_source(&state, source).await?; + let imported: i64 = sqlx::query_scalar( + "SELECT count(*) FROM documents WHERE source_id=$1 AND deleted_at IS NULL", + ) + .bind(source) + .fetch_one(&pool) + .await?; + assert_eq!( + imported, 2, + "运行期间改的那一条、添的那一条,下一轮都得进来(游标要停在那一轮**开始**的时刻,不是结束的时刻)" + ); + assert_eq!(second.updated, 1, "item-0 是改过的,item-1 是新的"); + Ok::<_, anyhow::Error>(()) + } + .await; + + sqlx::query("DELETE FROM knowledge_bases WHERE id=$1") + .bind(kb) + .execute(&pool) + .await?; + sqlx::query("DELETE FROM organizations WHERE id=$1") + .bind(org) + .execute(&pool) + .await?; + drop(state); + let _ = std::fs::remove_dir_all(dir); + result +} diff --git a/crates/utopia-store/src/sources.rs b/crates/utopia-store/src/sources.rs index 265277e71..a73fb3df2 100644 --- a/crates/utopia-store/src/sources.rs +++ b/crates/utopia-store/src/sources.rs @@ -571,7 +571,40 @@ pub async fn sync_checkpoint(pool: &PgPool, source_id: Uuid) -> AppResult