mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-06 03:32:25 +03:00
fix(server): harden predeploy recovery, CORS headers, and blob backfill (#16059)
Resolve failed `20261124060000_bound_snapshot_transaction_idle_time` migrations during self-hosted predeploy. Allow the `x-affine-refresh-attempt` header in CORS preflight responses. Skip missing workspaces during blob metadata reconciliation instead of failing the batch. Co-authored-by: DarkSky <darksky2048@gmail.com>
This commit is contained in:
1 parent
db4937b7ce
commit
b62c8ba093
5 files changed
+108
-23
No files matched your search
@@ -19,15 +19,21 @@ async fn workspace_exists(pool: &PgPool, workspace_id: &str) -> RuntimeResult<bo
|
||||
.map_err(|err| RuntimeError::database("Blob metadata backfill workspace check failed", err))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum ReconcileBlobOutcome {
|
||||
WorkspaceMissing,
|
||||
Reconciled(i64),
|
||||
}
|
||||
|
||||
async fn reconcile_blob_metadata<'e>(
|
||||
executor: impl PgExecutor<'e>,
|
||||
workspace_id: &str,
|
||||
key: &str,
|
||||
metadata: RuntimeObjectMetadata,
|
||||
) -> RuntimeResult<i64> {
|
||||
) -> RuntimeResult<ReconcileBlobOutcome> {
|
||||
let size = i32::try_from(metadata.content_length)
|
||||
.map_err(|_| RuntimeError::invalid_input("blob metadata content length exceeds i32::MAX"))?;
|
||||
let changed = sqlx::query_scalar::<_, i64>(
|
||||
match sqlx::query_scalar::<_, i64>(
|
||||
r#"
|
||||
WITH changed AS (
|
||||
INSERT INTO blobs (workspace_id,key,size,mime,status)
|
||||
@@ -47,9 +53,11 @@ async fn reconcile_blob_metadata<'e>(
|
||||
.bind(metadata.content_type)
|
||||
.fetch_one(executor)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Blob metadata reconciliation failed", err))?;
|
||||
|
||||
Ok(changed)
|
||||
{
|
||||
Ok(changed) => Ok(ReconcileBlobOutcome::Reconciled(changed)),
|
||||
Err(sqlx::Error::Database(err)) if err.is_foreign_key_violation() => Ok(ReconcileBlobOutcome::WorkspaceMissing),
|
||||
Err(err) => Err(RuntimeError::database("Blob metadata reconciliation failed", err)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn reconcile_blob_metadata_for_deployment(
|
||||
@@ -58,7 +66,7 @@ async fn reconcile_blob_metadata_for_deployment(
|
||||
workspace_id: &str,
|
||||
key: &str,
|
||||
metadata: RuntimeObjectMetadata,
|
||||
) -> RuntimeResult<i64> {
|
||||
) -> RuntimeResult<ReconcileBlobOutcome> {
|
||||
if deployment == Deployment::Cloud {
|
||||
return reconcile_blob_metadata(pool, workspace_id, key, metadata).await;
|
||||
}
|
||||
@@ -67,11 +75,17 @@ async fn reconcile_blob_metadata_for_deployment(
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("begin blob metadata reconciliation", error))?;
|
||||
let workspace: String = sqlx::query_scalar("SELECT id FROM workspaces WHERE id=$1 FOR UPDATE")
|
||||
let Some(workspace): Option<String> = sqlx::query_scalar("SELECT id FROM workspaces WHERE id=$1 FOR UPDATE")
|
||||
.bind(workspace_id)
|
||||
.fetch_one(&mut *tx)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("lock blob metadata workspace", error))?;
|
||||
.map_err(|error| RuntimeError::database("lock blob metadata workspace", error))?
|
||||
else {
|
||||
tx.rollback()
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("rollback blob metadata reconciliation", error))?;
|
||||
return Ok(ReconcileBlobOutcome::WorkspaceMissing);
|
||||
};
|
||||
let existing: Option<String> =
|
||||
sqlx::query_scalar("SELECT key FROM blobs WHERE workspace_id=$1 AND key=$2 FOR UPDATE")
|
||||
.bind(workspace_id)
|
||||
@@ -94,11 +108,20 @@ async fn reconcile_blob_metadata_for_deployment(
|
||||
}
|
||||
}
|
||||
|
||||
let changed = reconcile_blob_metadata(&mut *tx, workspace_id, key, metadata).await?;
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("commit blob metadata reconciliation", error))?;
|
||||
Ok(changed)
|
||||
let outcome = reconcile_blob_metadata(&mut *tx, workspace_id, key, metadata).await?;
|
||||
match outcome {
|
||||
ReconcileBlobOutcome::WorkspaceMissing => {
|
||||
tx.rollback()
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("rollback blob metadata reconciliation", error))?;
|
||||
}
|
||||
ReconcileBlobOutcome::Reconciled(_) => {
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("commit blob metadata reconciliation", error))?;
|
||||
}
|
||||
}
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
fn split_workspace_blob_key(full_key: &str) -> Option<(&str, &str)> {
|
||||
@@ -332,7 +355,7 @@ mod tests {
|
||||
reconcile_blob_metadata(&pool, &workspace_id, "asset", metadata)
|
||||
.await
|
||||
.unwrap(),
|
||||
1
|
||||
ReconcileBlobOutcome::Reconciled(1)
|
||||
);
|
||||
let inserted: (i32, String, String, bool) = sqlx::query_as(
|
||||
"SELECT size,mime,status::text,deleted_at IS NULL FROM blobs WHERE workspace_id=$1 AND key='asset'",
|
||||
@@ -357,7 +380,7 @@ mod tests {
|
||||
)
|
||||
.await
|
||||
.unwrap(),
|
||||
1
|
||||
ReconcileBlobOutcome::Reconciled(1)
|
||||
);
|
||||
let readable: bool = sqlx::query_scalar(
|
||||
"SELECT status='completed' AND deleted_at IS NULL FROM blobs WHERE workspace_id=$1 AND key='asset'",
|
||||
@@ -374,6 +397,46 @@ mod tests {
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn metadata_reconciliation_skips_missing_workspace() {
|
||||
let Ok(database_url) = std::env::var("DATABASE_URL") else {
|
||||
return;
|
||||
};
|
||||
let _guard = crate::runtime::migrations::DATABASE_TEST_LOCK.lock().await;
|
||||
let pool = PgPoolOptions::new()
|
||||
.max_connections(1)
|
||||
.connect(&database_url)
|
||||
.await
|
||||
.unwrap();
|
||||
crate::runtime::migrations::migrate_all_tables(&pool).await.unwrap();
|
||||
let missing_workspace_id = format!("blob-metadata-missing-{}", Uuid::new_v4());
|
||||
|
||||
for deployment in [Deployment::SelfHosted, Deployment::Cloud] {
|
||||
let outcome = reconcile_blob_metadata_for_deployment(
|
||||
&pool,
|
||||
deployment,
|
||||
&missing_workspace_id,
|
||||
"orphan",
|
||||
RuntimeObjectMetadata {
|
||||
content_type: "image/png".to_string(),
|
||||
content_length: 42,
|
||||
last_modified_ms: 1,
|
||||
checksum_crc32: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(outcome, ReconcileBlobOutcome::WorkspaceMissing);
|
||||
}
|
||||
|
||||
let inserted: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM blobs WHERE workspace_id=$1)")
|
||||
.bind(&missing_workspace_id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!inserted);
|
||||
}
|
||||
}
|
||||
|
||||
fn push_workspace_once(workspace_ids: &mut Vec<String>, workspace_id: &str) {
|
||||
@@ -460,7 +523,11 @@ impl StorageRuntime {
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(affected) => affected,
|
||||
Ok(ReconcileBlobOutcome::WorkspaceMissing) => {
|
||||
result.skipped_workspace_missing += 1;
|
||||
continue;
|
||||
}
|
||||
Ok(ReconcileBlobOutcome::Reconciled(affected)) => affected,
|
||||
Err(RuntimeError::InvalidInput(_)) => {
|
||||
result.failed += 1;
|
||||
continue;
|
||||
|
||||
@@ -56,6 +56,7 @@ function fixFailedMigrations(exec) {
|
||||
console.log('fixing failed migrations.');
|
||||
const maybeFailedMigrations = [
|
||||
'20250521083048_fix_workspace_embedding_chunk_primary_key',
|
||||
'20261124060000_bound_snapshot_transaction_idle_time',
|
||||
];
|
||||
for (const migration of maybeFailedMigrations) {
|
||||
try {
|
||||
|
||||
@@ -30,6 +30,7 @@ export const CORS_ALLOWED_HEADERS = [
|
||||
'content-type',
|
||||
'x-affine-version',
|
||||
'x-affine-client-kind',
|
||||
'x-affine-refresh-attempt',
|
||||
'x-operation-name',
|
||||
'x-request-id',
|
||||
'x-captcha-token',
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import ava, { TestFn } from 'ava';
|
||||
import Sinon from 'sinon';
|
||||
|
||||
import { buildCorsAllowedOrigins, isCorsOriginAllowed } from '../../cors';
|
||||
import {
|
||||
buildCorsAllowedOrigins,
|
||||
CORS_ALLOWED_HEADERS,
|
||||
isCorsOriginAllowed,
|
||||
} from '../../cors';
|
||||
import { ActionForbidden } from '../../error';
|
||||
import { URLHelper } from '../url';
|
||||
|
||||
@@ -220,3 +224,7 @@ test('should allow desktop file origin', t => {
|
||||
|
||||
t.true(isCorsOriginAllowed('file://', allowedOrigins));
|
||||
});
|
||||
|
||||
test('should allow x-affine-refresh-attempt in CORS allowed headers', t => {
|
||||
t.true(CORS_ALLOWED_HEADERS.includes('x-affine-refresh-attempt'));
|
||||
});
|
||||
@@ -14,7 +14,7 @@ type RunSelfHostPredeploy = (options?: {
|
||||
exec?: (command: string, options?: unknown) => string;
|
||||
}) => void;
|
||||
|
||||
test('self-host-predeploy runs all package.json predeploy steps in order', async t => {
|
||||
test('self-host-predeploy resolves failed migrations and runs package.json predeploy steps in order', async t => {
|
||||
const pkg = JSON.parse(
|
||||
fs.readFileSync(path.join(serverRoot, 'package.json'), 'utf-8')
|
||||
) as { scripts: { predeploy: string } };
|
||||
@@ -42,10 +42,18 @@ test('self-host-predeploy runs all package.json predeploy steps in order', async
|
||||
},
|
||||
});
|
||||
|
||||
const expectedResolveSteps = [
|
||||
'yarn prisma migrate resolve --rolled-back 20250521083048_fix_workspace_embedding_chunk_primary_key',
|
||||
'yarn prisma migrate resolve --rolled-back 20261124060000_bound_snapshot_transaction_idle_time',
|
||||
];
|
||||
|
||||
t.true(prepared);
|
||||
t.is(
|
||||
executed[0],
|
||||
'yarn prisma migrate resolve --rolled-back 20250521083048_fix_workspace_embedding_chunk_primary_key'
|
||||
t.deepEqual(
|
||||
executed.slice(0, expectedResolveSteps.length),
|
||||
expectedResolveSteps
|
||||
);
|
||||
t.deepEqual(
|
||||
executed.slice(expectedResolveSteps.length),
|
||||
expectedPredeploySteps
|
||||
);
|
||||
t.deepEqual(executed.slice(1), expectedPredeploySteps);
|
||||
});
|
||||
Reference in new issue
Block a user