|
1 | 1 | //! 连接流程的几道关卡与「谁连上的谁来选」(0074 决定 3、5),连真库跑。 |
2 | 2 | //! 测试环境没配 OAuth 客户端:过了所有关卡的回调停在「没配置」,不会去敲 Google |
3 | 3 | use super::*; |
| 4 | +use axum::body::{to_bytes, Body}; |
| 5 | +use axum::http::{Request, StatusCode}; |
4 | 6 | use std::sync::Arc; |
| 7 | +use tower::ServiceExt; |
5 | 8 | use utopia_core::models::User; |
6 | 9 |
|
7 | 10 | struct Fixture { |
@@ -114,6 +117,268 @@ impl Fixture { |
114 | 117 | .await? |
115 | 118 | .config) |
116 | 119 | } |
| 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(()) |
117 | 382 | } |
118 | 383 |
|
119 | 384 | fn denied_code<T>(result: ApiResult<T>) -> Option<&'static str> { |
|
0 commit comments