Skip to content
Merged
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
2 changes: 2 additions & 0 deletions crates/utopia-server/src/api/google_drive_routes_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
118 changes: 109 additions & 9 deletions crates/utopia-server/src/ingest_sources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<DateTime<Utc>>,
}

Expand Down Expand Up @@ -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<SyncStats> {
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);
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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<String> = 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;
Expand Down Expand Up @@ -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);
}
Expand Down
2 changes: 1 addition & 1 deletion crates/utopia-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading