Skip to content

Commit d9bb2c8

Browse files
committed
Keep sources schedulable when sync job insertion fails
Signed-off-by: Floating-Y <118035379+Floating-Y@users.noreply.github.com>
1 parent c8aedf9 commit d9bb2c8

5 files changed

Lines changed: 308 additions & 39 deletions

File tree

‎crates/utopia-server/src/api/google_drive_routes.rs‎

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -469,13 +469,7 @@ pub async fn select(
469469
)
470470
.await?;
471471
if !body.folders.is_empty() {
472-
let _ = utopia_store::sources::mark_queued(&state.pool, source_id).await;
473-
utopia_store::jobs::enqueue(
474-
&state.pool,
475-
"sync_source",
476-
json!({ "source_id": source_id }),
477-
)
478-
.await?;
472+
utopia_store::sources::enqueue_sync_after_config_change(&state.pool, source_id).await?;
479473
}
480474
state.emit_source(kb_id);
481475
let _ = utopia_store::audit::record(

‎crates/utopia-server/src/api/google_drive_routes_tests.rs‎

Lines changed: 265 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
//! 连接流程的几道关卡与「谁连上的谁来选」(0074 决定 3、5),连真库跑。
22
//! 测试环境没配 OAuth 客户端:过了所有关卡的回调停在「没配置」,不会去敲 Google
33
use super::*;
4+
use axum::body::{to_bytes, Body};
5+
use axum::http::{Request, StatusCode};
46
use std::sync::Arc;
7+
use tower::ServiceExt;
58
use utopia_core::models::User;
69

710
struct Fixture {
@@ -114,6 +117,268 @@ impl Fixture {
114117
.await?
115118
.config)
116119
}
120+
121+
async fn sync_http(&self) -> anyhow::Result<(StatusCode, Value)> {
122+
self.post_http(
123+
&format!("/api/v1/kbs/{}/sources/{}/sync", self.kb, self.source),
124+
json!({}),
125+
)
126+
.await
127+
}
128+
129+
async fn post_http(&self, path: &str, body: Value) -> anyhow::Result<(StatusCode, Value)> {
130+
let token = crate::auth::issue_token(&self.state, self.connector.id)?;
131+
let response = super::super::router(self.state.clone(), &Default::default())
132+
.oneshot(
133+
Request::post(path)
134+
.header("Authorization", format!("Bearer {token}"))
135+
.header("Content-Type", "application/json")
136+
.body(Body::from(body.to_string()))?,
137+
)
138+
.await?;
139+
let status = response.status();
140+
let bytes = to_bytes(response.into_body(), 1 << 20).await?;
141+
Ok((status, serde_json::from_slice(&bytes)?))
142+
}
143+
144+
async fn sync_state(&self) -> anyhow::Result<(String, i64)> {
145+
Ok(sqlx::query_as(
146+
"SELECT last_sync_status,
147+
(SELECT count(*) FROM jobs WHERE kind = 'sync_source'
148+
AND payload->>'source_id' = sources.id::text)
149+
FROM sources WHERE id = $1",
150+
)
151+
.bind(self.source)
152+
.fetch_one(&self.pool)
153+
.await?)
154+
}
155+
156+
async fn choose_folder(&self, id: &str) -> ApiResult<Json<Value>> {
157+
select(
158+
State(self.state.clone()),
159+
AuthUser(self.connector.clone()),
160+
Path((self.kb, self.source)),
161+
Json(SelectBody {
162+
folders: vec![FolderEntry {
163+
id: id.into(),
164+
name: id.into(),
165+
}],
166+
}),
167+
)
168+
.await
169+
}
170+
171+
async fn reject_sync_jobs(&self, reject: bool) -> anyhow::Result<()> {
172+
// Install once: dropping a table trigger between tests can deadlock parallel fixtures.
173+
static INSTALLED: tokio::sync::OnceCell<()> = tokio::sync::OnceCell::const_new();
174+
INSTALLED
175+
.get_or_try_init(|| async {
176+
sqlx::raw_sql(
177+
"SELECT pg_advisory_xact_lock(hashtext('test_reject_source_sync'));
178+
CREATE OR REPLACE FUNCTION test_reject_source_sync() RETURNS trigger
179+
LANGUAGE plpgsql AS $$ BEGIN
180+
IF NEW.kind = 'sync_source' AND EXISTS(
181+
SELECT 1 FROM sources WHERE id::text = NEW.payload->>'source_id'
182+
AND name = 'reject-source-sync-test')
183+
THEN RAISE EXCEPTION 'test source sync insert failure'; END IF;
184+
RETURN NEW;
185+
END $$;
186+
DO $$ BEGIN
187+
IF NOT EXISTS(SELECT 1 FROM pg_trigger WHERE tgname = 'test_reject_source_sync'
188+
AND tgrelid = 'jobs'::regclass) THEN
189+
CREATE TRIGGER test_reject_source_sync BEFORE INSERT ON jobs
190+
FOR EACH ROW EXECUTE FUNCTION test_reject_source_sync();
191+
END IF;
192+
END $$;",
193+
)
194+
.execute(&self.pool)
195+
.await
196+
.map(drop)
197+
})
198+
.await?;
199+
sqlx::query("UPDATE sources SET name = $2 WHERE id = $1")
200+
.bind(self.source)
201+
.bind(if reject {
202+
"reject-source-sync-test"
203+
} else {
204+
"Drive"
205+
})
206+
.execute(&self.pool)
207+
.await?;
208+
Ok(())
209+
}
210+
}
211+
212+
#[tokio::test]
213+
async fn source_sync_enqueue_creation_failure_keeps_source_schedulable() -> anyhow::Result<()> {
214+
let Some(mut fx) = Fixture::new().await? else {
215+
return Ok(());
216+
};
217+
fx.reject_sync_jobs(false).await?;
218+
let config = json!({"url": "https://example.com/source-sync-test"});
219+
let (status, body) = fx
220+
.post_http(
221+
&format!("/api/v1/kbs/{}/sources", fx.kb),
222+
json!({"kind": "url", "name": "reject-source-sync-test", "config": config}),
223+
)
224+
.await?;
225+
assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR, "{body}");
226+
fx.source = sqlx::query_scalar(
227+
"SELECT id FROM sources WHERE kb_id = $1 AND kind = 'url'
228+
AND name = 'reject-source-sync-test'",
229+
)
230+
.bind(fx.kb)
231+
.fetch_one(&fx.pool)
232+
.await?;
233+
assert_eq!(fx.config().await?, config);
234+
assert_eq!(fx.sync_state().await?, ("never".into(), 0));
235+
fx.reject_sync_jobs(false).await?;
236+
let (status, body) = fx.sync_http().await?;
237+
assert_eq!(status, StatusCode::OK, "{body}");
238+
assert_eq!(body["queued"], true);
239+
assert_eq!(fx.sync_state().await?, ("queued".into(), 1));
240+
Ok(())
241+
}
242+
243+
#[tokio::test]
244+
async fn source_sync_enqueue_manual_failure_rolls_back_and_can_retry() -> anyhow::Result<()> {
245+
let Some(fx) = Fixture::new().await? else {
246+
return Ok(());
247+
};
248+
fx.reject_sync_jobs(true).await?;
249+
let (status, body) = fx.sync_http().await?;
250+
assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR, "{body}");
251+
assert_eq!(fx.sync_state().await?, ("never".into(), 0));
252+
253+
fx.reject_sync_jobs(false).await?;
254+
let (status, body) = fx.sync_http().await?;
255+
assert_eq!(status, StatusCode::OK, "{body}");
256+
assert_eq!(body["queued"], true);
257+
assert_eq!(fx.sync_state().await?, ("queued".into(), 1));
258+
let (payload, max_attempts): (Value, i32) = sqlx::query_as(
259+
"SELECT payload, max_attempts FROM jobs WHERE kind = 'sync_source'
260+
AND payload->>'source_id' = $1",
261+
)
262+
.bind(fx.source.to_string())
263+
.fetch_one(&fx.pool)
264+
.await?;
265+
assert_eq!(payload, json!({"source_id": fx.source}));
266+
assert_eq!(max_attempts, 3);
267+
268+
for pending in ["queued", "running"] {
269+
sqlx::query("UPDATE sources SET last_sync_status = $2 WHERE id = $1")
270+
.bind(fx.source)
271+
.bind(pending)
272+
.execute(&fx.pool)
273+
.await?;
274+
let (status, body) = fx.sync_http().await?;
275+
assert_eq!(status, StatusCode::OK, "{body}");
276+
assert_eq!(body["queued"], false);
277+
assert_eq!(fx.sync_state().await?, (pending.into(), 1));
278+
}
279+
Ok(())
280+
}
281+
282+
#[tokio::test]
283+
async fn source_sync_enqueue_concurrent_manual_requests_enqueue_once() -> anyhow::Result<()> {
284+
let Some(fx) = Fixture::new().await? else {
285+
return Ok(());
286+
};
287+
// AppState and the router do not start a worker, so the first task stays queued.
288+
let (first, second) = tokio::join!(fx.sync_http(), fx.sync_http());
289+
let mut queued = Vec::new();
290+
for result in [first, second] {
291+
let (status, body) = result?;
292+
assert_eq!(status, StatusCode::OK, "{body}");
293+
queued.push(body["queued"].as_bool().expect("queued is a boolean"));
294+
}
295+
queued.sort_unstable();
296+
assert_eq!(queued, [false, true]);
297+
assert_eq!(fx.sync_state().await?, ("queued".into(), 1));
298+
Ok(())
299+
}
300+
301+
#[tokio::test]
302+
async fn source_sync_enqueue_drive_selection_keeps_follow_up_when_pending() -> anyhow::Result<()> {
303+
for pending in ["queued", "running"] {
304+
let Some(fx) = Fixture::new().await? else {
305+
return Ok(());
306+
};
307+
let (status, body) = fx.sync_http().await?;
308+
assert_eq!(status, StatusCode::OK, "{body}");
309+
sqlx::query("UPDATE sources SET last_sync_status = $2 WHERE id = $1")
310+
.bind(fx.source)
311+
.bind(pending)
312+
.execute(&fx.pool)
313+
.await?;
314+
sqlx::query("UPDATE jobs SET status = $2 WHERE payload->>'source_id' = $1")
315+
.bind(fx.source.to_string())
316+
.bind(pending)
317+
.execute(&fx.pool)
318+
.await?;
319+
let _ = fx
320+
.choose_folder("next-folder")
321+
.await
322+
.map_err(|ApiErr(error)| error)?;
323+
assert_eq!(fx.sync_state().await?, (pending.into(), 2));
324+
let latest_status: String = sqlx::query_scalar(
325+
"SELECT status FROM jobs WHERE kind = 'sync_source'
326+
AND payload->>'source_id' = $1 ORDER BY id DESC LIMIT 1",
327+
)
328+
.bind(fx.source.to_string())
329+
.fetch_one(&fx.pool)
330+
.await?;
331+
assert_eq!(latest_status, "queued");
332+
assert_eq!(fx.config().await?["folders"][0]["id"], "next-folder");
333+
}
334+
Ok(())
335+
}
336+
337+
#[tokio::test]
338+
async fn source_sync_enqueue_drive_failure_keeps_config_but_rolls_back_queue() -> anyhow::Result<()>
339+
{
340+
for initial in ["never", "running"] {
341+
let Some(fx) = Fixture::new().await? else {
342+
return Ok(());
343+
};
344+
let existing_jobs = if initial == "running" {
345+
let (status, body) = fx.sync_http().await?;
346+
assert_eq!(status, StatusCode::OK, "{body}");
347+
sqlx::query("UPDATE sources SET last_sync_status = 'running' WHERE id = $1")
348+
.bind(fx.source)
349+
.execute(&fx.pool)
350+
.await?;
351+
sqlx::query("UPDATE jobs SET status = 'running' WHERE payload->>'source_id' = $1")
352+
.bind(fx.source.to_string())
353+
.execute(&fx.pool)
354+
.await?;
355+
1
356+
} else {
357+
0
358+
};
359+
fx.reject_sync_jobs(true).await?;
360+
assert!(matches!(
361+
fx.choose_folder("saved-folder").await,
362+
Err(ApiErr(AppError::Db(_)))
363+
));
364+
assert_eq!(fx.config().await?["folders"][0]["id"], "saved-folder");
365+
assert_eq!(fx.sync_state().await?, (initial.into(), existing_jobs));
366+
fx.reject_sync_jobs(false).await?;
367+
let _ = fx
368+
.choose_folder("saved-folder")
369+
.await
370+
.map_err(|ApiErr(error)| error)?;
371+
let expected_status = if initial == "running" {
372+
"running"
373+
} else {
374+
"queued"
375+
};
376+
assert_eq!(
377+
fx.sync_state().await?,
378+
(expected_status.into(), existing_jobs + 1)
379+
);
380+
}
381+
Ok(())
117382
}
118383

119384
fn denied_code<T>(result: ApiResult<T>) -> Option<&'static str> {

‎crates/utopia-server/src/api/sources_routes.rs‎

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -132,13 +132,7 @@ pub async fn create(
132132
.await?;
133133
// 拉取型来源建好立即同步一次(有配置即产出,无需等下一个调度周期)
134134
if matches!(source.kind.as_str(), "url" | "rss" | "custom") {
135-
let _ = utopia_store::sources::mark_queued(&state.pool, source.id).await;
136-
utopia_store::jobs::enqueue(
137-
&state.pool,
138-
"sync_source",
139-
json!({ "source_id": source.id }),
140-
)
141-
.await?;
135+
utopia_store::sources::enqueue_sync(&state.pool, source.id).await?;
142136
}
143137
// api 来源:生成专属推送密钥(此后可随时经 get_token 查看)
144138
let mut ingest_token: Option<String> = None;
@@ -396,14 +390,8 @@ pub async fn sync_now(
396390
) -> ApiResult<Json<serde_json::Value>> {
397391
require_kb(&state, &user, kb_id, Role::Editor).await?;
398392
source_in_kb(&state, kb_id, source_id).await?;
399-
let queued = utopia_store::sources::mark_queued(&state.pool, source_id).await?;
393+
let queued = utopia_store::sources::enqueue_sync(&state.pool, source_id).await?;
400394
if queued {
401-
utopia_store::jobs::enqueue(
402-
&state.pool,
403-
"sync_source",
404-
json!({ "source_id": source_id }),
405-
)
406-
.await?;
407395
state.emit_source(kb_id);
408396
}
409397
Ok(Json(json!({ "queued": queued })))

‎crates/utopia-server/src/main.rs‎

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -232,20 +232,10 @@ async fn main() -> anyhow::Result<()> {
232232
match utopia_store::sources::due_sources(&sched_state.pool).await {
233233
Ok(due) => {
234234
for s in due {
235-
match utopia_store::sources::mark_queued(&sched_state.pool, s.id).await {
236-
Ok(true) => {
237-
if let Err(e) = utopia_store::jobs::enqueue(
238-
&sched_state.pool,
239-
"sync_source",
240-
serde_json::json!({ "source_id": s.id }),
241-
)
242-
.await
243-
{
244-
tracing::warn!(source_id = %s.id, error = %e, "同步任务入队失败");
245-
}
246-
}
247-
Ok(false) => {}
248-
Err(e) => tracing::warn!(source_id = %s.id, error = %e, "标记入队失败"),
235+
if let Err(e) =
236+
utopia_store::sources::enqueue_sync(&sched_state.pool, s.id).await
237+
{
238+
tracing::warn!(source_id = %s.id, error = %e, "同步任务入队失败");
249239
}
250240
}
251241
}

0 commit comments

Comments
 (0)