fix: test & lint

This commit is contained in:
DarkSky committed 2026-11-16 16:09:11 +08:00
1 parent 4c5c80f69f
commit 72011d7e82
31 files changed
+1058 -314

No files matched your search

Generated
+2 -2
View File
@@ -76,9 +76,9 @@ dependencies = [
[[package]]
name = "affine_core"
version = "0.0.13"
version = "0.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9248b8911bb9045881f88d20f83c39a46e90ebbe98ce8b3ca05ffa06ceb9c2f0"
checksum = "4d1e63389dbf25dd1ae36b4846996a7eeb604f8ffea497a571ef117557349083"
dependencies = [
"base64 0.23.1",
"chrono",
+1 -1
View File
@@ -11,7 +11,7 @@ crate-type = ["cdylib"]
[dependencies]
aes-gcm = { workspace = true }
affine_common = { workspace = true, features = ["hashcash", "napi"] }
affine_core = "0.0.13"
affine_core = "0.0.14"
affine_doc_loader = { workspace = true }
anyhow = { workspace = true }
argon2 = "0.6"
@@ -292,6 +292,7 @@ async fn publish_update(
invalidation
.publish(InvalidationHintV1::WorkspaceInventoryChanged {
workspace_id: workspace_id.clone(),
doc_id: Some(doc_id.clone()),
})
.await;
}
@@ -24,6 +24,7 @@ impl DomainCommandInputV1 {
} => vec![
InvalidationHintV1::WorkspaceInventoryChanged {
workspace_id: workspace_id.clone(),
doc_id: Some(doc_id.clone()),
},
InvalidationHintV1::BlobSource {
source: SourceIdentity::CurrentDoc {
@@ -44,15 +45,30 @@ impl DomainCommandInputV1 {
},
InvalidationHintV1::WorkspaceInventoryChanged {
workspace_id: workspace_id.clone(),
doc_id: None,
},
],
Self::PublishDoc { workspace_id, .. }
| Self::UnpublishDoc { workspace_id, .. }
| Self::TransitionWorkspaceRole { workspace_id, .. }
| Self::TransitionDocRole { workspace_id, .. }
| Self::GrantDocRoles { workspace_id, .. }
| Self::SetDocDefaultRole { workspace_id, .. } => vec![InvalidationHintV1::WorkspaceInventoryChanged {
Self::PublishDoc {
workspace_id, doc_id, ..
}
| Self::UnpublishDoc {
workspace_id, doc_id, ..
}
| Self::TransitionDocRole {
workspace_id, doc_id, ..
}
| Self::GrantDocRoles {
workspace_id, doc_id, ..
}
| Self::SetDocDefaultRole {
workspace_id, doc_id, ..
} => vec![InvalidationHintV1::WorkspaceInventoryChanged {
workspace_id: workspace_id.clone(),
doc_id: Some(doc_id.clone()),
}],
Self::TransitionWorkspaceRole { workspace_id, .. } => vec![InvalidationHintV1::WorkspaceInventoryChanged {
workspace_id: workspace_id.clone(),
doc_id: None,
}],
_ => Vec::new(),
}
@@ -404,6 +420,7 @@ mod tests {
serde_json::json!({"command":"transition_workspace_role","actorUserId":"actor","workspaceId":"workspace","targetUserId":"target","newRole":"owner"}),
vec![InvalidationHintV1::WorkspaceInventoryChanged {
workspace_id: "workspace".into(),
doc_id: None,
}],
),
(
@@ -414,6 +431,7 @@ mod tests {
},
InvalidationHintV1::WorkspaceInventoryChanged {
workspace_id: "workspace".into(),
doc_id: None,
},
],
),
@@ -425,6 +443,7 @@ mod tests {
},
InvalidationHintV1::WorkspaceInventoryChanged {
workspace_id: "workspace".into(),
doc_id: None,
},
],
),
@@ -433,6 +452,7 @@ mod tests {
vec![
InvalidationHintV1::WorkspaceInventoryChanged {
workspace_id: "workspace".into(),
doc_id: Some("doc".into()),
},
InvalidationHintV1::BlobSource {
source: SourceIdentity::CurrentDoc {
@@ -456,6 +476,22 @@ mod tests {
Vec::new(),
),
];
for command in [
serde_json::json!({"command":"publish_doc","actorUserId":"actor","workspaceId":"workspace","docId":"doc","mode":0}),
serde_json::json!({"command":"unpublish_doc","actorUserId":"actor","workspaceId":"workspace","docId":"doc"}),
serde_json::json!({"command":"transition_doc_role","actorUserId":"actor","workspaceId":"workspace","docId":"doc","targetUserId":"target","newRole":"reader"}),
serde_json::json!({"command":"grant_doc_roles","actorUserId":"actor","workspaceId":"workspace","docId":"doc","targetUserIds":["target"],"newRole":"reader"}),
serde_json::json!({"command":"set_doc_default_role","actorUserId":"actor","workspaceId":"workspace","docId":"doc","newRole":"reader"}),
] {
let input = serde_json::from_value::<DomainCommandInputV1>(command).unwrap();
assert_eq!(
input.invalidations(),
vec![InvalidationHintV1::WorkspaceInventoryChanged {
workspace_id: "workspace".into(),
doc_id: Some("doc".into()),
}]
);
}
for (input, expected) in cases {
let input = serde_json::from_value::<DomainCommandInputV1>(input).unwrap();
assert_eq!(input.invalidations(), expected);
@@ -563,7 +599,8 @@ mod tests {
assert_eq!(
outcome.invalidations,
vec![InvalidationHintV1::WorkspaceInventoryChanged {
workspace_id: workspace_id.clone()
workspace_id: workspace_id.clone(),
doc_id: Some(doc_id.clone()),
}]
);
assert!(
@@ -636,6 +636,22 @@ mod tests {
super::super::source::sync_documents(&pool, &workspace_id, &repaired, i32::MAX)
.await
.unwrap();
let stale_failure = [crate::runtime::types::DocumentEmbeddingProjectionInput {
skip_reason: Some("invalid_document".into()),
..skipped[0].clone()
}];
super::super::source::sync_documents(&pool, &workspace_id, &stale_failure, i32::MAX)
.await
.unwrap();
let current: (String, Option<String>) = sqlx::query_as(
"SELECT source.content_revision,projection.last_error_code FROM embedding_sources source JOIN \
embedding_projections projection ON projection.source_id=source.id WHERE source.id=$1",
)
.bind(source_id)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(current, ("4000".into(), Some("document_contains_nul".into())));
let repaired_claim = claim_projection(&pool, "repaired-worker").await.unwrap().unwrap();
assert_eq!(repaired_claim.content_revision, "4000");
assert_eq!(repaired_claim.source_id, source_id);
@@ -182,6 +182,10 @@ impl SearchRuntime {
r#"SELECT workspace_id FROM search_projection.workspace_states
WHERE generation_id=$1
AND last_error IS DISTINCT FROM 'search_workspace_reconcile_failed'
AND (NOT EXISTS(SELECT 1 FROM workspaces workspace WHERE workspace.id=workspace_states.workspace_id)
OR EXISTS(SELECT 1 FROM storage_reconciliation_checkpoints checkpoint
WHERE checkpoint.kind='workspace_doc_lifecycle' AND checkpoint.scope=workspace_states.workspace_id
AND checkpoint.status='completed'))
AND (
available_at <= now()
OR EXISTS (SELECT 1 FROM search_projection.document_states document
@@ -38,5 +38,5 @@ use workspace_state::{
use super::{
ActiveGeneration, DOCUMENT_PROJECTION_FAILED, ProjectionInput, SearchChange, SearchProvider, SearchTable,
WORKSPACE_RECONCILE_FAILED, is_ordinary_workspace_doc, load_workspace_doc_states_in, project_document,
projection_external_id, provider_payload, workspace_lifecycle_completed,
projection_external_id, provider_payload,
};
@@ -5,7 +5,6 @@ use super::{
WorkspacePhase, WorkspaceReconcileContext, WorkspaceStep, checkpoint_workspace, checkpoint_workspace_after,
claim_workspace, complete_workspace, delete_workspace_state, mark_workspace_failed, reconcile_documents,
reconcile_stale_provider_rows, renew_workspace_lease, sweep_deleted_workspace, upsert_document,
workspace_lifecycle_completed,
};
use crate::{
runtime::{RuntimeError, RuntimeResult},
@@ -29,19 +28,6 @@ pub(in crate::runtime::backend_runtime::search) async fn reconcile_workspace(
generation: &ActiveGeneration,
workspace_id: &str,
) -> RuntimeResult<bool> {
let mut connection = pool
.acquire()
.await
.map_err(|error| RuntimeError::database("load search migration boundary", error))?;
let workspace_exists: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM workspaces WHERE id=$1)")
.bind(workspace_id)
.fetch_one(&mut *connection)
.await
.map_err(|error| RuntimeError::database("load search workspace existence", error))?;
if workspace_exists && !workspace_lifecycle_completed(&mut connection, workspace_id).await? {
return Ok(false);
}
drop(connection);
sqlx::query(
r#"INSERT INTO search_projection.workspace_states(generation_id,workspace_id)
VALUES ($1,$2) ON CONFLICT DO NOTHING"#,
@@ -824,24 +810,6 @@ mod tests {
manifest: json!({}),
};
sqlx::query("DELETE FROM storage_reconciliation_checkpoints WHERE kind='workspace_doc_lifecycle' AND scope=$1")
.bind(&workspace_id)
.execute(&pool)
.await
.unwrap();
assert!(
!reconcile_workspace(&pool, &embedded, None, &generation, &workspace_id)
.await
.unwrap()
);
sqlx::query(
"INSERT INTO storage_reconciliation_checkpoints(kind,scope,status) \
VALUES('workspace_doc_lifecycle',$1,'completed')",
)
.bind(&workspace_id)
.execute(&pool)
.await
.unwrap();
let old_claim = claim_workspace(&pool, generation_id, &workspace_id)
.await
.unwrap()
@@ -591,6 +591,58 @@ mod tests {
);
assert_eq!(runtime.status().await.unwrap()["metrics"]["pendingPublications"], 0);
let pending_workspace = format!("!a-unmigrated-{generation_id}");
let ready_workspace = format!("!b-migrated-{generation_id}");
for id in [&pending_workspace, &ready_workspace] {
sqlx::query("INSERT INTO workspaces(id) VALUES($1)")
.bind(id)
.execute(&pool)
.await
.unwrap();
sqlx::query("INSERT INTO search_projection.workspace_states(generation_id,workspace_id) VALUES($1,$2)")
.bind(generation_id)
.bind(id)
.execute(&pool)
.await
.unwrap();
}
sqlx::query(
"INSERT INTO storage_reconciliation_checkpoints(kind,scope,status) \
VALUES('workspace_doc_lifecycle',$1,'completed')",
)
.bind(&ready_workspace)
.execute(&pool)
.await
.unwrap();
for _ in 0..4 {
assert_eq!(runtime.reconcile_pending(1).await.unwrap(), 1);
}
let coverage: Vec<(String, bool)> = sqlx::query_as(
"SELECT workspace_id,covered FROM search_projection.workspace_states WHERE generation_id=$1 AND \
workspace_id=ANY($2) ORDER BY workspace_id",
)
.bind(generation_id)
.bind([pending_workspace.clone(), ready_workspace.clone()])
.fetch_all(&pool)
.await
.unwrap();
assert_eq!(
coverage,
vec![(pending_workspace.clone(), false), (ready_workspace.clone(), true)]
);
for id in [&pending_workspace, &ready_workspace] {
sqlx::query("DELETE FROM storage_reconciliation_checkpoints WHERE scope=$1")
.bind(id)
.execute(&pool)
.await
.unwrap();
sqlx::query("DELETE FROM workspaces WHERE id=$1")
.bind(id)
.execute(&pool)
.await
.unwrap();
}
sqlx::query("DELETE FROM search_projection.generations WHERE id=$1")
.bind(generation_id)
.execute(&pool)
@@ -265,6 +265,7 @@ impl BackendRuntime {
self
.publish_invalidation(InvalidationHintV1::WorkspaceInventoryChanged {
workspace_id: input.workspace_id,
doc_id: None,
})
.await;
Ok(true)
@@ -4,7 +4,6 @@ use chrono::{DateTime, Duration, Utc};
use sqlx::{FromRow, PgConnection};
use uuid::Uuid;
const DELETE_BATCH_SIZE: usize = 16;
const DELETE_BATCH_BUDGET: StdDuration = StdDuration::from_millis(200);
use super::{
@@ -284,8 +283,7 @@ impl StorageRuntime {
operation.release().await?;
return Ok(result);
}
let end = (offset + DELETE_BATCH_SIZE).min(rows.len());
while offset < end {
while offset < rows.len() {
let row = &rows[offset];
// Candidate enumeration precedes this lock. An upload or another pass
// may have replaced the ledger row while the workspace was unlocked.
@@ -17,6 +17,7 @@ import type { TestFn } from 'ava';
import ava from 'ava';
import { ServerFeature, ServerService } from '../../core';
import { BackendRuntimeProvider } from '../../core/backend-runtime';
import { Models } from '../../models';
import { processImage } from '../../native';
import { McpCredentialService } from '../../plugins/copilot/mcp/credential';
@@ -51,6 +52,9 @@ test.before(async t => {
test.beforeEach(async t => {
await t.context.app.initTestingDB();
await t.context.app
.get(BackendRuntimeProvider)
.activateWorkspaceLifecycleV1();
});
test.after.always(async t => {
@@ -150,10 +150,19 @@ function emitWithAck<T>(socket: SocketIOClient, event: string, data: unknown) {
);
}
function waitForEvent<T>(socket: SocketIOClient, event: string) {
function waitForEvent<T>(
socket: SocketIOClient,
event: string,
accept: (payload: T) => boolean = () => true
) {
return withTimeout(
new Promise<T>(resolve => {
socket.once(event, (payload: T) => resolve(payload));
const listener = (payload: T) => {
if (!accept(payload)) return;
socket.off(event, listener);
resolve(payload);
};
socket.on(event, listener);
}),
WS_TIMEOUT_MS,
`event ${event}`
@@ -1395,6 +1404,44 @@ test('permission revocation removes an active document subscription', async t =>
const permissionService = app.get(PermissionService);
const batchPermissions =
permissionService.batchDocPermissions.bind(permissionService);
const inventoryPermissions = Sinon.spy(
permissionService,
'batchDocPermissions'
);
try {
for (let i = 0; i < 100; i++) {
await app.get(EventBus).emitAsync('backendRuntime.invalidation', {
version: 1,
kind: 'workspaceInventoryChanged',
workspaceId: workspace.id,
docId: `new-document-${i}`,
});
}
t.is(inventoryPermissions.callCount, 0);
} finally {
inventoryPermissions.restore();
}
const unrelatedDocId = 'unrelated-doc';
await createSnapshot(db, {
workspaceId: workspace.id,
docId: unrelatedDocId,
userId: owner.id,
blob: Buffer.from(encodeStateAsUpdate(new Doc())),
state: Buffer.from(encodeStateVector(new Doc())),
});
unwrapResponse(
t,
await emitWithAck(otherOwnerSocket, 'space:join-batch', {
...join,
spaces: [
{
spaceType: 'workspace',
spaceId: workspace.id,
docId: unrelatedDocId,
},
],
})
);
const changed = { workspaceId: workspace.id, docId };
for (const burstSize of [1, 20]) {
await models.docUser.set(
@@ -1438,8 +1485,25 @@ test('permission revocation removes an active document subscription', async t =>
});
const oldRevalidation = app
.get(EventBus)
.emitAsync('doc.grants.changed', changed);
.emitAsync('backendRuntime.invalidation', {
version: 1,
kind: 'workspaceInventoryChanged',
...changed,
});
await captured[0].promise;
const unrelatedUpdate = waitForEvent<{ docId: string }>(
otherOwnerSocket,
'space:broadcast-doc-updates',
message => message.docId === unrelatedDocId
);
await app.get(EventBus).emitAsync('doc.updates.pushed', {
spaceType: 'workspace',
spaceId: workspace.id,
docId: unrelatedDocId,
updates: [Buffer.from(createYjsUpdateBase64(), 'base64')],
timestamp: Date.now(),
});
t.is((await unrelatedUpdate).docId, unrelatedDocId);
await db.docGrant.deleteMany({
where: {
workspaceId: workspace.id,
@@ -1450,18 +1514,32 @@ test('permission revocation removes an active document subscription', async t =>
});
const newRevalidation = Promise.all(
Array.from({ length: burstSize }, () =>
app.get(EventBus).emitAsync('doc.grants.changed', changed)
app.get(EventBus).emitAsync('backendRuntime.invalidation', {
version: 1,
kind: 'workspaceInventoryChanged',
...changed,
})
)
);
const noEarlyUpdate = expectNoEvent(
ownerSocket,
'space:broadcast-doc-updates'
);
const invalidation = waitForEvent<{ inventoryChanged?: boolean }>(
ownerSocket,
'space:broadcast-doc-invalidation',
message => !message.inventoryChanged
);
const update = Buffer.from(createYjsUpdateBase64(), 'base64');
await db.snapshot.update({
where: { workspaceId_id: { workspaceId: workspace.id, id: docId } },
data: { blob: update, updatedAt: new Date() },
});
await app.get(EventBus).emitAsync('doc.updates.pushed', {
spaceType: 'workspace',
spaceId: workspace.id,
docId,
updates: [Buffer.from(createYjsUpdateBase64(), 'base64')],
updates: [update],
timestamp: Date.now(),
});
try {
@@ -1469,23 +1547,35 @@ test('permission revocation removes an active document subscription', async t =>
t.is(reads, 1);
resume[0].resolve();
await captured[1].promise;
const deliveredUpdate = waitForEvent(
ownerSocket,
'space:broadcast-doc-updates'
t.not((await invalidation).inventoryChanged, true);
unwrapResponse(
t,
await emitWithAck(ownerSocket, 'space:join-batch', join)
);
const repaired = unwrapResponse(
t,
await emitWithAck<{ missing: string }>(
ownerSocket,
'space:load-doc',
{
spaceType: 'workspace',
spaceId: workspace.id,
docId,
}
)
);
const repairedDoc = new Doc();
applyUpdate(repairedDoc, Buffer.from(repaired.missing, 'base64'));
t.is(repairedDoc.getMap('m').get('k'), 'v');
repairedDoc.destroy();
const noRevokedUpdate = expectNoEvent(
collaboratorSocket,
'space:broadcast-doc-updates'
);
resume[1].resolve();
await Promise.all([
oldRevalidation,
newRevalidation,
deliveredUpdate,
noRevokedUpdate,
]);
await Promise.all([oldRevalidation, newRevalidation, noRevokedUpdate]);
t.is(reads, 2);
t.is(ownerReads, 2);
t.is(ownerReads, 3);
} finally {
for (const pending of resume) pending.resolve();
await Promise.all([oldRevalidation, newRevalidation]);
@@ -1510,7 +1600,9 @@ test('permission revocation removes an active document subscription', async t =>
})
);
t.snapshot(stableError(staleGenerationLoad, workspace.id));
await app.get(EventBus).emitAsync('doc.grants.changed', {
await app.get(EventBus).emitAsync('backendRuntime.invalidation', {
version: 1,
kind: 'workspaceInventoryChanged',
workspaceId: workspace.id,
docId,
});
@@ -1560,6 +1652,86 @@ test('permission revocation removes an active document subscription', async t =>
})
);
await noRevokedUpdate;
const otherDocId = 'generation-race-unrelated-doc';
await createSnapshot(db, {
workspaceId: workspace.id,
docId: otherDocId,
userId: owner.id,
});
const otherDocJoin = {
...join,
spaces: [
...join.spaces,
{ spaceType: 'workspace', spaceId: workspace.id, docId: otherDocId },
],
};
for (const socket of [ownerSocket, otherOwnerSocket]) {
unwrapResponse(
t,
await emitWithAck(socket, 'space:join-batch', otherDocJoin)
);
}
const captured = Promise.withResolvers<void>();
const resume = Promise.withResolvers<void>();
const checkedDocs: string[][] = [];
const permissionStub = Sinon.stub(
permissionService,
'batchDocPermissions'
).callsFake(async input => {
const result = await batchPermissions(input);
if (input.userId === owner.id) {
checkedDocs.push(input.docs.map(doc => doc.docId).sort());
if (checkedDocs.length === 1) {
captured.resolve();
await resume.promise;
}
}
return result;
});
const workspaceCheck = app
.get(EventBus)
.emitAsync('workspace.updated', updatedWorkspace);
await captured.promise;
await db.$executeRaw`
UPDATE workspace_sync_permission_generations
SET generation = generation + 1
WHERE workspace_id = ${workspace.id}
`;
const docCheck = app
.get(EventBus)
.emitAsync('backendRuntime.invalidation', {
version: 1,
kind: 'workspaceInventoryChanged',
...changed,
});
try {
resume.resolve();
await Promise.all([workspaceCheck, docCheck]);
} finally {
resume.resolve();
await Promise.all([workspaceCheck, docCheck]);
permissionStub.restore();
}
t.deepEqual(checkedDocs, [
[docId, otherDocId, unrelatedDocId].sort(),
[docId, otherDocId, unrelatedDocId].sort(),
]);
const receivedAfterRace = waitForEvent<{ docId: string }>(
ownerSocket,
'space:broadcast-doc-updates'
);
unwrapResponse(
t,
await emitWithAck(otherOwnerSocket, 'space:push-doc-update', {
spaceType: 'workspace',
spaceId: workspace.id,
docId: otherDocId,
intent: 'update',
update: createYjsUpdateBase64(),
})
);
t.is((await receivedAfterRace).docId, otherDocId);
} finally {
ownerSocket.disconnect();
otherOwnerSocket.disconnect();
@@ -1,7 +1,9 @@
import { randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { ScheduleModule } from '@nestjs/schedule';
import { PrismaClient } from '@prisma/client';
import ava, { TestFn } from 'ava';
import Sinon from 'sinon';
import {
@@ -24,8 +26,18 @@ import {
CopilotSelectedSourcesLimitExceeded,
CopilotSelectedSourcesProcessing,
CopilotSelectedSourcesUnavailable,
DocUpdateInvalid,
EventBus,
} from '../../../base';
import { Models } from '../../../models';
import { ServerConfigHandle } from '../../../native';
import {
DatabaseDocReader,
DocStorageModule,
DocStorageOptions,
} from '../../doc';
import { DocJobRunner } from '../../doc-jobs/job';
import { StorageRuntimeProvider } from '../../storage-runtime';
import {
BackendRuntimeModule,
BackendRuntimeProvider,
@@ -87,6 +99,7 @@ test.before(async t => {
ScheduleModule.forRoot(),
BackendRuntimeModule,
BackendRuntimeWorkerModule,
DocStorageModule,
],
tapModule: builder => {
builder
@@ -143,7 +156,7 @@ test.after.always(async t => {
});
test('backend-runtime jobs ingest documents and clean runtime state', async t => {
await t.context.embeddingService.syncDocument('workspace-1', 'doc-1');
await t.context.embeddingService.syncDocument('workspace-1', 'doc-1', '1');
t.is(t.context.getCurrentWorkspaceDocV1.callCount, 1);
t.is(t.context.runtime.syncEmbeddingState.callCount, 1);
t.like(t.context.runtime.syncEmbeddingState.firstCall.args[0], {
@@ -260,7 +273,7 @@ test('backend-runtime jobs ingest documents and clean runtime state', async t =>
...healthyRoot,
bin: Buffer.from(encodeStateAsUpdate(partialRoot, priorState)),
});
await t.context.embeddingService.syncDocument('workspace-1', 'doc-1');
await t.context.embeddingService.syncDocument('workspace-1', 'doc-1', '1');
t.true(
t.context.runtime.syncEmbeddingState.lastCall.args[0].documents[0].units
.length > 0
@@ -283,14 +296,13 @@ test('backend-runtime jobs ingest documents and clean runtime state', async t =>
text.insert(0, '\0');
for (const [blob, reason] of [
[Buffer.from([0, 0]), 'empty_document'],
[Buffer.from([255]), 'invalid_document'],
[Buffer.from(encodeStateAsUpdate(viewOnly)), 'document_blocks_missing'],
[Buffer.from(encodeStateAsUpdate(nulDoc)), 'document_contains_nul'],
] as const) {
t.context.getCurrentWorkspaceDocV1
.withArgs('workspace-1', 'doc-1')
.resolves({ ...healthySnapshot, bin: blob });
await t.context.embeddingService.syncDocument('workspace-1', 'doc-1');
await t.context.embeddingService.syncDocument('workspace-1', 'doc-1', '1');
t.like(t.context.runtime.syncEmbeddingState.lastCall.args[0].documents[0], {
docId: 'doc-1',
revision: healthySnapshot.timestamp.toString(),
@@ -298,12 +310,45 @@ test('backend-runtime jobs ingest documents and clean runtime state', async t =>
units: [],
});
}
t.context.getCurrentWorkspaceDocV1
.withArgs('workspace-1', 'doc-1')
.rejects(new DocUpdateInvalid());
await t.context.embeddingService.syncDocument(
'workspace-1',
'doc-1',
'old-candidate'
);
t.like(t.context.runtime.syncEmbeddingState.lastCall.args[0].documents[0], {
revision: 'old-candidate',
skipReason: 'invalid_document',
units: [],
});
await t.throwsAsync(
() =>
t.context.embeddingService.prepareSelectedDocuments('workspace-1', [
'doc-1',
]),
{ instanceOf: CopilotSelectedSourcesFailed }
);
const databaseFailure = new Error('database unavailable');
t.context.getCurrentWorkspaceDocV1
.withArgs('workspace-1', 'doc-1')
.rejects(databaseFailure);
await t.throwsAsync(
() =>
t.context.embeddingService.syncDocument(
'workspace-1',
'doc-1',
'old-candidate'
),
{ is: databaseFailure }
);
viewOnly.destroy();
nulDoc.destroy();
t.context.getCurrentWorkspaceDocV1
.withArgs('workspace-1', 'doc-1')
.resolves(healthySnapshot);
await t.context.embeddingService.syncDocument('workspace-1', 'doc-1');
await t.context.embeddingService.syncDocument('workspace-1', 'doc-1', '1');
t.true(
t.context.runtime.syncEmbeddingState.lastCall.args[0].documents[0].units
.length > 0
@@ -318,7 +363,11 @@ test('backend-runtime jobs ingest documents and clean runtime state', async t =>
);
const callsBeforeMissingBackgroundDoc =
t.context.runtime.syncEmbeddingState.callCount;
await t.context.embeddingService.syncDocument('workspace-1', 'missing-doc');
await t.context.embeddingService.syncDocument(
'workspace-1',
'missing-doc',
'1'
);
t.is(
t.context.runtime.syncEmbeddingState.callCount,
callsBeforeMissingBackgroundDoc
@@ -342,4 +391,113 @@ test('backend-runtime jobs ingest documents and clean runtime state', async t =>
t.context.runtime.searchEnabled.returns(true);
t.is(await t.context.searchJob.reconcileProjection(7), 2);
t.true(t.context.runtime.reconcileSearchProjection.calledOnceWithExactly(7));
const module = t.context.module;
const db = module.get(PrismaClient);
const nativeProvider = new BackendRuntimeProvider(
module.get(ServerConfigHandle)
);
const workspaceId = `embedding-poison-${randomUUID()}`;
await nativeProvider.start();
try {
await nativeProvider.runMigrations();
await nativeProvider.activateWorkspaceLifecycleV1();
await db.$executeRaw`INSERT INTO workspaces(id,enable_doc_embedding) VALUES(${workspaceId},true)`;
await db.$executeRaw`INSERT INTO storage_reconciliation_checkpoints(kind,scope,status)
VALUES('workspace_doc_lifecycle',${workspaceId},'completed')`;
await db.$executeRaw`INSERT INTO snapshots(workspace_id,guid,blob,updated_at)
SELECT ${workspaceId},'bad-'||lpad(i::text,3,'0'),decode('ff','hex'),to_timestamp(1)
FROM generate_series(1,100) i`;
await db.$executeRaw`INSERT INTO snapshots(workspace_id,guid,blob,updated_at)
VALUES(${workspaceId},'healthy',${healthySnapshot.bin},to_timestamp(2))`;
const service = new BackendRuntimeEmbeddingService(
nativeProvider,
module.get(Models)
);
const runner = new DocJobRunner(
module.get(DatabaseDocReader),
db,
module.get(Models),
nativeProvider,
service,
module.get(StorageRuntimeProvider),
module.get(DocStorageOptions),
module.get(EventBus)
);
await t.throwsAsync(
() => nativeProvider.getCurrentWorkspaceDocV1(workspaceId, 'bad-001'),
{
instanceOf: DocUpdateInvalid,
}
);
await t.throwsAsync(
() => service.prepareSelectedDocuments(workspaceId, ['bad-001']),
{
instanceOf: CopilotSelectedSourcesFailed,
}
);
const getCurrent =
nativeProvider.getCurrentWorkspaceDocV1.bind(nativeProvider);
const read = Sinon.stub(
nativeProvider,
'getCurrentWorkspaceDocV1'
).callsFake(async (workspace, docId) => {
try {
return await getCurrent(workspace, docId);
} catch (error) {
if (docId === 'bad-001') {
await db.$executeRaw`UPDATE snapshots SET blob=${healthySnapshot.bin},updated_at=to_timestamp(2)
WHERE workspace_id=${workspaceId} AND guid='bad-001'`;
}
throw error;
}
});
try {
t.deepEqual(await runner.syncEmbeddingDocuments(), {
scannedDocuments: 100,
syncedDocuments: 100,
});
} finally {
read.restore();
}
const raced = await db.$queryRaw<
{ count: bigint }[]
>`SELECT count(*) FROM embedding_sources
WHERE workspace_id=${workspaceId} AND source_key='bad-001'`;
t.is(raced[0].count, 0n);
t.deepEqual(await runner.syncEmbeddingDocuments(), {
scannedDocuments: 2,
syncedDocuments: 2,
});
t.deepEqual(await runner.syncEmbeddingDocuments(), {
scannedDocuments: 0,
syncedDocuments: 0,
});
const sources = await db.$queryRaw<
{ source_key: string; content_revision: string; reason: string | null }[]
>`
SELECT source_key,content_revision,document_projection->>'skipReason' AS reason FROM embedding_sources
WHERE workspace_id=${workspaceId} ORDER BY source_key`;
t.is(sources.length, 101);
t.is(
sources.filter(source => source.reason === 'invalid_document').length,
99
);
t.like(
sources.find(source => source.source_key === 'bad-001'),
{ content_revision: '2000', reason: null }
);
t.like(
sources.find(source => source.source_key === 'healthy'),
{ content_revision: '2000', reason: null }
);
} finally {
await nativeProvider.stop();
await db.$executeRaw`DELETE FROM embedding_sources WHERE workspace_id=${workspaceId}`;
await db.$executeRaw`DELETE FROM embedding_workspace_states WHERE workspace_id=${workspaceId}`;
await db.$executeRaw`DELETE FROM snapshots WHERE workspace_id=${workspaceId}`;
await db.$executeRaw`DELETE FROM storage_reconciliation_checkpoints WHERE scope=${workspaceId}`;
await db.$executeRaw`DELETE FROM search_projection.workspace_states WHERE workspace_id=${workspaceId}`;
await db.$executeRaw`DELETE FROM workspaces WHERE id=${workspaceId}`;
}
});
@@ -298,6 +298,7 @@ test('workspace lifecycle sweep reports failures and continues beyond a failed p
const completed = new Set<string>();
let failing = true;
const attempted: string[] = [];
let blocked: Promise<never> | undefined;
const migration = new WorkspaceLifecycleMigration({
async listWorkspaceLifecycleMigrationCandidatesV1(after) {
return ids
@@ -305,6 +306,7 @@ test('workspace lifecycle sweep reports failures and continues beyond a failed p
.slice(0, 100);
},
async prepareWorkspaceLifecycleMigrationV1(id) {
if (blocked) return blocked;
attempted.push(id);
if (id === ids[0] && failing) throw new Error('source unavailable');
return { completed: false, revision: '1', rootStatus: 'missing' };
@@ -321,4 +323,21 @@ test('workspace lifecycle sweep reports failures and continues beyond a failed p
await migration.run();
t.is(completed.size, 101);
await migration.stop();
const failure = Promise.withResolvers<never>();
blocked = failure.promise;
const foreground = migration.ensure('foreground');
const rejected = t.throwsAsync(foreground, { message: 'foreground failed' });
const provider = new BackendRuntimeProvider(serverConfig);
const nativeStop = Sinon.stub().resolves();
Object.assign(provider, {
workspaceLifecycle: migration,
runtime: { stop: nativeStop },
});
const stopping = provider.stop();
await Promise.resolve();
failure.reject(new Error('foreground failed'));
await rejected;
await stopping;
t.true(nativeStop.calledOnce);
});
@@ -6,6 +6,7 @@ import {
CopilotSelectedSourcesLimitExceeded,
CopilotSelectedSourcesProcessing,
CopilotSelectedSourcesUnavailable,
DocUpdateInvalid,
metrics,
} from '../../base';
import { Models } from '../../models';
@@ -29,8 +30,25 @@ export class BackendRuntimeEmbeddingService {
private readonly models: Models
) {}
async syncDocument(workspaceId: string, docId: string) {
await this.syncDocuments(workspaceId, [docId]);
async syncDocument(workspaceId: string, docId: string, revision: string) {
try {
await this.syncDocuments(workspaceId, [docId]);
} catch (error) {
if (!(error instanceof DocUpdateInvalid)) throw error;
await this.rt.syncEmbeddingState({
workspaceId,
enabled: true,
documents: [
{
docId,
revision,
sourceHash: revision,
units: [],
skipReason: 'invalid_document',
},
],
});
}
}
async prepareSelectedDocuments(workspaceId: string, docIds: string[]) {
@@ -49,6 +67,8 @@ export class BackendRuntimeEmbeddingService {
}
private mapSelectedSourceError(error: unknown) {
if (error instanceof DocUpdateInvalid)
return new CopilotSelectedSourcesFailed();
const message = error instanceof Error ? error.message : String(error);
if (message.includes('embedding_selected_sources_processing')) {
return new CopilotSelectedSourcesProcessing();
@@ -49,7 +49,12 @@ export type RuntimeInvalidation =
workspaceId: string;
}
| { version: 1; kind: 'blobSource'; source: unknown }
| { version: 1; kind: 'workspaceInventoryChanged'; workspaceId: string }
| {
version: 1;
kind: 'workspaceInventoryChanged';
workspaceId: string;
docId?: string;
}
| {
version: 1;
kind: 'workspaceRootChanged';
@@ -28,7 +28,7 @@ export class WorkspaceLifecycleMigration {
async stop() {
this.stopped = true;
await this.sweep?.catch(() => {});
await Promise.all(this.pending.values());
await Promise.allSettled(this.pending.values());
}
async ensure(workspaceId: string): Promise<void> {
@@ -56,7 +56,7 @@ export class DocJobRunner {
}
const documents = await this.prisma.$queryRaw<
{ workspaceId: string; docId: string }[]
{ workspaceId: string; docId: string; revision: string }[]
>`
WITH current_sources AS (
SELECT workspace_id, guid, max(timestamp) AS updated_at
@@ -66,7 +66,8 @@ export class DocJobRunner {
SELECT workspace_id, guid, created_at AS timestamp FROM updates
) sources GROUP BY workspace_id, guid
)
SELECT snapshot.workspace_id AS "workspaceId", snapshot.guid AS "docId"
SELECT snapshot.workspace_id AS "workspaceId", snapshot.guid AS "docId",
((extract(epoch FROM snapshot.updated_at) * 1000)::bigint)::text AS revision
FROM current_sources snapshot
JOIN workspaces workspace ON workspace.id = snapshot.workspace_id
LEFT JOIN workspace_pages page ON page.workspace_id = snapshot.workspace_id AND page.page_id = snapshot.guid
@@ -95,7 +96,11 @@ export class DocJobRunner {
let syncedDocuments = 0;
for (const document of documents) {
try {
await this.embedding.syncDocument(document.workspaceId, document.docId);
await this.embedding.syncDocument(
document.workspaceId,
document.docId,
document.revision
);
syncedDocuments++;
} catch (error) {
this.logger.error('document embedding sync failed', {
@@ -624,17 +624,6 @@ export class SpaceSyncGateway
sourceSocketId?: string,
broadcastPayload?: BroadcastDocUpdatesMessage
) {
const revalidation = this.subscriptionRevalidations.get(
`${payload.spaceType}:${payload.spaceId}`
);
if (revalidation) {
void revalidation.promise
.then(() =>
this.emitActiveDocUpdate(payload, sourceSocketId, broadcastPayload)
)
.catch(error => this.logger.error(error));
return;
}
const sockets = this.activeDocSockets.get(
this.activeDocKey(payload.spaceType, payload.spaceId, payload.docId)
);
@@ -660,15 +649,6 @@ export class SpaceSyncGateway
}
private emitActiveAwarenessCollect(event: SyncAwarenessEvent) {
const revalidation = this.subscriptionRevalidations.get(
`${event.spaceType}:${event.spaceId}`
);
if (revalidation) {
void revalidation.promise
.then(() => this.emitActiveAwarenessCollect(event))
.catch(error => this.logger.error(error));
return;
}
const sockets = this.activeDocSockets.get(
this.activeDocKey(event.spaceType, event.spaceId, event.docId)
);
@@ -690,15 +670,6 @@ export class SpaceSyncGateway
private emitActiveAwarenessUpdate(
event: SyncAwarenessEvent & { awarenessUpdate: string }
) {
const revalidation = this.subscriptionRevalidations.get(
`${event.spaceType}:${event.spaceId}`
);
if (revalidation) {
void revalidation.promise
.then(() => this.emitActiveAwarenessUpdate(event))
.catch(error => this.logger.error(error));
return;
}
const sockets = this.activeDocSockets.get(
this.activeDocKey(event.spaceType, event.spaceId, event.docId)
);
@@ -918,6 +889,7 @@ export class SpaceSyncGateway
await this.revalidateActiveDocSubscriptions({
spaceType: SpaceType.Workspace,
spaceId: hint.workspaceId,
docId: hint.docId,
});
}
@@ -960,10 +932,6 @@ export class SpaceSyncGateway
this.emitActiveAwarenessUpdate(event);
}
@OnEvent('doc.grants.changed')
@OnEvent('doc.owner.changed')
@OnEvent('doc.default_role.changed')
@OnEvent('doc.public_state.changed')
@OnEvent('workspace.members.updated')
@OnEvent('workspace.members.roleChanged')
@OnEvent('workspace.members.removed')
@@ -1020,47 +988,57 @@ export class SpaceSyncGateway
const spaceKey = `${event.spaceType}:${event.spaceId}`;
let revalidation = this.subscriptionRevalidations.get(spaceKey);
const pending = revalidation?.pending ?? new Set<string>();
for (const [key, sockets] of this.activeDocSockets) {
if (key !== exactKey && (exactKey || !key.startsWith(spacePrefix)))
continue;
pending.add(key);
for (const socket of sockets) {
const authorizations = this.activeSocketDocActions.get(socket.id);
if (!authorizations) continue;
for (const [socketId, docs] of this.activeSocketDocs) {
const socket = this.server.sockets.sockets.get(socketId);
const authorizations = this.activeSocketDocActions.get(socketId);
if (!socket || !authorizations) continue;
for (const key of docs) {
if (key !== exactKey && (exactKey || !key.startsWith(spacePrefix)))
continue;
pending.add(key);
const actions = authorizations.get(key);
if (actions) authorizations.set(key, new Set(actions));
const sockets = this.activeDocSockets.get(key);
sockets?.delete(socket);
if (sockets?.size === 0) this.activeDocSockets.delete(key);
}
}
if (!revalidation) {
// Start after registration so overlapping hints share this worker.
const promise = Promise.resolve().then(async () => {
revalidation = {
pending,
promise: Promise.resolve(),
};
this.subscriptionRevalidations.set(spaceKey, revalidation);
const work = revalidation;
work.promise = Promise.resolve().then(async () => {
try {
while (pending.size) {
const keys = [...pending];
pending.clear();
await this.revalidateDocSubscriptions(event, keys);
await this.revalidateDocSubscriptions(event, keys, pending);
}
} finally {
this.subscriptionRevalidations.delete(spaceKey);
}
});
revalidation = { pending, promise };
this.subscriptionRevalidations.set(spaceKey, revalidation);
}
await revalidation.promise;
}
private async revalidateDocSubscriptions(
event: Events['sync.permissions.changed'],
keys: string[]
keys: string[],
pending: Set<string>
) {
const subscriptions = keys.flatMap(key =>
[...(this.activeDocSockets.get(key) ?? [])].flatMap(socket => {
const actions = this.activeSocketDocActions.get(socket.id)?.get(key);
return actions
? [{ key, socket, actions, docId: key.split(':')[2] }]
: [];
})
const docKeys = new Set(keys);
const subscriptions = [...this.server.sockets.sockets.values()].flatMap(
socket =>
[...(this.activeSocketDocActions.get(socket.id) ?? [])].flatMap(
([key, actions]) =>
docKeys.has(key)
? [{ key, socket, actions, docId: key.split(':')[2] }]
: []
)
);
const users = Map.groupBy(subscriptions, ({ socket }) =>
this.resolvePresenceUserId(socket)
@@ -1134,10 +1112,18 @@ export class SpaceSyncGateway
for (const { key, socket, actions, docId } of subscriptions) {
if (this.activeSocketDocActions.get(socket.id)?.get(key) !== actions)
continue;
if (
event.spaceType === SpaceType.Workspace &&
before !== undefined &&
before !== generation
) {
pending.add(key);
continue;
}
const nextActions = allowed.get(docId);
if (
nextActions?.has('Doc.Read') &&
(event.spaceType === SpaceType.Userspace || before === generation)
(event.spaceType === SpaceType.Userspace || before !== undefined)
) {
this.addActiveDocSubscription(
socket,
@@ -146,54 +146,69 @@ describe('CloudDocStorage broadcast updates', () => {
});
test('repairs strict invalidation through readable timestamps', async () => {
const storage = new CloudDocStorage({
accountId: 'account-1',
id: 'space-1',
serverBaseUrl: 'http://localhost',
isSelfHosted: true,
type: 'workspace',
readonlyMode: true,
});
vi.useFakeTimers();
try {
const storage = new CloudDocStorage({
accountId: 'account-1',
id: 'space-1',
serverBaseUrl: 'http://localhost',
isSelfHosted: true,
type: 'workspace',
readonlyMode: true,
});
(storage as any).connection.idConverter = {
oldIdToNewId: (id: string) => id,
newIdToOldId: (id: string) => id,
};
(storage as any).connection.idConverter = {
oldIdToNewId: (id: string) => id,
newIdToOldId: (id: string) => id,
};
const getDocTimestamps = vi
.spyOn(storage, 'getDocTimestamps')
.mockResolvedValue({ 'doc-a': new Date(1_000) });
const received: Array<{ docId: string; bin: Uint8Array }> = [];
storage.subscribeDocUpdate(update => {
received.push({ docId: update.docId, bin: update.bin });
});
const getDocTimestamps = vi
.spyOn(storage, 'getDocTimestamps')
.mockResolvedValue({ 'doc-a': new Date(1_000) });
const received: Array<{ docId: string; bin: Uint8Array }> = [];
storage.subscribeDocUpdate(update => {
received.push({ docId: update.docId, bin: update.bin });
});
storage.onServerInvalidation({
spaceType: 'workspace',
spaceId: 'space-1',
timestamp: 1_000,
});
storage.onServerInvalidation({
spaceType: 'workspace',
spaceId: 'space-1',
timestamp: 1_001,
});
storage.onServerInvalidation({
spaceType: 'workspace',
spaceId: 'space-1',
timestamp: 1_000,
});
storage.onServerInvalidation({
spaceType: 'workspace',
spaceId: 'space-1',
timestamp: 1_001,
});
await vi.waitFor(() => expect(received).toHaveLength(1));
expect(getDocTimestamps).toHaveBeenCalledOnce();
expect(received[0]).toMatchObject({ docId: 'doc-a' });
expect(received[0]?.bin).toEqual(new Uint8Array());
const inventoryChanged = vi.fn();
const unsubscribe =
storage.subscribeWorkspaceStateInvalidation(inventoryChanged);
storage.onServerInvalidation({
spaceType: 'workspace',
spaceId: 'space-1',
inventoryChanged: true,
});
expect(inventoryChanged).toHaveBeenCalledOnce();
expect(getDocTimestamps).toHaveBeenCalledOnce();
unsubscribe();
for (let i = 0; i < 3; i++) {
await vi.advanceTimersByTimeAsync(20);
storage.onServerInvalidation({
spaceType: 'workspace',
spaceId: 'space-1',
timestamp: 1_002 + i,
});
}
expect(received).toHaveLength(1);
expect(getDocTimestamps).toHaveBeenCalledOnce();
expect(received[0]).toMatchObject({ docId: 'doc-a' });
expect(received[0]?.bin).toEqual(new Uint8Array());
const inventoryChanged = vi.fn();
const unsubscribe =
storage.subscribeWorkspaceStateInvalidation(inventoryChanged);
storage.onServerInvalidation({
spaceType: 'workspace',
spaceId: 'space-1',
inventoryChanged: true,
});
expect(inventoryChanged).toHaveBeenCalledOnce();
expect(getDocTimestamps).toHaveBeenCalledOnce();
unsubscribe();
await vi.advanceTimersByTimeAsync(50);
expect(getDocTimestamps).toHaveBeenCalledTimes(2);
} finally {
vi.useRealTimers();
}
});
test('batch route joins the workspace and applies lifecycle commands', async () => {
@@ -1,5 +1,7 @@
import 'fake-indexeddb/auto';
import { readFileSync } from 'node:fs';
import * as reader from '@affine/reader';
import { OpConsumer } from '@toeverything/infra/op';
import { BehaviorSubject, firstValueFrom, NEVER } from 'rxjs';
@@ -1236,11 +1238,13 @@ test.each([
'malformed',
'reader-error',
'empty',
'rootless',
'storage-error',
'root-read-error',
] as const)(
'indexer completion waits for the current job and preserves failed %s sources',
async mode => {
const readAllBlocksFromDoc = reader.readAllBlocksFromDoc;
const docsInRootDoc = new Map([
['doc1', { title: 'Doc 1' }],
['doc2', { title: 'Doc 2' }],
@@ -1282,6 +1286,11 @@ test.each([
const prefixClock = encodeStateVector(prefix);
prefix.getMap('test').set('tail', true);
const pendingBin = encodeStateAsUpdate(prefix, prefixClock);
const rootless = new YDoc();
const image = new YMap();
image.set('sys:flavour', 'affine:image');
image.set('prop:sourceId', 'blob-1');
rootless.getMap('blocks').set('image', image);
const getDoc = vi
.spyOn(docStorage, 'getDoc')
.mockImplementation(async docId => {
@@ -1305,15 +1314,24 @@ test.each([
...doc,
bin:
mode === 'partial'
? pendingBin
? mergeUpdates([
readFileSync(
`${process.cwd()}/packages/common/reader/__tests__/__fixtures__/test-doc.snapshot.bin`
),
pendingBin,
])
: mode === 'malformed'
? new Uint8Array([255])
: doc.bin,
: mode === 'rootless'
? encodeStateAsUpdate(rootless)
: doc.bin,
};
});
const crawl = vi
.spyOn(reader, 'readAllBlocksFromDoc')
.mockImplementation(async () => {
.mockImplementation(async options => {
if (mode === 'partial' || mode === 'rootless')
return readAllBlocksFromDoc(options);
if (mode === 'reader-error' && !recovered) {
failedParseStarted.resolve();
await releaseFailedParse.promise;
@@ -1389,11 +1407,7 @@ test.each([
});
releaseFailedParse.resolve();
}
if (
mode === 'partial' ||
mode === 'malformed' ||
mode === 'storage-error'
) {
if (mode === 'malformed' || mode === 'storage-error') {
await sync.waitForDocCompleted('doc2');
expect(completed).toBe(false);
expect(docCompleted).toBe(false);
@@ -1425,6 +1439,22 @@ test.each([
await waitForCompleted;
await waitForDocCompleted;
expect((await firstValueFrom(sync.state$)).errorMessage).toBeNull();
if (mode === 'partial') {
expect(crawl).toHaveBeenCalled();
expect(
calls.filter(call => call.startsWith('insert:block:doc1:'))
).toHaveLength(42);
}
if (mode === 'rootless') {
expect(deleteBlocks).toHaveBeenCalledWith('block', {
type: 'match',
field: 'docId',
match: 'doc1',
});
expect(
calls.filter(call => call.startsWith('insert:block:doc1:'))
).toHaveLength(0);
}
if (mode === 'native')
expect(getDoc.mock.calls.map(([id]) => id)).toEqual(['workspace-id']);
expect(await metadata.getDocIndexedClock('doc1')).toMatchObject({
@@ -126,14 +126,11 @@ export class CloudDocStorage extends SnapshotDocStorageBase<CloudDocStorageOptio
private invalidationPending = false;
private scheduleInvalidationRepair() {
if (this.invalidationTimer) {
clearTimeout(this.invalidationTimer);
if (this.invalidationTimer || this.invalidationRepair) {
return;
}
this.invalidationTimer = setTimeout(() => {
this.invalidationTimer = undefined;
if (this.invalidationRepair) {
return;
}
this.invalidationPending = false;
this.invalidationRepair = this.repairInvalidatedDocs()
.catch(error => {
@@ -481,18 +481,12 @@ export class IndexerSyncImpl implements IndexerSync {
const docYDoc = new YDoc({ guid: docId });
try {
applyUpdate(docYDoc, doc.bin);
if (docYDoc.store.pendingStructs || docYDoc.store.pendingDs) {
throw new Error('Document source is incomplete');
}
const result = await crawlingDocData({
ydoc: docYDoc,
rootYDoc: this.status.rootDoc,
spaceId: this.status.rootDocId,
docId,
});
if (!result && docYDoc.getMap('blocks').size > 0) {
throw new Error('Document has no readable root block');
}
blocks = result?.blocks ?? [];
preview = result?.preview ?? '';
bodyTitle = result?.title ?? '';
@@ -30,6 +30,44 @@ const docSnapshotWithAiEditable = readFileSync(
)
);
test.each(['missing-child', 'parent-cycle'])(
'reads remaining blocks once with a %s',
async mode => {
const doc = new YDoc();
const blocks = doc.getMap('blocks');
blocks.set(
'page',
new YMap<unknown>([
['sys:id', 'page'],
['sys:flavour', 'affine:page'],
['prop:title', new YText('Title')],
[
'sys:children',
YArray.from(
mode === 'missing-child' ? ['missing', 'image'] : ['image']
),
],
])
);
blocks.set(
'image',
new YMap<unknown>([
['sys:id', 'image'],
['sys:flavour', 'affine:image'],
['prop:sourceId', 'image-blob'],
['sys:children', YArray.from(mode === 'parent-cycle' ? ['page'] : [])],
])
);
const result = await readAllBlocksFromDoc({ ydoc: doc, spaceId: 'space' });
expect(result?.blocks.map(block => block.blockId)).toEqual([
'page',
'image',
]);
expect(result?.blocks[1].blob).toEqual(['image-blob']);
doc.destroy();
}
);
test('should read doc blocks work', async () => {
const rootDoc = new YDoc({
guid: 'test-root-doc',
+5 -3
View File
@@ -562,7 +562,9 @@ export async function readAllBlocksFromDoc({
predicate: (block: YMap<any>) => boolean
) => {
let current: string | null = blockId;
while (current) {
const visited = new Set<string>();
while (current && !visited.has(current)) {
visited.add(current);
const block = blocks.get(current);
if (block && predicate(block)) {
return block;
@@ -589,7 +591,7 @@ export async function readAllBlocksFromDoc({
}
const queue: { parent?: string; id: string }[] = [{ id: rootBlockId }];
const visited = new Set<string>(); // avoid loop
const visited = new Set<string>([rootBlockId]); // avoid loop
const pushChildren = (id: string, block: YMap<any>) => {
const children = block.get('sys:children');
@@ -615,7 +617,7 @@ export async function readAllBlocksFromDoc({
const block = blockId ? blocks.get(blockId) : null;
const parentBlock = parentBlockId ? blocks.get(parentBlockId) : null;
if (!block) {
break;
continue;
}
const flavour = block.get('sys:flavour')?.toString();
@@ -1,82 +1,224 @@
/** @vitest-environment happy-dom */
import type { PeerWorkspaceState } from '@affine/nbstore';
import { Framework } from '@toeverything/infra';
import { describe, expect, it, vi } from 'vitest';
import { BehaviorSubject } from 'rxjs';
import { expect, test, vi } from 'vitest';
import {
Array as YArray,
Doc as YDoc,
encodeStateAsUpdate,
encodeStateVector,
Map as YMap,
mergeUpdates,
Text as YText,
} from 'yjs';
import { DocsSearchService } from '../../docs-search';
import { WorkspaceService } from '../../workspace';
import { WorkspaceFlavoursService } from '../../workspace/services/flavours';
import { UnusedBlobs } from './unused-blobs';
describe('UnusedBlobs', () => {
it('reads every used blob page from the local index', async () => {
const aggregate = vi
test.each([
'local',
'cloud',
'absent-root',
'pending',
'pending-delete',
'malformed',
'rootless',
'missing-child',
'parent-cycle',
'root-pending',
'root-clock-change',
'inventory-clock-source',
'missing-inventory-clock-source',
'missing',
'clock-change',
'inventory-change',
'inventory-unready',
] as const)(
'unused blob detection requires complete body coverage: %s',
async mode => {
const pending = new YDoc();
pending.getMap('test').set('prefix', 1);
const state = encodeStateVector(pending);
if (mode === 'root-pending')
pending.getMap('meta').set('avatar', 'hidden-avatar');
else if (mode === 'pending-delete') pending.getMap('test').delete('prefix');
else pending.getMap('test').set('tail', 2);
const partial = encodeStateAsUpdate(pending, state);
const sources = new Map<string, Uint8Array>([
['empty', new Uint8Array([0, 0])],
]);
for (const id of ['workspace', 'db$properties', 'userdata$user$settings']) {
if (mode === 'absent-root' && id === 'workspace') continue;
const doc = new YDoc({ guid: id });
doc.getMap('meta').set('avatar', `avatar-${id}`);
doc.getMap('blocks').set(
'image',
new YMap<unknown>([
['sys:flavour', 'affine:image'],
['prop:sourceId', `used-${id}`],
])
);
sources.set(
id,
mode === 'root-pending' && id === 'workspace'
? mergeUpdates([encodeStateAsUpdate(doc), partial])
: encodeStateAsUpdate(doc)
);
doc.destroy();
}
for (const id of ['doc1', 'doc2']) {
const doc = new YDoc({ guid: id });
const blocks = doc.getMap('blocks');
if (mode !== 'rootless' || id !== 'doc1') {
blocks.set(
'page',
new YMap<unknown>([
['sys:id', 'page'],
['sys:flavour', 'affine:page'],
['prop:title', new YText('Document')],
[
'sys:children',
YArray.from(
mode === 'missing-child' ? ['missing', 'image'] : ['image']
),
],
])
);
}
blocks.set(
'image',
new YMap<unknown>([
['sys:id', 'image'],
['sys:flavour', 'affine:image'],
['prop:sourceId', `used-${id}`],
[
'sys:children',
YArray.from(mode === 'parent-cycle' ? ['page'] : []),
],
])
);
let bin = encodeStateAsUpdate(doc);
if (id === 'doc1') {
if (mode === 'pending' || mode === 'pending-delete') {
bin = mergeUpdates([bin, partial]);
}
if (mode === 'malformed') bin = new Uint8Array([255]);
}
sources.set(id, bin);
doc.destroy();
}
pending.destroy();
const clocks = Object.fromEntries(
[...sources.keys()].map(id => [id, new Date(1000)])
);
if (
mode === 'inventory-clock-source' ||
mode === 'missing-inventory-clock-source'
) {
delete clocks['userdata$user$settings'];
}
const inventory = new BehaviorSubject<PeerWorkspaceState>({
ready: mode !== 'inventory-unready',
cacheToken: 1,
clocks: {
doc1: 1000,
doc2: 1000,
empty: 1000,
userdata$user$settings: 1000,
},
docs: ['doc1', 'doc2', 'empty'].map(docId => ({
docId,
timestamp: 1000,
lifecycle: docId === 'doc2' ? 'trashed' : null,
lifecycleChangedAt: null,
})),
});
const storage = {
getDocTimestamps: vi
.fn()
.mockResolvedValueOnce(clocks)
.mockResolvedValue(
mode === 'clock-change'
? { ...clocks, doc1: new Date(2000) }
: mode === 'root-clock-change'
? { ...clocks, workspace: new Date(2000) }
: clocks
),
getDoc: vi.fn(async (docId: string) => {
if (mode === 'missing' && docId === 'doc1') return null;
if (
mode === 'missing-inventory-clock-source' &&
docId === 'userdata$user$settings'
)
return null;
if (mode === 'inventory-change' && docId === 'doc2') {
inventory.next({ ...inventory.value, ready: false, docs: [] });
}
return { docId, bin: sources.get(docId), timestamp: clocks[docId] };
}),
};
const flavour = mode === 'local' ? 'local' : 'affine-cloud';
const listManageableBlobs = vi
.fn()
.mockResolvedValueOnce({
pagination: { hasMore: true },
buckets: [{ key: 'used-1' }],
})
.mockResolvedValueOnce({
pagination: { hasMore: false },
buckets: [{ key: 'used-2' }],
});
const getWorkspaceBlob = vi.fn();
const flavoursService = {
flavours$: {
value: [
{
flavour: 'local',
listManageableBlobs: vi
.fn()
.mockResolvedValue([
{ key: 'used-1' },
{ key: 'used-2' },
{ key: 'unused' },
]),
getWorkspaceBlob,
},
],
},
};
const workspaceService = {
workspace: {
id: 'workspace',
flavour: 'local',
avatar$: { value: null },
engine: { doc: { waitForSynced: vi.fn() } },
},
};
const docsSearchService = {
indexer: { aggregate, waitForCompleted: vi.fn() },
};
.mockResolvedValue(
[
'used-doc1',
'used-doc2',
'unused',
...(mode === 'root-pending' ? ['hidden-avatar'] : []),
...['workspace', 'db$properties', 'userdata$user$settings'].flatMap(
id =>
mode === 'absent-root' && id === 'workspace'
? []
: [`used-${id}`, `avatar-${id}`]
),
].map(key => ({ key }))
);
const framework = new Framework();
framework
.service(
WorkspaceFlavoursService,
flavoursService as unknown as WorkspaceFlavoursService
)
.service(
WorkspaceService,
workspaceService as unknown as WorkspaceService
)
.service(
DocsSearchService,
docsSearchService as unknown as DocsSearchService
)
.entity(UnusedBlobs, [
WorkspaceFlavoursService,
WorkspaceService,
DocsSearchService,
]);
.service(WorkspaceFlavoursService, {
flavours$: { value: [{ flavour, listManageableBlobs }] },
} as unknown as WorkspaceFlavoursService)
.service(WorkspaceService, {
workspace: {
id: 'workspace',
flavour,
engine: {
doc: {
waitForSynced: vi.fn(),
workspaceState$: inventory,
storage,
},
},
},
} as unknown as WorkspaceService)
.entity(UnusedBlobs, [WorkspaceFlavoursService, WorkspaceService]);
const entity = framework.provider().createEntity(UnusedBlobs);
await expect(entity.getUnusedBlobs()).resolves.toEqual([{ key: 'unused' }]);
expect(entity).not.toHaveProperty('hydrateBlob');
expect(getWorkspaceBlob).not.toHaveBeenCalled();
expect(aggregate).toHaveBeenCalledTimes(2);
expect(aggregate.mock.calls.map(call => call[3])).toEqual([
{ pagination: { limit: 1000, skip: 0 }, prefer: 'local' },
{ pagination: { limit: 1000, skip: 1000 }, prefer: 'local' },
]);
});
});
if (
mode === 'local' ||
mode === 'cloud' ||
mode === 'absent-root' ||
mode === 'rootless' ||
mode === 'missing-child' ||
mode === 'parent-cycle' ||
mode === 'inventory-clock-source'
) {
await expect(entity.getUnusedBlobs()).resolves.toEqual([
{ key: 'unused' },
]);
expect(storage.getDoc.mock.calls.map(([id]) => id).sort()).toEqual([
'db$properties',
'doc1',
'doc2',
'empty',
'userdata$user$settings',
...(mode === 'absent-root' ? [] : ['workspace']),
]);
} else {
await expect(entity.getUnusedBlobs()).rejects.toThrow();
}
}
);
@@ -7,17 +7,17 @@ import {
onComplete,
onStart,
} from '@toeverything/infra';
import { switchMap, tap } from 'rxjs';
import { isEqual } from 'lodash-es';
import { firstValueFrom, switchMap, tap } from 'rxjs';
import { applyUpdate, Doc as YDoc, Map as YMap } from 'yjs';
import type { DocsSearchService } from '../../docs-search';
import type { WorkspaceService } from '../../workspace';
import type { WorkspaceFlavoursService } from '../../workspace/services/flavours';
export class UnusedBlobs extends Entity {
constructor(
private readonly flavoursService: WorkspaceFlavoursService,
private readonly workspaceService: WorkspaceService,
private readonly docsSearchService: DocsSearchService
private readonly workspaceService: WorkspaceService
) {
super();
}
@@ -27,8 +27,8 @@ export class UnusedBlobs extends Entity {
readonly revalidate = effect(
switchMap(() =>
fromPromise(async () => {
return await this.getUnusedBlobs();
fromPromise(async signal => {
return await this.getUnusedBlobs(signal);
}).pipe(
tap(data => {
this.unusedBlobs$.setValue(data);
@@ -61,45 +61,76 @@ export class UnusedBlobs extends Entity {
}
async getUnusedBlobs(abortSignal?: AbortSignal) {
// Wait for both sync and indexing to complete
await this.workspaceService.workspace.engine.doc.waitForSynced();
await this.docsSearchService.indexer.waitForCompleted(abortSignal);
const [blobs, usedBlobs] = await Promise.all([
this.listManageableBlobs(),
this.getUsedBlobs(),
]);
// ignore the workspace avatar
const workspaceAvatar = this.workspaceService.workspace.avatar$.value;
return (
blobs?.filter(
blob => !usedBlobs.includes(blob.key) && blob.key !== workspaceAvatar
) ?? []
await this.workspaceService.workspace.engine.doc.waitForSynced(
undefined,
abortSignal
);
const blobs = await this.listManageableBlobs();
const usedBlobs = await this.getUsedBlobs(abortSignal);
abortSignal?.throwIfAborted();
return blobs?.filter(blob => !usedBlobs.has(blob.key)) ?? [];
}
private async getUsedBlobs(): Promise<string[]> {
const limit = 1000;
const usedBlobs: string[] = [];
for (let skip = 0; ; skip += limit) {
const result = await this.docsSearchService.indexer.aggregate(
'block',
{
type: 'boolean',
occur: 'must',
queries: [{ type: 'exists', field: 'blob' }],
},
'blob',
{ pagination: { limit, skip }, prefer: 'local' }
);
usedBlobs.push(...result.buckets.map(bucket => bucket.key));
if (!result.pagination.hasMore) return usedBlobs;
if (result.buckets.length === 0) {
throw new Error('Local blob index pagination did not advance');
private async getUsedBlobs(signal?: AbortSignal): Promise<Set<string>> {
const workspace = this.workspaceService.workspace;
const frontend = workspace.engine.doc;
const storage = frontend.storage;
const inventory =
workspace.flavour === 'local'
? null
: await firstValueFrom(frontend.workspaceState$);
if (workspace.flavour !== 'local' && !inventory?.ready) {
throw new Error('Document inventory is not ready');
}
const clocks = await storage.getDocTimestamps();
const docIds = new Set([
...Object.keys(clocks),
...(inventory?.docs.map(doc => doc.docId) ?? []),
...Object.keys(inventory?.clocks ?? {}),
]);
const usedBlobs = new Set<string>();
for (const docId of docIds) {
signal?.throwIfAborted();
const record = await storage.getDoc(docId);
if (!record) throw new Error('Document source is unavailable');
const doc = new YDoc({ guid: docId });
try {
applyUpdate(doc, record.bin);
if (doc.store.pendingStructs || doc.store.pendingDs) {
throw new Error('Document blob references are incomplete');
}
const avatar = doc.getMap('meta').get('avatar');
if (typeof avatar === 'string' && avatar) usedBlobs.add(avatar);
for (const block of doc.getMap('blocks').values()) {
if (!(block instanceof YMap)) continue;
const flavour = block.get('sys:flavour');
if (flavour !== 'affine:image' && flavour !== 'affine:attachment') {
continue;
}
const blob = block.get('prop:sourceId');
if (typeof blob === 'string') usedBlobs.add(blob);
}
} finally {
doc.destroy();
}
}
signal?.throwIfAborted();
const currentClocks = await storage.getDocTimestamps();
if (!isEqual(clocks, currentClocks)) {
throw new Error(
'Document sources changed while checking blob references'
);
}
if (
inventory &&
!isEqual(inventory, await firstValueFrom(frontend.workspaceState$))
) {
throw new Error(
'Document inventory changed while checking blob references'
);
}
return usedBlobs;
}
}
@@ -1,6 +1,5 @@
import { type Framework } from '@toeverything/infra';
import { DocsSearchService } from '../docs-search';
import { WorkspaceScope, WorkspaceService } from '../workspace';
import { WorkspaceFlavoursService } from '../workspace/services/flavours';
import { UnusedBlobs } from './entity/unused-blobs';
@@ -9,10 +8,6 @@ import { BlobManagementService } from './services';
export function configureBlobManagementModule(framework: Framework) {
framework
.scope(WorkspaceScope)
.entity(UnusedBlobs, [
WorkspaceFlavoursService,
WorkspaceService,
DocsSearchService,
])
.entity(UnusedBlobs, [WorkspaceFlavoursService, WorkspaceService])
.service(BlobManagementService);
}
@@ -80,7 +80,7 @@ export class Workspace extends Entity {
id: this.openOptions.metadata.id,
rootDoc: this.rootYDoc,
inventory$:
this.flavour === 'local'
this.flavour === 'local' || this.openOptions.isSharedMode
? undefined
: this.engine.doc.workspaceState$,
projectedTitles$:
@@ -1,10 +1,64 @@
import type { PeerWorkspaceState } from '@affine/nbstore';
import { Framework } from '@toeverything/infra';
import { BehaviorSubject } from 'rxjs';
import { expect, test } from 'vitest';
import { expect, test, vi } from 'vitest';
import { Array as YArray, Doc as YDoc, Map as YMap } from 'yjs';
import { FeatureFlagService } from '../../feature-flag';
import { Workspace } from '../entities/workspace';
import { WorkspaceScope } from '../scopes/workspace';
import { WorkspaceEngineService } from '../services/engine';
import { WorkspaceImpl } from './workspace';
test.each([true, false])(
'workspace public mode %s selects its document identity source',
isSharedMode => {
const framework = new Framework();
framework
.service(FeatureFlagService, {} as FeatureFlagService)
.scope(WorkspaceScope)
.service(WorkspaceEngineService, {
engine: {
doc: {
workspaceState$: new BehaviorSubject(null),
connectDoc: vi.fn(),
},
indexer: { docTitles$: new BehaviorSubject({}) },
blob: { registerSource: vi.fn().mockResolvedValue(undefined) },
},
} as unknown as WorkspaceEngineService)
.entity(Workspace, [WorkspaceScope, FeatureFlagService]);
const scope = framework.provider().createScope(WorkspaceScope, {
openOptions: {
metadata: { id: 'public-workspace', flavour: 'affine-cloud' },
isSharedMode,
},
engineWorkerInitOptions: {
local: {
doc: {
name: 'StaticCloudDocStorage',
opts: {
id: 'public-workspace',
publicRootDocId: 'public-doc',
serverBaseUrl: 'https://example.com',
},
},
},
remotes: {},
},
});
const workspace = scope.framework.createEntity(Workspace);
const pages = new YArray<YMap<unknown>>();
workspace.rootYDoc.getMap('meta').set('pages', pages);
pages.push([new YMap<unknown>([['id', 'public-doc']])]);
expect(workspace.docCollection.meta.docMetas.map(doc => doc.id)).toEqual(
isSharedMode ? ['public-doc'] : []
);
expect(!!workspace.docCollection.getDoc('public-doc')).toBe(isSharedMode);
scope.dispose();
}
);
test('cloud documents use inventory identity and preserve editors through raw metadata changes', () => {
const root = new YDoc({ guid: 'cloud-workspace' });
const pages = new YArray<YMap<unknown>>();