mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-01 09:52:11 +03:00
feat(core): improve sync protocol
This commit is contained in:
1 parent
9c61550279
commit
fb744d6aed
173 files changed
+11032
-7617
No files matched your search
Generated
+8
-8
@@ -76,9 +76,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "affine_core"
|
||||
version = "0.0.11"
|
||||
version = "0.0.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5061001e55555388ecbe1c614daa401188441e54c38e8b085b7f94f2bac01563"
|
||||
checksum = "9248b8911bb9045881f88d20f83c39a46e90ebbe98ce8b3ca05ffa06ceb9c2f0"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"chrono",
|
||||
@@ -93,9 +93,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "affine_doc_loader"
|
||||
version = "0.1.11"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "52f78576f0d8862c41e56a15ecc63b5424630b126a41160e7fcd3fdbb441f4ff"
|
||||
checksum = "da9b86987246581f2219a7e9838426669cf26187406977d3ae065f041e115dbb"
|
||||
dependencies = [
|
||||
"affine_merge",
|
||||
"chrono",
|
||||
@@ -110,9 +110,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "affine_importer"
|
||||
version = "0.1.4"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7b1cf38c45c12d6e981adc554264d5c3318cabde658719d138b497e87d8bbf49"
|
||||
checksum = "907e52a22fb81129174c9033036c4dd8050017d798b1b18e0016b69742588c8f"
|
||||
dependencies = [
|
||||
"affine_doc_loader",
|
||||
"bytes",
|
||||
@@ -11362,9 +11362,9 @@ checksum = "aee1b19627c7c60102ab80d3a9cbe18de90bfe03bfa6c3715447681f0e8c8af6"
|
||||
|
||||
[[package]]
|
||||
name = "y-octo"
|
||||
version = "0.1.1"
|
||||
version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1b067d00433f8ea8e07988706e8664d137dd35e262bf8a6f5ea82afe8d3ee920"
|
||||
checksum = "befa3530e907f8e7cf681391b09f7f6110a8a6474cb1fa11157ae0e904ac7e28"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"arbitrary",
|
||||
|
||||
+3
-3
@@ -16,8 +16,8 @@ resolver = "3"
|
||||
[workspace.dependencies]
|
||||
aes-gcm = "0.10"
|
||||
affine_common = { path = "./packages/common/native" }
|
||||
affine_doc_loader = "0.1.11"
|
||||
affine_importer = "0.1.4"
|
||||
affine_doc_loader = "0.2.1"
|
||||
affine_importer = "0.2.0"
|
||||
affine_nbstore = { path = "./packages/frontend/native/nbstore" }
|
||||
affine_preview = { version = "0.1.0", default-features = false }
|
||||
anyhow = "1"
|
||||
@@ -111,7 +111,7 @@ resolver = "3"
|
||||
"Win32_UI_Shell_PropertiesSystem",
|
||||
] }
|
||||
windows-core = { version = "0.62" }
|
||||
y-octo = "0.1.1"
|
||||
y-octo = { version = "0.1.4", features = ["large_refs"] }
|
||||
zeroize = "1.9"
|
||||
zip = "9.0.5"
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ crate-type = ["cdylib"]
|
||||
[dependencies]
|
||||
aes-gcm = { workspace = true }
|
||||
affine_common = { workspace = true, features = ["hashcash", "napi"] }
|
||||
affine_core = "0.0.11"
|
||||
affine_core = "0.0.13"
|
||||
affine_doc_loader = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
argon2 = "0.6"
|
||||
@@ -89,7 +89,7 @@ url = { workspace = true }
|
||||
uuid = { workspace = true, features = ["v4"] }
|
||||
v_htmlescape = { workspace = true }
|
||||
webpki-roots = "1.0"
|
||||
y-octo = { workspace = true, features = ["large_refs"] }
|
||||
y-octo = { workspace = true }
|
||||
zeroize = { workspace = true }
|
||||
|
||||
[target.'cfg(not(target_os = "linux"))'.dependencies]
|
||||
|
||||
Vendored
+39
-30
@@ -44,16 +44,14 @@ export declare class BackendRuntime {
|
||||
/**
|
||||
* Merge pending doc updates with y-octo and persist the merged snapshot.
|
||||
*
|
||||
* Do not use this for snapshots that will be sent back to yjs clients until
|
||||
* the y-octo/yjs round-trip compatibility issue is resolved.
|
||||
*
|
||||
* The caller must pass the canonical history retention period resolved for
|
||||
* this workspace. The compactor does not make quota decisions.
|
||||
*/
|
||||
compactPendingDocUpdates(workspaceId: string, docId: string, batchLimit: number, historyMinIntervalMs: number, historyMaxAgeSeconds: number): Promise<RuntimeDocCompactionResult>
|
||||
getCurrentWorkspaceDocV1(workspaceId: string, docId: string): Promise<RuntimeDocRecord | null>
|
||||
upsertDocSnapshot(workspaceId: string, docId: string, blob: Buffer, timestampMs: number, editorId?: string | undefined | null): Promise<boolean>
|
||||
createDocHistory(input: RuntimeDocHistoryInput): Promise<boolean>
|
||||
appendWorkspaceDocUpdatesV1(input: AppendWorkspaceDocUpdatesInputV1): Promise<number>
|
||||
appendWorkspaceDocUpdatesV1(input: AppendWorkspaceDocUpdatesInputV1): Promise<WorkspaceDocWriteResultV1>
|
||||
appendWorkspaceDocUpdatesTrustedV1(input: AppendWorkspaceDocUpdatesTrustedInputV1): Promise<number>
|
||||
embeddingHealth(): Promise<EmbeddingHealth>
|
||||
syncEmbeddingState(input: SyncEmbeddingStateInput): Promise<RuntimeEmbeddingWorkspaceState>
|
||||
@@ -126,6 +124,11 @@ export declare class BackendRuntime {
|
||||
activateWorkspaceSeatV1(input: RuntimeSeatActivationInput): Promise<boolean>
|
||||
reserveWorkspaceSeatsV1(input: RuntimeSeatReservationInput): Promise<RuntimeSeatReservationDecision>
|
||||
reserveStorageQuotaV1(input: RuntimeStorageReservationInput): Promise<RuntimeStorageReservationDecision>
|
||||
activateWorkspaceLifecycleV1(): Promise<boolean>
|
||||
listWorkspaceLifecycleMigrationCandidatesV1(): Promise<Array<string>>
|
||||
prepareWorkspaceLifecycleMigrationV1(workspaceId: string): Promise<WorkspaceLifecycleMigrationSourceV1>
|
||||
migrateWorkspaceLifecycleV1(input: WorkspaceLifecycleMigrationInputV1): Promise<boolean>
|
||||
getWorkspaceStateV1(workspaceId: string, actorUserId: string): Promise<any>
|
||||
constructor(serverConfig: ServerConfigHandle, privateKey?: string | undefined | null, permissionTelemetry?: (((err: Error | null, arg: string) => void)) | undefined | null, invalidationEvents?: (((err: Error | null, arg: string) => void)) | undefined | null)
|
||||
}
|
||||
|
||||
@@ -153,8 +156,6 @@ export declare class StorageRuntime {
|
||||
backfillMissingBlobMetadata(workspaceId: string | undefined | null, limit: number): Promise<RuntimeBlobMetadataBackfillResult>
|
||||
rebuildDocBlobRefs(workspaceId: string, docId: string, sourceRevision: number): Promise<RuntimeDocBlobRefsResult>
|
||||
rebuildWorkspaceDocBlobRefs(workspaceId: string, limit: number): Promise<RuntimeDocBlobRefsResult>
|
||||
reconcileWorkspaceDocuments(workspaceId: string): Promise<RuntimeDocumentCleanupReconcileResult>
|
||||
executeDocumentCleanupCandidates(workspaceId: string | undefined | null, gracePeriodDays: number, limit: number): Promise<RuntimeDocumentCleanupExecuteResult>
|
||||
deleteWorkspaceObjects(workspaceId: string, userIds?: Array<string> | undefined | null): Promise<number>
|
||||
reconcileWorkspaceStorage(limit: number): Promise<RuntimeWorkspaceStorageReconcileResult>
|
||||
constructor(serverConfig: ServerConfigHandle)
|
||||
@@ -239,8 +240,8 @@ export interface AppendWorkspaceDocUpdatesInputV1 {
|
||||
updates: Array<Buffer>
|
||||
actorUserId: string
|
||||
writeIntent: WorkspaceDocWriteIntentV1
|
||||
permissionDocId?: string
|
||||
expectedPermissionGeneration?: number
|
||||
protocolVersion?: number
|
||||
}
|
||||
|
||||
export interface AppendWorkspaceDocUpdatesTrustedInputV1 {
|
||||
@@ -615,9 +616,7 @@ export interface DocumentEmbeddingProjectionInput {
|
||||
revision: string
|
||||
sourceHash: string
|
||||
skipReason?: string
|
||||
rootRevision?: string
|
||||
units: Array<DocumentEmbeddingUnitInput>
|
||||
deleted?: boolean
|
||||
}
|
||||
|
||||
export interface DocumentEmbeddingUnitInput {
|
||||
@@ -689,6 +688,8 @@ export interface InvalidationHealth {
|
||||
publishFailures: number
|
||||
}
|
||||
|
||||
export declare function isOrdinaryWorkspaceDoc(workspaceId: string, docId: string): boolean
|
||||
|
||||
export interface IssueLicenseInput {
|
||||
licenseId: string
|
||||
workspaceId: string
|
||||
@@ -845,11 +846,7 @@ export interface MatchEmbeddingCandidatesInput {
|
||||
limit?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge updates in form like `Y.applyUpdate(doc, update)` way and return the
|
||||
* result binary.
|
||||
*/
|
||||
export declare function mergeUpdatesInApplyWay(updates: Array<Buffer>): Buffer
|
||||
export declare function mergeUpdates(updates: Array<Buffer>): Buffer
|
||||
|
||||
export declare function mintChallengeResponse(resource: string, bits?: number | undefined | null): Promise<string>
|
||||
|
||||
@@ -1320,21 +1317,10 @@ export interface RuntimeDocHistoryInput {
|
||||
historyMaxAgeMs: number
|
||||
}
|
||||
|
||||
export interface RuntimeDocumentCleanupExecuteResult {
|
||||
scannedCandidates: number
|
||||
serializationRetries: number
|
||||
executed: number
|
||||
recovered: number
|
||||
reset: number
|
||||
failed: number
|
||||
deletedRows: number
|
||||
}
|
||||
|
||||
export interface RuntimeDocumentCleanupReconcileResult {
|
||||
scannedDocs: number
|
||||
marked: number
|
||||
reset: number
|
||||
recovered: number
|
||||
export interface RuntimeDocRecord {
|
||||
bin: Buffer
|
||||
timestamp: number
|
||||
editor?: string
|
||||
}
|
||||
|
||||
export interface RuntimeEmbeddingCandidate {
|
||||
@@ -1825,7 +1811,6 @@ export interface SyncEmbeddingStateInput {
|
||||
workspaceId: string
|
||||
enabled: boolean
|
||||
documents?: Array<DocumentEmbeddingProjectionInput>
|
||||
reconcileDocuments?: boolean
|
||||
priority?: number
|
||||
waitForReadyMs?: number
|
||||
}
|
||||
@@ -1917,3 +1902,27 @@ export declare function verifyChallengeResponse(response: string, bits: number,
|
||||
|
||||
export type WorkspaceDocWriteIntentV1 = 'update_doc'|
|
||||
'create_doc';
|
||||
|
||||
export interface WorkspaceDocWriteResultV1 {
|
||||
timestamp: number
|
||||
created: boolean
|
||||
}
|
||||
|
||||
export interface WorkspaceLegacyDocV1 {
|
||||
docId: string
|
||||
trashed: boolean
|
||||
}
|
||||
|
||||
export interface WorkspaceLifecycleMigrationInputV1 {
|
||||
workspaceId: string
|
||||
sourceRevision: string
|
||||
rootStatus: string
|
||||
docs: Array<WorkspaceLegacyDocV1>
|
||||
}
|
||||
|
||||
export interface WorkspaceLifecycleMigrationSourceV1 {
|
||||
revision: string
|
||||
bin?: Buffer
|
||||
completed: boolean
|
||||
rootStatus: string
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
pub(crate) fn spawn<T: Send + 'static>(
|
||||
guard: impl Send + 'static,
|
||||
task: impl FnOnce() -> T + Send + 'static,
|
||||
) -> tokio::task::JoinHandle<T> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let _guard = guard;
|
||||
task()
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn permit_outlives_the_caller() {
|
||||
for cancel in [false, true] {
|
||||
let slots = Arc::new(Semaphore::new(1));
|
||||
let permit = slots.clone().try_acquire_owned().unwrap();
|
||||
let (started, entered) = tokio::sync::oneshot::channel();
|
||||
let (release, blocked) = std::sync::mpsc::channel();
|
||||
let (finished, exited) = tokio::sync::oneshot::channel();
|
||||
let validation = tokio::spawn(async move {
|
||||
let task = spawn(permit, move || {
|
||||
started.send(()).unwrap();
|
||||
blocked.recv().unwrap();
|
||||
finished.send(()).unwrap();
|
||||
});
|
||||
if cancel {
|
||||
task.await.unwrap();
|
||||
false
|
||||
} else {
|
||||
tokio::time::timeout(std::time::Duration::from_millis(10), task)
|
||||
.await
|
||||
.is_err()
|
||||
}
|
||||
});
|
||||
entered.await.unwrap();
|
||||
if cancel {
|
||||
validation.abort();
|
||||
assert!(validation.await.unwrap_err().is_cancelled());
|
||||
} else {
|
||||
assert!(validation.await.unwrap());
|
||||
}
|
||||
assert!(slots.clone().try_acquire_owned().is_err());
|
||||
release.send(()).unwrap();
|
||||
exited.await.unwrap();
|
||||
let permit = tokio::time::timeout(std::time::Duration::from_secs(1), slots.acquire_owned())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(spawn(permit, || 42).await.unwrap(), 42);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
mod write;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::{Arc, OnceLock},
|
||||
};
|
||||
|
||||
use affine_common::napi_utils::map_napi_err;
|
||||
use affine_doc_loader::{
|
||||
@@ -10,11 +13,24 @@ use affine_doc_loader::{
|
||||
};
|
||||
use napi::bindgen_prelude::*;
|
||||
use napi_derive::napi;
|
||||
use tokio::sync::{OwnedSemaphorePermit, Semaphore, TryAcquireError};
|
||||
pub use write::{
|
||||
DocWriteContext, add_doc_to_root_doc, build_public_root_doc, create_doc_with_markdown, update_doc_properties,
|
||||
update_doc_title, update_doc_with_markdown, update_root_doc_meta_title,
|
||||
};
|
||||
|
||||
pub(crate) fn try_validation_slot() -> std::result::Result<OwnedSemaphorePermit, TryAcquireError> {
|
||||
static SLOTS: OnceLock<Arc<Semaphore>> = OnceLock::new();
|
||||
SLOTS
|
||||
.get_or_init(|| {
|
||||
Arc::new(Semaphore::new(
|
||||
std::thread::available_parallelism().map_or(1, usize::from),
|
||||
))
|
||||
})
|
||||
.clone()
|
||||
.try_acquire_owned()
|
||||
}
|
||||
|
||||
#[napi(object)]
|
||||
pub struct NativeMarkdownResult {
|
||||
pub title: String,
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
mod audio_slice;
|
||||
mod auth_session;
|
||||
mod blocking;
|
||||
pub mod content_policy;
|
||||
pub mod doc;
|
||||
pub mod doc_loader;
|
||||
@@ -23,7 +24,7 @@ mod utils;
|
||||
|
||||
use affine_common::napi_utils::map_napi_err;
|
||||
use napi::{Result, Status, bindgen_prelude::*};
|
||||
use y_octo::{Doc, Update};
|
||||
use y_octo::Update;
|
||||
|
||||
#[cfg(not(target_arch = "arm"))]
|
||||
#[global_allocator]
|
||||
@@ -32,28 +33,21 @@ static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc;
|
||||
#[macro_use]
|
||||
extern crate napi_derive;
|
||||
|
||||
/// Merge updates in form like `Y.applyUpdate(doc, update)` way and return the
|
||||
/// result binary.
|
||||
#[napi(catch_unwind)]
|
||||
pub fn merge_updates_in_apply_way(updates: Vec<Buffer>) -> Result<Buffer> {
|
||||
let mut doc = Doc::default();
|
||||
for update in updates {
|
||||
map_napi_err(doc.apply_update_from_binary_v1(update.as_ref()), Status::GenericFailure)?;
|
||||
}
|
||||
|
||||
let buf = map_napi_err(doc.encode_update_v1(), Status::GenericFailure)?;
|
||||
|
||||
Ok(buf.into())
|
||||
pub fn merge_updates(updates: Vec<Buffer>) -> Result<Buffer> {
|
||||
let merged = map_napi_err(y_octo::merge_updates_v1(&updates), Status::GenericFailure)?;
|
||||
Ok(map_napi_err(merged.encode_v1(), Status::GenericFailure)?.into())
|
||||
}
|
||||
|
||||
/// Check whether a Yjs update binary can be decoded without applying it to a
|
||||
/// document state.
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn validate_doc_update(update: Buffer) -> Result<bool> {
|
||||
let permit = doc::try_validation_slot().map_err(|_| napi::Error::from_reason("doc_validation_unavailable"))?;
|
||||
let update = update.to_vec();
|
||||
tokio::task::spawn_blocking(move || Update::decode_v1(update).is_ok())
|
||||
blocking::spawn(permit, move || Update::decode_v1(update).is_ok())
|
||||
.await
|
||||
.map_err(|err| napi::Error::from_reason(format!("Doc update validation task failed: {err}")))
|
||||
.map_err(|_| napi::Error::from_reason("doc_validation_unavailable"))
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
@@ -88,7 +82,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn merge_updates_reports_generic_failure() {
|
||||
let err = match merge_updates_in_apply_way(vec![Buffer::from(vec![0])]) {
|
||||
let err = match merge_updates(vec![Buffer::from(vec![0])]) {
|
||||
Ok(_) => panic!("expected error"),
|
||||
Err(err) => err,
|
||||
};
|
||||
|
||||
@@ -27,6 +27,11 @@ pub fn canonicalize_document_identity(
|
||||
})
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub fn is_ordinary_workspace_doc(workspace_id: String, doc_id: String) -> bool {
|
||||
affine_core::access_control::is_ordinary_workspace_doc(&workspace_id, &doc_id)
|
||||
}
|
||||
|
||||
pub(crate) fn permission_evaluation_output(
|
||||
decision: affine_core::access_control::AuthorizationDecision,
|
||||
) -> PermissionEvaluationOutputV1 {
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::{
|
||||
use affine_doc_loader::blob_refs::{MAX_SOURCE_BINARY_BYTES, live_blob_keys};
|
||||
use tokio::sync::{Mutex, OwnedSemaphorePermit, Semaphore};
|
||||
|
||||
use super::{SourceIdentity, types::LoadedSource};
|
||||
use super::{SourceIdentity, blocking, types::LoadedSource};
|
||||
use crate::runtime::{
|
||||
RuntimeError, RuntimeResult, backend_runtime::permission::PermissionTelemetry, blob_ref_projection_error_code,
|
||||
};
|
||||
@@ -138,15 +138,14 @@ impl BlobRefCache {
|
||||
self.remove_flight(&identity, &stamp, &flight).await;
|
||||
return Ok(keys);
|
||||
}
|
||||
let Ok(_parse) = self.parse_slots.clone().acquire_owned().await else {
|
||||
let Ok(permit) = self.parse_slots.clone().acquire_owned().await else {
|
||||
self.remove_flight(&identity, &stamp, &flight).await;
|
||||
return Err(RuntimeError::invalid_state("blob_ref_parse_unavailable"));
|
||||
};
|
||||
let workspace_root = identity.is_workspace_root();
|
||||
let parsed = tokio::task::spawn_blocking(move || live_blob_keys(blob, workspace_root)).await;
|
||||
drop(_parse);
|
||||
let (keys, parser) = match parsed {
|
||||
Ok(Ok((keys, parser))) => (Arc::<[Box<str>]>::from(keys), parser),
|
||||
let parsed = blocking::spawn(permit, move || live_blob_keys(blob, workspace_root)).await;
|
||||
let keys = match parsed {
|
||||
Ok(Ok(keys)) => Arc::<[Box<str>]>::from(keys),
|
||||
Ok(Err(error)) => {
|
||||
let reason = blob_ref_projection_error_code(error);
|
||||
self.remove_flight(&identity, &stamp, &flight).await;
|
||||
@@ -159,7 +158,7 @@ impl BlobRefCache {
|
||||
return Err(RuntimeError::invalid_state("parse_task_failed"));
|
||||
}
|
||||
};
|
||||
self.record("parse", parser.label()).await;
|
||||
self.record("parse", "immutable").await;
|
||||
let result = confirm().await;
|
||||
if result.is_ok() {
|
||||
self
|
||||
@@ -430,41 +429,79 @@ mod tests {
|
||||
assert_eq!(cache.generations().await, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn concurrent_misses_share_one_parsed_result() {
|
||||
let cache = Arc::new(BlobRefCache::with_limits(4096, 1, 1));
|
||||
let source = loaded_source("stamp", "blob");
|
||||
let confirmation_started = Arc::new(tokio::sync::Notify::new());
|
||||
let release_confirmation = Arc::new(tokio::sync::Notify::new());
|
||||
let left = {
|
||||
let cache = Arc::clone(&cache);
|
||||
let source = source.clone();
|
||||
let confirmation_started = Arc::clone(&confirmation_started);
|
||||
let release_confirmation = Arc::clone(&release_confirmation);
|
||||
tokio::spawn(async move {
|
||||
cache
|
||||
.refs(source, || async {
|
||||
confirmation_started.notify_one();
|
||||
release_confirmation.notified().await;
|
||||
Ok(())
|
||||
#[test]
|
||||
fn shared_parses_hold_capacity_through_cancellation() {
|
||||
tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.max_blocking_threads(1)
|
||||
.build()
|
||||
.unwrap()
|
||||
.block_on(async {
|
||||
let cache = Arc::new(BlobRefCache::with_limits(4096, 1, 1));
|
||||
let source = loaded_source("stamp", "blob");
|
||||
let confirmation_started = Arc::new(tokio::sync::Notify::new());
|
||||
let release_confirmation = Arc::new(tokio::sync::Notify::new());
|
||||
let left = {
|
||||
let cache = Arc::clone(&cache);
|
||||
let source = source.clone();
|
||||
let confirmation_started = Arc::clone(&confirmation_started);
|
||||
let release_confirmation = Arc::clone(&release_confirmation);
|
||||
tokio::spawn(async move {
|
||||
cache
|
||||
.refs(source, || async {
|
||||
confirmation_started.notify_one();
|
||||
release_confirmation.notified().await;
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
})
|
||||
};
|
||||
confirmation_started.notified().await;
|
||||
let right = {
|
||||
let cache = Arc::clone(&cache);
|
||||
let source = source.clone();
|
||||
tokio::spawn(async move { cache.refs(source, || async { Ok(()) }).await })
|
||||
};
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(cache.flights().await, 1);
|
||||
release_confirmation.notify_one();
|
||||
let left = left.await.unwrap().unwrap();
|
||||
let right = right.await.unwrap().unwrap();
|
||||
assert!(Arc::ptr_eq(&left, &right));
|
||||
assert!(cache.hit(&source.identity, &source.stamp).await.is_some());
|
||||
assert_eq!(cache.flights().await, 0);
|
||||
let (release_worker, blocked_worker) = std::sync::mpsc::channel();
|
||||
let (worker_started, worker_entered) = tokio::sync::oneshot::channel();
|
||||
let worker = tokio::task::spawn_blocking(move || {
|
||||
worker_started.send(()).unwrap();
|
||||
blocked_worker.recv().unwrap();
|
||||
});
|
||||
worker_entered.await.unwrap();
|
||||
let cancelled = {
|
||||
let cache = Arc::clone(&cache);
|
||||
tokio::spawn(async move {
|
||||
cache
|
||||
.refs(loaded_source("cancelled", "other-blob"), || async { Ok(()) })
|
||||
.await
|
||||
})
|
||||
};
|
||||
tokio::time::timeout(Duration::from_secs(1), async {
|
||||
while cache.parse_slots.available_permits() != 0 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
cancelled.abort();
|
||||
assert!(cancelled.await.unwrap_err().is_cancelled());
|
||||
assert!(cache.parse_slots.clone().try_acquire_owned().is_err());
|
||||
release_worker.send(()).unwrap();
|
||||
worker.await.unwrap();
|
||||
let _permit = tokio::time::timeout(Duration::from_secs(1), cache.parse_slots.clone().acquire_owned())
|
||||
.await
|
||||
})
|
||||
};
|
||||
confirmation_started.notified().await;
|
||||
let right = {
|
||||
let cache = Arc::clone(&cache);
|
||||
let source = source.clone();
|
||||
tokio::spawn(async move { cache.refs(source, || async { Ok(()) }).await })
|
||||
};
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(cache.flights().await, 1);
|
||||
release_confirmation.notify_one();
|
||||
let left = left.await.unwrap().unwrap();
|
||||
let right = right.await.unwrap().unwrap();
|
||||
assert!(Arc::ptr_eq(&left, &right));
|
||||
assert!(cache.hit(&source.identity, &source.stamp).await.is_some());
|
||||
assert_eq!(cache.flights().await, 0);
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
});
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -10,7 +10,9 @@ use std::{
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use affine_core::access_control::{DocAction, WorkspaceAction};
|
||||
use affine_core::access_control::{
|
||||
DocAction, ReservedDocumentAccessDecision, WorkspaceAction, authorize_reserved_document, classify_reserved_document,
|
||||
};
|
||||
pub(super) use affine_core::blob_access::SourceIdentity;
|
||||
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use serde_json::Value;
|
||||
@@ -29,8 +31,9 @@ use self::{
|
||||
},
|
||||
};
|
||||
use super::{
|
||||
BackendRuntime,
|
||||
BackendRuntime, blocking,
|
||||
invalidation::{InvalidationHintV1, InvalidationTarget},
|
||||
load_workspace_doc_states_page_in,
|
||||
permission::{PermissionAuthorizer, PermissionTelemetry},
|
||||
};
|
||||
use crate::runtime::{Deployment, RuntimeError, RuntimeResult, napi_error, object_storage::ObjectStorageService};
|
||||
@@ -147,6 +150,16 @@ impl BlobAccessService {
|
||||
break;
|
||||
}
|
||||
let next_source_cursor = doc_ids.last().cloned();
|
||||
let doc_ids = doc_ids
|
||||
.into_iter()
|
||||
.filter(|doc_id| {
|
||||
doc_id == &request.workspace_id
|
||||
|| authorize_reserved_document(
|
||||
&request.actor_user_id,
|
||||
classify_reserved_document(&request.workspace_id, doc_id),
|
||||
) != ReservedDocumentAccessDecision::Denied
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let readable_docs = self
|
||||
.authorizer
|
||||
.authorize_doc_action_batch_in(
|
||||
@@ -328,8 +341,18 @@ impl BlobAccessService {
|
||||
impl InvalidationTarget for BlobAccessService {
|
||||
fn invalidate<'a>(&'a self, hint: &'a InvalidationHintV1) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
|
||||
Box::pin(async move {
|
||||
if let InvalidationHintV1::BlobSource { source } = hint {
|
||||
self.cache.invalidate(source).await;
|
||||
match hint {
|
||||
InvalidationHintV1::BlobSource { source } => self.cache.invalidate(source).await,
|
||||
InvalidationHintV1::WorkspaceRootChanged { workspace_id, .. } => {
|
||||
self
|
||||
.cache
|
||||
.invalidate(&SourceIdentity::CurrentDoc {
|
||||
workspace_id: workspace_id.clone(),
|
||||
doc_id: workspace_id.clone(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
use affine_doc_loader::blob_refs::{MAX_SOURCE_BINARY_BYTES, MAX_SOURCE_UPDATES, page_workspace_doc_ids};
|
||||
use affine_doc_loader::blob_refs::{MAX_SOURCE_BINARY_BYTES, MAX_SOURCE_UPDATES};
|
||||
use chrono::{DateTime, Utc};
|
||||
use futures_util::TryStreamExt;
|
||||
use sha2::{Digest, Sha256};
|
||||
use sqlx::{PgPool, Postgres, Row, Transaction};
|
||||
use y_octo::Doc;
|
||||
|
||||
use super::{
|
||||
SourceIdentity,
|
||||
SourceIdentity, load_workspace_doc_states_page_in,
|
||||
types::{LoadedSource, ManifestEntry},
|
||||
};
|
||||
use crate::runtime::{RuntimeError, RuntimeResult, blob_ref_projection_error_code};
|
||||
use crate::runtime::{RuntimeError, RuntimeResult};
|
||||
|
||||
pub(super) struct BlobAccessStore {
|
||||
pool: PgPool,
|
||||
@@ -114,14 +113,13 @@ impl BlobAccessStore {
|
||||
include_cursor: bool,
|
||||
limit: i64,
|
||||
) -> RuntimeResult<Vec<String>> {
|
||||
let identity = SourceIdentity::CurrentDoc {
|
||||
workspace_id: workspace_id.to_string(),
|
||||
doc_id: workspace_id.to_string(),
|
||||
};
|
||||
let root = Self::load_source(transaction, &identity).await?;
|
||||
let limit = usize::try_from(limit).map_err(|_| RuntimeError::invalid_input("blob_page_limit_invalid"))?;
|
||||
page_workspace_doc_ids(root.blob, workspace_id, cursor, include_cursor, limit)
|
||||
.map_err(|error| RuntimeError::invalid_state(blob_ref_projection_error_code(error)))
|
||||
Ok(
|
||||
load_workspace_doc_states_page_in(transaction, workspace_id, cursor, include_cursor, Some(limit))
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|state| state.doc_id)
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,7 +189,7 @@ async fn load_current(
|
||||
return Err(RuntimeError::invalid_input("blob_source_not_found"));
|
||||
}
|
||||
let mut source_times = Vec::with_capacity(updates.len() + usize::from(snapshot.is_some()));
|
||||
let mut doc = Doc::default();
|
||||
let mut parts = Vec::with_capacity(updates.len() + usize::from(snapshot.is_some()));
|
||||
if let Some(snapshot) = snapshot {
|
||||
let blob: Vec<u8> = snapshot
|
||||
.try_get("blob")
|
||||
@@ -201,9 +199,7 @@ async fn load_current(
|
||||
.try_get("source_time")
|
||||
.map_err(|error| RuntimeError::database("decode current blob source timestamp", error))?,
|
||||
);
|
||||
doc
|
||||
.apply_update_from_binary_v1(&blob)
|
||||
.map_err(|_| RuntimeError::invalid_state("blob_source_parse_failed"))?;
|
||||
parts.push(blob);
|
||||
}
|
||||
for update in updates {
|
||||
let blob: Vec<u8> = update
|
||||
@@ -214,12 +210,10 @@ async fn load_current(
|
||||
.try_get("source_time")
|
||||
.map_err(|error| RuntimeError::database("decode current blob update timestamp", error))?,
|
||||
);
|
||||
doc
|
||||
.apply_update_from_binary_v1(&blob)
|
||||
.map_err(|_| RuntimeError::invalid_state("blob_source_parse_failed"))?;
|
||||
parts.push(blob);
|
||||
}
|
||||
let blob = doc
|
||||
.encode_update_v1()
|
||||
let blob = y_octo::merge_updates_v1(parts.iter().map(Vec::as_slice))
|
||||
.and_then(|update| update.encode_v1())
|
||||
.map_err(|_| RuntimeError::invalid_state("blob_source_parse_failed"))?;
|
||||
if blob.len() > MAX_SOURCE_BINARY_BYTES {
|
||||
return Err(RuntimeError::invalid_state("blob_ref_source_too_large"));
|
||||
|
||||
@@ -241,6 +241,123 @@ async fn source_acl_history_and_live_ledger_are_enforced_together() {
|
||||
service.manifest(None, current(&fixture)).await.unwrap().entries.len(),
|
||||
1
|
||||
);
|
||||
sqlx::query("INSERT INTO workspace_members(workspace_id,user_id,role,state) VALUES($1,$2,'member','active')")
|
||||
.bind(&fixture.workspace_id)
|
||||
.bind(&fixture.direct_user_id)
|
||||
.execute(&fixture.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let userdata_id = affine_core::access_control::userdata_document_id(
|
||||
&fixture.member_user_id,
|
||||
&fixture.workspace_id,
|
||||
affine_core::access_control::UserdataTable::Settings,
|
||||
)
|
||||
.unwrap();
|
||||
let global_id = format!("db${}$folders", fixture.workspace_id);
|
||||
let later_id = format!("zz-ordinary-{}", Uuid::new_v4().simple());
|
||||
let invalid_id = format!("db${}$invalid00", fixture.workspace_id);
|
||||
let mut sources = vec![
|
||||
(userdata_id.clone(), "userdata-key"),
|
||||
(global_id.clone(), "global-key"),
|
||||
(later_id.clone(), "later-ordinary-key"),
|
||||
];
|
||||
sources.extend((0..SOURCE_PAGE_LIMIT * 2 + 2).map(|index| {
|
||||
(
|
||||
format!("db${}$invalid{index:02}", fixture.workspace_id),
|
||||
"invalid-reserved-key",
|
||||
)
|
||||
}));
|
||||
let timestamp = chrono::DateTime::from_timestamp_millis(fixture.history_timestamp_ms).unwrap();
|
||||
for (doc_id, key) in sources {
|
||||
let blob = affine_doc_loader::build_full_doc("Reserved source", &format!(""), &doc_id).unwrap();
|
||||
sqlx::query(
|
||||
"WITH snapshot AS (INSERT INTO snapshots(workspace_id,guid,blob,updated_at) VALUES($1,$2,$3,now()) RETURNING \
|
||||
workspace_id,guid,blob) INSERT INTO snapshot_histories(workspace_id,guid,blob,timestamp,expired_at) SELECT \
|
||||
workspace_id,guid,blob,$4,now()+interval '1 day' FROM snapshot",
|
||||
)
|
||||
.bind(&fixture.workspace_id)
|
||||
.bind(&doc_id)
|
||||
.bind(blob)
|
||||
.bind(timestamp)
|
||||
.execute(&fixture.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
for key in [
|
||||
"userdata-key",
|
||||
"global-key",
|
||||
"later-ordinary-key",
|
||||
"invalid-reserved-key",
|
||||
] {
|
||||
sqlx::query("INSERT INTO blobs(workspace_id,key,size,mime,status) VALUES($1,$2,7,'image/png','completed')")
|
||||
.bind(&fixture.workspace_id)
|
||||
.bind(key)
|
||||
.execute(&fixture.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
for actor in [&fixture.member_user_id, &fixture.direct_user_id] {
|
||||
for (doc_id, key, allowed) in [
|
||||
(&userdata_id, "userdata-key", actor == &fixture.member_user_id),
|
||||
(&global_id, "global-key", true),
|
||||
(&later_id, "later-ordinary-key", true),
|
||||
(&invalid_id, "invalid-reserved-key", false),
|
||||
] {
|
||||
for source in [
|
||||
SourceIdentity::CurrentDoc {
|
||||
workspace_id: fixture.workspace_id.clone(),
|
||||
doc_id: doc_id.clone(),
|
||||
},
|
||||
SourceIdentity::History {
|
||||
workspace_id: fixture.workspace_id.clone(),
|
||||
doc_id: doc_id.clone(),
|
||||
timestamp_ms: fixture.history_timestamp_ms,
|
||||
},
|
||||
] {
|
||||
let result = service.manifest(Some(actor), source).await;
|
||||
if allowed {
|
||||
assert_eq!(result.unwrap().entries[0].key, key);
|
||||
} else {
|
||||
assert!(result.is_err(), "reserved source must deny {actor}");
|
||||
}
|
||||
}
|
||||
}
|
||||
let entries = tokio::time::timeout(Duration::from_secs(10), async {
|
||||
let mut entries = Vec::new();
|
||||
let mut cursor = None;
|
||||
let mut cursors = HashSet::new();
|
||||
loop {
|
||||
let page = service
|
||||
.workspace_manifest(WorkspaceManifestRequestV1 {
|
||||
actor_user_id: actor.clone(),
|
||||
workspace_id: fixture.workspace_id.clone(),
|
||||
cursor,
|
||||
limit: Some(1),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
entries.extend(page.entries);
|
||||
let Some(next) = page.next_cursor else {
|
||||
break;
|
||||
};
|
||||
assert!(
|
||||
cursors.insert(next.clone()),
|
||||
"denied source pages must advance the cursor"
|
||||
);
|
||||
cursor = Some(next);
|
||||
}
|
||||
entries
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let keys = entries.iter().map(|entry| entry.key.as_str()).collect::<HashSet<_>>();
|
||||
assert!(keys.contains("completed-key"));
|
||||
assert!(keys.contains("global-key"));
|
||||
assert!(keys.contains("later-ordinary-key"));
|
||||
assert!(!keys.contains("invalid-reserved-key"));
|
||||
assert_eq!(keys.contains("userdata-key"), actor == &fixture.member_user_id);
|
||||
assert_eq!(entries.len(), if actor == &fixture.member_user_id { 4 } else { 3 });
|
||||
}
|
||||
teardown(&fixture).await;
|
||||
}
|
||||
|
||||
@@ -450,7 +567,7 @@ async fn doc_append_invalidation_fences_inflight_refresh_and_stamp_covers_redis_
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn workspace_page_uses_complete_root_live_set_and_excludes_orphan_snapshots() {
|
||||
async fn workspace_page_uses_body_identity_independently_of_root_directory() {
|
||||
let _guard = BLOB_ACCESS_TEST_LOCK.lock().await;
|
||||
let Some(fixture) = setup().await else {
|
||||
return;
|
||||
@@ -502,6 +619,15 @@ async fn workspace_page_uses_complete_root_live_set_and_excludes_orphan_snapshot
|
||||
.execute(&fixture.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"INSERT INTO workspace_pages(workspace_id,page_id,lifecycle_state,lifecycle_changed_at) \
|
||||
VALUES($1,$2,'trashed',now())",
|
||||
)
|
||||
.bind(&fixture.workspace_id)
|
||||
.bind(&orphan_id)
|
||||
.execute(&fixture.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let output = service(&fixture)
|
||||
.workspace_manifest(WorkspaceManifestRequestV1 {
|
||||
actor_user_id: fixture.member_user_id.clone(),
|
||||
@@ -523,7 +649,7 @@ async fn workspace_page_uses_complete_root_live_set_and_excludes_orphan_snapshot
|
||||
.is_err(),
|
||||
"a direct document grant must not bypass the workspace member-only manifest gate"
|
||||
);
|
||||
assert!(output.entries.iter().all(|entry| entry.key != "orphan-key"));
|
||||
assert!(output.entries.iter().any(|entry| entry.key == "orphan-key"));
|
||||
let same_key_sources = output
|
||||
.entries
|
||||
.iter()
|
||||
@@ -578,7 +704,7 @@ async fn workspace_page_uses_complete_root_live_set_and_excludes_orphan_snapshot
|
||||
let Some(next) = page.next_cursor else { break };
|
||||
cursor = Some(next);
|
||||
}
|
||||
assert_eq!(paged.len(), 5);
|
||||
assert_eq!(paged.len(), 6);
|
||||
assert_eq!(paged.iter().filter(|(_, key)| key == "completed-key").count(), 2);
|
||||
|
||||
let mut complete_root = Doc::default();
|
||||
@@ -635,7 +761,7 @@ async fn workspace_page_uses_complete_root_live_set_and_excludes_orphan_snapshot
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(bounded.entries.len(), source_count + 5);
|
||||
assert_eq!(bounded.entries.len(), source_count + 6);
|
||||
assert!(bounded.next_cursor.is_none());
|
||||
|
||||
sqlx::query("DELETE FROM doc_grants WHERE workspace_id=$1 AND doc_id=$2 AND principal_id=$3")
|
||||
@@ -688,6 +814,30 @@ async fn workspace_page_uses_complete_root_live_set_and_excludes_orphan_snapshot
|
||||
.execute(&fixture.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut transaction = fixture.pool.begin().await.unwrap();
|
||||
let ids = BlobAccessStore::page_doc_ids(&mut transaction, &fixture.workspace_id, None, false, 100)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(ids.contains(&orphan_id));
|
||||
assert!(ids.contains(&live_doc_id));
|
||||
let full = crate::runtime::document_state::load_workspace_doc_states_in(&mut transaction, &fixture.workspace_id)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(ids, full.into_iter().map(|state| state.doc_id).collect::<Vec<_>>());
|
||||
let mut cursor = None;
|
||||
let mut paged_ids = Vec::new();
|
||||
loop {
|
||||
let page = BlobAccessStore::page_doc_ids(&mut transaction, &fixture.workspace_id, cursor.as_deref(), false, 2)
|
||||
.await
|
||||
.unwrap();
|
||||
if page.is_empty() {
|
||||
break;
|
||||
}
|
||||
cursor = page.last().cloned();
|
||||
paged_ids.extend(page);
|
||||
}
|
||||
assert_eq!(paged_ids, ids);
|
||||
transaction.commit().await.unwrap();
|
||||
assert!(
|
||||
service(&fixture)
|
||||
.workspace_manifest(WorkspaceManifestRequestV1 {
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
use chrono::{DateTime, Duration, Utc};
|
||||
use sqlx::{FromRow, PgPool, Postgres, Row, Transaction};
|
||||
#[cfg(test)]
|
||||
use y_octo::Doc;
|
||||
|
||||
use super::{BackendRuntime, RuntimeError, RuntimeResult, napi_error, types::RuntimeDocCompactionResult};
|
||||
use super::{
|
||||
BackendRuntime, RuntimeError, RuntimeResult, ensure_doc_not_deleted_in, napi_error, try_lock_current_doc_read,
|
||||
types::RuntimeDocCompactionResult,
|
||||
};
|
||||
|
||||
#[derive(FromRow)]
|
||||
struct SnapshotRow {
|
||||
@@ -56,16 +60,10 @@ fn is_empty_doc(bin: &[u8]) -> bool {
|
||||
bin.is_empty() || (bin.len() == 1 && bin[0] == 0) || (bin.len() == 2 && bin[0] == 0 && bin[1] == 0)
|
||||
}
|
||||
|
||||
fn apply_updates(updates: impl IntoIterator<Item = Vec<u8>>) -> RuntimeResult<Vec<u8>> {
|
||||
let mut doc = Doc::default();
|
||||
for update in updates {
|
||||
doc
|
||||
.apply_update_from_binary_v1(&update)
|
||||
.map_err(|err| RuntimeError::invalid_state(format!("DocCompactor merge failed: {err}")))?;
|
||||
}
|
||||
doc
|
||||
.encode_update_v1()
|
||||
.map_err(|err| RuntimeError::invalid_state(format!("DocCompactor encode failed: {err}")))
|
||||
fn merge_updates(updates: impl IntoIterator<Item = Vec<u8>>) -> RuntimeResult<Vec<u8>> {
|
||||
y_octo::merge_updates_v1(updates)
|
||||
.and_then(|update| update.encode_v1())
|
||||
.map_err(|error| RuntimeError::invalid_state(format!("DocCompactor merge failed: {error}")))
|
||||
}
|
||||
|
||||
fn checked_milliseconds(value: i64, field: &str) -> RuntimeResult<Duration> {
|
||||
@@ -128,13 +126,8 @@ async fn upsert_snapshot(
|
||||
blob: &[u8],
|
||||
timestamp: DateTime<Utc>,
|
||||
editor: Option<&str>,
|
||||
allow_empty: bool,
|
||||
) -> RuntimeResult<bool> {
|
||||
if !allow_empty && is_empty_doc(blob) {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
let row = sqlx::query(
|
||||
) -> RuntimeResult<()> {
|
||||
sqlx::query(
|
||||
r#"
|
||||
INSERT INTO snapshots
|
||||
(workspace_id, guid, blob, size, created_at, updated_at, created_by, updated_by)
|
||||
@@ -158,11 +151,11 @@ async fn upsert_snapshot(
|
||||
.bind(blob.len() as i64)
|
||||
.bind(timestamp)
|
||||
.bind(editor)
|
||||
.fetch_optional(&mut **tx)
|
||||
.fetch_one(&mut **tx)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("DocCompactor upsert snapshot failed", err))?;
|
||||
|
||||
Ok(row.is_some())
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn should_create_history(
|
||||
@@ -285,13 +278,7 @@ async fn compact_doc(
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("DocCompactor begin transaction failed", err))?;
|
||||
|
||||
super::domain_command::lock_workspace_storage_shared(&mut tx, workspace_id).await?;
|
||||
|
||||
let locked: bool = sqlx::query_scalar("SELECT pg_try_advisory_xact_lock(hashtextextended($1, 0))")
|
||||
.bind(format!("workspace-doc-update:{workspace_id}/{doc_id}"))
|
||||
.fetch_one(&mut *tx)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("DocCompactor acquire document transaction lock failed", err))?;
|
||||
let locked = try_lock_current_doc_read(&mut tx, workspace_id, doc_id).await?;
|
||||
if !locked {
|
||||
tx.rollback()
|
||||
.await
|
||||
@@ -299,6 +286,7 @@ async fn compact_doc(
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
ensure_doc_not_deleted_in(&mut tx, workspace_id, doc_id).await?;
|
||||
let snapshot = load_snapshot(&mut tx, workspace_id, doc_id).await?;
|
||||
let updates = load_updates(&mut tx, workspace_id, doc_id, batch_limit).await?;
|
||||
if updates.is_empty() {
|
||||
@@ -320,23 +308,27 @@ async fn compact_doc(
|
||||
let final_blob = if merge_inputs.len() == 1 {
|
||||
merge_inputs.remove(0)
|
||||
} else {
|
||||
apply_updates(merge_inputs)?
|
||||
merge_updates(merge_inputs)?
|
||||
};
|
||||
|
||||
let snapshot_updated = upsert_snapshot(
|
||||
&mut tx,
|
||||
workspace_id,
|
||||
doc_id,
|
||||
&final_blob,
|
||||
last.created_at,
|
||||
last.created_by.as_deref(),
|
||||
snapshot.is_none(),
|
||||
)
|
||||
.await?;
|
||||
let mut timestamp = snapshot
|
||||
.as_ref()
|
||||
.map_or(last.created_at, |snapshot| snapshot.updated_at.max(last.created_at));
|
||||
if snapshot
|
||||
.as_ref()
|
||||
.is_some_and(|snapshot| snapshot.updated_at >= last.created_at && snapshot.blob != final_blob)
|
||||
{
|
||||
timestamp = super::domain_command::next_workspace_doc_update_timestamp(&mut tx, workspace_id, doc_id).await?;
|
||||
}
|
||||
let editor = snapshot
|
||||
.as_ref()
|
||||
.filter(|snapshot| snapshot.updated_at > last.created_at)
|
||||
.and_then(|snapshot| snapshot.updated_by.as_deref())
|
||||
.or(last.created_by.as_deref());
|
||||
upsert_snapshot(&mut tx, workspace_id, doc_id, &final_blob, timestamp, editor).await?;
|
||||
|
||||
let mut history_created = false;
|
||||
if snapshot_updated
|
||||
&& let Some(snapshot) = &snapshot
|
||||
if let Some(snapshot) = &snapshot
|
||||
&& should_create_history(&mut tx, snapshot, workspace_id, doc_id, history_min_interval_ms).await?
|
||||
{
|
||||
history_created = create_history(&mut tx, workspace_id, doc_id, snapshot, history_max_age_seconds).await?;
|
||||
@@ -356,9 +348,6 @@ async fn compact_doc(
|
||||
impl BackendRuntime {
|
||||
/// Merge pending doc updates with y-octo and persist the merged snapshot.
|
||||
///
|
||||
/// Do not use this for snapshots that will be sent back to yjs clients until
|
||||
/// the y-octo/yjs round-trip compatibility issue is resolved.
|
||||
///
|
||||
/// The caller must pass the canonical history retention period resolved for
|
||||
/// this workspace. The compactor does not make quota decisions.
|
||||
#[napi]
|
||||
@@ -491,6 +480,106 @@ mod tests {
|
||||
.unwrap()
|
||||
);
|
||||
|
||||
let first: DateTime<Utc> = sqlx::query_scalar("SELECT updated_at FROM snapshots WHERE workspace_id=$1 AND guid=$2")
|
||||
.bind(&workspace_id)
|
||||
.bind(doc_id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let empty_ack = first + Duration::milliseconds(1);
|
||||
sqlx::query("INSERT INTO updates(workspace_id,guid,blob,created_at) VALUES($1,$2,decode('0000','hex'),$3)")
|
||||
.bind(&workspace_id)
|
||||
.bind(doc_id)
|
||||
.bind(empty_ack)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
runtime
|
||||
.compact_pending_doc_updates(workspace_id.clone(), doc_id.into(), 100, 0, 3600)
|
||||
.await
|
||||
.unwrap();
|
||||
let current: DateTime<Utc> =
|
||||
sqlx::query_scalar("SELECT updated_at FROM snapshots WHERE workspace_id=$1 AND guid=$2")
|
||||
.bind(&workspace_id)
|
||||
.bind(doc_id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(current, empty_ack);
|
||||
let older = Doc::with_client(99);
|
||||
older
|
||||
.get_or_create_text("text")
|
||||
.unwrap()
|
||||
.insert(0, "older material")
|
||||
.unwrap();
|
||||
sqlx::query("INSERT INTO updates(workspace_id,guid,blob,created_at) VALUES($1,$2,$3,$4)")
|
||||
.bind(&workspace_id)
|
||||
.bind(doc_id)
|
||||
.bind(older.encode_update_v1().unwrap())
|
||||
.bind(first - Duration::milliseconds(1))
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
runtime
|
||||
.compact_pending_doc_updates(workspace_id.clone(), doc_id.into(), 100, 0, 3600)
|
||||
.await
|
||||
.unwrap();
|
||||
let merged: (Vec<u8>, DateTime<Utc>) =
|
||||
sqlx::query_as("SELECT blob,updated_at FROM snapshots WHERE workspace_id=$1 AND guid=$2")
|
||||
.bind(&workspace_id)
|
||||
.bind(doc_id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(merged.1 > current);
|
||||
assert_eq!(
|
||||
Doc::try_from_binary_v1(&merged.0)
|
||||
.unwrap()
|
||||
.get_or_create_text("text")
|
||||
.unwrap()
|
||||
.to_string(),
|
||||
"older material"
|
||||
);
|
||||
let trigger = format!("rfc21_compactor_{}", uuid::Uuid::new_v4().simple());
|
||||
sqlx::raw_sql(&format!(
|
||||
"CREATE FUNCTION {trigger}() RETURNS trigger LANGUAGE plpgsql AS $$BEGIN RETURN NULL; END$$; CREATE TRIGGER \
|
||||
{trigger} BEFORE UPDATE ON snapshots FOR EACH ROW WHEN(NEW.workspace_id='{workspace_id}') EXECUTE FUNCTION \
|
||||
{trigger}()"
|
||||
))
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("INSERT INTO updates(workspace_id,guid,blob,created_at) VALUES($1,$2,decode('0000','hex'),$3)")
|
||||
.bind(&workspace_id)
|
||||
.bind(doc_id)
|
||||
.bind(merged.1 + Duration::milliseconds(1))
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
runtime
|
||||
.compact_pending_doc_updates(workspace_id.clone(), doc_id.into(), 100, 0, 3600)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
let pending: i64 = sqlx::query_scalar("SELECT count(*) FROM updates WHERE workspace_id=$1 AND guid=$2")
|
||||
.bind(&workspace_id)
|
||||
.bind(doc_id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(pending, 1);
|
||||
sqlx::raw_sql(&format!(
|
||||
"DROP TRIGGER {trigger} ON snapshots; DROP FUNCTION {trigger}()"
|
||||
))
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
runtime
|
||||
.compact_pending_doc_updates(workspace_id.clone(), doc_id.into(), 100, 0, 3600)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
sqlx::query("DELETE FROM workspaces WHERE id=$1")
|
||||
.bind(&workspace_id)
|
||||
.execute(&pool)
|
||||
|
||||
@@ -2,7 +2,10 @@ use chrono::{DateTime, Duration, Utc};
|
||||
use napi::bindgen_prelude::Buffer;
|
||||
use sqlx::{Postgres, Row, Transaction};
|
||||
|
||||
use super::{BackendRuntime, RuntimeError, RuntimeResult, napi_error, types::RuntimeDocHistoryInput};
|
||||
use super::{
|
||||
BackendRuntime, RuntimeError, RuntimeResult, load_current_doc_parts_in, lock_current_doc_read, merge_current_doc,
|
||||
napi_error, types::RuntimeDocHistoryInput,
|
||||
};
|
||||
|
||||
fn is_empty_doc(bin: &[u8]) -> bool {
|
||||
bin.is_empty() || (bin.len() == 1 && bin[0] == 0) || (bin.len() == 2 && bin[0] == 0 && bin[1] == 0)
|
||||
@@ -30,8 +33,42 @@ async fn latest_history_timestamp(
|
||||
.map_err(|err| RuntimeError::database("DocStorage load latest history failed", err))
|
||||
}
|
||||
|
||||
#[napi_derive::napi(object)]
|
||||
pub struct RuntimeDocRecord {
|
||||
pub bin: Buffer,
|
||||
pub timestamp: i64,
|
||||
pub editor: Option<String>,
|
||||
}
|
||||
|
||||
#[napi_derive::napi]
|
||||
impl BackendRuntime {
|
||||
#[napi]
|
||||
pub async fn get_current_workspace_doc_v1(
|
||||
&self,
|
||||
workspace_id: String,
|
||||
doc_id: String,
|
||||
) -> napi::Result<Option<RuntimeDocRecord>> {
|
||||
let pool = self.pool().await?;
|
||||
let mut transaction = pool
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("begin current document read", error))?;
|
||||
lock_current_doc_read(&mut transaction, &workspace_id, &doc_id).await?;
|
||||
let (snapshot, updates) = load_current_doc_parts_in(&mut transaction, &workspace_id, &doc_id).await?;
|
||||
let result = merge_current_doc(snapshot, updates)
|
||||
.map_err(|_| RuntimeError::invalid_state("doc_update_invalid"))?
|
||||
.map(|root| RuntimeDocRecord {
|
||||
bin: root.blob.into(),
|
||||
timestamp: root.updated_at.timestamp_millis(),
|
||||
editor: root.updated_by,
|
||||
});
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("commit current document read", error))?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub async fn upsert_doc_snapshot(
|
||||
&self,
|
||||
@@ -41,10 +78,9 @@ impl BackendRuntime {
|
||||
timestamp_ms: i64,
|
||||
editor_id: Option<String>,
|
||||
) -> napi::Result<bool> {
|
||||
if is_empty_doc(blob.as_ref()) {
|
||||
return Ok(false);
|
||||
if workspace_id == doc_id {
|
||||
return Err(napi_error("doc_is_workspace"));
|
||||
}
|
||||
|
||||
let timestamp = DateTime::<Utc>::from_timestamp_millis(timestamp_ms)
|
||||
.ok_or_else(|| RuntimeError::invalid_input(format!("Invalid doc snapshot timestamp: {timestamp_ms}")))?;
|
||||
let pool = self.pool().await?;
|
||||
@@ -54,6 +90,7 @@ impl BackendRuntime {
|
||||
.map_err(|err| RuntimeError::database("DocStorage begin snapshot transaction failed", err))?;
|
||||
super::domain_command::lock_workspace_storage_shared(&mut transaction, &workspace_id).await?;
|
||||
super::domain_command::lock_workspace_doc_update(&mut transaction, &workspace_id, &doc_id).await?;
|
||||
super::ensure_doc_not_deleted_in(&mut transaction, &workspace_id, &doc_id).await?;
|
||||
let row = sqlx::query(
|
||||
r#"
|
||||
INSERT INTO snapshots
|
||||
@@ -68,7 +105,7 @@ impl BackendRuntime {
|
||||
updated_by = $6
|
||||
WHERE snapshots.workspace_id = $1
|
||||
AND snapshots.guid = $2
|
||||
AND snapshots.updated_at <= $5
|
||||
AND (snapshots.updated_at < $5 OR (snapshots.updated_at = $5 AND snapshots.blob = $3))
|
||||
RETURNING updated_at
|
||||
"#,
|
||||
)
|
||||
@@ -116,13 +153,7 @@ impl BackendRuntime {
|
||||
.map_err(|err| RuntimeError::database("DocStorage begin history transaction failed", err))?;
|
||||
super::domain_command::lock_workspace_storage_shared(&mut transaction, &input.workspace_id).await?;
|
||||
super::domain_command::lock_workspace_doc_update(&mut transaction, &input.workspace_id, &input.doc_id).await?;
|
||||
super::domain_command::invalidate_doc_blob_projection(
|
||||
&mut transaction,
|
||||
&input.workspace_id,
|
||||
&input.doc_id,
|
||||
self.embedding_schema_ready()?,
|
||||
)
|
||||
.await?;
|
||||
super::ensure_doc_not_deleted_in(&mut transaction, &input.workspace_id, &input.doc_id).await?;
|
||||
let should_create = match latest_history_timestamp(&mut transaction, &input.workspace_id, &input.doc_id).await? {
|
||||
None => true,
|
||||
Some(last_timestamp) if last_timestamp == timestamp => false,
|
||||
@@ -192,16 +223,75 @@ mod tests {
|
||||
timestamp,
|
||||
None
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
let empty_id = "empty-snapshot".to_string();
|
||||
assert!(
|
||||
runtime
|
||||
.upsert_doc_snapshot(
|
||||
workspace_id.clone(),
|
||||
empty_id.clone(),
|
||||
vec![0, 0].into(),
|
||||
timestamp,
|
||||
None
|
||||
)
|
||||
.await?
|
||||
);
|
||||
assert!(
|
||||
!runtime
|
||||
.upsert_doc_snapshot(
|
||||
workspace_id.clone(),
|
||||
empty_id.clone(),
|
||||
blob.clone().into(),
|
||||
timestamp,
|
||||
None
|
||||
)
|
||||
.await?
|
||||
);
|
||||
let empty: Vec<u8> = sqlx::query_scalar("SELECT blob FROM snapshots WHERE workspace_id=$1 AND guid=$2")
|
||||
.bind(&workspace_id)
|
||||
.bind(&empty_id)
|
||||
.fetch_one(&pool)
|
||||
.await?;
|
||||
assert_eq!(empty, [0, 0]);
|
||||
assert!(
|
||||
runtime
|
||||
.upsert_doc_snapshot(
|
||||
workspace_id.clone(),
|
||||
empty_id.clone(),
|
||||
vec![0, 0].into(),
|
||||
timestamp,
|
||||
None
|
||||
)
|
||||
.await?
|
||||
);
|
||||
assert!(
|
||||
runtime
|
||||
.upsert_doc_snapshot(workspace_id.clone(), empty_id, blob.clone().into(), timestamp + 1, None)
|
||||
.await?
|
||||
);
|
||||
let doc_id = "snapshot-doc".to_string();
|
||||
assert!(
|
||||
runtime
|
||||
.upsert_doc_snapshot(
|
||||
workspace_id.clone(),
|
||||
doc_id.clone(),
|
||||
blob.clone().into(),
|
||||
timestamp,
|
||||
None
|
||||
)
|
||||
.await?
|
||||
);
|
||||
for delta in [-1, 0, 1] {
|
||||
sqlx::query(
|
||||
"INSERT INTO doc_blob_ref_projections(workspace_id,doc_id,source_revision,parser_version,status,indexed_at) \
|
||||
VALUES($1,$1,to_timestamp($2::bigint::double precision/1000),1,'fresh',now()) ON \
|
||||
VALUES($1,$3,to_timestamp($2::bigint::double precision/1000),1,'fresh',now()) ON \
|
||||
CONFLICT(workspace_id,doc_id) DO UPDATE SET status='fresh',indexed_at=now()",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(timestamp)
|
||||
.bind(&doc_id)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
@@ -214,7 +304,7 @@ mod tests {
|
||||
let accepted = runtime
|
||||
.upsert_doc_snapshot(
|
||||
workspace_id.clone(),
|
||||
workspace_id.clone(),
|
||||
doc_id.clone(),
|
||||
blob.clone().into(),
|
||||
timestamp + delta,
|
||||
None,
|
||||
@@ -222,8 +312,9 @@ mod tests {
|
||||
.await?;
|
||||
assert_eq!(accepted, delta >= 0);
|
||||
let status: String =
|
||||
sqlx::query_scalar("SELECT status FROM doc_blob_ref_projections WHERE workspace_id=$1 AND doc_id=$1")
|
||||
sqlx::query_scalar("SELECT status FROM doc_blob_ref_projections WHERE workspace_id=$1 AND doc_id=$2")
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.fetch_one(&pool)
|
||||
.await?;
|
||||
assert_eq!(status, if accepted { "pending" } else { "fresh" });
|
||||
@@ -231,7 +322,7 @@ mod tests {
|
||||
.bind(&workspace_id)
|
||||
.fetch_one(&pool)
|
||||
.await?;
|
||||
assert_eq!(checked_at.timestamp_millis(), if accepted { 0 } else { timestamp });
|
||||
assert_eq!(checked_at.timestamp_millis(), timestamp);
|
||||
}
|
||||
sqlx::query("DELETE FROM doc_blob_ref_projections WHERE workspace_id=$1")
|
||||
.bind(&workspace_id)
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use affine_core::access_control::{
|
||||
DomainCommand, ReservedDocumentAccessDecision, authorize_reserved_document, classify_reserved_document,
|
||||
};
|
||||
use affine_core::access_control::{DomainCommand, classify_reserved_document};
|
||||
use chrono::Duration;
|
||||
use napi::{Result, bindgen_prelude::Buffer};
|
||||
use sqlx::PgPool;
|
||||
use sqlx::{PgPool, Postgres, Transaction};
|
||||
use y_octo::Update;
|
||||
|
||||
use super::{
|
||||
BackendRuntime, SourceIdentity,
|
||||
BackendRuntime, RuntimeError, RuntimeResult, SourceIdentity, blocking,
|
||||
domain_command::{
|
||||
authorize_domain, invalidate_doc_blob_projection, lock_workspace_doc_update, lock_workspace_storage_shared,
|
||||
next_workspace_doc_update_timestamp, workspace_root_contains_active_doc,
|
||||
authorize_doc_creation_in, invalidate_doc_blob_projection, invalidate_workspace_inventory_in,
|
||||
lock_workspace_doc_update, lock_workspace_storage_shared, next_workspace_doc_update_timestamp,
|
||||
},
|
||||
ensure_doc_not_deleted_in, ensure_workspace_sync_protocol_in,
|
||||
invalidation::{InvalidationHintV1, InvalidationRuntime},
|
||||
napi_error,
|
||||
is_ordinary_workspace_doc, load_command_quota_in, napi_error,
|
||||
permission::PermissionAuthorizer,
|
||||
};
|
||||
|
||||
@@ -25,8 +25,15 @@ pub struct AppendWorkspaceDocUpdatesInputV1 {
|
||||
pub updates: Vec<Buffer>,
|
||||
pub actor_user_id: String,
|
||||
pub write_intent: WorkspaceDocWriteIntentV1,
|
||||
pub permission_doc_id: Option<String>,
|
||||
pub expected_permission_generation: Option<i64>,
|
||||
pub protocol_version: Option<u32>,
|
||||
}
|
||||
|
||||
#[napi_derive::napi(object)]
|
||||
#[derive(Debug)]
|
||||
pub struct WorkspaceDocWriteResultV1 {
|
||||
pub timestamp: i64,
|
||||
pub created: bool,
|
||||
}
|
||||
|
||||
#[napi_derive::napi(string_enum = "snake_case")]
|
||||
@@ -47,7 +54,10 @@ pub struct AppendWorkspaceDocUpdatesTrustedInputV1 {
|
||||
#[napi_derive::napi]
|
||||
impl BackendRuntime {
|
||||
#[napi]
|
||||
pub async fn append_workspace_doc_updates_v1(&self, input: AppendWorkspaceDocUpdatesInputV1) -> Result<i64> {
|
||||
pub async fn append_workspace_doc_updates_v1(
|
||||
&self,
|
||||
input: AppendWorkspaceDocUpdatesInputV1,
|
||||
) -> Result<WorkspaceDocWriteResultV1> {
|
||||
let pool = self.pool().await?;
|
||||
let invalidation = self.invalidation.lock().await.as_ref().cloned();
|
||||
let config = self.config().map_err(super::to_napi_error)?;
|
||||
@@ -89,103 +99,109 @@ async fn append_authorized_updates(
|
||||
telemetry: super::permission::PermissionTelemetry,
|
||||
embedding_schema_ready: bool,
|
||||
input: AppendWorkspaceDocUpdatesInputV1,
|
||||
) -> Result<i64> {
|
||||
) -> Result<WorkspaceDocWriteResultV1> {
|
||||
if input.updates.is_empty() {
|
||||
return Ok(0);
|
||||
return Ok(WorkspaceDocWriteResultV1 {
|
||||
timestamp: 0,
|
||||
created: false,
|
||||
});
|
||||
}
|
||||
validate_doc_updates(&input.updates, input.doc_id == input.workspace_id).await?;
|
||||
let mut transaction = pool
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|error| napi_error(format!("begin workspace doc update: {error}")))?;
|
||||
let permission_doc_id = input.permission_doc_id.as_deref().unwrap_or(&input.doc_id);
|
||||
lock_workspace_storage_shared(&mut transaction, &input.workspace_id)
|
||||
.await
|
||||
.map_err(super::to_napi_error)?;
|
||||
let mut locked_doc_ids = [&*input.doc_id, permission_doc_id];
|
||||
locked_doc_ids.sort_unstable();
|
||||
lock_workspace_doc_update(&mut transaction, &input.workspace_id, locked_doc_ids[0])
|
||||
.await
|
||||
.map_err(super::to_napi_error)?;
|
||||
if locked_doc_ids[1] != locked_doc_ids[0] {
|
||||
lock_workspace_doc_update(&mut transaction, &input.workspace_id, locked_doc_ids[1])
|
||||
.await
|
||||
.map_err(super::to_napi_error)?;
|
||||
lock_workspace_storage_shared(&mut transaction, &input.workspace_id).await?;
|
||||
ensure_workspace_sync_protocol_in(&mut transaction, &input.workspace_id, input.protocol_version).await?;
|
||||
lock_workspace_doc_update(&mut transaction, &input.workspace_id, &input.doc_id).await?;
|
||||
let classification = classify_reserved_document(&input.workspace_id, &input.doc_id);
|
||||
let reserved = input.doc_id == input.workspace_id || classification.is_valid_reserved();
|
||||
let source_exists: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT 1 FROM snapshots WHERE workspace_id=$1 AND guid=$2) OR EXISTS(SELECT 1 FROM updates WHERE \
|
||||
workspace_id=$1 AND guid=$2)",
|
||||
)
|
||||
.bind(&input.workspace_id)
|
||||
.bind(&input.doc_id)
|
||||
.fetch_one(&mut *transaction)
|
||||
.await
|
||||
.map_err(|error| napi_error(format!("load workspace document source: {error}")))?;
|
||||
if !source_exists && !reserved && input.write_intent == WorkspaceDocWriteIntentV1::UpdateDoc {
|
||||
return Err(napi_error("doc_not_found"));
|
||||
}
|
||||
let authorizer = PermissionAuthorizer::with_telemetry(pool.clone(), deployment, telemetry);
|
||||
let classification = classify_reserved_document(&input.workspace_id, &input.doc_id);
|
||||
if authorize_reserved_document(&input.actor_user_id, classification) == ReservedDocumentAccessDecision::Denied {
|
||||
return Err(napi_error("domain_permission_denied"));
|
||||
}
|
||||
let reserved = input.doc_id == permission_doc_id && classification.is_valid_reserved();
|
||||
let write_intent = if reserved {
|
||||
WorkspaceDocWriteIntentV1::UpdateDoc
|
||||
let creating = !source_exists && !reserved;
|
||||
let assign_owner = if creating {
|
||||
authorize_doc_creation_in(
|
||||
&authorizer,
|
||||
&mut transaction,
|
||||
&input.actor_user_id,
|
||||
&input.workspace_id,
|
||||
&input.doc_id,
|
||||
input.expected_permission_generation,
|
||||
)
|
||||
.await?
|
||||
} else {
|
||||
input.write_intent
|
||||
};
|
||||
match write_intent {
|
||||
WorkspaceDocWriteIntentV1::UpdateDoc => {
|
||||
let command = DomainCommand::UpdateDoc {
|
||||
doc_id: permission_doc_id.to_string(),
|
||||
};
|
||||
authorize_domain(
|
||||
&authorizer,
|
||||
let quota = load_command_quota_in(&mut transaction, deployment, &input.workspace_id, false).await?;
|
||||
lock_permission_generation(
|
||||
&mut transaction,
|
||||
&input.workspace_id,
|
||||
input.expected_permission_generation,
|
||||
)
|
||||
.await?;
|
||||
let command = if input.doc_id == input.workspace_id {
|
||||
DomainCommand::AppendRootUpdate {
|
||||
doc_id: input.doc_id.clone(),
|
||||
}
|
||||
} else {
|
||||
DomainCommand::UpdateDoc {
|
||||
doc_id: input.doc_id.clone(),
|
||||
}
|
||||
};
|
||||
authorizer
|
||||
.authorize_command_in(
|
||||
&mut transaction,
|
||||
&input.actor_user_id,
|
||||
&input.workspace_id,
|
||||
Some(permission_doc_id),
|
||||
Some(&input.doc_id),
|
||||
&command,
|
||||
quota.as_ref().map(|quota| quota.facts()),
|
||||
)
|
||||
.await
|
||||
.map_err(super::to_napi_error)?;
|
||||
let source_exists = sqlx::query_scalar::<_, bool>(
|
||||
"SELECT EXISTS(SELECT 1 FROM snapshots WHERE workspace_id=$1 AND guid=$2) OR EXISTS(SELECT 1 FROM updates \
|
||||
WHERE workspace_id=$1 AND guid=$2)",
|
||||
)
|
||||
.bind(&input.workspace_id)
|
||||
.bind(permission_doc_id)
|
||||
.fetch_one(&mut *transaction)
|
||||
.await
|
||||
.map_err(|error| napi_error(format!("load workspace document source: {error}")))?;
|
||||
if !source_exists && !reserved {
|
||||
return Err(napi_error("doc_not_found"));
|
||||
}
|
||||
}
|
||||
WorkspaceDocWriteIntentV1::CreateDoc => {
|
||||
authorize_domain(
|
||||
&authorizer,
|
||||
&mut transaction,
|
||||
&input.actor_user_id,
|
||||
&input.workspace_id,
|
||||
None,
|
||||
&DomainCommand::CreateDoc,
|
||||
)
|
||||
.await
|
||||
.map_err(super::to_napi_error)?;
|
||||
if input.doc_id != input.workspace_id
|
||||
&& !workspace_root_contains_active_doc(&mut transaction, &input.workspace_id, &input.doc_id)
|
||||
.await
|
||||
.map_err(super::to_napi_error)?
|
||||
{
|
||||
return Err(napi_error("doc_not_found"));
|
||||
}
|
||||
}
|
||||
.await?;
|
||||
false
|
||||
};
|
||||
if assign_owner {
|
||||
sqlx::query(
|
||||
"INSERT INTO doc_grants(workspace_id,doc_id,principal_type,principal_id,role,granted_by) \
|
||||
VALUES($1,$2,'user',$3,'owner',$3)",
|
||||
)
|
||||
.bind(&input.workspace_id)
|
||||
.bind(&input.doc_id)
|
||||
.bind(&input.actor_user_id)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(|error| napi_error(format!("assign initial document owner: {error}")))?;
|
||||
}
|
||||
lock_permission_generation(
|
||||
let timestamp = append_updates_in(
|
||||
&mut transaction,
|
||||
embedding_schema_ready,
|
||||
&input.workspace_id,
|
||||
input.expected_permission_generation,
|
||||
&input.doc_id,
|
||||
input.updates,
|
||||
Some(&input.actor_user_id),
|
||||
)
|
||||
.await?;
|
||||
append_updates_in(
|
||||
transaction,
|
||||
invalidation,
|
||||
embedding_schema_ready,
|
||||
input.workspace_id,
|
||||
input.doc_id,
|
||||
input.updates,
|
||||
Some(input.actor_user_id),
|
||||
)
|
||||
.await
|
||||
if creating {
|
||||
invalidate_workspace_inventory_in(&mut transaction, &input.workspace_id).await?;
|
||||
}
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|error| napi_error(format!("commit workspace doc update: {error}")))?;
|
||||
publish_update(invalidation, input.workspace_id, input.doc_id, creating).await;
|
||||
Ok(WorkspaceDocWriteResultV1 {
|
||||
timestamp,
|
||||
created: creating,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) async fn append_updates(
|
||||
@@ -200,92 +216,138 @@ pub(super) async fn append_updates(
|
||||
if updates.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
let transaction = pool
|
||||
validate_doc_updates(&updates, workspace_id == doc_id).await?;
|
||||
let mut transaction = pool
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|error| napi_error(format!("begin workspace doc update: {error}")))?;
|
||||
append_updates_in(
|
||||
transaction,
|
||||
invalidation,
|
||||
embedding_schema_ready,
|
||||
workspace_id,
|
||||
doc_id,
|
||||
updates,
|
||||
editor_id,
|
||||
lock_workspace_storage_shared(&mut transaction, &workspace_id).await?;
|
||||
lock_workspace_doc_update(&mut transaction, &workspace_id, &doc_id).await?;
|
||||
ensure_doc_not_deleted_in(&mut transaction, &workspace_id, &doc_id).await?;
|
||||
let source_exists: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT 1 FROM snapshots WHERE workspace_id=$1 AND guid=$2) OR EXISTS(SELECT 1 FROM updates WHERE \
|
||||
workspace_id=$1 AND guid=$2)",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.fetch_one(&mut *transaction)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn append_updates_in(
|
||||
mut transaction: sqlx::Transaction<'_, sqlx::Postgres>,
|
||||
invalidation: Option<Arc<InvalidationRuntime>>,
|
||||
embedding_schema_ready: bool,
|
||||
workspace_id: String,
|
||||
doc_id: String,
|
||||
updates: Vec<Buffer>,
|
||||
editor_id: Option<String>,
|
||||
) -> Result<i64> {
|
||||
lock_workspace_storage_shared(&mut transaction, &workspace_id)
|
||||
.await
|
||||
.map_err(super::to_napi_error)?;
|
||||
lock_workspace_doc_update(&mut transaction, &workspace_id, &doc_id)
|
||||
.await
|
||||
.map_err(super::to_napi_error)?;
|
||||
let now = next_workspace_doc_update_timestamp(&mut transaction, &workspace_id, &doc_id)
|
||||
.await
|
||||
.map_err(super::to_napi_error)?;
|
||||
invalidate_doc_blob_projection(&mut transaction, &workspace_id, &doc_id, embedding_schema_ready)
|
||||
.await
|
||||
.map_err(super::to_napi_error)?;
|
||||
let mut timestamp = 0;
|
||||
for (index, update) in updates.into_iter().enumerate() {
|
||||
let created_at = now + Duration::milliseconds(index as i64);
|
||||
sqlx::query("INSERT INTO updates(workspace_id,guid,blob,created_at,created_by) VALUES($1,$2,$3,$4,$5)")
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.bind(update.to_vec())
|
||||
.bind(created_at)
|
||||
.bind(editor_id.as_deref())
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(|error| napi_error(format!("append workspace doc update: {error}")))?;
|
||||
timestamp = created_at.timestamp_millis();
|
||||
.map_err(|error| RuntimeError::database("load trusted document source", error))?;
|
||||
let created = !source_exists && is_ordinary_workspace_doc(&workspace_id, &doc_id);
|
||||
let timestamp = append_updates_in(
|
||||
&mut transaction,
|
||||
embedding_schema_ready,
|
||||
&workspace_id,
|
||||
&doc_id,
|
||||
updates,
|
||||
editor_id.as_deref(),
|
||||
)
|
||||
.await?;
|
||||
if created {
|
||||
invalidate_workspace_inventory_in(&mut transaction, &workspace_id).await?;
|
||||
}
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|error| napi_error(format!("commit workspace doc update: {error}")))?;
|
||||
publish_update(invalidation, workspace_id, doc_id, created).await;
|
||||
Ok(timestamp)
|
||||
}
|
||||
|
||||
pub(super) async fn append_updates_in(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
embedding_schema_ready: bool,
|
||||
workspace_id: &str,
|
||||
doc_id: &str,
|
||||
updates: Vec<Buffer>,
|
||||
editor_id: Option<&str>,
|
||||
) -> RuntimeResult<i64> {
|
||||
let now = next_workspace_doc_update_timestamp(transaction, workspace_id, doc_id).await?;
|
||||
invalidate_doc_blob_projection(transaction, workspace_id, doc_id, embedding_schema_ready).await?;
|
||||
let mut timestamp = 0;
|
||||
for (index, update) in updates.into_iter().enumerate() {
|
||||
let created_at = now + Duration::milliseconds(index as i64);
|
||||
sqlx::query("INSERT INTO updates(workspace_id,guid,blob,created_at,created_by) VALUES($1,$2,$3,$4,$5)")
|
||||
.bind(workspace_id)
|
||||
.bind(doc_id)
|
||||
.bind(update.to_vec())
|
||||
.bind(created_at)
|
||||
.bind(editor_id)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("append workspace doc update", error))?;
|
||||
timestamp = created_at.timestamp_millis();
|
||||
}
|
||||
Ok(timestamp)
|
||||
}
|
||||
|
||||
async fn publish_update(
|
||||
invalidation: Option<Arc<InvalidationRuntime>>,
|
||||
workspace_id: String,
|
||||
doc_id: String,
|
||||
inventory_changed: bool,
|
||||
) {
|
||||
if let Some(invalidation) = invalidation {
|
||||
if inventory_changed {
|
||||
invalidation
|
||||
.publish(InvalidationHintV1::WorkspaceInventoryChanged {
|
||||
workspace_id: workspace_id.clone(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
invalidation
|
||||
.publish(InvalidationHintV1::BlobSource {
|
||||
source: SourceIdentity::CurrentDoc { workspace_id, doc_id },
|
||||
})
|
||||
.await;
|
||||
}
|
||||
Ok(timestamp)
|
||||
}
|
||||
|
||||
pub(super) async fn lock_permission_generation(
|
||||
pub(in crate::runtime) async fn validate_doc_updates(updates: &[Buffer], root: bool) -> RuntimeResult<()> {
|
||||
const MAX_UPDATE_BYTES: usize = 32 * 1024 * 1024;
|
||||
if updates.iter().any(|update| update.len() > MAX_UPDATE_BYTES)
|
||||
|| (root && updates.iter().map(|update| update.len()).sum::<usize>() > MAX_UPDATE_BYTES)
|
||||
{
|
||||
return Err(RuntimeError::invalid_input("doc_update_too_large"));
|
||||
}
|
||||
let permit = super::try_validation_slot().map_err(|_| RuntimeError::invalid_state("doc_validation_unavailable"))?;
|
||||
let updates = updates.iter().map(|update| update.to_vec()).collect::<Vec<_>>();
|
||||
tokio::time::timeout(
|
||||
std::time::Duration::from_secs(1),
|
||||
blocking::spawn(permit, move || {
|
||||
updates.into_iter().try_for_each(|update| {
|
||||
Update::decode_v1(update)
|
||||
.map(|_| ())
|
||||
.map_err(|_| RuntimeError::invalid_input("doc_update_invalid"))
|
||||
})
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| RuntimeError::invalid_state("doc_validation_unavailable"))?
|
||||
.map_err(|_| RuntimeError::invalid_state("doc_validation_unavailable"))?
|
||||
}
|
||||
|
||||
pub(in crate::runtime) async fn lock_permission_generation(
|
||||
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||
workspace_id: &str,
|
||||
expected: Option<i64>,
|
||||
) -> Result<()> {
|
||||
) -> RuntimeResult<()> {
|
||||
sqlx::query(
|
||||
"INSERT INTO workspace_sync_permission_generations(workspace_id,generation) VALUES($1,0) ON CONFLICT DO NOTHING",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| napi_error(format!("initialize sync permission generation: {error}")))?;
|
||||
.map_err(|error| RuntimeError::database("initialize sync permission generation", error))?;
|
||||
let current = sqlx::query_scalar::<_, i64>(
|
||||
"SELECT generation FROM workspace_sync_permission_generations WHERE workspace_id=$1 FOR SHARE",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.fetch_one(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| napi_error(format!("lock sync permission generation: {error}")))?;
|
||||
.map_err(|error| RuntimeError::database("lock sync permission generation", error))?;
|
||||
if expected.is_some_and(|expected| current != expected) {
|
||||
return Err(napi_error("sync_permission_generation_changed"));
|
||||
return Err(RuntimeError::invalid_state("sync_permission_generation_changed"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -361,11 +423,30 @@ mod tests {
|
||||
invalidate_doc_blob_projection(&mut no_embedding, &workspace_id, &doc_id, false).await?;
|
||||
no_embedding.rollback().await?;
|
||||
|
||||
assert!(
|
||||
runtime
|
||||
.append_workspace_doc_updates_trusted_v1(AppendWorkspaceDocUpdatesTrustedInputV1 {
|
||||
workspace_id: workspace_id.clone(),
|
||||
doc_id: doc_id.clone(),
|
||||
updates: vec![Buffer::from(vec![0, 0]), Buffer::from(vec![0xff])],
|
||||
editor_id: None,
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>("SELECT count(*) FROM updates WHERE workspace_id=$1 AND guid=$2")
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.fetch_one(&pool)
|
||||
.await?,
|
||||
0
|
||||
);
|
||||
let first = runtime
|
||||
.append_workspace_doc_updates_trusted_v1(AppendWorkspaceDocUpdatesTrustedInputV1 {
|
||||
workspace_id: workspace_id.clone(),
|
||||
doc_id: doc_id.clone(),
|
||||
updates: vec![Buffer::from(vec![1]), Buffer::from(vec![2])],
|
||||
updates: vec![Buffer::from(vec![0, 0]), Buffer::from(vec![0, 0])],
|
||||
editor_id: None,
|
||||
})
|
||||
.await
|
||||
@@ -374,7 +455,7 @@ mod tests {
|
||||
.append_workspace_doc_updates_trusted_v1(AppendWorkspaceDocUpdatesTrustedInputV1 {
|
||||
workspace_id: workspace_id.clone(),
|
||||
doc_id: doc_id.clone(),
|
||||
updates: vec![Buffer::from(vec![3])],
|
||||
updates: vec![Buffer::from(vec![0, 0])],
|
||||
editor_id: None,
|
||||
})
|
||||
.await
|
||||
@@ -391,9 +472,9 @@ mod tests {
|
||||
assert_eq!(rows.len(), 3);
|
||||
assert!(rows.windows(2).all(|rows| rows[0] < rows[1]));
|
||||
assert!(second > first);
|
||||
assert_eq!(target.0.lock().await.len(), 2);
|
||||
assert_eq!(target.0.lock().await.len(), 3);
|
||||
if redis_url.is_some() {
|
||||
assert_eq!(invalidation.health().published, 2);
|
||||
assert_eq!(invalidation.health().published, 3);
|
||||
}
|
||||
|
||||
let generation = runtime
|
||||
@@ -420,10 +501,11 @@ mod tests {
|
||||
AppendWorkspaceDocUpdatesInputV1 {
|
||||
workspace_id: racing_workspace_id,
|
||||
doc_id: racing_doc_id,
|
||||
updates: vec![Buffer::from(vec![4])],
|
||||
updates: vec![Buffer::from(vec![0, 0])],
|
||||
actor_user_id: racing_user_id,
|
||||
write_intent: WorkspaceDocWriteIntentV1::UpdateDoc,
|
||||
permission_doc_id: None,
|
||||
|
||||
protocol_version: None,
|
||||
expected_permission_generation: Some(generation),
|
||||
},
|
||||
)
|
||||
@@ -440,10 +522,11 @@ mod tests {
|
||||
.append_workspace_doc_updates_v1(AppendWorkspaceDocUpdatesInputV1 {
|
||||
workspace_id: workspace_id.clone(),
|
||||
doc_id: doc_id.clone(),
|
||||
updates: vec![Buffer::from(vec![5])],
|
||||
updates: vec![Buffer::from(vec![0, 0])],
|
||||
actor_user_id: user_id.clone(),
|
||||
write_intent: WorkspaceDocWriteIntentV1::UpdateDoc,
|
||||
permission_doc_id: None,
|
||||
|
||||
protocol_version: None,
|
||||
expected_permission_generation: None,
|
||||
})
|
||||
.await;
|
||||
@@ -537,10 +620,11 @@ mod tests {
|
||||
AppendWorkspaceDocUpdatesInputV1 {
|
||||
workspace_id: racing_workspace_id,
|
||||
doc_id: racing_doc_id,
|
||||
updates: vec![Buffer::from(vec![6])],
|
||||
updates: vec![Buffer::from(vec![0, 0])],
|
||||
actor_user_id: racing_user_id,
|
||||
write_intent: WorkspaceDocWriteIntentV1::UpdateDoc,
|
||||
permission_doc_id: None,
|
||||
|
||||
protocol_version: None,
|
||||
expected_permission_generation: Some(generation),
|
||||
},
|
||||
)
|
||||
@@ -567,7 +651,8 @@ mod tests {
|
||||
updates: vec![Buffer::from(vec![0, 0])],
|
||||
actor_user_id: user_id.clone(),
|
||||
write_intent: WorkspaceDocWriteIntentV1::CreateDoc,
|
||||
permission_doc_id: None,
|
||||
|
||||
protocol_version: None,
|
||||
expected_permission_generation: None,
|
||||
})
|
||||
.await;
|
||||
@@ -575,39 +660,349 @@ mod tests {
|
||||
}
|
||||
|
||||
let creating_doc_id = format!("doc-writer-creating-{suffix}");
|
||||
let root = affine_doc_loader::add_doc_to_root_doc(vec![0, 0], &creating_doc_id, None)?;
|
||||
sqlx::query("INSERT INTO snapshots(workspace_id,guid,blob,size,updated_at) VALUES($1,$1,$2,$3,now())")
|
||||
let input = |doc_id: &str, intent| AppendWorkspaceDocUpdatesInputV1 {
|
||||
workspace_id: workspace_id.clone(),
|
||||
doc_id: doc_id.into(),
|
||||
updates: vec![Buffer::from(vec![0, 0])],
|
||||
actor_user_id: user_id.clone(),
|
||||
write_intent: intent,
|
||||
|
||||
protocol_version: Some(2),
|
||||
expected_permission_generation: None,
|
||||
};
|
||||
let (first, retry) = tokio::join!(
|
||||
runtime.append_workspace_doc_updates_v1(input(&creating_doc_id, WorkspaceDocWriteIntentV1::CreateDoc)),
|
||||
runtime.append_workspace_doc_updates_v1(input(&creating_doc_id, WorkspaceDocWriteIntentV1::CreateDoc))
|
||||
);
|
||||
let first = first?;
|
||||
let retry = retry?;
|
||||
assert_ne!(first.created, retry.created);
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>(
|
||||
"SELECT count(*) FROM doc_grants WHERE workspace_id=$1 AND doc_id=$2 AND principal_id=$3 AND role='owner'"
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&root)
|
||||
.bind(root.len() as i64)
|
||||
.bind(&creating_doc_id)
|
||||
.bind(&user_id)
|
||||
.fetch_one(&pool)
|
||||
.await?,
|
||||
1
|
||||
);
|
||||
let mut shared = pool.begin().await?;
|
||||
load_command_quota_in(&mut shared, crate::runtime::Deployment::Cloud, &workspace_id, false).await?;
|
||||
lock_permission_generation(&mut shared, &workspace_id, None).await?;
|
||||
let concurrent = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(2),
|
||||
runtime.append_workspace_doc_updates_v1(input(&creating_doc_id, WorkspaceDocWriteIntentV1::UpdateDoc)),
|
||||
)
|
||||
.await;
|
||||
shared.rollback().await?;
|
||||
assert!(
|
||||
concurrent?.is_ok(),
|
||||
"unrelated shared quota readers must permit document updates"
|
||||
);
|
||||
let failed_id = format!("failed-{suffix}");
|
||||
sqlx::query(
|
||||
"CREATE OR REPLACE FUNCTION rfc21_test_fail_append() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.guid \
|
||||
LIKE 'failed-%' THEN RAISE EXCEPTION 'injected append failure'; END IF; RETURN NEW; END $$",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"CREATE TRIGGER rfc21_test_fail_append BEFORE INSERT ON updates FOR EACH ROW EXECUTE FUNCTION \
|
||||
rfc21_test_fail_append()",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
let failed = runtime
|
||||
.append_workspace_doc_updates_v1(input(&failed_id, WorkspaceDocWriteIntentV1::CreateDoc))
|
||||
.await;
|
||||
sqlx::query("DROP TRIGGER rfc21_test_fail_append ON updates")
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
runtime
|
||||
.execute_domain_command_v1(serde_json::json!({
|
||||
"command": "apply_doc_lifecycle",
|
||||
"actorUserId": user_id.clone(),
|
||||
"workspaceId": workspace_id.clone(),
|
||||
"docId": creating_doc_id.clone(),
|
||||
"lifecycle": "delete"
|
||||
}))
|
||||
.await
|
||||
.map_err(|error| anyhow::anyhow!(error.to_string()))?;
|
||||
let create_after_delete = runtime
|
||||
.append_workspace_doc_updates_v1(AppendWorkspaceDocUpdatesInputV1 {
|
||||
workspace_id: workspace_id.clone(),
|
||||
doc_id: creating_doc_id,
|
||||
updates: vec![Buffer::from(vec![7])],
|
||||
actor_user_id: user_id.clone(),
|
||||
write_intent: WorkspaceDocWriteIntentV1::CreateDoc,
|
||||
permission_doc_id: None,
|
||||
expected_permission_generation: None,
|
||||
})
|
||||
.await;
|
||||
assert!(
|
||||
create_after_delete.is_err(),
|
||||
"document creation must recheck root membership after a committed delete"
|
||||
sqlx::query("DROP FUNCTION rfc21_test_fail_append()")
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
assert!(failed.is_err());
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>("SELECT count(*) FROM doc_grants WHERE workspace_id=$1 AND doc_id=$2")
|
||||
.bind(&workspace_id)
|
||||
.bind(&failed_id)
|
||||
.fetch_one(&pool)
|
||||
.await?,
|
||||
0
|
||||
);
|
||||
|
||||
let bound_id = format!("bound-{suffix}");
|
||||
sqlx::query(
|
||||
"INSERT INTO doc_grants(workspace_id,doc_id,principal_type,principal_id,role) \
|
||||
VALUES($1,$2,'user','previous-owner','owner')",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&bound_id)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
assert!(
|
||||
runtime
|
||||
.append_workspace_doc_updates_v1(input(&bound_id, WorkspaceDocWriteIntentV1::CreateDoc))
|
||||
.await?
|
||||
.created
|
||||
);
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, String>(
|
||||
"SELECT principal_id FROM doc_grants WHERE workspace_id=$1 AND doc_id=$2 AND role='owner'"
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&bound_id)
|
||||
.fetch_one(&pool)
|
||||
.await?,
|
||||
"previous-owner"
|
||||
);
|
||||
|
||||
for lifecycle in ["trash", "restore", "trash", "delete"] {
|
||||
let output = runtime.execute_domain_command_v1(serde_json::json!({"command":"apply_doc_lifecycle","actorUserId":user_id,"workspaceId":workspace_id,"docId":creating_doc_id,"lifecycle":lifecycle})).await?;
|
||||
assert!(output.get("rootUpdate").is_none());
|
||||
assert!(output["timestamp"].is_i64());
|
||||
if lifecycle == "trash" {
|
||||
assert!(
|
||||
!runtime
|
||||
.append_workspace_doc_updates_v1(input(&creating_doc_id, WorkspaceDocWriteIntentV1::UpdateDoc))
|
||||
.await?
|
||||
.created
|
||||
);
|
||||
}
|
||||
}
|
||||
for intent in [
|
||||
WorkspaceDocWriteIntentV1::CreateDoc,
|
||||
WorkspaceDocWriteIntentV1::UpdateDoc,
|
||||
] {
|
||||
assert!(
|
||||
runtime
|
||||
.append_workspace_doc_updates_v1(input(&creating_doc_id, intent))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
runtime
|
||||
.append_workspace_doc_updates_trusted_v1(AppendWorkspaceDocUpdatesTrustedInputV1 {
|
||||
workspace_id: workspace_id.clone(),
|
||||
doc_id: creating_doc_id.clone(),
|
||||
updates: vec![Buffer::from(vec![0, 0])],
|
||||
editor_id: Some(user_id.clone())
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
runtime
|
||||
.upsert_doc_snapshot(
|
||||
workspace_id.clone(),
|
||||
creating_doc_id.clone(),
|
||||
Buffer::from(vec![0, 0, 0]),
|
||||
chrono::Utc::now().timestamp_millis(),
|
||||
None
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(runtime.execute_domain_command_v1(serde_json::json!({"command":"apply_doc_lifecycle","actorUserId":user_id,"workspaceId":workspace_id,"docId":creating_doc_id,"lifecycle":"restore"})).await.is_err());
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, String>(
|
||||
"SELECT lifecycle_state::text FROM workspace_pages WHERE workspace_id=$1 AND page_id=$2"
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&creating_doc_id)
|
||||
.fetch_one(&pool)
|
||||
.await?,
|
||||
"deleted"
|
||||
);
|
||||
|
||||
use super::super::workspace_state::{WorkspaceLegacyDocV1, WorkspaceLifecycleMigrationInputV1};
|
||||
sqlx::query(
|
||||
"DELETE FROM storage_reconciliation_checkpoints WHERE kind='workspace_doc_lifecycle_activation' AND \
|
||||
scope='global'",
|
||||
)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
assert!(
|
||||
runtime
|
||||
.list_workspace_lifecycle_migration_candidates_v1()
|
||||
.await?
|
||||
.is_empty()
|
||||
);
|
||||
assert!(
|
||||
runtime
|
||||
.prepare_workspace_lifecycle_migration_v1(workspace_id.clone())
|
||||
.await
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
.contains("workspace_lifecycle_not_active")
|
||||
);
|
||||
let inactive_id = format!("inactive-{suffix}");
|
||||
assert!(
|
||||
runtime
|
||||
.migrate_workspace_lifecycle_v1(WorkspaceLifecycleMigrationInputV1 {
|
||||
workspace_id: workspace_id.clone(),
|
||||
source_revision: String::new(),
|
||||
root_status: "absent".into(),
|
||||
docs: vec![WorkspaceLegacyDocV1 {
|
||||
doc_id: inactive_id.clone(),
|
||||
trashed: true
|
||||
}],
|
||||
})
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("workspace_lifecycle_not_active")
|
||||
);
|
||||
let changed: i64 = sqlx::query_scalar(
|
||||
"SELECT (SELECT count(*) FROM storage_reconciliation_checkpoints WHERE kind IN \
|
||||
('workspace_doc_lifecycle_activation','workspace_doc_lifecycle') AND (scope='global' OR scope=$1))+(SELECT \
|
||||
count(*) FROM updates WHERE workspace_id=$1 AND guid=$2)+(SELECT count(*) FROM workspace_pages WHERE \
|
||||
workspace_id=$1 AND page_id=$2)",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&inactive_id)
|
||||
.fetch_one(&pool)
|
||||
.await?;
|
||||
assert_eq!(changed, 0);
|
||||
assert!(runtime.activate_workspace_lifecycle_v1().await?);
|
||||
assert!(!runtime.activate_workspace_lifecycle_v1().await?);
|
||||
|
||||
let root_source = y_octo::Doc::with_client(7);
|
||||
root_source.get_or_create_text("text")?.insert(0, "ab")?;
|
||||
let partial = root_source.encode_state_as_update_v1(&y_octo::StateVector::from([(7, 1)]))?;
|
||||
let stale = runtime
|
||||
.prepare_workspace_lifecycle_migration_v1(workspace_id.clone())
|
||||
.await?;
|
||||
let mut root_input = input(&workspace_id, WorkspaceDocWriteIntentV1::UpdateDoc);
|
||||
root_input.updates = vec![Buffer::from(partial.clone())];
|
||||
runtime.append_workspace_doc_updates_v1(root_input).await?;
|
||||
let root = runtime
|
||||
.get_current_workspace_doc_v1(workspace_id.clone(), workspace_id.clone())
|
||||
.await?
|
||||
.unwrap();
|
||||
assert_eq!(root.bin.as_ref(), partial.as_slice());
|
||||
assert!(
|
||||
!runtime
|
||||
.migrate_workspace_lifecycle_v1(WorkspaceLifecycleMigrationInputV1 {
|
||||
workspace_id: workspace_id.clone(),
|
||||
source_revision: stale.revision,
|
||||
root_status: stale.root_status,
|
||||
docs: vec![]
|
||||
})
|
||||
.await?
|
||||
);
|
||||
let source = runtime
|
||||
.prepare_workspace_lifecycle_migration_v1(workspace_id.clone())
|
||||
.await?;
|
||||
let legacy_id = format!("legacy-{suffix}");
|
||||
sqlx::query(
|
||||
"INSERT INTO workspace_pages(workspace_id,page_id,lifecycle_state,lifecycle_changed_at) VALUES($1,$2,NULL,now())",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&bound_id)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
let migration_input = || WorkspaceLifecycleMigrationInputV1 {
|
||||
workspace_id: workspace_id.clone(),
|
||||
source_revision: source.revision.clone(),
|
||||
root_status: source.root_status.clone(),
|
||||
docs: vec![
|
||||
WorkspaceLegacyDocV1 {
|
||||
doc_id: legacy_id.clone(),
|
||||
trashed: true,
|
||||
},
|
||||
WorkspaceLegacyDocV1 {
|
||||
doc_id: bound_id.clone(),
|
||||
trashed: true,
|
||||
},
|
||||
WorkspaceLegacyDocV1 {
|
||||
doc_id: creating_doc_id.clone(),
|
||||
trashed: false,
|
||||
},
|
||||
],
|
||||
};
|
||||
let (foreground, background) = tokio::join!(
|
||||
runtime.migrate_workspace_lifecycle_v1(migration_input()),
|
||||
runtime.migrate_workspace_lifecycle_v1(migration_input())
|
||||
);
|
||||
assert!(foreground?);
|
||||
assert!(background?);
|
||||
let seeded: i64 = sqlx::query_scalar("SELECT count(*) FROM updates WHERE workspace_id=$1 AND guid=$2")
|
||||
.bind(&workspace_id)
|
||||
.bind(&legacy_id)
|
||||
.fetch_one(&pool)
|
||||
.await?;
|
||||
assert_eq!(seeded, 1);
|
||||
assert!(
|
||||
runtime
|
||||
.prepare_workspace_lifecycle_migration_v1(workspace_id.clone())
|
||||
.await?
|
||||
.completed
|
||||
);
|
||||
let second_workspace = format!("second-{suffix}");
|
||||
sqlx::query("INSERT INTO workspaces(id) VALUES($1)")
|
||||
.bind(&second_workspace)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
assert!(
|
||||
runtime
|
||||
.list_workspace_lifecycle_migration_candidates_v1()
|
||||
.await?
|
||||
.contains(&second_workspace)
|
||||
);
|
||||
let second = runtime
|
||||
.prepare_workspace_lifecycle_migration_v1(second_workspace.clone())
|
||||
.await?;
|
||||
assert!(
|
||||
runtime
|
||||
.migrate_workspace_lifecycle_v1(WorkspaceLifecycleMigrationInputV1 {
|
||||
workspace_id: second_workspace.clone(),
|
||||
source_revision: second.revision,
|
||||
root_status: second.root_status,
|
||||
docs: vec![]
|
||||
})
|
||||
.await?
|
||||
);
|
||||
assert!(
|
||||
runtime
|
||||
.prepare_workspace_lifecycle_migration_v1(second_workspace.clone())
|
||||
.await?
|
||||
.completed
|
||||
);
|
||||
sqlx::query("DELETE FROM workspaces WHERE id=$1")
|
||||
.bind(&second_workspace)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
let state = runtime
|
||||
.get_workspace_state_v1(workspace_id.clone(), user_id.clone())
|
||||
.await?;
|
||||
assert!(state["clocks"].get(&workspace_id).is_some());
|
||||
let docs = state["docs"].as_array().unwrap();
|
||||
assert!(
|
||||
docs
|
||||
.iter()
|
||||
.any(|doc| doc["docId"] == legacy_id && doc["lifecycle"] == "trashed")
|
||||
);
|
||||
assert!(
|
||||
docs
|
||||
.iter()
|
||||
.any(|doc| doc["docId"] == bound_id && doc["lifecycle"].is_null())
|
||||
);
|
||||
assert!(!docs.iter().any(|doc| doc["docId"] == creating_doc_id));
|
||||
let mut old = input(&bound_id, WorkspaceDocWriteIntentV1::UpdateDoc);
|
||||
old.protocol_version = None;
|
||||
assert!(
|
||||
runtime
|
||||
.append_workspace_doc_updates_v1(old)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("sync_protocol_upgrade_required")
|
||||
);
|
||||
sqlx::query("DELETE FROM workspaces WHERE id=$1")
|
||||
.bind(&workspace_id)
|
||||
.execute(&pool)
|
||||
|
||||
@@ -18,46 +18,44 @@ pub(in crate::runtime::backend_runtime) struct DomainCommandOutcome {
|
||||
|
||||
impl DomainCommandInputV1 {
|
||||
fn invalidations(&self) -> Vec<InvalidationHintV1> {
|
||||
if let Self::RevokeWorkspaceMember { workspace_id, .. } | Self::LeaveWorkspace { workspace_id, .. } = self {
|
||||
return vec![InvalidationHintV1::QuotaSeatUsage {
|
||||
workspace_id: workspace_id.clone(),
|
||||
}];
|
||||
}
|
||||
let source = match self {
|
||||
match self {
|
||||
Self::ApplyDocLifecycle {
|
||||
workspace_id, doc_id, ..
|
||||
} => {
|
||||
return vec![
|
||||
InvalidationHintV1::BlobSource {
|
||||
source: SourceIdentity::CurrentDoc {
|
||||
workspace_id: workspace_id.clone(),
|
||||
doc_id: workspace_id.clone(),
|
||||
},
|
||||
} => vec![
|
||||
InvalidationHintV1::WorkspaceInventoryChanged {
|
||||
workspace_id: workspace_id.clone(),
|
||||
},
|
||||
InvalidationHintV1::BlobSource {
|
||||
source: SourceIdentity::CurrentDoc {
|
||||
workspace_id: workspace_id.clone(),
|
||||
doc_id: doc_id.clone(),
|
||||
},
|
||||
InvalidationHintV1::BlobSource {
|
||||
source: SourceIdentity::CurrentDoc {
|
||||
workspace_id: workspace_id.clone(),
|
||||
doc_id: doc_id.clone(),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
Self::AppendRootUpdate { workspace_id, .. } => Some(SourceIdentity::CurrentDoc {
|
||||
},
|
||||
],
|
||||
Self::AppendRootUpdate { workspace_id, .. } => vec![InvalidationHintV1::BlobSource {
|
||||
source: SourceIdentity::CurrentDoc {
|
||||
workspace_id: workspace_id.clone(),
|
||||
doc_id: workspace_id.clone(),
|
||||
},
|
||||
}],
|
||||
Self::RevokeWorkspaceMember { workspace_id, .. } | Self::LeaveWorkspace { workspace_id, .. } => vec![
|
||||
InvalidationHintV1::QuotaSeatUsage {
|
||||
workspace_id: workspace_id.clone(),
|
||||
},
|
||||
InvalidationHintV1::WorkspaceInventoryChanged {
|
||||
workspace_id: workspace_id.clone(),
|
||||
},
|
||||
],
|
||||
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 {
|
||||
workspace_id: workspace_id.clone(),
|
||||
doc_id: workspace_id.clone(),
|
||||
}),
|
||||
Self::RecoverDoc {
|
||||
workspace_id, doc_id, ..
|
||||
} => Some(SourceIdentity::CurrentDoc {
|
||||
workspace_id: workspace_id.clone(),
|
||||
doc_id: doc_id.clone(),
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
source
|
||||
.map(|source| InvalidationHintV1::BlobSource { source })
|
||||
.into_iter()
|
||||
.collect()
|
||||
}],
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -238,7 +236,6 @@ pub(in crate::runtime::backend_runtime) async fn execute(
|
||||
workspace_id,
|
||||
doc_id,
|
||||
timestamp,
|
||||
embedding_schema_ready,
|
||||
)
|
||||
.await?
|
||||
}
|
||||
@@ -405,28 +402,37 @@ mod tests {
|
||||
let cases = [
|
||||
(
|
||||
serde_json::json!({"command":"transition_workspace_role","actorUserId":"actor","workspaceId":"workspace","targetUserId":"target","newRole":"owner"}),
|
||||
Vec::new(),
|
||||
vec![InvalidationHintV1::WorkspaceInventoryChanged {
|
||||
workspace_id: "workspace".into(),
|
||||
}],
|
||||
),
|
||||
(
|
||||
serde_json::json!({"command":"revoke_workspace_member","actorUserId":"actor","workspaceId":"workspace","targetUserId":"target"}),
|
||||
vec![InvalidationHintV1::QuotaSeatUsage {
|
||||
workspace_id: "workspace".to_string(),
|
||||
}],
|
||||
vec![
|
||||
InvalidationHintV1::QuotaSeatUsage {
|
||||
workspace_id: "workspace".to_string(),
|
||||
},
|
||||
InvalidationHintV1::WorkspaceInventoryChanged {
|
||||
workspace_id: "workspace".into(),
|
||||
},
|
||||
],
|
||||
),
|
||||
(
|
||||
serde_json::json!({"command":"leave_workspace","actorUserId":"actor","workspaceId":"workspace"}),
|
||||
vec![InvalidationHintV1::QuotaSeatUsage {
|
||||
workspace_id: "workspace".to_string(),
|
||||
}],
|
||||
vec![
|
||||
InvalidationHintV1::QuotaSeatUsage {
|
||||
workspace_id: "workspace".to_string(),
|
||||
},
|
||||
InvalidationHintV1::WorkspaceInventoryChanged {
|
||||
workspace_id: "workspace".into(),
|
||||
},
|
||||
],
|
||||
),
|
||||
(
|
||||
serde_json::json!({"command":"apply_doc_lifecycle","actorUserId":"actor","workspaceId":"workspace","docId":"doc","lifecycle":"delete"}),
|
||||
vec![
|
||||
InvalidationHintV1::BlobSource {
|
||||
source: SourceIdentity::CurrentDoc {
|
||||
workspace_id: "workspace".to_string(),
|
||||
doc_id: "workspace".to_string(),
|
||||
},
|
||||
InvalidationHintV1::WorkspaceInventoryChanged {
|
||||
workspace_id: "workspace".into(),
|
||||
},
|
||||
InvalidationHintV1::BlobSource {
|
||||
source: SourceIdentity::CurrentDoc {
|
||||
@@ -447,12 +453,7 @@ mod tests {
|
||||
),
|
||||
(
|
||||
serde_json::json!({"command":"recover_doc","actorUserId":"actor","workspaceId":"workspace","docId":"doc","timestamp":timestamp}),
|
||||
vec![InvalidationHintV1::BlobSource {
|
||||
source: SourceIdentity::CurrentDoc {
|
||||
workspace_id: "workspace".to_string(),
|
||||
doc_id: "doc".to_string(),
|
||||
},
|
||||
}],
|
||||
Vec::new(),
|
||||
),
|
||||
];
|
||||
for (input, expected) in cases {
|
||||
@@ -559,7 +560,12 @@ mod tests {
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(outcome.value["public"], true);
|
||||
assert!(outcome.invalidations.is_empty());
|
||||
assert_eq!(
|
||||
outcome.invalidations,
|
||||
vec![InvalidationHintV1::WorkspaceInventoryChanged {
|
||||
workspace_id: workspace_id.clone()
|
||||
}]
|
||||
);
|
||||
assert!(
|
||||
sqlx::query_scalar::<_, bool>(
|
||||
"SELECT EXISTS(SELECT 1 FROM doc_access_policies WHERE workspace_id=$1 AND doc_id=$2 AND visibility='public') \
|
||||
|
||||
@@ -1,20 +1,12 @@
|
||||
use affine_core::access_control::DomainCommand;
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::{FromRow, Postgres, Row, Transaction};
|
||||
use sqlx::{Postgres, Row, Transaction};
|
||||
|
||||
use super::{authorize_domain, invalidate_doc_blob_projection, lock_workspace_doc_update};
|
||||
use crate::runtime::{
|
||||
RuntimeError, RuntimeResult,
|
||||
backend_runtime::permission::PermissionAuthorizer,
|
||||
storage_runtime::{CurrentDoc, CurrentDocUpdate, merge_current_doc},
|
||||
use super::{
|
||||
authorize_domain_after_storage_lock, load_current_doc_in, lock_workspace_doc_update, lock_workspace_storage_shared,
|
||||
};
|
||||
|
||||
#[derive(FromRow)]
|
||||
struct LockedSnapshot {
|
||||
blob: Vec<u8>,
|
||||
updated_at: DateTime<Utc>,
|
||||
}
|
||||
use crate::runtime::{RuntimeError, RuntimeResult, backend_runtime::permission::PermissionAuthorizer};
|
||||
|
||||
pub(super) async fn recover(
|
||||
authorizer: &PermissionAuthorizer,
|
||||
@@ -23,10 +15,14 @@ pub(super) async fn recover(
|
||||
workspace_id: String,
|
||||
doc_id: String,
|
||||
timestamp: DateTime<Utc>,
|
||||
embedding_schema_ready: bool,
|
||||
) -> RuntimeResult<Value> {
|
||||
if workspace_id == doc_id {
|
||||
return Err(RuntimeError::invalid_input("doc_is_workspace"));
|
||||
}
|
||||
lock_workspace_storage_shared(transaction, &workspace_id).await?;
|
||||
lock_workspace_doc_update(transaction, &workspace_id, &doc_id).await?;
|
||||
let command = DomainCommand::RecoverDoc { doc_id: doc_id.clone() };
|
||||
authorize_domain(
|
||||
authorize_domain_after_storage_lock(
|
||||
authorizer,
|
||||
transaction,
|
||||
&actor_user_id,
|
||||
@@ -36,34 +32,9 @@ pub(super) async fn recover(
|
||||
)
|
||||
.await?;
|
||||
|
||||
lock_workspace_doc_update(transaction, &workspace_id, &doc_id).await?;
|
||||
invalidate_doc_blob_projection(transaction, &workspace_id, &doc_id, embedding_schema_ready).await?;
|
||||
|
||||
let snapshot = sqlx::query_as::<_, LockedSnapshot>(
|
||||
"SELECT blob, updated_at FROM snapshots WHERE workspace_id=$1 AND guid=$2 FOR UPDATE",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("load recovery current snapshot", error))?
|
||||
.ok_or_else(|| RuntimeError::invalid_input("doc_not_found"))?;
|
||||
let updates = sqlx::query_as::<_, CurrentDocUpdate>(
|
||||
"SELECT blob, created_at FROM updates WHERE workspace_id=$1 AND guid=$2 ORDER BY created_at FOR UPDATE",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.fetch_all(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("load recovery pending updates", error))?;
|
||||
let current = merge_current_doc(
|
||||
Some(CurrentDoc {
|
||||
blob: snapshot.blob,
|
||||
updated_at: snapshot.updated_at,
|
||||
}),
|
||||
updates,
|
||||
)?
|
||||
.ok_or_else(|| RuntimeError::invalid_input("doc_not_found"))?;
|
||||
let current = load_current_doc_in(transaction, &workspace_id, &doc_id)
|
||||
.await?
|
||||
.ok_or_else(|| RuntimeError::invalid_input("doc_not_found"))?;
|
||||
let history = sqlx::query(
|
||||
"SELECT blob, state, EXTRACT(EPOCH FROM expired_at - timestamp)::bigint AS retention FROM snapshot_histories \
|
||||
WHERE workspace_id=$1 AND guid=$2 AND timestamp=$3 FOR UPDATE",
|
||||
@@ -75,167 +46,263 @@ pub(super) async fn recover(
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("load recovery history", error))?
|
||||
.ok_or_else(|| RuntimeError::invalid_input("doc_history_not_found"))?;
|
||||
sqlx::query(
|
||||
r#"INSERT INTO snapshot_histories
|
||||
(workspace_id, guid, timestamp, blob, state, expired_at, created_by)
|
||||
VALUES ($1, $2, $3, $4, NULL, clock_timestamp() + make_interval(secs => $5), $6)
|
||||
ON CONFLICT (workspace_id, guid, timestamp) DO NOTHING"#,
|
||||
let retention = history
|
||||
.try_get::<i64, _>("retention")
|
||||
.map_err(|error| RuntimeError::database("decode recovery retention", error))?;
|
||||
let existing = sqlx::query_scalar::<_, Vec<u8>>(
|
||||
"SELECT blob FROM snapshot_histories WHERE workspace_id=$1 AND guid=$2 AND timestamp=$3",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.bind(current.updated_at)
|
||||
.bind(current.blob)
|
||||
.bind(
|
||||
history
|
||||
.try_get::<i64, _>("retention")
|
||||
.map_err(|error| RuntimeError::database("decode recovery retention", error))?,
|
||||
)
|
||||
.bind(&actor_user_id)
|
||||
.execute(&mut **transaction)
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("record fixed recovery", error))?;
|
||||
sqlx::query("DELETE FROM updates WHERE workspace_id=$1 AND guid=$2")
|
||||
.map_err(|error| RuntimeError::database("load current recovery archive", error))?;
|
||||
let archive_timestamp = if existing.as_ref().is_some_and(|blob| blob != ¤t.blob) {
|
||||
let latest = sqlx::query(
|
||||
"SELECT timestamp,blob,GREATEST(timestamp + interval '1 millisecond', \
|
||||
date_trunc('milliseconds',clock_timestamp())) AS next_timestamp FROM snapshot_histories WHERE workspace_id=$1 \
|
||||
AND guid=$2 ORDER BY timestamp DESC LIMIT 1",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.execute(&mut **transaction)
|
||||
.fetch_one(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("clear recovered pending updates", error))?;
|
||||
let recovered = sqlx::query(
|
||||
r#"UPDATE snapshots SET blob=$3, state=$4, updated_at=clock_timestamp(), updated_by=$5
|
||||
WHERE workspace_id=$1 AND guid=$2
|
||||
RETURNING updated_at"#,
|
||||
.map_err(|error| RuntimeError::database("load latest recovery archive", error))?;
|
||||
let same_blob = latest
|
||||
.try_get::<Vec<u8>, _>("blob")
|
||||
.map_err(|error| RuntimeError::database("decode recovery archive", error))?
|
||||
== current.blob;
|
||||
latest
|
||||
.try_get::<DateTime<Utc>, _>(if same_blob { "timestamp" } else { "next_timestamp" })
|
||||
.map_err(|error| RuntimeError::database("decode recovery archive timestamp", error))?
|
||||
} else {
|
||||
current.updated_at
|
||||
};
|
||||
sqlx::query_scalar::<_, DateTime<Utc>>(
|
||||
r#"INSERT INTO snapshot_histories
|
||||
(workspace_id, guid, timestamp, blob, state, expired_at, created_by)
|
||||
VALUES ($1, $2, $3, $4, NULL, clock_timestamp() + make_interval(secs => $5), $6)
|
||||
ON CONFLICT (workspace_id, guid, timestamp) DO UPDATE
|
||||
SET expired_at=GREATEST(snapshot_histories.expired_at,EXCLUDED.expired_at)
|
||||
WHERE snapshot_histories.blob=EXCLUDED.blob
|
||||
RETURNING timestamp"#,
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.bind(
|
||||
history
|
||||
.try_get::<Vec<u8>, _>("blob")
|
||||
.map_err(|error| RuntimeError::database("decode recovery history blob", error))?,
|
||||
)
|
||||
.bind(
|
||||
history
|
||||
.try_get::<Option<Vec<u8>>, _>("state")
|
||||
.map_err(|error| RuntimeError::database("decode recovery history state", error))?,
|
||||
)
|
||||
.bind(archive_timestamp)
|
||||
.bind(current.blob)
|
||||
.bind(retention)
|
||||
.bind(&actor_user_id)
|
||||
.fetch_one(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("restore recovery snapshot", error))?;
|
||||
Ok(json!({
|
||||
"timestamp": timestamp,
|
||||
"updatedAt": recovered.try_get::<DateTime<Utc>, _>("updated_at")
|
||||
.map_err(|error| RuntimeError::database("decode recovered timestamp", error))?,
|
||||
}))
|
||||
.map_err(|error| RuntimeError::database("record fixed recovery", error))?;
|
||||
Ok(json!({ "timestamp": timestamp }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::runtime::Deployment;
|
||||
use crate::runtime::{
|
||||
Deployment,
|
||||
storage_runtime::{CurrentDoc, CurrentDocUpdate, merge_current_doc},
|
||||
};
|
||||
|
||||
#[tokio::test]
|
||||
async fn recovery_archives_current_content_and_restores_target_content() {
|
||||
async fn recovery_archives_current_content_without_replacing_source() {
|
||||
let _guard = crate::runtime::migrations::DATABASE_TEST_LOCK.lock().await;
|
||||
let Some((pool, workspace_id, actor_user_id)) = super::super::test_support::owner_workspace().await else {
|
||||
return;
|
||||
};
|
||||
let doc_id = format!("domain-history-{}", uuid::Uuid::new_v4().simple());
|
||||
let target_timestamp = Utc::now() - chrono::Duration::minutes(10);
|
||||
let current_timestamp = Utc::now() - chrono::Duration::minutes(1);
|
||||
let current_blob = affine_doc_loader::add_doc_to_root_doc(vec![0, 0], "current", None).unwrap();
|
||||
let pending_blob = affine_doc_loader::add_doc_to_root_doc(current_blob.clone(), "pending", None).unwrap();
|
||||
let target_blob = affine_doc_loader::add_doc_to_root_doc(vec![0, 0], "target", None).unwrap();
|
||||
let expected_current = merge_current_doc(
|
||||
Some(CurrentDoc {
|
||||
blob: current_blob.clone(),
|
||||
updated_at: current_timestamp,
|
||||
}),
|
||||
vec![CurrentDocUpdate {
|
||||
blob: pending_blob.clone(),
|
||||
created_at: current_timestamp + chrono::Duration::seconds(1),
|
||||
}],
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let current_timestamp = sqlx::query_scalar::<_, DateTime<Utc>>(
|
||||
"INSERT INTO snapshots(workspace_id,guid,blob,state,updated_at,created_by,updated_by) \
|
||||
VALUES($1,$2,$3,$4,$5,$6,$6) RETURNING updated_at",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.bind(¤t_blob)
|
||||
.bind(b"current-state".as_slice())
|
||||
.bind(current_timestamp)
|
||||
.bind(&actor_user_id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let pending_timestamp = sqlx::query_scalar::<_, DateTime<Utc>>(
|
||||
"INSERT INTO updates(workspace_id,guid,blob,created_at,created_by) VALUES($1,$2,$3,$4,$5) RETURNING created_at",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.bind(&pending_blob)
|
||||
.bind(current_timestamp + chrono::Duration::seconds(1))
|
||||
.bind(&actor_user_id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let target_timestamp = sqlx::query_scalar::<_, DateTime<Utc>>(
|
||||
"INSERT INTO snapshot_histories(workspace_id,guid,timestamp,blob,state,expired_at,created_by) \
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7) RETURNING timestamp",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.bind(target_timestamp)
|
||||
.bind(&target_blob)
|
||||
.bind(b"target-state".as_slice())
|
||||
.bind(target_timestamp + chrono::Duration::days(30))
|
||||
.bind(&actor_user_id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let authorizer = PermissionAuthorizer::new(pool.clone(), Deployment::Cloud);
|
||||
let mut transaction = pool.begin().await.unwrap();
|
||||
recover(
|
||||
&authorizer,
|
||||
&mut transaction,
|
||||
actor_user_id,
|
||||
workspace_id.clone(),
|
||||
doc_id.clone(),
|
||||
target_timestamp,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
transaction.commit().await.unwrap();
|
||||
|
||||
let restored = sqlx::query("SELECT blob,state,updated_at FROM snapshots WHERE workspace_id=$1 AND guid=$2")
|
||||
for collision in ["none", "same", "different", "gc"] {
|
||||
let doc_id = format!("domain-history-{}", uuid::Uuid::new_v4().simple());
|
||||
let target_timestamp = Utc::now() - chrono::Duration::minutes(10);
|
||||
let current_timestamp = Utc::now() - chrono::Duration::minutes(1);
|
||||
let current_blob = affine_doc_loader::add_doc_to_root_doc(vec![0, 0], "current", None).unwrap();
|
||||
let pending_blob = affine_doc_loader::add_doc_to_root_doc(current_blob.clone(), "pending", None).unwrap();
|
||||
let mut pending = y_octo::Doc::with_options(y_octo::DocOptions::default().auto_gc(false));
|
||||
pending
|
||||
.apply_update(y_octo::merge_updates_v1([current_blob.as_slice(), pending_blob.as_slice()]).unwrap())
|
||||
.unwrap();
|
||||
let mut meta = pending.get_map("meta").unwrap();
|
||||
meta
|
||||
.insert("discarded".to_string(), y_octo::Any::String("old payload".into()))
|
||||
.unwrap();
|
||||
meta.remove("discarded");
|
||||
let pending_blob = pending.encode_update_v1().unwrap();
|
||||
let target_blob = affine_doc_loader::add_doc_to_root_doc(vec![0, 0], "target", None).unwrap();
|
||||
let expected_current = merge_current_doc(
|
||||
Some(CurrentDoc {
|
||||
blob: current_blob.clone(),
|
||||
updated_at: current_timestamp,
|
||||
updated_by: None,
|
||||
}),
|
||||
vec![CurrentDocUpdate {
|
||||
blob: pending_blob.clone(),
|
||||
created_at: current_timestamp + chrono::Duration::seconds(1),
|
||||
created_by: None,
|
||||
}],
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let current_timestamp = sqlx::query_scalar::<_, DateTime<Utc>>(
|
||||
"INSERT INTO snapshots(workspace_id,guid,blob,state,updated_at,created_by,updated_by) \
|
||||
VALUES($1,$2,$3,$4,$5,$6,$6) RETURNING updated_at",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.bind(¤t_blob)
|
||||
.bind(b"current-state".as_slice())
|
||||
.bind(current_timestamp)
|
||||
.bind(&actor_user_id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(restored.get::<Vec<u8>, _>("blob"), target_blob);
|
||||
assert_eq!(restored.get::<Vec<u8>, _>("state"), b"target-state");
|
||||
assert!(restored.get::<DateTime<Utc>, _>("updated_at") > current_timestamp);
|
||||
let pending_count = sqlx::query_scalar::<_, i64>("SELECT count(*) FROM updates WHERE workspace_id=$1 AND guid=$2")
|
||||
let pending_timestamp = sqlx::query_scalar::<_, DateTime<Utc>>(
|
||||
"INSERT INTO updates(workspace_id,guid,blob,created_at,created_by) VALUES($1,$2,$3,$4,$5) RETURNING created_at",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.bind(&pending_blob)
|
||||
.bind(current_timestamp + chrono::Duration::seconds(1))
|
||||
.bind(&actor_user_id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(pending_count, 0);
|
||||
let archived = sqlx::query_scalar::<_, Vec<u8>>(
|
||||
"SELECT blob FROM snapshot_histories WHERE workspace_id=$1 AND guid=$2 AND timestamp=$3",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.bind(pending_timestamp)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(archived, expected_current.blob);
|
||||
let target_timestamp = sqlx::query_scalar::<_, DateTime<Utc>>(
|
||||
"INSERT INTO snapshot_histories(workspace_id,guid,timestamp,blob,state,expired_at,created_by) \
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7) RETURNING timestamp",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.bind(target_timestamp)
|
||||
.bind(&target_blob)
|
||||
.bind(b"target-state".as_slice())
|
||||
.bind(target_timestamp + chrono::Duration::days(30))
|
||||
.bind(&actor_user_id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let collision_blob = match collision {
|
||||
"same" => Some(expected_current.blob.clone()),
|
||||
"different" => Some(target_blob.clone()),
|
||||
"gc" => {
|
||||
let compacted = y_octo::Doc::try_from_binary_v1(&expected_current.blob).unwrap();
|
||||
compacted.gc().unwrap();
|
||||
let blob = compacted.encode_update_v1().unwrap();
|
||||
assert_ne!(blob, expected_current.blob);
|
||||
assert_eq!(
|
||||
affine_doc_loader::project_workspace_root(blob.clone(), true)
|
||||
.unwrap()
|
||||
.doc_ids,
|
||||
affine_doc_loader::project_workspace_root(expected_current.blob.clone(), true)
|
||||
.unwrap()
|
||||
.doc_ids,
|
||||
);
|
||||
Some(blob)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(blob) = &collision_blob {
|
||||
sqlx::query(
|
||||
"INSERT INTO snapshot_histories(workspace_id,guid,timestamp,blob,expired_at,created_by) \
|
||||
VALUES($1,$2,$3,$4,clock_timestamp() + interval '1 day',$5)",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.bind(pending_timestamp)
|
||||
.bind(blob)
|
||||
.bind(&actor_user_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let before_recovery =
|
||||
sqlx::query_scalar::<_, DateTime<Utc>>("SELECT date_trunc('milliseconds',clock_timestamp())")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let authorizer = PermissionAuthorizer::new(pool.clone(), Deployment::Cloud);
|
||||
for _ in 0..2 {
|
||||
let mut transaction = pool.begin().await.unwrap();
|
||||
recover(
|
||||
&authorizer,
|
||||
&mut transaction,
|
||||
actor_user_id.clone(),
|
||||
workspace_id.clone(),
|
||||
doc_id.clone(),
|
||||
target_timestamp,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
transaction.commit().await.unwrap();
|
||||
}
|
||||
|
||||
let restored = sqlx::query("SELECT blob,state,updated_at FROM snapshots WHERE workspace_id=$1 AND guid=$2")
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(restored.get::<Vec<u8>, _>("blob"), current_blob);
|
||||
assert_eq!(restored.get::<Vec<u8>, _>("state"), b"current-state");
|
||||
assert_eq!(restored.get::<DateTime<Utc>, _>("updated_at"), current_timestamp);
|
||||
let pending_count =
|
||||
sqlx::query_scalar::<_, i64>("SELECT count(*) FROM updates WHERE workspace_id=$1 AND guid=$2")
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(pending_count, 1);
|
||||
let pending_stored = sqlx::query_scalar::<_, Vec<u8>>(
|
||||
"SELECT blob FROM updates WHERE workspace_id=$1 AND guid=$2 AND created_at=$3",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.bind(pending_timestamp)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(pending_stored, pending_blob);
|
||||
let archives = sqlx::query(
|
||||
"SELECT timestamp,blob,expired_at FROM snapshot_histories WHERE workspace_id=$1 AND guid=$2 ORDER BY timestamp",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let collided = matches!(collision, "different" | "gc");
|
||||
assert_eq!(archives.len(), if collided { 3 } else { 2 }, "{collision}");
|
||||
assert_eq!(archives[0].get::<Vec<u8>, _>("blob"), target_blob);
|
||||
if let Some(blob) = collision_blob {
|
||||
assert_eq!(archives[1].get::<Vec<u8>, _>("blob"), blob);
|
||||
}
|
||||
let archived = archives.last().unwrap();
|
||||
assert_eq!(archived.get::<Vec<u8>, _>("blob"), expected_current.blob);
|
||||
let archived_timestamp = archived.get::<DateTime<Utc>, _>("timestamp");
|
||||
if collided {
|
||||
assert!(archived_timestamp > pending_timestamp);
|
||||
assert!(archived_timestamp >= before_recovery);
|
||||
} else {
|
||||
assert_eq!(archived_timestamp, pending_timestamp);
|
||||
}
|
||||
assert!(archived.get::<DateTime<Utc>, _>("expired_at") > before_recovery + chrono::Duration::days(29));
|
||||
let mut rejected = pool.begin().await.unwrap();
|
||||
let error = recover(
|
||||
&authorizer,
|
||||
&mut rejected,
|
||||
"actor".to_string(),
|
||||
workspace_id.clone(),
|
||||
workspace_id.clone(),
|
||||
target_timestamp,
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("doc_is_workspace"));
|
||||
rejected.rollback().await.unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,14 @@
|
||||
use affine_core::access_control::{DocLifecycleCommand, DomainCommand};
|
||||
use base64::{Engine, engine::general_purpose::STANDARD as BASE64};
|
||||
use chrono::Utc;
|
||||
use chrono::{DateTime, Utc};
|
||||
use napi::bindgen_prelude::Buffer;
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::{Postgres, Transaction};
|
||||
use y_octo::{Any, Doc, Value as YValue};
|
||||
|
||||
use super::{
|
||||
DocLifecycle, authorize_domain, invalidate_doc_blob_projection, lock_workspace_doc_update,
|
||||
lock_workspace_storage_shared, next_workspace_doc_update_timestamp,
|
||||
DocLifecycle, append_updates_in, authorize_domain_after_storage_lock, invalidate_workspace_inventory_in,
|
||||
is_ordinary_workspace_doc, lock_permission_generation, lock_workspace_doc_update, lock_workspace_storage_shared,
|
||||
validate_doc_updates,
|
||||
};
|
||||
use crate::runtime::{RuntimeError, RuntimeResult, backend_runtime::permission::PermissionAuthorizer};
|
||||
|
||||
@@ -20,15 +21,11 @@ pub(super) async fn apply(
|
||||
lifecycle: DocLifecycle,
|
||||
embedding_schema_ready: bool,
|
||||
) -> RuntimeResult<Value> {
|
||||
if workspace_id == doc_id {
|
||||
return Err(RuntimeError::invalid_input("doc_is_workspace"));
|
||||
if !is_ordinary_workspace_doc(&workspace_id, &doc_id) {
|
||||
return Err(RuntimeError::invalid_input("domain_permission_denied"));
|
||||
}
|
||||
lock_workspace_storage_shared(transaction, &workspace_id).await?;
|
||||
let mut locked_doc_ids = [&*workspace_id, &*doc_id];
|
||||
locked_doc_ids.sort_unstable();
|
||||
for locked_doc_id in locked_doc_ids {
|
||||
lock_workspace_doc_update(transaction, &workspace_id, locked_doc_id).await?;
|
||||
}
|
||||
lock_workspace_doc_update(transaction, &workspace_id, &doc_id).await?;
|
||||
let command = DomainCommand::ApplyDocLifecycle {
|
||||
doc_id: doc_id.clone(),
|
||||
lifecycle: match lifecycle {
|
||||
@@ -37,7 +34,7 @@ pub(super) async fn apply(
|
||||
DocLifecycle::Delete => DocLifecycleCommand::Delete,
|
||||
},
|
||||
};
|
||||
authorize_domain(
|
||||
authorize_domain_after_storage_lock(
|
||||
authorizer,
|
||||
transaction,
|
||||
&actor_user_id,
|
||||
@@ -46,47 +43,52 @@ pub(super) async fn apply(
|
||||
&command,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let snapshot =
|
||||
sqlx::query_scalar::<_, Vec<u8>>("SELECT blob FROM snapshots WHERE workspace_id=$1 AND guid=$1 FOR UPDATE")
|
||||
.bind(&workspace_id)
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("load workspace root snapshot", error))?
|
||||
.ok_or_else(|| RuntimeError::invalid_input("workspace_root_not_found"))?;
|
||||
let updates = sqlx::query_scalar::<_, Vec<u8>>(
|
||||
"SELECT blob FROM updates WHERE workspace_id=$1 AND guid=$1 ORDER BY created_at FOR SHARE",
|
||||
let exists: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT 1 FROM snapshots WHERE workspace_id=$1 AND guid=$2) OR EXISTS(SELECT 1 FROM updates WHERE \
|
||||
workspace_id=$1 AND guid=$2)",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.fetch_all(&mut **transaction)
|
||||
.bind(&doc_id)
|
||||
.fetch_one(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("load workspace root updates", error))?;
|
||||
let root_update = mutate_root(snapshot, updates, &doc_id, lifecycle)?;
|
||||
let timestamp = next_workspace_doc_update_timestamp(transaction, &workspace_id, &workspace_id).await?;
|
||||
sqlx::query("INSERT INTO updates (workspace_id,guid,blob,created_at,created_by) VALUES($1,$1,$2,$3,$4)")
|
||||
.bind(&workspace_id)
|
||||
.bind(&root_update)
|
||||
.bind(timestamp)
|
||||
.bind(&actor_user_id)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("persist workspace root lifecycle update", error))?;
|
||||
invalidate_doc_blob_projection(transaction, &workspace_id, &workspace_id, embedding_schema_ready).await?;
|
||||
|
||||
.map_err(|error| RuntimeError::database("load lifecycle document", error))?;
|
||||
if !exists {
|
||||
return Err(RuntimeError::invalid_input("doc_not_found"));
|
||||
}
|
||||
if matches!(lifecycle, DocLifecycle::Delete) {
|
||||
delete_doc_rows(transaction, &workspace_id, &doc_id).await?;
|
||||
}
|
||||
Ok(json!({
|
||||
"workspaceId": workspace_id,
|
||||
"docId": doc_id,
|
||||
"lifecycle": match lifecycle {
|
||||
DocLifecycle::Trash => "trash",
|
||||
DocLifecycle::Restore => "restore",
|
||||
DocLifecycle::Delete => "delete",
|
||||
},
|
||||
"rootUpdate": BASE64.encode(root_update),
|
||||
"timestamp": timestamp,
|
||||
}))
|
||||
let state = match lifecycle {
|
||||
DocLifecycle::Trash => Some("trashed"),
|
||||
DocLifecycle::Restore => None,
|
||||
DocLifecycle::Delete => Some("deleted"),
|
||||
};
|
||||
let timestamp: DateTime<Utc> = sqlx::query_scalar(
|
||||
"INSERT INTO workspace_pages(workspace_id,page_id,lifecycle_state,lifecycle_changed_at) \
|
||||
VALUES($1,$2,$3::\"DocLifecycleState\",date_trunc('milliseconds',clock_timestamp())) ON \
|
||||
CONFLICT(workspace_id,page_id) DO UPDATE SET \
|
||||
lifecycle_state=EXCLUDED.lifecycle_state,lifecycle_changed_at=GREATEST(EXCLUDED.lifecycle_changed_at,\
|
||||
workspace_pages.lifecycle_changed_at+interval '1 millisecond') RETURNING lifecycle_changed_at",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.bind(state)
|
||||
.fetch_one(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("set document lifecycle", error))?;
|
||||
if embedding_schema_ready {
|
||||
sqlx::query(
|
||||
"UPDATE embedding_sources SET deleted_at=clock_timestamp(),updated_at=clock_timestamp() WHERE workspace_id=$1 \
|
||||
AND source_kind='document' AND source_key=$2",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("invalidate deleted document embedding", error))?;
|
||||
}
|
||||
invalidate_workspace_inventory_in(transaction, &workspace_id).await?;
|
||||
Ok(json!({"workspaceId": workspace_id, "docId": doc_id, "timestamp": timestamp.timestamp_millis()}))
|
||||
}
|
||||
|
||||
pub(super) async fn append_root_update(
|
||||
@@ -98,245 +100,35 @@ pub(super) async fn append_root_update(
|
||||
expected_permission_generation: Option<i64>,
|
||||
embedding_schema_ready: bool,
|
||||
) -> RuntimeResult<Value> {
|
||||
let update = BASE64
|
||||
.decode(encoded_update)
|
||||
.map_err(|_| RuntimeError::invalid_input("doc_update_invalid"))?;
|
||||
let updates = vec![Buffer::from(update)];
|
||||
validate_doc_updates(&updates, true).await?;
|
||||
lock_workspace_storage_shared(transaction, &workspace_id).await?;
|
||||
lock_workspace_doc_update(transaction, &workspace_id, &workspace_id).await?;
|
||||
let command = DomainCommand::AppendRootUpdate {
|
||||
doc_id: workspace_id.clone(),
|
||||
};
|
||||
authorize_domain(
|
||||
authorize_domain_after_storage_lock(
|
||||
authorizer,
|
||||
transaction,
|
||||
&actor_user_id,
|
||||
&workspace_id,
|
||||
Some(&workspace_id),
|
||||
&command,
|
||||
&DomainCommand::AppendRootUpdate {
|
||||
doc_id: workspace_id.clone(),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
if let Some(expected) = expected_permission_generation {
|
||||
sqlx::query(
|
||||
"INSERT INTO workspace_sync_permission_generations(workspace_id,generation) VALUES($1,0) ON CONFLICT DO NOTHING",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("initialize sync permission generation", error))?;
|
||||
let current = sqlx::query_scalar::<_, i64>(
|
||||
"SELECT generation FROM workspace_sync_permission_generations WHERE workspace_id=$1 FOR SHARE",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.fetch_one(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("lock sync permission generation", error))?;
|
||||
if current != expected {
|
||||
return Err(RuntimeError::invalid_state("sync_permission_generation_changed"));
|
||||
}
|
||||
}
|
||||
let snapshot =
|
||||
sqlx::query_scalar::<_, Vec<u8>>("SELECT blob FROM snapshots WHERE workspace_id=$1 AND guid=$1 FOR UPDATE")
|
||||
.bind(&workspace_id)
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("load root snapshot for append", error))?;
|
||||
let updates = sqlx::query_scalar::<_, Vec<u8>>(
|
||||
"SELECT blob FROM updates WHERE workspace_id=$1 AND guid=$1 ORDER BY created_at FOR SHARE",
|
||||
lock_permission_generation(transaction, &workspace_id, expected_permission_generation).await?;
|
||||
let timestamp = append_updates_in(
|
||||
transaction,
|
||||
embedding_schema_ready,
|
||||
&workspace_id,
|
||||
&workspace_id,
|
||||
updates,
|
||||
Some(&actor_user_id),
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.fetch_all(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("load root updates for append", error))?;
|
||||
let update = BASE64
|
||||
.decode(encoded_update)
|
||||
.map_err(|error| RuntimeError::invalid_input(format!("invalid root update: {error}")))?;
|
||||
let initialize = snapshot.is_none();
|
||||
let merged = validate_root_update(snapshot.unwrap_or_else(|| vec![0, 0]), updates, &update)?;
|
||||
let timestamp = next_workspace_doc_update_timestamp(transaction, &workspace_id, &workspace_id).await?;
|
||||
if initialize {
|
||||
sqlx::query(
|
||||
"INSERT INTO snapshots (workspace_id,guid,blob,size,updated_at,created_by,updated_by) \
|
||||
VALUES($1,$1,$2,$3,$4,$5,$5)",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&merged)
|
||||
.bind(merged.len() as i64)
|
||||
.bind(timestamp)
|
||||
.bind(&actor_user_id)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("initialize canonical root snapshot", error))?;
|
||||
} else {
|
||||
sqlx::query("INSERT INTO updates (workspace_id,guid,blob,created_at,created_by) VALUES($1,$1,$2,$3,$4)")
|
||||
.bind(&workspace_id)
|
||||
.bind(&update)
|
||||
.bind(timestamp)
|
||||
.bind(&actor_user_id)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("append canonical root update", error))?;
|
||||
}
|
||||
invalidate_doc_blob_projection(transaction, &workspace_id, &workspace_id, embedding_schema_ready).await?;
|
||||
Ok(json!({ "timestamp": timestamp }))
|
||||
}
|
||||
|
||||
pub(in crate::runtime::backend_runtime) async fn workspace_root_contains_active_doc(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &str,
|
||||
doc_id: &str,
|
||||
) -> RuntimeResult<bool> {
|
||||
let Some(snapshot) =
|
||||
sqlx::query_scalar::<_, Vec<u8>>("SELECT blob FROM snapshots WHERE workspace_id=$1 AND guid=$1 FOR SHARE")
|
||||
.bind(workspace_id)
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("load workspace root for document creation", error))?
|
||||
else {
|
||||
return Ok(false);
|
||||
};
|
||||
let updates = sqlx::query_scalar::<_, Vec<u8>>(
|
||||
"SELECT blob FROM updates WHERE workspace_id=$1 AND guid=$1 ORDER BY created_at FOR SHARE",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.fetch_all(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("load workspace root updates for document creation", error))?;
|
||||
let mut root = Doc::default();
|
||||
root
|
||||
.apply_update_from_binary_v1(&snapshot)
|
||||
.map_err(|error| RuntimeError::invalid_state(format!("workspace root snapshot invalid: {error}")))?;
|
||||
for update in updates {
|
||||
root
|
||||
.apply_update_from_binary_v1(&update)
|
||||
.map_err(|error| RuntimeError::invalid_state(format!("workspace root update invalid: {error}")))?;
|
||||
}
|
||||
let binary = root
|
||||
.encode_update_v1()
|
||||
.map_err(|error| RuntimeError::invalid_state(format!("encode workspace root failed: {error}")))?;
|
||||
Ok(project_complete_root(binary, false, "before document creation")?.contains(doc_id))
|
||||
}
|
||||
|
||||
fn validate_root_update(snapshot: Vec<u8>, updates: Vec<Vec<u8>>, incoming: &[u8]) -> RuntimeResult<Vec<u8>> {
|
||||
let mut root = Doc::default();
|
||||
root
|
||||
.apply_update_from_binary_v1(&snapshot)
|
||||
.map_err(|error| RuntimeError::invalid_state(format!("workspace root snapshot invalid: {error}")))?;
|
||||
for update in updates {
|
||||
root
|
||||
.apply_update_from_binary_v1(&update)
|
||||
.map_err(|error| RuntimeError::invalid_state(format!("workspace root update invalid: {error}")))?;
|
||||
}
|
||||
let before = root
|
||||
.encode_update_v1()
|
||||
.map_err(|error| RuntimeError::invalid_state(format!("encode root before append failed: {error}")))?;
|
||||
let old_all = project_complete_root(before.clone(), true, "before append")?;
|
||||
let old_active = project_complete_root(before, false, "before append")?;
|
||||
root
|
||||
.apply_update_from_binary_v1(incoming)
|
||||
.map_err(|error| RuntimeError::invalid_input(format!("invalid root update: {error}")))?;
|
||||
let after = root
|
||||
.encode_update_v1()
|
||||
.map_err(|error| RuntimeError::invalid_state(format!("encode root after append failed: {error}")))?;
|
||||
let new_all = project_complete_root(after.clone(), true, "after append")?;
|
||||
let new_active = project_complete_root(after.clone(), false, "after append")?;
|
||||
let deletes = old_all.iter().any(|id| !new_all.contains(id));
|
||||
let trashes = old_active.iter().any(|id| !new_active.contains(id));
|
||||
let restores = new_active
|
||||
.iter()
|
||||
.any(|id| old_all.contains(id) && !old_active.contains(id));
|
||||
if deletes || trashes || restores {
|
||||
return Err(RuntimeError::invalid_input("doc_lifecycle_requires_command"));
|
||||
}
|
||||
Ok(after)
|
||||
}
|
||||
|
||||
fn project_complete_root(
|
||||
binary: Vec<u8>,
|
||||
include_trash: bool,
|
||||
operation: &str,
|
||||
) -> RuntimeResult<std::collections::BTreeSet<String>> {
|
||||
if binary == [0, 0] {
|
||||
return Ok(Default::default());
|
||||
}
|
||||
let projection = affine_doc_loader::project_workspace_root(binary, include_trash)
|
||||
.map_err(|error| RuntimeError::invalid_state(format!("project root {operation} failed: {error}")))?;
|
||||
if !projection.complete {
|
||||
return Err(RuntimeError::invalid_state(format!(
|
||||
"workspace root {operation} is incomplete"
|
||||
)));
|
||||
}
|
||||
Ok(projection.doc_ids.into_iter().collect())
|
||||
}
|
||||
|
||||
fn mutate_root(
|
||||
snapshot: Vec<u8>,
|
||||
updates: Vec<Vec<u8>>,
|
||||
doc_id: &str,
|
||||
lifecycle: DocLifecycle,
|
||||
) -> RuntimeResult<Vec<u8>> {
|
||||
let mut root = Doc::default();
|
||||
root
|
||||
.apply_update_from_binary_v1(&snapshot)
|
||||
.map_err(|error| RuntimeError::invalid_state(format!("workspace root snapshot invalid: {error}")))?;
|
||||
for update in updates {
|
||||
root
|
||||
.apply_update_from_binary_v1(&update)
|
||||
.map_err(|error| RuntimeError::invalid_state(format!("workspace root update invalid: {error}")))?;
|
||||
}
|
||||
let before = root
|
||||
.encode_update_v1()
|
||||
.map_err(|error| RuntimeError::invalid_state(format!("encode workspace root failed: {error}")))?;
|
||||
project_complete_root(before, true, "before lifecycle command")?;
|
||||
let state = root.get_state_vector();
|
||||
let meta = root
|
||||
.get_map("meta")
|
||||
.map_err(|error| RuntimeError::invalid_state(format!("workspace root meta missing: {error}")))?;
|
||||
let mut pages = meta
|
||||
.get("pages")
|
||||
.and_then(|value| value.to_array())
|
||||
.ok_or_else(|| RuntimeError::invalid_state("workspace root pages missing"))?;
|
||||
let index = pages
|
||||
.iter()
|
||||
.position(|value| {
|
||||
value
|
||||
.to_map()
|
||||
.and_then(|page| page.get("id"))
|
||||
.and_then(|id| id.to_any())
|
||||
== Some(Any::String(doc_id.to_string()))
|
||||
})
|
||||
.ok_or_else(|| RuntimeError::invalid_input("doc_not_found"))?;
|
||||
match lifecycle {
|
||||
DocLifecycle::Trash | DocLifecycle::Restore => {
|
||||
let mut page = pages
|
||||
.iter()
|
||||
.nth(index)
|
||||
.and_then(|value| value.to_map())
|
||||
.ok_or_else(|| RuntimeError::invalid_state("workspace root doc meta invalid"))?;
|
||||
page
|
||||
.insert(
|
||||
"trash".to_string(),
|
||||
YValue::Any(if matches!(lifecycle, DocLifecycle::Trash) {
|
||||
Any::True
|
||||
} else {
|
||||
Any::False
|
||||
}),
|
||||
)
|
||||
.map_err(|error| RuntimeError::invalid_state(format!("write doc lifecycle failed: {error}")))?;
|
||||
if matches!(lifecycle, DocLifecycle::Trash) {
|
||||
page
|
||||
.insert(
|
||||
"trashDate".to_string(),
|
||||
YValue::Any(Any::BigInt64(Utc::now().timestamp_millis())),
|
||||
)
|
||||
.map_err(|error| RuntimeError::invalid_state(format!("write trash timestamp failed: {error}")))?;
|
||||
} else {
|
||||
page.remove("trashDate");
|
||||
}
|
||||
}
|
||||
DocLifecycle::Delete => pages
|
||||
.remove(index as u64, 1)
|
||||
.map_err(|error| RuntimeError::invalid_state(format!("delete doc meta failed: {error}")))?,
|
||||
}
|
||||
root
|
||||
.encode_state_as_update_v1(&state)
|
||||
.map_err(|error| RuntimeError::invalid_state(format!("encode workspace root lifecycle failed: {error}")))
|
||||
.await?;
|
||||
Ok(json!({"timestamp": timestamp}))
|
||||
}
|
||||
|
||||
async fn delete_doc_rows(
|
||||
@@ -344,202 +136,42 @@ async fn delete_doc_rows(
|
||||
workspace_id: &str,
|
||||
doc_id: &str,
|
||||
) -> RuntimeResult<()> {
|
||||
for statement in [
|
||||
"DELETE FROM replies WHERE workspace_id=$1 AND doc_id=$2",
|
||||
"DELETE FROM comments WHERE workspace_id=$1 AND doc_id=$2",
|
||||
"DELETE FROM updates WHERE workspace_id=$1 AND guid=$2",
|
||||
"DELETE FROM snapshot_histories WHERE workspace_id=$1 AND guid=$2",
|
||||
"DELETE FROM snapshots WHERE workspace_id=$1 AND guid=$2",
|
||||
"DELETE FROM doc_grants WHERE workspace_id=$1 AND doc_id=$2",
|
||||
"DELETE FROM doc_access_policies WHERE workspace_id=$1 AND doc_id=$2",
|
||||
"DELETE FROM workspace_pages WHERE workspace_id=$1 AND page_id=$2",
|
||||
for (table, column) in [
|
||||
("replies", "doc_id"),
|
||||
("comment_attachments", "doc_id"),
|
||||
("comments", "doc_id"),
|
||||
("doc_blob_refs", "doc_id"),
|
||||
("doc_blob_ref_projections", "doc_id"),
|
||||
("ai_workspace_ignored_docs", "doc_id"),
|
||||
("workspace_doc_view_daily", "doc_id"),
|
||||
("doc_grants", "doc_id"),
|
||||
("doc_access_policies", "doc_id"),
|
||||
("updates", "guid"),
|
||||
("snapshot_histories", "guid"),
|
||||
("snapshots", "guid"),
|
||||
("workspace_pages", "page_id"),
|
||||
] {
|
||||
sqlx::query(statement)
|
||||
sqlx::query(&format!("DELETE FROM {table} WHERE workspace_id=$1 AND {column}=$2"))
|
||||
.bind(workspace_id)
|
||||
.bind(doc_id)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("delete document domain rows", error))?;
|
||||
.map_err(|error| RuntimeError::database(format!("delete document {table}"), error))?;
|
||||
}
|
||||
for (table, column) in [
|
||||
("workspace_member_last_access", "last_doc_id"),
|
||||
("ai_sessions_metadata", "doc_id"),
|
||||
("ai_action_runs", "doc_id"),
|
||||
] {
|
||||
sqlx::query(&format!(
|
||||
"UPDATE {table} SET {column}=NULL WHERE workspace_id=$1 AND {column}=$2"
|
||||
))
|
||||
.bind(workspace_id)
|
||||
.bind(doc_id)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database(format!("unlink document {table}"), error))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use super::*;
|
||||
use crate::runtime::{Deployment, backend_runtime::permission::PermissionAuthorizer};
|
||||
|
||||
fn merge_root(snapshot: &[u8], updates: &[&[u8]]) -> Vec<u8> {
|
||||
let mut root = Doc::default();
|
||||
root.apply_update_from_binary_v1(snapshot).unwrap();
|
||||
for update in updates {
|
||||
root.apply_update_from_binary_v1(update).unwrap();
|
||||
}
|
||||
root.encode_update_v1().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lifecycle_mutation_changes_only_target_membership() {
|
||||
let snapshot = affine_doc_loader::add_doc_to_root_doc(vec![0, 0], "a", None).unwrap();
|
||||
let add_b = affine_doc_loader::add_doc_to_root_doc(snapshot.clone(), "b", None).unwrap();
|
||||
let snapshot = merge_root(&snapshot, &[&add_b]);
|
||||
let trashed = mutate_root(snapshot.clone(), Vec::new(), "a", DocLifecycle::Trash).unwrap();
|
||||
let trashed_root = merge_root(&snapshot, &[&trashed]);
|
||||
let current = affine_doc_loader::get_doc_ids_from_binary(trashed_root.clone(), false).unwrap();
|
||||
assert_eq!(current, vec!["b"]);
|
||||
let all = affine_doc_loader::get_doc_ids_from_binary(trashed_root, true).unwrap();
|
||||
assert_eq!(BTreeSet::from_iter(all), BTreeSet::from(["a".into(), "b".into()]));
|
||||
let restored = mutate_root(snapshot.clone(), vec![trashed.clone()], "a", DocLifecycle::Restore).unwrap();
|
||||
let restored_root = merge_root(&snapshot, &[&trashed, &restored]);
|
||||
let current = affine_doc_loader::get_doc_ids_from_binary(restored_root, false).unwrap();
|
||||
assert_eq!(BTreeSet::from_iter(current), BTreeSet::from(["a".into(), "b".into()]));
|
||||
let deleted = mutate_root(snapshot.clone(), Vec::new(), "a", DocLifecycle::Delete).unwrap();
|
||||
let deleted_root = merge_root(&snapshot, &[&deleted]);
|
||||
assert_eq!(
|
||||
affine_doc_loader::get_doc_ids_from_binary(deleted_root, true).unwrap(),
|
||||
vec!["b"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinary_root_updates_cannot_encode_lifecycle_effects() {
|
||||
let snapshot = affine_doc_loader::add_doc_to_root_doc(vec![0, 0], "a", None).unwrap();
|
||||
let trash = mutate_root(snapshot.clone(), Vec::new(), "a", DocLifecycle::Trash).unwrap();
|
||||
assert!(validate_root_update(snapshot.clone(), Vec::new(), &trash).is_err());
|
||||
|
||||
let restore = mutate_root(snapshot.clone(), vec![trash.clone()], "a", DocLifecycle::Restore).unwrap();
|
||||
assert!(validate_root_update(snapshot.clone(), vec![trash], &restore).is_err());
|
||||
|
||||
let delete = mutate_root(snapshot.clone(), Vec::new(), "a", DocLifecycle::Delete).unwrap();
|
||||
assert!(validate_root_update(snapshot.clone(), Vec::new(), &delete).is_err());
|
||||
|
||||
let add = affine_doc_loader::add_doc_to_root_doc(snapshot.clone(), "b", None).unwrap();
|
||||
assert!(validate_root_update(snapshot, Vec::new(), &add).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_workspace_root_is_rejected_before_semantic_comparison() {
|
||||
let snapshot = affine_doc_loader::add_doc_to_root_doc(vec![0, 0], "a", None).unwrap();
|
||||
let dependent_delta = mutate_root(snapshot.clone(), Vec::new(), "a", DocLifecycle::Trash).unwrap();
|
||||
assert!(validate_root_update(vec![0, 0], Vec::new(), &dependent_delta).is_err());
|
||||
assert!(
|
||||
validate_root_update(dependent_delta, Vec::new(), &snapshot).is_err(),
|
||||
"a root update with missing client-clock predecessors must fail closed"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn readonly_denies_restore_but_allows_trash_and_delete() {
|
||||
let _guard = crate::runtime::migrations::DATABASE_TEST_LOCK.lock().await;
|
||||
let Some((pool, workspace_id, actor_user_id)) = super::super::test_support::owner_workspace().await else {
|
||||
return;
|
||||
};
|
||||
let suffix = uuid::Uuid::new_v4().simple().to_string();
|
||||
let doc_id = format!("domain-lifecycle-{suffix}");
|
||||
let root = affine_doc_loader::add_doc_to_root_doc(vec![0, 0], &doc_id, None).unwrap();
|
||||
let authorizer = PermissionAuthorizer::new(pool.clone(), Deployment::Cloud);
|
||||
let mut transaction = pool.begin().await.unwrap();
|
||||
append_root_update(
|
||||
&authorizer,
|
||||
&mut transaction,
|
||||
actor_user_id.clone(),
|
||||
workspace_id.clone(),
|
||||
BASE64.encode(root),
|
||||
None,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
transaction.commit().await.unwrap();
|
||||
|
||||
for index in 0..3 {
|
||||
let user_id = format!("domain-lifecycle-overflow-{index}-{suffix}");
|
||||
sqlx::query(
|
||||
"INSERT INTO users(id,name,email,registered,email_verified,disabled) VALUES($1,'Overflow',$2,true,now(),false)",
|
||||
)
|
||||
.bind(&user_id)
|
||||
.bind(format!("{user_id}@example.com"))
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("INSERT INTO workspace_members(workspace_id,user_id,role,state) VALUES($1,$2,'member','active')")
|
||||
.bind(&workspace_id)
|
||||
.bind(&user_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let mut root_writer = pool.begin().await.unwrap();
|
||||
lock_workspace_doc_update(&mut root_writer, &workspace_id, &workspace_id)
|
||||
.await
|
||||
.unwrap();
|
||||
let racing_pool = pool.clone();
|
||||
let racing_workspace_id = workspace_id.clone();
|
||||
let racing_actor_user_id = actor_user_id.clone();
|
||||
let racing_doc_id = doc_id.clone();
|
||||
let trash = tokio::spawn(async move {
|
||||
let authorizer = PermissionAuthorizer::new(racing_pool.clone(), Deployment::Cloud);
|
||||
let mut transaction = racing_pool.begin().await.unwrap();
|
||||
apply(
|
||||
&authorizer,
|
||||
&mut transaction,
|
||||
racing_actor_user_id,
|
||||
racing_workspace_id,
|
||||
racing_doc_id,
|
||||
DocLifecycle::Trash,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
transaction.commit().await.unwrap();
|
||||
});
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
assert!(
|
||||
!trash.is_finished(),
|
||||
"a lifecycle update must wait for an in-flight workspace root writer"
|
||||
);
|
||||
root_writer.commit().await.unwrap();
|
||||
trash.await.unwrap();
|
||||
|
||||
let authorizer = PermissionAuthorizer::new(pool.clone(), Deployment::Cloud);
|
||||
let mut transaction = pool.begin().await.unwrap();
|
||||
let restore = apply(
|
||||
&authorizer,
|
||||
&mut transaction,
|
||||
actor_user_id.clone(),
|
||||
workspace_id.clone(),
|
||||
doc_id.clone(),
|
||||
DocLifecycle::Restore,
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
assert!(restore.is_err());
|
||||
transaction.rollback().await.unwrap();
|
||||
|
||||
let mut transaction = pool.begin().await.unwrap();
|
||||
apply(
|
||||
&authorizer,
|
||||
&mut transaction,
|
||||
actor_user_id,
|
||||
workspace_id.clone(),
|
||||
doc_id,
|
||||
DocLifecycle::Delete,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
transaction.commit().await.unwrap();
|
||||
let timestamps = sqlx::query_scalar::<_, chrono::DateTime<Utc>>(
|
||||
"SELECT created_at FROM updates WHERE workspace_id=$1 AND guid=$1 ORDER BY created_at",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(timestamps.len(), 2);
|
||||
assert!(timestamps[0] < timestamps[1]);
|
||||
}
|
||||
}
|
||||
@@ -11,12 +11,14 @@ use affine_core::access_control::{CommandAuthorizationDecision, DomainCommand};
|
||||
use chrono::{DateTime, Utc};
|
||||
use comments::{load_target, lock_target, value};
|
||||
pub(super) use execute::execute;
|
||||
pub(super) use lifecycle::workspace_root_contains_active_doc;
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
use sqlx::{Postgres, Transaction};
|
||||
|
||||
use super::{InvalidationHintV1, SourceIdentity, load_command_quota_in, permission::PermissionAuthorizer};
|
||||
pub(super) use super::{
|
||||
append_updates_in, is_ordinary_workspace_doc, load_current_doc_in, lock_permission_generation, validate_doc_updates,
|
||||
};
|
||||
use crate::runtime::{RuntimeError, RuntimeResult};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -152,9 +154,21 @@ pub(super) async fn authorize_domain(
|
||||
doc_id: Option<&str>,
|
||||
command: &DomainCommand,
|
||||
) -> RuntimeResult<CommandAuthorizationDecision> {
|
||||
lock_workspace(transaction, workspace_id).await?;
|
||||
lock_workspace_storage_shared(transaction, workspace_id).await?;
|
||||
authorize_domain_after_storage_lock(authorizer, transaction, actor_user_id, workspace_id, doc_id, command).await
|
||||
}
|
||||
|
||||
pub(super) async fn authorize_domain_after_storage_lock(
|
||||
authorizer: &PermissionAuthorizer,
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
actor_user_id: &str,
|
||||
workspace_id: &str,
|
||||
doc_id: Option<&str>,
|
||||
command: &DomainCommand,
|
||||
) -> RuntimeResult<CommandAuthorizationDecision> {
|
||||
lock_domain_workspace(transaction, workspace_id).await?;
|
||||
let quota = if command.effect().requires_quota_guard() {
|
||||
load_command_quota_in(transaction, authorizer.deployment, workspace_id).await?
|
||||
load_command_quota_in(transaction, authorizer.deployment, workspace_id, true).await?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -171,11 +185,53 @@ pub(super) async fn authorize_domain(
|
||||
.await
|
||||
}
|
||||
|
||||
pub(super) async fn authorize_doc_creation_in(
|
||||
authorizer: &PermissionAuthorizer,
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
actor_user_id: &str,
|
||||
workspace_id: &str,
|
||||
doc_id: &str,
|
||||
expected_generation: Option<i64>,
|
||||
) -> RuntimeResult<bool> {
|
||||
lock_domain_workspace(transaction, workspace_id).await?;
|
||||
let quota = load_command_quota_in(transaction, authorizer.deployment, workspace_id, true).await?;
|
||||
lock_permission_facts(transaction, actor_user_id, workspace_id, Some(doc_id)).await?;
|
||||
lock_permission_generation(transaction, workspace_id, expected_generation).await?;
|
||||
let bindings: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT 1 FROM doc_access_policies WHERE workspace_id=$1 AND doc_id=$2) OR EXISTS(SELECT 1 FROM \
|
||||
doc_grants WHERE workspace_id=$1 AND doc_id=$2)",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(doc_id)
|
||||
.fetch_one(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("load initial document permission bindings", error))?;
|
||||
let mut commands = vec![DomainCommand::CreateDoc];
|
||||
if bindings {
|
||||
commands.push(DomainCommand::UpdateDoc { doc_id: doc_id.into() });
|
||||
}
|
||||
authorizer
|
||||
.authorize_commands_in(
|
||||
transaction,
|
||||
actor_user_id,
|
||||
workspace_id,
|
||||
Some(doc_id),
|
||||
&commands,
|
||||
quota.as_ref().map(|quota| quota.facts()),
|
||||
)
|
||||
.await?;
|
||||
Ok(!bindings)
|
||||
}
|
||||
|
||||
pub(super) async fn lock_workspace(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &str,
|
||||
) -> RuntimeResult<()> {
|
||||
lock_workspace_storage_shared(transaction, workspace_id).await?;
|
||||
lock_domain_workspace(transaction, workspace_id).await
|
||||
}
|
||||
|
||||
async fn lock_domain_workspace(transaction: &mut Transaction<'_, Postgres>, workspace_id: &str) -> RuntimeResult<()> {
|
||||
let key = format!("domain:workspace:{workspace_id}");
|
||||
loop {
|
||||
let locked: bool = sqlx::query_scalar("SELECT pg_try_advisory_xact_lock(hashtextextended($1, 0))")
|
||||
@@ -190,14 +246,14 @@ pub(super) async fn lock_workspace(
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn lock_workspace_storage_shared(
|
||||
pub(in crate::runtime) async fn lock_workspace_storage_shared(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &str,
|
||||
) -> RuntimeResult<()> {
|
||||
super::super::lock_workspace_storage_shared_transaction(transaction, workspace_id).await
|
||||
}
|
||||
|
||||
pub(super) async fn invalidate_doc_blob_projection(
|
||||
pub(in crate::runtime) async fn invalidate_doc_blob_projection(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &str,
|
||||
doc_id: &str,
|
||||
@@ -233,18 +289,25 @@ pub(super) async fn invalidate_doc_blob_projection(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn try_lock_workspace_doc_update(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &str,
|
||||
doc_id: &str,
|
||||
) -> RuntimeResult<bool> {
|
||||
sqlx::query_scalar("SELECT pg_try_advisory_xact_lock(hashtextextended($1, 0))")
|
||||
.bind(format!("workspace-doc-update:{workspace_id}/{doc_id}"))
|
||||
.fetch_one(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("lock workspace document update", error))
|
||||
}
|
||||
|
||||
pub(super) async fn lock_workspace_doc_update(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &str,
|
||||
doc_id: &str,
|
||||
) -> RuntimeResult<()> {
|
||||
let key = format!("workspace-doc-update:{workspace_id}/{doc_id}");
|
||||
loop {
|
||||
let locked: bool = sqlx::query_scalar("SELECT pg_try_advisory_xact_lock(hashtextextended($1, 0))")
|
||||
.bind(&key)
|
||||
.fetch_one(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("lock workspace document update", error))?;
|
||||
let locked = try_lock_workspace_doc_update(transaction, workspace_id, doc_id).await?;
|
||||
if locked {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -252,14 +315,15 @@ pub(super) async fn lock_workspace_doc_update(
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn next_workspace_doc_update_timestamp(
|
||||
pub(in crate::runtime) async fn next_workspace_doc_update_timestamp(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &str,
|
||||
doc_id: &str,
|
||||
) -> RuntimeResult<DateTime<Utc>> {
|
||||
sqlx::query_scalar(
|
||||
"SELECT GREATEST(date_trunc('milliseconds',clock_timestamp()),COALESCE(max(created_at)+interval '1 \
|
||||
millisecond','epoch')) FROM updates WHERE workspace_id=$1 AND guid=$2",
|
||||
"SELECT GREATEST(date_trunc('milliseconds',clock_timestamp()),COALESCE(max(timestamp)+interval '1 \
|
||||
millisecond','epoch')) FROM (SELECT updated_at AS timestamp FROM snapshots WHERE workspace_id=$1 AND guid=$2 \
|
||||
UNION ALL SELECT created_at AS timestamp FROM updates WHERE workspace_id=$1 AND guid=$2) source",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(doc_id)
|
||||
@@ -317,6 +381,7 @@ mod test_support {
|
||||
|
||||
pub(super) async fn owner_workspace() -> Option<(PgPool, String, String)> {
|
||||
let pool = PgPool::connect(&std::env::var("DATABASE_URL").ok()?).await.unwrap();
|
||||
crate::runtime::migrations::migrate_runtime_tables(&pool).await.unwrap();
|
||||
assert!(
|
||||
crate::runtime::migrations::migrate_embedding_tables(&pool)
|
||||
.await
|
||||
@@ -405,3 +470,20 @@ mod tests {
|
||||
assert!(command.await.unwrap().is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn invalidate_workspace_inventory_in(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &str,
|
||||
) -> RuntimeResult<()> {
|
||||
sqlx::query(
|
||||
"UPDATE search_projection.workspace_states SET \
|
||||
target_root_revision=nextval('search_projection.source_mutation_version'),pending_scope='workspace',\
|
||||
progress=NULL,claim_fence=nextval('search_projection.claim_fence'),lease_owner=NULL,lease_expires_at=NULL,\
|
||||
last_error=NULL,available_at=now(),updated_at=now() WHERE workspace_id=$1",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("invalidate workspace search inventory", error))?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -18,7 +18,12 @@ use tokio::sync::Notify;
|
||||
pub(super) use types::EmbeddingTarget;
|
||||
use types::*;
|
||||
|
||||
use super::{RuntimeError, RuntimeResult, copilot::BackgroundEmbeddingProvider};
|
||||
use super::{
|
||||
RuntimeError, RuntimeResult,
|
||||
copilot::BackgroundEmbeddingProvider,
|
||||
domain_command::{lock_workspace_doc_update, lock_workspace_storage_shared},
|
||||
is_ordinary_workspace_doc, load_doc_states_in,
|
||||
};
|
||||
use crate::runtime::object_storage::ObjectStorageService;
|
||||
|
||||
fn extraction_file_name(mime_type: &str) -> String {
|
||||
@@ -97,10 +102,9 @@ impl EmbeddingService {
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
documents: &[crate::runtime::types::DocumentEmbeddingProjectionInput],
|
||||
reconcile: bool,
|
||||
priority: i32,
|
||||
) -> RuntimeResult<()> {
|
||||
source::sync_documents(&self.pool, workspace_id, documents, reconcile, priority).await?;
|
||||
source::sync_documents(&self.pool, workspace_id, documents, priority).await?;
|
||||
self.wake();
|
||||
Ok(())
|
||||
}
|
||||
@@ -130,12 +134,6 @@ impl EmbeddingService {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn reconcile_documents(&self, workspace_id: &str) -> RuntimeResult<()> {
|
||||
source::reconcile_documents(&self.pool, workspace_id).await?;
|
||||
self.wake();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn health_counts(&self) -> RuntimeResult<EmbeddingQueueCounts> {
|
||||
store::queue_counts(&self.pool).await
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{RuntimeError, RuntimeResult, extraction_file_name};
|
||||
use crate::runtime::{
|
||||
storage_runtime::load_current_doc,
|
||||
types::{DocumentEmbeddingProjectionInput, RuntimeWorkspaceArtifact},
|
||||
use super::{
|
||||
RuntimeError, RuntimeResult, extraction_file_name, is_ordinary_workspace_doc, load_doc_states_in,
|
||||
lock_workspace_doc_update, lock_workspace_storage_shared,
|
||||
};
|
||||
use crate::runtime::types::{DocumentEmbeddingProjectionInput, RuntimeWorkspaceArtifact};
|
||||
|
||||
const DOCUMENT_RECIPE: &str = "document-projection-v1";
|
||||
const ARTIFACT_RECIPE: &str = "artifact-extraction-v1";
|
||||
@@ -14,29 +14,30 @@ pub(super) async fn sync_documents(
|
||||
pool: &PgPool,
|
||||
workspace_id: &str,
|
||||
documents: &[DocumentEmbeddingProjectionInput],
|
||||
reconcile: bool,
|
||||
priority: i32,
|
||||
) -> RuntimeResult<()> {
|
||||
let live_doc_ids = if reconcile {
|
||||
Some(load_live_doc_ids(pool, workspace_id).await?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut transaction = pool
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("sync document sources transaction failed", error))?;
|
||||
lock_workspace_storage_shared(&mut transaction, workspace_id).await?;
|
||||
let mut doc_ids = documents.iter().map(|doc| doc.doc_id.clone()).collect::<Vec<_>>();
|
||||
doc_ids.sort_unstable();
|
||||
doc_ids.dedup();
|
||||
for doc_id in &doc_ids {
|
||||
lock_workspace_doc_update(&mut transaction, workspace_id, doc_id).await?;
|
||||
}
|
||||
let states = load_doc_states_in(&mut transaction, workspace_id, &doc_ids)
|
||||
.await?
|
||||
.into_iter()
|
||||
.filter(|doc| doc.lifecycle.is_none() && is_ordinary_workspace_doc(workspace_id, &doc.doc_id))
|
||||
.map(|doc| (doc.doc_id.clone(), doc))
|
||||
.collect::<std::collections::BTreeMap<_, _>>();
|
||||
for document in documents {
|
||||
if document.deleted.unwrap_or(false) {
|
||||
sqlx::query(
|
||||
"UPDATE embedding_sources SET deleted_at=now(),updated_at=now() WHERE workspace_id=$1 AND \
|
||||
source_kind='document' AND source_key=$2",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(&document.doc_id)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("delete document embedding source failed", error))?;
|
||||
if !states
|
||||
.get(&document.doc_id)
|
||||
.is_some_and(|state| state.timestamp.timestamp_millis().to_string() == document.revision)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let projection =
|
||||
@@ -79,9 +80,6 @@ pub(super) async fn sync_documents(
|
||||
.map_err(|error| RuntimeError::database("record skipped document projection failed", error))?;
|
||||
}
|
||||
}
|
||||
if let Some(live_doc_ids) = live_doc_ids {
|
||||
reconcile_document_sources(&mut transaction, workspace_id, &live_doc_ids).await?;
|
||||
}
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
@@ -126,72 +124,6 @@ pub(super) async fn document_readiness(
|
||||
.map_err(|error| RuntimeError::database("load document embedding readiness failed", error))
|
||||
}
|
||||
|
||||
pub(super) async fn reconcile_documents(pool: &PgPool, workspace_id: &str) -> RuntimeResult<()> {
|
||||
let live_doc_ids = load_live_doc_ids(pool, workspace_id).await?;
|
||||
let mut transaction = pool
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("reconcile document sources transaction failed", error))?;
|
||||
reconcile_document_sources(&mut transaction, workspace_id, &live_doc_ids).await?;
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("reconcile document sources commit failed", error))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn load_live_doc_ids(pool: &PgPool, workspace_id: &str) -> RuntimeResult<Vec<String>> {
|
||||
let root = load_current_doc(pool, workspace_id, workspace_id)
|
||||
.await?
|
||||
.ok_or_else(|| RuntimeError::invalid_state("workspace root doc is missing"))?;
|
||||
let projection = affine_doc_loader::project_workspace_root(root.blob, true)
|
||||
.map_err(|error| RuntimeError::invalid_state(format!("workspace root projection failed: {error}")))?;
|
||||
if !projection.complete {
|
||||
return Err(RuntimeError::invalid_state("workspace root projection is incomplete"));
|
||||
}
|
||||
Ok(projection.doc_ids)
|
||||
}
|
||||
|
||||
async fn reconcile_document_sources(
|
||||
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||
workspace_id: &str,
|
||||
live_doc_ids: &[String],
|
||||
) -> RuntimeResult<()> {
|
||||
let deleted = sqlx::query_scalar::<_, Uuid>(
|
||||
r#"UPDATE embedding_sources SET deleted_at=now(),updated_at=now()
|
||||
WHERE workspace_id=$1 AND source_kind='document' AND deleted_at IS NULL
|
||||
AND NOT(source_key=ANY($2::text[]))
|
||||
RETURNING id"#,
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(live_doc_ids)
|
||||
.fetch_all(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("reconcile deleted document sources failed", error))?;
|
||||
if !deleted.is_empty() {
|
||||
sqlx::query("DELETE FROM embedding_projections WHERE source_id=ANY($1::uuid[])")
|
||||
.bind(&deleted)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("remove deleted document projections failed", error))?;
|
||||
}
|
||||
let restored = sqlx::query_scalar::<_, Uuid>(
|
||||
r#"UPDATE embedding_sources SET deleted_at=NULL,updated_at=now()
|
||||
WHERE workspace_id=$1 AND source_kind='document' AND deleted_at IS NOT NULL
|
||||
AND source_key=ANY($2::text[])
|
||||
RETURNING id"#,
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(live_doc_ids)
|
||||
.fetch_all(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("reconcile restored document sources failed", error))?;
|
||||
for source_id in restored {
|
||||
queue_active_projection(transaction, workspace_id, source_id, 100).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn register_artifact(pool: &PgPool, artifact: &RuntimeWorkspaceArtifact) -> RuntimeResult<()> {
|
||||
let mut transaction = pool
|
||||
.begin()
|
||||
|
||||
@@ -316,7 +316,7 @@ mod tests {
|
||||
use super::{super::claim_projection, *};
|
||||
|
||||
#[tokio::test]
|
||||
async fn leases_fence_stale_commits_and_gc_old_tokens_and_indexes() {
|
||||
async fn source_reconciliation_fences_leases_and_gc_preserves_current_facts() {
|
||||
let Ok(database_url) = std::env::var("DATABASE_URL") else {
|
||||
return;
|
||||
};
|
||||
@@ -365,6 +365,18 @@ mod tests {
|
||||
.await
|
||||
.unwrap();
|
||||
let workspace_id = format!("rust-test-store-{}", Uuid::new_v4());
|
||||
sqlx::query("INSERT INTO workspaces(id) VALUES($1)")
|
||||
.bind(&workspace_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"INSERT INTO snapshots(workspace_id,guid,blob,updated_at) VALUES($1,'doc',decode('0000','hex'),to_timestamp(1))",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let index_id = Uuid::new_v4();
|
||||
let source_id = Uuid::new_v4();
|
||||
sqlx::query(
|
||||
@@ -390,7 +402,7 @@ mod tests {
|
||||
r#"INSERT INTO embedding_sources(
|
||||
id,workspace_id,source_kind,source_key,content_revision,
|
||||
descriptor_revision,recipe_revision,document_projection)
|
||||
VALUES($1,$2,'document','doc','content-1','descriptor','recipe','{}')"#,
|
||||
VALUES($1,$2,'document','doc','1000','descriptor','recipe','{}')"#,
|
||||
)
|
||||
.bind(source_id)
|
||||
.bind(&workspace_id)
|
||||
@@ -474,12 +486,10 @@ mod tests {
|
||||
let first_token = commit_token(&pool, ¤t, &[chunk("first")]).await.unwrap();
|
||||
let requested = [crate::runtime::types::DocumentEmbeddingProjectionInput {
|
||||
skip_reason: None,
|
||||
root_revision: None,
|
||||
doc_id: "doc".to_string(),
|
||||
revision: "content-1".to_string(),
|
||||
revision: "1000".to_string(),
|
||||
source_hash: "descriptor".to_string(),
|
||||
units: Vec::new(),
|
||||
deleted: None,
|
||||
}];
|
||||
assert_eq!(
|
||||
super::super::source::document_readiness(&pool, &workspace_id, &requested)
|
||||
@@ -527,7 +537,7 @@ mod tests {
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(status, "ready");
|
||||
sqlx::query("UPDATE embedding_sources SET content_revision='content-2' WHERE id=$1")
|
||||
sqlx::query("UPDATE embedding_sources SET content_revision='2000' WHERE id=$1")
|
||||
.bind(source_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
@@ -541,18 +551,23 @@ mod tests {
|
||||
let refreshed = claim_projection(&pool, "worker-c").await.unwrap().unwrap();
|
||||
let second_token = commit_token(&pool, &refreshed, &[chunk("second")]).await.unwrap();
|
||||
assert_ne!(first_token, second_token);
|
||||
sqlx::query("UPDATE snapshots SET updated_at=to_timestamp(2) WHERE workspace_id=$1 AND guid='doc'")
|
||||
.bind(&workspace_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let updated = [crate::runtime::types::DocumentEmbeddingProjectionInput {
|
||||
revision: "content-2".to_string(),
|
||||
revision: "2000".to_string(),
|
||||
..requested[0].clone()
|
||||
}];
|
||||
super::super::source::sync_documents(&pool, &workspace_id, &updated, false, i32::MAX)
|
||||
super::super::source::sync_documents(&pool, &workspace_id, &updated, i32::MAX)
|
||||
.await
|
||||
.unwrap();
|
||||
let recipe_changed = claim_projection(&pool, "worker-d").await.unwrap().unwrap();
|
||||
commit_token(&pool, &recipe_changed, &[chunk("updated recipe")])
|
||||
.await
|
||||
.unwrap();
|
||||
super::super::source::sync_documents(&pool, &workspace_id, &updated, false, i32::MAX)
|
||||
super::super::source::sync_documents(&pool, &workspace_id, &updated, i32::MAX)
|
||||
.await
|
||||
.unwrap();
|
||||
let status: String = sqlx::query_scalar("SELECT status FROM embedding_projections WHERE source_id=$1")
|
||||
@@ -582,12 +597,17 @@ mod tests {
|
||||
assert_eq!(result.chunks, 1);
|
||||
assert_eq!(result.indexes, 1);
|
||||
|
||||
sqlx::query("UPDATE snapshots SET updated_at=to_timestamp(3) WHERE workspace_id=$1 AND guid='doc'")
|
||||
.bind(&workspace_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let skipped = [crate::runtime::types::DocumentEmbeddingProjectionInput {
|
||||
revision: "content-3".to_string(),
|
||||
revision: "3000".to_string(),
|
||||
skip_reason: Some("document_contains_nul".to_string()),
|
||||
..updated[0].clone()
|
||||
}];
|
||||
super::super::source::sync_documents(&pool, &workspace_id, &skipped, false, i32::MAX)
|
||||
super::super::source::sync_documents(&pool, &workspace_id, &skipped, i32::MAX)
|
||||
.await
|
||||
.unwrap();
|
||||
let skipped_state: (String, Option<String>, String) = sqlx::query_as(
|
||||
@@ -600,24 +620,99 @@ mod tests {
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
skipped_state,
|
||||
(
|
||||
"failed".into(),
|
||||
Some("document_contains_nul".into()),
|
||||
"content-3".into()
|
||||
)
|
||||
("failed".into(), Some("document_contains_nul".into()), "3000".into())
|
||||
);
|
||||
assert!(claim_projection(&pool, "skip-check").await.unwrap().is_none());
|
||||
sqlx::query("UPDATE snapshots SET updated_at=to_timestamp(4) WHERE workspace_id=$1 AND guid='doc'")
|
||||
.bind(&workspace_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let repaired = [crate::runtime::types::DocumentEmbeddingProjectionInput {
|
||||
revision: "content-4".to_string(),
|
||||
revision: "4000".to_string(),
|
||||
..updated[0].clone()
|
||||
}];
|
||||
super::super::source::sync_documents(&pool, &workspace_id, &repaired, false, i32::MAX)
|
||||
super::super::source::sync_documents(&pool, &workspace_id, &repaired, i32::MAX)
|
||||
.await
|
||||
.unwrap();
|
||||
let repaired_claim = claim_projection(&pool, "repaired-worker").await.unwrap().unwrap();
|
||||
assert_eq!(repaired_claim.content_revision, "content-4");
|
||||
assert_eq!(repaired_claim.content_revision, "4000");
|
||||
assert_eq!(repaired_claim.source_id, source_id);
|
||||
|
||||
for root in [vec![0xffu8], vec![0u8, 0]] {
|
||||
sqlx::query(
|
||||
"INSERT INTO snapshots(workspace_id,guid,blob,updated_at) VALUES($1,$1,$2,now()) ON \
|
||||
CONFLICT(workspace_id,guid) DO UPDATE SET blob=excluded.blob",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(root)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
super::super::source::sync_documents(&pool, &workspace_id, &repaired, i32::MAX)
|
||||
.await
|
||||
.unwrap();
|
||||
let deleted: bool = sqlx::query_scalar("SELECT deleted_at IS NOT NULL FROM embedding_sources WHERE id=$1")
|
||||
.bind(source_id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!deleted);
|
||||
}
|
||||
let mut trash = pool.begin().await.unwrap();
|
||||
sqlx::query(
|
||||
"INSERT INTO workspace_pages(workspace_id,page_id,lifecycle_state,lifecycle_changed_at) \
|
||||
VALUES($1,'doc','trashed',now())",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.execute(&mut *trash)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("UPDATE embedding_sources SET deleted_at=now() WHERE id=$1")
|
||||
.bind(source_id)
|
||||
.execute(&mut *trash)
|
||||
.await
|
||||
.unwrap();
|
||||
trash.commit().await.unwrap();
|
||||
super::super::source::sync_documents(&pool, &workspace_id, &repaired, i32::MAX)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
sqlx::query_scalar::<_, bool>("SELECT deleted_at IS NOT NULL FROM embedding_sources WHERE id=$1")
|
||||
.bind(source_id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
sqlx::query(
|
||||
"UPDATE workspace_pages SET lifecycle_state=NULL,lifecycle_changed_at=now() WHERE workspace_id=$1 AND \
|
||||
page_id='doc'",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
super::super::source::sync_documents(&pool, &workspace_id, &requested, i32::MAX)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
sqlx::query_scalar::<_, bool>("SELECT deleted_at IS NOT NULL FROM embedding_sources WHERE id=$1")
|
||||
.bind(source_id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
super::super::source::sync_documents(&pool, &workspace_id, &repaired, i32::MAX)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
!sqlx::query_scalar::<_, bool>("SELECT deleted_at IS NOT NULL FROM embedding_sources WHERE id=$1")
|
||||
.bind(source_id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
|
||||
crate::runtime::migrations::migrate_runtime_tables(&pool).await.unwrap();
|
||||
let cleanup_claim = repaired_claim;
|
||||
let commit_pool = sqlx::postgres::PgPoolOptions::new()
|
||||
@@ -730,7 +825,7 @@ mod tests {
|
||||
assert_eq!(count, 0, "workspace cleanup left rows in {table}");
|
||||
}
|
||||
let unavailable = [crate::runtime::types::DocumentEmbeddingProjectionInput {
|
||||
revision: "content-2".to_string(),
|
||||
revision: "2000".to_string(),
|
||||
..requested[0].clone()
|
||||
}];
|
||||
assert_eq!(
|
||||
|
||||
@@ -63,13 +63,12 @@ impl BackendRuntime {
|
||||
.sync_workspace(&input.workspace_id, input.enabled, target)
|
||||
.await
|
||||
.map_err(to_napi_error)?;
|
||||
let reconcile_documents = input.reconcile_documents.unwrap_or(false);
|
||||
if let Some(documents) = input.documents {
|
||||
if input.wait_for_ready_ms.is_some() && state.active_index_id.is_none() {
|
||||
return Err(napi_error("embedding_selected_sources_unavailable"));
|
||||
}
|
||||
embedding
|
||||
.sync_documents(&input.workspace_id, &documents, reconcile_documents, priority)
|
||||
.sync_documents(&input.workspace_id, &documents, priority)
|
||||
.await
|
||||
.map_err(to_napi_error)?;
|
||||
if let Some(wait_ms) = input.wait_for_ready_ms {
|
||||
@@ -82,12 +81,8 @@ impl BackendRuntime {
|
||||
.await
|
||||
.map_err(to_napi_error)?;
|
||||
}
|
||||
} else if reconcile_documents {
|
||||
embedding
|
||||
.reconcile_documents(&input.workspace_id)
|
||||
.await
|
||||
.map_err(to_napi_error)?;
|
||||
}
|
||||
|
||||
Ok(types::RuntimeEmbeddingWorkspaceState {
|
||||
workspace_id: state.workspace_id,
|
||||
active_index_id: state.active_index_id.map(|id| id.to_string()),
|
||||
|
||||
@@ -30,12 +30,15 @@ mod search;
|
||||
mod strict_quota;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod workspace_state;
|
||||
use std::{
|
||||
sync::{Arc, RwLock},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use byok::LocalLeasePayload;
|
||||
use doc_writer::append_updates_in;
|
||||
pub(super) use doc_writer::{lock_permission_generation, validate_doc_updates};
|
||||
use embedding::register_artifact_source;
|
||||
use napi::{Result, Status, bindgen_prelude::Buffer, threadsafe_function::ThreadsafeFunction};
|
||||
#[cfg(test)]
|
||||
@@ -60,11 +63,16 @@ use self::{
|
||||
use super::object_storage::ObjectStorageService;
|
||||
pub(crate) use super::types;
|
||||
pub(super) use super::{
|
||||
BackendRuntimeConfig, InviteQuotaConfig, RedisRuntimeConfig, RuntimeError, RuntimeResult,
|
||||
BackendRuntimeConfig, InviteQuotaConfig, RedisRuntimeConfig, RuntimeError, RuntimeResult, WorkspaceDocState,
|
||||
ensure_doc_not_deleted_in, ensure_workspace_sync_protocol_in, is_ordinary_workspace_doc, load_doc_states_in,
|
||||
load_workspace_doc_states_in, load_workspace_doc_states_page_in,
|
||||
migrations::{embedding_schema_health, migrate_all_tables},
|
||||
napi_error, to_napi_error, webpki_tls_config,
|
||||
};
|
||||
pub(super) use crate::runtime::storage_runtime::{load_current_doc_in, load_current_doc_parts_in, merge_current_doc};
|
||||
use crate::{
|
||||
blocking,
|
||||
doc::try_validation_slot,
|
||||
llm::{
|
||||
ByokLocalLeaseOutput, ByokPolicyOutput, ByokProbeResultOutput, ByokProfileOutput, CreateByokLocalLeaseInput,
|
||||
CreateByokProfileInput, ProbeByokDraftInput, ProbeByokProfileInput, ReorderByokProfilesInput,
|
||||
@@ -210,7 +218,6 @@ impl BackendRuntime {
|
||||
workspace_id: workspace_id.to_string(),
|
||||
enabled,
|
||||
documents: None,
|
||||
reconcile_documents: None,
|
||||
priority: None,
|
||||
wait_for_ready_ms: None,
|
||||
})
|
||||
@@ -319,3 +326,25 @@ impl BackendRuntime {
|
||||
}
|
||||
|
||||
use super::{entitlement_input_error, parse_quantity, parse_target_type};
|
||||
|
||||
pub(in crate::runtime) async fn lock_current_doc_read(
|
||||
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||
workspace_id: &str,
|
||||
doc_id: &str,
|
||||
) -> RuntimeResult<()> {
|
||||
domain_command::lock_workspace_storage_shared(transaction, workspace_id).await?;
|
||||
domain_command::lock_workspace_doc_update(transaction, workspace_id, doc_id).await
|
||||
}
|
||||
|
||||
pub(super) async fn try_lock_current_doc_read(
|
||||
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||
workspace_id: &str,
|
||||
doc_id: &str,
|
||||
) -> RuntimeResult<bool> {
|
||||
if !super::try_lock_workspace_storage_shared_transaction(transaction, workspace_id).await? {
|
||||
return Ok(false);
|
||||
}
|
||||
domain_command::try_lock_workspace_doc_update(transaction, workspace_id, doc_id).await
|
||||
}
|
||||
|
||||
pub(super) use super::{CurrentDoc, CurrentDocUpdate};
|
||||
@@ -179,6 +179,24 @@ impl PermissionAuthorizer {
|
||||
Ok(doc_decisions(decision))
|
||||
}
|
||||
|
||||
pub(in crate::runtime::backend_runtime) async fn authorize_workspace_sync_docs_in(
|
||||
&self,
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &str,
|
||||
actor_user_id: &str,
|
||||
doc_ids: &[String],
|
||||
) -> RuntimeResult<BTreeMap<String, Decision>> {
|
||||
let mut request = doc_request(doc_ids, DocAction::Read);
|
||||
request.workspace_actions.push(WorkspaceAction::Sync.into());
|
||||
let decision = self
|
||||
.authorize_typed_request_in(transaction, workspace_id, Some(actor_user_id), request)
|
||||
.await?;
|
||||
if !decision.workspace.first().is_some_and(|decision| decision.allowed) {
|
||||
return Err(RuntimeError::invalid_input("space_access_denied"));
|
||||
}
|
||||
Ok(doc_decisions(decision))
|
||||
}
|
||||
|
||||
async fn authorize_typed(
|
||||
&self,
|
||||
workspace_id: &str,
|
||||
@@ -221,49 +239,84 @@ impl PermissionAuthorizer {
|
||||
command: &DomainCommand,
|
||||
quota: Option<CommandQuotaFacts<'_>>,
|
||||
) -> RuntimeResult<CommandAuthorizationDecision> {
|
||||
Ok(
|
||||
self
|
||||
.authorize_commands_in(
|
||||
transaction,
|
||||
actor_user_id,
|
||||
workspace_id,
|
||||
doc_id,
|
||||
std::slice::from_ref(command),
|
||||
quota,
|
||||
)
|
||||
.await?
|
||||
.pop()
|
||||
.expect("single command decision"),
|
||||
)
|
||||
}
|
||||
|
||||
pub(in crate::runtime::backend_runtime) async fn authorize_commands_in(
|
||||
&self,
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
actor_user_id: &str,
|
||||
workspace_id: &str,
|
||||
doc_id: Option<&str>,
|
||||
commands: &[DomainCommand],
|
||||
quota: Option<CommandQuotaFacts<'_>>,
|
||||
) -> RuntimeResult<Vec<CommandAuthorizationDecision>> {
|
||||
let snapshot = self
|
||||
.store
|
||||
.command_snapshot_in(transaction, workspace_id, actor_user_id, doc_id)
|
||||
.await?;
|
||||
let decision = authorize_command(
|
||||
command,
|
||||
CommandFacts {
|
||||
acl: &snapshot.facts,
|
||||
access_grant: &snapshot.grant,
|
||||
quota,
|
||||
},
|
||||
);
|
||||
if decision.allowed {
|
||||
Ok(decision)
|
||||
} else {
|
||||
Err(RuntimeError::invalid_input(match (decision.denial_reason, command) {
|
||||
(Some(CommandDenialReason::WorkspaceOwnerCannotLeave), _) => "workspace_owner_cannot_leave".to_string(),
|
||||
(Some(CommandDenialReason::CannotRevokeSelf), _) => "cannot_revoke_self".to_string(),
|
||||
(Some(CommandDenialReason::OwnerMustTransfer), DomainCommand::TransitionDocRole { .. }) => {
|
||||
"doc_owner_must_transfer".to_string()
|
||||
}
|
||||
(Some(CommandDenialReason::OwnerMustTransfer), _) => "workspace_owner_must_transfer".to_string(),
|
||||
(Some(CommandDenialReason::TargetMemberMustBeActive), _) => "target_member_not_active".to_string(),
|
||||
(Some(CommandDenialReason::ActiveMemberRequired), _) => "active_member_required".to_string(),
|
||||
(Some(CommandDenialReason::WorkspaceNotFound), _) => "workspace_not_found".to_string(),
|
||||
(Some(CommandDenialReason::WorkspaceReadonly), _) => "workspace_readonly".to_string(),
|
||||
(Some(CommandDenialReason::QuotaFactsUnavailable), _) => "command_quota_unavailable".to_string(),
|
||||
(
|
||||
Some(CommandDenialReason::Permission(_)),
|
||||
DomainCommand::MutateComment { .. } | DomainCommand::MutateReply { .. },
|
||||
) => "comment_mutation_denied".to_string(),
|
||||
(Some(CommandDenialReason::Permission(permission)), _) => {
|
||||
format!(
|
||||
"domain_permission_denied:{}",
|
||||
match permission {
|
||||
CommandPermission::Workspace(action) => action.as_str(),
|
||||
CommandPermission::Doc(action) => action.as_str(),
|
||||
}
|
||||
)
|
||||
}
|
||||
(None, _) => "domain_permission_denied".to_string(),
|
||||
}))
|
||||
if doc_id.is_some_and(|doc_id| snapshot.deleted_docs.iter().any(|deleted| deleted == doc_id)) {
|
||||
return Err(RuntimeError::invalid_input("doc_not_found"));
|
||||
}
|
||||
if doc_id.is_some_and(|doc_id| snapshot.subject_denied_docs.iter().any(|denied| denied == doc_id)) {
|
||||
return Err(RuntimeError::invalid_input("domain_permission_denied"));
|
||||
}
|
||||
let mut decisions = Vec::with_capacity(commands.len());
|
||||
for command in commands {
|
||||
let decision = authorize_command(
|
||||
command,
|
||||
CommandFacts {
|
||||
acl: &snapshot.facts,
|
||||
access_grant: &snapshot.grant,
|
||||
quota,
|
||||
},
|
||||
);
|
||||
if decision.allowed {
|
||||
decisions.push(decision);
|
||||
} else {
|
||||
return Err(RuntimeError::invalid_input(match (decision.denial_reason, command) {
|
||||
(Some(CommandDenialReason::WorkspaceOwnerCannotLeave), _) => "workspace_owner_cannot_leave".to_string(),
|
||||
(Some(CommandDenialReason::CannotRevokeSelf), _) => "cannot_revoke_self".to_string(),
|
||||
(Some(CommandDenialReason::OwnerMustTransfer), DomainCommand::TransitionDocRole { .. }) => {
|
||||
"doc_owner_must_transfer".to_string()
|
||||
}
|
||||
(Some(CommandDenialReason::OwnerMustTransfer), _) => "workspace_owner_must_transfer".to_string(),
|
||||
(Some(CommandDenialReason::TargetMemberMustBeActive), _) => "target_member_not_active".to_string(),
|
||||
(Some(CommandDenialReason::ActiveMemberRequired), _) => "active_member_required".to_string(),
|
||||
(Some(CommandDenialReason::WorkspaceNotFound), _) => "workspace_not_found".to_string(),
|
||||
(Some(CommandDenialReason::WorkspaceReadonly), _) => "workspace_readonly".to_string(),
|
||||
(Some(CommandDenialReason::QuotaFactsUnavailable), _) => "command_quota_unavailable".to_string(),
|
||||
(
|
||||
Some(CommandDenialReason::Permission(_)),
|
||||
DomainCommand::MutateComment { .. } | DomainCommand::MutateReply { .. },
|
||||
) => "comment_mutation_denied".to_string(),
|
||||
(Some(CommandDenialReason::Permission(permission)), _) => {
|
||||
format!(
|
||||
"domain_permission_denied:{}",
|
||||
match permission {
|
||||
CommandPermission::Workspace(action) => action.as_str(),
|
||||
CommandPermission::Doc(action) => action.as_str(),
|
||||
}
|
||||
)
|
||||
}
|
||||
(None, _) => "domain_permission_denied".to_string(),
|
||||
}));
|
||||
}
|
||||
}
|
||||
Ok(decisions)
|
||||
}
|
||||
|
||||
pub(in crate::runtime::backend_runtime) async fn authorize_search(
|
||||
@@ -327,7 +380,18 @@ impl PermissionAuthorizer {
|
||||
}
|
||||
|
||||
fn evaluate_snapshot(snapshot: PermissionSnapshot) -> RuntimeResult<AuthorizedPermission> {
|
||||
let decision = authorize(&snapshot.request, &snapshot.facts, &snapshot.grant);
|
||||
let mut decision = authorize(&snapshot.request, &snapshot.facts, &snapshot.grant);
|
||||
for doc in &mut decision.docs {
|
||||
if snapshot.deleted_docs.contains(&doc.doc_id) || snapshot.subject_denied_docs.contains(&doc.doc_id) {
|
||||
doc.effective_role = None;
|
||||
doc.preview = None;
|
||||
for action in &mut doc.decisions {
|
||||
action.allowed = false;
|
||||
action.source = None;
|
||||
action.denial_reason = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
let effective_workspace_role = decision.effective_workspace_role;
|
||||
let output = permission_evaluation_output(decision.clone());
|
||||
Ok(AuthorizedPermission {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use affine_core::access_control::{
|
||||
AccessContext, AclFacts, AuthorizationRequest, Deployment as CoreDeployment, DocAclFacts, DocAuthorizationRequest,
|
||||
DocRole, EntitlementFact as CoreEntitlementFact, RequestedDocAction, RequestedWorkspaceAction, TargetType,
|
||||
WorkspaceRole, resolve_entitlements,
|
||||
DocRole, EntitlementFact as CoreEntitlementFact, RequestedDocAction, RequestedWorkspaceAction,
|
||||
ReservedDocumentAccessDecision, TargetType, WorkspaceRole, authorize_reserved_document, classify_reserved_document,
|
||||
resolve_entitlements,
|
||||
};
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::Deserialize;
|
||||
@@ -30,6 +31,7 @@ struct SnapshotRow {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct DocFact {
|
||||
deleted: bool,
|
||||
doc_id: String,
|
||||
visibility: Option<String>,
|
||||
public_role: Option<String>,
|
||||
@@ -167,6 +169,16 @@ impl PermissionStore {
|
||||
.iter()
|
||||
.map(|doc| doc.doc_id.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let subject_denied_docs = doc_ids
|
||||
.iter()
|
||||
.filter(|doc_id| {
|
||||
authorize_reserved_document(
|
||||
actor_user_id.unwrap_or_default(),
|
||||
classify_reserved_document(workspace_id, doc_id),
|
||||
) == ReservedDocumentAccessDecision::Denied
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
let row = sqlx::query(
|
||||
r#"SELECT jsonb_build_object(
|
||||
'visibility', policy.visibility,
|
||||
@@ -179,6 +191,7 @@ impl PermissionStore {
|
||||
'docs', coalesce((
|
||||
SELECT jsonb_agg(jsonb_build_object(
|
||||
'docId', candidate.doc_id,
|
||||
'deleted', EXISTS(SELECT 1 FROM workspace_pages page WHERE page.workspace_id=workspace.id AND page.page_id=candidate.doc_id AND page.lifecycle_state='deleted'),
|
||||
'visibility', doc_policy.visibility,
|
||||
'publicRole', CASE WHEN doc_policy.published_at IS NOT NULL AND EXISTS(
|
||||
SELECT 1 FROM workspace_pages page
|
||||
@@ -241,6 +254,8 @@ impl PermissionStore {
|
||||
})
|
||||
.collect();
|
||||
return Ok(PermissionSnapshot {
|
||||
subject_denied_docs,
|
||||
deleted_docs: Vec::new(),
|
||||
request: core_request,
|
||||
facts: AclFacts {
|
||||
workspace_exists: false,
|
||||
@@ -341,6 +356,12 @@ impl PermissionStore {
|
||||
&& matches!(facts.role.as_deref(), Some("member" | "admin" | "owner"));
|
||||
let assigned_workspace_role = facts.role.clone().filter(|_| active_member);
|
||||
let sharing_enabled = facts.sharing_enabled;
|
||||
let deleted_docs = facts
|
||||
.docs
|
||||
.iter()
|
||||
.filter(|doc| doc.deleted)
|
||||
.map(|doc| doc.doc_id.clone())
|
||||
.collect();
|
||||
let docs = core_request
|
||||
.doc_actions
|
||||
.iter()
|
||||
@@ -358,6 +379,8 @@ impl PermissionStore {
|
||||
})
|
||||
.collect::<RuntimeResult<Vec<_>>>()?;
|
||||
Ok(PermissionSnapshot {
|
||||
subject_denied_docs,
|
||||
deleted_docs,
|
||||
request: core_request,
|
||||
facts: AclFacts {
|
||||
workspace_exists: true,
|
||||
|
||||
@@ -175,6 +175,89 @@ async fn canonical_doc_acl_facts_are_evaluated_without_search_state() {
|
||||
readable,
|
||||
["doc".to_string(), "hidden".to_string()].into_iter().collect()
|
||||
);
|
||||
sqlx::query("UPDATE workspace_members SET role='owner' WHERE workspace_id=$1 AND user_id=$2")
|
||||
.bind(&workspace_id)
|
||||
.bind(&user_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
use affine_core::access_control::{DocAction, DomainCommand};
|
||||
for (doc_id, allowed) in [
|
||||
(format!("userdata${user_id}${workspace_id}$settings"), true),
|
||||
(format!("userdata$someone-else${workspace_id}$settings"), false),
|
||||
(format!("db${workspace_id}$docProperties"), true),
|
||||
(format!("db${workspace_id}$unknown"), false),
|
||||
] {
|
||||
let mut transaction = pool.begin().await.unwrap();
|
||||
for action in [DocAction::Read, DocAction::Update, DocAction::HistoryRead] {
|
||||
assert_eq!(
|
||||
authorizer
|
||||
.authorize_doc_action_in(&mut transaction, &workspace_id, Some(&user_id), &doc_id, action)
|
||||
.await
|
||||
.unwrap()
|
||||
.allowed,
|
||||
allowed,
|
||||
"{doc_id} {action:?}"
|
||||
);
|
||||
}
|
||||
let quota = super::super::load_command_quota_in(&mut transaction, Deployment::Cloud, &workspace_id, false)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let command = authorizer
|
||||
.authorize_command_in(
|
||||
&mut transaction,
|
||||
&user_id,
|
||||
&workspace_id,
|
||||
Some(&doc_id),
|
||||
&DomainCommand::RecoverDoc { doc_id: doc_id.clone() },
|
||||
Some(quota.facts()),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(command.is_ok(), allowed, "{doc_id}: {command:?}");
|
||||
transaction.rollback().await.unwrap();
|
||||
}
|
||||
sqlx::query("INSERT INTO workspace_pages(workspace_id,page_id,published_at) VALUES($1,'public',now())")
|
||||
.bind(&workspace_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"INSERT INTO doc_access_policies(workspace_id,doc_id,visibility,public_role,published_at) \
|
||||
VALUES($1,'public','public','external',now())",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("UPDATE workspace_members SET state='suspended' WHERE workspace_id=$1 AND user_id=$2")
|
||||
.bind(&workspace_id)
|
||||
.bind(&user_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut transaction = pool.begin().await.unwrap();
|
||||
assert!(
|
||||
authorizer
|
||||
.authorize_doc_action_in(
|
||||
&mut transaction,
|
||||
&workspace_id,
|
||||
Some(&user_id),
|
||||
"public",
|
||||
DocAction::Read
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.allowed
|
||||
);
|
||||
assert!(
|
||||
authorizer
|
||||
.authorize_workspace_sync_docs_in(&mut transaction, &workspace_id, &user_id, &["public".into()])
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("space_access_denied")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -25,6 +25,8 @@ pub(in crate::runtime::backend_runtime) struct AuthorizedSearchScope {
|
||||
}
|
||||
|
||||
pub(super) struct PermissionSnapshot {
|
||||
pub(super) subject_denied_docs: Vec<String>,
|
||||
pub(super) deleted_docs: Vec<String>,
|
||||
pub(super) request: AuthorizationRequest,
|
||||
pub(super) facts: AclFacts,
|
||||
pub(super) grant: AccessGrant,
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use affine_core::access_control::{
|
||||
ReservedDocumentClassification, UserdataTable, WorkspaceDatabaseTable, classify_reserved_document,
|
||||
userdata_document_id,
|
||||
ReservedDocumentClassification, UserdataTable, classify_reserved_document, userdata_document_id,
|
||||
};
|
||||
use affine_doc_loader::{
|
||||
apply_favorites, apply_workspace_db, evaluate_collection, project_orm_records, project_workspace_root_facts,
|
||||
@@ -11,7 +10,8 @@ use chrono::Utc;
|
||||
use sqlx::{PgPool, Row};
|
||||
|
||||
use super::{
|
||||
RuntimeError, RuntimeResult,
|
||||
RuntimeError, RuntimeResult, is_ordinary_workspace_doc, load_current_doc_in, load_doc_states_in,
|
||||
load_workspace_doc_states_in,
|
||||
permission::{PermissionAuthorizer, PermissionTelemetry},
|
||||
types,
|
||||
};
|
||||
@@ -50,38 +50,90 @@ impl ScopeCompiler {
|
||||
input.preferred_source_ids.unwrap_or_default(),
|
||||
));
|
||||
}
|
||||
let root = load_current_doc(&self.pool, &input.workspace_id, &input.workspace_id)
|
||||
.await?
|
||||
.ok_or_else(|| RuntimeError::invalid_state("workspace root doc is missing"))?;
|
||||
let mut facts = project_workspace_root_facts(&root.blob)
|
||||
.map_err(|error| RuntimeError::invalid_state(format!("workspace scope projection failed: {error}")))?;
|
||||
if !facts.complete {
|
||||
return Err(RuntimeError::invalid_state("workspace root projection is incomplete"));
|
||||
let mut transaction = self
|
||||
.pool
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("begin workspace scope read", error))?;
|
||||
sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("configure workspace scope snapshot", error))?;
|
||||
let collection = input.selectors.iter().any(|selector| selector.kind == "collection");
|
||||
let favorite = collection || input.selectors.iter().any(|selector| selector.kind == "favorite");
|
||||
let metadata = collection || input.selectors.iter().any(|selector| selector.kind == "tag");
|
||||
let states = if metadata || favorite {
|
||||
load_workspace_doc_states_in(&mut transaction, &input.workspace_id).await?
|
||||
} else {
|
||||
let doc_ids = input
|
||||
.selectors
|
||||
.iter()
|
||||
.filter(|selector| selector.kind == "document")
|
||||
.map(|selector| selector.id.clone())
|
||||
.collect::<Vec<_>>();
|
||||
load_doc_states_in(&mut transaction, &input.workspace_id, &doc_ids).await?
|
||||
};
|
||||
let mut facts = affine_doc_loader::WorkspaceFacts {
|
||||
complete: false,
|
||||
documents: Vec::new(),
|
||||
tags: Vec::new(),
|
||||
collections: Vec::new(),
|
||||
};
|
||||
if metadata {
|
||||
match load_current_doc_in(&mut transaction, &input.workspace_id, &input.workspace_id).await {
|
||||
Ok(Some(root)) => {
|
||||
if let Ok(projected) = project_workspace_root_facts(&root.blob) {
|
||||
facts = projected;
|
||||
}
|
||||
}
|
||||
Ok(None) | Err(RuntimeError::InvalidState(_)) => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
let properties_id = format!("db${}$docProperties", input.workspace_id);
|
||||
if classify_reserved_document(&input.workspace_id, &properties_id)
|
||||
!= (ReservedDocumentClassification::WorkspaceDatabase {
|
||||
table: WorkspaceDatabaseTable::DocProperties,
|
||||
let mut metadata = facts
|
||||
.documents
|
||||
.into_iter()
|
||||
.map(|doc| (doc.id.clone(), doc))
|
||||
.collect::<std::collections::BTreeMap<_, _>>();
|
||||
facts.documents = states
|
||||
.into_iter()
|
||||
.filter(|doc| is_ordinary_workspace_doc(&input.workspace_id, &doc.doc_id))
|
||||
.map(|state| {
|
||||
let mut doc = metadata
|
||||
.remove(&state.doc_id)
|
||||
.unwrap_or_else(|| affine_doc_loader::DocumentFacts {
|
||||
id: state.doc_id,
|
||||
..Default::default()
|
||||
});
|
||||
doc.trash = state.lifecycle.as_deref() == Some("trashed");
|
||||
doc
|
||||
})
|
||||
{
|
||||
return Err(RuntimeError::invalid_state("workspace properties subject is invalid"));
|
||||
.collect();
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("commit workspace scope read", error))?;
|
||||
|
||||
if collection {
|
||||
let properties_id = format!("db${}$docProperties", input.workspace_id);
|
||||
if let Some(properties) = load_current_doc(&self.pool, &input.workspace_id, &properties_id).await? {
|
||||
let records = project_orm_records(&properties.blob)
|
||||
.map_err(|error| RuntimeError::invalid_state(format!("workspace properties projection failed: {error}")))?;
|
||||
apply_workspace_db(&mut facts.documents, &records);
|
||||
}
|
||||
self
|
||||
.enrich_product_facts(&input.workspace_id, &mut facts.documents)
|
||||
.await?;
|
||||
}
|
||||
if let Some(properties) = load_current_doc(&self.pool, &input.workspace_id, &properties_id).await? {
|
||||
let records = project_orm_records(&properties.blob)
|
||||
.map_err(|error| RuntimeError::invalid_state(format!("workspace properties projection failed: {error}")))?;
|
||||
apply_workspace_db(&mut facts.documents, &records);
|
||||
if favorite {
|
||||
let favorite_id = userdata_document_id(&input.user_id, &input.workspace_id, UserdataTable::Favorite)
|
||||
.map_err(|_| RuntimeError::invalid_input("userdata_subject_denied"))?;
|
||||
if let Some(favorite) = load_current_doc(&self.pool, &input.workspace_id, &favorite_id).await? {
|
||||
let records = project_orm_records(&favorite.blob)
|
||||
.map_err(|error| RuntimeError::invalid_state(format!("favorite projection failed: {error}")))?;
|
||||
apply_favorites(&mut facts.documents, &records);
|
||||
}
|
||||
}
|
||||
let favorite_id = userdata_document_id(&input.user_id, &input.workspace_id, UserdataTable::Favorite)
|
||||
.map_err(|_| RuntimeError::invalid_input("userdata_subject_denied"))?;
|
||||
if let Some(favorite) = load_current_doc(&self.pool, &input.workspace_id, &favorite_id).await? {
|
||||
let records = project_orm_records(&favorite.blob)
|
||||
.map_err(|error| RuntimeError::invalid_state(format!("favorite projection failed: {error}")))?;
|
||||
apply_favorites(&mut facts.documents, &records);
|
||||
}
|
||||
self
|
||||
.enrich_product_facts(&input.workspace_id, &mut facts.documents)
|
||||
.await?;
|
||||
|
||||
let readable = self
|
||||
.authorizer
|
||||
@@ -91,6 +143,12 @@ impl ScopeCompiler {
|
||||
facts.documents.iter().map(|doc| doc.id.clone()).collect(),
|
||||
)
|
||||
.await?;
|
||||
let active = facts
|
||||
.documents
|
||||
.iter()
|
||||
.filter(|doc| !doc.trash && readable.contains(&doc.id))
|
||||
.map(|doc| doc.id.clone())
|
||||
.collect::<BTreeSet<_>>();
|
||||
let mut required_docs = BTreeSet::new();
|
||||
let mut required_artifacts = BTreeSet::new();
|
||||
for selector in &input.selectors {
|
||||
@@ -106,7 +164,7 @@ impl ScopeCompiler {
|
||||
.iter()
|
||||
.find(|tag| tag.id == selector.id)
|
||||
.ok_or_else(|| RuntimeError::invalid_input("scope_selector_not_found"))?;
|
||||
required_docs.extend(tag.document_ids.iter().filter(|id| readable.contains(*id)).cloned());
|
||||
required_docs.extend(tag.document_ids.iter().filter(|id| active.contains(*id)).cloned());
|
||||
}
|
||||
"collection" => {
|
||||
let collection = facts
|
||||
@@ -116,14 +174,14 @@ impl ScopeCompiler {
|
||||
.ok_or_else(|| RuntimeError::invalid_input("scope_selector_not_found"))?;
|
||||
let resolved = evaluate_collection(collection, &facts.documents, Utc::now())
|
||||
.map_err(|error| RuntimeError::invalid_input(format!("scope_selector_unsupported: {error}")))?;
|
||||
required_docs.extend(resolved.into_iter().filter(|id| readable.contains(id)));
|
||||
required_docs.extend(resolved.into_iter().filter(|id| active.contains(id)));
|
||||
}
|
||||
"favorite" => {
|
||||
required_docs.extend(
|
||||
facts
|
||||
.documents
|
||||
.iter()
|
||||
.filter(|doc| doc.favorite && readable.contains(&doc.id))
|
||||
.filter(|doc| doc.favorite && active.contains(&doc.id))
|
||||
.map(|doc| doc.id.clone()),
|
||||
);
|
||||
}
|
||||
@@ -335,6 +393,7 @@ mod tests {
|
||||
.unwrap();
|
||||
for (guid, blob) in [
|
||||
(workspace_id.as_str(), root),
|
||||
(doc_id.as_str(), vec![0, 0]),
|
||||
(favorite_doc_id.as_str(), favorite.encode_update_v1().unwrap()),
|
||||
] {
|
||||
sqlx::query("INSERT INTO snapshots(workspace_id,guid,blob,updated_at) VALUES($1,$2,$3,clock_timestamp())")
|
||||
@@ -396,6 +455,72 @@ mod tests {
|
||||
std::slice::from_ref(&doc_id)
|
||||
);
|
||||
|
||||
let retained_sources: Vec<(String, Vec<u8>)> =
|
||||
sqlx::query_as("SELECT guid,blob FROM snapshots WHERE workspace_id=$1 AND guid<>$2")
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.fetch_all(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("UPDATE snapshots SET blob=$3 WHERE workspace_id=$1 AND guid<>$2")
|
||||
.bind(&workspace_id)
|
||||
.bind(&doc_id)
|
||||
.bind(&[255u8][..])
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let properties_id = format!("db${workspace_id}$docProperties");
|
||||
sqlx::query("INSERT INTO snapshots(workspace_id,guid,blob,updated_at) VALUES($1,$2,$3,clock_timestamp())")
|
||||
.bind(&workspace_id)
|
||||
.bind(&properties_id)
|
||||
.bind(&[255u8][..])
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
for kind in ["document", "artifact"] {
|
||||
let compiled = compiler
|
||||
.compile(types::CompileScopeInput {
|
||||
workspace_id: workspace_id.clone(),
|
||||
user_id: collaborator_id.clone(),
|
||||
selectors: vec![types::ScopeSelectorInput {
|
||||
kind: kind.into(),
|
||||
id: if kind == "document" {
|
||||
doc_id.clone()
|
||||
} else {
|
||||
uuid::Uuid::new_v4().to_string()
|
||||
},
|
||||
name: None,
|
||||
source: "draft".into(),
|
||||
}],
|
||||
preferred_source_ids: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
compiled.required_doc_ids,
|
||||
if kind == "document" {
|
||||
vec![doc_id.clone()]
|
||||
} else {
|
||||
vec![]
|
||||
}
|
||||
);
|
||||
}
|
||||
for (guid, blob) in retained_sources {
|
||||
sqlx::query("UPDATE snapshots SET blob=$3 WHERE workspace_id=$1 AND guid=$2")
|
||||
.bind(&workspace_id)
|
||||
.bind(guid)
|
||||
.bind(blob)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
sqlx::query("DELETE FROM snapshots WHERE workspace_id=$1 AND guid=$2")
|
||||
.bind(&workspace_id)
|
||||
.bind(&properties_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
sqlx::query("DELETE FROM workspace_members WHERE workspace_id=$1 AND user_id=$2")
|
||||
.bind(&workspace_id)
|
||||
.bind(&collaborator_id)
|
||||
|
||||
@@ -9,6 +9,7 @@ mod types;
|
||||
mod worker;
|
||||
|
||||
use generation::{ActiveGeneration, activate, cleanup_retired_generation, config_hash, ensure, fail, load_active};
|
||||
#[cfg(test)]
|
||||
pub(super) use projection::project_current_doc;
|
||||
use projection::{ProjectionInput, project_document};
|
||||
use provider::{SearchChange, SearchProvider, projection_external_id};
|
||||
@@ -20,6 +21,7 @@ pub(super) use types::{RuntimeAggregateRequest, RuntimeSearchRequest};
|
||||
use worker::{reconcile_workspace, sweep_generation_orphans};
|
||||
|
||||
use super::{
|
||||
blocking, is_ordinary_workspace_doc, load_workspace_doc_states_in,
|
||||
permission::{AuthorizedSearchScope, DocReadScope, PermissionAuthorizer, PermissionTelemetry, SearchActor},
|
||||
webpki_tls_config,
|
||||
};
|
||||
|
||||
@@ -2,6 +2,7 @@ use serde_json::{Value, json};
|
||||
use sqlx::{PgPool, Row};
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
use super::blocking;
|
||||
use crate::{
|
||||
permission::doc_role_allows,
|
||||
runtime::{
|
||||
@@ -30,8 +31,7 @@ pub(in crate::runtime::backend_runtime) async fn project_current_doc<T: Send + '
|
||||
.acquire()
|
||||
.await
|
||||
.map_err(|error| RuntimeError::invalid_state(format!("search projection admission failed: {error}")))?;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let _permit = permit;
|
||||
blocking::spawn(permit, move || {
|
||||
let current = merge_current_doc(snapshot, updates).map_err(|error| match error {
|
||||
RuntimeError::InvalidState(message) => RuntimeError::SearchSourceInvalid(message),
|
||||
error => error,
|
||||
@@ -58,15 +58,20 @@ pub(super) async fn project_document(
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(metadata) = sqlx::query(
|
||||
r#"SELECT snapshot.created_at,snapshot.updated_at,snapshot.created_by,snapshot.updated_by,
|
||||
coalesce(doc_policy.visibility,'private') AS visibility,
|
||||
doc_policy.public_role,
|
||||
coalesce(doc_policy.member_default_role,workspace_policy.member_default_doc_role,'manager') AS member_default_role
|
||||
FROM snapshots snapshot
|
||||
LEFT JOIN workspace_access_policies workspace_policy ON workspace_policy.workspace_id=snapshot.workspace_id
|
||||
LEFT JOIN doc_access_policies doc_policy
|
||||
ON doc_policy.workspace_id=snapshot.workspace_id AND doc_policy.doc_id=snapshot.guid
|
||||
WHERE snapshot.workspace_id=$1 AND snapshot.guid=$2"#,
|
||||
r#"WITH records AS (
|
||||
SELECT created_at,updated_at,created_by,updated_by FROM snapshots WHERE workspace_id=$1 AND guid=$2
|
||||
UNION ALL SELECT created_at,created_at,created_by,created_by FROM updates WHERE workspace_id=$1 AND guid=$2
|
||||
), source AS (
|
||||
SELECT min(created_at) AS created_at,max(updated_at) AS updated_at,
|
||||
(array_agg(created_by ORDER BY created_at))[1] AS created_by,
|
||||
(array_agg(updated_by ORDER BY updated_at DESC))[1] AS updated_by
|
||||
FROM records HAVING count(*) > 0
|
||||
)
|
||||
SELECT source.*,coalesce(doc_policy.visibility,'private') AS visibility,doc_policy.public_role,
|
||||
coalesce(doc_policy.member_default_role,workspace_policy.member_default_doc_role,'manager') AS member_default_role
|
||||
FROM source
|
||||
LEFT JOIN workspace_access_policies workspace_policy ON workspace_policy.workspace_id=$1
|
||||
LEFT JOIN doc_access_policies doc_policy ON doc_policy.workspace_id=$1 AND doc_policy.doc_id=$2"#,
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(doc_id)
|
||||
|
||||
@@ -8,7 +8,7 @@ use tokio::time::Instant;
|
||||
|
||||
use super::{
|
||||
ActiveGeneration, DocReadScope, RuntimeAggregateRequest, RuntimeSearchRequest, SearchActor, SearchRuntime,
|
||||
SearchTable, candidates, compile, compile_aggregate, retain_visible_nodes,
|
||||
SearchTable, candidates, compile, compile_aggregate, is_ordinary_workspace_doc, retain_visible_nodes,
|
||||
};
|
||||
use crate::runtime::{RuntimeError, RuntimeResult};
|
||||
|
||||
@@ -115,6 +115,7 @@ impl SearchRuntime {
|
||||
let candidate_tuples = candidates(result)?;
|
||||
let doc_ids = candidate_tuples
|
||||
.iter()
|
||||
.filter(|candidate| is_ordinary_workspace_doc(workspace_id, &candidate.doc_id))
|
||||
.map(|candidate| candidate.doc_id.clone())
|
||||
.collect::<BTreeSet<_>>()
|
||||
.into_iter()
|
||||
@@ -125,10 +126,13 @@ impl SearchRuntime {
|
||||
let rows = sqlx::query(
|
||||
r#"SELECT state.doc_id,state.published_source_version,state.published_permission_version
|
||||
FROM search_projection.document_states state
|
||||
JOIN snapshots source
|
||||
ON source.workspace_id=state.workspace_id AND source.guid=state.doc_id
|
||||
LEFT JOIN workspace_pages page
|
||||
ON page.workspace_id=state.workspace_id AND page.page_id=state.doc_id
|
||||
WHERE state.generation_id=$1 AND state.workspace_id=$2
|
||||
AND state.doc_id=ANY($3) AND state.published_source_exists
|
||||
AND page.lifecycle_state IS NULL
|
||||
AND (EXISTS(SELECT 1 FROM snapshots source WHERE source.workspace_id=state.workspace_id AND source.guid=state.doc_id)
|
||||
OR EXISTS(SELECT 1 FROM updates source WHERE source.workspace_id=state.workspace_id AND source.guid=state.doc_id))
|
||||
AND state.last_error IS NULL"#,
|
||||
)
|
||||
.bind(generation.id)
|
||||
|
||||
@@ -904,6 +904,29 @@ mod tests {
|
||||
{"id":"missing","_source":{"doc_id":"missing","source_version":2,"permission_version":3}}
|
||||
]
|
||||
});
|
||||
let reserved = format!("userdata$other${workspace_id}$favorite");
|
||||
sqlx::query("INSERT INTO snapshots(workspace_id,guid,blob,updated_at) VALUES($1,$2,decode('0000','hex'),now())")
|
||||
.bind(&workspace_id)
|
||||
.bind(&reserved)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"INSERT INTO \
|
||||
search_projection.document_states(generation_id,workspace_id,doc_id,target_source_version,target_source_exists,\
|
||||
target_permission_version,published_source_version,published_source_exists,published_permission_version) \
|
||||
VALUES($1,$2,$3,2,true,3,2,true,3) ON CONFLICT(generation_id,workspace_id,doc_id) DO UPDATE SET \
|
||||
published_source_version=2,published_source_exists=true,published_permission_version=3,last_error=NULL",
|
||||
)
|
||||
.bind(generation_id)
|
||||
.bind(&workspace_id)
|
||||
.bind(&reserved)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
result["nodes"].as_array_mut().unwrap().push(
|
||||
serde_json::json!({"id":"reserved", "_source":{"doc_id":reserved,"source_version":2,"permission_version":3}}),
|
||||
);
|
||||
let all_scope_result = result.clone();
|
||||
let scope = runtime
|
||||
.authorizer
|
||||
@@ -932,7 +955,7 @@ mod tests {
|
||||
assert_eq!(result["total"], 1);
|
||||
assert_eq!(result["nodes"][0]["id"], "allowed");
|
||||
|
||||
let mut result = all_scope_result;
|
||||
let mut result = all_scope_result.clone();
|
||||
runtime
|
||||
.retain_canonically_visible(
|
||||
&ActiveGeneration {
|
||||
@@ -951,6 +974,44 @@ mod tests {
|
||||
assert_eq!(result["nodes"][1]["id"], "hidden");
|
||||
assert_eq!(result["nodes"][2]["id"], "pending");
|
||||
|
||||
sqlx::query(
|
||||
"INSERT INTO workspace_pages(workspace_id,page_id,lifecycle_state,lifecycle_changed_at) \
|
||||
VALUES($1,'allowed','trashed',now())",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut trashed = all_scope_result.clone();
|
||||
runtime
|
||||
.retain_canonically_visible(
|
||||
&ActiveGeneration {
|
||||
id: generation_id,
|
||||
manifest: serde_json::json!({}),
|
||||
},
|
||||
&workspace_id,
|
||||
&user_id,
|
||||
&DocReadScope::All,
|
||||
&mut trashed,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
!trashed["nodes"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|node| node["id"] == "allowed")
|
||||
);
|
||||
sqlx::query(
|
||||
"UPDATE workspace_pages SET lifecycle_state=NULL,lifecycle_changed_at=now() WHERE workspace_id=$1 AND \
|
||||
page_id='allowed'",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let mut aggregate = serde_json::json!({
|
||||
"total":2,
|
||||
"buckets":[
|
||||
|
||||
@@ -3,7 +3,7 @@ use uuid::Uuid;
|
||||
|
||||
use super::{
|
||||
ActiveGeneration, DOCUMENT_LEASE_SECONDS, DOCUMENT_PROJECTION_FAILED, ProjectionInput, SearchChange, SearchProvider,
|
||||
SearchTable as ProviderTable, project_document, projection_external_id, provider_payload,
|
||||
SearchTable as ProviderTable, is_ordinary_workspace_doc, project_document, projection_external_id, provider_payload,
|
||||
};
|
||||
use crate::{
|
||||
runtime::{RuntimeError, RuntimeResult},
|
||||
@@ -31,6 +31,7 @@ pub(super) async fn upsert_document(
|
||||
workspace_id: &str,
|
||||
doc_id: &str,
|
||||
) -> RuntimeResult<()> {
|
||||
let ordinary = is_ordinary_workspace_doc(workspace_id, doc_id);
|
||||
let mut transaction = pool
|
||||
.begin()
|
||||
.await
|
||||
@@ -41,7 +42,7 @@ pub(super) async fn upsert_document(
|
||||
.map_err(|error| RuntimeError::database("lock search document enqueue", error))?;
|
||||
let updated = sqlx::query(
|
||||
r#"UPDATE search_projection.document_states state
|
||||
SET target_permission_version=GREATEST(state.target_permission_version,workspace.required_permission_version),
|
||||
SET target_source_exists=state.target_source_exists AND $4, target_permission_version=GREATEST(state.target_permission_version,workspace.required_permission_version),
|
||||
available_at=CASE WHEN state.last_error IS NULL THEN now() ELSE state.available_at END, updated_at=now()
|
||||
FROM search_projection.workspace_states workspace
|
||||
WHERE state.generation_id=$1 AND state.workspace_id=$2 AND state.doc_id=$3
|
||||
@@ -50,6 +51,7 @@ pub(super) async fn upsert_document(
|
||||
.bind(generation.id)
|
||||
.bind(workspace_id)
|
||||
.bind(doc_id)
|
||||
.bind(ordinary)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("refresh search document target", error))?
|
||||
@@ -59,7 +61,7 @@ pub(super) async fn upsert_document(
|
||||
r#"INSERT INTO search_projection.document_states
|
||||
(generation_id,workspace_id,doc_id,target_source_version,target_source_exists,target_permission_version)
|
||||
SELECT $1,$2,$3,nextval('search_projection.source_mutation_version'),
|
||||
EXISTS(SELECT 1 FROM snapshots WHERE workspace_id=$2 AND guid=$3),
|
||||
$4 AND (EXISTS(SELECT 1 FROM snapshots WHERE workspace_id=$2 AND guid=$3) OR EXISTS(SELECT 1 FROM updates WHERE workspace_id=$2 AND guid=$3)),
|
||||
required_permission_version
|
||||
FROM search_projection.workspace_states
|
||||
WHERE generation_id=$1 AND workspace_id=$2"#,
|
||||
@@ -67,6 +69,7 @@ pub(super) async fn upsert_document(
|
||||
.bind(generation.id)
|
||||
.bind(workspace_id)
|
||||
.bind(doc_id)
|
||||
.bind(ordinary)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("enqueue search document", error))?;
|
||||
@@ -133,7 +136,7 @@ async fn projection_changes(
|
||||
}
|
||||
let Some((document, blocks)) = project_document(pool, workspace_id, doc_id).await? else {
|
||||
return Err(RuntimeError::SearchSourceInvalid(
|
||||
"document declared by workspace root is missing".to_string(),
|
||||
"document source is unavailable".to_string(),
|
||||
));
|
||||
};
|
||||
let mut changes = Vec::with_capacity(blocks.len() + 1);
|
||||
|
||||
+51
-44
@@ -1,22 +1,23 @@
|
||||
use sqlx::{PgPool, Row};
|
||||
use sqlx::Row;
|
||||
|
||||
use super::{
|
||||
DOCUMENT_PROJECTION_FAILED, ProjectionExpectation, RECONCILE_BATCH, WorkspacePhase, WorkspaceReconcileContext,
|
||||
WorkspaceStep, project_current_doc, provider_projection_matches, renew_workspace_lease, upsert_document,
|
||||
WorkspaceStep, is_ordinary_workspace_doc, load_workspace_doc_states_in, provider_projection_matches,
|
||||
renew_workspace_lease, upsert_document,
|
||||
};
|
||||
use crate::runtime::{RuntimeError, RuntimeResult};
|
||||
|
||||
pub(super) const ROOT_DOCUMENT_BATCH_SQL: &str = r#"WITH root_document AS (
|
||||
pub(super) const DOCUMENT_BATCH_SQL: &str = r#"WITH active_document AS (
|
||||
SELECT unnest($5::text[]) AS doc_id
|
||||
), candidate AS (
|
||||
SELECT doc_id,true AS root_member FROM root_document
|
||||
SELECT doc_id,true AS active_member FROM active_document
|
||||
UNION ALL
|
||||
SELECT state.doc_id,false
|
||||
FROM search_projection.document_states state
|
||||
WHERE state.generation_id=$2 AND state.workspace_id=$1
|
||||
AND NOT state.doc_id=ANY($5::text[])
|
||||
)
|
||||
SELECT candidate.doc_id,candidate.root_member
|
||||
SELECT candidate.doc_id,candidate.active_member
|
||||
FROM candidate
|
||||
WHERE ($3::text IS NULL OR candidate.doc_id > $3)
|
||||
ORDER BY candidate.doc_id LIMIT $4"#;
|
||||
@@ -29,12 +30,12 @@ struct DocumentTarget {
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) enum RootReconcilePhase {
|
||||
pub(super) enum DocumentReconcilePhase {
|
||||
Documents,
|
||||
Source,
|
||||
}
|
||||
|
||||
impl RootReconcilePhase {
|
||||
impl DocumentReconcilePhase {
|
||||
fn progress(self, after_doc_id: Option<String>) -> WorkspacePhase {
|
||||
match self {
|
||||
Self::Documents => WorkspacePhase::Documents { after_doc_id },
|
||||
@@ -43,32 +44,25 @@ impl RootReconcilePhase {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn load_root_document_ids(pool: &PgPool, workspace_id: &str) -> RuntimeResult<Vec<String>> {
|
||||
project_current_doc(pool, workspace_id, workspace_id, |root| {
|
||||
let projection = affine_doc_loader::project_workspace_root(root.blob, false)
|
||||
.map_err(|error| RuntimeError::SearchSourceInvalid(format!("workspace root projection failed: {error}")))?;
|
||||
if !projection.complete {
|
||||
return Err(RuntimeError::SearchSourceInvalid(
|
||||
"workspace root projection is incomplete".to_string(),
|
||||
));
|
||||
}
|
||||
let mut doc_ids = projection.doc_ids;
|
||||
doc_ids.sort();
|
||||
doc_ids.dedup();
|
||||
Ok(doc_ids)
|
||||
})
|
||||
.await?
|
||||
.ok_or_else(|| RuntimeError::SearchSourceInvalid("workspace root doc is missing".to_string()))
|
||||
async fn active_document_ids(connection: &mut sqlx::PgConnection, workspace_id: &str) -> RuntimeResult<Vec<String>> {
|
||||
Ok(
|
||||
load_workspace_doc_states_in(connection, workspace_id)
|
||||
.await?
|
||||
.into_iter()
|
||||
.filter(|doc| doc.lifecycle.is_none() && is_ordinary_workspace_doc(workspace_id, &doc.doc_id))
|
||||
.map(|doc| doc.doc_id)
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
async fn converge_document_membership(
|
||||
pool: &PgPool,
|
||||
connection: &mut sqlx::PgConnection,
|
||||
generation_id: uuid::Uuid,
|
||||
workspace_id: &str,
|
||||
doc_id: &str,
|
||||
root_member: bool,
|
||||
active_member: bool,
|
||||
) -> RuntimeResult<DocumentTarget> {
|
||||
if root_member {
|
||||
if active_member {
|
||||
let row = sqlx::query(
|
||||
r#"INSERT INTO search_projection.document_states(
|
||||
generation_id,workspace_id,doc_id,target_source_version,target_source_exists,target_permission_version
|
||||
@@ -112,7 +106,7 @@ async fn converge_document_membership(
|
||||
.bind(generation_id)
|
||||
.bind(workspace_id)
|
||||
.bind(doc_id)
|
||||
.fetch_one(pool)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("converge live search document membership", error))?;
|
||||
return decode_target(row);
|
||||
@@ -135,7 +129,7 @@ async fn converge_document_membership(
|
||||
.bind(generation_id)
|
||||
.bind(workspace_id)
|
||||
.bind(doc_id)
|
||||
.fetch_one(pool)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("converge removed search document membership", error))?;
|
||||
decode_target(row)
|
||||
@@ -159,42 +153,55 @@ fn decode_target(row: sqlx::postgres::PgRow) -> RuntimeResult<DocumentTarget> {
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) async fn reconcile_root_documents(
|
||||
pub(super) async fn reconcile_documents(
|
||||
context: &WorkspaceReconcileContext<'_>,
|
||||
root_document_ids: &[String],
|
||||
permission_version: i64,
|
||||
after_doc_id: Option<String>,
|
||||
phase: RootReconcilePhase,
|
||||
phase: DocumentReconcilePhase,
|
||||
) -> RuntimeResult<WorkspaceStep> {
|
||||
let rows = sqlx::query(ROOT_DOCUMENT_BATCH_SQL)
|
||||
let mut transaction = context
|
||||
.pool
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("begin document membership reconciliation", error))?;
|
||||
let active_doc_ids = active_document_ids(&mut transaction, context.workspace_id).await?;
|
||||
let rows = sqlx::query(DOCUMENT_BATCH_SQL)
|
||||
.bind(context.workspace_id)
|
||||
.bind(context.generation.id)
|
||||
.bind(&after_doc_id)
|
||||
.bind(RECONCILE_BATCH + 1)
|
||||
.bind(root_document_ids)
|
||||
.fetch_all(context.pool)
|
||||
.bind(&active_doc_ids)
|
||||
.fetch_all(&mut *transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("load canonical root search document batch", error))?;
|
||||
.map_err(|error| RuntimeError::database("load active search document batch", error))?;
|
||||
let complete = rows.len() <= RECONCILE_BATCH as usize;
|
||||
let mut after_doc_id = after_doc_id;
|
||||
let mut targets = Vec::with_capacity(rows.len());
|
||||
for row in rows.into_iter().take(RECONCILE_BATCH as usize) {
|
||||
let doc_id: String = row
|
||||
.try_get("doc_id")
|
||||
.map_err(|error| RuntimeError::database("decode canonical root search document", error))?;
|
||||
let root_member: bool = row
|
||||
.try_get("root_member")
|
||||
.map_err(|error| RuntimeError::database("decode canonical root document membership", error))?;
|
||||
if !renew_workspace_lease(context.pool, context.generation.id, context.workspace_id, context.fence).await? {
|
||||
return Ok(WorkspaceStep::Continue(phase.progress(after_doc_id)));
|
||||
}
|
||||
.map_err(|error| RuntimeError::database("decode active search document", error))?;
|
||||
let active_member: bool = row
|
||||
.try_get("active_member")
|
||||
.map_err(|error| RuntimeError::database("decode active membership", error))?;
|
||||
let target = converge_document_membership(
|
||||
context.pool,
|
||||
&mut transaction,
|
||||
context.generation.id,
|
||||
context.workspace_id,
|
||||
&doc_id,
|
||||
root_member,
|
||||
active_member,
|
||||
)
|
||||
.await?;
|
||||
targets.push((doc_id, target));
|
||||
}
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("commit document membership reconciliation", error))?;
|
||||
for (doc_id, target) in targets {
|
||||
if !renew_workspace_lease(context.pool, context.generation.id, context.workspace_id, context.fence).await? {
|
||||
return Ok(WorkspaceStep::Continue(phase.progress(after_doc_id)));
|
||||
}
|
||||
if target.failed {
|
||||
after_doc_id = Some(doc_id);
|
||||
continue;
|
||||
@@ -1,6 +1,6 @@
|
||||
mod anti_entropy;
|
||||
mod document;
|
||||
mod root;
|
||||
mod inventory;
|
||||
mod workspace;
|
||||
mod workspace_state;
|
||||
|
||||
@@ -28,7 +28,7 @@ use anti_entropy::{
|
||||
ProjectionExpectation, provider_projection_matches, reconcile_stale_provider_rows, sweep_deleted_workspace,
|
||||
};
|
||||
use document::upsert_document;
|
||||
use root::{RootReconcilePhase, load_root_document_ids, reconcile_root_documents};
|
||||
use inventory::{DocumentReconcilePhase, reconcile_documents};
|
||||
pub(super) use workspace::reconcile_workspace;
|
||||
use workspace_state::{
|
||||
WorkspacePhase, checkpoint_workspace, checkpoint_workspace_after, claim_workspace, complete_workspace,
|
||||
@@ -37,5 +37,6 @@ use workspace_state::{
|
||||
|
||||
use super::{
|
||||
ActiveGeneration, DOCUMENT_PROJECTION_FAILED, ProjectionInput, SearchChange, SearchProvider, SearchTable,
|
||||
WORKSPACE_RECONCILE_FAILED, project_current_doc, project_document, projection_external_id, provider_payload,
|
||||
WORKSPACE_RECONCILE_FAILED, is_ordinary_workspace_doc, load_workspace_doc_states_in, project_document,
|
||||
projection_external_id, provider_payload,
|
||||
};
|
||||
@@ -1,11 +1,10 @@
|
||||
use sqlx::{PgPool, Row};
|
||||
|
||||
use super::{
|
||||
ActiveGeneration, DOCUMENT_LEASE_SECONDS, RECONCILE_BATCH, RootReconcilePhase, SearchProvider, SearchTable,
|
||||
ActiveGeneration, DOCUMENT_LEASE_SECONDS, DocumentReconcilePhase, RECONCILE_BATCH, SearchProvider, SearchTable,
|
||||
WorkspacePhase, WorkspaceReconcileContext, WorkspaceStep, checkpoint_workspace, checkpoint_workspace_after,
|
||||
claim_workspace, complete_workspace, delete_workspace_state, load_root_document_ids, mark_workspace_failed,
|
||||
reconcile_root_documents, reconcile_stale_provider_rows, renew_workspace_lease, sweep_deleted_workspace,
|
||||
upsert_document,
|
||||
claim_workspace, complete_workspace, delete_workspace_state, mark_workspace_failed, reconcile_documents,
|
||||
reconcile_stale_provider_rows, renew_workspace_lease, sweep_deleted_workspace, upsert_document,
|
||||
};
|
||||
use crate::{
|
||||
runtime::{RuntimeError, RuntimeResult},
|
||||
@@ -81,15 +80,6 @@ pub(in crate::runtime::backend_runtime::search) async fn reconcile_workspace(
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
let root_document_ids = match load_root_document_ids(pool, workspace_id).await {
|
||||
Ok(doc_ids) => doc_ids,
|
||||
Err(error) if error.is_permanent_search_source() => {
|
||||
mark_workspace_failed(pool, generation.id, workspace_id, claim.fence).await?;
|
||||
return Ok(true);
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
|
||||
if let WorkspacePhase::Stale { table, cursor } = claim.progress.phase.clone() {
|
||||
match reconcile_stale_provider_rows(&context, table, cursor).await? {
|
||||
WorkspaceStep::Continue(progress) => {
|
||||
@@ -119,16 +109,15 @@ pub(in crate::runtime::backend_runtime::search) async fn reconcile_workspace(
|
||||
}
|
||||
|
||||
if let WorkspacePhase::Source { after_doc_id } = claim.progress.phase.clone() {
|
||||
match reconcile_root_documents(
|
||||
match reconcile_documents(
|
||||
&context,
|
||||
&root_document_ids,
|
||||
claim.progress.captured_permission_version,
|
||||
after_doc_id,
|
||||
RootReconcilePhase::Source,
|
||||
DocumentReconcilePhase::Source,
|
||||
)
|
||||
.await?
|
||||
.await
|
||||
{
|
||||
WorkspaceStep::Continue(progress) => {
|
||||
Ok(WorkspaceStep::Continue(progress)) => {
|
||||
checkpoint_workspace(
|
||||
pool,
|
||||
generation.id,
|
||||
@@ -139,8 +128,13 @@ pub(in crate::runtime::backend_runtime::search) async fn reconcile_workspace(
|
||||
.await?;
|
||||
return Ok(true);
|
||||
}
|
||||
WorkspaceStep::Quiet(_) => unreachable!("source reconciliation does not schedule a quiet period"),
|
||||
WorkspaceStep::Complete => {}
|
||||
Ok(WorkspaceStep::Quiet(_)) => unreachable!("source reconciliation does not schedule a quiet period"),
|
||||
Ok(WorkspaceStep::Complete) => {}
|
||||
Err(error) if error.is_permanent_search_source() => {
|
||||
mark_workspace_failed(pool, generation.id, workspace_id, claim.fence).await?;
|
||||
return Ok(true);
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
checkpoint_workspace(
|
||||
pool,
|
||||
@@ -256,16 +250,15 @@ pub(in crate::runtime::backend_runtime::search) async fn reconcile_workspace(
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
match reconcile_root_documents(
|
||||
match reconcile_documents(
|
||||
&context,
|
||||
&root_document_ids,
|
||||
claim.progress.captured_permission_version,
|
||||
after_doc_id,
|
||||
RootReconcilePhase::Documents,
|
||||
DocumentReconcilePhase::Documents,
|
||||
)
|
||||
.await?
|
||||
.await
|
||||
{
|
||||
WorkspaceStep::Continue(progress) => {
|
||||
Ok(WorkspaceStep::Continue(progress)) => {
|
||||
checkpoint_workspace(
|
||||
pool,
|
||||
generation.id,
|
||||
@@ -276,10 +269,14 @@ pub(in crate::runtime::backend_runtime::search) async fn reconcile_workspace(
|
||||
.await?;
|
||||
return Ok(true);
|
||||
}
|
||||
WorkspaceStep::Complete => {}
|
||||
WorkspaceStep::Quiet(_) => unreachable!("root document reconcile does not schedule a quiet period"),
|
||||
Ok(WorkspaceStep::Complete) => {}
|
||||
Ok(WorkspaceStep::Quiet(_)) => unreachable!("document reconcile does not schedule a quiet period"),
|
||||
Err(error) if error.is_permanent_search_source() => {
|
||||
mark_workspace_failed(pool, generation.id, workspace_id, claim.fence).await?;
|
||||
return Ok(true);
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
|
||||
checkpoint_workspace(
|
||||
pool,
|
||||
generation.id,
|
||||
@@ -885,7 +882,8 @@ mod tests {
|
||||
|
||||
if phase_name == "documents" {
|
||||
let orphan_doc_id = format!("orphan-{suffix}");
|
||||
let orphan_blob = affine_doc_loader::build_full_doc("orphan", "must stay hidden", &orphan_doc_id).unwrap();
|
||||
let orphan_blob =
|
||||
affine_doc_loader::build_full_doc("unclassified", "body establishes identity", &orphan_doc_id).unwrap();
|
||||
sqlx::query("INSERT INTO snapshots(workspace_id,guid,blob,updated_at) VALUES($1,$2,$3,now())")
|
||||
.bind(&workspace_id)
|
||||
.bind(&orphan_doc_id)
|
||||
@@ -908,7 +906,39 @@ mod tests {
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!orphan_published);
|
||||
assert!(orphan_published);
|
||||
let update_only = format!("update-only-{suffix}");
|
||||
let mut transaction = pool.begin().await.unwrap();
|
||||
sqlx::query("INSERT INTO updates(workspace_id,guid,blob,created_at) VALUES($1,$2,$3,clock_timestamp())")
|
||||
.bind(&workspace_id)
|
||||
.bind(&update_only)
|
||||
.bind(affine_doc_loader::build_full_doc("update only", "persisted identity", &update_only).unwrap())
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.unwrap();
|
||||
crate::runtime::backend_runtime::domain_command::invalidate_workspace_inventory_in(
|
||||
&mut transaction,
|
||||
&workspace_id,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
transaction.commit().await.unwrap();
|
||||
for _ in 0..8 {
|
||||
let _ = reconcile_workspace(&pool, &embedded, None, &generation, &workspace_id)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let published: (bool, Option<String>) = sqlx::query_as(
|
||||
"SELECT published_source_exists,last_error FROM search_projection.document_states WHERE generation_id=$1 \
|
||||
AND workspace_id=$2 AND doc_id=$3",
|
||||
)
|
||||
.bind(generation_id)
|
||||
.bind(&workspace_id)
|
||||
.bind(&update_only)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(published, (true, None));
|
||||
}
|
||||
|
||||
sqlx::query("DELETE FROM search_projection.generations WHERE id=$1")
|
||||
@@ -923,89 +953,159 @@ mod tests {
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let generation_id = Uuid::new_v4();
|
||||
let workspace_id = format!("missing-root-{}", Uuid::new_v4().simple());
|
||||
sqlx::query("INSERT INTO workspaces(id) VALUES($1)")
|
||||
.bind(&workspace_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
let partial_root = Doc::default();
|
||||
let mut partial_meta = partial_root.get_or_create_map("meta").unwrap();
|
||||
partial_meta.insert("name".into(), "before").unwrap();
|
||||
let prefix_state = partial_root.get_state_vector();
|
||||
partial_meta.insert("name".into(), "after").unwrap();
|
||||
let partial = partial_root.encode_state_as_update_v1(&prefix_state).unwrap();
|
||||
let invalid_shape = Doc::default();
|
||||
invalid_shape
|
||||
.get_or_create_map("meta")
|
||||
.unwrap()
|
||||
.insert("pages".into(), "invalid")
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
r#"INSERT INTO search_projection.generations(id,provider,state,config_hash,schema_version,manifest)
|
||||
VALUES($1,'embedded','building',decode(repeat('00',32),'hex'),1,'{}')"#,
|
||||
)
|
||||
.bind(generation_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("INSERT INTO search_projection.workspace_states(generation_id,workspace_id) VALUES($1,$2)")
|
||||
.bind(generation_id)
|
||||
.bind(&workspace_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let embedded = EmbeddedSearchIndex::default();
|
||||
embedded.prepare_generation(generation_id).await;
|
||||
let generation = ActiveGeneration {
|
||||
id: generation_id,
|
||||
manifest: json!({}),
|
||||
};
|
||||
assert!(
|
||||
reconcile_workspace(&pool, &embedded, None, &generation, &workspace_id)
|
||||
let invalid_shape = invalid_shape.encode_update_v1().unwrap();
|
||||
for (phase_name, phase) in [
|
||||
("documents", WorkspacePhase::Documents { after_doc_id: None }),
|
||||
("source", WorkspacePhase::Source { after_doc_id: None }),
|
||||
(
|
||||
"stale",
|
||||
WorkspacePhase::Stale {
|
||||
table: SearchTable::Doc,
|
||||
cursor: None,
|
||||
},
|
||||
),
|
||||
] {
|
||||
for (failure_name, root_blob) in [
|
||||
("missing", None),
|
||||
("partial", Some(partial.clone())),
|
||||
("invalid_shape", Some(invalid_shape.clone())),
|
||||
("invalid_encoding", Some(vec![0xff])),
|
||||
] {
|
||||
let generation_id = Uuid::new_v4();
|
||||
let workspace_id = format!("root-{phase_name}-{failure_name}-{}", Uuid::new_v4().simple());
|
||||
sqlx::query("INSERT INTO workspaces(id) VALUES($1)")
|
||||
.bind(&workspace_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
if let Some(blob) = root_blob {
|
||||
sqlx::query("INSERT INTO snapshots(workspace_id,guid,blob,updated_at) VALUES($1,$1,$2,now())")
|
||||
.bind(&workspace_id)
|
||||
.bind(blob)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
sqlx::query(
|
||||
"INSERT INTO search_projection.generations(id,provider,state,config_hash,schema_version,manifest) \
|
||||
VALUES($1,'embedded','building',decode(repeat('00',32),'hex'),1,'{}')",
|
||||
)
|
||||
.bind(generation_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
let root_failure: Option<String> = sqlx::query_scalar(
|
||||
"SELECT last_error FROM search_projection.workspace_states WHERE generation_id=$1 AND workspace_id=$2",
|
||||
)
|
||||
.bind(generation_id)
|
||||
.bind(&workspace_id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(root_failure.as_deref(), Some("search_workspace_reconcile_failed"));
|
||||
|
||||
let unrelated_doc = format!("unrelated-{}", Uuid::new_v4().simple());
|
||||
sqlx::query("INSERT INTO snapshots(workspace_id,guid,blob,updated_at) VALUES($1,$2,decode('00','hex'),now())")
|
||||
.bind(&workspace_id)
|
||||
.bind(unrelated_doc)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let still_failed: Option<String> = sqlx::query_scalar(
|
||||
"SELECT last_error FROM search_projection.workspace_states WHERE generation_id=$1 AND workspace_id=$2",
|
||||
)
|
||||
.bind(generation_id)
|
||||
.bind(&workspace_id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(still_failed.as_deref(), Some("search_workspace_reconcile_failed"));
|
||||
|
||||
sqlx::query("INSERT INTO snapshots(workspace_id,guid,blob,updated_at) VALUES($1,$1,$2,now())")
|
||||
.bind(&workspace_id)
|
||||
.bind(affine_doc_loader::add_doc_to_root_doc(Vec::new(), "recovered", None).unwrap())
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let reopened: Option<String> = sqlx::query_scalar(
|
||||
"SELECT last_error FROM search_projection.workspace_states WHERE generation_id=$1 AND workspace_id=$2",
|
||||
)
|
||||
.bind(generation_id)
|
||||
.bind(&workspace_id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(reopened, None);
|
||||
sqlx::query("DELETE FROM search_projection.generations WHERE id=$1")
|
||||
.bind(generation_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("DELETE FROM workspaces WHERE id=$1")
|
||||
.bind(&workspace_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"INSERT INTO search_projection.workspace_states(generation_id,workspace_id,pending_scope,progress) \
|
||||
VALUES($1,$2,'workspace',$3)",
|
||||
)
|
||||
.bind(generation_id)
|
||||
.bind(&workspace_id)
|
||||
.bind(WorkspaceProgress::new(0, 0, phase.clone()).value())
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let embedded = EmbeddedSearchIndex::default();
|
||||
embedded.prepare_generation(generation_id).await;
|
||||
let generation = ActiveGeneration {
|
||||
id: generation_id,
|
||||
manifest: json!({}),
|
||||
};
|
||||
assert!(
|
||||
reconcile_workspace(&pool, &embedded, None, &generation, &workspace_id)
|
||||
.await
|
||||
.unwrap(),
|
||||
"{phase_name}/{failure_name}"
|
||||
);
|
||||
let failure: Option<String> = sqlx::query_scalar(
|
||||
"SELECT last_error FROM search_projection.workspace_states WHERE generation_id=$1 AND workspace_id=$2",
|
||||
)
|
||||
.bind(generation_id)
|
||||
.bind(&workspace_id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(failure, None, "{phase_name}/{failure_name}");
|
||||
let body_id = format!("body-{}", Uuid::new_v4().simple());
|
||||
let body = affine_doc_loader::build_full_doc("visible", "root independent body", &body_id).unwrap();
|
||||
sqlx::query("INSERT INTO snapshots(workspace_id,guid,blob,updated_at) VALUES($1,$2,$3,now())")
|
||||
.bind(&workspace_id)
|
||||
.bind(&body_id)
|
||||
.bind(body)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
for _ in 0..8 {
|
||||
let _ = reconcile_workspace(&pool, &embedded, None, &generation, &workspace_id)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let published: bool = sqlx::query_scalar(
|
||||
"SELECT published_source_exists FROM search_projection.document_states WHERE generation_id=$1 AND \
|
||||
workspace_id=$2 AND doc_id=$3",
|
||||
)
|
||||
.bind(generation_id)
|
||||
.bind(&workspace_id)
|
||||
.bind(&body_id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(published, "{phase_name}/{failure_name} must publish persisted bodies");
|
||||
let mut transaction = pool.begin().await.unwrap();
|
||||
sqlx::query(
|
||||
"INSERT INTO workspace_pages(workspace_id,page_id,lifecycle_state,lifecycle_changed_at) \
|
||||
VALUES($1,$2,'trashed',now())",
|
||||
)
|
||||
.bind(&workspace_id)
|
||||
.bind(&body_id)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.unwrap();
|
||||
crate::runtime::backend_runtime::domain_command::invalidate_workspace_inventory_in(
|
||||
&mut transaction,
|
||||
&workspace_id,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
transaction.commit().await.unwrap();
|
||||
for _ in 0..8 {
|
||||
let _ = reconcile_workspace(&pool, &embedded, None, &generation, &workspace_id)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let published: bool = sqlx::query_scalar(
|
||||
"SELECT published_source_exists FROM search_projection.document_states WHERE generation_id=$1 AND \
|
||||
workspace_id=$2 AND doc_id=$3",
|
||||
)
|
||||
.bind(generation_id)
|
||||
.bind(&workspace_id)
|
||||
.bind(&body_id)
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!published, "{phase_name}/{failure_name} must withdraw SQL trash");
|
||||
sqlx::query("DELETE FROM search_projection.generations WHERE id=$1")
|
||||
.bind(generation_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("DELETE FROM workspaces WHERE id=$1")
|
||||
.bind(&workspace_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@ pub(in crate::runtime::backend_runtime) async fn load_command_quota_in(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
deployment: Deployment,
|
||||
workspace_id: &str,
|
||||
exclusive: bool,
|
||||
) -> RuntimeResult<Option<CommandQuotaSnapshot>> {
|
||||
let Some(owner_id) = sqlx::query_scalar::<_, String>(
|
||||
"SELECT user_id FROM workspace_members WHERE workspace_id=$1 AND role='owner' AND state='active' LIMIT 1",
|
||||
@@ -36,17 +37,25 @@ pub(in crate::runtime::backend_runtime) async fn load_command_quota_in(
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
sqlx::query("SELECT id FROM users WHERE id=$1 FOR UPDATE")
|
||||
.bind(&owner_id)
|
||||
.fetch_one(&mut **tx)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("lock command quota owner", error))?;
|
||||
let workspace_exists = sqlx::query("SELECT id FROM workspaces WHERE id=$1 FOR UPDATE")
|
||||
.bind(workspace_id)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("lock command quota workspace", error))?
|
||||
.is_some();
|
||||
sqlx::query(if exclusive {
|
||||
"SELECT id FROM users WHERE id=$1 FOR UPDATE"
|
||||
} else {
|
||||
"SELECT id FROM users WHERE id=$1 FOR SHARE"
|
||||
})
|
||||
.bind(&owner_id)
|
||||
.fetch_one(&mut **tx)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("lock command quota owner", error))?;
|
||||
let workspace_exists = sqlx::query(if exclusive {
|
||||
"SELECT id FROM workspaces WHERE id=$1 FOR UPDATE"
|
||||
} else {
|
||||
"SELECT id FROM workspaces WHERE id=$1 FOR SHARE"
|
||||
})
|
||||
.bind(workspace_id)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("lock command quota workspace", error))?
|
||||
.is_some();
|
||||
if !workspace_exists {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use napi::{Result, bindgen_prelude::Buffer};
|
||||
use serde_json::{Value, json};
|
||||
use sha2::{Digest, Sha256};
|
||||
use sqlx::PgConnection;
|
||||
|
||||
use super::{
|
||||
BackendRuntime, CurrentDoc, CurrentDocUpdate, InvalidationHintV1, RuntimeError, RuntimeResult, WorkspaceDocState,
|
||||
domain_command::{invalidate_workspace_inventory_in, lock_workspace_doc_update},
|
||||
is_ordinary_workspace_doc, load_current_doc_parts_in, load_workspace_doc_states_in, merge_current_doc,
|
||||
permission::PermissionAuthorizer,
|
||||
};
|
||||
|
||||
#[napi_derive::napi(object)]
|
||||
pub struct WorkspaceLifecycleMigrationSourceV1 {
|
||||
pub revision: String,
|
||||
pub bin: Option<Buffer>,
|
||||
pub completed: bool,
|
||||
pub root_status: String,
|
||||
}
|
||||
|
||||
#[napi_derive::napi(object)]
|
||||
pub struct WorkspaceLegacyDocV1 {
|
||||
pub doc_id: String,
|
||||
pub trashed: bool,
|
||||
}
|
||||
|
||||
#[napi_derive::napi(object)]
|
||||
pub struct WorkspaceLifecycleMigrationInputV1 {
|
||||
pub workspace_id: String,
|
||||
pub source_revision: String,
|
||||
pub root_status: String,
|
||||
pub docs: Vec<WorkspaceLegacyDocV1>,
|
||||
}
|
||||
|
||||
fn source_revision(snapshot: &Option<CurrentDoc>, updates: &[CurrentDocUpdate]) -> String {
|
||||
let mut hash = Sha256::new();
|
||||
for (timestamp, bytes) in snapshot
|
||||
.iter()
|
||||
.map(|record| (record.updated_at, &record.blob))
|
||||
.chain(updates.iter().map(|record| (record.created_at, &record.blob)))
|
||||
{
|
||||
hash.update(timestamp.timestamp_micros().to_le_bytes());
|
||||
hash.update((bytes.len() as u64).to_le_bytes());
|
||||
hash.update(bytes);
|
||||
}
|
||||
hex::encode(hash.finalize())
|
||||
}
|
||||
|
||||
async fn completed(connection: &mut PgConnection, workspace_id: &str) -> RuntimeResult<bool> {
|
||||
sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT 1 FROM storage_reconciliation_checkpoints WHERE kind='workspace_doc_lifecycle' AND scope=$1 \
|
||||
AND status='completed')",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.fetch_one(connection)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("load workspace lifecycle migration", error))
|
||||
}
|
||||
|
||||
async fn ensure_migration_active(connection: &mut PgConnection) -> RuntimeResult<()> {
|
||||
let active: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT 1 FROM storage_reconciliation_checkpoints WHERE kind='workspace_doc_lifecycle_activation' \
|
||||
AND scope='global' AND status='active')",
|
||||
)
|
||||
.fetch_one(connection)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("load workspace lifecycle activation", error))?;
|
||||
if !active {
|
||||
return Err(RuntimeError::invalid_state("workspace_lifecycle_not_active"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[napi_derive::napi]
|
||||
impl BackendRuntime {
|
||||
#[napi]
|
||||
pub async fn activate_workspace_lifecycle_v1(&self) -> Result<bool> {
|
||||
sqlx::query(
|
||||
"INSERT INTO storage_reconciliation_checkpoints(kind,scope,status,metadata,completed_at) \
|
||||
VALUES('workspace_doc_lifecycle_activation','global','active','{\"protocolVersion\":2}',clock_timestamp()) ON \
|
||||
CONFLICT(kind,scope) DO NOTHING",
|
||||
)
|
||||
.execute(&self.pool().await?)
|
||||
.await
|
||||
.map(|result| result.rows_affected() != 0)
|
||||
.map_err(|error| RuntimeError::database("activate workspace lifecycle migration", error).into())
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub async fn list_workspace_lifecycle_migration_candidates_v1(&self) -> Result<Vec<String>> {
|
||||
sqlx::query_scalar(
|
||||
"SELECT id FROM workspaces workspace WHERE EXISTS(SELECT 1 FROM storage_reconciliation_checkpoints WHERE \
|
||||
kind='workspace_doc_lifecycle_activation' AND scope='global' AND status='active') AND NOT EXISTS(SELECT 1 FROM \
|
||||
storage_reconciliation_checkpoints checkpoint WHERE checkpoint.kind='workspace_doc_lifecycle' AND \
|
||||
checkpoint.scope=workspace.id AND checkpoint.status='completed') ORDER BY workspace.sid LIMIT 100",
|
||||
)
|
||||
.fetch_all(&self.pool().await?)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("list workspace lifecycle migrations", error).into())
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub async fn prepare_workspace_lifecycle_migration_v1(
|
||||
&self,
|
||||
workspace_id: String,
|
||||
) -> Result<WorkspaceLifecycleMigrationSourceV1> {
|
||||
let pool = self.pool().await?;
|
||||
let mut transaction = pool
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("begin workspace lifecycle source", error))?;
|
||||
sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("set lifecycle source snapshot", error))?;
|
||||
ensure_migration_active(&mut transaction).await?;
|
||||
let done = completed(&mut transaction, &workspace_id).await?;
|
||||
if done {
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("commit completed lifecycle source", error))?;
|
||||
return Ok(WorkspaceLifecycleMigrationSourceV1 {
|
||||
revision: String::new(),
|
||||
bin: None,
|
||||
completed: true,
|
||||
root_status: "completed".into(),
|
||||
});
|
||||
}
|
||||
|
||||
let (snapshot, updates) = load_current_doc_parts_in(&mut transaction, &workspace_id, &workspace_id).await?;
|
||||
let revision = source_revision(&snapshot, &updates);
|
||||
let (bin, root_status) = match merge_current_doc(snapshot, updates) {
|
||||
Ok(Some(doc)) => (Some(doc.blob.into()), "decoded"),
|
||||
Ok(None) => (None, "absent"),
|
||||
Err(_) => (None, "invalid_binary"),
|
||||
};
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("commit lifecycle source snapshot", error))?;
|
||||
Ok(WorkspaceLifecycleMigrationSourceV1 {
|
||||
revision,
|
||||
bin,
|
||||
completed: done,
|
||||
root_status: root_status.into(),
|
||||
})
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub async fn migrate_workspace_lifecycle_v1(&self, input: WorkspaceLifecycleMigrationInputV1) -> Result<bool> {
|
||||
let pool = self.pool().await?;
|
||||
let mut transaction = pool
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("begin workspace lifecycle migration", error))?;
|
||||
loop {
|
||||
let locked: bool = sqlx::query_scalar("SELECT pg_try_advisory_xact_lock(hashtextextended($1,0))")
|
||||
.bind(format!("storage-workspace:{}", input.workspace_id))
|
||||
.fetch_one(&mut *transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("lock workspace lifecycle migration", error))?;
|
||||
if locked {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(25)).await;
|
||||
}
|
||||
ensure_migration_active(&mut transaction).await?;
|
||||
lock_workspace_doc_update(&mut transaction, &input.workspace_id, &input.workspace_id).await?;
|
||||
let workspace = sqlx::query_scalar::<_, String>("SELECT id FROM workspaces WHERE id=$1 FOR KEY SHARE")
|
||||
.bind(&input.workspace_id)
|
||||
.fetch_optional(&mut *transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("lock workspace lifecycle identity", error))?;
|
||||
if workspace.is_none() {
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
if completed(&mut transaction, &input.workspace_id).await? {
|
||||
return Ok(true);
|
||||
}
|
||||
let (snapshot, updates) =
|
||||
load_current_doc_parts_in(&mut transaction, &input.workspace_id, &input.workspace_id).await?;
|
||||
if source_revision(&snapshot, &updates) != input.source_revision {
|
||||
return Ok(false);
|
||||
}
|
||||
let mut unique = BTreeMap::<String, Option<bool>>::new();
|
||||
for doc in input.docs {
|
||||
if is_ordinary_workspace_doc(&input.workspace_id, &doc.doc_id) {
|
||||
unique
|
||||
.entry(doc.doc_id)
|
||||
.and_modify(|state| *state = None)
|
||||
.or_insert(Some(doc.trashed));
|
||||
}
|
||||
}
|
||||
let (doc_ids, trashed): (Vec<_>, Vec<_>) = unique
|
||||
.into_iter()
|
||||
.filter_map(|(id, state)| state.map(|trash| (id, trash)))
|
||||
.unzip();
|
||||
sqlx::query(
|
||||
"INSERT INTO updates(workspace_id,guid,blob,created_at) SELECT \
|
||||
$1,input.doc_id,$3,date_trunc('milliseconds',clock_timestamp()) FROM unnest($2::text[]) input(doc_id) LEFT \
|
||||
JOIN workspace_pages page ON page.workspace_id=$1 AND page.page_id=input.doc_id WHERE page.lifecycle_state IS \
|
||||
DISTINCT FROM 'deleted' AND NOT EXISTS(SELECT 1 FROM snapshots WHERE workspace_id=$1 AND guid=input.doc_id) \
|
||||
AND NOT EXISTS(SELECT 1 FROM updates WHERE workspace_id=$1 AND guid=input.doc_id)",
|
||||
)
|
||||
.bind(&input.workspace_id)
|
||||
.bind(&doc_ids)
|
||||
.bind(&[0u8, 0][..])
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("retain legacy document identities", error))?;
|
||||
sqlx::query(
|
||||
"INSERT INTO workspace_pages(workspace_id,page_id,lifecycle_state,lifecycle_changed_at) SELECT \
|
||||
$1,input.doc_id,'trashed',date_trunc('milliseconds',clock_timestamp()) FROM unnest($2::text[],$3::bool[]) \
|
||||
input(doc_id,trashed) WHERE input.trashed ON CONFLICT(workspace_id,page_id) DO UPDATE SET \
|
||||
lifecycle_state='trashed',lifecycle_changed_at=EXCLUDED.lifecycle_changed_at WHERE \
|
||||
workspace_pages.lifecycle_changed_at IS NULL AND workspace_pages.lifecycle_state IS DISTINCT FROM 'deleted'",
|
||||
)
|
||||
.bind(&input.workspace_id)
|
||||
.bind(&doc_ids)
|
||||
.bind(&trashed)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("migrate legacy document trash", error))?;
|
||||
sqlx::query(
|
||||
"INSERT INTO storage_reconciliation_checkpoints(kind,scope,status,metadata,completed_at) \
|
||||
VALUES('workspace_doc_lifecycle',$1,'completed',$2,clock_timestamp()) ON CONFLICT(kind,scope) DO UPDATE SET \
|
||||
status='completed',metadata=EXCLUDED.metadata,completed_at=EXCLUDED.completed_at",
|
||||
)
|
||||
.bind(&input.workspace_id)
|
||||
.bind(json!({"protocolVersion":2,"sourceRevision":input.source_revision,"rootStatus":input.root_status}))
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("complete workspace lifecycle migration", error))?;
|
||||
if self.embedding_schema_ready()? {
|
||||
let active_ids = load_workspace_doc_states_in(&mut transaction, &input.workspace_id)
|
||||
.await?
|
||||
.into_iter()
|
||||
.filter(|doc| doc.lifecycle.is_none() && is_ordinary_workspace_doc(&input.workspace_id, &doc.doc_id))
|
||||
.map(|doc| doc.doc_id)
|
||||
.collect::<Vec<_>>();
|
||||
sqlx::query(
|
||||
"UPDATE embedding_sources SET deleted_at=clock_timestamp(),updated_at=clock_timestamp() WHERE workspace_id=$1 \
|
||||
AND source_kind='document' AND NOT(source_key=ANY($2))",
|
||||
)
|
||||
.bind(&input.workspace_id)
|
||||
.bind(&active_ids)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("retire inactive legacy document embeddings", error))?;
|
||||
}
|
||||
invalidate_workspace_inventory_in(&mut transaction, &input.workspace_id).await?;
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("commit workspace lifecycle migration", error))?;
|
||||
self
|
||||
.publish_invalidation(InvalidationHintV1::WorkspaceInventoryChanged {
|
||||
workspace_id: input.workspace_id,
|
||||
})
|
||||
.await;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
#[napi]
|
||||
pub async fn get_workspace_state_v1(&self, workspace_id: String, actor_user_id: String) -> Result<Value> {
|
||||
let pool = self.pool().await?;
|
||||
let mut transaction = pool
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("begin workspace state", error))?;
|
||||
sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("set workspace state snapshot", error))?;
|
||||
let states = load_workspace_doc_states_in(&mut transaction, &workspace_id).await?;
|
||||
let candidates = states.iter().map(|doc| doc.doc_id.clone()).collect::<Vec<_>>();
|
||||
let authorizer =
|
||||
PermissionAuthorizer::with_telemetry(pool, self.config()?.deployment, self.permission_telemetry.clone());
|
||||
let readable = authorizer
|
||||
.authorize_workspace_sync_docs_in(&mut transaction, &workspace_id, &actor_user_id, &candidates)
|
||||
.await?;
|
||||
let mut docs = Vec::new();
|
||||
let mut clocks = serde_json::Map::new();
|
||||
for WorkspaceDocState {
|
||||
doc_id,
|
||||
timestamp,
|
||||
lifecycle,
|
||||
lifecycle_changed_at,
|
||||
} in states
|
||||
{
|
||||
if !readable.get(&doc_id).is_some_and(|decision| decision.allowed) {
|
||||
continue;
|
||||
}
|
||||
if is_ordinary_workspace_doc(&workspace_id, &doc_id) {
|
||||
docs.push(json!({"docId":doc_id,"timestamp":timestamp.timestamp_millis(),"lifecycle":lifecycle,"lifecycleChangedAt":lifecycle_changed_at.map(|timestamp|timestamp.timestamp_millis())}));
|
||||
} else {
|
||||
clocks.insert(doc_id, json!(timestamp.timestamp_millis()));
|
||||
}
|
||||
}
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("commit workspace state", error))?;
|
||||
Ok(json!({"docs":docs,"clocks":clocks}))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
pub(in crate::runtime) use affine_core::access_control::is_ordinary_workspace_doc;
|
||||
use chrono::{DateTime, Utc};
|
||||
use sqlx::PgConnection;
|
||||
|
||||
use super::{RuntimeError, RuntimeResult};
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
pub(in crate::runtime) struct WorkspaceDocState {
|
||||
pub(in crate::runtime) doc_id: String,
|
||||
pub(in crate::runtime) timestamp: DateTime<Utc>,
|
||||
pub(in crate::runtime) lifecycle: Option<String>,
|
||||
pub(in crate::runtime) lifecycle_changed_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
pub(in crate::runtime) async fn load_workspace_doc_states_in(
|
||||
connection: &mut PgConnection,
|
||||
workspace_id: &str,
|
||||
) -> RuntimeResult<Vec<WorkspaceDocState>> {
|
||||
load_workspace_doc_states_page_in(connection, workspace_id, None, false, None).await
|
||||
}
|
||||
|
||||
pub(in crate::runtime) async fn load_workspace_doc_states_page_in(
|
||||
connection: &mut PgConnection,
|
||||
workspace_id: &str,
|
||||
cursor: Option<&str>,
|
||||
include_cursor: bool,
|
||||
limit: Option<i64>,
|
||||
) -> RuntimeResult<Vec<WorkspaceDocState>> {
|
||||
load_states_in(connection, workspace_id, cursor, include_cursor, limit, None).await
|
||||
}
|
||||
|
||||
pub(in crate::runtime) async fn load_doc_states_in(
|
||||
connection: &mut PgConnection,
|
||||
workspace_id: &str,
|
||||
doc_ids: &[String],
|
||||
) -> RuntimeResult<Vec<WorkspaceDocState>> {
|
||||
load_states_in(connection, workspace_id, None, false, None, Some(doc_ids)).await
|
||||
}
|
||||
|
||||
async fn load_states_in(
|
||||
connection: &mut PgConnection,
|
||||
workspace_id: &str,
|
||||
cursor: Option<&str>,
|
||||
include_cursor: bool,
|
||||
limit: Option<i64>,
|
||||
doc_ids: Option<&[String]>,
|
||||
) -> RuntimeResult<Vec<WorkspaceDocState>> {
|
||||
sqlx::query_as(
|
||||
"SELECT source.doc_id,source.timestamp,page.lifecycle_state::text AS lifecycle,page.lifecycle_changed_at FROM \
|
||||
(SELECT guid AS doc_id,max(timestamp) AS timestamp FROM (SELECT guid,updated_at AS timestamp FROM snapshots \
|
||||
WHERE workspace_id=$1 AND ($5::text[] IS NULL OR guid=ANY($5)) UNION ALL SELECT guid,created_at AS timestamp \
|
||||
FROM updates WHERE workspace_id=$1 AND ($5::text[] IS NULL OR guid=ANY($5))) records GROUP BY guid) source LEFT \
|
||||
JOIN workspace_pages page ON page.workspace_id=$1 AND page.page_id=source.doc_id WHERE page.lifecycle_state IS \
|
||||
DISTINCT FROM 'deleted' AND ($2::text IS NULL OR source.doc_id > $2 OR ($3 AND source.doc_id = $2)) ORDER BY \
|
||||
source.doc_id LIMIT $4",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(cursor)
|
||||
.bind(include_cursor)
|
||||
.bind(limit)
|
||||
.bind(doc_ids)
|
||||
.fetch_all(connection)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("load workspace document states", error))
|
||||
}
|
||||
|
||||
pub(in crate::runtime) async fn ensure_doc_not_deleted_in(
|
||||
connection: &mut PgConnection,
|
||||
workspace_id: &str,
|
||||
doc_id: &str,
|
||||
) -> RuntimeResult<()> {
|
||||
let deleted: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT 1 FROM workspace_pages WHERE workspace_id=$1 AND page_id=$2 AND lifecycle_state='deleted')",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(doc_id)
|
||||
.fetch_one(connection)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("load document tombstone", error))?;
|
||||
if deleted {
|
||||
return Err(RuntimeError::invalid_input("doc_not_found"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(in crate::runtime) async fn ensure_workspace_sync_protocol_in(
|
||||
connection: &mut PgConnection,
|
||||
workspace_id: &str,
|
||||
protocol_version: Option<u32>,
|
||||
) -> RuntimeResult<()> {
|
||||
if protocol_version == Some(2) {
|
||||
return Ok(());
|
||||
}
|
||||
let migrated: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT 1 FROM storage_reconciliation_checkpoints WHERE kind='workspace_doc_lifecycle' AND scope=$1 \
|
||||
AND status='completed')",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.fetch_one(connection)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("load workspace sync protocol", error))?;
|
||||
if migrated {
|
||||
return Err(RuntimeError::invalid_input("sync_protocol_upgrade_required"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -111,16 +111,6 @@ impl RuntimeError {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_serialization_failure(&self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::Database {
|
||||
source: sqlx::Error::Database(source),
|
||||
..
|
||||
} if source.code().as_deref() == Some("40001")
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn is_permanent_search_source(&self) -> bool {
|
||||
matches!(self, Self::SearchSourceInvalid(_))
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ const EMBEDDING_V2_MIGRATION: &str = include_str!("sql/embedding_v2.sql");
|
||||
const SEARCH_PROJECTION_MIGRATION: &str = include_str!("sql/search_projection.sql");
|
||||
const SEARCH_PROJECTION_V2_MIGRATION: &str = include_str!("sql/search_projection_v2.sql");
|
||||
const SEARCH_PROJECTION_V3_MIGRATION: &str = include_str!("sql/search_projection_v3.sql");
|
||||
const SEARCH_PROJECTION_V4_MIGRATION: &str = include_str!("sql/search_projection_v4.sql");
|
||||
const EMBEDDING_ADVISORY_LOCK: i64 = 0x4146_4649_4e45_0046;
|
||||
const SEARCH_ADVISORY_LOCK: i64 = 0x4146_4649_4e45_0053;
|
||||
#[cfg(test)]
|
||||
@@ -93,6 +94,7 @@ pub(crate) async fn migrate_search_tables(pool: &PgPool) -> RuntimeResult<()> {
|
||||
(1, &[SEARCH_PROJECTION_MIGRATION]),
|
||||
(2, &[SEARCH_PROJECTION_V2_MIGRATION]),
|
||||
(3, &[SEARCH_PROJECTION_V3_MIGRATION]),
|
||||
(4, &[SEARCH_PROJECTION_V4_MIGRATION]),
|
||||
],
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -1,14 +1,22 @@
|
||||
pub mod backend_runtime;
|
||||
pub(in crate::runtime) use backend_runtime::lock_current_doc_read;
|
||||
pub mod storage_runtime;
|
||||
|
||||
pub(crate) mod config;
|
||||
pub use config::ServerConfigHandle;
|
||||
mod document_state;
|
||||
pub(crate) mod error;
|
||||
mod http;
|
||||
pub(crate) mod migrations;
|
||||
pub(crate) mod object_storage;
|
||||
mod storage_lifecycle;
|
||||
use storage_lifecycle::{StorageOperation, lock_workspace_storage_shared_transaction};
|
||||
pub(in crate::runtime) use document_state::{
|
||||
WorkspaceDocState, ensure_doc_not_deleted_in, ensure_workspace_sync_protocol_in, is_ordinary_workspace_doc,
|
||||
load_doc_states_in, load_workspace_doc_states_in, load_workspace_doc_states_page_in,
|
||||
};
|
||||
use storage_lifecycle::{
|
||||
StorageOperation, lock_workspace_storage_shared_transaction, try_lock_workspace_storage_shared_transaction,
|
||||
};
|
||||
pub(crate) mod types;
|
||||
|
||||
pub(super) use affine_doc_loader::blob_refs::{BlobRefProjectionError, extract_blob_refs};
|
||||
@@ -30,9 +38,6 @@ fn blob_ref_projection_error_code(error: BlobRefProjectionError) -> &'static str
|
||||
BlobRefProjectionError::PendingDependency => "pending_dependency",
|
||||
BlobRefProjectionError::Unsupported => "yocto_unsupported",
|
||||
BlobRefProjectionError::SourceTooLarge => "blob_ref_source_too_large",
|
||||
BlobRefProjectionError::WorkspaceRootTooLarge => "blob_workspace_root_too_large",
|
||||
BlobRefProjectionError::WorkspaceRootInvalid => "blob_workspace_root_parse_failed",
|
||||
BlobRefProjectionError::WorkspaceRootDocCountTooLarge => "blob_workspace_root_doc_count_too_large",
|
||||
BlobRefProjectionError::TreeTooLarge => "blob_ref_tree_too_large",
|
||||
BlobRefProjectionError::TreeRootInvalid => "blob_ref_tree_root_invalid",
|
||||
BlobRefProjectionError::TreeFanoutTooLarge => "blob_ref_tree_fanout_too_large",
|
||||
@@ -42,4 +47,6 @@ fn blob_ref_projection_error_code(error: BlobRefProjectionError) -> &'static str
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::runtime) use storage_runtime::{CurrentDoc, CurrentDocUpdate};
|
||||
|
||||
pub(super) use crate::entitlement::{entitlement_input_error, parse_quantity, parse_target_type};
|
||||
@@ -117,6 +117,7 @@ CREATE TABLE IF NOT EXISTS doc_blob_ref_projections (
|
||||
workspace_id TEXT NOT NULL,
|
||||
doc_id TEXT NOT NULL,
|
||||
source_revision TIMESTAMPTZ(3),
|
||||
source_fingerprint TEXT,
|
||||
parser_version INTEGER NOT NULL,
|
||||
status TEXT NOT NULL CHECK (status IN ('pending', 'running', 'fresh', 'failed', 'missing')),
|
||||
indexed_at TIMESTAMPTZ(3),
|
||||
@@ -129,6 +130,8 @@ CREATE TABLE IF NOT EXISTS doc_blob_ref_projections (
|
||||
CHECK (error_summary IS NULL OR octet_length(error_summary) <= 512)
|
||||
);
|
||||
|
||||
ALTER TABLE doc_blob_ref_projections ADD COLUMN IF NOT EXISTS source_fingerprint TEXT;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS doc_blob_ref_projections_workspace_status_idx
|
||||
ON doc_blob_ref_projections (workspace_id, status, updated_at DESC);
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
CREATE OR REPLACE FUNCTION search_projection.capture_snapshot_mutation()
|
||||
RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE
|
||||
target_workspace TEXT := COALESCE(NEW.workspace_id, OLD.workspace_id);
|
||||
target_doc TEXT := COALESCE(NEW.guid, OLD.guid);
|
||||
target_version BIGINT;
|
||||
candidate RECORD;
|
||||
BEGIN
|
||||
IF target_doc = target_workspace THEN RETURN COALESCE(NEW, OLD); END IF;
|
||||
PERFORM pg_advisory_xact_lock_shared(hashtextextended('search-projection-generation', 0));
|
||||
target_version := nextval('search_projection.source_mutation_version');
|
||||
|
||||
FOR candidate IN
|
||||
SELECT id, state FROM search_projection.generations
|
||||
WHERE state IN ('building', 'active')
|
||||
LOOP
|
||||
PERFORM search_projection.ensure_workspace_state(candidate.id, target_workspace);
|
||||
UPDATE search_projection.workspace_states
|
||||
SET progress = CASE WHEN last_error = 'search_workspace_reconcile_failed' THEN progress ELSE NULL END,
|
||||
claim_fence = CASE WHEN last_error = 'search_workspace_reconcile_failed'
|
||||
THEN claim_fence ELSE nextval('search_projection.claim_fence') END,
|
||||
lease_owner = CASE WHEN last_error = 'search_workspace_reconcile_failed' THEN lease_owner ELSE NULL END,
|
||||
lease_expires_at = CASE WHEN last_error = 'search_workspace_reconcile_failed'
|
||||
THEN lease_expires_at ELSE NULL END,
|
||||
available_at = CASE WHEN last_error = 'search_workspace_reconcile_failed' THEN available_at ELSE now() END,
|
||||
updated_at = now()
|
||||
WHERE generation_id = candidate.id AND workspace_id = target_workspace;
|
||||
INSERT INTO search_projection.document_states(
|
||||
generation_id, workspace_id, doc_id, target_source_version,
|
||||
target_source_exists, target_permission_version
|
||||
)
|
||||
SELECT candidate.id, target_workspace, target_doc, target_version, TG_OP <> 'DELETE',
|
||||
state.required_permission_version
|
||||
FROM search_projection.workspace_states state
|
||||
WHERE state.generation_id = candidate.id AND state.workspace_id = target_workspace
|
||||
ON CONFLICT (generation_id, workspace_id, doc_id) DO UPDATE
|
||||
SET target_source_version = EXCLUDED.target_source_version,
|
||||
target_source_exists = CASE
|
||||
WHEN TG_OP = 'DELETE' THEN false
|
||||
ELSE search_projection.document_states.target_source_exists END,
|
||||
target_permission_version = GREATEST(search_projection.document_states.target_permission_version, EXCLUDED.target_permission_version),
|
||||
published_source_exists = CASE
|
||||
WHEN TG_OP = 'DELETE' THEN false
|
||||
ELSE search_projection.document_states.published_source_exists END,
|
||||
claim_fence = NULL, lease_owner = NULL, lease_expires_at = NULL,
|
||||
last_error = NULL, available_at = now(), updated_at = now();
|
||||
END LOOP;
|
||||
RETURN COALESCE(NEW, OLD);
|
||||
END;
|
||||
$$;
|
||||
|
||||
UPDATE search_projection.workspace_states
|
||||
SET target_root_revision = nextval('search_projection.source_mutation_version'),
|
||||
pending_scope = 'workspace', progress = NULL,
|
||||
claim_fence = nextval('search_projection.claim_fence'),
|
||||
lease_owner = NULL, lease_expires_at = NULL, last_error = NULL,
|
||||
available_at = now(), updated_at = now();
|
||||
@@ -6,18 +6,24 @@ use super::{RuntimeError, RuntimeResult};
|
||||
|
||||
const LOCK_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
pub(super) async fn try_lock_workspace_storage_shared_transaction(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &str,
|
||||
) -> RuntimeResult<bool> {
|
||||
sqlx::query_scalar("SELECT pg_try_advisory_xact_lock_shared(hashtextextended($1, 0))")
|
||||
.bind(format!("storage-workspace:{workspace_id}"))
|
||||
.fetch_one(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("lock workspace storage source", error))
|
||||
}
|
||||
|
||||
pub(super) async fn lock_workspace_storage_shared_transaction(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &str,
|
||||
) -> RuntimeResult<()> {
|
||||
let key = format!("storage-workspace:{workspace_id}");
|
||||
tokio::time::timeout(LOCK_TIMEOUT, async {
|
||||
loop {
|
||||
let locked: bool = sqlx::query_scalar("SELECT pg_try_advisory_xact_lock_shared(hashtextextended($1, 0))")
|
||||
.bind(&key)
|
||||
.fetch_one(&mut **transaction)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("lock workspace storage source", error))?;
|
||||
let locked = try_lock_workspace_storage_shared_transaction(transaction, workspace_id).await?;
|
||||
if locked {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -35,10 +41,24 @@ pub(super) struct StorageOperation {
|
||||
connection: Option<PoolConnection<Postgres>>,
|
||||
workspace_key: String,
|
||||
object_key: Option<String>,
|
||||
workspace_shared: bool,
|
||||
}
|
||||
|
||||
impl StorageOperation {
|
||||
pub(super) async fn acquire(pool: &PgPool, workspace_id: &str, object_key: Option<&str>) -> RuntimeResult<Self> {
|
||||
Self::acquire_inner(pool, workspace_id, object_key, object_key.is_some()).await
|
||||
}
|
||||
|
||||
pub(super) async fn acquire_shared(pool: &PgPool, workspace_id: &str) -> RuntimeResult<Self> {
|
||||
Self::acquire_inner(pool, workspace_id, None, true).await
|
||||
}
|
||||
|
||||
async fn acquire_inner(
|
||||
pool: &PgPool,
|
||||
workspace_id: &str,
|
||||
object_key: Option<&str>,
|
||||
workspace_shared: bool,
|
||||
) -> RuntimeResult<Self> {
|
||||
tokio::time::timeout(LOCK_TIMEOUT, async {
|
||||
let connection = pool
|
||||
.acquire()
|
||||
@@ -48,8 +68,9 @@ impl StorageOperation {
|
||||
connection: Some(connection),
|
||||
workspace_key: format!("storage-workspace:{workspace_id}"),
|
||||
object_key: object_key.map(|key| format!("storage-object:{key}")),
|
||||
workspace_shared,
|
||||
};
|
||||
let statement = if object_key.is_some() {
|
||||
let statement = if workspace_shared {
|
||||
"SELECT pg_try_advisory_lock_shared(hashtextextended($1,0))"
|
||||
} else {
|
||||
"SELECT pg_try_advisory_lock(hashtextextended($1,0))"
|
||||
@@ -90,7 +111,7 @@ impl StorageOperation {
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("unlock storage object lifecycle", error))?;
|
||||
}
|
||||
let statement = if self.object_key.is_some() {
|
||||
let statement = if self.workspace_shared {
|
||||
"SELECT pg_advisory_unlock_shared(hashtextextended($1,0))"
|
||||
} else {
|
||||
"SELECT pg_advisory_unlock(hashtextextended($1,0))"
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
use chrono::{DateTime, Duration, Utc};
|
||||
use sqlx::{FromRow, PgConnection, PgPool};
|
||||
use sqlx::{FromRow, PgConnection};
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::{
|
||||
RuntimeBlobCleanupResult, RuntimeError, RuntimeResult, StorageOperation, StorageRuntime,
|
||||
doc_blob_refs::PARSER_VERSION, load_workspace_canonical_doc_ids, napi_error,
|
||||
doc_blob_refs::{DOC_BLOB_SOURCES_SQL, PARSER_VERSION, SOURCE_FINGERPRINT_SQL, retained_doc_ids},
|
||||
napi_error,
|
||||
};
|
||||
|
||||
#[derive(FromRow)]
|
||||
@@ -16,122 +17,62 @@ struct BlobRow {
|
||||
deleted_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
async fn checkpoint_completed(pool: &PgPool, kind: &str, scope: &str) -> RuntimeResult<bool> {
|
||||
async fn checkpoint_completed(connection: &mut PgConnection, kind: &str, scope: &str) -> RuntimeResult<bool> {
|
||||
sqlx::query_scalar::<_, bool>(
|
||||
"SELECT EXISTS(SELECT 1 FROM storage_reconciliation_checkpoints WHERE kind = $1 AND scope = $2 AND status = \
|
||||
'completed')",
|
||||
)
|
||||
.bind(kind)
|
||||
.bind(scope)
|
||||
.fetch_one(pool)
|
||||
.fetch_one(connection)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("Blob cleanup checkpoint check failed", error))
|
||||
}
|
||||
|
||||
async fn projection_is_stale(connection: &mut PgConnection, workspace_id: &str) -> RuntimeResult<bool> {
|
||||
let completed_at = sqlx::query_scalar::<_, Option<DateTime<Utc>>>(
|
||||
r#"
|
||||
SELECT MIN(completed_at)
|
||||
FROM storage_reconciliation_checkpoints
|
||||
WHERE scope = $1
|
||||
AND kind IN ('document_cleanup', 'doc_blob_refs')
|
||||
AND status = 'completed'
|
||||
HAVING COUNT(*) = 2
|
||||
"#,
|
||||
let checkpoint = sqlx::query_scalar::<_, serde_json::Value>(
|
||||
"SELECT metadata FROM storage_reconciliation_checkpoints WHERE scope=$1 AND kind='doc_blob_refs' AND \
|
||||
status='completed'",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("Blob cleanup retention checkpoint load failed", error))?
|
||||
.flatten();
|
||||
let Some(completed_at) = completed_at else {
|
||||
.map_err(|error| RuntimeError::database("load blob retention checkpoint", error))?;
|
||||
let Some(checkpoint) = checkpoint else {
|
||||
return Ok(true);
|
||||
};
|
||||
let activity_after_checkpoint = sqlx::query_scalar::<_, bool>(
|
||||
r#"
|
||||
SELECT EXISTS(
|
||||
SELECT 1 FROM snapshots WHERE workspace_id = $1 AND updated_at > $2
|
||||
UNION ALL SELECT 1 FROM updates WHERE workspace_id = $1 AND created_at > $2
|
||||
UNION ALL SELECT 1 FROM snapshot_histories WHERE workspace_id = $1 AND timestamp > $2
|
||||
)
|
||||
"#,
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(completed_at)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("Blob cleanup retention activity check failed", error))?;
|
||||
if sqlx::query_scalar::<_, bool>("SELECT EXISTS(SELECT 1 FROM updates WHERE workspace_id = $1)")
|
||||
.bind(workspace_id)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("Blob cleanup pending update check failed", error))?
|
||||
{
|
||||
if checkpoint.get("parserVersion").and_then(serde_json::Value::as_i64) != Some(i64::from(PARSER_VERSION)) {
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
let mut current_doc_ids = match load_workspace_canonical_doc_ids(&mut *connection, workspace_id).await {
|
||||
Ok(ids) => ids,
|
||||
Err(_) => return Ok(true),
|
||||
};
|
||||
current_doc_ids.push(workspace_id.to_string());
|
||||
current_doc_ids.extend(
|
||||
sqlx::query_scalar::<_, String>(
|
||||
"SELECT doc_id FROM document_cleanup_candidates WHERE workspace_id = $1 AND status IN ('marked', 'failed')",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.fetch_all(&mut *connection)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("Blob cleanup retained document load failed", error))?,
|
||||
);
|
||||
current_doc_ids.sort();
|
||||
current_doc_ids.dedup();
|
||||
let projection_invalid = sqlx::query_scalar::<_, bool>(
|
||||
let current_doc_ids = retained_doc_ids(connection, workspace_id).await?;
|
||||
let query = format!(
|
||||
r#"
|
||||
WITH sources AS ({DOC_BLOB_SOURCES_SQL})
|
||||
SELECT EXISTS(
|
||||
SELECT 1
|
||||
FROM unnest($2::text[]) AS ids(doc_id)
|
||||
LEFT JOIN snapshots s ON s.workspace_id = $1 AND s.guid = ids.doc_id
|
||||
LEFT JOIN doc_blob_ref_projections p ON p.workspace_id = $1 AND p.doc_id = ids.doc_id
|
||||
WHERE s.guid IS NULL
|
||||
OR p.doc_id IS NULL
|
||||
OR p.status <> 'fresh'
|
||||
OR p.parser_version <> $3
|
||||
OR p.source_revision IS DISTINCT FROM s.updated_at
|
||||
SELECT ids.doc_id
|
||||
FROM unnest($3::text[]) AS ids(doc_id)
|
||||
LEFT JOIN sources ON sources.doc_id=ids.doc_id
|
||||
LEFT JOIN doc_blob_ref_projections p ON p.workspace_id=$1 AND p.doc_id=ids.doc_id
|
||||
GROUP BY ids.doc_id,p.doc_id,p.status,p.parser_version,p.source_fingerprint
|
||||
HAVING p.doc_id IS NULL OR p.status <> 'fresh' OR p.parser_version <> $4 OR count(sources.doc_id)=0
|
||||
OR p.source_fingerprint IS DISTINCT FROM {SOURCE_FINGERPRINT_SQL}
|
||||
) OR EXISTS(
|
||||
SELECT 1 FROM doc_blob_ref_projections WHERE workspace_id=$1 AND status <> 'fresh'
|
||||
) OR EXISTS(
|
||||
SELECT 1 FROM doc_blob_refs r LEFT JOIN doc_blob_ref_projections p ON p.workspace_id=r.workspace_id AND p.doc_id=r.doc_id
|
||||
WHERE r.workspace_id=$1 AND (p.doc_id IS NULL OR p.status <> 'fresh' OR r.status <> 'fresh'
|
||||
OR r.parser_version <> p.parser_version OR r.snapshot_updated_at IS DISTINCT FROM p.source_revision)
|
||||
)
|
||||
OR EXISTS(
|
||||
SELECT 1 FROM doc_blob_ref_projections
|
||||
WHERE workspace_id = $1 AND status <> 'fresh'
|
||||
)
|
||||
OR EXISTS(
|
||||
SELECT 1
|
||||
FROM doc_blob_refs r
|
||||
LEFT JOIN doc_blob_ref_projections p
|
||||
ON p.workspace_id = r.workspace_id AND p.doc_id = r.doc_id
|
||||
WHERE r.workspace_id = $1
|
||||
AND (
|
||||
p.doc_id IS NULL
|
||||
OR p.status <> 'fresh'
|
||||
OR r.parser_version <> p.parser_version
|
||||
OR r.snapshot_updated_at IS DISTINCT FROM p.source_revision
|
||||
)
|
||||
)
|
||||
"#,
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(¤t_doc_ids)
|
||||
.bind(PARSER_VERSION)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("Blob cleanup projection state check failed", error))?;
|
||||
let stale_refs = sqlx::query_scalar::<_, bool>(
|
||||
"SELECT EXISTS(SELECT 1 FROM doc_blob_refs WHERE workspace_id = $1 AND status <> 'fresh')",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.fetch_one(&mut *connection)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("Blob cleanup projection freshness check failed", error))?;
|
||||
Ok(activity_after_checkpoint || projection_invalid || stale_refs)
|
||||
"#
|
||||
);
|
||||
sqlx::query_scalar(&query)
|
||||
.bind(workspace_id)
|
||||
.bind(None::<&str>)
|
||||
.bind(¤t_doc_ids)
|
||||
.bind(PARSER_VERSION)
|
||||
.fetch_one(connection)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("check installed blob source fingerprints", error))
|
||||
}
|
||||
|
||||
async fn has_doc_ref<'a>(
|
||||
@@ -190,12 +131,12 @@ async fn has_other_ref<'a>(
|
||||
.map_err(|error| RuntimeError::database("Blob cleanup protected ref check failed", error))
|
||||
}
|
||||
|
||||
async fn load_cursor(pool: &PgPool, workspace_id: &str) -> RuntimeResult<Option<String>> {
|
||||
async fn load_cursor(connection: &mut PgConnection, workspace_id: &str) -> RuntimeResult<Option<String>> {
|
||||
let row = sqlx::query_as::<_, (String, serde_json::Value)>(
|
||||
"SELECT status, cursor FROM storage_reconciliation_checkpoints WHERE kind = 'blob_cleanup' AND scope = $1",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.fetch_optional(pool)
|
||||
.fetch_optional(connection)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("Blob cleanup checkpoint load failed", error))?;
|
||||
let Some((status, cursor)) = row else {
|
||||
@@ -213,7 +154,7 @@ async fn load_cursor(pool: &PgPool, workspace_id: &str) -> RuntimeResult<Option<
|
||||
}
|
||||
|
||||
async fn save_cursor(
|
||||
pool: &PgPool,
|
||||
connection: &mut PgConnection,
|
||||
workspace_id: &str,
|
||||
last_blob_key: Option<&str>,
|
||||
completed: bool,
|
||||
@@ -236,13 +177,13 @@ async fn save_cursor(
|
||||
.bind(serde_json::json!({ "lastBlobKey": last_blob_key }))
|
||||
.bind(last_blob_key)
|
||||
.bind(completed)
|
||||
.execute(pool)
|
||||
.execute(connection)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("Blob cleanup checkpoint write failed", error))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn load_denied(pool: &PgPool, workspace_id: &str, limit: i64) -> RuntimeResult<Vec<BlobRow>> {
|
||||
async fn load_denied(connection: &mut PgConnection, workspace_id: &str, limit: i64) -> RuntimeResult<Vec<BlobRow>> {
|
||||
sqlx::query_as::<_, BlobRow>(
|
||||
r#"
|
||||
SELECT workspace_id, key, size, reservation_id, deleted_at
|
||||
@@ -254,13 +195,13 @@ async fn load_denied(pool: &PgPool, workspace_id: &str, limit: i64) -> RuntimeRe
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(limit)
|
||||
.fetch_all(pool)
|
||||
.fetch_all(connection)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("Blob cleanup denied row load failed", error))
|
||||
}
|
||||
|
||||
async fn load_live(
|
||||
pool: &PgPool,
|
||||
connection: &mut PgConnection,
|
||||
workspace_id: &str,
|
||||
after_key: Option<&str>,
|
||||
limit: i64,
|
||||
@@ -280,7 +221,7 @@ async fn load_live(
|
||||
.bind(workspace_id)
|
||||
.bind(after_key)
|
||||
.bind(limit)
|
||||
.fetch_all(pool)
|
||||
.fetch_all(connection)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("Blob cleanup live row load failed", error))
|
||||
}
|
||||
@@ -312,27 +253,24 @@ impl StorageRuntime {
|
||||
next_cursor: None,
|
||||
workspace_ids: Vec::new(),
|
||||
};
|
||||
let cursor = load_cursor(&pool, &workspace_id).await?;
|
||||
if !checkpoint_completed(&pool, "blob_metadata_backfill", &workspace_id).await?
|
||||
|| projection_is_stale(
|
||||
&mut *pool
|
||||
.acquire()
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("acquire retention projection connection", error))?,
|
||||
&workspace_id,
|
||||
)
|
||||
.await?
|
||||
let mut operation = StorageOperation::acquire(&pool, &workspace_id, None).await?;
|
||||
let cursor = load_cursor(operation.connection(), &workspace_id).await?;
|
||||
if !checkpoint_completed(operation.connection(), "blob_metadata_backfill", &workspace_id).await?
|
||||
|| projection_is_stale(operation.connection(), &workspace_id).await?
|
||||
{
|
||||
result.protected_by_metadata = load_live(&pool, &workspace_id, cursor.as_deref(), limit).await?.len() as i64;
|
||||
result.protected_by_metadata = load_live(operation.connection(), &workspace_id, cursor.as_deref(), limit)
|
||||
.await?
|
||||
.len() as i64;
|
||||
operation.release().await?;
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
let denied = load_denied(&pool, &workspace_id, limit).await?;
|
||||
let denied = load_denied(operation.connection(), &workspace_id, limit).await?;
|
||||
let recovering = !denied.is_empty();
|
||||
let rows = if recovering {
|
||||
denied
|
||||
} else {
|
||||
load_live(&pool, &workspace_id, cursor.as_deref(), limit).await?
|
||||
load_live(operation.connection(), &workspace_id, cursor.as_deref(), limit).await?
|
||||
};
|
||||
result.scanned_blobs = rows.len() as i64;
|
||||
let has_more = recovering || rows.len() == limit as usize;
|
||||
@@ -340,7 +278,7 @@ impl StorageRuntime {
|
||||
let minimum_modified = Utc::now() - Duration::days(grace_period_days);
|
||||
for row in rows {
|
||||
if self
|
||||
.cleanup_blob_row(&pool, &row, minimum_modified, &mut result)
|
||||
.cleanup_blob_row(operation.connection(), &row, minimum_modified, &mut result)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
@@ -351,8 +289,9 @@ impl StorageRuntime {
|
||||
result.next_cursor = cursor;
|
||||
} else {
|
||||
result.next_cursor = has_more.then_some(last_key.clone()).flatten();
|
||||
save_cursor(&pool, &workspace_id, last_key.as_deref(), !has_more).await?;
|
||||
save_cursor(operation.connection(), &workspace_id, last_key.as_deref(), !has_more).await?;
|
||||
}
|
||||
operation.release().await?;
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
@@ -360,94 +299,84 @@ impl StorageRuntime {
|
||||
impl StorageRuntime {
|
||||
async fn cleanup_blob_row(
|
||||
&self,
|
||||
pool: &PgPool,
|
||||
connection: &mut PgConnection,
|
||||
row: &BlobRow,
|
||||
minimum_modified: DateTime<Utc>,
|
||||
result: &mut RuntimeBlobCleanupResult,
|
||||
) -> RuntimeResult<()> {
|
||||
let object_key = format!("{}/{}", row.workspace_id, row.key);
|
||||
let mut operation = StorageOperation::acquire(pool, &row.workspace_id, None).await?;
|
||||
let outcome = async {
|
||||
if projection_is_stale(operation.connection(), &row.workspace_id).await? {
|
||||
result.protected_by_metadata += 1;
|
||||
return Ok(());
|
||||
}
|
||||
let doc_ref = has_doc_ref(operation.connection(), &row.workspace_id, &row.key).await?;
|
||||
let other_ref = has_other_ref(operation.connection(), &row.workspace_id, &row.key).await?;
|
||||
let metadata = self.object_storage_head(object_key.clone()).await?;
|
||||
if doc_ref || other_ref {
|
||||
if row.deleted_at.is_some() && metadata.is_some() {
|
||||
sqlx::query(
|
||||
"UPDATE blobs SET deleted_at = NULL WHERE workspace_id = $1 AND key = $2 AND reservation_id IS NOT \
|
||||
DISTINCT FROM $3 AND deleted_at IS NOT NULL",
|
||||
)
|
||||
.bind(&row.workspace_id)
|
||||
.bind(&row.key)
|
||||
.bind(row.reservation_id)
|
||||
.execute(operation.connection())
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("restore referenced blob cleanup row", error))?;
|
||||
}
|
||||
if doc_ref {
|
||||
result.protected_by_doc_refs += 1;
|
||||
}
|
||||
if other_ref {
|
||||
result.protected_by_other_refs += 1;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if row.deleted_at.is_none() {
|
||||
let Some(metadata) = metadata.as_ref() else {
|
||||
result.protected_by_metadata += 1;
|
||||
return Ok(());
|
||||
};
|
||||
let modified = DateTime::<Utc>::from_timestamp_millis(metadata.last_modified_ms)
|
||||
.ok_or_else(|| RuntimeError::invalid_state("blob cleanup object last modified is invalid"))?;
|
||||
if metadata.content_length != i64::from(row.size) || modified > minimum_modified {
|
||||
result.protected_by_metadata += 1;
|
||||
return Ok(());
|
||||
}
|
||||
let denied = sqlx::query_scalar::<_, bool>(
|
||||
"UPDATE blobs SET deleted_at = clock_timestamp(), reservation_expires_at = NULL WHERE workspace_id = $1 AND \
|
||||
key = $2 AND status = 'completed' AND deleted_at IS NULL AND reservation_id IS NOT DISTINCT FROM $3 \
|
||||
RETURNING true",
|
||||
let doc_ref = has_doc_ref(&mut *connection, &row.workspace_id, &row.key).await?;
|
||||
let other_ref = has_other_ref(&mut *connection, &row.workspace_id, &row.key).await?;
|
||||
let metadata = self.object_storage_head(object_key.clone()).await?;
|
||||
if doc_ref || other_ref {
|
||||
if row.deleted_at.is_some() && metadata.is_some() {
|
||||
sqlx::query(
|
||||
"UPDATE blobs SET deleted_at = NULL WHERE workspace_id = $1 AND key = $2 AND reservation_id IS NOT DISTINCT \
|
||||
FROM $3 AND deleted_at IS NOT NULL",
|
||||
)
|
||||
.bind(&row.workspace_id)
|
||||
.bind(&row.key)
|
||||
.bind(row.reservation_id)
|
||||
.fetch_optional(operation.connection())
|
||||
.execute(&mut *connection)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("deny unreferenced blob", error))?
|
||||
.unwrap_or(false);
|
||||
if !denied {
|
||||
return Ok(());
|
||||
}
|
||||
.map_err(|error| RuntimeError::database("restore referenced blob cleanup row", error))?;
|
||||
}
|
||||
if metadata.is_some() {
|
||||
let locator = super::ObjectLocator::new(super::StorageScope::Blob, super::ObjectKey::new(object_key)?);
|
||||
self.object_storage()?.delete(&locator).await?;
|
||||
result.deleted_objects += 1;
|
||||
if doc_ref {
|
||||
result.protected_by_doc_refs += 1;
|
||||
}
|
||||
let deleted = sqlx::query(
|
||||
"DELETE FROM blobs WHERE workspace_id = $1 AND key = $2 AND status = 'completed' AND deleted_at IS NOT NULL \
|
||||
AND reservation_id IS NOT DISTINCT FROM $3",
|
||||
if other_ref {
|
||||
result.protected_by_other_refs += 1;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if row.deleted_at.is_none() {
|
||||
let Some(metadata) = metadata.as_ref() else {
|
||||
result.protected_by_metadata += 1;
|
||||
return Ok(());
|
||||
};
|
||||
let modified = DateTime::<Utc>::from_timestamp_millis(metadata.last_modified_ms)
|
||||
.ok_or_else(|| RuntimeError::invalid_state("blob cleanup object last modified is invalid"))?;
|
||||
if metadata.content_length != i64::from(row.size) || modified > minimum_modified {
|
||||
result.protected_by_metadata += 1;
|
||||
return Ok(());
|
||||
}
|
||||
let denied = sqlx::query_scalar::<_, bool>(
|
||||
"UPDATE blobs SET deleted_at = clock_timestamp(), reservation_expires_at = NULL WHERE workspace_id = $1 AND \
|
||||
key = $2 AND status = 'completed' AND deleted_at IS NULL AND reservation_id IS NOT DISTINCT FROM $3 \
|
||||
RETURNING true",
|
||||
)
|
||||
.bind(&row.workspace_id)
|
||||
.bind(&row.key)
|
||||
.bind(row.reservation_id)
|
||||
.execute(operation.connection())
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("delete unreferenced blob ledger", error))?
|
||||
.rows_affected() as i64;
|
||||
result.deleted_metadata += deleted;
|
||||
if deleted > 0 && !result.workspace_ids.iter().any(|id| id == &row.workspace_id) {
|
||||
result.workspace_ids.push(row.workspace_id.clone());
|
||||
.map_err(|error| RuntimeError::database("deny unreferenced blob", error))?
|
||||
.unwrap_or(false);
|
||||
if !denied {
|
||||
return Ok(());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
.await;
|
||||
let released = operation.release().await;
|
||||
outcome.and(released)
|
||||
if metadata.is_some() {
|
||||
let locator = super::ObjectLocator::new(super::StorageScope::Blob, super::ObjectKey::new(object_key)?);
|
||||
self.object_storage()?.delete(&locator).await?;
|
||||
result.deleted_objects += 1;
|
||||
}
|
||||
let deleted = sqlx::query(
|
||||
"DELETE FROM blobs WHERE workspace_id = $1 AND key = $2 AND status = 'completed' AND deleted_at IS NOT NULL AND \
|
||||
reservation_id IS NOT DISTINCT FROM $3",
|
||||
)
|
||||
.bind(&row.workspace_id)
|
||||
.bind(&row.key)
|
||||
.bind(row.reservation_id)
|
||||
.execute(&mut *connection)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("delete unreferenced blob ledger", error))?
|
||||
.rows_affected() as i64;
|
||||
result.deleted_metadata += deleted;
|
||||
if deleted > 0 && !result.workspace_ids.iter().any(|id| id == &row.workspace_id) {
|
||||
result.workspace_ids.push(row.workspace_id.clone());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -460,7 +389,7 @@ mod tests {
|
||||
|
||||
use anyhow::{Context, Result as AnyResult};
|
||||
use napi::bindgen_prelude::Buffer;
|
||||
use sqlx::postgres::PgPoolOptions;
|
||||
use sqlx::{PgPool, postgres::PgPoolOptions};
|
||||
use tempfile::TempDir;
|
||||
use tokio::sync::Mutex;
|
||||
use uuid::Uuid;
|
||||
@@ -487,9 +416,6 @@ mod tests {
|
||||
let doc = Doc::default();
|
||||
let mut blocks = doc.get_or_create_map("blocks").expect("blocks root should build");
|
||||
let mut attachment = doc.create_map().expect("attachment should build");
|
||||
attachment
|
||||
.insert("sys:id".to_string(), "attachment")
|
||||
.expect("attachment id should insert");
|
||||
attachment
|
||||
.insert("sys:flavour".to_string(), "affine:attachment")
|
||||
.expect("attachment flavour should insert");
|
||||
@@ -539,17 +465,23 @@ mod tests {
|
||||
let suffix = Uuid::new_v4().simple().to_string();
|
||||
let workspace_id = format!("blob-cleanup-ws-{suffix}");
|
||||
let doc_id = format!("blob-cleanup-doc-{suffix}");
|
||||
let blob_key = format!("blob-cleanup-attachment-{suffix}");
|
||||
let blob_key = "live-blob".to_string();
|
||||
sqlx::query("INSERT INTO workspaces (id, created_at) VALUES ($1, CURRENT_TIMESTAMP)")
|
||||
.bind(&workspace_id)
|
||||
.execute(&pool)
|
||||
.await?;
|
||||
let root = affine_doc_loader::add_doc_to_root_doc(Vec::new(), &doc_id, None)?;
|
||||
let mut root_doc = Doc::default();
|
||||
root_doc.apply_update_from_binary_v1(&root)?;
|
||||
root_doc.get_or_create_map("blocks")?.insert("fixture".into(), "root")?;
|
||||
let root = root_doc.encode_update_v1()?;
|
||||
let doc = attachment_doc(with_ref.then_some(blob_key.as_str()));
|
||||
let root = vec![0_u8, 0];
|
||||
let doc = if with_ref {
|
||||
vec![
|
||||
2, 4, 2, 0, 39, 1, 6, 98, 108, 111, 99, 107, 115, 5, 105, 109, 97, 103, 101, 1, 40, 0, 2, 0, 6, 115, 121, 115,
|
||||
58, 105, 100, 1, 119, 5, 105, 109, 97, 103, 101, 40, 0, 2, 0, 11, 115, 121, 115, 58, 102, 108, 97, 118, 111,
|
||||
117, 114, 1, 119, 12, 97, 102, 102, 105, 110, 101, 58, 105, 109, 97, 103, 101, 40, 0, 2, 0, 13, 112, 114, 111,
|
||||
112, 58, 115, 111, 117, 114, 99, 101, 73, 100, 1, 119, 9, 108, 105, 118, 101, 45, 98, 108, 111, 98, 1, 1, 0,
|
||||
33, 1, 6, 98, 108, 111, 99, 107, 115, 5, 105, 109, 97, 103, 101, 1, 1, 1, 1, 0, 1,
|
||||
]
|
||||
} else {
|
||||
attachment_doc(None)
|
||||
};
|
||||
sqlx::query(
|
||||
"INSERT INTO snapshots (workspace_id, guid, blob, updated_at) VALUES ($1, $1, $2, CURRENT_TIMESTAMP), ($1, $3, \
|
||||
$4, CURRENT_TIMESTAMP)",
|
||||
@@ -589,7 +521,7 @@ mod tests {
|
||||
}
|
||||
|
||||
async fn complete_cleanup_checkpoints(pool: &PgPool, workspace_id: &str) -> AnyResult<()> {
|
||||
for kind in ["document_cleanup", "blob_metadata_backfill", "doc_blob_refs"] {
|
||||
for kind in ["blob_metadata_backfill", "doc_blob_refs"] {
|
||||
sqlx::query(
|
||||
"INSERT INTO storage_reconciliation_checkpoints (kind, scope, status, cursor, completed_at, metadata) VALUES \
|
||||
($1, $2, 'completed', '{}', CURRENT_TIMESTAMP, '{}') ON CONFLICT (kind, scope) DO UPDATE SET status = \
|
||||
@@ -609,7 +541,10 @@ mod tests {
|
||||
"blob_cleanup_candidates",
|
||||
"doc_blob_refs",
|
||||
"doc_blob_ref_projections",
|
||||
"updates",
|
||||
"snapshot_histories",
|
||||
"snapshots",
|
||||
"workspace_pages",
|
||||
"blobs",
|
||||
] {
|
||||
sqlx::query(&format!("DELETE FROM {table} WHERE workspace_id = $1"))
|
||||
@@ -693,6 +628,14 @@ mod tests {
|
||||
let _guard = EMBEDDING_TEST_LOCK.lock().await;
|
||||
let fixture = blob_cleanup_fixture(true).await?;
|
||||
let _object_root = &fixture.object_root;
|
||||
sqlx::query(
|
||||
"INSERT INTO workspace_pages (workspace_id,page_id,lifecycle_state,lifecycle_changed_at) VALUES \
|
||||
($1,$2,'trashed',CURRENT_TIMESTAMP)",
|
||||
)
|
||||
.bind(&fixture.workspace_id)
|
||||
.bind(&fixture.doc_id)
|
||||
.execute(&fixture.pool)
|
||||
.await?;
|
||||
fixture
|
||||
.runtime
|
||||
.rebuild_workspace_doc_blob_refs(fixture.workspace_id.clone(), 100)
|
||||
@@ -700,6 +643,24 @@ mod tests {
|
||||
.map_err(|err| anyhow::anyhow!(err.to_string()))?;
|
||||
complete_cleanup_checkpoints(&fixture.pool, &fixture.workspace_id).await?;
|
||||
|
||||
// A fresh empty result from the old parser cannot authorize deletion.
|
||||
sqlx::query("DELETE FROM doc_blob_refs WHERE workspace_id=$1")
|
||||
.bind(&fixture.workspace_id)
|
||||
.execute(&fixture.pool)
|
||||
.await?;
|
||||
sqlx::query("UPDATE doc_blob_ref_projections SET parser_version=1,status='fresh' WHERE workspace_id=$1")
|
||||
.bind(&fixture.workspace_id)
|
||||
.execute(&fixture.pool)
|
||||
.await?;
|
||||
let old = fixture
|
||||
.runtime
|
||||
.cleanup_unreferenced_workspace_blobs(fixture.workspace_id.clone(), 0, 100)
|
||||
.await?;
|
||||
assert_eq!((old.deleted_objects, old.protected_by_metadata), (0, 1));
|
||||
fixture
|
||||
.runtime
|
||||
.rebuild_workspace_doc_blob_refs(fixture.workspace_id.clone(), 100)
|
||||
.await?;
|
||||
let referenced = fixture
|
||||
.runtime
|
||||
.cleanup_unreferenced_workspace_blobs(fixture.workspace_id.clone(), 0, 100)
|
||||
@@ -718,6 +679,95 @@ mod tests {
|
||||
.is_some()
|
||||
);
|
||||
|
||||
assert!(
|
||||
sqlx::query_scalar::<_, bool>("SELECT deleted_at IS NULL FROM blobs WHERE workspace_id=$1 AND key=$2")
|
||||
.bind(&fixture.workspace_id)
|
||||
.bind(&fixture.blob_key)
|
||||
.fetch_one(&fixture.pool)
|
||||
.await?
|
||||
);
|
||||
let projection_before = sqlx::query_as::<_, (String, String)>(
|
||||
"SELECT status,source_fingerprint FROM doc_blob_ref_projections WHERE workspace_id=$1 AND doc_id=$2",
|
||||
)
|
||||
.bind(&fixture.workspace_id)
|
||||
.bind(&fixture.doc_id)
|
||||
.fetch_one(&fixture.pool)
|
||||
.await?;
|
||||
let refs_before =
|
||||
sqlx::query_scalar::<_, i64>("SELECT count(*) FROM doc_blob_refs WHERE workspace_id=$1 AND doc_id=$2")
|
||||
.bind(&fixture.workspace_id)
|
||||
.bind(&fixture.doc_id)
|
||||
.fetch_one(&fixture.pool)
|
||||
.await?;
|
||||
assert!(refs_before > 0);
|
||||
let suffix = Uuid::new_v4().simple().to_string();
|
||||
let function_name = format!("blob_purge_fault_{suffix}");
|
||||
let trigger_name = format!("blob_purge_fault_{suffix}");
|
||||
let mut connection = fixture.pool.acquire().await?;
|
||||
sqlx::raw_sql(&format!(
|
||||
"CREATE FUNCTION {function_name}() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'blob \
|
||||
projection delete fault'; END $$; CREATE TRIGGER {trigger_name} BEFORE DELETE ON doc_blob_ref_projections FOR \
|
||||
EACH ROW WHEN (OLD.workspace_id='{}') EXECUTE FUNCTION {function_name}()",
|
||||
fixture.workspace_id
|
||||
))
|
||||
.execute(&mut *connection)
|
||||
.await?;
|
||||
let interrupted = super::super::doc_blob_refs::purge_removed_doc_projections(
|
||||
&mut connection,
|
||||
&fixture.workspace_id,
|
||||
std::slice::from_ref(&fixture.workspace_id),
|
||||
)
|
||||
.await;
|
||||
sqlx::raw_sql(&format!(
|
||||
"DROP TRIGGER {trigger_name} ON doc_blob_ref_projections; DROP FUNCTION {function_name}()"
|
||||
))
|
||||
.execute(&mut *connection)
|
||||
.await?;
|
||||
let refs_after =
|
||||
sqlx::query_scalar::<_, i64>("SELECT count(*) FROM doc_blob_refs WHERE workspace_id=$1 AND doc_id=$2")
|
||||
.bind(&fixture.workspace_id)
|
||||
.bind(&fixture.doc_id)
|
||||
.fetch_one(&mut *connection)
|
||||
.await?;
|
||||
let projection_after = sqlx::query_as::<_, (String, String)>(
|
||||
"SELECT status,source_fingerprint FROM doc_blob_ref_projections WHERE workspace_id=$1 AND doc_id=$2",
|
||||
)
|
||||
.bind(&fixture.workspace_id)
|
||||
.bind(&fixture.doc_id)
|
||||
.fetch_one(&mut *connection)
|
||||
.await?;
|
||||
drop(connection);
|
||||
assert!(
|
||||
interrupted
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("blob projection delete fault")
|
||||
);
|
||||
assert_eq!(
|
||||
refs_after, refs_before,
|
||||
"failed projection deletion must roll back reference deletion"
|
||||
);
|
||||
assert_eq!(projection_after, projection_before);
|
||||
let retained_after_failure = fixture
|
||||
.runtime
|
||||
.cleanup_unreferenced_workspace_blobs(fixture.workspace_id.clone(), 0, 100)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
(
|
||||
retained_after_failure.deleted_objects,
|
||||
retained_after_failure.protected_by_doc_refs
|
||||
),
|
||||
(0, 1)
|
||||
);
|
||||
sqlx::query(
|
||||
"INSERT INTO snapshot_histories (workspace_id,guid,blob,timestamp,expired_at) SELECT \
|
||||
workspace_id,guid,blob,updated_at,clock_timestamp()+interval '1 day' FROM snapshots WHERE workspace_id=$1 AND \
|
||||
guid=$2",
|
||||
)
|
||||
.bind(&fixture.workspace_id)
|
||||
.bind(&fixture.doc_id)
|
||||
.execute(&fixture.pool)
|
||||
.await?;
|
||||
sqlx::query("UPDATE snapshots SET blob = $3, updated_at = clock_timestamp() WHERE workspace_id = $1 AND guid = $2")
|
||||
.bind(&fixture.workspace_id)
|
||||
.bind(&fixture.doc_id)
|
||||
@@ -738,6 +788,153 @@ mod tests {
|
||||
.map_err(|err| anyhow::anyhow!(err.to_string()))?;
|
||||
complete_cleanup_checkpoints(&fixture.pool, &fixture.workspace_id).await?;
|
||||
|
||||
let history = fixture
|
||||
.runtime
|
||||
.cleanup_unreferenced_workspace_blobs(fixture.workspace_id.clone(), 0, 100)
|
||||
.await?;
|
||||
assert_eq!((history.deleted_objects, history.protected_by_doc_refs), (0, 1));
|
||||
sqlx::query("UPDATE snapshot_histories SET expired_at=clock_timestamp()-interval '1 day' WHERE workspace_id=$1")
|
||||
.bind(&fixture.workspace_id)
|
||||
.execute(&fixture.pool)
|
||||
.await?;
|
||||
let expired = fixture
|
||||
.runtime
|
||||
.cleanup_unreferenced_workspace_blobs(fixture.workspace_id.clone(), 0, 100)
|
||||
.await?;
|
||||
assert_eq!(expired.deleted_objects, 0);
|
||||
fixture
|
||||
.runtime
|
||||
.rebuild_workspace_doc_blob_refs(fixture.workspace_id.clone(), 100)
|
||||
.await?;
|
||||
let (old_revision, old_fingerprint) = sqlx::query_as::<_, (DateTime<Utc>, String)>(
|
||||
"SELECT source_revision,source_fingerprint FROM doc_blob_ref_projections WHERE workspace_id=$1 AND doc_id=$2",
|
||||
)
|
||||
.bind(&fixture.workspace_id)
|
||||
.bind(&fixture.doc_id)
|
||||
.fetch_one(&fixture.pool)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO snapshot_histories(workspace_id,guid,blob,timestamp,expired_at) VALUES($1,$2,$3,$4-interval '1 \
|
||||
day',clock_timestamp()+interval '1 day')",
|
||||
)
|
||||
.bind(&fixture.workspace_id)
|
||||
.bind(&fixture.doc_id)
|
||||
.bind(attachment_doc(Some(&fixture.blob_key)))
|
||||
.bind(old_revision)
|
||||
.execute(&fixture.pool)
|
||||
.await?;
|
||||
fixture
|
||||
.runtime
|
||||
.rebuild_workspace_doc_blob_refs(fixture.workspace_id.clone(), 100)
|
||||
.await?;
|
||||
let mut connection = fixture.pool.acquire().await?;
|
||||
let stale = super::super::doc_blob_refs::replace_doc_refs(
|
||||
&mut connection,
|
||||
&fixture.workspace_id,
|
||||
&fixture.doc_id,
|
||||
old_revision,
|
||||
&old_fingerprint,
|
||||
Vec::new(),
|
||||
)
|
||||
.await?;
|
||||
assert!(
|
||||
stale.is_none(),
|
||||
"a late source without the older retained history cannot overwrite the current projection"
|
||||
);
|
||||
drop(connection);
|
||||
let retained = fixture
|
||||
.runtime
|
||||
.cleanup_unreferenced_workspace_blobs(fixture.workspace_id.clone(), 0, 100)
|
||||
.await?;
|
||||
assert_eq!((retained.deleted_objects, retained.protected_by_doc_refs), (0, 1));
|
||||
sqlx::query("DELETE FROM doc_blob_refs WHERE workspace_id=$1 AND doc_id=$2")
|
||||
.bind(&fixture.workspace_id)
|
||||
.bind(&fixture.doc_id)
|
||||
.execute(&fixture.pool)
|
||||
.await?;
|
||||
sqlx::query("UPDATE doc_blob_ref_projections SET source_fingerprint=$3 WHERE workspace_id=$1 AND doc_id=$2")
|
||||
.bind(&fixture.workspace_id)
|
||||
.bind(&fixture.doc_id)
|
||||
.bind(old_fingerprint)
|
||||
.execute(&fixture.pool)
|
||||
.await?;
|
||||
let stale_installed = fixture
|
||||
.runtime
|
||||
.cleanup_unreferenced_workspace_blobs(fixture.workspace_id.clone(), 0, 100)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
(stale_installed.deleted_objects, stale_installed.protected_by_metadata),
|
||||
(0, 1)
|
||||
);
|
||||
sqlx::query("UPDATE snapshot_histories SET expired_at=clock_timestamp()-interval '1 day' WHERE workspace_id=$1")
|
||||
.bind(&fixture.workspace_id)
|
||||
.execute(&fixture.pool)
|
||||
.await?;
|
||||
let jobs = tokio::time::timeout(std::time::Duration::from_secs(10), async {
|
||||
tokio::join!(
|
||||
fixture
|
||||
.runtime
|
||||
.rebuild_workspace_doc_blob_refs(fixture.workspace_id.clone(), 100),
|
||||
fixture
|
||||
.runtime
|
||||
.rebuild_workspace_doc_blob_refs(fixture.workspace_id.clone(), 100),
|
||||
fixture
|
||||
.runtime
|
||||
.rebuild_workspace_doc_blob_refs(fixture.workspace_id.clone(), 100),
|
||||
fixture
|
||||
.runtime
|
||||
.rebuild_workspace_doc_blob_refs(fixture.workspace_id.clone(), 100),
|
||||
fixture
|
||||
.runtime
|
||||
.rebuild_workspace_doc_blob_refs(fixture.workspace_id.clone(), 100)
|
||||
)
|
||||
})
|
||||
.await?;
|
||||
for job in [jobs.0, jobs.1, jobs.2, jobs.3, jobs.4] {
|
||||
assert_eq!(job?.failed_docs, 0);
|
||||
}
|
||||
for source_id in [
|
||||
fixture.workspace_id.clone(),
|
||||
format!("db${}$folders", fixture.workspace_id),
|
||||
] {
|
||||
let blob = if source_id == fixture.workspace_id {
|
||||
let root = Doc::default();
|
||||
root
|
||||
.get_or_create_map("meta")?
|
||||
.insert("avatar".into(), fixture.blob_key.clone())?;
|
||||
root.encode_update_v1()?
|
||||
} else {
|
||||
attachment_doc(Some(&fixture.blob_key))
|
||||
};
|
||||
sqlx::query(
|
||||
"INSERT INTO snapshots(workspace_id,guid,blob,updated_at) VALUES($1,$2,$3,clock_timestamp()) ON \
|
||||
CONFLICT(workspace_id,guid) DO UPDATE SET blob=EXCLUDED.blob,updated_at=EXCLUDED.updated_at",
|
||||
)
|
||||
.bind(&fixture.workspace_id)
|
||||
.bind(&source_id)
|
||||
.bind(blob)
|
||||
.execute(&fixture.pool)
|
||||
.await?;
|
||||
fixture
|
||||
.runtime
|
||||
.rebuild_workspace_doc_blob_refs(fixture.workspace_id.clone(), 100)
|
||||
.await?;
|
||||
let retained = fixture
|
||||
.runtime
|
||||
.cleanup_unreferenced_workspace_blobs(fixture.workspace_id.clone(), 0, 100)
|
||||
.await?;
|
||||
assert_eq!((retained.deleted_objects, retained.protected_by_doc_refs), (0, 1));
|
||||
sqlx::query("UPDATE snapshots SET blob=$3,updated_at=clock_timestamp() WHERE workspace_id=$1 AND guid=$2")
|
||||
.bind(&fixture.workspace_id)
|
||||
.bind(&source_id)
|
||||
.bind(vec![0_u8, 0])
|
||||
.execute(&fixture.pool)
|
||||
.await?;
|
||||
}
|
||||
fixture
|
||||
.runtime
|
||||
.rebuild_workspace_doc_blob_refs(fixture.workspace_id.clone(), 100)
|
||||
.await?;
|
||||
let executed = fixture
|
||||
.runtime
|
||||
.cleanup_unreferenced_workspace_blobs(fixture.workspace_id.clone(), 0, 100)
|
||||
@@ -767,7 +964,7 @@ mod tests {
|
||||
#[ignore = "requires DATABASE_URL and a migrated PostgreSQL database"]
|
||||
async fn blob_cleanup_projection_outdated_pending_and_failed_projections_fail_closed() -> AnyResult<()> {
|
||||
let _guard = EMBEDDING_TEST_LOCK.lock().await;
|
||||
for status in ["fresh", "pending", "failed"] {
|
||||
for status in ["fresh", "pending", "failed", "partial"] {
|
||||
let fixture = blob_cleanup_fixture(false).await?;
|
||||
let _object_root = &fixture.object_root;
|
||||
fixture
|
||||
@@ -776,12 +973,30 @@ mod tests {
|
||||
.await
|
||||
.map_err(|err| anyhow::anyhow!(err.to_string()))?;
|
||||
complete_cleanup_checkpoints(&fixture.pool, &fixture.workspace_id).await?;
|
||||
if status == "partial" {
|
||||
let doc = Doc::with_client(1);
|
||||
doc.get_or_create_text("gap")?.insert(0, "prefix")?;
|
||||
let state = doc.get_state_vector();
|
||||
doc.get_or_create_text("gap")?.insert(6, "tail")?;
|
||||
let partial = doc.encode_state_as_update_v1(&state)?;
|
||||
sqlx::query("UPDATE snapshots SET blob=$3,updated_at=clock_timestamp() WHERE workspace_id=$1 AND guid=$2")
|
||||
.bind(&fixture.workspace_id)
|
||||
.bind(&fixture.doc_id)
|
||||
.bind(partial)
|
||||
.execute(&fixture.pool)
|
||||
.await?;
|
||||
let projection = fixture
|
||||
.runtime
|
||||
.rebuild_workspace_doc_blob_refs(fixture.workspace_id.clone(), 100)
|
||||
.await?;
|
||||
assert_eq!(projection.failed_docs, 1);
|
||||
}
|
||||
sqlx::query(
|
||||
"UPDATE doc_blob_ref_projections SET parser_version = 0, status = $3 WHERE workspace_id = $1 AND doc_id = $2",
|
||||
"UPDATE doc_blob_ref_projections SET parser_version = 1, status = $3 WHERE workspace_id = $1 AND doc_id = $2",
|
||||
)
|
||||
.bind(&fixture.workspace_id)
|
||||
.bind(&fixture.doc_id)
|
||||
.bind(status)
|
||||
.bind(if status == "partial" { "failed" } else { status })
|
||||
.execute(&fixture.pool)
|
||||
.await?;
|
||||
|
||||
@@ -795,16 +1010,18 @@ mod tests {
|
||||
(0, 1)
|
||||
);
|
||||
|
||||
sqlx::query(
|
||||
"UPDATE doc_blob_ref_projections p SET parser_version = $3, status = 'fresh', source_revision = s.updated_at \
|
||||
FROM snapshots s WHERE p.workspace_id = $1 AND p.doc_id = $2 AND s.workspace_id = p.workspace_id AND s.guid \
|
||||
= p.doc_id",
|
||||
)
|
||||
.bind(&fixture.workspace_id)
|
||||
.bind(&fixture.doc_id)
|
||||
.bind(PARSER_VERSION)
|
||||
.execute(&fixture.pool)
|
||||
.await?;
|
||||
if status == "partial" {
|
||||
sqlx::query("UPDATE snapshots SET blob=$3,updated_at=clock_timestamp() WHERE workspace_id=$1 AND guid=$2")
|
||||
.bind(&fixture.workspace_id)
|
||||
.bind(&fixture.doc_id)
|
||||
.bind(attachment_doc(None))
|
||||
.execute(&fixture.pool)
|
||||
.await?;
|
||||
}
|
||||
fixture
|
||||
.runtime
|
||||
.rebuild_workspace_doc_blob_refs(fixture.workspace_id.clone(), 100)
|
||||
.await?;
|
||||
complete_cleanup_checkpoints(&fixture.pool, &fixture.workspace_id).await?;
|
||||
assert!(
|
||||
fixture
|
||||
|
||||
@@ -1,19 +1,20 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use sqlx::{FromRow, PgConnection, PgExecutor, PgPool};
|
||||
use y_octo::Doc;
|
||||
use sqlx::{FromRow, PgConnection, PgPool};
|
||||
|
||||
use super::{RuntimeError, RuntimeResult};
|
||||
use super::{RuntimeError, RuntimeResult, lock_current_doc_read};
|
||||
|
||||
#[derive(FromRow)]
|
||||
pub(in crate::runtime) struct CurrentDoc {
|
||||
pub(in crate::runtime) blob: Vec<u8>,
|
||||
pub(in crate::runtime) updated_at: DateTime<Utc>,
|
||||
pub(in crate::runtime) updated_by: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(FromRow)]
|
||||
pub(in crate::runtime) struct CurrentDocUpdate {
|
||||
pub(in crate::runtime) blob: Vec<u8>,
|
||||
pub(in crate::runtime) created_at: DateTime<Utc>,
|
||||
pub(in crate::runtime) created_by: Option<String>,
|
||||
}
|
||||
|
||||
pub(in crate::runtime) async fn load_current_doc(
|
||||
@@ -30,64 +31,61 @@ pub(in crate::runtime) async fn load_current_doc_parts(
|
||||
workspace_id: &str,
|
||||
doc_id: &str,
|
||||
) -> RuntimeResult<(Option<CurrentDoc>, Vec<CurrentDocUpdate>)> {
|
||||
let snapshot = sqlx::query_as::<_, CurrentDoc>(
|
||||
r#"
|
||||
SELECT blob, updated_at
|
||||
FROM snapshots
|
||||
WHERE workspace_id = $1 AND guid = $2
|
||||
"#,
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(doc_id)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Current doc snapshot load failed", err))?;
|
||||
let updates = sqlx::query_as::<_, CurrentDocUpdate>(
|
||||
r#"
|
||||
SELECT blob, created_at
|
||||
FROM updates
|
||||
WHERE workspace_id = $1 AND guid = $2
|
||||
ORDER BY created_at ASC
|
||||
"#,
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(doc_id)
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Current doc updates load failed", err))?;
|
||||
Ok((snapshot, updates))
|
||||
let mut transaction = pool
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("begin current document read", error))?;
|
||||
lock_current_doc_read(&mut transaction, workspace_id, doc_id).await?;
|
||||
let result = load_current_doc_parts_in(&mut transaction, workspace_id, doc_id).await?;
|
||||
transaction
|
||||
.commit()
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("commit current document read", error))?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub(super) async fn load_canonical_doc<'a>(
|
||||
connection: impl PgExecutor<'a>,
|
||||
pub(in crate::runtime) async fn load_current_doc_in(
|
||||
connection: &mut PgConnection,
|
||||
workspace_id: &str,
|
||||
doc_id: &str,
|
||||
) -> RuntimeResult<Option<CurrentDoc>> {
|
||||
sqlx::query_as::<_, CurrentDoc>(
|
||||
r#"
|
||||
SELECT blob, updated_at
|
||||
FROM snapshots
|
||||
WHERE workspace_id = $1 AND guid = $2
|
||||
"#,
|
||||
let (snapshot, updates) = load_current_doc_parts_in(connection, workspace_id, doc_id).await?;
|
||||
merge_current_doc(snapshot, updates)
|
||||
}
|
||||
|
||||
pub(in crate::runtime) async fn load_current_doc_parts_in(
|
||||
connection: &mut PgConnection,
|
||||
workspace_id: &str,
|
||||
doc_id: &str,
|
||||
) -> RuntimeResult<(Option<CurrentDoc>, Vec<CurrentDocUpdate>)> {
|
||||
let rows = sqlx::query_as::<_, (Vec<u8>, DateTime<Utc>, bool, Option<String>)>(
|
||||
"SELECT blob,updated_at AS timestamp,true AS snapshot,updated_by AS editor FROM snapshots WHERE workspace_id=$1 \
|
||||
AND guid=$2 UNION ALL SELECT blob,created_at AS timestamp,false AS snapshot,created_by AS editor FROM updates \
|
||||
WHERE workspace_id=$1 AND guid=$2 ORDER BY snapshot DESC,timestamp ASC",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(doc_id)
|
||||
.fetch_optional(connection)
|
||||
.fetch_all(connection)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Canonical doc snapshot load failed", err))
|
||||
}
|
||||
|
||||
pub(super) async fn has_pending_updates<'a>(
|
||||
connection: impl PgExecutor<'a>,
|
||||
workspace_id: &str,
|
||||
doc_id: &str,
|
||||
) -> RuntimeResult<bool> {
|
||||
sqlx::query_scalar::<_, bool>("SELECT EXISTS(SELECT 1 FROM updates WHERE workspace_id = $1 AND guid = $2)")
|
||||
.bind(workspace_id)
|
||||
.bind(doc_id)
|
||||
.fetch_one(connection)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Pending doc updates check failed", err))
|
||||
.map_err(|error| RuntimeError::database("load current document parts", error))?;
|
||||
let mut snapshot = None;
|
||||
let mut updates = Vec::new();
|
||||
for (blob, timestamp, is_snapshot, editor) in rows {
|
||||
if is_snapshot {
|
||||
snapshot = Some(CurrentDoc {
|
||||
blob,
|
||||
updated_at: timestamp,
|
||||
updated_by: editor,
|
||||
});
|
||||
} else {
|
||||
updates.push(CurrentDocUpdate {
|
||||
blob,
|
||||
created_at: timestamp,
|
||||
created_by: editor,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok((snapshot, updates))
|
||||
}
|
||||
|
||||
pub(in crate::runtime) fn merge_current_doc(
|
||||
@@ -97,62 +95,27 @@ pub(in crate::runtime) fn merge_current_doc(
|
||||
if snapshot.is_none() && updates.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
if updates.is_empty() {
|
||||
return Ok(snapshot);
|
||||
}
|
||||
let mut doc = Doc::default();
|
||||
let mut updated_at = snapshot
|
||||
.as_ref()
|
||||
.map(|snapshot| snapshot.updated_at)
|
||||
.or_else(|| updates.first().map(|update| update.created_at))
|
||||
.unwrap_or_else(Utc::now);
|
||||
if let Some(snapshot) = &snapshot {
|
||||
doc
|
||||
.apply_update_from_binary_v1(&snapshot.blob)
|
||||
.map_err(|err| RuntimeError::invalid_state(format!("Current doc snapshot merge failed: {err}")))?;
|
||||
}
|
||||
for update in updates {
|
||||
updated_at = updated_at.max(update.created_at);
|
||||
doc
|
||||
.apply_update_from_binary_v1(&update.blob)
|
||||
.map_err(|err| RuntimeError::invalid_state(format!("Current doc update merge failed: {err}")))?;
|
||||
}
|
||||
let blob = doc
|
||||
.encode_update_v1()
|
||||
.map_err(|err| RuntimeError::invalid_state(format!("Current doc encode failed: {err}")))?;
|
||||
let (updated_at, updated_by) = snapshot
|
||||
.iter()
|
||||
.map(|snapshot| (snapshot.updated_at, &snapshot.updated_by))
|
||||
.chain(updates.iter().map(|update| (update.created_at, &update.created_by)))
|
||||
.max_by_key(|(timestamp, _)| *timestamp)
|
||||
.expect("current source is not empty");
|
||||
let updated_by = updated_by.clone();
|
||||
let blob = y_octo::merge_updates_v1(
|
||||
snapshot
|
||||
.iter()
|
||||
.map(|snapshot| snapshot.blob.as_slice())
|
||||
.chain(updates.iter().map(|update| update.blob.as_slice())),
|
||||
)
|
||||
.and_then(|update| update.encode_v1())
|
||||
.map_err(|error| RuntimeError::invalid_state(format!("Current doc update merge failed: {error}")))?;
|
||||
|
||||
Ok(Some(CurrentDoc { blob, updated_at }))
|
||||
}
|
||||
|
||||
pub(super) async fn load_workspace_live_doc_ids(pool: &PgPool, workspace_id: &str) -> RuntimeResult<Vec<String>> {
|
||||
let mut connection = pool
|
||||
.acquire()
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("acquire workspace root connection", error))?;
|
||||
load_workspace_canonical_doc_ids(&mut connection, workspace_id).await
|
||||
}
|
||||
|
||||
pub(super) async fn load_workspace_canonical_doc_ids(
|
||||
connection: &mut PgConnection,
|
||||
workspace_id: &str,
|
||||
) -> RuntimeResult<Vec<String>> {
|
||||
if has_pending_updates(&mut *connection, workspace_id, workspace_id).await? {
|
||||
return Err(RuntimeError::invalid_state("Workspace root doc has pending updates"));
|
||||
}
|
||||
workspace_live_doc_ids(load_canonical_doc(&mut *connection, workspace_id, workspace_id).await?)
|
||||
}
|
||||
|
||||
fn workspace_live_doc_ids(root: Option<CurrentDoc>) -> RuntimeResult<Vec<String>> {
|
||||
let root = root.ok_or_else(|| RuntimeError::invalid_state("Workspace root doc is missing"))?;
|
||||
let projection = affine_doc_loader::project_workspace_root(root.blob, true)
|
||||
.map_err(|err| RuntimeError::invalid_state(format!("Workspace root doc parse failed: {err}")))?;
|
||||
if !projection.complete {
|
||||
return Err(RuntimeError::invalid_state("Workspace root doc is incomplete"));
|
||||
}
|
||||
let mut ids = projection.doc_ids;
|
||||
ids.sort();
|
||||
ids.dedup();
|
||||
Ok(ids)
|
||||
Ok(Some(CurrentDoc {
|
||||
blob,
|
||||
updated_at,
|
||||
updated_by,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -160,76 +123,42 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn workspace_live_set_merges_pending_updates_and_includes_trash() {
|
||||
use y_octo::{Any, Value};
|
||||
|
||||
let snapshot = affine_doc_loader::add_doc_to_root_doc(Vec::new(), "live", None).unwrap();
|
||||
let pending = affine_doc_loader::add_doc_to_root_doc(snapshot.clone(), "trash", None).unwrap();
|
||||
fn current_sources_preserve_structs() {
|
||||
let snapshot = vec![
|
||||
1, 1, 7, 0, 4, 1, 7, 99, 111, 110, 116, 101, 110, 116, 18, 114, 101, 116, 97, 105, 110, 101, 100, 32, 116, 111,
|
||||
109, 98, 115, 116, 111, 110, 101, 0,
|
||||
];
|
||||
let deletion = vec![0, 1, 7, 1, 0, 18];
|
||||
let mut expected = snapshot.clone();
|
||||
expected.pop();
|
||||
expected.extend_from_slice(&deletion[1..]);
|
||||
let timestamp = Utc::now();
|
||||
let merged = merge_current_doc(
|
||||
Some(CurrentDoc {
|
||||
blob: snapshot,
|
||||
updated_at: Utc::now(),
|
||||
updated_at: timestamp,
|
||||
updated_by: Some("snapshot-editor".into()),
|
||||
}),
|
||||
vec![CurrentDocUpdate {
|
||||
blob: pending,
|
||||
created_at: Utc::now(),
|
||||
blob: deletion,
|
||||
created_at: timestamp,
|
||||
created_by: Some("update-editor".into()),
|
||||
}],
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let mut root = Doc::default();
|
||||
root.apply_update_from_binary_v1(&merged.blob).unwrap();
|
||||
let meta = root.get_map("meta").unwrap();
|
||||
let mut pages = meta.get("pages").and_then(|value| value.to_array()).unwrap();
|
||||
let mut trash = pages
|
||||
.iter()
|
||||
.find_map(|value| {
|
||||
let page = value.to_map()?;
|
||||
(page.get("id")?.to_any()? == Any::String("trash".to_string())).then_some(page)
|
||||
})
|
||||
.unwrap();
|
||||
trash.insert("trash".to_string(), Value::Any(Any::True)).unwrap();
|
||||
assert_eq!(merged.blob, expected);
|
||||
assert_eq!(merged.updated_by.as_deref(), Some("update-editor"));
|
||||
|
||||
let ids = workspace_live_doc_ids(Some(CurrentDoc {
|
||||
blob: root.encode_update_v1().unwrap(),
|
||||
updated_at: Utc::now(),
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(ids, ["live", "trash"]);
|
||||
|
||||
let trash_index = pages
|
||||
.iter()
|
||||
.position(|value| {
|
||||
value.to_map().and_then(|page| page.get("id")) == Some(Value::Any(Any::String("trash".to_string())))
|
||||
})
|
||||
.unwrap();
|
||||
pages.remove(trash_index as u64, 1).unwrap();
|
||||
let ids = workspace_live_doc_ids(Some(CurrentDoc {
|
||||
blob: root.encode_update_v1().unwrap(),
|
||||
updated_at: Utc::now(),
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(ids, ["live"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_live_set_fails_closed_for_missing_or_corrupt_root() {
|
||||
assert!(workspace_live_doc_ids(None).is_err());
|
||||
assert!(
|
||||
workspace_live_doc_ids(Some(CurrentDoc {
|
||||
blob: vec![0xff],
|
||||
updated_at: Utc::now(),
|
||||
}))
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
workspace_live_doc_ids(Some(CurrentDoc {
|
||||
blob: vec![
|
||||
1, 1, 1, 1, 40, 0, 1, 0, 11, 115, 117, 98, 95, 109, 97, 112, 95, 107, 101, 121, 1, 119, 13, 115, 117, 98, 95,
|
||||
109, 97, 112, 95, 118, 97, 108, 117, 101, 0,
|
||||
],
|
||||
updated_at: Utc::now(),
|
||||
}))
|
||||
merge_current_doc(
|
||||
Some(CurrentDoc {
|
||||
blob: vec![0xff],
|
||||
updated_at: timestamp,
|
||||
updated_by: None,
|
||||
}),
|
||||
vec![]
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,23 +1,17 @@
|
||||
use affine_doc_loader as doc_loader;
|
||||
use chrono::{DateTime, Utc};
|
||||
use sqlx::{Executor, FromRow, PgPool, Postgres};
|
||||
use sqlx::{Executor, PgConnection, Postgres};
|
||||
|
||||
use super::{
|
||||
CurrentDoc, RuntimeDocBlobRefsResult, RuntimeError, RuntimeResult, StorageRuntime, load_canonical_doc,
|
||||
load_workspace_canonical_doc_ids, napi_error,
|
||||
CurrentDoc, CurrentDocUpdate, RuntimeDocBlobRefsResult, RuntimeError, RuntimeResult, StorageOperation,
|
||||
StorageRuntime, load_workspace_doc_states_in, merge_current_doc, napi_error,
|
||||
};
|
||||
|
||||
pub(super) const PARSER_VERSION: i32 = 1;
|
||||
pub(super) const PARSER_VERSION: i32 = 3;
|
||||
const ERROR_SUMMARY_LIMIT: usize = 512;
|
||||
|
||||
type ExtractedRef = doc_loader::BlobRef;
|
||||
|
||||
#[derive(FromRow)]
|
||||
struct DocSource {
|
||||
updated_at: DateTime<Utc>,
|
||||
has_pending_updates: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ProjectionState {
|
||||
cursor: Option<String>,
|
||||
@@ -28,89 +22,47 @@ struct ProjectionState {
|
||||
struct ProjectionStats {
|
||||
result: RuntimeDocBlobRefsResult,
|
||||
pending_docs: i64,
|
||||
missing_docs: i64,
|
||||
shadow_mismatches: i64,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ProjectionAttempt {
|
||||
written: i64,
|
||||
deleted: i64,
|
||||
shadow_mismatch: bool,
|
||||
}
|
||||
|
||||
enum ProjectionOutcome {
|
||||
Fresh(ProjectionAttempt),
|
||||
Pending,
|
||||
Missing,
|
||||
}
|
||||
|
||||
async fn load_workspace_doc_ids(pool: &PgPool, workspace_id: &str) -> RuntimeResult<Vec<String>> {
|
||||
let mut connection = pool
|
||||
.acquire()
|
||||
pub(super) async fn retained_doc_ids(connection: &mut PgConnection, workspace_id: &str) -> RuntimeResult<Vec<String>> {
|
||||
let mut ids = load_workspace_doc_states_in(connection, workspace_id)
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|state| state.doc_id)
|
||||
.collect::<Vec<_>>();
|
||||
ids.extend(
|
||||
sqlx::query_scalar::<_, String>(
|
||||
"SELECT DISTINCT guid FROM snapshot_histories WHERE workspace_id=$1 AND expired_at > CURRENT_TIMESTAMP ORDER BY \
|
||||
guid",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.fetch_all(connection)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("acquire retained document connection", error))?;
|
||||
let mut ids = load_workspace_canonical_doc_ids(&mut connection, workspace_id).await?;
|
||||
ids.push(workspace_id.to_string());
|
||||
let retained = sqlx::query_scalar::<_, String>(
|
||||
"SELECT doc_id FROM document_cleanup_candidates WHERE workspace_id = $1 AND status IN ('marked', 'failed') ORDER \
|
||||
BY doc_id",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.fetch_all(&mut *connection)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Doc blob refs candidate load failed", err))?;
|
||||
ids.extend(retained);
|
||||
.map_err(|error| RuntimeError::database("load retained history identities", error))?,
|
||||
);
|
||||
ids.sort();
|
||||
ids.dedup();
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
async fn load_doc_source(pool: &PgPool, workspace_id: &str, doc_id: &str) -> RuntimeResult<Option<DocSource>> {
|
||||
sqlx::query_as::<_, DocSource>(
|
||||
r#"
|
||||
SELECT s.updated_at,
|
||||
EXISTS(
|
||||
SELECT 1 FROM updates u
|
||||
WHERE u.workspace_id = s.workspace_id AND u.guid = s.guid
|
||||
) AS has_pending_updates
|
||||
FROM snapshots s
|
||||
WHERE s.workspace_id = $1 AND s.guid = $2
|
||||
"#,
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(doc_id)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Doc blob refs source load failed", err))
|
||||
}
|
||||
|
||||
async fn projection_is_fresh(
|
||||
pool: &PgPool,
|
||||
workspace_id: &str,
|
||||
doc_id: &str,
|
||||
source_revision: DateTime<Utc>,
|
||||
) -> RuntimeResult<bool> {
|
||||
sqlx::query_scalar::<_, bool>(
|
||||
r#"
|
||||
SELECT EXISTS(
|
||||
SELECT 1 FROM doc_blob_ref_projections
|
||||
WHERE workspace_id = $1
|
||||
AND doc_id = $2
|
||||
AND source_revision = $3
|
||||
AND parser_version = $4
|
||||
AND status = 'fresh'
|
||||
)
|
||||
"#,
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(doc_id)
|
||||
.bind(source_revision)
|
||||
.bind(PARSER_VERSION)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Doc blob refs projection freshness load failed", err))
|
||||
}
|
||||
pub(super) const DOC_BLOB_SOURCES_SQL: &str = r#"
|
||||
SELECT guid AS doc_id,blob,updated_at AS timestamp,'snapshot'::text AS kind,
|
||||
NULL::timestamptz AS expired_at,encode(sha256(blob),'hex') AS digest
|
||||
FROM snapshots WHERE workspace_id=$1 AND ($2::text IS NULL OR guid=$2)
|
||||
UNION ALL
|
||||
SELECT guid,blob,created_at,'update',NULL::timestamptz,encode(sha256(blob),'hex')
|
||||
FROM updates WHERE workspace_id=$1 AND ($2::text IS NULL OR guid=$2)
|
||||
UNION ALL
|
||||
SELECT guid,blob,timestamp,'history',expired_at,encode(sha256(blob),'hex')
|
||||
FROM snapshot_histories
|
||||
WHERE workspace_id=$1 AND ($2::text IS NULL OR guid=$2) AND expired_at>CURRENT_TIMESTAMP
|
||||
"#;
|
||||
pub(super) const SOURCE_FINGERPRINT_SQL: &str = r#"
|
||||
encode(sha256(convert_to(COALESCE(string_agg(
|
||||
jsonb_build_array(kind,extract(epoch from timestamp),extract(epoch from expired_at),digest)::text,
|
||||
',' ORDER BY kind,timestamp,digest
|
||||
),''),'UTF8')),'hex')
|
||||
"#;
|
||||
|
||||
fn truncate_error_summary(error: &str) -> String {
|
||||
let mut end = error.len().min(ERROR_SUMMARY_LIMIT);
|
||||
@@ -125,6 +77,7 @@ async fn upsert_projection_state<'e, E>(
|
||||
workspace_id: &str,
|
||||
doc_id: &str,
|
||||
source_revision: Option<DateTime<Utc>>,
|
||||
source_fingerprint: &str,
|
||||
status: &str,
|
||||
error_code: Option<&str>,
|
||||
error_summary: Option<&str>,
|
||||
@@ -135,10 +88,11 @@ where
|
||||
sqlx::query(
|
||||
r#"
|
||||
INSERT INTO doc_blob_ref_projections
|
||||
(workspace_id, doc_id, source_revision, parser_version, status, indexed_at, error_code, error_summary, attempt_count)
|
||||
VALUES ($1, $2, $3, $4, $5, CURRENT_TIMESTAMP, $6, $7, CASE WHEN $5 = 'fresh' THEN 0 ELSE 1 END)
|
||||
(workspace_id, doc_id, source_revision, parser_version, status, indexed_at, error_code, error_summary, source_fingerprint, attempt_count)
|
||||
VALUES ($1, $2, $3, $4, $5, CURRENT_TIMESTAMP, $6, $7, $8, CASE WHEN $5 = 'fresh' THEN 0 ELSE 1 END)
|
||||
ON CONFLICT (workspace_id, doc_id) DO UPDATE
|
||||
SET source_revision = EXCLUDED.source_revision,
|
||||
source_fingerprint = EXCLUDED.source_fingerprint,
|
||||
parser_version = EXCLUDED.parser_version,
|
||||
status = EXCLUDED.status,
|
||||
indexed_at = EXCLUDED.indexed_at,
|
||||
@@ -149,18 +103,6 @@ where
|
||||
ELSE doc_blob_ref_projections.attempt_count + 1
|
||||
END,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE (
|
||||
EXCLUDED.source_revision IS NULL
|
||||
AND doc_blob_ref_projections.source_revision IS NULL
|
||||
AND doc_blob_ref_projections.parser_version <= EXCLUDED.parser_version
|
||||
) OR (
|
||||
EXCLUDED.source_revision IS NOT NULL
|
||||
AND doc_blob_ref_projections.parser_version <= EXCLUDED.parser_version
|
||||
AND (
|
||||
doc_blob_ref_projections.source_revision IS NULL
|
||||
OR EXCLUDED.source_revision >= doc_blob_ref_projections.source_revision
|
||||
)
|
||||
)
|
||||
"#,
|
||||
)
|
||||
.bind(workspace_id)
|
||||
@@ -170,6 +112,7 @@ where
|
||||
.bind(status)
|
||||
.bind(error_code)
|
||||
.bind(error_summary.map(truncate_error_summary))
|
||||
.bind(source_fingerprint)
|
||||
.execute(executor)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Doc blob refs projection state write failed", err))?;
|
||||
@@ -177,12 +120,10 @@ where
|
||||
}
|
||||
|
||||
async fn upsert_projection_checkpoint(
|
||||
pool: &PgPool,
|
||||
connection: &mut PgConnection,
|
||||
workspace_id: &str,
|
||||
result: &RuntimeDocBlobRefsResult,
|
||||
pending_docs: i64,
|
||||
missing_docs: i64,
|
||||
shadow_mismatches: i64,
|
||||
) -> RuntimeResult<()> {
|
||||
let status = if result.next_cursor.is_some() {
|
||||
"running"
|
||||
@@ -211,47 +152,20 @@ async fn upsert_projection_checkpoint(
|
||||
"parserVersion": PARSER_VERSION,
|
||||
"failedDocs": result.failed_docs,
|
||||
"pendingDocs": pending_docs,
|
||||
"missingDocs": missing_docs,
|
||||
"shadowMismatches": shadow_mismatches,
|
||||
}))
|
||||
.execute(pool)
|
||||
.execute(&mut *connection)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Doc blob refs checkpoint write failed", err))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn upsert_projection_failure_checkpoint(pool: &PgPool, workspace_id: &str) -> RuntimeResult<()> {
|
||||
sqlx::query(
|
||||
r#"
|
||||
INSERT INTO storage_reconciliation_checkpoints
|
||||
(kind, scope, status, cursor, completed_at, metadata)
|
||||
VALUES ('doc_blob_refs', $1, 'failed', '{}', NULL, $2)
|
||||
ON CONFLICT (kind, scope) DO UPDATE
|
||||
SET status = 'failed',
|
||||
cursor = '{}',
|
||||
completed_at = NULL,
|
||||
updated_at = CURRENT_TIMESTAMP,
|
||||
metadata = EXCLUDED.metadata
|
||||
"#,
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(serde_json::json!({
|
||||
"parserVersion": PARSER_VERSION,
|
||||
"errorCode": "root_projection_failed",
|
||||
}))
|
||||
.execute(pool)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Doc blob refs failure checkpoint write failed", err))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn load_projection_state(pool: &PgPool, workspace_id: &str) -> RuntimeResult<ProjectionState> {
|
||||
async fn load_projection_state(connection: &mut PgConnection, workspace_id: &str) -> RuntimeResult<ProjectionState> {
|
||||
let checkpoint = sqlx::query_as::<_, (String, serde_json::Value, serde_json::Value)>(
|
||||
"SELECT status, cursor, metadata FROM storage_reconciliation_checkpoints WHERE kind = 'doc_blob_refs' AND scope = \
|
||||
$1",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.fetch_optional(pool)
|
||||
.fetch_optional(&mut *connection)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Doc blob refs checkpoint load failed", err))?;
|
||||
let Some((status, cursor, metadata)) = checkpoint else {
|
||||
@@ -278,139 +192,47 @@ async fn load_projection_state(pool: &PgPool, workspace_id: &str) -> RuntimeResu
|
||||
})
|
||||
}
|
||||
|
||||
async fn purge_removed_doc_projections(
|
||||
pool: &PgPool,
|
||||
pub(super) async fn purge_removed_doc_projections(
|
||||
connection: &mut PgConnection,
|
||||
workspace_id: &str,
|
||||
current_doc_ids: &[String],
|
||||
) -> RuntimeResult<i64> {
|
||||
let refs = sqlx::query("DELETE FROM doc_blob_refs WHERE workspace_id = $1 AND NOT (doc_id = ANY($2))")
|
||||
.bind(workspace_id)
|
||||
.bind(current_doc_ids)
|
||||
.execute(pool)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Doc blob refs purge removed docs failed", err))?
|
||||
.rows_affected() as i64;
|
||||
sqlx::query("DELETE FROM doc_blob_ref_projections WHERE workspace_id = $1 AND NOT (doc_id = ANY($2))")
|
||||
.bind(workspace_id)
|
||||
.bind(current_doc_ids)
|
||||
.execute(pool)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Doc blob ref projections purge removed docs failed", err))?;
|
||||
Ok(refs)
|
||||
sqlx::query_scalar(
|
||||
"WITH refs AS (DELETE FROM doc_blob_refs WHERE workspace_id=$1 AND NOT (doc_id=ANY($2)) RETURNING 1), projections \
|
||||
AS (DELETE FROM doc_blob_ref_projections WHERE workspace_id=$1 AND NOT (doc_id=ANY($2))) SELECT count(*)::bigint \
|
||||
FROM refs",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(current_doc_ids)
|
||||
.fetch_one(connection)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("purge removed document projections", error))
|
||||
}
|
||||
|
||||
fn extract_refs(blob: Vec<u8>) -> std::result::Result<Vec<ExtractedRef>, super::BlobRefProjectionError> {
|
||||
super::extract_blob_refs(blob).map(|extraction| extraction.refs)
|
||||
}
|
||||
|
||||
async fn replace_doc_refs_if_current(
|
||||
pool: &PgPool,
|
||||
pub(super) async fn replace_doc_refs(
|
||||
connection: &mut PgConnection,
|
||||
workspace_id: &str,
|
||||
doc_id: &str,
|
||||
source_revision: DateTime<Utc>,
|
||||
source_fingerprint: &str,
|
||||
refs: Vec<ExtractedRef>,
|
||||
) -> RuntimeResult<ProjectionOutcome> {
|
||||
let mut tx = pool
|
||||
) -> RuntimeResult<Option<(i64, i64)>> {
|
||||
use sqlx::Connection;
|
||||
let mut tx = connection
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Doc blob refs transaction failed", err))?;
|
||||
let current = sqlx::query_as::<_, (DateTime<Utc>, bool)>(
|
||||
r#"
|
||||
SELECT s.updated_at,
|
||||
EXISTS(
|
||||
SELECT 1 FROM updates u
|
||||
WHERE u.workspace_id = s.workspace_id AND u.guid = s.guid
|
||||
) AS has_pending_updates
|
||||
FROM snapshots s
|
||||
WHERE s.workspace_id = $1 AND s.guid = $2
|
||||
"#,
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(doc_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Doc blob refs CAS source load failed", err))?;
|
||||
let Some((current_revision, has_pending_updates)) = current else {
|
||||
tx.rollback()
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Doc blob refs CAS rollback failed", err))?;
|
||||
upsert_projection_state(
|
||||
pool,
|
||||
workspace_id,
|
||||
doc_id,
|
||||
None,
|
||||
"missing",
|
||||
Some("snapshot_missing"),
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
return Ok(ProjectionOutcome::Missing);
|
||||
};
|
||||
if current_revision != source_revision || has_pending_updates {
|
||||
tx.rollback()
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Doc blob refs CAS rollback failed", err))?;
|
||||
upsert_projection_state(
|
||||
pool,
|
||||
workspace_id,
|
||||
doc_id,
|
||||
Some(source_revision),
|
||||
"pending",
|
||||
Some("source_changed"),
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
return Ok(ProjectionOutcome::Pending);
|
||||
.map_err(|err| RuntimeError::database("begin blob ref projection", err))?;
|
||||
let fingerprint_query =
|
||||
format!("WITH sources AS ({DOC_BLOB_SOURCES_SQL}) SELECT {SOURCE_FINGERPRINT_SQL} FROM sources");
|
||||
let current_fingerprint: String = sqlx::query_scalar(&fingerprint_query)
|
||||
.bind(workspace_id)
|
||||
.bind(doc_id)
|
||||
.fetch_one(&mut *tx)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("check blob projection source fingerprint", error))?;
|
||||
if current_fingerprint != source_fingerprint {
|
||||
return Ok(None);
|
||||
}
|
||||
let projection = sqlx::query_as::<_, (i32, Option<DateTime<Utc>>)>(
|
||||
"SELECT parser_version, source_revision FROM doc_blob_ref_projections WHERE workspace_id = $1 AND doc_id = $2",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(doc_id)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Doc blob refs projection CAS load failed", err))?;
|
||||
if projection.is_some_and(|(parser_version, projection_revision)| {
|
||||
parser_version > PARSER_VERSION || projection_revision.is_some_and(|revision| revision > source_revision)
|
||||
}) {
|
||||
tx.rollback()
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Doc blob refs projection CAS rollback failed", err))?;
|
||||
upsert_projection_state(
|
||||
pool,
|
||||
workspace_id,
|
||||
doc_id,
|
||||
Some(source_revision),
|
||||
"pending",
|
||||
Some("projection_newer"),
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
return Ok(ProjectionOutcome::Pending);
|
||||
}
|
||||
|
||||
let mut old_refs = sqlx::query_as::<_, (String, String, String)>(
|
||||
"SELECT blob_key, block_id, flavour FROM doc_blob_refs WHERE workspace_id = $1 AND doc_id = $2",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(doc_id)
|
||||
.fetch_all(&mut *tx)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Doc blob refs shadow load failed", err))?;
|
||||
old_refs.sort();
|
||||
let mut new_refs = refs
|
||||
.iter()
|
||||
.map(|reference| {
|
||||
(
|
||||
reference.blob_key.clone(),
|
||||
reference.block_id.clone(),
|
||||
reference.flavour.clone(),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
new_refs.sort();
|
||||
let shadow_mismatch = old_refs != new_refs;
|
||||
|
||||
let deleted = sqlx::query("DELETE FROM doc_blob_refs WHERE workspace_id = $1 AND doc_id = $2")
|
||||
.bind(workspace_id)
|
||||
.bind(doc_id)
|
||||
@@ -451,6 +273,7 @@ async fn replace_doc_refs_if_current(
|
||||
workspace_id,
|
||||
doc_id,
|
||||
Some(source_revision),
|
||||
source_fingerprint,
|
||||
"fresh",
|
||||
None,
|
||||
None,
|
||||
@@ -459,125 +282,99 @@ async fn replace_doc_refs_if_current(
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Doc blob refs transaction commit failed", err))?;
|
||||
Ok(ProjectionOutcome::Fresh(ProjectionAttempt {
|
||||
written,
|
||||
deleted,
|
||||
shadow_mismatch,
|
||||
}))
|
||||
Ok(Some((written, deleted)))
|
||||
}
|
||||
|
||||
async fn rebuild_doc_blob_refs_inner(
|
||||
runtime: &StorageRuntime,
|
||||
connection: &mut PgConnection,
|
||||
workspace_id: &str,
|
||||
doc_id: &str,
|
||||
expected_source_revision: Option<i64>,
|
||||
) -> RuntimeResult<ProjectionStats> {
|
||||
let pool = runtime.pool().await?;
|
||||
let mut stats = ProjectionStats::default();
|
||||
stats.result.scanned_docs = 1;
|
||||
let Some(source) = load_doc_source(&pool, workspace_id, doc_id).await? else {
|
||||
upsert_projection_state(
|
||||
&pool,
|
||||
workspace_id,
|
||||
doc_id,
|
||||
None,
|
||||
"missing",
|
||||
Some("snapshot_missing"),
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
stats.result.failed_docs = 1;
|
||||
stats.missing_docs = 1;
|
||||
let source_query = format!(
|
||||
"WITH sources AS ({DOC_BLOB_SOURCES_SQL}), fingerprint AS (SELECT {SOURCE_FINGERPRINT_SQL} AS stamp FROM sources) \
|
||||
SELECT blob,timestamp,kind,stamp FROM sources CROSS JOIN fingerprint ORDER BY kind,timestamp,digest"
|
||||
);
|
||||
let rows = sqlx::query_as::<_, (Vec<u8>, DateTime<Utc>, String, String)>(&source_query)
|
||||
.bind(workspace_id)
|
||||
.bind(doc_id)
|
||||
.fetch_all(&mut *connection)
|
||||
.await
|
||||
.map_err(|error| RuntimeError::database("load blob projection sources", error))?;
|
||||
let Some((_, _, _, source_fingerprint)) = rows.first() else {
|
||||
return Ok(stats);
|
||||
};
|
||||
if expected_source_revision.is_some_and(|revision| source.updated_at.timestamp_millis() != revision) {
|
||||
upsert_projection_state(
|
||||
&pool,
|
||||
workspace_id,
|
||||
doc_id,
|
||||
Some(source.updated_at),
|
||||
"pending",
|
||||
Some("source_changed"),
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
let source_fingerprint = source_fingerprint.clone();
|
||||
let revision = rows.iter().map(|(_, timestamp, _, _)| *timestamp).max();
|
||||
let mut snapshot = None;
|
||||
let mut updates = Vec::new();
|
||||
let mut histories = Vec::new();
|
||||
for (blob, timestamp, kind, _) in rows {
|
||||
match kind.as_str() {
|
||||
"snapshot" => {
|
||||
snapshot = Some(CurrentDoc {
|
||||
blob,
|
||||
updated_at: timestamp,
|
||||
updated_by: None,
|
||||
})
|
||||
}
|
||||
"update" => updates.push(CurrentDocUpdate {
|
||||
blob,
|
||||
created_at: timestamp,
|
||||
created_by: None,
|
||||
}),
|
||||
_ => histories.push(blob),
|
||||
}
|
||||
}
|
||||
let current = merge_current_doc(snapshot, updates)?;
|
||||
let Some(revision) = revision else {
|
||||
return Ok(stats);
|
||||
};
|
||||
if expected_source_revision.is_some_and(|expected| {
|
||||
current
|
||||
.as_ref()
|
||||
.is_none_or(|doc| doc.updated_at.timestamp_millis() != expected)
|
||||
}) {
|
||||
stats.pending_docs = 1;
|
||||
return Ok(stats);
|
||||
}
|
||||
if source.has_pending_updates {
|
||||
upsert_projection_state(
|
||||
&pool,
|
||||
workspace_id,
|
||||
doc_id,
|
||||
Some(source.updated_at),
|
||||
"pending",
|
||||
Some("pending_updates"),
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
let mut refs = Vec::new();
|
||||
for blob in current.into_iter().map(|doc| doc.blob).chain(histories) {
|
||||
match super::extract_blob_refs(blob) {
|
||||
Ok(extracted) => refs.extend(extracted),
|
||||
Err(error) => {
|
||||
let code = super::blob_ref_projection_error_code(error);
|
||||
upsert_projection_state(
|
||||
&mut *connection,
|
||||
workspace_id,
|
||||
doc_id,
|
||||
Some(revision),
|
||||
&source_fingerprint,
|
||||
"failed",
|
||||
Some(code),
|
||||
Some(code),
|
||||
)
|
||||
.await?;
|
||||
stats.result.failed_docs = 1;
|
||||
return Ok(stats);
|
||||
}
|
||||
}
|
||||
}
|
||||
refs.sort_by(|left, right| {
|
||||
(&left.blob_key, &left.block_id, &left.flavour).cmp(&(&right.blob_key, &right.block_id, &right.flavour))
|
||||
});
|
||||
refs.dedup_by(|left, right| left.blob_key == right.blob_key && left.block_id == right.block_id);
|
||||
let Some((written, deleted)) =
|
||||
replace_doc_refs(connection, workspace_id, doc_id, revision, &source_fingerprint, refs).await?
|
||||
else {
|
||||
stats.pending_docs = 1;
|
||||
return Ok(stats);
|
||||
}
|
||||
if projection_is_fresh(&pool, workspace_id, doc_id, source.updated_at).await? {
|
||||
return Ok(stats);
|
||||
}
|
||||
upsert_projection_state(
|
||||
&pool,
|
||||
workspace_id,
|
||||
doc_id,
|
||||
Some(source.updated_at),
|
||||
"running",
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
let Some(snapshot) = load_canonical_doc(&pool, workspace_id, doc_id).await? else {
|
||||
upsert_projection_state(
|
||||
&pool,
|
||||
workspace_id,
|
||||
doc_id,
|
||||
None,
|
||||
"missing",
|
||||
Some("snapshot_missing"),
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
stats.result.failed_docs = 1;
|
||||
stats.missing_docs = 1;
|
||||
return Ok(stats);
|
||||
};
|
||||
let CurrentDoc { blob, updated_at, .. } = snapshot;
|
||||
let refs = match extract_refs(blob) {
|
||||
Ok(refs) => refs,
|
||||
Err(error) => {
|
||||
let error_code = super::blob_ref_projection_error_code(error);
|
||||
upsert_projection_state(
|
||||
&pool,
|
||||
workspace_id,
|
||||
doc_id,
|
||||
Some(updated_at),
|
||||
"failed",
|
||||
Some(error_code),
|
||||
Some(error_code),
|
||||
)
|
||||
.await?;
|
||||
stats.result.failed_docs = 1;
|
||||
return Ok(stats);
|
||||
}
|
||||
};
|
||||
match replace_doc_refs_if_current(&pool, workspace_id, doc_id, updated_at, refs).await? {
|
||||
ProjectionOutcome::Fresh(attempt) => {
|
||||
stats.result.parsed_docs = 1;
|
||||
stats.result.refs_written = attempt.written;
|
||||
stats.result.refs_deleted = attempt.deleted;
|
||||
stats.shadow_mismatches = i64::from(attempt.shadow_mismatch);
|
||||
}
|
||||
ProjectionOutcome::Pending => stats.pending_docs = 1,
|
||||
ProjectionOutcome::Missing => {
|
||||
stats.result.failed_docs = 1;
|
||||
stats.missing_docs = 1;
|
||||
}
|
||||
}
|
||||
stats.result.parsed_docs = 1;
|
||||
stats.result.refs_written = written;
|
||||
stats.result.refs_deleted = deleted;
|
||||
Ok(stats)
|
||||
}
|
||||
|
||||
@@ -601,11 +398,12 @@ impl StorageRuntime {
|
||||
doc_id: String,
|
||||
source_revision: i64,
|
||||
) -> napi::Result<RuntimeDocBlobRefsResult> {
|
||||
Ok(
|
||||
rebuild_doc_blob_refs_inner(self, &workspace_id, &doc_id, Some(source_revision))
|
||||
.await?
|
||||
.result,
|
||||
)
|
||||
let pool = self.pool().await?;
|
||||
let mut operation = StorageOperation::acquire_shared(&pool, &workspace_id).await?;
|
||||
let result =
|
||||
rebuild_doc_blob_refs_inner(operation.connection(), &workspace_id, &doc_id, Some(source_revision)).await;
|
||||
operation.release().await?;
|
||||
Ok(result?.result)
|
||||
}
|
||||
|
||||
#[napi]
|
||||
@@ -618,14 +416,9 @@ impl StorageRuntime {
|
||||
return Err(napi_error("doc blob refs rebuild limit must be positive"));
|
||||
}
|
||||
let pool = self.pool().await?;
|
||||
let doc_ids = match load_workspace_doc_ids(&pool, &workspace_id).await {
|
||||
Ok(doc_ids) => doc_ids,
|
||||
Err(err) => {
|
||||
upsert_projection_failure_checkpoint(&pool, &workspace_id).await?;
|
||||
return Err(err.into());
|
||||
}
|
||||
};
|
||||
let state = load_projection_state(&pool, &workspace_id).await?;
|
||||
let mut operation = StorageOperation::acquire_shared(&pool, &workspace_id).await?;
|
||||
let doc_ids = retained_doc_ids(operation.connection(), &workspace_id).await?;
|
||||
let state = load_projection_state(operation.connection(), &workspace_id).await?;
|
||||
let current_doc_ids = doc_ids.clone();
|
||||
let doc_ids = doc_ids
|
||||
.into_iter()
|
||||
@@ -637,30 +430,22 @@ impl StorageRuntime {
|
||||
let mut last_doc_id = None;
|
||||
for doc_id in doc_ids.into_iter().take(limit as usize) {
|
||||
last_doc_id = Some(doc_id.clone());
|
||||
let stats = rebuild_doc_blob_refs_inner(self, &workspace_id, &doc_id, None).await?;
|
||||
let stats = rebuild_doc_blob_refs_inner(operation.connection(), &workspace_id, &doc_id, None).await?;
|
||||
total.result.scanned_docs += stats.result.scanned_docs;
|
||||
total.result.parsed_docs += stats.result.parsed_docs;
|
||||
total.result.refs_written += stats.result.refs_written;
|
||||
total.result.refs_deleted += stats.result.refs_deleted;
|
||||
total.result.failed_docs += stats.result.failed_docs;
|
||||
total.pending_docs += stats.pending_docs;
|
||||
total.missing_docs += stats.missing_docs;
|
||||
total.shadow_mismatches += stats.shadow_mismatches;
|
||||
}
|
||||
if has_more {
|
||||
total.result.next_cursor = last_doc_id;
|
||||
} else if total.result.failed_docs == 0 && total.pending_docs == 0 {
|
||||
total.result.refs_deleted += purge_removed_doc_projections(&pool, &workspace_id, ¤t_doc_ids).await?;
|
||||
total.result.refs_deleted +=
|
||||
purge_removed_doc_projections(operation.connection(), &workspace_id, ¤t_doc_ids).await?;
|
||||
}
|
||||
upsert_projection_checkpoint(
|
||||
&pool,
|
||||
&workspace_id,
|
||||
&total.result,
|
||||
total.pending_docs,
|
||||
total.missing_docs,
|
||||
total.shadow_mismatches,
|
||||
)
|
||||
.await?;
|
||||
upsert_projection_checkpoint(operation.connection(), &workspace_id, &total.result, total.pending_docs).await?;
|
||||
operation.release().await?;
|
||||
Ok(total.result)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,278 +0,0 @@
|
||||
use affine_core::access_control::classify_reserved_document;
|
||||
use chrono::{DateTime, Utc};
|
||||
use sqlx::{PgPool, Postgres, Transaction};
|
||||
|
||||
use super::{CurrentDoc, CurrentDocUpdate, DocumentCleanupCandidate, RuntimeError, RuntimeResult, merge_current_doc};
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(super) enum DocumentCleanupOutcome {
|
||||
Deleted(i64),
|
||||
Recovered,
|
||||
Reset,
|
||||
Failed,
|
||||
Busy,
|
||||
}
|
||||
|
||||
async fn load_current_doc_for_update(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &str,
|
||||
doc_id: &str,
|
||||
) -> RuntimeResult<Option<CurrentDoc>> {
|
||||
let snapshot =
|
||||
sqlx::query_as::<_, CurrentDoc>("SELECT blob, updated_at FROM snapshots WHERE workspace_id = $1 AND guid = $2")
|
||||
.bind(workspace_id)
|
||||
.bind(doc_id)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Document cleanup current snapshot load failed", err))?;
|
||||
let updates = sqlx::query_as::<_, CurrentDocUpdate>(
|
||||
"SELECT blob, created_at FROM updates WHERE workspace_id = $1 AND guid = $2 ORDER BY created_at ASC",
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(doc_id)
|
||||
.fetch_all(&mut **tx)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Document cleanup current updates load failed", err))?;
|
||||
merge_current_doc(snapshot, updates)
|
||||
}
|
||||
|
||||
async fn current_activity(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &str,
|
||||
doc_id: &str,
|
||||
) -> RuntimeResult<Option<DateTime<Utc>>> {
|
||||
sqlx::query_scalar::<_, Option<DateTime<Utc>>>(
|
||||
r#"
|
||||
SELECT MAX(activity_at)
|
||||
FROM (
|
||||
SELECT updated_at AS activity_at FROM snapshots WHERE workspace_id = $1 AND guid = $2
|
||||
UNION ALL SELECT created_at FROM updates WHERE workspace_id = $1 AND guid = $2
|
||||
UNION ALL SELECT timestamp FROM snapshot_histories WHERE workspace_id = $1 AND guid = $2
|
||||
) activity
|
||||
"#,
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(doc_id)
|
||||
.fetch_one(&mut **tx)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Document cleanup activity load failed", err))
|
||||
}
|
||||
|
||||
fn root_contains(root: CurrentDoc, doc_id: &str) -> RuntimeResult<bool> {
|
||||
let projection = affine_doc_loader::project_workspace_root(root.blob, true)
|
||||
.map_err(|err| RuntimeError::invalid_state(format!("Document cleanup root parse failed: {err}")))?;
|
||||
if !projection.complete {
|
||||
return Err(RuntimeError::invalid_state("Document cleanup root doc is incomplete"));
|
||||
}
|
||||
Ok(projection.doc_ids.iter().any(|id| id == doc_id))
|
||||
}
|
||||
|
||||
async fn delete_doc_rows(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
candidate: &DocumentCleanupCandidate,
|
||||
) -> RuntimeResult<i64> {
|
||||
let mut deleted_rows = 0;
|
||||
for (table, doc_column) in [
|
||||
("workspace_pages", "page_id"),
|
||||
("doc_access_policies", "doc_id"),
|
||||
("doc_grants", "doc_id"),
|
||||
("doc_blob_refs", "doc_id"),
|
||||
("doc_blob_ref_projections", "doc_id"),
|
||||
("ai_workspace_ignored_docs", "doc_id"),
|
||||
("comments", "doc_id"),
|
||||
("comment_attachments", "doc_id"),
|
||||
("workspace_doc_view_daily", "doc_id"),
|
||||
] {
|
||||
let query = format!("DELETE FROM {table} WHERE workspace_id = $1 AND {doc_column} = $2");
|
||||
deleted_rows += sqlx::query(&query)
|
||||
.bind(&candidate.workspace_id)
|
||||
.bind(&candidate.doc_id)
|
||||
.execute(&mut **tx)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database(format!("Document cleanup {table} delete failed"), err))?
|
||||
.rows_affected() as i64;
|
||||
}
|
||||
for (table, doc_column) in [
|
||||
("workspace_member_last_access", "last_doc_id"),
|
||||
("ai_sessions_metadata", "doc_id"),
|
||||
("ai_action_runs", "doc_id"),
|
||||
] {
|
||||
let query = format!("UPDATE {table} SET {doc_column} = NULL WHERE workspace_id = $1 AND {doc_column} = $2");
|
||||
deleted_rows += sqlx::query(&query)
|
||||
.bind(&candidate.workspace_id)
|
||||
.bind(&candidate.doc_id)
|
||||
.execute(&mut **tx)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database(format!("Document cleanup {table} unlink failed"), err))?
|
||||
.rows_affected() as i64;
|
||||
}
|
||||
for table in ["updates", "snapshot_histories", "snapshots"] {
|
||||
deleted_rows += sqlx::query(&format!("DELETE FROM {table} WHERE workspace_id = $1 AND guid = $2"))
|
||||
.bind(&candidate.workspace_id)
|
||||
.bind(&candidate.doc_id)
|
||||
.execute(&mut **tx)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database(format!("Document cleanup {table} delete failed"), err))?
|
||||
.rows_affected() as i64;
|
||||
}
|
||||
sqlx::query("DELETE FROM document_cleanup_candidates WHERE workspace_id = $1 AND doc_id = $2")
|
||||
.bind(&candidate.workspace_id)
|
||||
.bind(&candidate.doc_id)
|
||||
.execute(&mut **tx)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Document cleanup candidate delete failed", err))?;
|
||||
Ok(deleted_rows)
|
||||
}
|
||||
|
||||
async fn mark_candidate_failed(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
candidate: &DocumentCleanupCandidate,
|
||||
error: String,
|
||||
) -> RuntimeResult<()> {
|
||||
sqlx::query(
|
||||
"UPDATE document_cleanup_candidates SET status = 'failed', attempt_count = attempt_count + 1, error = $3, \
|
||||
updated_at = CURRENT_TIMESTAMP WHERE workspace_id = $1 AND doc_id = $2",
|
||||
)
|
||||
.bind(&candidate.workspace_id)
|
||||
.bind(&candidate.doc_id)
|
||||
.bind(&error)
|
||||
.execute(&mut **tx)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Document cleanup candidate failure write failed", err))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn execute_document_cleanup_candidate(
|
||||
pool: &PgPool,
|
||||
workspace_id: Option<&str>,
|
||||
grace_period_days: i64,
|
||||
busy_workspaces: &[String],
|
||||
) -> RuntimeResult<Option<(DocumentCleanupCandidate, DocumentCleanupOutcome)>> {
|
||||
let mut tx = pool
|
||||
.begin()
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Document cleanup execute transaction failed", err))?;
|
||||
sqlx::query("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE")
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Document cleanup isolation setup failed", err))?;
|
||||
let candidate = sqlx::query_as::<_, DocumentCleanupCandidate>(
|
||||
r#"
|
||||
SELECT workspace_id, doc_id, last_doc_activity_at
|
||||
FROM document_cleanup_candidates
|
||||
WHERE (status = 'marked'
|
||||
OR (status = 'failed' AND updated_at <= CURRENT_TIMESTAMP - INTERVAL '5 minutes'))
|
||||
AND ($1::text IS NULL OR workspace_id = $1)
|
||||
AND missing_since <= CURRENT_TIMESTAMP - make_interval(days => $2::int)
|
||||
AND NOT (workspace_id = ANY($3))
|
||||
ORDER BY missing_since, workspace_id, doc_id
|
||||
FOR UPDATE SKIP LOCKED
|
||||
LIMIT 1
|
||||
"#,
|
||||
)
|
||||
.bind(workspace_id)
|
||||
.bind(grace_period_days as i32)
|
||||
.bind(busy_workspaces)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Document cleanup candidate claim failed", err))?;
|
||||
let Some(candidate) = candidate else {
|
||||
tx.rollback()
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Document cleanup empty claim rollback failed", err))?;
|
||||
return Ok(None);
|
||||
};
|
||||
let workspace_lock_key = format!("storage-workspace:{}", candidate.workspace_id);
|
||||
let locked: bool = sqlx::query_scalar("SELECT pg_try_advisory_xact_lock(hashtextextended($1,0))")
|
||||
.bind(&workspace_lock_key)
|
||||
.fetch_one(&mut *tx)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Document cleanup workspace source lock failed", err))?;
|
||||
if !locked {
|
||||
tx.rollback()
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Document cleanup busy claim rollback failed", err))?;
|
||||
return Ok(Some((candidate, DocumentCleanupOutcome::Busy)));
|
||||
}
|
||||
|
||||
if classify_reserved_document(&candidate.workspace_id, &candidate.doc_id).is_valid_reserved() {
|
||||
sqlx::query("DELETE FROM document_cleanup_candidates WHERE workspace_id = $1 AND doc_id = $2")
|
||||
.bind(&candidate.workspace_id)
|
||||
.bind(&candidate.doc_id)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Document cleanup reserved candidate delete failed", err))?;
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Document cleanup reserved candidate commit failed", err))?;
|
||||
return Ok(Some((candidate, DocumentCleanupOutcome::Recovered)));
|
||||
}
|
||||
|
||||
let root = match load_current_doc_for_update(&mut tx, &candidate.workspace_id, &candidate.workspace_id).await {
|
||||
Ok(Some(root)) => root,
|
||||
Ok(None) => {
|
||||
mark_candidate_failed(
|
||||
&mut tx,
|
||||
&candidate,
|
||||
"Workspace root doc is missing during document cleanup execute".to_string(),
|
||||
)
|
||||
.await?;
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Document cleanup failed candidate commit failed", err))?;
|
||||
return Ok(Some((candidate, DocumentCleanupOutcome::Failed)));
|
||||
}
|
||||
Err(err) => {
|
||||
mark_candidate_failed(&mut tx, &candidate, err.to_string()).await?;
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Document cleanup failed candidate commit failed", err))?;
|
||||
return Ok(Some((candidate, DocumentCleanupOutcome::Failed)));
|
||||
}
|
||||
};
|
||||
let contains = match root_contains(root, &candidate.doc_id) {
|
||||
Ok(contains) => contains,
|
||||
Err(err) => {
|
||||
mark_candidate_failed(&mut tx, &candidate, err.to_string()).await?;
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Document cleanup failed candidate commit failed", err))?;
|
||||
return Ok(Some((candidate, DocumentCleanupOutcome::Failed)));
|
||||
}
|
||||
};
|
||||
if contains {
|
||||
sqlx::query("DELETE FROM document_cleanup_candidates WHERE workspace_id = $1 AND doc_id = $2")
|
||||
.bind(&candidate.workspace_id)
|
||||
.bind(&candidate.doc_id)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Document cleanup recovered candidate delete failed", err))?;
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Document cleanup recovered candidate commit failed", err))?;
|
||||
return Ok(Some((candidate, DocumentCleanupOutcome::Recovered)));
|
||||
}
|
||||
let activity = current_activity(&mut tx, &candidate.workspace_id, &candidate.doc_id).await?;
|
||||
if activity != candidate.last_doc_activity_at {
|
||||
sqlx::query(
|
||||
"UPDATE document_cleanup_candidates SET status = 'marked', missing_since = CURRENT_TIMESTAMP, \
|
||||
last_observed_missing_at = CURRENT_TIMESTAMP, last_doc_activity_at = $3, error = NULL, updated_at = \
|
||||
CURRENT_TIMESTAMP WHERE workspace_id = $1 AND doc_id = $2",
|
||||
)
|
||||
.bind(&candidate.workspace_id)
|
||||
.bind(&candidate.doc_id)
|
||||
.bind(activity)
|
||||
.execute(&mut *tx)
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Document cleanup activity reset failed", err))?;
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Document cleanup activity reset commit failed", err))?;
|
||||
return Ok(Some((candidate, DocumentCleanupOutcome::Reset)));
|
||||
}
|
||||
let deleted_rows = delete_doc_rows(&mut tx, &candidate).await?;
|
||||
tx.commit()
|
||||
.await
|
||||
.map_err(|err| RuntimeError::database("Document cleanup execute commit failed", err))?;
|
||||
Ok(Some((candidate, DocumentCleanupOutcome::Deleted(deleted_rows))))
|
||||
}
|
||||
@@ -4,8 +4,6 @@ mod capabilities;
|
||||
mod config;
|
||||
mod current_doc;
|
||||
mod doc_blob_refs;
|
||||
mod document_cleanup;
|
||||
mod document_cleanup_execution;
|
||||
mod workspace_cleanup;
|
||||
mod workspace_cleanup_checkpoint;
|
||||
mod workspace_cleanup_namespace;
|
||||
@@ -15,20 +13,22 @@ pub use capabilities::StorageProviderCapabilities;
|
||||
use capabilities::storage_provider_capabilities;
|
||||
pub(in crate::runtime) use config::StorageRuntimeConfig;
|
||||
pub(super) use current_doc::load_current_doc;
|
||||
pub(in crate::runtime) use current_doc::{CurrentDoc, CurrentDocUpdate, load_current_doc_parts, merge_current_doc};
|
||||
use current_doc::{load_canonical_doc, load_workspace_canonical_doc_ids, load_workspace_live_doc_ids};
|
||||
pub(in crate::runtime) use current_doc::{
|
||||
CurrentDoc, CurrentDocUpdate, load_current_doc_in, load_current_doc_parts, load_current_doc_parts_in,
|
||||
merge_current_doc,
|
||||
};
|
||||
use napi::bindgen_prelude::Buffer;
|
||||
use serde_json::Value;
|
||||
use sqlx::{PgPool, Row, postgres::PgPoolOptions};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
pub(super) use super::{
|
||||
BlobRefProjectionError, RuntimeError, RuntimeResult, blob_ref_projection_error_code, extract_blob_refs,
|
||||
RuntimeError, RuntimeResult, blob_ref_projection_error_code, extract_blob_refs, load_workspace_doc_states_in,
|
||||
lock_current_doc_read,
|
||||
migrations::migrate_runtime_tables,
|
||||
napi_error, to_napi_error,
|
||||
types::{
|
||||
RuntimeBlobCleanupResult, RuntimeBlobMetadataBackfillResult, RuntimeDocBlobRefsResult,
|
||||
RuntimeDocumentCleanupExecuteResult, RuntimeDocumentCleanupReconcileResult, RuntimeMultipartUploadInit,
|
||||
RuntimeBlobCleanupResult, RuntimeBlobMetadataBackfillResult, RuntimeDocBlobRefsResult, RuntimeMultipartUploadInit,
|
||||
RuntimeMultipartUploadPart, RuntimeObjectGetResult, RuntimeObjectMetadata, RuntimeObjectStoragePutOptions,
|
||||
RuntimePresignedObjectRequest, RuntimeWorkspaceStorageReconcileResult,
|
||||
},
|
||||
@@ -44,14 +44,6 @@ use crate::runtime::config::{ServerConfig, ServerConfigHandle};
|
||||
|
||||
type Result<T> = RuntimeResult<T>;
|
||||
|
||||
#[derive(sqlx::FromRow)]
|
||||
pub(super) struct DocumentCleanupCandidate {
|
||||
pub(super) workspace_id: String,
|
||||
pub(super) doc_id: String,
|
||||
pub(super) last_doc_activity_at: Option<chrono::DateTime<chrono::Utc>>,
|
||||
}
|
||||
|
||||
use document_cleanup_execution::{DocumentCleanupOutcome, execute_document_cleanup_candidate};
|
||||
use workspace_cleanup_checkpoint::{
|
||||
delete_orphan_storage_rows, embedding_tables_exist, load_integer_cursor, load_object_cursor, mark_checkpoint_failed,
|
||||
reconcile_orphan_storage_rows, save_integer_cursor, save_object_cursor,
|
||||
|
||||
@@ -125,6 +125,7 @@ const WORKSPACE_CHECKPOINT_KINDS: &[&str] = &[
|
||||
"blob_cleanup",
|
||||
"blob_cleanup_plan",
|
||||
"blob_metadata_backfill",
|
||||
"workspace_root_source",
|
||||
];
|
||||
|
||||
pub(super) async fn embedding_tables_exist(pool: &PgPool) -> napi::Result<bool> {
|
||||
|
||||
@@ -73,9 +73,7 @@ pub struct DocumentEmbeddingProjectionInput {
|
||||
pub revision: String,
|
||||
pub source_hash: String,
|
||||
pub skip_reason: Option<String>,
|
||||
pub root_revision: Option<String>,
|
||||
pub units: Vec<DocumentEmbeddingUnitInput>,
|
||||
pub deleted: Option<bool>,
|
||||
}
|
||||
|
||||
#[napi_derive::napi(object)]
|
||||
@@ -83,7 +81,6 @@ pub struct SyncEmbeddingStateInput {
|
||||
pub workspace_id: String,
|
||||
pub enabled: bool,
|
||||
pub documents: Option<Vec<DocumentEmbeddingProjectionInput>>,
|
||||
pub reconcile_documents: Option<bool>,
|
||||
pub priority: Option<i32>,
|
||||
pub wait_for_ready_ms: Option<u32>,
|
||||
}
|
||||
@@ -548,25 +545,6 @@ pub struct RuntimeDocBlobRefsResult {
|
||||
pub next_cursor: Option<String>,
|
||||
}
|
||||
|
||||
#[napi_derive::napi(object)]
|
||||
pub struct RuntimeDocumentCleanupReconcileResult {
|
||||
pub scanned_docs: i64,
|
||||
pub marked: i64,
|
||||
pub reset: i64,
|
||||
pub recovered: i64,
|
||||
}
|
||||
|
||||
#[napi_derive::napi(object)]
|
||||
pub struct RuntimeDocumentCleanupExecuteResult {
|
||||
pub scanned_candidates: i64,
|
||||
pub serialization_retries: i64,
|
||||
pub executed: i64,
|
||||
pub recovered: i64,
|
||||
pub reset: i64,
|
||||
pub failed: i64,
|
||||
pub deleted_rows: i64,
|
||||
}
|
||||
|
||||
#[napi_derive::napi(object)]
|
||||
pub struct RuntimeBlobCleanupResult {
|
||||
pub scanned_blobs: i64,
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
CREATE TYPE "DocLifecycleState" AS ENUM ('trashed', 'deleted');
|
||||
ALTER TABLE "workspace_pages"
|
||||
ADD COLUMN "lifecycle_state" "DocLifecycleState",
|
||||
ADD COLUMN "lifecycle_changed_at" TIMESTAMPTZ(3);
|
||||
@@ -466,6 +466,11 @@ model DocGrant {
|
||||
// We won't make sure every page has a corresponding record in this table.
|
||||
// Only the ones that have ever changed will have records here,
|
||||
// and for others we will make sure it's has a default value return in our business logic.
|
||||
enum DocLifecycleState {
|
||||
trashed
|
||||
deleted
|
||||
}
|
||||
|
||||
model WorkspaceDoc {
|
||||
workspaceId String @map("workspace_id") @db.VarChar
|
||||
docId String @map("page_id") @db.VarChar
|
||||
@@ -476,6 +481,8 @@ model WorkspaceDoc {
|
||||
title String? @db.VarChar
|
||||
summary String? @db.VarChar
|
||||
publishedAt DateTime? @map("published_at") @db.Timestamptz(3)
|
||||
lifecycleState DocLifecycleState? @map("lifecycle_state")
|
||||
lifecycleChangedAt DateTime? @map("lifecycle_changed_at") @db.Timestamptz(3)
|
||||
|
||||
workspace Workspace @relation(fields: [workspaceId], references: [id], onDelete: Cascade)
|
||||
|
||||
|
||||
@@ -154,28 +154,6 @@ test('should create history if time diff is larger than interval config and stat
|
||||
t.truthy(history);
|
||||
});
|
||||
|
||||
test('should create history with force flag even if time diff in small', async t => {
|
||||
const timestamp = new Date();
|
||||
|
||||
// @ts-expect-error private method
|
||||
Sinon.stub(adapter, 'lastDocHistory').resolves({
|
||||
timestamp: new Date(timestamp.getTime() - 1),
|
||||
state: Buffer.from([0, 1]),
|
||||
});
|
||||
|
||||
// @ts-expect-error private method
|
||||
await adapter.createDocHistory(getSnapshot(timestamp), true);
|
||||
|
||||
const history = await db.snapshotHistory.findFirst({
|
||||
where: {
|
||||
workspaceId: '1',
|
||||
id: 'doc1',
|
||||
},
|
||||
});
|
||||
|
||||
t.truthy(history);
|
||||
});
|
||||
|
||||
test('should correctly list all history records', async t => {
|
||||
const timestamp = Date.now();
|
||||
|
||||
@@ -222,7 +200,7 @@ test('should be able to get history data', async t => {
|
||||
const timestamp = Date.now();
|
||||
|
||||
// @ts-expect-error private method
|
||||
await adapter.createDocHistory(getSnapshot(timestamp), true);
|
||||
await adapter.createDocHistory(getSnapshot(timestamp));
|
||||
|
||||
const history = await adapter.getDocHistory(
|
||||
snapshot.workspaceId,
|
||||
@@ -260,36 +238,3 @@ test('should be able to get last history record', async t => {
|
||||
t.truthy(history);
|
||||
t.is(history?.timestamp, timestamp + 9);
|
||||
});
|
||||
|
||||
test('should be able to recover from history', async t => {
|
||||
await db.snapshot.create({
|
||||
data: {
|
||||
...snapshot,
|
||||
blob: Buffer.from([1, 1]),
|
||||
state: Buffer.from([1, 1]),
|
||||
},
|
||||
});
|
||||
const history1Timestamp = snapshot.updatedAt.getTime() - 10;
|
||||
|
||||
// @ts-expect-error private method
|
||||
await adapter.createDocHistory(getSnapshot(history1Timestamp));
|
||||
|
||||
await adapter.rollbackDoc(
|
||||
snapshot.workspaceId,
|
||||
snapshot.id,
|
||||
history1Timestamp
|
||||
);
|
||||
|
||||
const [history1, history2] = await db.snapshotHistory.findMany({
|
||||
where: {
|
||||
workspaceId: snapshot.workspaceId,
|
||||
id: snapshot.id,
|
||||
},
|
||||
});
|
||||
|
||||
t.is(history1.timestamp.getTime(), history1Timestamp);
|
||||
t.is(history2.timestamp.getTime(), snapshot.updatedAt.getTime());
|
||||
|
||||
// new history data force created with snapshot state before recovered
|
||||
t.deepEqual(history2.blob, Uint8Array.from([1, 1]));
|
||||
});
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
DocStorageModule,
|
||||
PgUserspaceDocStorageAdapter as Adapter,
|
||||
} from '../../core/doc';
|
||||
import { mergeUpdatesWithYjs } from '../../core/doc/merge-updates';
|
||||
import { Models, type User } from '../../models';
|
||||
import { createTestingModule, type TestingModule } from '../utils';
|
||||
|
||||
@@ -55,7 +56,7 @@ test('should push user doc updates work', async t => {
|
||||
text.insert(5, 'world');
|
||||
text.insert(5, ' ');
|
||||
|
||||
let timestamp = await t.context.adapter.pushDocUpdates(
|
||||
let { timestamp } = await t.context.adapter.pushDocUpdates(
|
||||
user.id,
|
||||
docId,
|
||||
updates
|
||||
@@ -67,6 +68,23 @@ test('should push user doc updates work', async t => {
|
||||
applyUpdate(newDoc, record!.bin);
|
||||
|
||||
t.is(newDoc.getText('content').toString(), 'hello world');
|
||||
await t.throwsAsync(
|
||||
t.context.adapter.pushDocUpdates(user.id, docId, [
|
||||
updates[0],
|
||||
new Uint8Array([255]),
|
||||
]),
|
||||
{ name: 'doc_update_invalid' }
|
||||
);
|
||||
const unchanged = await t.context.adapter.getDoc(user.id, docId);
|
||||
t.deepEqual(Buffer.from(unchanged!.bin), Buffer.from(record!.bin));
|
||||
t.is(unchanged!.timestamp, record!.timestamp);
|
||||
t.throws(() =>
|
||||
mergeUpdatesWithYjs(
|
||||
[...Array.from({ length: 10 }, () => updates[0]), new Uint8Array([255])],
|
||||
'userspace.invalid_later_batch'
|
||||
)
|
||||
);
|
||||
|
||||
// find all timestamps
|
||||
const timestamps = await t.context.adapter.getSpaceDocTimestamps(user.id);
|
||||
t.deepEqual(timestamps, {
|
||||
@@ -88,7 +106,7 @@ test('should delete user doc work', async t => {
|
||||
text.insert(5, 'world');
|
||||
text.insert(5, ' ');
|
||||
|
||||
let timestamp = await t.context.adapter.pushDocUpdates(
|
||||
let { timestamp } = await t.context.adapter.pushDocUpdates(
|
||||
user.id,
|
||||
docId,
|
||||
updates
|
||||
@@ -118,7 +136,7 @@ test('should delete all user docs work', async t => {
|
||||
text.insert(5, 'world');
|
||||
text.insert(5, ' ');
|
||||
|
||||
let timestamp = await t.context.adapter.pushDocUpdates(
|
||||
let { timestamp } = await t.context.adapter.pushDocUpdates(
|
||||
user.id,
|
||||
docId,
|
||||
updates
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
DocStorageModule,
|
||||
PgWorkspaceDocStorageAdapter as Adapter,
|
||||
} from '../../core/doc';
|
||||
import { DocWriter } from '../../core/doc/writer';
|
||||
import { createTestingModule, type TestingModule } from '../utils';
|
||||
|
||||
let m: TestingModule;
|
||||
@@ -48,19 +49,19 @@ test('should not compact from a stale update view', async t => {
|
||||
text.insert(5, 'world');
|
||||
text.insert(5, ' ');
|
||||
|
||||
await adapter.pushDocUpdatesTrusted('2', '2', updates);
|
||||
await adapter.pushDocUpdatesTrusted('2', 'doc-2', updates);
|
||||
|
||||
await adapter.getDoc('2', '2');
|
||||
await adapter.pushDocUpdatesTrusted('2', '2', updates);
|
||||
await adapter.getDoc('2', 'doc-2');
|
||||
await adapter.pushDocUpdatesTrusted('2', 'doc-2', updates);
|
||||
|
||||
const records = await db.update.findMany({
|
||||
where: {
|
||||
workspaceId: '2',
|
||||
id: '2',
|
||||
id: 'doc-2',
|
||||
},
|
||||
});
|
||||
|
||||
await adapter.pushDocUpdatesTrusted('2', '2', updates.slice(0, 1));
|
||||
await adapter.pushDocUpdatesTrusted('2', 'doc-2', updates.slice(0, 1));
|
||||
|
||||
// @ts-expect-error private method
|
||||
const stub = Sinon.stub(adapter, 'getDocUpdates').resolves(
|
||||
@@ -70,43 +71,78 @@ test('should not compact from a stale update view', async t => {
|
||||
}))
|
||||
);
|
||||
|
||||
await adapter.getDoc('2', '2');
|
||||
await adapter.getDoc('2', 'doc-2');
|
||||
stub.restore();
|
||||
|
||||
t.not(await db.update.count(), 0);
|
||||
});
|
||||
|
||||
test('should finish doc creation after retrying failed updates', async t => {
|
||||
const stub = Sinon.stub(runtime, 'appendWorkspaceDocUpdatesTrustedV1');
|
||||
test('should emit creation only from the committed creation receipt', async t => {
|
||||
const stub = Sinon.stub(runtime, 'appendWorkspaceDocUpdatesV1');
|
||||
t.teardown(() => stub.restore());
|
||||
let creationCompleted = false;
|
||||
let creations = 0;
|
||||
t.teardown(
|
||||
m.get(EventBus).on('doc.created', async () => {
|
||||
await new Promise<void>(resolve => setImmediate(resolve));
|
||||
creationCompleted = true;
|
||||
m.get(EventBus).on('doc.created', () => {
|
||||
creations++;
|
||||
})
|
||||
);
|
||||
stub.onCall(0).rejects(new Error('storage unavailable'));
|
||||
stub.onCall(1).resolves({ timestamp: Date.now(), created: true });
|
||||
stub.onCall(2).resolves({ timestamp: Date.now(), created: false });
|
||||
const push = () =>
|
||||
adapter.pushDocUpdates(
|
||||
'1',
|
||||
'doc-1',
|
||||
[Buffer.from([0, 0])],
|
||||
'owner',
|
||||
undefined,
|
||||
'create_doc'
|
||||
);
|
||||
await t.throwsAsync(push);
|
||||
t.is(creations, 0);
|
||||
await push();
|
||||
await push();
|
||||
t.is(creations, 1);
|
||||
|
||||
stub.onCall(0).rejects(new Error());
|
||||
stub.onCall(1).resolves(Date.now());
|
||||
|
||||
await t.notThrowsAsync(() =>
|
||||
adapter.pushDocUpdatesTrusted('1', '1', [Buffer.from([0, 0])])
|
||||
);
|
||||
t.is(stub.callCount, 2);
|
||||
t.true(creationCompleted);
|
||||
const trusted = Sinon.stub(adapter, 'pushDocUpdatesTrusted').resolves(42);
|
||||
const read = Sinon.stub(adapter, 'getDoc').resolves(null);
|
||||
t.teardown(() => {
|
||||
trusted.restore();
|
||||
read.restore();
|
||||
});
|
||||
const writer = new DocWriter(adapter, m.get(EventBus));
|
||||
stub.onCall(3).rejects(new Error('permission denied'));
|
||||
await t.throwsAsync(() => writer.createDoc('1', 'title', 'body', 'actor'), {
|
||||
message: 'permission denied',
|
||||
});
|
||||
t.is(trusted.callCount, 0);
|
||||
stub.onCall(4).resolves({ timestamp: 41, created: true });
|
||||
const created = await writer.createDoc('1', 'title', 'body', 'actor');
|
||||
t.is(trusted.callCount, 1);
|
||||
const [workspaceId, propertiesId, updates, editor] = trusted.firstCall.args;
|
||||
t.is(workspaceId, '1');
|
||||
t.is(propertiesId, 'db$1$docProperties');
|
||||
t.is(editor, 'actor');
|
||||
const properties = new YDoc();
|
||||
for (const update of updates) applyUpdate(properties, update);
|
||||
t.deepEqual(properties.getMap(created.docId).toJSON(), {
|
||||
id: created.docId,
|
||||
createdBy: 'actor',
|
||||
updatedBy: 'actor',
|
||||
});
|
||||
t.deepEqual([...properties.share.keys()], [created.docId]);
|
||||
});
|
||||
|
||||
test('should throw if meet max retry times', async t => {
|
||||
test('should propagate storage errors without internal retries', async t => {
|
||||
const stub = Sinon.stub(runtime, 'appendWorkspaceDocUpdatesTrustedV1');
|
||||
|
||||
stub.rejects(new Error());
|
||||
stub.rejects(new Error('storage unavailable'));
|
||||
|
||||
await t.throwsAsync(
|
||||
() => adapter.pushDocUpdatesTrusted('1', '1', [Buffer.from([0, 0])]),
|
||||
{ message: 'Failed to store doc updates.' }
|
||||
() => adapter.pushDocUpdatesTrusted('1', 'doc-1', [Buffer.from([0, 0])]),
|
||||
{ message: 'storage unavailable' }
|
||||
);
|
||||
t.is(stub.callCount, 4);
|
||||
t.is(stub.callCount, 1);
|
||||
|
||||
stub.restore();
|
||||
});
|
||||
@@ -127,7 +163,7 @@ test('should be able to merge updates as snapshot', async t => {
|
||||
await db.update.createMany({
|
||||
data: [
|
||||
{
|
||||
id: '1',
|
||||
id: 'doc-1',
|
||||
workspaceId: '1',
|
||||
blob: Buffer.from(update),
|
||||
createdAt: new Date(Date.now() + 1),
|
||||
@@ -137,7 +173,7 @@ test('should be able to merge updates as snapshot', async t => {
|
||||
});
|
||||
|
||||
t.deepEqual(
|
||||
Buffer.from((await adapter.getDoc('1', '1'))!.bin),
|
||||
Buffer.from((await adapter.getDoc('1', 'doc-1'))!.bin),
|
||||
Buffer.from(update)
|
||||
);
|
||||
|
||||
@@ -150,7 +186,7 @@ test('should be able to merge updates as snapshot', async t => {
|
||||
await db.update.create({
|
||||
data: {
|
||||
workspaceId: '1',
|
||||
id: '1',
|
||||
id: 'doc-1',
|
||||
blob: appendUpdate,
|
||||
createdAt: new Date(),
|
||||
createdBy: null,
|
||||
@@ -158,7 +194,7 @@ test('should be able to merge updates as snapshot', async t => {
|
||||
});
|
||||
|
||||
{
|
||||
const { bin } = (await adapter.getDoc('1', '1'))!;
|
||||
const { bin } = (await adapter.getDoc('1', 'doc-1'))!;
|
||||
const dbDoc = new YDoc();
|
||||
applyUpdate(dbDoc, bin);
|
||||
|
||||
@@ -167,7 +203,7 @@ test('should be able to merge updates as snapshot', async t => {
|
||||
}
|
||||
});
|
||||
|
||||
test('should be able to merge updates into snapshot', async t => {
|
||||
test('should raw merge updates without replacing persisted fragments', async t => {
|
||||
const updates: Buffer[] = [];
|
||||
{
|
||||
const doc = new YDoc();
|
||||
@@ -183,9 +219,9 @@ test('should be able to merge updates into snapshot', async t => {
|
||||
}
|
||||
|
||||
{
|
||||
await adapter.pushDocUpdatesTrusted('1', '1', updates.slice(0, 2));
|
||||
await adapter.pushDocUpdatesTrusted('1', 'doc-1', updates.slice(0, 2));
|
||||
// merge
|
||||
const { bin } = (await adapter.getDoc('1', '1'))!;
|
||||
const { bin } = (await adapter.getDoc('1', 'doc-1'))!;
|
||||
const doc = new YDoc();
|
||||
applyUpdate(doc, bin);
|
||||
|
||||
@@ -193,16 +229,16 @@ test('should be able to merge updates into snapshot', async t => {
|
||||
}
|
||||
|
||||
{
|
||||
await adapter.pushDocUpdatesTrusted('1', '1', updates.slice(2));
|
||||
await adapter.pushDocUpdatesTrusted('1', 'doc-1', updates.slice(2));
|
||||
// merge
|
||||
const { bin } = (await adapter.getDoc('1', '1'))!;
|
||||
const { bin } = (await adapter.getDoc('1', 'doc-1'))!;
|
||||
const doc = new YDoc();
|
||||
applyUpdate(doc, bin);
|
||||
|
||||
t.is(doc.getText('content').toString(), 'hello world!');
|
||||
}
|
||||
|
||||
t.is(await db.update.count(), 0);
|
||||
t.is(await db.update.count(), updates.length);
|
||||
});
|
||||
|
||||
test('should merge updates after a future-dated snapshot', async t => {
|
||||
@@ -220,25 +256,22 @@ test('should merge updates after a future-dated snapshot', async t => {
|
||||
text.insert(11, '!');
|
||||
}
|
||||
|
||||
await adapter.pushDocUpdatesTrusted('2', '1', updates.slice(0, 2)); // 'helloworld'
|
||||
// merge
|
||||
await adapter.getDoc('2', '1');
|
||||
// fake the snapshot is a lot newer
|
||||
await db.snapshot.update({
|
||||
where: {
|
||||
workspaceId_id: {
|
||||
workspaceId: '2',
|
||||
id: '1',
|
||||
},
|
||||
},
|
||||
await adapter.pushDocUpdatesTrusted('2', 'doc-1', updates.slice(0, 2)); // 'helloworld'
|
||||
const current = (await adapter.getDoc('2', 'doc-1'))!;
|
||||
const future = new Date(Date.now() + 10000);
|
||||
await db.snapshot.create({
|
||||
data: {
|
||||
updatedAt: new Date(Date.now() + 10000),
|
||||
workspaceId: '2',
|
||||
id: 'doc-1',
|
||||
blob: Buffer.from(current.bin),
|
||||
size: current.bin.byteLength,
|
||||
updatedAt: future,
|
||||
},
|
||||
});
|
||||
|
||||
{
|
||||
await adapter.pushDocUpdatesTrusted('2', '1', updates.slice(2)); // 'hello world!'
|
||||
const { bin } = (await adapter.getDoc('2', '1'))!;
|
||||
await adapter.pushDocUpdatesTrusted('2', 'doc-1', updates.slice(2)); // 'hello world!'
|
||||
const { bin } = (await adapter.getDoc('2', 'doc-1'))!;
|
||||
|
||||
const doc = new YDoc();
|
||||
applyUpdate(doc, bin);
|
||||
@@ -247,14 +280,15 @@ test('should merge updates after a future-dated snapshot', async t => {
|
||||
|
||||
{
|
||||
const doc = new YDoc();
|
||||
applyUpdate(doc, (await adapter.getDoc('2', '1'))!.bin);
|
||||
applyUpdate(doc, (await adapter.getDoc('2', 'doc-1'))!.bin);
|
||||
t.is(doc.getText('content').toString(), 'hello world!');
|
||||
|
||||
t.is(await db.update.count(), 0);
|
||||
t.is(await db.update.count(), updates.length);
|
||||
t.true((await adapter.getDoc('2', 'doc-1'))!.timestamp > future.getTime());
|
||||
}
|
||||
});
|
||||
|
||||
test('should not recreate a doc deleted before compaction acquires its database lock', async t => {
|
||||
test('should not recreate a doc deleted before its read acquires the database lock', async t => {
|
||||
const workspaceId = 'delete-before-compaction';
|
||||
const docId = 'doc';
|
||||
const doc = new YDoc();
|
||||
|
||||
@@ -3,7 +3,7 @@ import test, { registerCompletionHandler } from 'ava';
|
||||
|
||||
import { BackendRuntimeProvider } from '../../core/backend-runtime';
|
||||
import { Env } from '../../env';
|
||||
import { addDocToRootDoc, mergeUpdatesInApplyWay } from '../../native';
|
||||
import { addDocToRootDoc, mergeUpdates } from '../../native';
|
||||
import { type TestingApp } from './create-app';
|
||||
|
||||
export const e2e = test;
|
||||
@@ -27,7 +27,7 @@ export async function addDocumentToRoot(workspaceId: string, docId: string) {
|
||||
await db.snapshot.update({
|
||||
where,
|
||||
data: {
|
||||
blob: mergeUpdatesInApplyWay([rootBlob, update]),
|
||||
blob: mergeUpdates([rootBlob, update]),
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import ava, { TestFn } from 'ava';
|
||||
|
||||
import { Config } from '../../base/config';
|
||||
@@ -18,7 +19,7 @@ interface Context {
|
||||
history: HistoryModel;
|
||||
}
|
||||
|
||||
const test = ava as TestFn<Context>;
|
||||
const test = ava.serial as TestFn<Context>;
|
||||
|
||||
test.before(async t => {
|
||||
const module = await createTestingModule();
|
||||
@@ -229,6 +230,11 @@ test('should upsert a doc', async t => {
|
||||
t.truthy(updatedSnapshot);
|
||||
t.deepEqual(updatedSnapshot!.blob, snapshot.blob);
|
||||
t.is(updatedSnapshot!.editorId, otherUser.id);
|
||||
await t.throwsAsync(
|
||||
t.context.doc.upsert({ ...snapshot, docId: workspace.id }),
|
||||
{ message: 'Workspace indexes must use the root update writer.' }
|
||||
);
|
||||
t.is(await t.context.doc.get(workspace.id, workspace.id), null);
|
||||
});
|
||||
|
||||
test('should get a doc authors', async t => {
|
||||
@@ -479,6 +485,23 @@ test('should update doc meta', async t => {
|
||||
...data,
|
||||
public: false,
|
||||
});
|
||||
const db = t.context.module.get(PrismaClient);
|
||||
await db.workspaceDoc.update({
|
||||
where: { workspaceId_docId: { workspaceId: workspace.id, docId } },
|
||||
data: { lifecycleState: 'deleted', lifecycleChangedAt: new Date() },
|
||||
});
|
||||
await t.throwsAsync(
|
||||
t.context.doc.upsertMeta(workspace.id, docId, { title: 'revive' }),
|
||||
{ message: 'Document not found' }
|
||||
);
|
||||
t.is(
|
||||
(
|
||||
await db.workspaceDoc.findUniqueOrThrow({
|
||||
where: { workspaceId_docId: { workspaceId: workspace.id, docId } },
|
||||
})
|
||||
).lifecycleState,
|
||||
'deleted'
|
||||
);
|
||||
});
|
||||
|
||||
test('should get null when doc meta not exists', async t => {
|
||||
@@ -505,11 +528,42 @@ test('should get public doc count', async t => {
|
||||
const docId3 = randomUUID();
|
||||
await t.context.doc.upsertMeta(workspace.id, docId1, {
|
||||
public: true,
|
||||
publishedAt: new Date(),
|
||||
});
|
||||
await t.context.doc.upsertMeta(workspace.id, docId2, {
|
||||
public: true,
|
||||
publishedAt: new Date(),
|
||||
});
|
||||
await t.context.doc.upsertMeta(workspace.id, docId3);
|
||||
await t.context.doc.createUpdates(
|
||||
[docId1, docId2, docId3].map(docId => ({
|
||||
spaceId: workspace.id,
|
||||
docId,
|
||||
blob: Buffer.from([0, 0]),
|
||||
timestamp: Date.now(),
|
||||
editorId: user.id,
|
||||
}))
|
||||
);
|
||||
await t.context.doc.upsertMeta(workspace.id, 'metadata-only-public', {
|
||||
public: true,
|
||||
publishedAt: new Date(),
|
||||
});
|
||||
await t.context.doc.createUpdates([
|
||||
{
|
||||
spaceId: workspace.id,
|
||||
docId: 'orphan-policy',
|
||||
blob: Buffer.from([0, 0]),
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
]);
|
||||
await t.context.module.get(PrismaClient).docAccessPolicy.create({
|
||||
data: {
|
||||
workspaceId: workspace.id,
|
||||
docId: 'orphan-policy',
|
||||
visibility: 'public',
|
||||
publicRole: 'external',
|
||||
},
|
||||
});
|
||||
const count = await t.context.doc.getPublicsCount(workspace.id);
|
||||
t.is(count, 2);
|
||||
});
|
||||
@@ -520,13 +574,28 @@ test('should get public docs of a workspace', async t => {
|
||||
const docId3 = `3-${randomUUID()}`;
|
||||
await t.context.doc.upsertMeta(workspace.id, docId1, {
|
||||
public: true,
|
||||
publishedAt: new Date(),
|
||||
});
|
||||
await t.context.doc.upsertMeta(workspace.id, docId2, {
|
||||
public: true,
|
||||
publishedAt: new Date(),
|
||||
});
|
||||
await t.context.doc.upsertMeta(workspace.id, docId3, {
|
||||
public: false,
|
||||
});
|
||||
await t.context.doc.createUpdates(
|
||||
[docId1, docId2, docId3].map(docId => ({
|
||||
spaceId: workspace.id,
|
||||
docId,
|
||||
blob: Buffer.from([0, 0]),
|
||||
timestamp: Date.now(),
|
||||
editorId: user.id,
|
||||
}))
|
||||
);
|
||||
await t.context.doc.upsertMeta(workspace.id, 'metadata-only-public', {
|
||||
public: true,
|
||||
publishedAt: new Date(),
|
||||
});
|
||||
const docs = await t.context.doc.findPublics(workspace.id);
|
||||
t.is(docs.length, 2);
|
||||
t.deepEqual(docs.map(d => d.docId).sort(), [docId1, docId2]);
|
||||
@@ -686,6 +755,33 @@ test('should get doc info', async t => {
|
||||
title: 'test title',
|
||||
summary: 'test summary',
|
||||
});
|
||||
const updateOnlyId = randomUUID();
|
||||
await t.context.doc.createUpdates([
|
||||
{
|
||||
spaceId: workspace.id,
|
||||
docId: updateOnlyId,
|
||||
blob: Buffer.from([0, 0]),
|
||||
timestamp: snapshot.timestamp + 1,
|
||||
editorId: user.id,
|
||||
},
|
||||
]);
|
||||
const updateOnly = await t.context.doc.getDocInfo(workspace.id, updateOnlyId);
|
||||
t.like(updateOnly, {
|
||||
docId: updateOnlyId,
|
||||
title: null,
|
||||
updatedAt: new Date(snapshot.timestamp + 1),
|
||||
creatorId: user.id,
|
||||
lastUpdaterId: user.id,
|
||||
});
|
||||
t.true(
|
||||
(await t.context.doc.listWorkspaceDocIds(workspace.id)).includes(
|
||||
updateOnlyId
|
||||
)
|
||||
);
|
||||
t.like(await t.context.doc.getAuthors(workspace.id, updateOnlyId), {
|
||||
createdByUser: { id: user.id },
|
||||
updatedByUser: { id: user.id },
|
||||
});
|
||||
});
|
||||
|
||||
test('should paginate docs info', async t => {
|
||||
@@ -740,5 +836,39 @@ test('should paginate docs info', async t => {
|
||||
t.is(docs.length, 1);
|
||||
t.is(docs[0].docId, docId2);
|
||||
t.false(docs[0].public);
|
||||
|
||||
// Migrated empty documents can share every source timestamp.
|
||||
await t.context.module.get(PrismaClient).snapshot.updateMany({
|
||||
where: { workspaceId: workspace.id },
|
||||
data: {
|
||||
createdAt: new Date(snapshot1.timestamp),
|
||||
updatedAt: new Date(snapshot1.timestamp),
|
||||
},
|
||||
});
|
||||
const expected = [docId1, docId2, docId3].sort();
|
||||
for (const load of [
|
||||
t.context.doc.paginateDocInfo.bind(t.context.doc),
|
||||
t.context.doc.paginateDocInfoByUpdatedAt.bind(t.context.doc),
|
||||
]) {
|
||||
const seen: string[] = [];
|
||||
let after: string | undefined;
|
||||
for (const expectedId of expected) {
|
||||
const [total, page] = await load(workspace.id, {
|
||||
first: 1,
|
||||
offset: 0,
|
||||
after,
|
||||
});
|
||||
t.is(total, 3);
|
||||
t.is(page.length, 1);
|
||||
t.is(page[0].docId, expectedId);
|
||||
seen.push(page[0].docId);
|
||||
after = page[0].cursor;
|
||||
}
|
||||
t.deepEqual(seen, expected);
|
||||
t.is(
|
||||
(await load(workspace.id, { first: 1, offset: 0, after }))[1].length,
|
||||
0
|
||||
);
|
||||
}
|
||||
});
|
||||
// #endregion
|
||||
@@ -5,10 +5,18 @@ import { PrismaClient } from '@prisma/client';
|
||||
import test, { type ExecutionContext } from 'ava';
|
||||
import Sinon from 'sinon';
|
||||
import { io, type Socket as SocketIOClient } from 'socket.io-client';
|
||||
import { applyUpdate, Doc, encodeStateAsUpdate, encodeStateVector } from 'yjs';
|
||||
import {
|
||||
applyUpdate,
|
||||
Array as YArray,
|
||||
Doc,
|
||||
encodeStateAsUpdate,
|
||||
encodeStateVector,
|
||||
Map as YMap,
|
||||
} from 'yjs';
|
||||
|
||||
import { CANARY_CLIENT_VERSION_MAX_AGE_DAYS, EventBus } from '../../base';
|
||||
import { BackendRuntimeProvider } from '../../core/backend-runtime';
|
||||
import { DocReader } from '../../core/doc';
|
||||
import { PermissionService } from '../../core/permission';
|
||||
import {
|
||||
DocRole,
|
||||
@@ -233,8 +241,8 @@ async function createSnapshot(
|
||||
data: {
|
||||
id: input.docId,
|
||||
workspaceId: input.workspaceId,
|
||||
blob: input.blob ?? Buffer.from([1, 1]),
|
||||
state: input.state ?? Buffer.from([1, 1]),
|
||||
blob: input.blob ?? Buffer.from([0, 0]),
|
||||
state: input.state ?? Buffer.from([0]),
|
||||
createdAt: input.updatedAt ?? new Date(),
|
||||
updatedAt: input.updatedAt ?? new Date(),
|
||||
createdBy: input.userId,
|
||||
@@ -291,6 +299,7 @@ test.before(async () => {
|
||||
|
||||
test.beforeEach(async () => {
|
||||
await app.initTestingDB();
|
||||
await app.get(BackendRuntimeProvider).activateWorkspaceLifecycleV1();
|
||||
});
|
||||
|
||||
test.after.always(async () => {
|
||||
@@ -356,6 +365,7 @@ test('push requires an authorized document subscription', async t => {
|
||||
|
||||
const batch = {
|
||||
spaces: [{ spaceType: 'userspace', spaceId }],
|
||||
protocolVersion: 2,
|
||||
clientVersion: '0.27.5',
|
||||
};
|
||||
for (const socket of [sender, receiver]) {
|
||||
@@ -369,6 +379,7 @@ test('push requires an authorized document subscription', async t => {
|
||||
spaceType: 'userspace',
|
||||
spaceId,
|
||||
docId: 'doc-2',
|
||||
intent: 'update',
|
||||
update,
|
||||
})
|
||||
);
|
||||
@@ -407,6 +418,7 @@ test('canary date clientVersion should use sync-027 in canary namespace', async
|
||||
{ spaceType: 'userspace', spaceId },
|
||||
{ spaceType: 'userspace', spaceId, docId: 'doc-canary' },
|
||||
],
|
||||
protocolVersion: 2,
|
||||
clientVersion: canaryVersion,
|
||||
}
|
||||
)
|
||||
@@ -423,6 +435,7 @@ test('canary date clientVersion should use sync-027 in canary namespace', async
|
||||
{ spaceType: 'userspace', spaceId },
|
||||
{ spaceType: 'userspace', spaceId, docId: 'doc-canary' },
|
||||
],
|
||||
protocolVersion: 2,
|
||||
clientVersion: canaryVersion,
|
||||
}
|
||||
)
|
||||
@@ -443,6 +456,7 @@ test('canary date clientVersion should use sync-027 in canary namespace', async
|
||||
spaceType: 'userspace',
|
||||
spaceId,
|
||||
docId: 'doc-canary',
|
||||
intent: 'update',
|
||||
update,
|
||||
}
|
||||
);
|
||||
@@ -488,6 +502,7 @@ test('old canary date clientVersion should be rejected and disconnected in canar
|
||||
'space:join-batch',
|
||||
{
|
||||
spaces: [{ spaceType: 'userspace', spaceId }],
|
||||
protocolVersion: 2,
|
||||
clientVersion: makeCanaryDateVersion(old, '015'),
|
||||
}
|
||||
)
|
||||
@@ -524,6 +539,7 @@ test('canary date clientVersion should be rejected outside canary namespace', as
|
||||
'space:join-batch',
|
||||
{
|
||||
spaces: [{ spaceType: 'userspace', spaceId }],
|
||||
protocolVersion: 2,
|
||||
clientVersion: makeCanaryDateVersion(new Date(), '15'),
|
||||
}
|
||||
)
|
||||
@@ -564,6 +580,7 @@ test('space:join-batch should validate entries before joining', async t => {
|
||||
{ spaceType: 'userspace', spaceId },
|
||||
{ spaceType: 'userspace', spaceId: `${spaceId}-other` },
|
||||
],
|
||||
protocolVersion: 2,
|
||||
clientVersion: '0.27.5',
|
||||
},
|
||||
},
|
||||
@@ -574,6 +591,7 @@ test('space:join-batch should validate entries before joining', async t => {
|
||||
{ spaceType: 'userspace', spaceId, docId: 'doc-1' },
|
||||
{ spaceType: 'userspace', spaceId, docId: 'doc-1' },
|
||||
],
|
||||
protocolVersion: 2,
|
||||
clientVersion: '0.27.5',
|
||||
},
|
||||
},
|
||||
@@ -581,6 +599,7 @@ test('space:join-batch should validate entries before joining', async t => {
|
||||
label: 'invalid entry',
|
||||
payload: {
|
||||
spaces: [{ spaceType: 'invalid', spaceId }],
|
||||
protocolVersion: 2,
|
||||
clientVersion: '0.27.5',
|
||||
},
|
||||
},
|
||||
@@ -592,6 +611,7 @@ test('space:join-batch should validate entries before joining', async t => {
|
||||
spaceId,
|
||||
docId: `doc-${index}`,
|
||||
})),
|
||||
protocolVersion: 2,
|
||||
clientVersion: '0.27.5',
|
||||
},
|
||||
},
|
||||
@@ -632,6 +652,7 @@ test('space:join-batch rejects old clients and accepts the current web build', a
|
||||
'space:join-batch',
|
||||
{
|
||||
spaces: [{ spaceType: 'userspace', spaceId: user.id }],
|
||||
protocolVersion: 2,
|
||||
clientVersion,
|
||||
}
|
||||
)
|
||||
@@ -672,9 +693,39 @@ test('space:join-batch joins rooms and initializes workspace documents', async t
|
||||
docId: `db$${workspace.id}$docProperties`,
|
||||
},
|
||||
],
|
||||
protocolVersion: 2,
|
||||
clientVersion: '0.27.5',
|
||||
};
|
||||
|
||||
const db = app.get(PrismaClient);
|
||||
const runtime = app.get(BackendRuntimeProvider);
|
||||
await db.$executeRaw`DELETE FROM storage_reconciliation_checkpoints WHERE kind='workspace_doc_lifecycle_activation' AND scope='global'`;
|
||||
const inactive = getErrorResponse(
|
||||
t,
|
||||
await emitWithAck(ownerSocket, 'space:join-batch', batch)
|
||||
);
|
||||
t.is(inactive.name, 'WORKSPACE_SYNC_UNAVAILABLE');
|
||||
t.is(inactive.status, 503);
|
||||
const [checkpoint] = await db.$queryRaw<
|
||||
{ count: bigint }[]
|
||||
>`SELECT count(*) AS count FROM storage_reconciliation_checkpoints WHERE kind IN ('workspace_doc_lifecycle_activation','workspace_doc_lifecycle') AND (scope='global' OR scope=${workspace.id})`;
|
||||
t.is(Number(checkpoint.count), 0);
|
||||
t.is(await db.update.count({ where: { workspaceId: workspace.id } }), 0);
|
||||
t.is(
|
||||
await db.workspaceDoc.count({ where: { workspaceId: workspace.id } }),
|
||||
0
|
||||
);
|
||||
const legacy = getErrorResponse(
|
||||
t,
|
||||
await emitWithAck(ownerSocket, 'space:join-batch', {
|
||||
...batch,
|
||||
protocolVersion: 1,
|
||||
})
|
||||
);
|
||||
t.is(legacy.name, 'BAD_REQUEST');
|
||||
t.true(await runtime.activateWorkspaceLifecycleV1());
|
||||
t.false(await runtime.activateWorkspaceLifecycleV1());
|
||||
|
||||
for (const socket of [ownerSocket, receiverSocket]) {
|
||||
const result = unwrapResponse(
|
||||
t,
|
||||
@@ -700,6 +751,7 @@ test('space:join-batch joins rooms and initializes workspace documents', async t
|
||||
docId: 'doc-c',
|
||||
},
|
||||
],
|
||||
protocolVersion: 2,
|
||||
clientVersion: '0.27.5',
|
||||
}
|
||||
)
|
||||
@@ -792,6 +844,7 @@ test('space:join-batch joins rooms and initializes workspace documents', async t
|
||||
docId: workspace.id,
|
||||
},
|
||||
],
|
||||
protocolVersion: 2,
|
||||
clientVersion: '0.27.5',
|
||||
})
|
||||
);
|
||||
@@ -802,6 +855,7 @@ test('space:join-batch joins rooms and initializes workspace documents', async t
|
||||
spaceType: 'workspace',
|
||||
spaceId: workspace.id,
|
||||
docId: workspace.id,
|
||||
intent: 'update',
|
||||
update: Buffer.from(root).toString('base64'),
|
||||
})
|
||||
);
|
||||
@@ -825,6 +879,7 @@ test('space:join-batch joins rooms and initializes workspace documents', async t
|
||||
spaceType: 'workspace',
|
||||
spaceId: workspace.id,
|
||||
docId,
|
||||
intent: docId === 'doc-a' ? 'create' : 'update',
|
||||
update: createYjsUpdateBase64(),
|
||||
})
|
||||
);
|
||||
@@ -873,6 +928,7 @@ test('batch doc entries require Doc.Read atomically', async t => {
|
||||
docId: `space:${docId}`,
|
||||
},
|
||||
],
|
||||
protocolVersion: 2,
|
||||
clientVersion: '0.27.5',
|
||||
})
|
||||
);
|
||||
@@ -910,6 +966,7 @@ test('batch sync routes active updates and only broadcasts invalidation to contr
|
||||
{ spaceType: 'userspace', spaceId },
|
||||
{ spaceType: 'userspace', spaceId, docId: 'some-doc' },
|
||||
],
|
||||
protocolVersion: 2,
|
||||
clientVersion: '0.27.5',
|
||||
};
|
||||
for (const socket of [sender, receiver]) {
|
||||
@@ -930,6 +987,7 @@ test('batch sync routes active updates and only broadcasts invalidation to contr
|
||||
'space:join-batch',
|
||||
{
|
||||
spaces: [{ spaceType: 'userspace', spaceId }],
|
||||
protocolVersion: 2,
|
||||
clientVersion: '0.27.5',
|
||||
}
|
||||
)
|
||||
@@ -958,6 +1016,7 @@ test('batch sync routes active updates and only broadcasts invalidation to contr
|
||||
spaceType: 'userspace',
|
||||
spaceId,
|
||||
docId: 'some-doc',
|
||||
intent: 'update',
|
||||
update: createYjsUpdateBase64(),
|
||||
})
|
||||
);
|
||||
@@ -999,6 +1058,7 @@ test('batch sync routes active updates and only broadcasts invalidation to contr
|
||||
spaceType: 'userspace',
|
||||
spaceId,
|
||||
docId: 'some-doc',
|
||||
intent: 'update',
|
||||
update: createYjsUpdateBase64(),
|
||||
})
|
||||
);
|
||||
@@ -1010,6 +1070,197 @@ test('batch sync routes active updates and only broadcasts invalidation to contr
|
||||
}
|
||||
});
|
||||
|
||||
test('partial roots accept edits and ordinary creation uses persisted identity', async t => {
|
||||
const { user, cookieHeader } = await login(app);
|
||||
const workspace = await app.get(Models).workspace.create(user.id);
|
||||
const db = app.get(PrismaClient);
|
||||
const root = new Doc();
|
||||
const pages = new YArray<{ id: string }>();
|
||||
root.getMap('meta').set('pages', pages);
|
||||
const vector = encodeStateVector(root);
|
||||
pages.push([{ id: 'missing-prefix-doc' }]);
|
||||
await createSnapshot(db, {
|
||||
workspaceId: workspace.id,
|
||||
docId: workspace.id,
|
||||
userId: user.id,
|
||||
blob: Buffer.from(encodeStateAsUpdate(root, vector)),
|
||||
});
|
||||
const legacyCases: {
|
||||
workspaceId: string;
|
||||
docId: string;
|
||||
duplicateId: string;
|
||||
}[] = [];
|
||||
for (let shape = 0; shape < 4; shape++) {
|
||||
const legacyWorkspace = await app.get(Models).workspace.create(user.id);
|
||||
const legacyRoot = new Doc();
|
||||
const docId = `legacy-shape-${shape}`;
|
||||
const duplicateId = `duplicate-${shape}`;
|
||||
const entry = (id: string, shared: boolean) =>
|
||||
shared
|
||||
? new YMap<unknown>([
|
||||
['id', id],
|
||||
['trash', true],
|
||||
])
|
||||
: { id, trash: true };
|
||||
if (shape === 0)
|
||||
legacyRoot
|
||||
.getMap('meta')
|
||||
.set('pages', [
|
||||
entry(docId, false),
|
||||
entry(duplicateId, false),
|
||||
entry(duplicateId, false),
|
||||
]);
|
||||
else {
|
||||
const legacyPages = new YArray();
|
||||
legacyRoot.getMap('meta').set('pages', legacyPages);
|
||||
legacyPages.push([
|
||||
entry(docId, shape >= 2),
|
||||
entry(duplicateId, shape >= 2),
|
||||
entry(duplicateId, shape === 2),
|
||||
]);
|
||||
}
|
||||
await createSnapshot(db, {
|
||||
workspaceId: legacyWorkspace.id,
|
||||
docId: legacyWorkspace.id,
|
||||
userId: user.id,
|
||||
blob: Buffer.from(encodeStateAsUpdate(legacyRoot)),
|
||||
});
|
||||
legacyCases.push({ workspaceId: legacyWorkspace.id, docId, duplicateId });
|
||||
legacyRoot.destroy();
|
||||
}
|
||||
const socket = createClient(url, cookieHeader);
|
||||
try {
|
||||
await waitForConnect(socket);
|
||||
const joined = unwrapResponse(
|
||||
t,
|
||||
await emitWithAck<{ protocolVersion: number }>(
|
||||
socket,
|
||||
'space:join-batch',
|
||||
{
|
||||
spaces: [
|
||||
{ spaceType: 'workspace', spaceId: workspace.id },
|
||||
{
|
||||
spaceType: 'workspace',
|
||||
spaceId: workspace.id,
|
||||
docId: workspace.id,
|
||||
},
|
||||
],
|
||||
clientVersion: '0.27.5',
|
||||
protocolVersion: 2,
|
||||
}
|
||||
)
|
||||
);
|
||||
t.is(joined.protocolVersion, 2);
|
||||
const independent = new Doc();
|
||||
independent.getMap('meta').set('name', 'saved while partial');
|
||||
unwrapResponse(
|
||||
t,
|
||||
await emitWithAck(socket, 'space:push-doc-update', {
|
||||
spaceType: 'workspace',
|
||||
spaceId: workspace.id,
|
||||
docId: workspace.id,
|
||||
intent: 'update',
|
||||
update: Buffer.from(encodeStateAsUpdate(independent)).toString(
|
||||
'base64'
|
||||
),
|
||||
})
|
||||
);
|
||||
const loaded = unwrapResponse(
|
||||
t,
|
||||
await emitWithAck<{ missing: string }>(socket, 'space:load-doc', {
|
||||
spaceType: 'workspace',
|
||||
spaceId: workspace.id,
|
||||
docId: workspace.id,
|
||||
})
|
||||
);
|
||||
const projected = new Doc();
|
||||
applyUpdate(projected, Buffer.from(loaded.missing, 'base64'));
|
||||
t.is(projected.getMap('meta').get('name'), 'saved while partial');
|
||||
|
||||
const docId = 'new-without-root-entry';
|
||||
const push = {
|
||||
spaceType: 'workspace',
|
||||
spaceId: workspace.id,
|
||||
docId,
|
||||
intent: 'create',
|
||||
update: Buffer.from([0, 0]).toString('base64'),
|
||||
};
|
||||
const created = unwrapResponse(
|
||||
t,
|
||||
await emitWithAck<{ created: boolean }>(
|
||||
socket,
|
||||
'space:push-doc-update',
|
||||
push
|
||||
)
|
||||
);
|
||||
t.true(created.created);
|
||||
const retried = unwrapResponse(
|
||||
t,
|
||||
await emitWithAck<{ created: boolean }>(
|
||||
socket,
|
||||
'space:push-doc-update',
|
||||
push
|
||||
)
|
||||
);
|
||||
t.false(retried.created);
|
||||
const state = unwrapResponse(
|
||||
t,
|
||||
await emitWithAck<{
|
||||
docs: { docId: string }[];
|
||||
clocks: Record<string, number>;
|
||||
}>(socket, 'space:load-workspace-state', {
|
||||
spaceType: 'workspace',
|
||||
spaceId: workspace.id,
|
||||
})
|
||||
);
|
||||
t.true(state.docs.some(doc => doc.docId === docId));
|
||||
t.true(workspace.id in state.clocks);
|
||||
const deleted = unwrapResponse(
|
||||
t,
|
||||
await emitWithAck<{ timestamp: number; rootUpdate?: string }>(
|
||||
socket,
|
||||
'space:doc-lifecycle',
|
||||
{
|
||||
spaceType: 'workspace',
|
||||
spaceId: workspace.id,
|
||||
docId,
|
||||
lifecycle: 'delete',
|
||||
}
|
||||
)
|
||||
);
|
||||
t.true(deleted.timestamp > 0);
|
||||
t.is(deleted.rootUpdate, undefined);
|
||||
const rejected = getErrorResponse(
|
||||
t,
|
||||
await emitWithAck(socket, 'space:push-doc-update', push)
|
||||
);
|
||||
t.is(rejected.name, 'NOT_FOUND');
|
||||
for (const legacy of legacyCases) {
|
||||
await app
|
||||
.get(BackendRuntimeProvider)
|
||||
.ensureWorkspaceLifecycleV1(legacy.workspaceId);
|
||||
const state = await app
|
||||
.get(BackendRuntimeProvider)
|
||||
.getWorkspaceStateV1(legacy.workspaceId, user.id);
|
||||
t.true(
|
||||
state.docs.some(
|
||||
doc => doc.docId === legacy.docId && doc.lifecycle === 'trashed'
|
||||
)
|
||||
);
|
||||
t.false(state.docs.some(doc => doc.docId === legacy.duplicateId));
|
||||
t.is(
|
||||
await db.docGrant.count({
|
||||
where: { workspaceId: legacy.workspaceId, docId: legacy.docId },
|
||||
}),
|
||||
0
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
socket.disconnect();
|
||||
root.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
test('permission revocation removes an active document subscription', async t => {
|
||||
const db = app.get(PrismaClient);
|
||||
const models = app.get(Models);
|
||||
@@ -1053,6 +1304,7 @@ test('permission revocation removes an active document subscription', async t =>
|
||||
{ spaceType: 'workspace', spaceId: workspace.id },
|
||||
{ spaceType: 'workspace', spaceId: workspace.id, docId },
|
||||
],
|
||||
protocolVersion: 2,
|
||||
clientVersion: '0.27.5',
|
||||
};
|
||||
const ownerJoin = unwrapResponse(
|
||||
@@ -1227,6 +1479,7 @@ test('permission revocation removes an active document subscription', async t =>
|
||||
spaceType: 'workspace',
|
||||
spaceId: workspace.id,
|
||||
docId,
|
||||
intent: 'update',
|
||||
update: createYjsUpdateBase64(),
|
||||
})
|
||||
);
|
||||
@@ -1245,6 +1498,7 @@ test('permission revocation removes an active document subscription', async t =>
|
||||
{ spaceType: 'workspace', spaceId: workspace.id },
|
||||
{ spaceType: 'workspace', spaceId: workspace.id, docId },
|
||||
],
|
||||
protocolVersion: 2,
|
||||
clientVersion: '0.27.5',
|
||||
})
|
||||
);
|
||||
@@ -1259,6 +1513,7 @@ test('permission revocation removes an active document subscription', async t =>
|
||||
spaceType: 'workspace',
|
||||
spaceId: workspace.id,
|
||||
docId,
|
||||
intent: 'update',
|
||||
update: createYjsUpdateBase64(),
|
||||
})
|
||||
);
|
||||
@@ -1310,6 +1565,7 @@ test('awareness requires Doc.Read but not Doc.Update', async t => {
|
||||
{ spaceType: 'workspace', spaceId: workspace.id },
|
||||
{ spaceType: 'workspace', spaceId: workspace.id, docId },
|
||||
],
|
||||
protocolVersion: 2,
|
||||
clientVersion: '0.27.5',
|
||||
}
|
||||
)
|
||||
@@ -1340,6 +1596,7 @@ test('awareness requires Doc.Read but not Doc.Update', async t => {
|
||||
spaceType: 'workspace',
|
||||
spaceId: workspace.id,
|
||||
docId,
|
||||
intent: 'update',
|
||||
update: createYjsUpdateBase64(),
|
||||
})
|
||||
);
|
||||
@@ -1412,6 +1669,7 @@ test('workspace sync delete-doc should enforce doc permissions', async t => {
|
||||
'space:join-batch',
|
||||
{
|
||||
spaces: [{ spaceType: 'workspace', spaceId: workspace.id }],
|
||||
protocolVersion: 2,
|
||||
clientVersion: '0.27.5',
|
||||
}
|
||||
)
|
||||
@@ -1436,7 +1694,7 @@ test('workspace sync delete-doc should enforce doc permissions', async t => {
|
||||
docId: `userdata$${owner.id}$${workspace.id}$docIntegrationRef`,
|
||||
})
|
||||
);
|
||||
t.is(userdataError.name, 'SPACE_ACCESS_DENIED');
|
||||
t.is(userdataError.name, 'DOC_ACTION_DENIED');
|
||||
|
||||
const ownerJoin = unwrapResponse(
|
||||
t,
|
||||
@@ -1452,6 +1710,7 @@ test('workspace sync delete-doc should enforce doc permissions', async t => {
|
||||
docId: workspace.id,
|
||||
},
|
||||
],
|
||||
protocolVersion: 2,
|
||||
clientVersion: '0.27.5',
|
||||
}
|
||||
)
|
||||
@@ -1465,19 +1724,27 @@ test('workspace sync delete-doc should enforce doc permissions', async t => {
|
||||
get(index: number): { set(key: string, value: unknown): void };
|
||||
};
|
||||
pages.get(0).set('trash', true);
|
||||
const bypassError = getErrorResponse(
|
||||
const rootReceipt = unwrapResponse(
|
||||
t,
|
||||
await emitWithAck(ownerSocket, 'space:push-doc-update', {
|
||||
spaceType: 'workspace',
|
||||
spaceId: workspace.id,
|
||||
docId: workspace.id,
|
||||
intent: 'update',
|
||||
update: Buffer.from(encodeStateAsUpdate(staleRoot, state)).toString(
|
||||
'base64'
|
||||
),
|
||||
})
|
||||
);
|
||||
t.is(bypassError.name, 'DOC_ACTION_DENIED');
|
||||
t.true(bypassError.message.includes('Doc.Update'));
|
||||
t.truthy(rootReceipt);
|
||||
t.is(
|
||||
(
|
||||
await db.workspaceDoc.findUnique({
|
||||
where: { workspaceId_docId: { workspaceId: workspace.id, docId } },
|
||||
})
|
||||
)?.lifecycleState ?? null,
|
||||
null
|
||||
);
|
||||
|
||||
unwrapResponse(
|
||||
t,
|
||||
@@ -1540,6 +1807,7 @@ test('workspace sync load-doc requires an active document subscription', async t
|
||||
'space:join-batch',
|
||||
{
|
||||
spaces: [{ spaceType: 'workspace', spaceId: workspace.id }],
|
||||
protocolVersion: 2,
|
||||
clientVersion: '0.27.5',
|
||||
}
|
||||
)
|
||||
@@ -1564,7 +1832,64 @@ test('workspace sync load-doc requires an active document subscription', async t
|
||||
docId: `userdata$${owner.id}$${workspace.id}$favorite`,
|
||||
})
|
||||
);
|
||||
t.is(userdataError.name, 'SPACE_ACCESS_DENIED');
|
||||
t.is(userdataError.name, 'NOT_IN_SPACE');
|
||||
const joinDoc = () =>
|
||||
emitWithAck(socket, 'space:join-batch', {
|
||||
spaces: [{ spaceType: 'workspace', spaceId: workspace.id, docId }],
|
||||
protocolVersion: 2,
|
||||
clientVersion: '0.27.5',
|
||||
});
|
||||
for (const renewed of [false, true]) {
|
||||
await models.docUser.set(
|
||||
workspace.id,
|
||||
docId,
|
||||
collaborator.id,
|
||||
DocRole.Reader
|
||||
);
|
||||
unwrapResponse(t, await joinDoc());
|
||||
const reader = app.get(DocReader);
|
||||
const load = reader.getDocDiff.bind(reader);
|
||||
const race = Sinon.stub(reader, 'getDocDiff').callsFake(
|
||||
async (...args) => {
|
||||
const result = await load(...args);
|
||||
const where = {
|
||||
workspaceId: workspace.id,
|
||||
docId,
|
||||
principalType: 'user',
|
||||
principalId: collaborator.id,
|
||||
};
|
||||
if (renewed) {
|
||||
await db.docGrant.updateMany({ where, data: { role: 'editor' } });
|
||||
unwrapResponse(t, await joinDoc());
|
||||
} else {
|
||||
await db.docGrant.deleteMany({ where });
|
||||
}
|
||||
return result;
|
||||
}
|
||||
);
|
||||
try {
|
||||
const raced = getErrorResponse(
|
||||
t,
|
||||
await emitWithAck(socket, 'space:load-doc', {
|
||||
spaceType: 'workspace',
|
||||
spaceId: workspace.id,
|
||||
docId,
|
||||
})
|
||||
);
|
||||
t.is(raced.name, 'NOT_IN_SPACE');
|
||||
} finally {
|
||||
race.restore();
|
||||
}
|
||||
if (renewed)
|
||||
unwrapResponse(
|
||||
t,
|
||||
await emitWithAck(socket, 'space:load-doc', {
|
||||
spaceType: 'workspace',
|
||||
spaceId: workspace.id,
|
||||
docId,
|
||||
})
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
socket.disconnect();
|
||||
}
|
||||
@@ -1614,6 +1939,7 @@ test('workspace sync push-doc-update should enforce doc update permissions', asy
|
||||
{ spaceType: 'workspace', spaceId: workspace.id },
|
||||
{ spaceType: 'workspace', spaceId: workspace.id, docId },
|
||||
],
|
||||
protocolVersion: 2,
|
||||
clientVersion: '0.27.5',
|
||||
}
|
||||
)
|
||||
@@ -1626,6 +1952,7 @@ test('workspace sync push-doc-update should enforce doc update permissions', asy
|
||||
spaceType: 'workspace',
|
||||
spaceId: workspace.id,
|
||||
docId,
|
||||
intent: 'update',
|
||||
update: createYjsUpdateBase64(),
|
||||
})
|
||||
);
|
||||
@@ -1637,10 +1964,11 @@ test('workspace sync push-doc-update should enforce doc update permissions', asy
|
||||
spaceType: 'workspace',
|
||||
spaceId: workspace.id,
|
||||
docId: `userdata$${owner.id}$${workspace.id}$settings`,
|
||||
intent: 'update',
|
||||
update: createYjsUpdateBase64(),
|
||||
})
|
||||
);
|
||||
t.is(userdataError.name, 'SPACE_ACCESS_DENIED');
|
||||
t.is(userdataError.name, 'NOT_IN_SPACE');
|
||||
|
||||
const malformedDatabaseError = getErrorResponse(
|
||||
t,
|
||||
@@ -1648,10 +1976,11 @@ test('workspace sync push-doc-update should enforce doc update permissions', asy
|
||||
spaceType: 'workspace',
|
||||
spaceId: workspace.id,
|
||||
docId: 'db$docProperties',
|
||||
intent: 'update',
|
||||
update: createYjsUpdateBase64(),
|
||||
})
|
||||
);
|
||||
t.is(malformedDatabaseError.name, 'SPACE_ACCESS_DENIED');
|
||||
t.is(malformedDatabaseError.name, 'NOT_IN_SPACE');
|
||||
|
||||
const updates = await db.update.count({
|
||||
where: {
|
||||
@@ -1715,6 +2044,7 @@ test('workspace sync load-doc-timestamps should filter unreadable docs', async t
|
||||
'space:join-batch',
|
||||
{
|
||||
spaces: [{ spaceType: 'workspace', spaceId: workspace.id }],
|
||||
protocolVersion: 2,
|
||||
clientVersion: '0.27.5',
|
||||
}
|
||||
)
|
||||
@@ -1735,6 +2065,19 @@ test('workspace sync load-doc-timestamps should filter unreadable docs', async t
|
||||
|
||||
t.false(privateDocId in timestamps);
|
||||
t.true(readableDocId in timestamps);
|
||||
await models.doc.publish(workspace.id, readableDocId);
|
||||
await db.workspaceMember.updateMany({
|
||||
where: { workspaceId: workspace.id, userId: collaborator.id },
|
||||
data: { state: 'suspended' },
|
||||
});
|
||||
const denied = getErrorResponse(
|
||||
t,
|
||||
await emitWithAck(socket, 'space:load-doc-timestamps', {
|
||||
spaceType: 'workspace',
|
||||
spaceId: workspace.id,
|
||||
})
|
||||
);
|
||||
t.is(denied.name, 'SPACE_ACCESS_DENIED');
|
||||
} finally {
|
||||
socket.disconnect();
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ import { WorkspacesController } from '../../core/workspaces/controller';
|
||||
import { Models, PublicDocMode } from '../../models';
|
||||
import {
|
||||
addDocToRootDoc,
|
||||
mergeUpdatesInApplyWay,
|
||||
mergeUpdates,
|
||||
readAllDocIdsFromRootDoc,
|
||||
} from '../../native';
|
||||
import { createTestingApp, TestingApp, TestUser } from '../utils';
|
||||
@@ -359,7 +359,7 @@ test('should expose filtered public root doc for shared page', async t => {
|
||||
|
||||
let root = addDocToRootDoc(Buffer.from([0, 0]), 'public', 'Public Doc');
|
||||
const privateUpdate = addDocToRootDoc(root, 'private-page', 'Private Doc');
|
||||
root = mergeUpdatesInApplyWay([root, privateUpdate]);
|
||||
root = mergeUpdates([root, privateUpdate]);
|
||||
|
||||
doc.getDoc.resolves({
|
||||
spaceId: 'private',
|
||||
|
||||
@@ -545,6 +545,22 @@ export const USER_FRIENDLY_ERRORS = {
|
||||
message: ({ docId, action }) =>
|
||||
`You do not have permission to perform ${action} action on doc ${docId}.`,
|
||||
},
|
||||
doc_update_invalid: {
|
||||
type: 'invalid_input',
|
||||
message: 'The document update is invalid.',
|
||||
},
|
||||
doc_update_too_large: {
|
||||
type: 'invalid_input',
|
||||
message: 'The document update exceeds the size limit.',
|
||||
},
|
||||
workspace_sync_unavailable: {
|
||||
type: 'service_unavailable',
|
||||
message: 'Workspace synchronization is temporarily unavailable.',
|
||||
},
|
||||
doc_validation_unavailable: {
|
||||
type: 'service_unavailable',
|
||||
message: 'Document validation is temporarily unavailable.',
|
||||
},
|
||||
doc_update_blocked: {
|
||||
type: 'action_forbidden',
|
||||
args: { spaceId: 'string', docId: 'string' },
|
||||
|
||||
@@ -458,6 +458,30 @@ export class DocActionDenied extends UserFriendlyError {
|
||||
super('no_permission', 'doc_action_denied', message, args);
|
||||
}
|
||||
}
|
||||
|
||||
export class DocUpdateInvalid extends UserFriendlyError {
|
||||
constructor(message?: string) {
|
||||
super('invalid_input', 'doc_update_invalid', message);
|
||||
}
|
||||
}
|
||||
|
||||
export class DocUpdateTooLarge extends UserFriendlyError {
|
||||
constructor(message?: string) {
|
||||
super('invalid_input', 'doc_update_too_large', message);
|
||||
}
|
||||
}
|
||||
|
||||
export class WorkspaceSyncUnavailable extends UserFriendlyError {
|
||||
constructor(message?: string) {
|
||||
super('service_unavailable', 'workspace_sync_unavailable', message);
|
||||
}
|
||||
}
|
||||
|
||||
export class DocValidationUnavailable extends UserFriendlyError {
|
||||
constructor(message?: string) {
|
||||
super('service_unavailable', 'doc_validation_unavailable', message);
|
||||
}
|
||||
}
|
||||
@ObjectType()
|
||||
class DocUpdateBlockedDataType {
|
||||
@Field() spaceId!: string
|
||||
@@ -1293,6 +1317,10 @@ export enum ErrorNames {
|
||||
CAN_NOT_REVOKE_YOURSELF,
|
||||
DOC_NOT_FOUND,
|
||||
DOC_ACTION_DENIED,
|
||||
DOC_UPDATE_INVALID,
|
||||
DOC_UPDATE_TOO_LARGE,
|
||||
WORKSPACE_SYNC_UNAVAILABLE,
|
||||
DOC_VALIDATION_UNAVAILABLE,
|
||||
DOC_UPDATE_BLOCKED,
|
||||
VERSION_REJECTED,
|
||||
INVALID_HISTORY_TIMESTAMP,
|
||||
|
||||
@@ -9,6 +9,7 @@ import { CliAppModule } from './data/app';
|
||||
import { CreateCommand } from './data/commands/create';
|
||||
import { CutoverCommand } from './data/commands/cutover';
|
||||
import { ImportConfigCommand } from './data/commands/import';
|
||||
import { RootSourceCommand } from './data/commands/root-source';
|
||||
import { RevertCommand, RunCommand } from './data/commands/run';
|
||||
|
||||
function getProgramName() {
|
||||
@@ -68,6 +69,24 @@ function buildProgram(logger: Logger) {
|
||||
});
|
||||
});
|
||||
|
||||
program
|
||||
.command('activate-workspace-lifecycle')
|
||||
.description(
|
||||
'Activate workspace lifecycle synchronization after all old writers and in-flight transactions have drained'
|
||||
)
|
||||
.action(async () => {
|
||||
await withCliApp(logger, async app => {
|
||||
const activated = await app
|
||||
.get(BackendRuntimeProvider)
|
||||
.activateWorkspaceLifecycleV1();
|
||||
logger.log(
|
||||
activated
|
||||
? 'Workspace lifecycle synchronization activated.'
|
||||
: 'Workspace lifecycle synchronization is already active.'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
program
|
||||
.command('validate-cutover')
|
||||
.description('Validate canonical authority data before server startup')
|
||||
@@ -112,6 +131,19 @@ function buildProgram(logger: Logger) {
|
||||
});
|
||||
});
|
||||
|
||||
const rootSource = program
|
||||
.command('root-source')
|
||||
.description('Export original workspace root material');
|
||||
rootSource
|
||||
.command('inspect')
|
||||
.requiredOption('--workspace <id>')
|
||||
.requiredOption('--output <file>')
|
||||
.action(async options => {
|
||||
await withCliApp(logger, app =>
|
||||
app.get(RootSourceCommand).inspect(options.workspace, options.output)
|
||||
);
|
||||
});
|
||||
|
||||
return program;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { Models } from '../../models';
|
||||
import { BackendRuntimeProvider } from '../backend-runtime';
|
||||
import { EntitlementService } from '../entitlement';
|
||||
|
||||
export async function createDevUsers(
|
||||
models: Models,
|
||||
entitlement: EntitlementService
|
||||
entitlement: EntitlementService,
|
||||
runtime: BackendRuntimeProvider
|
||||
) {
|
||||
const devUsers: {
|
||||
email: string;
|
||||
@@ -71,12 +73,12 @@ export async function createDevUsers(
|
||||
).some(Boolean);
|
||||
if (!hasTeamWorkspace) {
|
||||
const workspace = await models.workspace.create(devUser.id);
|
||||
await models.doc.upsert({
|
||||
spaceId: workspace.id,
|
||||
await runtime.appendWorkspaceDocUpdatesV1({
|
||||
workspaceId: workspace.id,
|
||||
docId: workspace.id,
|
||||
blob: devWorkspaceBlob,
|
||||
timestamp: Date.now(),
|
||||
editorId: devUser.id,
|
||||
updates: [devWorkspaceBlob],
|
||||
actorUserId: devUser.id,
|
||||
writeIntent: 'update_doc',
|
||||
});
|
||||
await entitlement.upsertAdminGrant({
|
||||
targetType: 'workspace',
|
||||
|
||||
@@ -76,7 +76,7 @@ export class AuthService implements OnApplicationBootstrap {
|
||||
|
||||
async onApplicationBootstrap() {
|
||||
if (env.dev) {
|
||||
await createDevUsers(this.models, this.entitlement);
|
||||
await createDevUsers(this.models, this.entitlement, this.rt);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -144,12 +144,11 @@ 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');
|
||||
t.is(t.context.getSnapshot.callCount, 2);
|
||||
t.is(t.context.getSnapshot.callCount, 1);
|
||||
t.is(t.context.runtime.syncEmbeddingState.callCount, 1);
|
||||
t.like(t.context.runtime.syncEmbeddingState.firstCall.args[0], {
|
||||
workspaceId: 'workspace-1',
|
||||
enabled: true,
|
||||
reconcileDocuments: false,
|
||||
});
|
||||
t.is(
|
||||
t.context.runtime.syncEmbeddingState.firstCall.args[0].documents[0].docId,
|
||||
@@ -160,26 +159,18 @@ test('backend-runtime jobs ingest documents and clean runtime state', async t =>
|
||||
.length > 0
|
||||
);
|
||||
|
||||
await t.context.embeddingService.reconcileDocuments('workspace-1');
|
||||
t.like(t.context.runtime.syncEmbeddingState.secondCall.args[0], {
|
||||
workspaceId: 'workspace-1',
|
||||
enabled: true,
|
||||
reconcileDocuments: true,
|
||||
});
|
||||
|
||||
await t.context.embeddingService.prepareSelectedDocuments('workspace-1', [
|
||||
'doc-1',
|
||||
'doc-1',
|
||||
]);
|
||||
t.like(t.context.runtime.syncEmbeddingState.thirdCall.args[0], {
|
||||
t.like(t.context.runtime.syncEmbeddingState.secondCall.args[0], {
|
||||
workspaceId: 'workspace-1',
|
||||
enabled: true,
|
||||
reconcileDocuments: false,
|
||||
priority: 1000,
|
||||
waitForReadyMs: 90_000,
|
||||
});
|
||||
t.is(
|
||||
t.context.runtime.syncEmbeddingState.thirdCall.args[0].documents.length,
|
||||
t.context.runtime.syncEmbeddingState.secondCall.args[0].documents.length,
|
||||
1
|
||||
);
|
||||
|
||||
@@ -225,18 +216,11 @@ test('backend-runtime jobs ingest documents and clean runtime state', async t =>
|
||||
...healthyRoot,
|
||||
blob: Buffer.from(encodeStateAsUpdate(partialRoot, priorState)),
|
||||
});
|
||||
t.false(
|
||||
(await t.context.embeddingService.inspectWorkspaceRoot('workspace-1'))
|
||||
.complete
|
||||
await t.context.embeddingService.syncDocument('workspace-1', 'doc-1');
|
||||
t.true(
|
||||
t.context.runtime.syncEmbeddingState.lastCall.args[0].documents[0].units
|
||||
.length > 0
|
||||
);
|
||||
t.context.getSnapshot.withArgs('workspace-1', 'workspace-1').resolves({
|
||||
...healthyRoot,
|
||||
blob: Buffer.from(encodeStateAsUpdate(partialRoot)),
|
||||
});
|
||||
const repairedRoot =
|
||||
await t.context.embeddingService.inspectWorkspaceRoot('workspace-1');
|
||||
t.true(repairedRoot.complete);
|
||||
t.true(repairedRoot.docIds.has('doc-1'));
|
||||
partialRoot.destroy();
|
||||
t.context.getSnapshot
|
||||
.withArgs('workspace-1', 'workspace-1')
|
||||
@@ -272,21 +256,7 @@ test('backend-runtime jobs ingest documents and clean runtime state', async t =>
|
||||
t.context.getSnapshot
|
||||
.withArgs('workspace-1', 'doc-1')
|
||||
.resolves(healthySnapshot);
|
||||
await t.context.embeddingService.syncDocument('workspace-1', 'doc-1', {
|
||||
complete: false,
|
||||
revision: 'root-1',
|
||||
docIds: new Set(),
|
||||
});
|
||||
t.like(t.context.runtime.syncEmbeddingState.lastCall.args[0].documents[0], {
|
||||
skipReason: 'workspace_root_incomplete',
|
||||
rootRevision: 'root-1',
|
||||
units: [],
|
||||
});
|
||||
await t.context.embeddingService.syncDocument('workspace-1', 'doc-1', {
|
||||
complete: true,
|
||||
revision: 'root-2',
|
||||
docIds: new Set(['doc-1']),
|
||||
});
|
||||
await t.context.embeddingService.syncDocument('workspace-1', 'doc-1');
|
||||
t.true(
|
||||
t.context.runtime.syncEmbeddingState.lastCall.args[0].documents[0].units
|
||||
.length > 0
|
||||
|
||||
@@ -9,10 +9,7 @@ import {
|
||||
metrics,
|
||||
} from '../../base';
|
||||
import { Models } from '../../models';
|
||||
import {
|
||||
type DocumentEmbeddingProjectionInput,
|
||||
projectWorkspaceRootFromBinary,
|
||||
} from '../../native';
|
||||
import { type DocumentEmbeddingProjectionInput } from '../../native';
|
||||
import { projectDocSearch } from '../utils/blocksuite';
|
||||
import { BackendRuntimeProvider } from './provider';
|
||||
|
||||
@@ -32,44 +29,8 @@ export class BackendRuntimeEmbeddingService {
|
||||
private readonly models: Models
|
||||
) {}
|
||||
|
||||
async inspectWorkspaceRoot(workspaceId: string) {
|
||||
const snapshot = await this.models.doc.getSnapshot(
|
||||
workspaceId,
|
||||
workspaceId
|
||||
);
|
||||
const revision = snapshot?.updatedAt.getTime().toString() ?? 'missing';
|
||||
if (!snapshot)
|
||||
return { revision, complete: false, docIds: new Set<string>() };
|
||||
try {
|
||||
const projection = projectWorkspaceRootFromBinary(
|
||||
Buffer.from(snapshot.blob)
|
||||
);
|
||||
return {
|
||||
revision,
|
||||
complete: projection.complete,
|
||||
docIds: new Set(projection.docIds),
|
||||
};
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
if (message !== 'invalid_binary') throw error;
|
||||
return { revision, complete: false, docIds: new Set<string>() };
|
||||
}
|
||||
}
|
||||
|
||||
async syncDocument(
|
||||
workspaceId: string,
|
||||
docId: string,
|
||||
root?: Awaited<
|
||||
ReturnType<BackendRuntimeEmbeddingService['inspectWorkspaceRoot']>
|
||||
>
|
||||
) {
|
||||
await this.syncDocuments(
|
||||
workspaceId,
|
||||
[docId],
|
||||
false,
|
||||
undefined,
|
||||
root ?? (await this.inspectWorkspaceRoot(workspaceId))
|
||||
);
|
||||
async syncDocument(workspaceId: string, docId: string) {
|
||||
await this.syncDocuments(workspaceId, [docId]);
|
||||
}
|
||||
|
||||
async prepareSelectedDocuments(workspaceId: string, docIds: string[]) {
|
||||
@@ -78,7 +39,7 @@ export class BackendRuntimeEmbeddingService {
|
||||
throw new CopilotSelectedSourcesLimitExceeded();
|
||||
}
|
||||
try {
|
||||
await this.syncDocuments(workspaceId, selectedDocIds, false, {
|
||||
await this.syncDocuments(workspaceId, selectedDocIds, {
|
||||
priority: SELECTED_DOCUMENT_PRIORITY,
|
||||
waitForReadyMs: SELECTED_DOCUMENT_WAIT_MS,
|
||||
});
|
||||
@@ -104,11 +65,7 @@ export class BackendRuntimeEmbeddingService {
|
||||
private async syncDocuments(
|
||||
workspaceId: string,
|
||||
docIds: string[],
|
||||
reconcileDocuments: boolean,
|
||||
scheduling?: { priority: number; waitForReadyMs: number },
|
||||
root?: Awaited<
|
||||
ReturnType<BackendRuntimeEmbeddingService['inspectWorkspaceRoot']>
|
||||
>
|
||||
scheduling?: { priority: number; waitForReadyMs: number }
|
||||
) {
|
||||
if (!(await this.rt.embeddingHealth()).enabled) {
|
||||
if (scheduling) throw new CopilotSelectedSourcesUnavailable();
|
||||
@@ -135,16 +92,6 @@ export class BackendRuntimeEmbeddingService {
|
||||
sourceHash: revision,
|
||||
units: [],
|
||||
};
|
||||
if (root && (!root.complete || !root.docIds.has(docId))) {
|
||||
documents.push({
|
||||
...skipped,
|
||||
skipReason: root.complete
|
||||
? 'document_not_in_root'
|
||||
: 'workspace_root_incomplete',
|
||||
rootRevision: root.revision,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
!snapshot.blob.length ||
|
||||
(snapshot.blob.length === 2 &&
|
||||
@@ -216,24 +163,14 @@ export class BackendRuntimeEmbeddingService {
|
||||
})),
|
||||
});
|
||||
}
|
||||
if (!documents.length && !reconcileDocuments) return;
|
||||
if (!documents.length) return;
|
||||
await this.rt.syncEmbeddingState({
|
||||
workspaceId,
|
||||
enabled,
|
||||
reconcileDocuments,
|
||||
documents,
|
||||
...scheduling,
|
||||
});
|
||||
}
|
||||
|
||||
async reconcileDocuments(workspaceId: string) {
|
||||
if (!(await this.rt.embeddingHealth()).enabled) return;
|
||||
await this.rt.syncEmbeddingState({
|
||||
workspaceId,
|
||||
enabled: await this.models.workspace.allowEmbedding(workspaceId),
|
||||
reconcileDocuments: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
|
||||
@@ -1,4 +1,14 @@
|
||||
import { AccessDenied, BadRequest, NotFound } from '../../base/error';
|
||||
import {
|
||||
AccessDenied,
|
||||
BadRequest,
|
||||
DocUpdateInvalid,
|
||||
DocUpdateTooLarge,
|
||||
DocValidationUnavailable,
|
||||
NotFound,
|
||||
SpaceAccessDenied,
|
||||
UserFriendlyError,
|
||||
WorkspaceSyncUnavailable,
|
||||
} from '../../base/error';
|
||||
import { wrapCallMetric } from '../../base/metrics';
|
||||
import type {
|
||||
RuntimeUserQuotaState,
|
||||
@@ -21,9 +31,18 @@ import {
|
||||
type RuntimeWorkspaceInviteQuotaInput,
|
||||
type RuntimeWorkspaceInviteQuotaUsage,
|
||||
} from './contracts';
|
||||
import { WorkspaceLifecycleMigration } from './workspace-lifecycle';
|
||||
|
||||
const runtimeErrorPattern = /\[affine-runtime:([a-z0-9_]+)\]\s*/;
|
||||
|
||||
const runtimeErrors: Record<string, (new () => UserFriendlyError) | undefined> =
|
||||
{
|
||||
doc_update_invalid: DocUpdateInvalid,
|
||||
doc_update_too_large: DocUpdateTooLarge,
|
||||
doc_validation_unavailable: DocValidationUnavailable,
|
||||
workspace_lifecycle_not_active: WorkspaceSyncUnavailable,
|
||||
};
|
||||
|
||||
export class BackendRuntimeError extends Error {
|
||||
constructor(
|
||||
readonly code: string,
|
||||
@@ -39,8 +58,28 @@ export function backendRuntimeErrorCode(error: unknown) {
|
||||
return error instanceof BackendRuntimeError ? error.code : undefined;
|
||||
}
|
||||
|
||||
export interface WorkspaceState {
|
||||
docs: {
|
||||
docId: string;
|
||||
timestamp: number;
|
||||
lifecycle: 'trashed' | null;
|
||||
lifecycleChangedAt: number | null;
|
||||
}[];
|
||||
clocks: Record<string, number>;
|
||||
}
|
||||
|
||||
export class BackendRuntimeCoreOperations {
|
||||
constructor(protected readonly runtime: RuntimeInstance) {}
|
||||
protected readonly workspaceLifecycle: WorkspaceLifecycleMigration;
|
||||
|
||||
protected stopWorkspaceLifecycleMigrations() {
|
||||
return this.workspaceLifecycle.stop();
|
||||
}
|
||||
protected startWorkspaceLifecycleMigrations() {
|
||||
this.workspaceLifecycle.start();
|
||||
}
|
||||
constructor(protected readonly runtime: RuntimeInstance) {
|
||||
this.workspaceLifecycle = new WorkspaceLifecycleMigration(runtime);
|
||||
}
|
||||
|
||||
stripeEnabled() {
|
||||
return this.runtime.stripeEnabled();
|
||||
@@ -252,11 +291,18 @@ export class BackendRuntimeCoreOperations {
|
||||
updates: Buffer[];
|
||||
actorUserId: string;
|
||||
writeIntent: 'update_doc' | 'create_doc';
|
||||
permissionDocId?: string;
|
||||
|
||||
expectedPermissionGeneration?: number;
|
||||
}): Promise<number> {
|
||||
return await this.measured('appendWorkspaceDocUpdatesV1', runtime =>
|
||||
runtime.appendWorkspaceDocUpdatesV1(input)
|
||||
protocolVersion?: number;
|
||||
}): Promise<{ timestamp: number; created: boolean }> {
|
||||
return await this.measured(
|
||||
'appendWorkspaceDocUpdatesV1',
|
||||
runtime =>
|
||||
runtime.appendWorkspaceDocUpdatesV1({
|
||||
...input,
|
||||
protocolVersion: input.protocolVersion ?? 2,
|
||||
}),
|
||||
{ workspaceId: input.workspaceId, docId: input.docId }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -271,6 +317,43 @@ export class BackendRuntimeCoreOperations {
|
||||
);
|
||||
}
|
||||
|
||||
getCurrentWorkspaceDocV1(workspaceId: string, docId: string) {
|
||||
return this.measured(
|
||||
'getCurrentWorkspaceDocV1',
|
||||
runtime => runtime.getCurrentWorkspaceDocV1(workspaceId, docId),
|
||||
{ workspaceId, docId }
|
||||
);
|
||||
}
|
||||
|
||||
async runWorkspaceLifecycleMigrationsV1() {
|
||||
await this.workspaceLifecycle.run();
|
||||
}
|
||||
|
||||
activateWorkspaceLifecycleV1() {
|
||||
return this.measured('activateWorkspaceLifecycleV1', runtime =>
|
||||
runtime.activateWorkspaceLifecycleV1()
|
||||
);
|
||||
}
|
||||
|
||||
ensureWorkspaceLifecycleV1(workspaceId: string) {
|
||||
return this.measured(
|
||||
'ensureWorkspaceLifecycleV1',
|
||||
() => this.workspaceLifecycle.ensure(workspaceId),
|
||||
{ workspaceId }
|
||||
);
|
||||
}
|
||||
|
||||
getWorkspaceStateV1(
|
||||
workspaceId: string,
|
||||
actorUserId: string
|
||||
): Promise<WorkspaceState> {
|
||||
return this.measured(
|
||||
'getWorkspaceStateV1',
|
||||
runtime => runtime.getWorkspaceStateV1(workspaceId, actorUserId),
|
||||
{ workspaceId }
|
||||
);
|
||||
}
|
||||
|
||||
async getSyncPermissionGenerationV1(workspaceId: string): Promise<number> {
|
||||
return await this.measured('getSyncPermissionGenerationV1', runtime =>
|
||||
runtime.getSyncPermissionGenerationV1(workspaceId)
|
||||
@@ -351,6 +434,12 @@ export class BackendRuntimeCoreOperations {
|
||||
}
|
||||
}
|
||||
|
||||
upsertDocSnapshot(...args: Parameters<RuntimeInstance['upsertDocSnapshot']>) {
|
||||
return this.measured('upsertDocSnapshot', runtime =>
|
||||
runtime.upsertDocSnapshot(...args)
|
||||
);
|
||||
}
|
||||
|
||||
async cleanupExpiredUserSessions(limit: number) {
|
||||
return await this.measured('cleanupExpiredUserSessions', rt =>
|
||||
rt.cleanupExpiredUserSessions(limit)
|
||||
@@ -593,7 +682,8 @@ export class BackendRuntimeCoreOperations {
|
||||
|
||||
protected async measured<T>(
|
||||
method: string,
|
||||
fn: (runtime: RuntimeInstance) => Promise<T>
|
||||
fn: (runtime: RuntimeInstance) => Promise<T>,
|
||||
context?: { workspaceId: string; docId?: string; sourceRevision?: string }
|
||||
): Promise<T> {
|
||||
try {
|
||||
return await wrapCallMetric(
|
||||
@@ -606,7 +696,26 @@ export class BackendRuntimeCoreOperations {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
const match = runtimeErrorPattern.exec(message);
|
||||
if (!match) throw error;
|
||||
const DocumentError = runtimeErrors[match[1]];
|
||||
if (DocumentError) {
|
||||
const mapped = new DocumentError();
|
||||
mapped.cause = error;
|
||||
mapped.data = context;
|
||||
throw mapped;
|
||||
}
|
||||
switch (match[1]) {
|
||||
case 'space_access_denied':
|
||||
if (context)
|
||||
throw new SpaceAccessDenied({ spaceId: context.workspaceId });
|
||||
throw new AccessDenied('Workspace sync access denied');
|
||||
case 'doc_not_found':
|
||||
throw new NotFound('Document not found');
|
||||
case 'sync_protocol_upgrade_required':
|
||||
throw new BadRequest('Sync protocol upgrade required.');
|
||||
case 'doc_is_workspace':
|
||||
throw new BadRequest(
|
||||
'Workspace indexes cannot be restored through document history.'
|
||||
);
|
||||
case 'blob_source_access_denied':
|
||||
throw new AccessDenied('Blob source access denied');
|
||||
case 'blob_source_not_found':
|
||||
|
||||
@@ -48,7 +48,14 @@ export type RuntimeInvalidation =
|
||||
kind: 'quotaOwnerMapping' | 'quotaSeatUsage';
|
||||
workspaceId: string;
|
||||
}
|
||||
| { version: 1; kind: 'blobSource'; source: unknown };
|
||||
| { version: 1; kind: 'blobSource'; source: unknown }
|
||||
| { version: 1; kind: 'workspaceInventoryChanged'; workspaceId: string }
|
||||
| {
|
||||
version: 1;
|
||||
kind: 'workspaceRootChanged';
|
||||
workspaceId: string;
|
||||
timestampMs: number;
|
||||
};
|
||||
|
||||
declare global {
|
||||
interface Events {
|
||||
@@ -97,6 +104,7 @@ export class BackendRuntimeProvider
|
||||
|
||||
async start() {
|
||||
await this.runtime.start();
|
||||
this.startWorkspaceLifecycleMigrations();
|
||||
await this.event?.emitAsync('backendRuntime.configApplied', {
|
||||
updates: { payment: {}, indexer: {}, copilot: {}, crypto: {}, oauth: {} },
|
||||
});
|
||||
@@ -119,6 +127,7 @@ export class BackendRuntimeProvider
|
||||
}
|
||||
|
||||
async stop() {
|
||||
await this.stopWorkspaceLifecycleMigrations();
|
||||
await this.runtime.stop();
|
||||
this.logger.log('backend runtime stopped');
|
||||
}
|
||||
|
||||
@@ -77,8 +77,15 @@ export class BackendRuntimeSearchOperations extends BackendRuntimeCoreOperations
|
||||
async executeDomainCommandV1(
|
||||
input: DomainCommandInputV1
|
||||
): Promise<DomainCommandOutputV1> {
|
||||
return await this.measured('executeDomainCommandV1', runtime =>
|
||||
this.permissionRuntime(runtime).executeDomainCommandV1(input)
|
||||
return await this.measured(
|
||||
'executeDomainCommandV1',
|
||||
runtime => this.permissionRuntime(runtime).executeDomainCommandV1(input),
|
||||
'workspaceId' in input
|
||||
? {
|
||||
workspaceId: input.workspaceId,
|
||||
docId: 'docId' in input ? input.docId : input.workspaceId,
|
||||
}
|
||||
: undefined
|
||||
);
|
||||
}
|
||||
|
||||
@@ -126,8 +133,10 @@ export class BackendRuntimeSearchOperations extends BackendRuntimeCoreOperations
|
||||
}
|
||||
|
||||
async syncEmbeddingState(input: SyncEmbeddingStateInput) {
|
||||
return await this.measured('syncEmbeddingState', runtime =>
|
||||
runtime.syncEmbeddingState(input)
|
||||
return await this.measured(
|
||||
'syncEmbeddingState',
|
||||
runtime => runtime.syncEmbeddingState(input),
|
||||
{ workspaceId: input.workspaceId, docId: input.workspaceId }
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import * as Y from 'yjs';
|
||||
|
||||
import type { RuntimeInstance } from './contracts';
|
||||
|
||||
export class WorkspaceLifecycleMigration {
|
||||
private readonly logger = new Logger(WorkspaceLifecycleMigration.name);
|
||||
private readonly pending = new Map<string, Promise<void>>();
|
||||
private sweep?: Promise<void>;
|
||||
private stopped = false;
|
||||
|
||||
constructor(private readonly runtime: RuntimeInstance) {}
|
||||
|
||||
start() {
|
||||
this.stopped = false;
|
||||
this.scheduleSweep();
|
||||
}
|
||||
|
||||
async stop() {
|
||||
this.stopped = true;
|
||||
await this.sweep;
|
||||
await Promise.all(this.pending.values());
|
||||
}
|
||||
|
||||
async ensure(workspaceId: string): Promise<void> {
|
||||
const pending = this.pending.get(workspaceId);
|
||||
if (pending) return pending;
|
||||
const migration = this.migrate(workspaceId).finally(() => {
|
||||
this.pending.delete(workspaceId);
|
||||
});
|
||||
this.pending.set(workspaceId, migration);
|
||||
return migration;
|
||||
}
|
||||
|
||||
run() {
|
||||
this.scheduleSweep();
|
||||
return this.sweep;
|
||||
}
|
||||
|
||||
private scheduleSweep() {
|
||||
if (this.sweep || this.stopped) return;
|
||||
this.sweep = (async () => {
|
||||
while (!this.stopped) {
|
||||
const workspaces =
|
||||
await this.runtime.listWorkspaceLifecycleMigrationCandidatesV1();
|
||||
if (!workspaces.length) return;
|
||||
for (const workspaceId of workspaces) {
|
||||
if (this.stopped) return;
|
||||
await this.ensure(workspaceId);
|
||||
}
|
||||
}
|
||||
})()
|
||||
.catch((error: unknown) => {
|
||||
this.logger.error('Workspace lifecycle migration sweep stopped', error);
|
||||
})
|
||||
.finally(() => {
|
||||
this.sweep = undefined;
|
||||
});
|
||||
}
|
||||
|
||||
private async migrate(workspaceId: string) {
|
||||
for (;;) {
|
||||
const source =
|
||||
await this.runtime.prepareWorkspaceLifecycleMigrationV1(workspaceId);
|
||||
if (source.completed) {
|
||||
this.scheduleSweep();
|
||||
return;
|
||||
}
|
||||
let rootStatus = source.rootStatus;
|
||||
const docs: { docId: string; trashed: boolean }[] = [];
|
||||
if (source.bin) {
|
||||
const root = new Y.Doc();
|
||||
try {
|
||||
Y.applyUpdate(root, source.bin);
|
||||
const pages: unknown = root.getMap('meta').toJSON().pages;
|
||||
if (Array.isArray(pages)) {
|
||||
for (const page of pages) {
|
||||
if (typeof page !== 'object' || page === null || !('id' in page))
|
||||
continue;
|
||||
const docId: unknown = page.id;
|
||||
if (typeof docId !== 'string' || !docId.trim()) continue;
|
||||
docs.push({
|
||||
docId,
|
||||
trashed: 'trash' in page && page.trash === true,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
docs.length = 0;
|
||||
rootStatus = 'invalid_metadata';
|
||||
this.logger.warn(
|
||||
`Ignoring invalid legacy root metadata during workspace lifecycle migration: ${workspaceId}`
|
||||
);
|
||||
} finally {
|
||||
root.destroy();
|
||||
}
|
||||
}
|
||||
const completed = await this.runtime.migrateWorkspaceLifecycleV1({
|
||||
workspaceId,
|
||||
sourceRevision: source.revision,
|
||||
rootStatus,
|
||||
docs,
|
||||
});
|
||||
if (completed) {
|
||||
this.scheduleSweep();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,7 @@ export class DocJobRunner {
|
||||
@Cron(CronExpression.EVERY_30_SECONDS, { waitForCompletion: true })
|
||||
async run() {
|
||||
await Promise.allSettled([
|
||||
this.runtime.runWorkspaceLifecycleMigrationsV1(),
|
||||
this.compactPendingDocUpdates(),
|
||||
this.syncEmbeddingDocuments(),
|
||||
this.recordPendingDocUpdatesCount(),
|
||||
@@ -49,84 +50,30 @@ export class DocJobRunner {
|
||||
async syncEmbeddingDocuments() {
|
||||
if (!(await this.runtime.embeddingHealth()).enabled) {
|
||||
return {
|
||||
reconciledWorkspaces: 0,
|
||||
scannedDocuments: 0,
|
||||
syncedDocuments: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const roots = await this.prisma.$queryRaw<
|
||||
{ id: string; lastCheckEmbeddings: Date }[]
|
||||
>`
|
||||
SELECT workspace.id, workspace.last_check_embeddings AS "lastCheckEmbeddings"
|
||||
FROM workspaces workspace
|
||||
JOIN snapshots root
|
||||
ON root.workspace_id = workspace.id AND root.guid = workspace.id
|
||||
WHERE workspace.last_check_embeddings <= root.updated_at
|
||||
ORDER BY workspace.last_check_embeddings, workspace.sid
|
||||
LIMIT ${WORKSPACE_BATCH_SIZE}
|
||||
`;
|
||||
const rootsByWorkspace = new Map<
|
||||
string,
|
||||
Awaited<
|
||||
ReturnType<BackendRuntimeEmbeddingService['inspectWorkspaceRoot']>
|
||||
>
|
||||
>();
|
||||
const inspectRoot = async (workspaceId: string) => {
|
||||
let root = rootsByWorkspace.get(workspaceId);
|
||||
if (!root) {
|
||||
root = await this.embedding.inspectWorkspaceRoot(workspaceId);
|
||||
rootsByWorkspace.set(workspaceId, root);
|
||||
}
|
||||
return root;
|
||||
};
|
||||
let reconciledWorkspaces = 0;
|
||||
for (const workspace of roots) {
|
||||
const claimedAt = new Date();
|
||||
const claimed = await this.prisma.workspace.updateMany({
|
||||
where: {
|
||||
id: workspace.id,
|
||||
lastCheckEmbeddings: workspace.lastCheckEmbeddings,
|
||||
},
|
||||
data: { lastCheckEmbeddings: claimedAt },
|
||||
});
|
||||
if (!claimed.count) continue;
|
||||
try {
|
||||
const root = await inspectRoot(workspace.id);
|
||||
if (!root.complete) continue;
|
||||
await this.embedding.reconcileDocuments(workspace.id);
|
||||
reconciledWorkspaces++;
|
||||
} catch (error) {
|
||||
await this.prisma.workspace.updateMany({
|
||||
where: { id: workspace.id, lastCheckEmbeddings: claimedAt },
|
||||
data: { lastCheckEmbeddings: new Date(0) },
|
||||
});
|
||||
this.logger.error('embedding workspace reconciliation failed', {
|
||||
workspaceId: workspace.id,
|
||||
error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const documents = await this.prisma.$queryRaw<
|
||||
{ workspaceId: string; docId: string }[]
|
||||
>`
|
||||
SELECT snapshot.workspace_id AS "workspaceId", snapshot.guid AS "docId"
|
||||
FROM snapshots snapshot
|
||||
JOIN workspaces workspace ON workspace.id = snapshot.workspace_id
|
||||
LEFT JOIN snapshots root ON root.workspace_id = snapshot.workspace_id AND root.guid = snapshot.workspace_id
|
||||
LEFT JOIN workspace_pages page ON page.workspace_id = snapshot.workspace_id AND page.page_id = snapshot.guid
|
||||
LEFT JOIN embedding_sources source
|
||||
ON source.workspace_id = snapshot.workspace_id
|
||||
AND source.source_kind = 'document'
|
||||
AND source.source_key = snapshot.guid
|
||||
WHERE workspace.enable_doc_embedding
|
||||
AND page.lifecycle_state IS NULL
|
||||
AND snapshot.guid <> snapshot.workspace_id
|
||||
AND snapshot.guid NOT LIKE 'db$%'
|
||||
AND snapshot.guid NOT LIKE 'userdata$%'
|
||||
AND (
|
||||
source.id IS NULL
|
||||
OR (source.document_projection->>'rootRevision' IS NOT NULL
|
||||
AND source.document_projection->>'rootRevision' <> COALESCE(((extract(epoch FROM root.updated_at) * 1000)::bigint)::text, 'missing'))
|
||||
OR source.deleted_at IS NOT NULL
|
||||
OR source.content_revision <> ((extract(epoch FROM snapshot.updated_at) * 1000)::bigint)::text
|
||||
)
|
||||
ORDER BY snapshot.updated_at, snapshot.workspace_id, snapshot.guid
|
||||
@@ -135,11 +82,7 @@ export class DocJobRunner {
|
||||
let syncedDocuments = 0;
|
||||
for (const document of documents) {
|
||||
try {
|
||||
await this.embedding.syncDocument(
|
||||
document.workspaceId,
|
||||
document.docId,
|
||||
await inspectRoot(document.workspaceId)
|
||||
);
|
||||
await this.embedding.syncDocument(document.workspaceId, document.docId);
|
||||
syncedDocuments++;
|
||||
} catch (error) {
|
||||
this.logger.error('document embedding sync failed', {
|
||||
@@ -149,7 +92,6 @@ export class DocJobRunner {
|
||||
}
|
||||
}
|
||||
return {
|
||||
reconciledWorkspaces,
|
||||
scannedDocuments: documents.length,
|
||||
syncedDocuments,
|
||||
};
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
# Snapshot report for `src/core/doc/__tests__/codec-compare.spec.ts`
|
||||
|
||||
The actual snapshot is saved in `codec-compare.spec.ts.snap`.
|
||||
|
||||
Generated by [AVA](https://avajs.dev).
|
||||
|
||||
## compareCodecResult ignores map ordering differences
|
||||
|
||||
> ignores map ordering differences
|
||||
|
||||
{
|
||||
matches: true,
|
||||
}
|
||||
|
||||
## compareCodecResult reports nested map text and xml changes
|
||||
|
||||
> reports nested map text and xml changes
|
||||
|
||||
{
|
||||
matches: false,
|
||||
treeDiff: [
|
||||
'$.blocks.meta.checked: yjs=false yocto=true',
|
||||
'$.content.attrs.kind: yjs="intro" yocto="summary"',
|
||||
'$.meta.info.flags.priority: yjs=3 yocto=7',
|
||||
'$.meta.info.tags[1]: yjs="beta" yocto="gamma"',
|
||||
'$.titles.main: yjs="Complex document" yocto="Complex document updated"',
|
||||
],
|
||||
}
|
||||
|
||||
## compareCodecResult reports weird mixed arrays nulls binary and nested text changes
|
||||
|
||||
> reports weird mixed arrays nulls binary and nested text changes
|
||||
|
||||
{
|
||||
matches: false,
|
||||
treeDiff: [
|
||||
'$.attachments[0].notes: yjs="first file" yocto="first file updated"',
|
||||
'$.attachments[2]: yjs=true yocto=false',
|
||||
'$.attachments[4] only exists in yocto: "tail"',
|
||||
'$.meta.nested[0].labels[1]: yjs="y" yocto="changed"',
|
||||
'$.rich.attrs.mood: yjs="calm" yocto="loud"',
|
||||
'$.rich.children[0].children[0]: yjs="hello" yocto="hello there"',
|
||||
],
|
||||
}
|
||||
|
||||
## compareCodecResult reports root text and reordered array content changes
|
||||
|
||||
> reports root text and reordered array content changes
|
||||
|
||||
{
|
||||
matches: false,
|
||||
treeDiff: [
|
||||
'$.logline: yjs="affine" yocto="affine cloud"',
|
||||
'$.queue: yjs="abc" yocto="acb"',
|
||||
'$.settings.enabled: yjs=true yocto=false',
|
||||
],
|
||||
}
|
||||
BIN
Binary file not shown.
@@ -1,358 +0,0 @@
|
||||
import test from 'ava';
|
||||
import * as Y from 'yjs';
|
||||
|
||||
import { compareCodecResult } from '../codec-compare';
|
||||
|
||||
type DocScalar = null | boolean | number | string | Uint8Array;
|
||||
|
||||
type DocTextValue = {
|
||||
$text: string;
|
||||
};
|
||||
|
||||
type DocXmlTextValue = {
|
||||
$xmlText: string;
|
||||
};
|
||||
|
||||
type DocXmlElementValue = {
|
||||
$xmlElement: string;
|
||||
attrs?: Record<string, boolean | number | string>;
|
||||
children?: DocValue[];
|
||||
};
|
||||
|
||||
type DocXmlFragmentValue = {
|
||||
$xmlFragment: DocValue[];
|
||||
};
|
||||
|
||||
type DocMapValue = {
|
||||
[key: string]: DocValue;
|
||||
};
|
||||
|
||||
type DocArrayValue = DocValue[];
|
||||
|
||||
type DocValue =
|
||||
| DocScalar
|
||||
| DocTextValue
|
||||
| DocXmlTextValue
|
||||
| DocXmlElementValue
|
||||
| DocXmlFragmentValue
|
||||
| DocMapValue
|
||||
| DocArrayValue;
|
||||
|
||||
type DocShape = Record<string, DocValue>;
|
||||
|
||||
type CodecCompareCase = {
|
||||
expectedMatches: boolean;
|
||||
left: DocShape;
|
||||
right: DocShape;
|
||||
title: string;
|
||||
};
|
||||
|
||||
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
||||
return (
|
||||
typeof value === 'object' &&
|
||||
value !== null &&
|
||||
!Array.isArray(value) &&
|
||||
!(value instanceof Uint8Array)
|
||||
);
|
||||
}
|
||||
|
||||
function isTextValue(value: DocValue): value is DocTextValue {
|
||||
return isPlainObject(value) && '$text' in value;
|
||||
}
|
||||
|
||||
function isXmlTextValue(value: DocValue): value is DocXmlTextValue {
|
||||
return isPlainObject(value) && '$xmlText' in value;
|
||||
}
|
||||
|
||||
function isXmlElementValue(value: DocValue): value is DocXmlElementValue {
|
||||
return isPlainObject(value) && '$xmlElement' in value;
|
||||
}
|
||||
|
||||
function isXmlFragmentValue(value: DocValue): value is DocXmlFragmentValue {
|
||||
return isPlainObject(value) && '$xmlFragment' in value;
|
||||
}
|
||||
|
||||
function buildText(text: string) {
|
||||
const yText = new Y.Text();
|
||||
yText.insert(0, text);
|
||||
return yText;
|
||||
}
|
||||
|
||||
function appendXmlNode(
|
||||
parent: Y.XmlElement | Y.XmlFragment,
|
||||
value: DocValue
|
||||
): void {
|
||||
if (isXmlTextValue(value)) {
|
||||
parent.push([new Y.XmlText(value.$xmlText)]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isXmlElementValue(value)) {
|
||||
throw new Error(`Expected xml node, got ${JSON.stringify(value)}`);
|
||||
}
|
||||
|
||||
const element = new Y.XmlElement(value.$xmlElement);
|
||||
parent.push([element]);
|
||||
for (const [key, attr] of Object.entries(value.attrs ?? {})) {
|
||||
element.setAttribute(key, String(attr));
|
||||
}
|
||||
for (const child of value.children ?? []) {
|
||||
appendXmlNode(element, child);
|
||||
}
|
||||
}
|
||||
|
||||
function buildArray(values: DocArrayValue) {
|
||||
const yArray = new Y.Array<unknown>();
|
||||
yArray.push(values.map(value => buildSharedValue(value)));
|
||||
return yArray;
|
||||
}
|
||||
|
||||
function buildMap(shape: DocMapValue) {
|
||||
const yMap = new Y.Map<unknown>();
|
||||
for (const [key, value] of Object.entries(shape)) {
|
||||
yMap.set(key, buildSharedValue(value));
|
||||
}
|
||||
return yMap;
|
||||
}
|
||||
|
||||
function buildSharedValue(value: DocValue): unknown {
|
||||
if (
|
||||
value == null ||
|
||||
typeof value === 'boolean' ||
|
||||
typeof value === 'number' ||
|
||||
typeof value === 'string' ||
|
||||
value instanceof Uint8Array
|
||||
) {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return buildArray(value);
|
||||
}
|
||||
|
||||
if (isTextValue(value)) {
|
||||
return buildText(value.$text);
|
||||
}
|
||||
|
||||
if (
|
||||
isXmlFragmentValue(value) ||
|
||||
isXmlElementValue(value) ||
|
||||
isXmlTextValue(value)
|
||||
) {
|
||||
throw new Error('XML values are only supported at root xmlFragment fields');
|
||||
}
|
||||
|
||||
return buildMap(value);
|
||||
}
|
||||
|
||||
function applyRootValue(doc: Y.Doc, key: string, value: DocValue) {
|
||||
if (isTextValue(value)) {
|
||||
doc.getText(key).insert(0, value.$text);
|
||||
return;
|
||||
}
|
||||
|
||||
if (isXmlFragmentValue(value)) {
|
||||
const fragment = doc.getXmlFragment(key);
|
||||
for (const child of value.$xmlFragment) {
|
||||
appendXmlNode(fragment, child);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
doc.getArray(key).push(value.map(item => buildSharedValue(item)));
|
||||
return;
|
||||
}
|
||||
|
||||
if (isPlainObject(value)) {
|
||||
const yMap = doc.getMap(key);
|
||||
for (const [childKey, childValue] of Object.entries(value)) {
|
||||
yMap.set(childKey, buildSharedValue(childValue as DocValue));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`Unsupported root value for "${key}": ${JSON.stringify(value)}`
|
||||
);
|
||||
}
|
||||
|
||||
function encodeDocFromShape(shape: DocShape): Buffer {
|
||||
const doc = new Y.Doc();
|
||||
for (const [key, value] of Object.entries(shape)) {
|
||||
applyRootValue(doc, key, value);
|
||||
}
|
||||
return Buffer.from(Y.encodeStateAsUpdate(doc));
|
||||
}
|
||||
|
||||
const baseDoc: DocShape = {
|
||||
blocks: [
|
||||
{
|
||||
id: 'block-1',
|
||||
meta: { checked: false, weight: 10 },
|
||||
type: 'todo',
|
||||
},
|
||||
],
|
||||
content: {
|
||||
$xmlFragment: [
|
||||
{
|
||||
$xmlElement: 'paragraph',
|
||||
attrs: { kind: 'intro' },
|
||||
children: [{ $xmlText: 'hello world' }],
|
||||
},
|
||||
],
|
||||
},
|
||||
meta: {
|
||||
info: {
|
||||
flags: { archived: false, priority: 3 },
|
||||
owner: 'alice',
|
||||
tags: ['alpha', 'beta'],
|
||||
},
|
||||
version: 1,
|
||||
},
|
||||
titles: {
|
||||
main: { $text: 'Complex document' },
|
||||
},
|
||||
};
|
||||
|
||||
const compareCases: CodecCompareCase[] = [
|
||||
{
|
||||
expectedMatches: true,
|
||||
title: 'ignores map ordering differences',
|
||||
left: baseDoc,
|
||||
right: {
|
||||
titles: { main: { $text: 'Complex document' } },
|
||||
content: {
|
||||
$xmlFragment: [
|
||||
{
|
||||
$xmlElement: 'paragraph',
|
||||
attrs: { kind: 'intro' },
|
||||
children: [{ $xmlText: 'hello world' }],
|
||||
},
|
||||
],
|
||||
},
|
||||
blocks: [
|
||||
{
|
||||
type: 'todo',
|
||||
meta: { weight: 10, checked: false },
|
||||
id: 'block-1',
|
||||
},
|
||||
],
|
||||
meta: {
|
||||
version: 1,
|
||||
info: {
|
||||
tags: ['alpha', 'beta'],
|
||||
owner: 'alice',
|
||||
flags: { priority: 3, archived: false },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
expectedMatches: false,
|
||||
title: 'reports nested map text and xml changes',
|
||||
left: baseDoc,
|
||||
right: {
|
||||
...baseDoc,
|
||||
blocks: [
|
||||
{ id: 'block-1', meta: { checked: true, weight: 10 }, type: 'todo' },
|
||||
],
|
||||
content: {
|
||||
$xmlFragment: [
|
||||
{
|
||||
$xmlElement: 'paragraph',
|
||||
attrs: { kind: 'summary' },
|
||||
children: [{ $xmlText: 'hello world' }],
|
||||
},
|
||||
],
|
||||
},
|
||||
meta: {
|
||||
info: {
|
||||
flags: { archived: false, priority: 7 },
|
||||
owner: 'alice',
|
||||
tags: ['alpha', 'gamma'],
|
||||
},
|
||||
version: 1,
|
||||
},
|
||||
titles: { main: { $text: 'Complex document updated' } },
|
||||
},
|
||||
},
|
||||
{
|
||||
expectedMatches: false,
|
||||
title: 'reports weird mixed arrays nulls binary and nested text changes',
|
||||
left: {
|
||||
attachments: [
|
||||
{
|
||||
blob: new Uint8Array([1, 2, 3]),
|
||||
filename: 'a.bin',
|
||||
notes: { $text: 'first file' },
|
||||
},
|
||||
null,
|
||||
true,
|
||||
42,
|
||||
],
|
||||
meta: { nested: [{ labels: ['x', 'y'] }, { labels: ['z'] }] },
|
||||
rich: {
|
||||
$xmlFragment: [
|
||||
{
|
||||
$xmlElement: 'card',
|
||||
attrs: { mood: 'calm' },
|
||||
children: [
|
||||
{ $xmlElement: 'title', children: [{ $xmlText: 'hello' }] },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
right: {
|
||||
attachments: [
|
||||
{
|
||||
blob: new Uint8Array([1, 2, 4]),
|
||||
filename: 'a.bin',
|
||||
notes: { $text: 'first file updated' },
|
||||
},
|
||||
null,
|
||||
false,
|
||||
42,
|
||||
'tail',
|
||||
],
|
||||
meta: { nested: [{ labels: ['x', 'changed'] }, { labels: ['z'] }] },
|
||||
rich: {
|
||||
$xmlFragment: [
|
||||
{
|
||||
$xmlElement: 'card',
|
||||
attrs: { mood: 'loud' },
|
||||
children: [
|
||||
{ $xmlElement: 'title', children: [{ $xmlText: 'hello there' }] },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
expectedMatches: false,
|
||||
title: 'reports root text and reordered array content changes',
|
||||
left: {
|
||||
logline: { $text: 'affine' },
|
||||
queue: ['a', 'b', 'c'],
|
||||
settings: { enabled: true, retries: 2 },
|
||||
},
|
||||
right: {
|
||||
logline: { $text: 'affine cloud' },
|
||||
queue: ['a', 'c', 'b'],
|
||||
settings: { enabled: false, retries: 2 },
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
for (const testCase of compareCases) {
|
||||
test(`compareCodecResult ${testCase.title}`, t => {
|
||||
const leftBinary = encodeDocFromShape(testCase.left);
|
||||
const rightBinary = encodeDocFromShape(testCase.right);
|
||||
const result = compareCodecResult(leftBinary, rightBinary);
|
||||
|
||||
t.is(result.matches, testCase.expectedMatches);
|
||||
t.snapshot(result, testCase.title);
|
||||
});
|
||||
}
|
||||
@@ -68,7 +68,7 @@ test('should update doc content to database when doc is updated', async t => {
|
||||
|
||||
const docId = randomUUID();
|
||||
await adapter.pushDocUpdatesTrusted(workspace.id, docId, updates);
|
||||
await adapter.getDocBinNative(workspace.id, docId);
|
||||
await adapter.getDoc(workspace.id, docId);
|
||||
|
||||
mock.method(docReader, 'parseDocContent', () => {
|
||||
return {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto';
|
||||
import { mock } from 'node:test';
|
||||
|
||||
import test from 'ava';
|
||||
import { applyUpdate, Doc as YDoc } from 'yjs';
|
||||
import { applyUpdate, Doc as YDoc, encodeStateAsUpdate } from 'yjs';
|
||||
|
||||
import { createModule } from '../../../__tests__/create-module';
|
||||
import { Mockers } from '../../../__tests__/mocks';
|
||||
@@ -52,11 +52,13 @@ test('should return doc when found', async t => {
|
||||
|
||||
const docId = randomUUID();
|
||||
const timestamp = Date.now();
|
||||
const source = new YDoc();
|
||||
source.getText('content').insert(0, 'blob1 data');
|
||||
await models.doc.createUpdates([
|
||||
{
|
||||
spaceId: workspace.id,
|
||||
docId,
|
||||
blob: Buffer.from('blob1 data'),
|
||||
blob: Buffer.from(encodeStateAsUpdate(source)),
|
||||
timestamp,
|
||||
editorId: user.id,
|
||||
},
|
||||
@@ -64,7 +66,9 @@ test('should return doc when found', async t => {
|
||||
|
||||
const doc = await docReader.getDoc(workspace.id, docId);
|
||||
t.truthy(doc);
|
||||
t.is(Buffer.from(doc!.bin).toString('utf8'), 'blob1 data');
|
||||
const loaded = new YDoc();
|
||||
applyUpdate(loaded, doc!.bin);
|
||||
t.is(loaded.getText('content').toString(), 'blob1 data');
|
||||
t.is(doc!.timestamp, timestamp);
|
||||
t.is(doc!.editor, user.id);
|
||||
});
|
||||
|
||||
@@ -37,10 +37,6 @@ export class PgUserspaceDocStorageAdapter extends DocStorageAdapter {
|
||||
return false;
|
||||
}
|
||||
|
||||
override async rollbackDoc() {
|
||||
return;
|
||||
}
|
||||
|
||||
override async getDoc(spaceId: string, docId: string) {
|
||||
return await this.getDocSnapshot(spaceId, docId);
|
||||
}
|
||||
@@ -52,14 +48,13 @@ export class PgUserspaceDocStorageAdapter extends DocStorageAdapter {
|
||||
editorId = userId,
|
||||
_expectedPermissionGeneration?: number,
|
||||
_writeIntent?: 'update_doc' | 'create_doc',
|
||||
_permissionDocId?: string
|
||||
_protocolVersion?: number
|
||||
) {
|
||||
if (!updates.length) {
|
||||
return 0;
|
||||
return { timestamp: 0, created: false };
|
||||
}
|
||||
|
||||
updates = await this.filterValidDocUpdates(userId, docId, updates);
|
||||
if (!updates.length) return 0;
|
||||
await this.assertValidDocUpdates(updates);
|
||||
|
||||
await using _lock = await this.lockDocForUpdate(userId, docId);
|
||||
const snapshot = await this.getDocSnapshot(userId, docId);
|
||||
@@ -81,7 +76,7 @@ export class PgUserspaceDocStorageAdapter extends DocStorageAdapter {
|
||||
editor: editorId,
|
||||
});
|
||||
|
||||
return timestamp;
|
||||
return { timestamp, created: snapshot === null };
|
||||
}
|
||||
|
||||
async pushDocUpdatesTrusted(
|
||||
@@ -90,7 +85,8 @@ export class PgUserspaceDocStorageAdapter extends DocStorageAdapter {
|
||||
updates: Uint8Array[],
|
||||
editorId = userId
|
||||
) {
|
||||
return await this.pushDocUpdates(userId, docId, updates, editorId);
|
||||
return (await this.pushDocUpdates(userId, docId, updates, editorId))
|
||||
.timestamp;
|
||||
}
|
||||
|
||||
async deleteDoc(userId: string, docId: string) {
|
||||
|
||||
@@ -1,18 +1,11 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { Transactional } from '@nestjs-cls/transactional';
|
||||
import { TransactionalAdapterPrisma } from '@nestjs-cls/transactional-adapter-prisma';
|
||||
import { chunk } from 'lodash-es';
|
||||
|
||||
import {
|
||||
DocHistoryNotFound,
|
||||
DocNotFound,
|
||||
EventBus,
|
||||
FailedToSaveUpdates,
|
||||
FailedToUpsertSnapshot,
|
||||
metrics,
|
||||
Mutex,
|
||||
} from '../../../base';
|
||||
import { retryable } from '../../../base/utils/promise';
|
||||
import { Models } from '../../../models';
|
||||
import { BackendRuntimeProvider } from '../../backend-runtime';
|
||||
import { DocStorageOptions } from '../options';
|
||||
@@ -57,22 +50,16 @@ export class PgWorkspaceDocStorageAdapter extends DocStorageAdapter {
|
||||
workspaceId: string,
|
||||
docId: string
|
||||
): Promise<DocRecord | null> {
|
||||
await using _lock = await this.lockDocForUpdate(workspaceId, docId);
|
||||
const result = await this.getDocInTransaction(workspaceId, docId);
|
||||
if (result.snapshotUpdated && result.doc) {
|
||||
this.event.emitDetached('doc.snapshot.updated', {
|
||||
workspaceId,
|
||||
docId,
|
||||
blob: Buffer.from(result.doc.bin),
|
||||
});
|
||||
}
|
||||
return result.doc;
|
||||
}
|
||||
|
||||
@Transactional<TransactionalAdapterPrisma>({ timeout: 60000 })
|
||||
private async getDocInTransaction(workspaceId: string, docId: string) {
|
||||
await this.models.doc.lockDocContent(workspaceId, docId);
|
||||
return await this.getDocUnderLock(workspaceId, docId);
|
||||
const doc = await this.runtime.getCurrentWorkspaceDocV1(workspaceId, docId);
|
||||
return doc
|
||||
? {
|
||||
spaceId: workspaceId,
|
||||
docId,
|
||||
bin: doc.bin,
|
||||
timestamp: doc.timestamp,
|
||||
editor: doc.editor ?? undefined,
|
||||
}
|
||||
: null;
|
||||
}
|
||||
|
||||
async pushDocUpdates(
|
||||
@@ -82,7 +69,7 @@ export class PgWorkspaceDocStorageAdapter extends DocStorageAdapter {
|
||||
editorId: string,
|
||||
expectedPermissionGeneration?: number,
|
||||
writeIntent: 'update_doc' | 'create_doc' = 'update_doc',
|
||||
permissionDocId?: string
|
||||
protocolVersion = 2
|
||||
) {
|
||||
return await this.pushDocUpdatesWithContract(
|
||||
workspaceId,
|
||||
@@ -92,8 +79,8 @@ export class PgWorkspaceDocStorageAdapter extends DocStorageAdapter {
|
||||
{
|
||||
actorUserId: editorId,
|
||||
writeIntent,
|
||||
permissionDocId,
|
||||
expectedPermissionGeneration,
|
||||
protocolVersion,
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -104,13 +91,15 @@ export class PgWorkspaceDocStorageAdapter extends DocStorageAdapter {
|
||||
updates: Uint8Array[],
|
||||
editorId?: string
|
||||
) {
|
||||
return await this.pushDocUpdatesWithContract(
|
||||
workspaceId,
|
||||
docId,
|
||||
updates,
|
||||
editorId,
|
||||
{ trusted: true }
|
||||
);
|
||||
return (
|
||||
await this.pushDocUpdatesWithContract(
|
||||
workspaceId,
|
||||
docId,
|
||||
updates,
|
||||
editorId,
|
||||
{ trusted: true }
|
||||
)
|
||||
).timestamp;
|
||||
}
|
||||
|
||||
private async pushDocUpdatesWithContract(
|
||||
@@ -122,76 +111,43 @@ export class PgWorkspaceDocStorageAdapter extends DocStorageAdapter {
|
||||
| {
|
||||
actorUserId: string;
|
||||
writeIntent: 'update_doc' | 'create_doc';
|
||||
permissionDocId?: string;
|
||||
|
||||
expectedPermissionGeneration?: number;
|
||||
protocolVersion: number;
|
||||
}
|
||||
| { trusted: true }
|
||||
) {
|
||||
if (!updates.length) {
|
||||
return 0;
|
||||
return { timestamp: 0, created: false };
|
||||
}
|
||||
|
||||
updates = await this.filterValidDocUpdates(workspaceId, docId, updates);
|
||||
if (!updates.length) return 0;
|
||||
const input = {
|
||||
workspaceId,
|
||||
docId,
|
||||
updates: updates.map(update => Buffer.from(update)),
|
||||
};
|
||||
const result =
|
||||
'trusted' in contract
|
||||
? {
|
||||
timestamp: await this.runtime.appendWorkspaceDocUpdatesTrustedV1({
|
||||
...input,
|
||||
editorId,
|
||||
}),
|
||||
created: false,
|
||||
}
|
||||
: await this.runtime.appendWorkspaceDocUpdatesV1({
|
||||
...input,
|
||||
...contract,
|
||||
});
|
||||
|
||||
const isNewDoc = !(await this.models.doc.exists(workspaceId, docId));
|
||||
|
||||
let pendings = updates;
|
||||
let done = 0;
|
||||
let timestamp = Date.now();
|
||||
try {
|
||||
await retryable(async () => {
|
||||
if (done !== 0) {
|
||||
pendings = pendings.slice(done);
|
||||
}
|
||||
|
||||
const batchCount = 10;
|
||||
for (const batch of chunk(pendings, batchCount)) {
|
||||
const input = {
|
||||
workspaceId,
|
||||
docId,
|
||||
updates: batch.map(update => Buffer.from(update)),
|
||||
};
|
||||
timestamp =
|
||||
'trusted' in contract
|
||||
? await this.runtime.appendWorkspaceDocUpdatesTrustedV1({
|
||||
...input,
|
||||
editorId,
|
||||
})
|
||||
: await this.runtime.appendWorkspaceDocUpdatesV1({
|
||||
...input,
|
||||
...contract,
|
||||
});
|
||||
done += batch.length;
|
||||
}
|
||||
});
|
||||
|
||||
if (isNewDoc) {
|
||||
await this.event.emitDetachedAsync('doc.created', {
|
||||
workspaceId,
|
||||
docId,
|
||||
editor: editorId,
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
this.logger.error('Failed to insert doc updates', {
|
||||
if (result.created) {
|
||||
await this.event.emitDetachedAsync('doc.created', {
|
||||
workspaceId,
|
||||
docId,
|
||||
actorUserId: editorId,
|
||||
writeIntent: 'trusted' in contract ? 'trusted' : contract.writeIntent,
|
||||
permissionDocId:
|
||||
'trusted' in contract ? docId : (contract.permissionDocId ?? docId),
|
||||
expectedPermissionGeneration:
|
||||
'trusted' in contract
|
||||
? undefined
|
||||
: contract.expectedPermissionGeneration,
|
||||
updateCount: updates.length,
|
||||
error: e,
|
||||
editor: editorId,
|
||||
});
|
||||
metrics.doc.counter('doc_update_insert_failed').add(1);
|
||||
throw new FailedToSaveUpdates();
|
||||
}
|
||||
return timestamp;
|
||||
return result;
|
||||
}
|
||||
|
||||
protected async getDocUpdates(workspaceId: string, docId: string) {
|
||||
@@ -262,48 +218,7 @@ export class PgWorkspaceDocStorageAdapter extends DocStorageAdapter {
|
||||
};
|
||||
}
|
||||
|
||||
override async rollbackDoc(
|
||||
spaceId: string,
|
||||
docId: string,
|
||||
timestamp: number,
|
||||
editorId?: string
|
||||
): Promise<void> {
|
||||
await using _lock = await this.lockDocForUpdate(spaceId, docId);
|
||||
const toSnapshot = await this.getDocHistory(spaceId, docId, timestamp);
|
||||
if (!toSnapshot) {
|
||||
throw new DocHistoryNotFound({ spaceId, docId, timestamp });
|
||||
}
|
||||
|
||||
const fromSnapshot = await this.getDocSnapshot(spaceId, docId);
|
||||
|
||||
if (!fromSnapshot) {
|
||||
throw new DocNotFound({ spaceId, docId });
|
||||
}
|
||||
|
||||
// force create a new history record after rollback
|
||||
await this.createDocHistory(
|
||||
{
|
||||
...fromSnapshot,
|
||||
// override the editor to the one who requested the rollback
|
||||
editor: editorId,
|
||||
},
|
||||
true
|
||||
);
|
||||
// WARN:
|
||||
// we should never do the snapshot updating in recovering,
|
||||
// which is not the solution in CRDT.
|
||||
// let user revert in client and update the data in sync system
|
||||
// const change = this.generateChangeUpdate(fromSnapshot.bin, toSnapshot.bin);
|
||||
// await this.pushDocUpdates(spaceId, docId, [change]);
|
||||
|
||||
metrics.doc
|
||||
.counter('history_recovered_counter', {
|
||||
description: 'How many times history recovered request happened',
|
||||
})
|
||||
.add(1);
|
||||
}
|
||||
|
||||
protected async createDocHistory(snapshot: DocRecord, force = false) {
|
||||
protected async createDocHistory(snapshot: DocRecord) {
|
||||
const last = await this.lastDocHistory(snapshot.spaceId, snapshot.docId);
|
||||
|
||||
let shouldCreateHistory = false;
|
||||
@@ -317,11 +232,9 @@ export class PgWorkspaceDocStorageAdapter extends DocStorageAdapter {
|
||||
// no change
|
||||
shouldCreateHistory = false;
|
||||
} else if (
|
||||
// force
|
||||
force ||
|
||||
// last history created before interval in configs
|
||||
lastHistoryTimestamp <
|
||||
snapshot.timestamp - this.options.historyMinInterval(snapshot.spaceId)
|
||||
snapshot.timestamp - this.options.historyMinInterval(snapshot.spaceId)
|
||||
) {
|
||||
shouldCreateHistory = true;
|
||||
}
|
||||
@@ -389,21 +302,14 @@ export class PgWorkspaceDocStorageAdapter extends DocStorageAdapter {
|
||||
}
|
||||
|
||||
protected async setDocSnapshot(snapshot: DocRecord) {
|
||||
if (this.isEmptyBin(snapshot.bin)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const blob = Buffer.from(snapshot.bin);
|
||||
const updatedSnapshot = await this.models.doc.upsert({
|
||||
spaceId: snapshot.spaceId,
|
||||
docId: snapshot.docId,
|
||||
blob,
|
||||
timestamp: snapshot.timestamp,
|
||||
editorId: snapshot.editor,
|
||||
});
|
||||
|
||||
return !!updatedSnapshot;
|
||||
return await this.runtime.upsertDocSnapshot(
|
||||
snapshot.spaceId,
|
||||
snapshot.docId,
|
||||
Buffer.from(snapshot.bin),
|
||||
snapshot.timestamp,
|
||||
snapshot.editor
|
||||
);
|
||||
} catch (e) {
|
||||
metrics.doc.counter('snapshot_upsert_failed').add(1);
|
||||
this.logger.error('Failed to upsert snapshot', e);
|
||||
|
||||
@@ -1,363 +0,0 @@
|
||||
import * as Y from 'yjs';
|
||||
|
||||
const TREE_DIFF_LIMIT = 12;
|
||||
|
||||
type ComparableTree =
|
||||
| null
|
||||
| boolean
|
||||
| number
|
||||
| string
|
||||
| ComparableTree[]
|
||||
| { [key: string]: ComparableTree };
|
||||
|
||||
export type CodecCompareResult = {
|
||||
matches: boolean;
|
||||
treeDiff?: string[];
|
||||
};
|
||||
|
||||
function loadAndReencodeWithYjs(binary: Buffer): Buffer {
|
||||
const doc = new Y.Doc();
|
||||
Y.applyUpdate(doc, binary);
|
||||
|
||||
return Buffer.from(Y.encodeStateAsUpdate(doc));
|
||||
}
|
||||
|
||||
function sortObjectEntries(
|
||||
object: Record<string, unknown>
|
||||
): Array<[string, ComparableTree]> {
|
||||
return Object.entries(object)
|
||||
.filter(([, value]) => value !== undefined)
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
.map(([key, value]) => [key, serializeYValue(value)]);
|
||||
}
|
||||
|
||||
function isPlainObject(value: object): value is Record<string, unknown> {
|
||||
return Object.getPrototypeOf(value) === Object.prototype;
|
||||
}
|
||||
|
||||
function getConstructorName(value: unknown): string | undefined {
|
||||
if (!value || typeof value !== 'object') {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return value.constructor?.name;
|
||||
}
|
||||
|
||||
function serializeItemContent(content: {
|
||||
arr?: unknown[];
|
||||
embed?: unknown;
|
||||
str?: string;
|
||||
type?: unknown;
|
||||
}): ComparableTree {
|
||||
if (content.type !== undefined) {
|
||||
return serializeYValue(content.type);
|
||||
}
|
||||
|
||||
if (Array.isArray(content.arr)) {
|
||||
if (content.arr.length === 1) {
|
||||
return serializeYValue(content.arr[0]);
|
||||
}
|
||||
|
||||
return content.arr.map(item => serializeYValue(item));
|
||||
}
|
||||
|
||||
if (typeof content.str === 'string') {
|
||||
return content.str;
|
||||
}
|
||||
|
||||
if (content.embed !== undefined) {
|
||||
return serializeYValue(content.embed);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function serializeMapItems(items: Map<string, { content: unknown }>) {
|
||||
return Object.fromEntries(
|
||||
Array.from(items.entries())
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
.map(([key, item]) => [
|
||||
key,
|
||||
serializeItemContent(
|
||||
item.content as Parameters<typeof serializeItemContent>[0]
|
||||
),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
function serializeSequenceItems(
|
||||
start: {
|
||||
content: unknown;
|
||||
deleted?: boolean;
|
||||
right: unknown;
|
||||
} | null
|
||||
): ComparableTree[] {
|
||||
const result: ComparableTree[] = [];
|
||||
let current = start;
|
||||
|
||||
while (current) {
|
||||
if (!current.deleted) {
|
||||
const content = current.content as Parameters<
|
||||
typeof serializeItemContent
|
||||
>[0];
|
||||
const serialized = serializeItemContent(content);
|
||||
|
||||
if (Array.isArray(serialized) && Array.isArray(content.arr)) {
|
||||
result.push(...serialized);
|
||||
} else {
|
||||
result.push(serialized);
|
||||
}
|
||||
}
|
||||
current = current.right as typeof current;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function serializeAbstractType(value: {
|
||||
_map?: Map<string, { content: unknown }>;
|
||||
_start?: {
|
||||
content: unknown;
|
||||
deleted?: boolean;
|
||||
right: unknown;
|
||||
} | null;
|
||||
nodeName?: string;
|
||||
}) {
|
||||
const map = value._map ? serializeMapItems(value._map) : {};
|
||||
const children = serializeSequenceItems(value._start ?? null);
|
||||
const constructorName = getConstructorName(value);
|
||||
|
||||
if (value.nodeName || constructorName === 'YXmlElement') {
|
||||
return {
|
||||
nodeName: value.nodeName ?? 'xml',
|
||||
...(Object.keys(map).length ? { attrs: map } : null),
|
||||
...(children.length ? { children } : null),
|
||||
};
|
||||
}
|
||||
|
||||
if (Object.keys(map).length && !children.length) {
|
||||
return map;
|
||||
}
|
||||
|
||||
if (!Object.keys(map).length) {
|
||||
if (constructorName === 'YArray') {
|
||||
return children;
|
||||
}
|
||||
|
||||
if (constructorName === 'YText' || constructorName === 'YXmlText') {
|
||||
return children.join('');
|
||||
}
|
||||
|
||||
if (children.every(child => typeof child === 'string')) {
|
||||
return children.join('');
|
||||
}
|
||||
|
||||
if (children.length === 1) {
|
||||
return children[0] ?? null;
|
||||
}
|
||||
|
||||
return children;
|
||||
}
|
||||
|
||||
return {
|
||||
...map,
|
||||
children,
|
||||
};
|
||||
}
|
||||
|
||||
function serializeYValue(value: unknown): ComparableTree {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (
|
||||
typeof value === 'boolean' ||
|
||||
typeof value === 'number' ||
|
||||
typeof value === 'string'
|
||||
) {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (value instanceof Uint8Array) {
|
||||
return `Uint8Array(${value.length})`;
|
||||
}
|
||||
|
||||
const constructorName = getConstructorName(value);
|
||||
|
||||
// Ignore map field storage order. Compare sorted keys only.
|
||||
if (
|
||||
value instanceof Y.Map ||
|
||||
constructorName === 'YMap' ||
|
||||
value instanceof Y.Array ||
|
||||
constructorName === 'YArray' ||
|
||||
value instanceof Y.Text ||
|
||||
constructorName === 'YText' ||
|
||||
value instanceof Y.XmlText ||
|
||||
constructorName === 'YXmlText' ||
|
||||
value instanceof Y.XmlElement ||
|
||||
constructorName === 'YXmlElement' ||
|
||||
value instanceof Y.XmlFragment ||
|
||||
constructorName === 'YXmlFragment' ||
|
||||
(typeof value === 'object' &&
|
||||
value !== null &&
|
||||
('_map' in value || '_start' in value))
|
||||
) {
|
||||
return serializeAbstractType(
|
||||
value as Parameters<typeof serializeAbstractType>[0]
|
||||
);
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return value.map(item => serializeYValue(item));
|
||||
}
|
||||
|
||||
if (typeof value === 'object' && isPlainObject(value)) {
|
||||
return Object.fromEntries(sortObjectEntries(value));
|
||||
}
|
||||
|
||||
if (typeof value === 'object') {
|
||||
return Object.prototype.toString.call(value);
|
||||
}
|
||||
|
||||
return String(value);
|
||||
}
|
||||
|
||||
function serializeYDoc(binary: Buffer): ComparableTree {
|
||||
const doc = new Y.Doc();
|
||||
Y.applyUpdate(doc, binary);
|
||||
|
||||
// Ignore top-level share/map ordering too.
|
||||
return Object.fromEntries(
|
||||
Array.from(doc.share.entries())
|
||||
.sort(([left], [right]) => left.localeCompare(right))
|
||||
.map(([key, value]) => [key, serializeYValue(value)])
|
||||
);
|
||||
}
|
||||
|
||||
export function serializeCodecBinaryForDebug(binary: Buffer): ComparableTree {
|
||||
return serializeYDoc(binary);
|
||||
}
|
||||
|
||||
function formatTreeValue(value: ComparableTree): string {
|
||||
const text = JSON.stringify(value);
|
||||
if (!text) return String(value);
|
||||
return text.length > 120 ? `${text.slice(0, 117)}...` : text;
|
||||
}
|
||||
|
||||
function diffTrees(
|
||||
yjsTree: ComparableTree,
|
||||
yoctoTree: ComparableTree,
|
||||
path = '$',
|
||||
diffs: string[] = []
|
||||
): string[] {
|
||||
if (diffs.length >= TREE_DIFF_LIMIT) {
|
||||
return diffs;
|
||||
}
|
||||
|
||||
if (Object.is(yjsTree, yoctoTree)) {
|
||||
return diffs;
|
||||
}
|
||||
|
||||
if (Array.isArray(yjsTree) && Array.isArray(yoctoTree)) {
|
||||
const maxLength = Math.max(yjsTree.length, yoctoTree.length);
|
||||
for (let index = 0; index < maxLength; index += 1) {
|
||||
if (diffs.length >= TREE_DIFF_LIMIT) {
|
||||
break;
|
||||
}
|
||||
const yjsValue = yjsTree[index];
|
||||
const yoctoValue = yoctoTree[index];
|
||||
if (index >= yjsTree.length) {
|
||||
diffs.push(
|
||||
`${path}[${index}] only exists in yocto: ${formatTreeValue(yoctoValue ?? null)}`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (index >= yoctoTree.length) {
|
||||
diffs.push(
|
||||
`${path}[${index}] only exists in yjs: ${formatTreeValue(yjsValue ?? null)}`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
diffTrees(
|
||||
yjsValue ?? null,
|
||||
yoctoValue ?? null,
|
||||
`${path}[${index}]`,
|
||||
diffs
|
||||
);
|
||||
}
|
||||
|
||||
return diffs;
|
||||
}
|
||||
|
||||
if (
|
||||
yjsTree &&
|
||||
yoctoTree &&
|
||||
typeof yjsTree === 'object' &&
|
||||
typeof yoctoTree === 'object' &&
|
||||
!Array.isArray(yjsTree) &&
|
||||
!Array.isArray(yoctoTree)
|
||||
) {
|
||||
const keys = Array.from(
|
||||
new Set([...Object.keys(yjsTree), ...Object.keys(yoctoTree)])
|
||||
).sort((left, right) => left.localeCompare(right));
|
||||
|
||||
for (const key of keys) {
|
||||
if (diffs.length >= TREE_DIFF_LIMIT) {
|
||||
break;
|
||||
}
|
||||
const yjsValue = yjsTree[key];
|
||||
const yoctoValue = yoctoTree[key];
|
||||
if (!(key in yjsTree)) {
|
||||
diffs.push(
|
||||
`${path}.${key} only exists in yocto: ${formatTreeValue(yoctoValue ?? null)}`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (!(key in yoctoTree)) {
|
||||
diffs.push(
|
||||
`${path}.${key} only exists in yjs: ${formatTreeValue(yjsValue ?? null)}`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
diffTrees(yjsValue ?? null, yoctoValue ?? null, `${path}.${key}`, diffs);
|
||||
}
|
||||
|
||||
return diffs;
|
||||
}
|
||||
|
||||
diffs.push(
|
||||
`${path}: yjs=${formatTreeValue(yjsTree)} yocto=${formatTreeValue(yoctoTree)}`
|
||||
);
|
||||
|
||||
return diffs;
|
||||
}
|
||||
|
||||
export function compareCodecResult(
|
||||
yBinary: Buffer,
|
||||
yoctoBinary: Buffer
|
||||
): CodecCompareResult {
|
||||
if (yBinary.equals(yoctoBinary)) {
|
||||
return { matches: true };
|
||||
}
|
||||
|
||||
const normalizedYBinary = loadAndReencodeWithYjs(yBinary);
|
||||
const normalizedYoctoBinary = loadAndReencodeWithYjs(yoctoBinary);
|
||||
|
||||
if (normalizedYBinary.equals(normalizedYoctoBinary)) {
|
||||
return { matches: true };
|
||||
}
|
||||
|
||||
const treeDiff = diffTrees(
|
||||
serializeYDoc(normalizedYBinary),
|
||||
serializeYDoc(normalizedYoctoBinary)
|
||||
);
|
||||
|
||||
if (treeDiff.length === 0) {
|
||||
return { matches: true };
|
||||
}
|
||||
|
||||
return {
|
||||
matches: false,
|
||||
treeDiff,
|
||||
};
|
||||
}
|
||||
@@ -1,19 +1,16 @@
|
||||
import type { Logger } from '@nestjs/common';
|
||||
import { chunk } from 'lodash-es';
|
||||
import * as Y from 'yjs';
|
||||
import { mergeUpdates as yjsMergeUpdatesInCore } from 'yjs';
|
||||
|
||||
import { metrics } from '../../base';
|
||||
import { mergeUpdatesInApplyWay as nativeMergeUpdatesInApplyWay } from '../../native';
|
||||
import { mergeUpdates as nativeMergeUpdates } from '../../native';
|
||||
|
||||
const SLOW_DOC_UPDATE_CODEC_MS = 250;
|
||||
|
||||
type CodecEngine = 'native' | 'yjs';
|
||||
type MetricStatus = 'ok' | 'error' | 'partial_error';
|
||||
type CodecLogger = Pick<Logger, 'warn' | 'error'>;
|
||||
type MetricStatus = 'ok' | 'error';
|
||||
|
||||
function recordCodecMetrics(
|
||||
operation: 'apply_updates' | 'merge_updates',
|
||||
operation: 'merge_updates',
|
||||
engine: CodecEngine,
|
||||
caller: string,
|
||||
status: MetricStatus,
|
||||
@@ -32,7 +29,7 @@ function recordCodecMetrics(
|
||||
}
|
||||
|
||||
function warnSlowCodecOperation(
|
||||
operation: 'apply_updates' | 'merge_updates',
|
||||
operation: 'merge_updates',
|
||||
engine: CodecEngine,
|
||||
caller: string,
|
||||
duration: number,
|
||||
@@ -85,40 +82,7 @@ function measureSyncCodecOperation<T>(
|
||||
}
|
||||
}
|
||||
|
||||
async function measureAsyncCodecOperation<T>(
|
||||
operation: 'merge_updates',
|
||||
engine: CodecEngine,
|
||||
updates: Uint8Array[],
|
||||
caller: string,
|
||||
logger: Pick<Logger, 'warn'> | undefined,
|
||||
fn: () => Promise<T>
|
||||
): Promise<T> {
|
||||
const start = performance.now();
|
||||
|
||||
try {
|
||||
const result = await fn();
|
||||
const duration = performance.now() - start;
|
||||
|
||||
recordCodecMetrics(operation, engine, caller, 'ok', duration);
|
||||
warnSlowCodecOperation(
|
||||
operation,
|
||||
engine,
|
||||
caller,
|
||||
duration,
|
||||
updates.length,
|
||||
logger
|
||||
);
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
const duration = performance.now() - start;
|
||||
|
||||
recordCodecMetrics(operation, engine, caller, 'error', duration);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export function applyUpdatesWithNative(
|
||||
export function mergeUpdatesWithNative(
|
||||
updates: Uint8Array[],
|
||||
caller: string,
|
||||
logger?: Pick<Logger, 'warn'>
|
||||
@@ -129,7 +93,7 @@ export function applyUpdatesWithNative(
|
||||
updates,
|
||||
caller,
|
||||
logger,
|
||||
() => nativeMergeUpdatesInApplyWay(updates.map(Buffer.from))
|
||||
() => nativeMergeUpdates(updates.map(Buffer.from))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -147,87 +111,3 @@ export function mergeUpdatesWithYjs(
|
||||
() => Buffer.from(yjsMergeUpdatesInCore(updates))
|
||||
);
|
||||
}
|
||||
|
||||
async function recoverDocWithYjs(
|
||||
updates: Uint8Array[],
|
||||
caller: string,
|
||||
logger?: CodecLogger
|
||||
): Promise<Y.Doc> {
|
||||
const doc = new Y.Doc();
|
||||
const chunks = chunk(updates, 10);
|
||||
let i = 0;
|
||||
let failedUpdates = 0;
|
||||
const start = performance.now();
|
||||
|
||||
try {
|
||||
await new Promise<void>(resolve => {
|
||||
Y.transact(doc, () => {
|
||||
const next = () => {
|
||||
const nextUpdates = chunks.at(i++);
|
||||
|
||||
if (nextUpdates?.length) {
|
||||
nextUpdates.forEach(update => {
|
||||
try {
|
||||
Y.applyUpdate(doc, update);
|
||||
} catch (error) {
|
||||
failedUpdates += 1;
|
||||
metrics.doc.counter('apply_update_failures').add(1, {
|
||||
engine: 'yjs',
|
||||
caller,
|
||||
});
|
||||
logger?.error('Failed to apply update', error);
|
||||
}
|
||||
});
|
||||
|
||||
// avoid applying too many updates in single round which will take the whole cpu time like dead lock
|
||||
setImmediate(() => {
|
||||
next();
|
||||
});
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
};
|
||||
|
||||
next();
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
const duration = performance.now() - start;
|
||||
|
||||
recordCodecMetrics('apply_updates', 'yjs', caller, 'error', duration);
|
||||
throw error;
|
||||
}
|
||||
|
||||
const duration = performance.now() - start;
|
||||
const status = failedUpdates > 0 ? 'partial_error' : 'ok';
|
||||
|
||||
recordCodecMetrics('apply_updates', 'yjs', caller, status, duration);
|
||||
warnSlowCodecOperation(
|
||||
'apply_updates',
|
||||
'yjs',
|
||||
caller,
|
||||
duration,
|
||||
updates.length,
|
||||
logger
|
||||
);
|
||||
|
||||
return doc;
|
||||
}
|
||||
|
||||
export async function applyUpdatesWithYjs(
|
||||
updates: Uint8Array[],
|
||||
caller: string,
|
||||
logger?: CodecLogger
|
||||
) {
|
||||
return measureAsyncCodecOperation(
|
||||
'merge_updates',
|
||||
'yjs',
|
||||
updates,
|
||||
caller,
|
||||
logger,
|
||||
async () => {
|
||||
const doc = await recoverDocWithYjs(updates, caller, logger);
|
||||
return Buffer.from(Y.encodeStateAsUpdate(doc));
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -1,75 +1,21 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
import { Config, metrics } from '../../base';
|
||||
import { QuotaService } from '../quota';
|
||||
import { compareCodecResult } from './codec-compare';
|
||||
import { applyUpdatesWithNative, applyUpdatesWithYjs } from './merge-updates';
|
||||
import { Config } from '../../base';
|
||||
import { QuotaService } from '../quota/service';
|
||||
import { mergeUpdatesWithNative, mergeUpdatesWithYjs } from './merge-updates';
|
||||
import { DocStorageOptions as IDocStorageOptions } from './storage';
|
||||
|
||||
@Injectable()
|
||||
export class DocStorageOptions implements IDocStorageOptions {
|
||||
private readonly logger = new Logger('DocStorageOptions');
|
||||
|
||||
constructor(
|
||||
private readonly config: Config,
|
||||
private readonly quota: QuotaService
|
||||
) {}
|
||||
|
||||
mergeUpdates = async (updates: Uint8Array[]) => {
|
||||
const yjsResult = await applyUpdatesWithYjs(
|
||||
updates,
|
||||
'doc.options.merge_updates',
|
||||
this.logger
|
||||
);
|
||||
|
||||
if (this.config.doc.experimental.yocto) {
|
||||
metrics.jwst.counter('codec_merge_counter').add(1);
|
||||
let log = false;
|
||||
let yoctoResult: Buffer | null = null;
|
||||
try {
|
||||
yoctoResult = applyUpdatesWithNative(
|
||||
updates,
|
||||
'doc.options.yocto_codec_compare',
|
||||
this.logger
|
||||
);
|
||||
const comparison = compareCodecResult(yjsResult, yoctoResult);
|
||||
if (!comparison.matches) {
|
||||
metrics.jwst.counter('codec_not_match').add(1);
|
||||
this.logger.warn(`yocto codec result doesn't match yjs codec result`);
|
||||
if (comparison.treeDiff?.length) {
|
||||
this.logger.warn(
|
||||
`yocto codec tree diff:\n${comparison.treeDiff.join('\n')}`
|
||||
);
|
||||
}
|
||||
log = true;
|
||||
if (env.dev) {
|
||||
this.logger.warn(`Expected:\n ${yjsResult.toString('hex')}`);
|
||||
this.logger.warn(`Result:\n ${yoctoResult.toString('hex')}`);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
metrics.jwst.counter('codec_fails_counter').add(1);
|
||||
this.logger.warn(`jwst apply update failed: ${e}`);
|
||||
log = true;
|
||||
}
|
||||
|
||||
if (log && env.dev) {
|
||||
this.logger.warn(
|
||||
`Updates: ${updates.map(u => Buffer.from(u).toString('hex')).join('\n')}`
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
env.namespaces.canary &&
|
||||
yoctoResult &&
|
||||
yoctoResult.length > 2 /* simple test for non-empty yjs binary */
|
||||
) {
|
||||
return yoctoResult;
|
||||
}
|
||||
}
|
||||
|
||||
return yjsResult;
|
||||
};
|
||||
mergeUpdates = (updates: Uint8Array[]) =>
|
||||
this.config.doc.experimental.yocto
|
||||
? mergeUpdatesWithNative(updates, 'doc.options.merge_updates')
|
||||
: mergeUpdatesWithYjs(updates, 'doc.options.merge_updates');
|
||||
|
||||
historyMaxAge = async (spaceId: string) => {
|
||||
const quota = await this.quota.getWorkspaceQuota(spaceId);
|
||||
|
||||
@@ -243,7 +243,8 @@ export class DatabaseDocReader extends DocReader {
|
||||
guid: string,
|
||||
fullContent?: boolean
|
||||
): Promise<PageDocContent | null> {
|
||||
const docBinary = await this.workspace.getDocBinNative(workspaceId, guid);
|
||||
const record = await this.workspace.getDoc(workspaceId, guid);
|
||||
const docBinary = record?.bin;
|
||||
if (!docBinary) return null;
|
||||
return this.parseDocContent(docBinary, fullContent ? -1 : 150);
|
||||
}
|
||||
|
||||
@@ -1,29 +1,22 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { Transactional } from '@nestjs-cls/transactional';
|
||||
import { TransactionalAdapterPrisma } from '@nestjs-cls/transactional-adapter-prisma';
|
||||
import {
|
||||
applyUpdate,
|
||||
diffUpdate,
|
||||
Doc,
|
||||
encodeStateAsUpdate,
|
||||
encodeStateVector,
|
||||
encodeStateVectorFromUpdate,
|
||||
UndoManager,
|
||||
} from 'yjs';
|
||||
import { diffUpdate, encodeStateVectorFromUpdate } from 'yjs';
|
||||
|
||||
import { CallMetric, metrics } from '../../../base';
|
||||
import {
|
||||
CallMetric,
|
||||
DocUpdateInvalid,
|
||||
DocUpdateTooLarge,
|
||||
DocValidationUnavailable,
|
||||
} from '../../../base';
|
||||
import { validateDocUpdate } from '../../../native';
|
||||
import { applyUpdatesWithNative, mergeUpdatesWithYjs } from '../merge-updates';
|
||||
import { mergeUpdatesWithYjs } from '../merge-updates';
|
||||
import { Connection } from './connection';
|
||||
import { SingletonLocker } from './lock';
|
||||
|
||||
const DOC_UPDATE_VALIDATE_TIMEOUT_MS = 1000;
|
||||
const DOC_UPDATE_VALIDATE_MAX_BYTES = 32 * 1024 * 1024;
|
||||
|
||||
async function nativeApplyUpdates(updates: Uint8Array[]): Promise<Uint8Array> {
|
||||
return applyUpdatesWithNative(updates, 'doc.storage.squash.native');
|
||||
}
|
||||
|
||||
async function yjsMergeUpdates(updates: Uint8Array[]): Promise<Uint8Array> {
|
||||
return mergeUpdatesWithYjs(updates, 'doc.storage.squash.yjs');
|
||||
}
|
||||
@@ -85,44 +78,24 @@ export abstract class DocStorageAdapter extends Connection {
|
||||
);
|
||||
}
|
||||
|
||||
protected async filterValidDocUpdates(
|
||||
spaceId: string,
|
||||
docId: string,
|
||||
updates: Uint8Array[]
|
||||
) {
|
||||
const valid: Uint8Array[] = [];
|
||||
protected async assertValidDocUpdates(updates: Uint8Array[]) {
|
||||
for (const update of updates) {
|
||||
const reason = await this.invalidDocUpdateReason(update);
|
||||
if (reason) {
|
||||
metrics.doc.counter('doc_update_rejected').add(1, { reason });
|
||||
this.logger.warn(
|
||||
`Dropped invalid doc update, spaceId: ${spaceId}, docId: ${docId}, reason: ${reason}, size: ${update.length}`
|
||||
);
|
||||
continue;
|
||||
if (update.length > DOC_UPDATE_VALIDATE_MAX_BYTES) {
|
||||
throw new DocUpdateTooLarge();
|
||||
}
|
||||
let valid: boolean;
|
||||
try {
|
||||
valid = await validateDocUpdate(Buffer.from(update), {
|
||||
timeoutMs: DOC_UPDATE_VALIDATE_TIMEOUT_MS,
|
||||
});
|
||||
} catch (error) {
|
||||
const unavailable = new DocValidationUnavailable();
|
||||
unavailable.cause = error;
|
||||
throw unavailable;
|
||||
}
|
||||
if (!valid) {
|
||||
throw new DocUpdateInvalid();
|
||||
}
|
||||
valid.push(update);
|
||||
}
|
||||
return valid;
|
||||
}
|
||||
|
||||
private async invalidDocUpdateReason(update: Uint8Array) {
|
||||
if (update.length === 2 && update[0] === 0 && update[1] === 0) {
|
||||
return null;
|
||||
}
|
||||
if (update.length > DOC_UPDATE_VALIDATE_MAX_BYTES) {
|
||||
return 'oversized';
|
||||
}
|
||||
|
||||
try {
|
||||
return (await validateDocUpdate(Buffer.from(update), {
|
||||
timeoutMs: DOC_UPDATE_VALIDATE_TIMEOUT_MS,
|
||||
}))
|
||||
? null
|
||||
: 'invalid';
|
||||
} catch (err) {
|
||||
this.logger.warn('Doc update validation failed', err);
|
||||
metrics.doc.counter('doc_update_validation_failed').add(1);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -155,27 +128,6 @@ export abstract class DocStorageAdapter extends Connection {
|
||||
return { doc: snapshot, snapshotUpdated: false };
|
||||
}
|
||||
|
||||
/// get final binary only but not updating the snapshot in database
|
||||
async getDocBinNative(
|
||||
spaceId: string,
|
||||
docId: string
|
||||
): Promise<Uint8Array | undefined> {
|
||||
await using _lock = await this.lockDocForUpdate(spaceId, docId);
|
||||
|
||||
const snapshot = await this.getDocSnapshot(spaceId, docId);
|
||||
const updates = await this.getDocUpdates(spaceId, docId);
|
||||
|
||||
if (updates.length) {
|
||||
const docUpdate = await this.squash(
|
||||
snapshot ? [snapshot, ...updates] : updates,
|
||||
nativeApplyUpdates
|
||||
);
|
||||
return docUpdate.bin;
|
||||
}
|
||||
|
||||
return snapshot?.bin;
|
||||
}
|
||||
|
||||
@Transactional<TransactionalAdapterPrisma>({ timeout: 60000 })
|
||||
protected async squashUpdatesToSnapshot(
|
||||
spaceId: string,
|
||||
@@ -245,8 +197,8 @@ export abstract class DocStorageAdapter extends Connection {
|
||||
editorId: string,
|
||||
expectedPermissionGeneration?: number,
|
||||
writeIntent?: 'update_doc' | 'create_doc',
|
||||
permissionDocId?: string
|
||||
): Promise<number>;
|
||||
protocolVersion?: number
|
||||
): Promise<{ timestamp: number; created: boolean }>;
|
||||
|
||||
abstract pushDocUpdatesTrusted(
|
||||
spaceId: string,
|
||||
@@ -257,30 +209,6 @@ export abstract class DocStorageAdapter extends Connection {
|
||||
|
||||
abstract deleteDoc(spaceId: string, docId: string): Promise<void>;
|
||||
abstract deleteSpace(spaceId: string): Promise<void>;
|
||||
async rollbackDoc(
|
||||
spaceId: string,
|
||||
docId: string,
|
||||
timestamp: number,
|
||||
editorId: string
|
||||
): Promise<void> {
|
||||
await using _lock = await this.lockDocForUpdate(spaceId, docId);
|
||||
const toSnapshot = await this.getDocHistory(spaceId, docId, timestamp);
|
||||
if (!toSnapshot) {
|
||||
throw new Error('Can not find the version to rollback to.');
|
||||
}
|
||||
|
||||
const fromSnapshot = await this.getDocSnapshot(spaceId, docId);
|
||||
|
||||
if (!fromSnapshot) {
|
||||
throw new Error('Can not find the current version of the doc.');
|
||||
}
|
||||
|
||||
const change = this.generateChangeUpdate(fromSnapshot.bin, toSnapshot.bin);
|
||||
await this.pushDocUpdates(spaceId, docId, [change], editorId);
|
||||
// force create a new history record after rollback
|
||||
await this.createDocHistory(fromSnapshot, true);
|
||||
}
|
||||
|
||||
abstract getSpaceDocTimestamps(
|
||||
spaceId: string,
|
||||
after?: number
|
||||
@@ -312,10 +240,7 @@ export abstract class DocStorageAdapter extends Connection {
|
||||
updates: DocUpdate[]
|
||||
): Promise<number>;
|
||||
|
||||
protected abstract createDocHistory(
|
||||
snapshot: DocRecord,
|
||||
force?: boolean
|
||||
): Promise<boolean>;
|
||||
protected abstract createDocHistory(snapshot: DocRecord): Promise<boolean>;
|
||||
|
||||
@CallMetric('doc', 'squash')
|
||||
protected async squash(
|
||||
@@ -348,24 +273,4 @@ export abstract class DocStorageAdapter extends Connection {
|
||||
): Promise<AsyncDisposable> {
|
||||
return this.locker.lock(`workspace:${spaceId}:update`, docId);
|
||||
}
|
||||
|
||||
protected generateChangeUpdate(newerBin: Uint8Array, olderBin: Uint8Array) {
|
||||
const newerDoc = new Doc();
|
||||
applyUpdate(newerDoc, newerBin);
|
||||
const olderDoc = new Doc();
|
||||
applyUpdate(olderDoc, olderBin);
|
||||
|
||||
const newerState = encodeStateVector(newerDoc);
|
||||
const olderState = encodeStateVector(olderDoc);
|
||||
|
||||
const diff = encodeStateAsUpdate(newerDoc, olderState);
|
||||
|
||||
const undoManager = new UndoManager(Array.from(newerDoc.share.values()));
|
||||
|
||||
applyUpdate(olderDoc, diff);
|
||||
|
||||
undoManager.undo();
|
||||
|
||||
return encodeStateAsUpdate(olderDoc, newerState);
|
||||
}
|
||||
}
|
||||
@@ -3,12 +3,11 @@ import { nanoid } from 'nanoid';
|
||||
|
||||
import { EventBus } from '../../base';
|
||||
import {
|
||||
addDocToRootDoc,
|
||||
createDocWithMarkdown,
|
||||
isOrdinaryWorkspaceDoc,
|
||||
updateDocProperties,
|
||||
updateDocTitle,
|
||||
updateDocWithMarkdown,
|
||||
updateRootDocMetaTitle,
|
||||
} from '../../native';
|
||||
import { PgWorkspaceDocStorageAdapter } from './adapters/workspace';
|
||||
|
||||
@@ -57,23 +56,6 @@ export class DocWriter {
|
||||
markdown: string,
|
||||
editorId: string
|
||||
): Promise<CreateDocResult> {
|
||||
// Fetch workspace root doc first - reject if not found
|
||||
// The root doc (docId = workspaceId) contains meta.pages array
|
||||
const rootDoc = await this.storage.getDoc(workspaceId, workspaceId);
|
||||
if (!rootDoc?.bin) {
|
||||
throw new NotFoundException(
|
||||
`Workspace ${workspaceId} not found or has no root document`
|
||||
);
|
||||
}
|
||||
|
||||
const rootDocBin = Buffer.isBuffer(rootDoc.bin)
|
||||
? rootDoc.bin
|
||||
: Buffer.from(
|
||||
rootDoc.bin.buffer,
|
||||
rootDoc.bin.byteOffset,
|
||||
rootDoc.bin.byteLength
|
||||
);
|
||||
|
||||
const docId = nanoid();
|
||||
|
||||
this.logger.debug(
|
||||
@@ -86,27 +68,7 @@ export class DocWriter {
|
||||
timestampMs: Date.now(),
|
||||
});
|
||||
|
||||
// Prepare root doc update to register the new document
|
||||
const rootDocUpdate = addDocToRootDoc(rootDocBin, docId, title);
|
||||
|
||||
// Push both updates together - root doc first, then the new doc
|
||||
const rootTimestamp = await this.storage.pushDocUpdates(
|
||||
workspaceId,
|
||||
workspaceId,
|
||||
[rootDocUpdate],
|
||||
editorId,
|
||||
undefined,
|
||||
'create_doc'
|
||||
);
|
||||
this.emitDocUpdatesPushed({
|
||||
spaceId: workspaceId,
|
||||
docId: workspaceId,
|
||||
updates: [rootDocUpdate],
|
||||
timestamp: rootTimestamp,
|
||||
editor: editorId,
|
||||
});
|
||||
|
||||
const docTimestamp = await this.storage.pushDocUpdates(
|
||||
const { timestamp: docTimestamp } = await this.storage.pushDocUpdates(
|
||||
workspaceId,
|
||||
docId,
|
||||
[binary],
|
||||
@@ -132,9 +94,7 @@ export class DocWriter {
|
||||
editorId
|
||||
);
|
||||
|
||||
this.logger.debug(
|
||||
`Created and registered doc ${docId} in workspace ${workspaceId}`
|
||||
);
|
||||
this.logger.debug(`Created doc ${docId} in workspace ${workspaceId}`);
|
||||
|
||||
return { docId };
|
||||
}
|
||||
@@ -184,7 +144,7 @@ export class DocWriter {
|
||||
});
|
||||
|
||||
// Push only the delta changes
|
||||
const timestamp = await this.storage.pushDocUpdates(
|
||||
const { timestamp } = await this.storage.pushDocUpdates(
|
||||
workspaceId,
|
||||
docId,
|
||||
[delta],
|
||||
@@ -233,13 +193,6 @@ export class DocWriter {
|
||||
throw new NotFoundException(`Document ${docId} not found`);
|
||||
}
|
||||
|
||||
const rootDoc = await this.storage.getDoc(workspaceId, workspaceId);
|
||||
if (!rootDoc?.bin) {
|
||||
throw new NotFoundException(
|
||||
`Workspace ${workspaceId} not found or has no root document`
|
||||
);
|
||||
}
|
||||
|
||||
const existingBinary = Buffer.isBuffer(existingDoc.bin)
|
||||
? existingDoc.bin
|
||||
: Buffer.from(
|
||||
@@ -247,39 +200,8 @@ export class DocWriter {
|
||||
existingDoc.bin.byteOffset,
|
||||
existingDoc.bin.byteLength
|
||||
);
|
||||
const rootDocBin = Buffer.isBuffer(rootDoc.bin)
|
||||
? rootDoc.bin
|
||||
: Buffer.from(
|
||||
rootDoc.bin.buffer,
|
||||
rootDoc.bin.byteOffset,
|
||||
rootDoc.bin.byteLength
|
||||
);
|
||||
|
||||
const titleUpdate = updateDocTitle(existingBinary, meta.title, docId);
|
||||
const rootMetaUpdate = updateRootDocMetaTitle(
|
||||
rootDocBin,
|
||||
docId,
|
||||
meta.title
|
||||
);
|
||||
|
||||
const rootTimestamp = await this.storage.pushDocUpdates(
|
||||
workspaceId,
|
||||
workspaceId,
|
||||
[rootMetaUpdate],
|
||||
editorId,
|
||||
undefined,
|
||||
'update_doc',
|
||||
docId
|
||||
);
|
||||
this.emitDocUpdatesPushed({
|
||||
spaceId: workspaceId,
|
||||
docId: workspaceId,
|
||||
updates: [rootMetaUpdate],
|
||||
timestamp: rootTimestamp,
|
||||
editor: editorId,
|
||||
});
|
||||
|
||||
const docTimestamp = await this.storage.pushDocUpdates(
|
||||
const { timestamp: docTimestamp } = await this.storage.pushDocUpdates(
|
||||
workspaceId,
|
||||
docId,
|
||||
[titleUpdate],
|
||||
@@ -326,11 +248,7 @@ export class DocWriter {
|
||||
props: { createdBy?: string; updatedBy?: string },
|
||||
editorId: string
|
||||
) {
|
||||
if (
|
||||
workspaceId === docId ||
|
||||
docId.startsWith('db$') ||
|
||||
docId.startsWith('userdata$')
|
||||
) {
|
||||
if (!isOrdinaryWorkspaceDoc(workspaceId, docId)) {
|
||||
return;
|
||||
}
|
||||
if (!props.createdBy && !props.updatedBy) {
|
||||
@@ -360,14 +278,11 @@ export class DocWriter {
|
||||
return;
|
||||
}
|
||||
|
||||
const timestamp = await this.storage.pushDocUpdates(
|
||||
const timestamp = await this.storage.pushDocUpdatesTrusted(
|
||||
workspaceId,
|
||||
propertiesDocId,
|
||||
[update],
|
||||
editorId,
|
||||
undefined,
|
||||
'update_doc',
|
||||
docId
|
||||
editorId
|
||||
);
|
||||
this.emitDocUpdatesPushed({
|
||||
spaceId: workspaceId,
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
import ava, { TestFn } from 'ava';
|
||||
|
||||
import {
|
||||
createTestingModule,
|
||||
type TestingModule,
|
||||
} from '../../../__tests__/utils';
|
||||
import { DocRole, Models, User, Workspace } from '../../../models';
|
||||
import { EventsListener } from '../event';
|
||||
import { PermissionModule } from '../index';
|
||||
|
||||
interface Context {
|
||||
module: TestingModule;
|
||||
models: Models;
|
||||
listener: EventsListener;
|
||||
}
|
||||
|
||||
const test = ava as TestFn<Context>;
|
||||
|
||||
let owner: User;
|
||||
let workspace: Workspace;
|
||||
|
||||
test.before(async t => {
|
||||
const module = await createTestingModule({ imports: [PermissionModule] });
|
||||
t.context.module = module;
|
||||
t.context.models = module.get(Models);
|
||||
t.context.listener = module.get(EventsListener);
|
||||
});
|
||||
|
||||
test.beforeEach(async t => {
|
||||
await t.context.module.initTestingDB();
|
||||
owner = await t.context.models.user.create({
|
||||
email: `${randomUUID()}@affine.pro`,
|
||||
});
|
||||
workspace = await t.context.models.workspace.create(owner.id);
|
||||
});
|
||||
|
||||
test.after.always(async t => {
|
||||
await t.context.module.close();
|
||||
});
|
||||
|
||||
test('should ignore default owner event when workspace does not exist', async t => {
|
||||
await t.notThrowsAsync(async () => {
|
||||
await t.context.listener.setDefaultPageOwner({
|
||||
workspaceId: randomUUID(),
|
||||
docId: randomUUID(),
|
||||
editor: owner.id,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('should ignore default owner event when editor does not exist', async t => {
|
||||
await t.notThrowsAsync(async () => {
|
||||
await t.context.listener.setDefaultPageOwner({
|
||||
workspaceId: workspace.id,
|
||||
docId: randomUUID(),
|
||||
editor: randomUUID(),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('should set owner when workspace and editor exist', async t => {
|
||||
const docId = randomUUID();
|
||||
await t.context.listener.setDefaultPageOwner({
|
||||
workspaceId: workspace.id,
|
||||
docId,
|
||||
editor: owner.id,
|
||||
});
|
||||
|
||||
const role = await t.context.models.docUser.get(
|
||||
workspace.id,
|
||||
docId,
|
||||
owner.id
|
||||
);
|
||||
t.is(role?.type, DocRole.Owner);
|
||||
});
|
||||
@@ -1,64 +0,0 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
|
||||
import { OnEvent } from '../../base';
|
||||
import { Models } from '../../models';
|
||||
|
||||
const IGNORED_PRISMA_CODES = new Set(['P2003', 'P2025', 'P2028']);
|
||||
|
||||
function isIgnorablePermissionEventError(error: unknown) {
|
||||
if (error instanceof Prisma.PrismaClientKnownRequestError) {
|
||||
return IGNORED_PRISMA_CODES.has(error.code);
|
||||
}
|
||||
if (error instanceof Prisma.PrismaClientUnknownRequestError) {
|
||||
return /transaction is aborted|transaction already closed/i.test(
|
||||
error.message
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class EventsListener {
|
||||
private readonly logger = new Logger(EventsListener.name);
|
||||
|
||||
constructor(private readonly models: Models) {}
|
||||
|
||||
@OnEvent('doc.created')
|
||||
async setDefaultPageOwner(payload: Events['doc.created']) {
|
||||
const { workspaceId, docId, editor } = payload;
|
||||
|
||||
if (!editor) {
|
||||
return;
|
||||
}
|
||||
|
||||
const workspace = await this.models.workspace.get(workspaceId);
|
||||
if (!workspace) {
|
||||
this.logger.warn(
|
||||
`Skip default doc owner event for missing workspace ${workspaceId}/${docId}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const user = await this.models.user.get(editor);
|
||||
if (!user) {
|
||||
this.logger.warn(
|
||||
`Skip default doc owner event for missing editor ${workspaceId}/${docId}/${editor}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await this.models.docUser.setOwner(workspaceId, docId, editor);
|
||||
} catch (error) {
|
||||
if (isIgnorablePermissionEventError(error)) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
this.logger.warn(
|
||||
`Ignore stale doc owner event for ${workspaceId}/${docId}/${editor}: ${message}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
import { AccessControllerBuilder } from './builder';
|
||||
import { EventsListener } from './event';
|
||||
import { PermissionService } from './service';
|
||||
|
||||
@Module({
|
||||
providers: [AccessControllerBuilder, EventsListener, PermissionService],
|
||||
providers: [AccessControllerBuilder, PermissionService],
|
||||
exports: [AccessControllerBuilder, PermissionService],
|
||||
})
|
||||
export class PermissionModule {}
|
||||
|
||||
@@ -284,22 +284,6 @@ export class StorageRuntimeProvider
|
||||
);
|
||||
}
|
||||
|
||||
async reconcileWorkspaceDocuments(workspaceId: string) {
|
||||
return await this.measured('reconcileWorkspaceDocuments', rt =>
|
||||
rt.reconcileWorkspaceDocuments(workspaceId)
|
||||
);
|
||||
}
|
||||
|
||||
async executeDocumentCleanupCandidates(
|
||||
workspaceId: string | null | undefined,
|
||||
gracePeriodDays: number,
|
||||
limit: number
|
||||
) {
|
||||
return await this.measured('executeDocumentCleanupCandidates', rt =>
|
||||
rt.executeDocumentCleanupCandidates(workspaceId, gracePeriodDays, limit)
|
||||
);
|
||||
}
|
||||
|
||||
async cleanupUnreferencedWorkspaceBlobs(
|
||||
workspaceId: string,
|
||||
gracePeriodDays: number,
|
||||
|
||||
@@ -30,7 +30,6 @@ test.beforeEach(t => {
|
||||
failedScopes: [],
|
||||
unknownPrefixSamples: [],
|
||||
}),
|
||||
reconcileWorkspaceDocuments: Sinon.stub().resolves({}),
|
||||
backfillMissingBlobMetadata: Sinon.stub().resolves({
|
||||
workspaceIds: [],
|
||||
upsertedMetadata: 0,
|
||||
@@ -51,11 +50,6 @@ test.beforeEach(t => {
|
||||
protectedByOtherRefs: 0,
|
||||
failed: 0,
|
||||
}),
|
||||
executeDocumentCleanupCandidates: Sinon.stub().resolves({
|
||||
serializationRetries: 0,
|
||||
failed: 0,
|
||||
effects: [],
|
||||
}),
|
||||
};
|
||||
t.context.event = { emitAsync: Sinon.stub().resolves(undefined) };
|
||||
t.context.db = {
|
||||
@@ -75,14 +69,14 @@ test('workspace sweep advances past failed workspaces and wraps for retry', asyn
|
||||
{ id: 'workspace-1', sid: 1 },
|
||||
{ id: 'workspace-2', sid: 2 },
|
||||
]);
|
||||
t.context.runtime.reconcileWorkspaceDocuments
|
||||
t.context.runtime.rebuildWorkspaceDocBlobRefs
|
||||
.onFirstCall()
|
||||
.rejects(new Error('broken workspace'));
|
||||
|
||||
const result = await t.context.job.reconcileWorkspaceBatch();
|
||||
|
||||
t.deepEqual(result, { scanned: 2, failures: 1, completed: false });
|
||||
t.is(t.context.runtime.reconcileWorkspaceDocuments.callCount, 2);
|
||||
t.is(t.context.runtime.rebuildWorkspaceDocBlobRefs.callCount, 2);
|
||||
t.true(t.context.runtime.cleanupUnreferencedWorkspaceBlobs.calledOnce);
|
||||
t.true(t.context.db.$executeRaw.calledOnce);
|
||||
t.deepEqual(JSON.parse(t.context.db.$executeRaw.lastCall.args[3]), {
|
||||
@@ -123,22 +117,3 @@ test('metadata sweep skips provider work when object storage is unavailable', as
|
||||
t.false(t.context.db.workspace.findMany.called);
|
||||
t.false(t.context.runtime.backfillMissingBlobMetadata.called);
|
||||
});
|
||||
|
||||
test('document cleanup records execution health without payload effects', async t => {
|
||||
t.context.runtime.executeDocumentCleanupCandidates.resolves({
|
||||
serializationRetries: 0,
|
||||
failed: 0,
|
||||
});
|
||||
t.context.db.$queryRaw.resolves([
|
||||
{
|
||||
marked: 0n,
|
||||
failed: 0n,
|
||||
failedWorkspaceCheckpoints: 0n,
|
||||
oldestFailedSeconds: null,
|
||||
},
|
||||
]);
|
||||
|
||||
await t.context.job.executeDocumentCleanup();
|
||||
|
||||
t.false(t.context.event.emitAsync.called);
|
||||
});
|
||||
@@ -9,7 +9,6 @@ import { StorageRuntimeProvider } from '../storage-runtime';
|
||||
|
||||
const WORKSPACE_BATCH_SIZE = 25;
|
||||
const OBJECT_BATCH_SIZE = 1_000;
|
||||
const DOCUMENT_CLEANUP_BATCH_SIZE = 100;
|
||||
const RECONCILIATION_LEASE_MS = 30 * 60 * 1000;
|
||||
|
||||
type SweepScope = 'metadata' | 'documents';
|
||||
@@ -39,7 +38,6 @@ export class StorageBlobJob {
|
||||
this.reconcileWorkspaceNamespaces(),
|
||||
this.reconcileWorkspaceBatch(),
|
||||
this.backfillBlobMetadata(),
|
||||
this.executeDocumentCleanup(),
|
||||
]).then(results => {
|
||||
for (const result of results) {
|
||||
if (result.status === 'rejected') {
|
||||
@@ -98,7 +96,6 @@ export class StorageBlobJob {
|
||||
return await this.runWorkspaceSweep(
|
||||
'documents',
|
||||
async (workspaceId, sid) => {
|
||||
await this.rt.reconcileWorkspaceDocuments(workspaceId);
|
||||
const refs = await this.rt.rebuildWorkspaceDocBlobRefs(
|
||||
workspaceId,
|
||||
OBJECT_BATCH_SIZE
|
||||
@@ -124,22 +121,6 @@ export class StorageBlobJob {
|
||||
);
|
||||
}
|
||||
|
||||
async executeDocumentCleanup() {
|
||||
const result = await this.rt.executeDocumentCleanupCandidates(
|
||||
undefined,
|
||||
30,
|
||||
DOCUMENT_CLEANUP_BATCH_SIZE
|
||||
);
|
||||
metrics.storage
|
||||
.counter('document_cleanup_serialization_retry_total')
|
||||
.add(result.serializationRetries);
|
||||
metrics.storage
|
||||
.counter('document_cleanup_execute_failure_total')
|
||||
.add(result.failed);
|
||||
await this.recordDocumentCleanupHealth();
|
||||
return result;
|
||||
}
|
||||
|
||||
private async runWorkspaceSweep(
|
||||
scope: SweepScope,
|
||||
run: (workspaceId: string, sid: number) => Promise<void>
|
||||
@@ -252,40 +233,6 @@ export class StorageBlobJob {
|
||||
`;
|
||||
}
|
||||
|
||||
private async recordDocumentCleanupHealth() {
|
||||
const [health] = await this.db.$queryRaw<
|
||||
{
|
||||
marked: bigint;
|
||||
failed: bigint;
|
||||
failedWorkspaceCheckpoints: bigint;
|
||||
oldestFailedSeconds: number | null;
|
||||
}[]
|
||||
>`
|
||||
SELECT
|
||||
COUNT(*) FILTER (WHERE status = 'marked') AS marked,
|
||||
COUNT(*) FILTER (WHERE status = 'failed') AS failed,
|
||||
EXTRACT(EPOCH FROM CURRENT_TIMESTAMP -
|
||||
MIN(updated_at) FILTER (WHERE status = 'failed'))::double precision AS "oldestFailedSeconds",
|
||||
(SELECT COUNT(*) FROM storage_reconciliation_checkpoints
|
||||
WHERE kind = 'document_cleanup' AND status = 'failed') AS "failedWorkspaceCheckpoints"
|
||||
FROM document_cleanup_candidates
|
||||
`;
|
||||
if (!health) return;
|
||||
for (const [name, value] of [
|
||||
['document_cleanup_marked', health.marked],
|
||||
['document_cleanup_failed', health.failed],
|
||||
[
|
||||
'document_cleanup_failed_workspace_checkpoints',
|
||||
health.failedWorkspaceCheckpoints,
|
||||
],
|
||||
] as const) {
|
||||
metrics.storage.gauge(name).record(Number(value));
|
||||
}
|
||||
metrics.storage
|
||||
.gauge('document_cleanup_oldest_failed_seconds')
|
||||
.record(health.oldestFailedSeconds ?? 0);
|
||||
}
|
||||
|
||||
private async emitBlobUpdates(workspaceIds: string[]) {
|
||||
await Promise.all(
|
||||
[...new Set(workspaceIds)].map(workspaceId =>
|
||||
|
||||
@@ -20,6 +20,7 @@ import semver from 'semver';
|
||||
import { type Server, Socket } from 'socket.io';
|
||||
|
||||
import {
|
||||
AccessDenied,
|
||||
BadRequest,
|
||||
CallMetric,
|
||||
checkCanaryDateClientVersion,
|
||||
@@ -35,10 +36,7 @@ import {
|
||||
SyncPermissionGenerationChanged,
|
||||
} from '../../base';
|
||||
import { Models } from '../../models';
|
||||
import {
|
||||
authorizeReservedDocSubject,
|
||||
canonicalizeDocumentIdentity,
|
||||
} from '../../native';
|
||||
import { canonicalizeDocumentIdentity } from '../../native';
|
||||
import { CurrentUser } from '../auth';
|
||||
import {
|
||||
backendRuntimeErrorCode,
|
||||
@@ -50,7 +48,7 @@ import {
|
||||
PgUserspaceDocStorageAdapter,
|
||||
PgWorkspaceDocStorageAdapter,
|
||||
} from '../doc';
|
||||
import { applyUpdatesWithNative } from '../doc/merge-updates';
|
||||
import { mergeUpdatesWithNative } from '../doc/merge-updates';
|
||||
import {
|
||||
type DocAction,
|
||||
PermissionAccess,
|
||||
@@ -120,6 +118,7 @@ interface JoinSpaceBatchEntry {
|
||||
interface JoinSpaceBatchMessage {
|
||||
spaces: [JoinSpaceBatchEntry, ...JoinSpaceBatchEntry[]];
|
||||
clientVersion: string;
|
||||
protocolVersion: 2;
|
||||
}
|
||||
|
||||
interface LeaveSpaceMessage {
|
||||
@@ -136,6 +135,7 @@ interface PushDocUpdateMessage {
|
||||
spaceId: string;
|
||||
docId: string;
|
||||
update: string;
|
||||
intent: 'create' | 'update';
|
||||
}
|
||||
|
||||
interface BroadcastDocUpdatesMessage {
|
||||
@@ -238,7 +238,9 @@ function parseJoinSpaceBatchMessage(message: unknown): JoinSpaceBatchMessage {
|
||||
throw new BadRequest('Invalid space join batch payload.');
|
||||
}
|
||||
|
||||
const { spaces, clientVersion } = message;
|
||||
const { spaces, clientVersion, protocolVersion } = message;
|
||||
if (protocolVersion !== 2)
|
||||
throw new BadRequest('Sync protocol upgrade required.');
|
||||
if (!Array.isArray(spaces) || spaces.length === 0) {
|
||||
throw new BadRequest('Space join batch must not be empty.');
|
||||
}
|
||||
@@ -298,7 +300,7 @@ function parseJoinSpaceBatchMessage(message: unknown): JoinSpaceBatchMessage {
|
||||
duplicateKeys.add(key);
|
||||
}
|
||||
|
||||
return { spaces: entries, clientVersion };
|
||||
return { spaces: entries, clientVersion, protocolVersion };
|
||||
}
|
||||
|
||||
function parseLeaveSpaceBatchMessage(message: unknown): LeaveSpaceBatchMessage {
|
||||
@@ -347,6 +349,11 @@ export class SpaceSyncGateway
|
||||
private activeUsersFlushInFlight = false;
|
||||
private activeUsersFlushQueued = false;
|
||||
private readonly activeDocSockets = new Map<string, Set<Socket>>();
|
||||
private readonly socketProtocolVersions = new Map<string, number>();
|
||||
private readonly socketAdapters = new WeakMap<
|
||||
Socket,
|
||||
Record<SpaceType, SyncSocketAdapter>
|
||||
>();
|
||||
private readonly activeSocketDocs = new Map<string, Set<string>>();
|
||||
private readonly activeSocketDocActions = new Map<
|
||||
string,
|
||||
@@ -413,7 +420,7 @@ export class SpaceSyncGateway
|
||||
}
|
||||
|
||||
try {
|
||||
const merged = applyUpdatesWithNative(
|
||||
const merged = mergeUpdatesWithNative(
|
||||
updates,
|
||||
'socketio.broadcast',
|
||||
this.logger
|
||||
@@ -466,20 +473,6 @@ export class SpaceSyncGateway
|
||||
await this.ac.user(userId).doc(spaceId, docId).assert(action);
|
||||
}
|
||||
|
||||
private assertReservedDocSubject(
|
||||
spaceType: SpaceType,
|
||||
userId: string,
|
||||
workspaceId: string,
|
||||
docId: string
|
||||
) {
|
||||
if (
|
||||
spaceType === SpaceType.Workspace &&
|
||||
!authorizeReservedDocSubject(userId, workspaceId, docId)
|
||||
) {
|
||||
throw new SpaceAccessDenied({ spaceId: workspaceId });
|
||||
}
|
||||
}
|
||||
|
||||
private activeDocKey(spaceType: SpaceType, spaceId: string, docId: string) {
|
||||
return `${spaceType}:${spaceId}:${docId}`;
|
||||
}
|
||||
@@ -702,6 +695,7 @@ export class SpaceSyncGateway
|
||||
}
|
||||
|
||||
handleDisconnect(client: Socket) {
|
||||
this.socketProtocolVersions.delete(client.id);
|
||||
this.removeAllActiveDocSubscriptions(client);
|
||||
this.connectionCount = Math.max(0, this.connectionCount - 1);
|
||||
this.trackDisconnectedSocket(client.id);
|
||||
@@ -877,6 +871,23 @@ export class SpaceSyncGateway
|
||||
);
|
||||
}
|
||||
|
||||
@OnEvent('backendRuntime.invalidation')
|
||||
async onRuntimeInvalidation(hint: Events['backendRuntime.invalidation']) {
|
||||
if (hint.kind !== 'workspaceInventoryChanged' || !this.server) return;
|
||||
const room = `${SpaceType.Workspace}:${Room(hint.workspaceId, 'sync-027')}`;
|
||||
for (const client of this.server.sockets.sockets.values()) {
|
||||
if (
|
||||
client.rooms.has(room) &&
|
||||
this.socketProtocolVersions.get(client.id) !== 2
|
||||
)
|
||||
client.disconnect(true);
|
||||
}
|
||||
await this.revalidateActiveDocSubscriptions({
|
||||
spaceType: SpaceType.Workspace,
|
||||
spaceId: hint.workspaceId,
|
||||
});
|
||||
}
|
||||
|
||||
@OnEvent('doc.updates.pushed')
|
||||
onDocUpdatesPushed({
|
||||
spaceType,
|
||||
@@ -962,6 +973,13 @@ export class SpaceSyncGateway
|
||||
private async revalidateActiveDocSubscriptions(
|
||||
event: Events['sync.permissions.changed']
|
||||
) {
|
||||
this.server?.local
|
||||
.to(`${event.spaceType}:${Room(event.spaceId, 'sync-027')}`)
|
||||
.emit('space:broadcast-doc-invalidation', {
|
||||
spaceType: event.spaceType,
|
||||
spaceId: event.spaceId,
|
||||
inventoryChanged: true,
|
||||
});
|
||||
const spacePrefix = `${event.spaceType}:${event.spaceId}:`;
|
||||
const exactKey = event.docId
|
||||
? this.activeDocKey(event.spaceType, event.spaceId, event.docId)
|
||||
@@ -997,6 +1015,10 @@ export class SpaceSyncGateway
|
||||
);
|
||||
continue;
|
||||
}
|
||||
await this.ac
|
||||
.user(userId)
|
||||
.workspace(spaceId)
|
||||
.assert('Workspace.Sync');
|
||||
const before =
|
||||
await this.runtime.getSyncPermissionGenerationV1(spaceId);
|
||||
const [permission] = await this.ac
|
||||
@@ -1086,8 +1108,7 @@ export class SpaceSyncGateway
|
||||
}
|
||||
|
||||
selectAdapter(client: Socket, spaceType: SpaceType): SyncSocketAdapter {
|
||||
let adapters: Record<SpaceType, SyncSocketAdapter> = (client as any)
|
||||
.affineSyncAdapters;
|
||||
let adapters = this.socketAdapters.get(client);
|
||||
|
||||
if (!adapters) {
|
||||
const workspace = new WorkspaceSyncAdapter(
|
||||
@@ -1095,12 +1116,17 @@ export class SpaceSyncGateway
|
||||
this.workspace,
|
||||
this.ac,
|
||||
this.docReader,
|
||||
this.models
|
||||
this.models,
|
||||
() => this.socketProtocolVersions.get(client.id) ?? 0
|
||||
);
|
||||
const userspace = new UserspaceSyncAdapter(
|
||||
client,
|
||||
this.userspace,
|
||||
() => this.socketProtocolVersions.get(client.id) ?? 0
|
||||
);
|
||||
const userspace = new UserspaceSyncAdapter(client, this.userspace);
|
||||
|
||||
adapters = { workspace, userspace };
|
||||
(client as any).affineSyncAdapters = adapters;
|
||||
this.socketAdapters.set(client, adapters);
|
||||
}
|
||||
|
||||
return adapters[spaceType];
|
||||
@@ -1111,30 +1137,28 @@ export class SpaceSyncGateway
|
||||
@CurrentUser() user: CurrentUser,
|
||||
@ConnectedSocket() client: Socket,
|
||||
@MessageBody() message: unknown
|
||||
): Promise<EventResponse<{ clientId: string; success: boolean }>> {
|
||||
const { spaces, clientVersion } = parseJoinSpaceBatchMessage(message);
|
||||
): Promise<
|
||||
EventResponse<{ clientId: string; success: boolean; protocolVersion: 2 }>
|
||||
> {
|
||||
const { spaces, clientVersion, protocolVersion } =
|
||||
parseJoinSpaceBatchMessage(message);
|
||||
if (!isBatchWsClientVersion(clientVersion)) {
|
||||
this.rejectJoin(client);
|
||||
return { data: { clientId: client.id, success: false } };
|
||||
return { data: { clientId: client.id, success: false, protocolVersion } };
|
||||
}
|
||||
|
||||
const [first] = spaces;
|
||||
const adapter = this.selectAdapter(client, first.spaceType);
|
||||
|
||||
await adapter.assertAccessible(first.spaceId, user.id, 'Workspace.Sync');
|
||||
if (first.spaceType === SpaceType.Workspace)
|
||||
await this.runtime.ensureWorkspaceLifecycleV1(first.spaceId);
|
||||
this.socketProtocolVersions.set(client.id, protocolVersion);
|
||||
|
||||
const docSpaces = spaces.filter(
|
||||
(space): space is JoinSpaceBatchEntry & { docId: string } =>
|
||||
space.docId !== undefined
|
||||
);
|
||||
for (const space of docSpaces) {
|
||||
this.assertReservedDocSubject(
|
||||
space.spaceType,
|
||||
user.id,
|
||||
space.spaceId,
|
||||
space.docId
|
||||
);
|
||||
}
|
||||
const docActions = new Map<string, Set<DocAction>>();
|
||||
let permissionGeneration = 0;
|
||||
const rooms = new Set<string>();
|
||||
@@ -1239,7 +1263,7 @@ export class SpaceSyncGateway
|
||||
throw error;
|
||||
}
|
||||
|
||||
return { data: { clientId: client.id, success: true } };
|
||||
return { data: { clientId: client.id, success: true, protocolVersion } };
|
||||
}
|
||||
|
||||
@SubscribeMessage('space:leave-batch')
|
||||
@@ -1281,7 +1305,6 @@ export class SpaceSyncGateway
|
||||
@SubscribeMessage('space:load-doc')
|
||||
async onLoadSpaceDoc(
|
||||
@ConnectedSocket() client: Socket,
|
||||
@CurrentUser() user: CurrentUser,
|
||||
@MessageBody()
|
||||
{ spaceType, spaceId, docId, stateVector }: LoadDocMessage
|
||||
): Promise<
|
||||
@@ -1290,7 +1313,6 @@ export class SpaceSyncGateway
|
||||
const canonicalId = canonicalDocId(docId, spaceId);
|
||||
const adapter = this.selectAdapter(client, spaceType);
|
||||
adapter.assertIn(spaceId);
|
||||
this.assertReservedDocSubject(spaceType, user.id, spaceId, canonicalId);
|
||||
if (
|
||||
!this.hasActiveDocSubscription(client, spaceType, spaceId, canonicalId)
|
||||
) {
|
||||
@@ -1302,15 +1324,6 @@ export class SpaceSyncGateway
|
||||
spaceId,
|
||||
canonicalId
|
||||
);
|
||||
if (
|
||||
permissionGeneration === undefined ||
|
||||
(spaceType === SpaceType.Workspace &&
|
||||
permissionGeneration !==
|
||||
(await this.runtime.getSyncPermissionGenerationV1(spaceId)))
|
||||
) {
|
||||
this.removeActiveDocSubscription(client, spaceType, spaceId, canonicalId);
|
||||
throw new NotInSpace({ spaceId });
|
||||
}
|
||||
|
||||
const doc = await adapter.diff(
|
||||
spaceId,
|
||||
@@ -1318,6 +1331,28 @@ export class SpaceSyncGateway
|
||||
stateVector ? Buffer.from(stateVector, 'base64') : undefined
|
||||
);
|
||||
|
||||
const currentGeneration =
|
||||
spaceType === SpaceType.Workspace
|
||||
? await this.runtime.getSyncPermissionGenerationV1(spaceId)
|
||||
: permissionGeneration;
|
||||
if (
|
||||
permissionGeneration === undefined ||
|
||||
this.activeDocGeneration(client, spaceType, spaceId, canonicalId) !==
|
||||
permissionGeneration ||
|
||||
permissionGeneration !== currentGeneration
|
||||
) {
|
||||
if (
|
||||
this.activeDocGeneration(client, spaceType, spaceId, canonicalId) ===
|
||||
permissionGeneration
|
||||
)
|
||||
this.removeActiveDocSubscription(
|
||||
client,
|
||||
spaceType,
|
||||
spaceId,
|
||||
canonicalId
|
||||
);
|
||||
throw new NotInSpace({ spaceId });
|
||||
}
|
||||
if (!doc) {
|
||||
throw new DocNotFound({ spaceId, docId });
|
||||
}
|
||||
@@ -1338,7 +1373,6 @@ export class SpaceSyncGateway
|
||||
@MessageBody() { spaceType, spaceId, docId }: DeleteDocMessage
|
||||
): Promise<EventResponse<{ success: true }>> {
|
||||
docId = canonicalDocId(docId, spaceId);
|
||||
this.assertReservedDocSubject(spaceType, user.id, spaceId, docId);
|
||||
if (spaceType === SpaceType.Workspace) {
|
||||
await this.applyDocLifecycle(client, user.id, spaceId, docId, 'delete');
|
||||
} else {
|
||||
@@ -1360,12 +1394,11 @@ export class SpaceSyncGateway
|
||||
@ConnectedSocket() client: Socket,
|
||||
@CurrentUser() user: CurrentUser,
|
||||
@MessageBody() { spaceType, spaceId, docId, lifecycle }: DocLifecycleMessage
|
||||
): Promise<EventResponse<{ rootUpdate: string; timestamp: number }>> {
|
||||
): Promise<EventResponse<{ timestamp: number }>> {
|
||||
if (!['trash', 'restore', 'delete'].includes(lifecycle)) {
|
||||
throw new BadRequest('Invalid document lifecycle');
|
||||
}
|
||||
docId = canonicalDocId(docId, spaceId);
|
||||
this.assertReservedDocSubject(spaceType, user.id, spaceId, docId);
|
||||
if (spaceType !== SpaceType.Workspace) {
|
||||
throw new DocActionDenied({
|
||||
action: lifecycle === 'delete' ? 'Doc.Delete' : 'Doc.Update',
|
||||
@@ -1391,6 +1424,7 @@ export class SpaceSyncGateway
|
||||
docId: string,
|
||||
lifecycle: 'trash' | 'restore' | 'delete'
|
||||
) {
|
||||
this.selectAdapter(client, SpaceType.Workspace).assertIn(workspaceId);
|
||||
const action =
|
||||
lifecycle === 'trash'
|
||||
? 'Doc.Trash'
|
||||
@@ -1412,20 +1446,8 @@ export class SpaceSyncGateway
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
const rootUpdate = output.rootUpdate as string;
|
||||
const timestamp = new Date(output.timestamp as string).getTime();
|
||||
this.publishDocUpdate(
|
||||
{
|
||||
spaceType: SpaceType.Workspace,
|
||||
spaceId: workspaceId,
|
||||
docId: workspaceId,
|
||||
updates: [Buffer.from(rootUpdate, 'base64')],
|
||||
timestamp,
|
||||
editor: actorUserId,
|
||||
},
|
||||
client
|
||||
);
|
||||
return { rootUpdate, timestamp };
|
||||
const timestamp = Number(output.timestamp);
|
||||
return { timestamp };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1437,73 +1459,57 @@ export class SpaceSyncGateway
|
||||
@CurrentUser() user: CurrentUser,
|
||||
@MessageBody()
|
||||
message: PushDocUpdateMessage
|
||||
): Promise<EventResponse<{ accepted: true; timestamp?: number }>> {
|
||||
): Promise<
|
||||
EventResponse<{ accepted: true; timestamp: number; created: boolean }>
|
||||
> {
|
||||
const { spaceType, spaceId, update } = message;
|
||||
const docId = canonicalDocId(message.docId, spaceId);
|
||||
const adapter = this.selectAdapter(client, spaceType);
|
||||
|
||||
// Quota recovery mode is intentionally not applied to sync.
|
||||
this.assertReservedDocSubject(spaceType, user.id, spaceId, docId);
|
||||
const active = this.hasActiveDocSubscription(
|
||||
client,
|
||||
spaceType,
|
||||
spaceId,
|
||||
docId
|
||||
);
|
||||
if (!active) {
|
||||
throw new NotInSpace({ spaceId });
|
||||
adapter.assertIn(spaceId);
|
||||
if (message.intent !== 'create' && message.intent !== 'update')
|
||||
throw new BadRequest('Document update intent is required.');
|
||||
let permissionGeneration: number | undefined;
|
||||
if (message.intent === 'update') {
|
||||
if (!this.hasActiveDocSubscription(client, spaceType, spaceId, docId))
|
||||
throw new NotInSpace({ spaceId });
|
||||
if (
|
||||
!this.hasActiveDocAction(
|
||||
client,
|
||||
spaceType,
|
||||
spaceId,
|
||||
docId,
|
||||
'Doc.Update'
|
||||
)
|
||||
)
|
||||
throw new DocActionDenied({ action: 'Doc.Update', docId, spaceId });
|
||||
permissionGeneration = this.activeDocGeneration(
|
||||
client,
|
||||
spaceType,
|
||||
spaceId,
|
||||
docId
|
||||
);
|
||||
if (permissionGeneration === undefined) throw new NotInSpace({ spaceId });
|
||||
}
|
||||
if (
|
||||
!this.hasActiveDocAction(client, spaceType, spaceId, docId, 'Doc.Update')
|
||||
) {
|
||||
throw new DocActionDenied({ action: 'Doc.Update', docId, spaceId });
|
||||
}
|
||||
const permissionGeneration = this.activeDocGeneration(
|
||||
client,
|
||||
spaceType,
|
||||
spaceId,
|
||||
docId
|
||||
);
|
||||
if (permissionGeneration === undefined) {
|
||||
throw new NotInSpace({ spaceId });
|
||||
}
|
||||
const canonicalRoot =
|
||||
spaceType === SpaceType.Workspace && docId === spaceId;
|
||||
let timestamp: number;
|
||||
if (canonicalRoot) {
|
||||
let output: Record<string, unknown>;
|
||||
try {
|
||||
output = await this.runtime.executeDomainCommandV1({
|
||||
command: 'append_root_update',
|
||||
actorUserId: user.id,
|
||||
workspaceId: spaceId,
|
||||
update,
|
||||
assertPermission: true,
|
||||
expectedPermissionGeneration: permissionGeneration,
|
||||
});
|
||||
} catch (error) {
|
||||
if (
|
||||
error instanceof Error &&
|
||||
error.message.includes('doc_lifecycle_requires_command')
|
||||
) {
|
||||
throw new DocActionDenied({
|
||||
action: 'Doc.Update',
|
||||
docId,
|
||||
spaceId,
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
timestamp = new Date(output.timestamp as string).getTime();
|
||||
} else {
|
||||
timestamp = await adapter.push(
|
||||
const { timestamp, created } = await adapter
|
||||
.push(
|
||||
spaceId,
|
||||
docId,
|
||||
[Buffer.from(update, 'base64')],
|
||||
user.id,
|
||||
permissionGeneration
|
||||
);
|
||||
}
|
||||
permissionGeneration,
|
||||
message.intent === 'create' ? 'create_doc' : 'update_doc',
|
||||
this.socketProtocolVersions.get(client.id) ?? 0
|
||||
)
|
||||
.catch((error: unknown) => {
|
||||
const code = backendRuntimeErrorCode(error);
|
||||
if (code === 'domain_permission_denied')
|
||||
throw new AccessDenied('Document write access denied');
|
||||
if (code === 'sync_permission_generation_changed')
|
||||
throw new SyncPermissionGenerationChanged({ spaceId });
|
||||
throw error;
|
||||
});
|
||||
|
||||
this.publishDocUpdate(
|
||||
{
|
||||
@@ -1521,10 +1527,26 @@ export class SpaceSyncGateway
|
||||
data: {
|
||||
accepted: true,
|
||||
timestamp,
|
||||
created,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@SubscribeMessage('space:load-workspace-state')
|
||||
async onLoadWorkspaceState(
|
||||
@ConnectedSocket() client: Socket,
|
||||
@CurrentUser() user: CurrentUser,
|
||||
@MessageBody() {
|
||||
spaceType,
|
||||
spaceId,
|
||||
}: { spaceType: SpaceType; spaceId: string }
|
||||
) {
|
||||
if (spaceType !== SpaceType.Workspace)
|
||||
throw new BadRequest('Workspace state requires a workspace.');
|
||||
this.selectAdapter(client, spaceType).assertIn(spaceId);
|
||||
return { data: await this.runtime.getWorkspaceStateV1(spaceId, user.id) };
|
||||
}
|
||||
|
||||
@SubscribeMessage('space:load-doc-timestamps')
|
||||
async onLoadDocTimestamps(
|
||||
@ConnectedSocket() client: Socket,
|
||||
@@ -1534,25 +1556,19 @@ export class SpaceSyncGateway
|
||||
): Promise<EventResponse<Record<string, number>>> {
|
||||
const adapter = this.selectAdapter(client, spaceType);
|
||||
|
||||
const stats = await adapter.getTimestamps(spaceId, timestamp);
|
||||
if (!stats || spaceType === SpaceType.Userspace) {
|
||||
return {
|
||||
data: stats ?? {},
|
||||
};
|
||||
}
|
||||
|
||||
const readableDocs = await this.ac
|
||||
.user(user.id)
|
||||
.workspace(spaceId)
|
||||
.docs(
|
||||
Object.keys(stats).map(docId => ({ docId })),
|
||||
'Doc.Read'
|
||||
);
|
||||
const readableDocIds = new Set(readableDocs.map(doc => doc.docId));
|
||||
|
||||
adapter.assertIn(spaceId);
|
||||
if (spaceType === SpaceType.Userspace)
|
||||
return { data: (await adapter.getTimestamps(spaceId, timestamp)) ?? {} };
|
||||
const state = await this.runtime.getWorkspaceStateV1(spaceId, user.id);
|
||||
const clocks = {
|
||||
...state.clocks,
|
||||
...Object.fromEntries(state.docs.map(doc => [doc.docId, doc.timestamp])),
|
||||
};
|
||||
return {
|
||||
data: Object.fromEntries(
|
||||
Object.entries(stats).filter(([docId]) => readableDocIds.has(docId))
|
||||
Object.entries(clocks).filter(
|
||||
([, value]) => timestamp === undefined || value > timestamp
|
||||
)
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -1603,7 +1619,8 @@ abstract class SyncSocketAdapter {
|
||||
constructor(
|
||||
private readonly spaceType: SpaceType,
|
||||
public readonly client: Socket,
|
||||
public readonly storage: DocStorageAdapter
|
||||
public readonly storage: DocStorageAdapter,
|
||||
private readonly protocolVersion: () => number
|
||||
) {}
|
||||
|
||||
room(spaceId: string, roomType: RoomType = 'sync') {
|
||||
@@ -1625,6 +1642,8 @@ abstract class SyncSocketAdapter {
|
||||
if (!this.client.rooms.has(this.room(spaceId, roomType))) {
|
||||
throw new NotInSpace({ spaceId });
|
||||
}
|
||||
if (this.protocolVersion() !== 2)
|
||||
throw new BadRequest('Sync protocol upgrade required.');
|
||||
}
|
||||
|
||||
abstract assertAccessible(
|
||||
@@ -1639,7 +1658,8 @@ abstract class SyncSocketAdapter {
|
||||
updates: Buffer[],
|
||||
editorId: string,
|
||||
expectedPermissionGeneration?: number,
|
||||
writeIntent: 'update_doc' | 'create_doc' = 'update_doc'
|
||||
writeIntent: 'update_doc' | 'create_doc' = 'update_doc',
|
||||
protocolVersion = 0
|
||||
) {
|
||||
this.assertIn(spaceId);
|
||||
return await this.storage.pushDocUpdates(
|
||||
@@ -1648,7 +1668,8 @@ abstract class SyncSocketAdapter {
|
||||
updates,
|
||||
editorId,
|
||||
expectedPermissionGeneration,
|
||||
writeIntent
|
||||
writeIntent,
|
||||
protocolVersion
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1674,9 +1695,10 @@ class WorkspaceSyncAdapter extends SyncSocketAdapter {
|
||||
storage: DocStorageAdapter,
|
||||
private readonly ac: PermissionAccess,
|
||||
private readonly docReader: DocReader,
|
||||
private readonly models: Models
|
||||
private readonly models: Models,
|
||||
protocolVersion: () => number
|
||||
) {
|
||||
super(SpaceType.Workspace, client, storage);
|
||||
super(SpaceType.Workspace, client, storage, protocolVersion);
|
||||
}
|
||||
|
||||
override async push(
|
||||
@@ -1684,25 +1706,22 @@ class WorkspaceSyncAdapter extends SyncSocketAdapter {
|
||||
docId: string,
|
||||
updates: Buffer[],
|
||||
editorId: string,
|
||||
expectedPermissionGeneration?: number
|
||||
expectedPermissionGeneration?: number,
|
||||
writeIntent: 'update_doc' | 'create_doc' = 'update_doc',
|
||||
protocolVersion = 0
|
||||
) {
|
||||
const docMeta = await this.models.doc.getMeta(spaceId, docId, {
|
||||
select: {
|
||||
blocked: true,
|
||||
},
|
||||
select: { blocked: true },
|
||||
});
|
||||
if (docMeta?.blocked) {
|
||||
throw new DocUpdateBlocked({ spaceId, docId });
|
||||
}
|
||||
return await super.push(
|
||||
if (docMeta?.blocked) throw new DocUpdateBlocked({ spaceId, docId });
|
||||
return super.push(
|
||||
spaceId,
|
||||
docId,
|
||||
updates,
|
||||
editorId,
|
||||
expectedPermissionGeneration,
|
||||
(await this.models.doc.exists(spaceId, docId))
|
||||
? 'update_doc'
|
||||
: 'create_doc'
|
||||
writeIntent,
|
||||
protocolVersion
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1724,8 +1743,12 @@ class WorkspaceSyncAdapter extends SyncSocketAdapter {
|
||||
}
|
||||
|
||||
class UserspaceSyncAdapter extends SyncSocketAdapter {
|
||||
constructor(client: Socket, storage: DocStorageAdapter) {
|
||||
super(SpaceType.Userspace, client, storage);
|
||||
constructor(
|
||||
client: Socket,
|
||||
storage: DocStorageAdapter,
|
||||
protocolVersion: () => number
|
||||
) {
|
||||
super(SpaceType.Userspace, client, storage, protocolVersion);
|
||||
}
|
||||
|
||||
async assertAccessible(
|
||||
|
||||
@@ -79,7 +79,7 @@ export class DocShareRealtimeProvider implements OnModuleInit {
|
||||
docId: string
|
||||
): Promise<DocShareStateSnapshot | null> {
|
||||
await this.assertRead(userId, workspaceId, docId);
|
||||
const doc = await this.models.doc.getMeta(workspaceId, docId);
|
||||
const doc = await this.models.doc.getDocInfo(workspaceId, docId);
|
||||
if (!doc) return null;
|
||||
return {
|
||||
public: doc.public,
|
||||
|
||||
@@ -11,11 +11,10 @@ import {
|
||||
ResolveField,
|
||||
Resolver,
|
||||
} from '@nestjs/graphql';
|
||||
import { Prisma, PrismaClient } from '@prisma/client';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { SafeIntResolver } from 'graphql-scalars';
|
||||
|
||||
import {
|
||||
Cache,
|
||||
DocActionDenied,
|
||||
DocDefaultRoleCanNotBeOwner,
|
||||
DocIsNotPublic,
|
||||
@@ -93,10 +92,10 @@ class DocType {
|
||||
updatedAt?: Date;
|
||||
|
||||
@Field(() => String, { nullable: true })
|
||||
creatorId?: string;
|
||||
creatorId?: string | null;
|
||||
|
||||
@Field(() => String, { nullable: true })
|
||||
lastUpdaterId?: string;
|
||||
lastUpdaterId?: string | null;
|
||||
|
||||
@Field(() => String, { nullable: true })
|
||||
title?: string | null;
|
||||
@@ -307,13 +306,8 @@ export class WorkspaceDocResolver {
|
||||
private readonly logger = new Logger(WorkspaceDocResolver.name);
|
||||
|
||||
constructor(
|
||||
/**
|
||||
* @deprecated migrate to models
|
||||
*/
|
||||
private readonly prisma: PrismaClient,
|
||||
private readonly ac: PermissionAccess,
|
||||
private readonly models: Models,
|
||||
private readonly cache: Cache,
|
||||
private readonly event: EventBus,
|
||||
private readonly runtime: BackendRuntimeProvider
|
||||
) {}
|
||||
@@ -367,7 +361,7 @@ export class WorkspaceDocResolver {
|
||||
pagination
|
||||
);
|
||||
|
||||
return paginate(rows, 'createdAt', pagination, count);
|
||||
return paginate(rows, 'cursor', pagination, count);
|
||||
}
|
||||
|
||||
@ResolveField(() => PaginatedDocType, {
|
||||
@@ -388,7 +382,7 @@ export class WorkspaceDocResolver {
|
||||
'Doc.Read'
|
||||
);
|
||||
const predicate = readable.length
|
||||
? Prisma.sql`"workspace_pages"."page_id" IN (${Prisma.join(readable.map(doc => doc.docId))})`
|
||||
? Prisma.sql`source.doc_id IN (SELECT jsonb_array_elements_text(${JSON.stringify(readable.map(doc => doc.docId))}::jsonb))`
|
||||
: Prisma.sql`FALSE`;
|
||||
const [count, rows] = await this.models.doc.paginateDocInfoByUpdatedAt(
|
||||
workspace.id,
|
||||
@@ -396,7 +390,7 @@ export class WorkspaceDocResolver {
|
||||
predicate
|
||||
);
|
||||
|
||||
return paginate(rows, 'updatedAt', pagination, count);
|
||||
return paginate(rows, 'cursor', pagination, count);
|
||||
}
|
||||
|
||||
@ResolveField(() => DocType, {
|
||||
@@ -408,24 +402,10 @@ export class WorkspaceDocResolver {
|
||||
@Parent() workspace: WorkspaceType,
|
||||
@Args('docId') docId: string
|
||||
): Promise<DocType> {
|
||||
await this.ac.user(me.id).doc(workspace.id, docId).assert('Doc.Read');
|
||||
const doc = await this.models.doc.getDocInfo(workspace.id, docId);
|
||||
if (doc) {
|
||||
// check if doc is readable
|
||||
await this.ac.user(me.id).doc(workspace.id, docId).assert('Doc.Read');
|
||||
return doc;
|
||||
}
|
||||
|
||||
await this.tryFixDocOwner(workspace.id, docId);
|
||||
|
||||
const isPublic = await this.models.doc.isPublic(workspace.id, docId);
|
||||
|
||||
return {
|
||||
docId,
|
||||
workspaceId: workspace.id,
|
||||
mode: PublicDocMode.Page,
|
||||
public: isPublic,
|
||||
defaultRole: DocRole.Manager,
|
||||
};
|
||||
if (!doc) throw new DocNotFound({ spaceId: workspace.id, docId });
|
||||
return doc;
|
||||
}
|
||||
|
||||
@Mutation(() => DocType)
|
||||
@@ -474,7 +454,7 @@ export class WorkspaceDocResolver {
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
const doc = await this.models.doc.getMeta(workspaceId, docId);
|
||||
const doc = await this.models.doc.getDocInfo(workspaceId, docId);
|
||||
if (!doc) {
|
||||
throw new DocNotFound({ spaceId: workspaceId, docId });
|
||||
}
|
||||
@@ -525,7 +505,7 @@ export class WorkspaceDocResolver {
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
const doc = await this.models.doc.getMeta(workspaceId, docId);
|
||||
const doc = await this.models.doc.getDocInfo(workspaceId, docId);
|
||||
if (!doc) {
|
||||
throw new DocNotFound({ spaceId: workspaceId, docId });
|
||||
}
|
||||
@@ -535,61 +515,6 @@ export class WorkspaceDocResolver {
|
||||
|
||||
return doc;
|
||||
}
|
||||
|
||||
private async tryFixDocOwner(workspaceId: string, docId: string) {
|
||||
const allowed = await this.cache.setnx(
|
||||
`fixingOwner:${workspaceId}:${docId}`,
|
||||
1,
|
||||
// TODO(@forehalo): we definitely need a timer helper
|
||||
{ ttl: 1000 * 60 * 60 * 24 }
|
||||
);
|
||||
|
||||
// fixed by other instance
|
||||
if (!allowed) {
|
||||
return;
|
||||
}
|
||||
|
||||
const exists = await this.models.doc.exists(workspaceId, docId);
|
||||
|
||||
// skip if doc not even exists
|
||||
if (!exists) {
|
||||
return;
|
||||
}
|
||||
|
||||
const owner = await this.models.docUser.getOwner(workspaceId, docId);
|
||||
|
||||
// skip if owner already exists
|
||||
if (owner) {
|
||||
return;
|
||||
}
|
||||
|
||||
// try snapshot.createdBy first
|
||||
const snapshot = await this.prisma.snapshot.findUnique({
|
||||
select: {
|
||||
createdBy: true,
|
||||
},
|
||||
where: {
|
||||
workspaceId_id: {
|
||||
workspaceId,
|
||||
id: docId,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
let fixedOwner = snapshot?.createdBy;
|
||||
|
||||
// try workspace.owner
|
||||
if (!fixedOwner) {
|
||||
const owner = await this.models.workspaceUser.getOwner(workspaceId);
|
||||
fixedOwner = owner.id;
|
||||
}
|
||||
|
||||
await this.models.docUser.setOwner(workspaceId, docId, fixedOwner);
|
||||
|
||||
this.logger.debug(
|
||||
`Fixed doc owner for ${docId} in workspace ${workspaceId}, new owner: ${fixedOwner}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@Resolver(() => DocType)
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
} from '../../../base';
|
||||
import { Models } from '../../../models';
|
||||
import { CurrentUser } from '../../auth';
|
||||
import { BackendRuntimeProvider } from '../../backend-runtime';
|
||||
import type { DotToUnderline } from '../../permission';
|
||||
import {
|
||||
mapPermissionsToGraphqlPermissions,
|
||||
@@ -69,6 +70,7 @@ export class WorkspaceResolver {
|
||||
private readonly quota: QuotaService,
|
||||
private readonly models: Models,
|
||||
private readonly workspaceService: WorkspaceService,
|
||||
private readonly runtime: BackendRuntimeProvider,
|
||||
private readonly logger: AFFiNELogger
|
||||
) {
|
||||
logger.setContext(WorkspaceResolver.name);
|
||||
@@ -228,12 +230,12 @@ export class WorkspaceResolver {
|
||||
const buffer = chunks.length ? Buffer.concat(chunks) : null;
|
||||
|
||||
if (buffer) {
|
||||
await this.models.doc.upsert({
|
||||
spaceId: workspace.id,
|
||||
await this.runtime.appendWorkspaceDocUpdatesV1({
|
||||
workspaceId: workspace.id,
|
||||
docId: workspace.id,
|
||||
blob: buffer,
|
||||
timestamp: Date.now(),
|
||||
editorId: user.id,
|
||||
updates: [buffer],
|
||||
actorUserId: user.id,
|
||||
writeIntent: 'update_doc',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { ServerConfigModule } from '../core/config';
|
||||
import { CreateCommand } from './commands/create';
|
||||
import { CutoverCommand } from './commands/cutover';
|
||||
import { ImportConfigCommand } from './commands/import';
|
||||
import { RootSourceCommand } from './commands/root-source';
|
||||
import { RevertCommand, RunCommand } from './commands/run';
|
||||
|
||||
@Module({
|
||||
@@ -15,6 +16,7 @@ import { RevertCommand, RunCommand } from './commands/run';
|
||||
RunCommand,
|
||||
RevertCommand,
|
||||
ImportConfigCommand,
|
||||
RootSourceCommand,
|
||||
],
|
||||
})
|
||||
export class CliAppModule {}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { writeFile } from 'node:fs/promises';
|
||||
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
@Injectable()
|
||||
export class RootSourceCommand {
|
||||
private readonly logger = new Logger(RootSourceCommand.name);
|
||||
|
||||
constructor(private readonly db: PrismaClient) {}
|
||||
|
||||
async inspect(workspaceId: string, output: string) {
|
||||
const material = await this.db.$transaction(
|
||||
async tx => {
|
||||
const snapshot = await tx.snapshot.findUnique({
|
||||
where: { workspaceId_id: { workspaceId, id: workspaceId } },
|
||||
});
|
||||
const updates = await tx.update.findMany({
|
||||
where: { workspaceId, id: workspaceId },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
});
|
||||
const histories = await tx.snapshotHistory.findMany({
|
||||
where: { workspaceId, id: workspaceId },
|
||||
orderBy: { timestamp: 'asc' },
|
||||
});
|
||||
const encode = <
|
||||
T extends { blob: Uint8Array; state?: Uint8Array | null },
|
||||
>(
|
||||
row: T
|
||||
) => ({
|
||||
...row,
|
||||
blob: Buffer.from(row.blob).toString('base64'),
|
||||
...(row.state && {
|
||||
state: Buffer.from(row.state).toString('base64'),
|
||||
}),
|
||||
});
|
||||
return {
|
||||
workspaceId,
|
||||
snapshot: snapshot && encode(snapshot),
|
||||
updates: updates.map(encode),
|
||||
histories: histories.map(encode),
|
||||
};
|
||||
},
|
||||
{ isolationLevel: 'RepeatableRead' }
|
||||
);
|
||||
await writeFile(
|
||||
output,
|
||||
JSON.stringify(
|
||||
material,
|
||||
(_key, value: unknown) =>
|
||||
typeof value === 'bigint' ? value.toString() : value,
|
||||
2
|
||||
) + '\n',
|
||||
{ mode: 0o600, flag: 'wx' }
|
||||
);
|
||||
this.logger.log(`Root material saved to ${output}`);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 173 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user