@syncular/server 0.33.0 → 0.35.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/blob-handlers.js +10 -3
- package/dist/blob-store.d.ts +9 -1
- package/dist/blob-store.js +0 -0
- package/dist/bucket-blob-store.d.ts +1 -0
- package/dist/bucket-blob-store.js +22 -16
- package/dist/d1-storage.d.ts +3 -1
- package/dist/d1-storage.js +27 -3
- package/dist/erase.d.ts +28 -0
- package/dist/erase.js +122 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/operations.d.ts +20 -3
- package/dist/operations.js +23 -3
- package/dist/postgres-storage.d.ts +3 -1
- package/dist/postgres-storage.js +40 -0
- package/dist/push.d.ts +8 -2
- package/dist/push.js +1 -1
- package/dist/relational-rows.d.ts +6 -3
- package/dist/relational-rows.js +8 -9
- package/dist/sqlite-blob-store.d.ts +1 -0
- package/dist/sqlite-blob-store.js +14 -2
- package/dist/sqlite-dialect.d.ts +11 -1
- package/dist/sqlite-dialect.js +35 -0
- package/dist/sqlite-storage.d.ts +3 -1
- package/dist/sqlite-storage.js +29 -9
- package/dist/storage-errors.d.ts +1 -1
- package/dist/storage-errors.js +2 -0
- package/dist/storage.d.ts +26 -0
- package/package.json +2 -2
- package/src/blob-handlers.ts +13 -5
- package/src/blob-store.ts +0 -0
- package/src/bucket-blob-store.ts +26 -20
- package/src/d1-storage.ts +48 -3
- package/src/erase.ts +173 -0
- package/src/index.ts +1 -0
- package/src/operations.ts +52 -5
- package/src/postgres-storage.ts +59 -0
- package/src/push.ts +1 -1
- package/src/relational-rows.ts +8 -11
- package/src/sqlite-blob-store.ts +17 -1
- package/src/sqlite-dialect.ts +43 -0
- package/src/sqlite-storage.ts +42 -10
- package/src/storage-errors.ts +7 -1
- package/src/storage.ts +35 -0
|
@@ -17,8 +17,15 @@ export class SqliteBlobStore {
|
|
|
17
17
|
}
|
|
18
18
|
async put(partition, blobId, bytes, nowMs, mediaType) {
|
|
19
19
|
const existing = await this.get(partition, blobId);
|
|
20
|
-
if (existing !== undefined)
|
|
21
|
-
|
|
20
|
+
if (existing !== undefined) {
|
|
21
|
+
if (existing.record.mediaType !== undefined || mediaType === undefined)
|
|
22
|
+
return existing.record;
|
|
23
|
+
// A re-upload names the media type an earlier upload left out.
|
|
24
|
+
this.db
|
|
25
|
+
.query('UPDATE sync_blobs SET media_type=? WHERE partition=? AND blob_id=? AND media_type IS NULL')
|
|
26
|
+
.run(mediaType, partition, blobId);
|
|
27
|
+
return { ...existing.record, mediaType };
|
|
28
|
+
}
|
|
22
29
|
const record = {
|
|
23
30
|
blobId,
|
|
24
31
|
partition,
|
|
@@ -33,6 +40,11 @@ export class SqliteBlobStore {
|
|
|
33
40
|
.run(partition, blobId, bytes.length, mediaType ?? null, nowMs, bytes);
|
|
34
41
|
return record;
|
|
35
42
|
}
|
|
43
|
+
async delete(partition, blobId) {
|
|
44
|
+
this.db
|
|
45
|
+
.query('DELETE FROM sync_blobs WHERE partition=? AND blob_id=?')
|
|
46
|
+
.run(partition, blobId);
|
|
47
|
+
}
|
|
36
48
|
async has(partition, blobId) {
|
|
37
49
|
const row = this.db
|
|
38
50
|
.query('SELECT 1 AS n FROM sync_blobs WHERE partition=? AND blob_id=?')
|
package/dist/sqlite-dialect.d.ts
CHANGED
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
* behavior is held key-for-key regardless.
|
|
17
17
|
*/
|
|
18
18
|
import type { ScopeMap } from '@syncular/core';
|
|
19
|
-
import type { StoredChange, StoredCommit, StoredPushResult, StoredRow } from './storage.js';
|
|
19
|
+
import type { ScopeValueHistoryQuery, StoredChange, StoredCommit, StoredPushResult, StoredRow } from './storage.js';
|
|
20
20
|
/**
|
|
21
21
|
* Schema DDL, one statement per `;`-delimited chunk. Native SQLite applies
|
|
22
22
|
* the whole string via `db.exec(SQLITE_DDL)`; D1 applies each statement
|
|
@@ -39,6 +39,16 @@ import type { StoredChange, StoredCommit, StoredPushResult, StoredRow } from './
|
|
|
39
39
|
export declare const SQLITE_DDL = "\nCREATE TABLE IF NOT EXISTS sync_partitions(\n partition TEXT PRIMARY KEY,\n max_commit_seq INTEGER NOT NULL DEFAULT 0,\n horizon_seq INTEGER NOT NULL DEFAULT 0\n);\nCREATE TABLE IF NOT EXISTS sync_partition_registry(\n partition TEXT PRIMARY KEY,\n log_epoch TEXT NOT NULL,\n epoch_required INTEGER NOT NULL DEFAULT 0,\n last_authenticated_at_ms INTEGER NOT NULL\n);\nCREATE TABLE IF NOT EXISTS sync_row_scopes(\n partition TEXT NOT NULL, tbl TEXT NOT NULL,\n var TEXT NOT NULL, value TEXT NOT NULL, row_id TEXT NOT NULL,\n PRIMARY KEY(partition, tbl, var, value, row_id)\n);\nCREATE INDEX IF NOT EXISTS sync_row_scopes_by_row\n ON sync_row_scopes(partition, tbl, row_id);\nCREATE TABLE IF NOT EXISTS sync_commits(\n partition TEXT NOT NULL, commit_seq INTEGER NOT NULL,\n client_id TEXT NOT NULL, client_commit_id TEXT NOT NULL,\n actor_id TEXT NOT NULL, created_at_ms INTEGER NOT NULL,\n writer_version INTEGER,\n PRIMARY KEY(partition, commit_seq)\n);\nCREATE INDEX IF NOT EXISTS sync_commits_by_time\n ON sync_commits(partition, created_at_ms);\nCREATE TABLE IF NOT EXISTS sync_changes(\n partition TEXT NOT NULL, commit_seq INTEGER NOT NULL, idx INTEGER NOT NULL,\n tbl TEXT NOT NULL, row_id TEXT NOT NULL, op INTEGER NOT NULL,\n row_version INTEGER, scopes TEXT NOT NULL, payload BLOB,\n PRIMARY KEY(partition, commit_seq, idx)\n);\nCREATE INDEX IF NOT EXISTS sync_changes_by_table\n ON sync_changes(partition, commit_seq, tbl, idx);\nCREATE TABLE IF NOT EXISTS sync_change_scopes(\n partition TEXT NOT NULL, tbl TEXT NOT NULL,\n var TEXT NOT NULL, value TEXT NOT NULL, commit_seq INTEGER NOT NULL,\n PRIMARY KEY(partition, tbl, var, value, commit_seq)\n);\nCREATE TABLE IF NOT EXISTS sync_push_results(\n partition TEXT NOT NULL, client_id TEXT NOT NULL,\n client_commit_id TEXT NOT NULL, result TEXT NOT NULL,\n PRIMARY KEY(partition, client_id, client_commit_id)\n);\nCREATE TABLE IF NOT EXISTS sync_reactions(\n partition TEXT NOT NULL, idempotency_key TEXT NOT NULL,\n type TEXT NOT NULL, version INTEGER NOT NULL, payload TEXT NOT NULL,\n source_client_id TEXT NOT NULL, source_client_commit_id TEXT NOT NULL,\n source_commit_seq INTEGER NOT NULL, created_at_ms INTEGER NOT NULL,\n available_at_ms INTEGER NOT NULL, status TEXT NOT NULL,\n attempts INTEGER NOT NULL, max_attempts INTEGER NOT NULL,\n lease_owner TEXT, lease_expires_at_ms INTEGER, completed_at_ms INTEGER,\n last_failure TEXT,\n PRIMARY KEY(partition, idempotency_key),\n CHECK(status IN ('pending', 'leased', 'completed', 'dead-letter'))\n);\nCREATE INDEX IF NOT EXISTS sync_reactions_due\n ON sync_reactions(partition, status, available_at_ms, created_at_ms, idempotency_key);\nCREATE INDEX IF NOT EXISTS sync_reactions_lease\n ON sync_reactions(partition, status, lease_expires_at_ms);\nCREATE INDEX IF NOT EXISTS sync_reactions_completed\n ON sync_reactions(partition, status, completed_at_ms, idempotency_key);\nCREATE INDEX IF NOT EXISTS sync_reactions_dead_letter\n ON sync_reactions(partition, status, available_at_ms, idempotency_key);\nCREATE TABLE IF NOT EXISTS sync_clients(\n partition TEXT NOT NULL, client_id TEXT NOT NULL, actor_id TEXT NOT NULL,\n wire_version INTEGER NOT NULL DEFAULT 1,\n cursor INTEGER NOT NULL, subscriptions TEXT NOT NULL,\n updated_at_ms INTEGER NOT NULL,\n PRIMARY KEY(partition, client_id)\n);\nCREATE TABLE IF NOT EXISTS sync_blob_refs(\n partition TEXT NOT NULL, tbl TEXT NOT NULL, row_id TEXT NOT NULL,\n blob_id TEXT NOT NULL,\n PRIMARY KEY(partition, tbl, row_id, blob_id)\n);\nCREATE INDEX IF NOT EXISTS sync_blob_refs_by_blob\n ON sync_blob_refs(partition, blob_id);\nCREATE TABLE IF NOT EXISTS sync_tombstones(\n partition TEXT NOT NULL, tbl TEXT NOT NULL, row_id TEXT NOT NULL,\n commit_seq INTEGER NOT NULL,\n PRIMARY KEY(partition, tbl, row_id)\n);\nCREATE TABLE IF NOT EXISTS sync_backfill_checkpoints(\n partition TEXT NOT NULL, name TEXT NOT NULL,\n schema_version INTEGER NOT NULL,\n state TEXT NOT NULL CHECK(state IN ('declared','backfilling','activated')),\n watermark INTEGER NOT NULL DEFAULT 0,\n owner_epoch INTEGER NOT NULL DEFAULT 0,\n observed_rows INTEGER NOT NULL DEFAULT 0,\n updated_at_ms INTEGER NOT NULL,\n PRIMARY KEY(partition, name)\n);\nCREATE TABLE IF NOT EXISTS sync_writer_fence(\n partition TEXT PRIMARY KEY,\n required_writer_version INTEGER NOT NULL\n);\n";
|
|
40
40
|
/** Split the DDL into individual statements (D1 applies them one by one). */
|
|
41
41
|
export declare function sqliteDdlStatements(): string[];
|
|
42
|
+
/** §4.6.1: rowIds of one table bound to one scope value, budgeted. */
|
|
43
|
+
export declare const LIST_SCOPE_VALUE_ROWS_SQLITE_SQL = "SELECT row_id FROM sync_row_scopes WHERE partition=? AND tbl=? AND var=? AND value=? ORDER BY row_id LIMIT ?";
|
|
44
|
+
/**
|
|
45
|
+
* §4.6.1 history scrub, bound by `eraseScopeValueHistoryParams`: upsert change
|
|
46
|
+
* records of the binding first, then the change scope entries whose commit
|
|
47
|
+
* no longer holds a change of the binding. Each returns one row per removed
|
|
48
|
+
* record (D1 batch results carry no reliable change count).
|
|
49
|
+
*/
|
|
50
|
+
export declare const ERASE_SCOPE_VALUE_HISTORY_SQLITE_SQL: readonly ["DELETE FROM sync_changes WHERE rowid IN (\n SELECT c.rowid FROM sync_change_scopes s JOIN sync_changes c\n ON c.partition=s.partition AND c.commit_seq=s.commit_seq AND c.tbl=s.tbl\n WHERE s.partition=?1 AND s.tbl=?2 AND s.var=?3 AND s.value=?4\n AND s.commit_seq<=?5 AND c.op=1 AND json_extract(c.scopes, ?6)=s.value\n LIMIT ?7) RETURNING 1 AS removed", "DELETE FROM sync_change_scopes WHERE rowid IN (\n SELECT s.rowid FROM sync_change_scopes s\n WHERE s.partition=?1 AND s.tbl=?2 AND s.var=?3 AND s.value=?4\n AND s.commit_seq<=?5 AND NOT EXISTS (\n SELECT 1 FROM sync_changes c\n WHERE c.partition=s.partition AND c.commit_seq=s.commit_seq\n AND c.tbl=s.tbl AND json_extract(c.scopes, ?6)=s.value)\n LIMIT ?7) RETURNING 1 AS removed"];
|
|
51
|
+
export declare function eraseScopeValueHistoryParams(partition: string, query: ScopeValueHistoryQuery): [string, string, string, string, number, string, number];
|
|
42
52
|
/** `?,?,…` for an `IN (…)` clause of `count` positional parameters. */
|
|
43
53
|
export declare function placeholders(count: number): string;
|
|
44
54
|
/** Serialize a push result to the JSON `TEXT` stored in `sync_push_results`. */
|
package/dist/sqlite-dialect.js
CHANGED
|
@@ -124,6 +124,41 @@ export function sqliteDdlStatements() {
|
|
|
124
124
|
.map((statement) => statement.trim())
|
|
125
125
|
.filter((statement) => statement.length > 0);
|
|
126
126
|
}
|
|
127
|
+
/** §4.6.1: rowIds of one table bound to one scope value, budgeted. */
|
|
128
|
+
export const LIST_SCOPE_VALUE_ROWS_SQLITE_SQL = 'SELECT row_id FROM sync_row_scopes WHERE partition=? AND tbl=? AND var=? AND value=? ORDER BY row_id LIMIT ?';
|
|
129
|
+
/**
|
|
130
|
+
* §4.6.1 history scrub, bound by `eraseScopeValueHistoryParams`: upsert change
|
|
131
|
+
* records of the binding first, then the change scope entries whose commit
|
|
132
|
+
* no longer holds a change of the binding. Each returns one row per removed
|
|
133
|
+
* record (D1 batch results carry no reliable change count).
|
|
134
|
+
*/
|
|
135
|
+
export const ERASE_SCOPE_VALUE_HISTORY_SQLITE_SQL = [
|
|
136
|
+
`DELETE FROM sync_changes WHERE rowid IN (
|
|
137
|
+
SELECT c.rowid FROM sync_change_scopes s JOIN sync_changes c
|
|
138
|
+
ON c.partition=s.partition AND c.commit_seq=s.commit_seq AND c.tbl=s.tbl
|
|
139
|
+
WHERE s.partition=?1 AND s.tbl=?2 AND s.var=?3 AND s.value=?4
|
|
140
|
+
AND s.commit_seq<=?5 AND c.op=1 AND json_extract(c.scopes, ?6)=s.value
|
|
141
|
+
LIMIT ?7) RETURNING 1 AS removed`,
|
|
142
|
+
`DELETE FROM sync_change_scopes WHERE rowid IN (
|
|
143
|
+
SELECT s.rowid FROM sync_change_scopes s
|
|
144
|
+
WHERE s.partition=?1 AND s.tbl=?2 AND s.var=?3 AND s.value=?4
|
|
145
|
+
AND s.commit_seq<=?5 AND NOT EXISTS (
|
|
146
|
+
SELECT 1 FROM sync_changes c
|
|
147
|
+
WHERE c.partition=s.partition AND c.commit_seq=s.commit_seq
|
|
148
|
+
AND c.tbl=s.tbl AND json_extract(c.scopes, ?6)=s.value)
|
|
149
|
+
LIMIT ?7) RETURNING 1 AS removed`,
|
|
150
|
+
];
|
|
151
|
+
export function eraseScopeValueHistoryParams(partition, query) {
|
|
152
|
+
return [
|
|
153
|
+
partition,
|
|
154
|
+
query.table,
|
|
155
|
+
query.variable,
|
|
156
|
+
query.value,
|
|
157
|
+
query.throughSeq,
|
|
158
|
+
`$.${JSON.stringify(query.variable)}`,
|
|
159
|
+
query.limit,
|
|
160
|
+
];
|
|
161
|
+
}
|
|
127
162
|
/** `?,?,…` for an `IN (…)` clause of `count` positional parameters. */
|
|
128
163
|
export function placeholders(count) {
|
|
129
164
|
return new Array(count).fill('?').join(',');
|
package/dist/sqlite-storage.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import type { CommitPruneQuery, CommitPruneResult } from './storage.js';
|
|
|
2
2
|
import type { ScopeMap } from '@syncular/core';
|
|
3
3
|
import type { CompiledSchema, CompiledTable } from './schema.js';
|
|
4
4
|
import { type SqliteDatabase } from './sqlite-driver.js';
|
|
5
|
-
import type { AuthoritativeQueryRequest, AuthoritativeQueryResult, CheckpointDeclaration, ClientCursorInfo, ClientPushResult, ClientRecord, CommitDetail, CommitMetadata, CommitMetadataQuery, CommitWindowQuery, IndexRowScanQuery, PartitionRegistryEntry, PrunedReactionCounts, ReactionClaimQuery, ReactionFailureUpdate, ReactionListQuery, ReactionPruneQuery, RowChangeRecord, RowChangesQuery, RowListQuery, RowScanQuery, ScopeActivityQuery, ScopeCommitActivity, ServerStorage, ServeGate, StorageTransaction, StoredCommit, StoredCheckpoint, StoredPushResult, StoredReaction, StoredRow } from './storage.js';
|
|
5
|
+
import type { AuthoritativeQueryRequest, AuthoritativeQueryResult, CheckpointDeclaration, ClientCursorInfo, ClientPushResult, ClientRecord, CommitDetail, CommitMetadata, CommitMetadataQuery, CommitWindowQuery, IndexRowScanQuery, PartitionRegistryEntry, PrunedReactionCounts, ReactionClaimQuery, ReactionFailureUpdate, ReactionListQuery, ReactionPruneQuery, RowChangeRecord, RowChangesQuery, RowListQuery, RowScanQuery, ScopeActivityQuery, ScopeCommitActivity, ScopeValueHistoryQuery, ScopeValueQuery, ServerStorage, ServeGate, StorageTransaction, StoredCommit, StoredCheckpoint, StoredPushResult, StoredReaction, StoredRow } from './storage.js';
|
|
6
6
|
export declare class SqliteServerStorage implements ServerStorage {
|
|
7
7
|
#private;
|
|
8
8
|
readonly db: SqliteDatabase;
|
|
@@ -67,6 +67,8 @@ export declare class SqliteServerStorage implements ServerStorage {
|
|
|
67
67
|
readonly scopes: Record<string, string>;
|
|
68
68
|
}[]>;
|
|
69
69
|
listReferencedBlobIds(partition: string): Promise<string[]>;
|
|
70
|
+
listScopeValueRows(partition: string, query: ScopeValueQuery): Promise<string[]>;
|
|
71
|
+
eraseScopeValueHistory(partition: string, query: ScopeValueHistoryQuery): Promise<number>;
|
|
70
72
|
listClientRecords(partition: string): Promise<ClientRecord[]>;
|
|
71
73
|
listCommitMetadata(partition: string, query: CommitMetadataQuery): Promise<CommitMetadata[]>;
|
|
72
74
|
getCommit(partition: string, commitSeq: number): Promise<CommitDetail | undefined>;
|
package/dist/sqlite-storage.js
CHANGED
|
@@ -13,9 +13,9 @@ import { serveNotReadyError } from './readiness.js';
|
|
|
13
13
|
*/
|
|
14
14
|
import { bindAuthoritativePartition, prepareAuthoritativeQuery, } from './authoritative-query.js';
|
|
15
15
|
import { syncError } from './errors.js';
|
|
16
|
-
import { assertPhysicalColumns, assertStoredLayouts, commitWindowPageSql,
|
|
16
|
+
import { assertPhysicalColumns, assertStoredLayouts, commitWindowPageSql, LATEST_SCOPED_CHANGE_SEQ_SQLITE_SQL, deleteRowSql, deleteSqliteRowScopesSql, dropTableDdl, indexRowPageStatement, layoutsOf, migratePayload, parseLayouts, quoteIdent, retiredTableNames, rewritePlan, rewriteRowSql, rewriteValues, SCHEMA_META_DDL_SQLITE, SYNC_COLUMN_VERSIONS_COLUMN, SYNC_PARTITION_COLUMN, SYNC_PAYLOAD_COLUMN, SYNC_ROW_ID_COLUMN, SYNC_SCOPES_COLUMN, SYNC_VERSION_COLUMN, scanRowPageSql, schemaDdl, selectRowScopesSql, selectRowSql, selectRowsForRewriteSql, upsertSql, upsertValues, } from './relational-rows.js';
|
|
17
17
|
import { matchesEffective } from './scopes.js';
|
|
18
|
-
import { collectCommitWindowPage, deserializePushResult, placeholders, SQLITE_DDL, serializePushResult, toStoredChange, toStoredRow, } from './sqlite-dialect.js';
|
|
18
|
+
import { collectCommitWindowPage, deserializePushResult, ERASE_SCOPE_VALUE_HISTORY_SQLITE_SQL, eraseScopeValueHistoryParams, LIST_SCOPE_VALUE_ROWS_SQLITE_SQL, placeholders, SQLITE_DDL, serializePushResult, toStoredChange, toStoredRow, } from './sqlite-dialect.js';
|
|
19
19
|
import { SqliteAdapterRequiredError, } from './sqlite-driver.js';
|
|
20
20
|
import { isSqliteConstraintError, StorageConstraintError, } from './storage-errors.js';
|
|
21
21
|
import { assertScopeIndexedScan, resolveIndexRowScan } from './storage-query.js';
|
|
@@ -1034,13 +1034,8 @@ END`);
|
|
|
1034
1034
|
if (firstVariable === undefined || values.length === 0)
|
|
1035
1035
|
return 0;
|
|
1036
1036
|
const row = this.db
|
|
1037
|
-
.query(
|
|
1038
|
-
.get(
|
|
1039
|
-
partition,
|
|
1040
|
-
query.table,
|
|
1041
|
-
firstVariable,
|
|
1042
|
-
value,
|
|
1043
|
-
]));
|
|
1037
|
+
.query(LATEST_SCOPED_CHANGE_SEQ_SQLITE_SQL)
|
|
1038
|
+
.get(partition, query.table, firstVariable, JSON.stringify(values));
|
|
1044
1039
|
return row?.seq ?? 0;
|
|
1045
1040
|
}
|
|
1046
1041
|
async readCommitWindow(partition, query) {
|
|
@@ -1203,6 +1198,31 @@ END`);
|
|
|
1203
1198
|
.all(partition);
|
|
1204
1199
|
return rows.map((r) => r.blob_id);
|
|
1205
1200
|
}
|
|
1201
|
+
async listScopeValueRows(partition, query) {
|
|
1202
|
+
return this.db
|
|
1203
|
+
.query(LIST_SCOPE_VALUE_ROWS_SQLITE_SQL)
|
|
1204
|
+
.all(partition, query.table, query.variable, query.value, query.limit)
|
|
1205
|
+
.map((row) => row.row_id);
|
|
1206
|
+
}
|
|
1207
|
+
async eraseScopeValueHistory(partition, query) {
|
|
1208
|
+
const params = eraseScopeValueHistoryParams(partition, query);
|
|
1209
|
+
return this.#serializeWrite(() => {
|
|
1210
|
+
this.db.exec('BEGIN IMMEDIATE');
|
|
1211
|
+
try {
|
|
1212
|
+
let removed = 0;
|
|
1213
|
+
for (const sql of ERASE_SCOPE_VALUE_HISTORY_SQLITE_SQL) {
|
|
1214
|
+
removed += this.db.query(sql).all(...params).length;
|
|
1215
|
+
}
|
|
1216
|
+
this.db.exec('COMMIT');
|
|
1217
|
+
return removed;
|
|
1218
|
+
}
|
|
1219
|
+
catch (error) {
|
|
1220
|
+
rollbackAfterError(() => {
|
|
1221
|
+
this.db.exec('ROLLBACK');
|
|
1222
|
+
}, error);
|
|
1223
|
+
}
|
|
1224
|
+
});
|
|
1225
|
+
}
|
|
1206
1226
|
// -- admin/console read surface --------------------------------------------
|
|
1207
1227
|
async listClientRecords(partition) {
|
|
1208
1228
|
const records = this.db
|
package/dist/storage-errors.d.ts
CHANGED
|
@@ -9,7 +9,7 @@ export declare class StorageConstraintError extends Error {
|
|
|
9
9
|
constructor(cause: unknown, opIndex?: number);
|
|
10
10
|
}
|
|
11
11
|
/** Stable, privacy-safe failures for trusted server storage queries. */
|
|
12
|
-
export type StorageQueryErrorCode = 'sync.storage.schema_migration_pending' | 'sync.storage.schema_migration_conflict' | 'sync.storage.schema_changed' | 'sync.storage.invalid_migration_budget' | 'sync.storage.scan_requires_scope' | 'sync.storage.index_not_found' | 'sync.storage.index_not_materialized' | 'sync.storage.index_value_count_mismatch' | 'sync.storage.invalid_limit' | 'sync.storage.prune_epoch_mismatch' | 'sync.storage.partition_unregistered' | 'sync.storage.invalid_prune_cursor' | 'sync.storage.checkpoint_not_declared' | 'sync.storage.checkpoint_unsupported' | 'sync.storage.checkpoint_fence_missing' | 'sync.storage.checkpoint_incomplete' | 'sync.storage.stored_layout_mismatch' | 'sync.storage.physical_layout_mismatch' | 'sync.storage.transaction_query_unsupported' | 'sync.storage.query_over_staged_writes';
|
|
12
|
+
export type StorageQueryErrorCode = 'sync.storage.schema_migration_pending' | 'sync.storage.schema_migration_conflict' | 'sync.storage.schema_changed' | 'sync.storage.invalid_migration_budget' | 'sync.storage.scan_requires_scope' | 'sync.storage.index_not_found' | 'sync.storage.index_not_materialized' | 'sync.storage.index_value_count_mismatch' | 'sync.storage.invalid_limit' | 'sync.storage.prune_epoch_mismatch' | 'sync.storage.partition_unregistered' | 'sync.storage.invalid_prune_cursor' | 'sync.storage.checkpoint_not_declared' | 'sync.storage.checkpoint_unsupported' | 'sync.storage.checkpoint_fence_missing' | 'sync.storage.checkpoint_incomplete' | 'sync.storage.stored_layout_mismatch' | 'sync.storage.physical_layout_mismatch' | 'sync.storage.transaction_query_unsupported' | 'sync.storage.query_over_staged_writes' | 'sync.storage.erase_unsupported' | 'sync.storage.invalid_erase_query';
|
|
13
13
|
/**
|
|
14
14
|
* Host-only query error. Messages never include identifiers, values, SQL,
|
|
15
15
|
* paths, or row data; callers branch on `code`, never message text. The
|
package/dist/storage-errors.js
CHANGED
|
@@ -32,6 +32,8 @@ const STORAGE_QUERY_MESSAGES = {
|
|
|
32
32
|
'sync.storage.index_not_materialized': 'trusted row lookup requires a materialized relational table',
|
|
33
33
|
'sync.storage.index_value_count_mismatch': 'trusted row lookup requires one exact value per index column',
|
|
34
34
|
'sync.storage.invalid_limit': 'trusted row lookup limit must be an integer from 1 through 1,000',
|
|
35
|
+
'sync.storage.erase_unsupported': 'this storage backend cannot erase a scope value',
|
|
36
|
+
'sync.storage.invalid_erase_query': 'erasure requires a declared scope variable, a non-empty value, and a row budget within the operation cap',
|
|
35
37
|
};
|
|
36
38
|
/**
|
|
37
39
|
* Host-only query error. Messages never include identifiers, values, SQL,
|
package/dist/storage.d.ts
CHANGED
|
@@ -701,6 +701,22 @@ export interface ServerStorage {
|
|
|
701
701
|
*/
|
|
702
702
|
listRowsReferencingBlob?(partition: string, blobId: string): Promise<BlobReferencingRow[]>;
|
|
703
703
|
listReferencedBlobIds?(partition: string): Promise<string[]>;
|
|
704
|
+
/**
|
|
705
|
+
* §4.6.1 scope-value erasure — ADDITIVE, optional; `eraseScopeValue`
|
|
706
|
+
* requires both.
|
|
707
|
+
*
|
|
708
|
+
* `listScopeValueRows`: up to `limit` rowIds of `table` whose stored scope
|
|
709
|
+
* binds `variable` to `value`, ordered by rowId (the row scope index).
|
|
710
|
+
*
|
|
711
|
+
* `eraseScopeValueHistory`: under the partition write lock, removes up to
|
|
712
|
+
* `limit` upsert change records of `table` at or below `throughSeq` whose
|
|
713
|
+
* scopes bind `variable` to `value`, then up to `limit` change scope index
|
|
714
|
+
* entries of that binding whose commit holds no such change any more.
|
|
715
|
+
* Delete change records stay: clients behind the erasure still need them.
|
|
716
|
+
* Returns the number of records removed.
|
|
717
|
+
*/
|
|
718
|
+
listScopeValueRows?(partition: string, query: ScopeValueQuery): Promise<string[]>;
|
|
719
|
+
eraseScopeValueHistory?(partition: string, query: ScopeValueHistoryQuery): Promise<number>;
|
|
704
720
|
/**
|
|
705
721
|
* Admin/console read surface (`SyncularAdmin`): ADDITIVE,
|
|
706
722
|
* optional. All read-only, partition-scoped, and JSON-able. A backend
|
|
@@ -736,6 +752,16 @@ export interface ServerStorage {
|
|
|
736
752
|
listPushResults?(partition: string, clientCommitId: string): Promise<ClientPushResult[]>;
|
|
737
753
|
listPartitions(): Promise<string[]>;
|
|
738
754
|
}
|
|
755
|
+
/** One scope binding of one table, budgeted (§4.6.1). */
|
|
756
|
+
export interface ScopeValueQuery {
|
|
757
|
+
readonly table: string;
|
|
758
|
+
readonly variable: string;
|
|
759
|
+
readonly value: string;
|
|
760
|
+
readonly limit: number;
|
|
761
|
+
}
|
|
762
|
+
export interface ScopeValueHistoryQuery extends ScopeValueQuery {
|
|
763
|
+
readonly throughSeq: number;
|
|
764
|
+
}
|
|
739
765
|
/** A row referencing a blob, with the scopes needed to authorize download. */
|
|
740
766
|
export interface BlobReferencingRow {
|
|
741
767
|
readonly table: string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@syncular/server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.35.0",
|
|
4
4
|
"description": "Syncular server: handleSyncRequest + storage/auth interfaces for the sync protocol",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Benjamin Kniffler",
|
|
@@ -68,7 +68,7 @@
|
|
|
68
68
|
"verify:node": "cd ../.. && bun build ./packages/server/test/sqlite-runtime/verify-node.mjs --target=node --conditions=bun --outfile=./packages/server/.verify-node.built.mjs && node ./packages/server/.verify-node.built.mjs"
|
|
69
69
|
},
|
|
70
70
|
"dependencies": {
|
|
71
|
-
"@syncular/core": "0.
|
|
71
|
+
"@syncular/core": "0.35.0"
|
|
72
72
|
},
|
|
73
73
|
"devDependencies": {
|
|
74
74
|
"@electric-sql/pglite": "^0.5.4"
|
package/src/blob-handlers.ts
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* `blobId` is never a bearer capability. Framework-free; the hono/runtime
|
|
7
7
|
* adapters map these onto `PUT/GET <mount>/blobs/{blobId}`.
|
|
8
8
|
*/
|
|
9
|
-
import { blobIdFor, isBlobId } from './blob-store';
|
|
9
|
+
import { type BlobRecord, blobIdFor, isBlobId } from './blob-store';
|
|
10
10
|
import type { SyncRequestContext } from './context';
|
|
11
11
|
import {
|
|
12
12
|
clockOf,
|
|
@@ -180,7 +180,7 @@ async function downloadBlob(
|
|
|
180
180
|
// egress path — it only needs to know the object EXISTS (a HEAD/`has`), not
|
|
181
181
|
// the bytes. Inline delivery loads the bytes; presigned delivery does not.
|
|
182
182
|
const presignConfigured = ctx.blobSignedUrls !== undefined;
|
|
183
|
-
let entry: { bytes: Uint8Array } | undefined;
|
|
183
|
+
let entry: { record: BlobRecord; bytes: Uint8Array } | undefined;
|
|
184
184
|
if (presignConfigured) {
|
|
185
185
|
if (!(await store.has(ctx.partition, blobId))) {
|
|
186
186
|
throw syncError('blob.not_found', 'unknown blob (§5.9.5)');
|
|
@@ -277,12 +277,20 @@ async function downloadBlob(
|
|
|
277
277
|
// Unreachable: presign not configured ⇒ `entry` was loaded above.
|
|
278
278
|
throw syncError('blob.not_found', 'blob bytes unavailable (§5.9.5)');
|
|
279
279
|
}
|
|
280
|
-
// §5.9.5: inline bytes
|
|
281
|
-
//
|
|
280
|
+
// §5.9.5: inline bytes carry the stored media type, so an <img> or <a>
|
|
281
|
+
// pointed at the route renders them. A JSON type stays octet-stream: a
|
|
282
|
+
// JSON body is reserved for the signed-URL envelope.
|
|
283
|
+
const mediaType = entry?.record.mediaType;
|
|
282
284
|
return {
|
|
283
285
|
bytes,
|
|
284
286
|
headers: {
|
|
285
|
-
'Content-Type':
|
|
287
|
+
'Content-Type':
|
|
288
|
+
mediaType === undefined ||
|
|
289
|
+
mediaType.toLowerCase().includes('application/json')
|
|
290
|
+
? 'application/octet-stream'
|
|
291
|
+
: mediaType,
|
|
292
|
+
'X-Content-Type-Options': 'nosniff',
|
|
293
|
+
'Content-Security-Policy': "sandbox; default-src 'none'",
|
|
286
294
|
ETag: `"${blobId}"`,
|
|
287
295
|
'Cache-Control': 'private, max-age=0',
|
|
288
296
|
Vary: 'Authorization, Accept-Encoding',
|
package/src/blob-store.ts
CHANGED
|
Binary file
|
package/src/bucket-blob-store.ts
CHANGED
|
@@ -218,29 +218,31 @@ export class BucketBlobStore implements BlobStore {
|
|
|
218
218
|
// blob once, and preserve the FIRST createdAtMs so the sweep's grace clock
|
|
219
219
|
// is not reset by a re-upload (§5.9.2 upload age).
|
|
220
220
|
const preexisting = await this.#bucket.head(objectKey);
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
}
|
|
221
|
+
const storedMeta = preexisting?.metadata[BLOB_META_KEY];
|
|
222
|
+
const existing =
|
|
223
|
+
storedMeta === undefined
|
|
224
|
+
? undefined
|
|
225
|
+
: parseMetaJson(base64urlToUtf8(storedMeta), blobId, this.#label);
|
|
226
|
+
if (
|
|
227
|
+
existing !== undefined &&
|
|
228
|
+
(existing.mediaType !== undefined || mediaType === undefined)
|
|
229
|
+
) {
|
|
230
|
+
return {
|
|
231
|
+
blobId,
|
|
232
|
+
partition,
|
|
233
|
+
byteLength: existing.byteLength,
|
|
234
|
+
...(existing.mediaType !== undefined
|
|
235
|
+
? { mediaType: existing.mediaType }
|
|
236
|
+
: {}),
|
|
237
|
+
createdAtMs: existing.createdAtMs,
|
|
238
|
+
};
|
|
239
239
|
}
|
|
240
|
+
// A re-upload that names the media type an earlier upload left out
|
|
241
|
+
// rewrites the object under the same precondition, keeping its age.
|
|
240
242
|
const meta: BlobMeta = {
|
|
241
243
|
byteLength: bytes.length,
|
|
242
244
|
...(mediaType !== undefined ? { mediaType } : {}),
|
|
243
|
-
createdAtMs: nowMs,
|
|
245
|
+
createdAtMs: existing?.createdAtMs ?? nowMs,
|
|
244
246
|
};
|
|
245
247
|
// Conditional write: of two concurrent uploads of the same blob exactly
|
|
246
248
|
// one lands, so the first createdAtMs survives and the blob counts once.
|
|
@@ -256,7 +258,11 @@ export class BucketBlobStore implements BlobStore {
|
|
|
256
258
|
if (!written) return this.put(partition, blobId, bytes, nowMs, mediaType);
|
|
257
259
|
if (preexisting === undefined)
|
|
258
260
|
await this.#bumpStats({ count: 1, bytes: bytes.length });
|
|
259
|
-
return record;
|
|
261
|
+
return { ...record, createdAtMs: meta.createdAtMs };
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
async delete(partition: string, blobId: string): Promise<void> {
|
|
265
|
+
await this.#bucket.delete(this.objectKeyFor(partition, blobId));
|
|
260
266
|
}
|
|
261
267
|
|
|
262
268
|
async has(partition: string, blobId: string): Promise<boolean> {
|
package/src/d1-storage.ts
CHANGED
|
@@ -54,7 +54,7 @@ import {
|
|
|
54
54
|
assertPhysicalColumns,
|
|
55
55
|
assertStoredLayouts,
|
|
56
56
|
commitWindowPageSql,
|
|
57
|
-
|
|
57
|
+
LATEST_SCOPED_CHANGE_SEQ_SQLITE_SQL,
|
|
58
58
|
deleteRowSql,
|
|
59
59
|
deleteSqliteRowScopesSql,
|
|
60
60
|
dropTableDdl,
|
|
@@ -92,6 +92,9 @@ import {
|
|
|
92
92
|
collectCommitWindowPage,
|
|
93
93
|
deserializePushResult,
|
|
94
94
|
placeholders,
|
|
95
|
+
ERASE_SCOPE_VALUE_HISTORY_SQLITE_SQL,
|
|
96
|
+
eraseScopeValueHistoryParams,
|
|
97
|
+
LIST_SCOPE_VALUE_ROWS_SQLITE_SQL,
|
|
95
98
|
type SqliteChangeRecord,
|
|
96
99
|
type SqliteCommitWindowRecord,
|
|
97
100
|
type SqliteRowRecord,
|
|
@@ -130,6 +133,8 @@ import type {
|
|
|
130
133
|
RowScanQuery,
|
|
131
134
|
ScopeActivityQuery,
|
|
132
135
|
ScopeCommitActivity,
|
|
136
|
+
ScopeValueHistoryQuery,
|
|
137
|
+
ScopeValueQuery,
|
|
133
138
|
ServerStorage,
|
|
134
139
|
ServeGate,
|
|
135
140
|
StorageTransaction,
|
|
@@ -2189,8 +2194,8 @@ export class D1ServerStorage implements ServerStorage {
|
|
|
2189
2194
|
if (firstVariable === undefined || values.length === 0) return 0;
|
|
2190
2195
|
// Concurrent reads of a pull share one `db.batch` round trip.
|
|
2191
2196
|
const [row] = await this.#batchedAll<{ seq: number | null }>(
|
|
2192
|
-
|
|
2193
|
-
|
|
2197
|
+
LATEST_SCOPED_CHANGE_SEQ_SQLITE_SQL,
|
|
2198
|
+
[partition, query.table, firstVariable, JSON.stringify(values)],
|
|
2194
2199
|
);
|
|
2195
2200
|
return row?.seq ?? 0;
|
|
2196
2201
|
}
|
|
@@ -2473,6 +2478,46 @@ export class D1ServerStorage implements ServerStorage {
|
|
|
2473
2478
|
return results.map((r) => r.blob_id);
|
|
2474
2479
|
}
|
|
2475
2480
|
|
|
2481
|
+
async listScopeValueRows(
|
|
2482
|
+
partition: string,
|
|
2483
|
+
query: ScopeValueQuery,
|
|
2484
|
+
): Promise<string[]> {
|
|
2485
|
+
const { results } = await this.#db
|
|
2486
|
+
.prepare(LIST_SCOPE_VALUE_ROWS_SQLITE_SQL)
|
|
2487
|
+
.bind(partition, query.table, query.variable, query.value, query.limit)
|
|
2488
|
+
.all<{ row_id: string }>();
|
|
2489
|
+
return results.map((row) => row.row_id);
|
|
2490
|
+
}
|
|
2491
|
+
|
|
2492
|
+
async eraseScopeValueHistory(
|
|
2493
|
+
partition: string,
|
|
2494
|
+
query: ScopeValueHistoryQuery,
|
|
2495
|
+
): Promise<number> {
|
|
2496
|
+
if (!this.#pushApplySerialized)
|
|
2497
|
+
throw new Error(
|
|
2498
|
+
'D1 erasure requires externally serialized partition writes',
|
|
2499
|
+
);
|
|
2500
|
+
const params = eraseScopeValueHistoryParams(partition, query);
|
|
2501
|
+
const results = await this.#db.batch(
|
|
2502
|
+
ERASE_SCOPE_VALUE_HISTORY_SQLITE_SQL.map((sql) =>
|
|
2503
|
+
this.#db.prepare(sql).bind(...params),
|
|
2504
|
+
),
|
|
2505
|
+
);
|
|
2506
|
+
let removed = 0;
|
|
2507
|
+
for (const result of results) {
|
|
2508
|
+
if (
|
|
2509
|
+
typeof result !== 'object' ||
|
|
2510
|
+
result === null ||
|
|
2511
|
+
!('results' in result) ||
|
|
2512
|
+
!Array.isArray(result.results)
|
|
2513
|
+
) {
|
|
2514
|
+
throw new Error('D1 erasure returned an invalid batch result');
|
|
2515
|
+
}
|
|
2516
|
+
removed += result.results.length;
|
|
2517
|
+
}
|
|
2518
|
+
return removed;
|
|
2519
|
+
}
|
|
2520
|
+
|
|
2476
2521
|
// -- admin/console read surface --------------------------------------------
|
|
2477
2522
|
|
|
2478
2523
|
async listClientRecords(partition: string): Promise<ClientRecord[]> {
|
package/src/erase.ts
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scope-value erasure (SPEC.md §4.6.1): remove every row whose stored scope
|
|
3
|
+
* binds one variable to one value, the upsert change records that carried
|
|
4
|
+
* those rows, and the blob bytes no remaining row references.
|
|
5
|
+
*
|
|
6
|
+
* Live rows leave through one ordinary delete commit per call, applied on
|
|
7
|
+
* the shared push path (partition lock, tombstones, blob reference index,
|
|
8
|
+
* realtime fanout). The commit advances the binding's scoped change seq, so
|
|
9
|
+
* no cached segment taken before the erasure is reused, and every client
|
|
10
|
+
* holding the rows receives the deletes. Once no live row is left, each call
|
|
11
|
+
* scrubs the change log of the binding. Hosts loop until `done`.
|
|
12
|
+
*/
|
|
13
|
+
import { decodeRow, type PushOperation } from '@syncular/core';
|
|
14
|
+
import { limitsOf, type SyncServerConfig } from './context';
|
|
15
|
+
import { SyncError } from './errors';
|
|
16
|
+
import { blobIdsInRow, processPushOperationsWithTrace } from './push';
|
|
17
|
+
import { compileSchema } from './schema';
|
|
18
|
+
import { StorageQueryError } from './storage-errors';
|
|
19
|
+
|
|
20
|
+
export interface EraseScopeValueOptions {
|
|
21
|
+
readonly partition: string;
|
|
22
|
+
/** The scope variable as declared by the schema's scope patterns. */
|
|
23
|
+
readonly variable: string;
|
|
24
|
+
readonly value: string;
|
|
25
|
+
/**
|
|
26
|
+
* Rows deleted per call, and change records removed per table per call
|
|
27
|
+
* (default 200, at most the push operation cap).
|
|
28
|
+
*/
|
|
29
|
+
readonly maxRows?: number;
|
|
30
|
+
/** Actor recorded on the erasure commits (default `syncular.erase`). */
|
|
31
|
+
readonly actorId?: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface EraseScopeValueResult {
|
|
35
|
+
/** Rows the erasure commit of this call deleted. */
|
|
36
|
+
readonly rowsErased: number;
|
|
37
|
+
/** The erasure commit of this call, when it deleted rows. */
|
|
38
|
+
readonly commitSeq?: number;
|
|
39
|
+
/** Change log records this call removed. */
|
|
40
|
+
readonly historyErased: number;
|
|
41
|
+
/** Blobs whose last reference this call removed; their bytes are gone. */
|
|
42
|
+
readonly blobsErased: readonly string[];
|
|
43
|
+
/** Nothing of the binding is left; further calls change nothing. */
|
|
44
|
+
readonly done: boolean;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Erase one scope binding of one partition, one budgeted step per call. */
|
|
48
|
+
export async function eraseScopeValue(
|
|
49
|
+
config: SyncServerConfig,
|
|
50
|
+
options: EraseScopeValueOptions,
|
|
51
|
+
): Promise<EraseScopeValueResult> {
|
|
52
|
+
const { storage } = config;
|
|
53
|
+
const { partition, variable, value } = options;
|
|
54
|
+
const maxRows = options.maxRows ?? 200;
|
|
55
|
+
const listRows = storage.listScopeValueRows?.bind(storage);
|
|
56
|
+
const eraseHistory = storage.eraseScopeValueHistory?.bind(storage);
|
|
57
|
+
const listReferences = storage.listRowsReferencingBlob?.bind(storage);
|
|
58
|
+
if (
|
|
59
|
+
listRows === undefined ||
|
|
60
|
+
eraseHistory === undefined ||
|
|
61
|
+
listReferences === undefined
|
|
62
|
+
) {
|
|
63
|
+
throw new StorageQueryError('sync.storage.erase_unsupported');
|
|
64
|
+
}
|
|
65
|
+
const schema = compileSchema(config.schema);
|
|
66
|
+
const tables = [...schema.tables.values()].filter((table) =>
|
|
67
|
+
table.scopePatterns.some((pattern) => pattern.variable === variable),
|
|
68
|
+
);
|
|
69
|
+
if (
|
|
70
|
+
tables.length === 0 ||
|
|
71
|
+
value.length === 0 ||
|
|
72
|
+
!Number.isSafeInteger(maxRows) ||
|
|
73
|
+
maxRows < 1 ||
|
|
74
|
+
maxRows > limitsOf(config).maxOperationsPerRequest
|
|
75
|
+
) {
|
|
76
|
+
throw new StorageQueryError('sync.storage.invalid_erase_query');
|
|
77
|
+
}
|
|
78
|
+
if ((await storage.getPartitionLogEpoch(partition)) === undefined) {
|
|
79
|
+
return { rowsErased: 0, historyErased: 0, blobsErased: [], done: true };
|
|
80
|
+
}
|
|
81
|
+
await storage.ensureSchema(schema, config.checkpoints);
|
|
82
|
+
|
|
83
|
+
const targets: { table: string; rowId: string }[] = [];
|
|
84
|
+
for (const table of tables) {
|
|
85
|
+
const limit = maxRows - targets.length;
|
|
86
|
+
if (limit === 0) break;
|
|
87
|
+
const query = { table: table.name, variable, value, limit };
|
|
88
|
+
for (const rowId of await listRows(partition, query)) {
|
|
89
|
+
targets.push({ table: table.name, rowId });
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
if (targets.length > 0) {
|
|
94
|
+
// Erasure is the operator's act: app validators do not gate it.
|
|
95
|
+
const { validators, commitValidator, ...trusted } = config;
|
|
96
|
+
const blobIds = new Set<string>();
|
|
97
|
+
let rowsErased = 0;
|
|
98
|
+
const processed = await processPushOperationsWithTrace(
|
|
99
|
+
{ ...trusted, partition, actorId: options.actorId ?? 'syncular.erase' },
|
|
100
|
+
schema,
|
|
101
|
+
{
|
|
102
|
+
ok: true,
|
|
103
|
+
allowed: Object.fromEntries(
|
|
104
|
+
[...schema.tables.values()].flatMap((table) =>
|
|
105
|
+
table.scopePatterns.map((pattern) => [pattern.variable, ['*']]),
|
|
106
|
+
),
|
|
107
|
+
),
|
|
108
|
+
},
|
|
109
|
+
'syncular.erase',
|
|
110
|
+
crypto.randomUUID(),
|
|
111
|
+
async (tx) => {
|
|
112
|
+
const operations: PushOperation[] = [];
|
|
113
|
+
for (const target of targets) {
|
|
114
|
+
// Re-read under the partition lock: a row may have moved or gone.
|
|
115
|
+
const stored = await tx.getRow(target.table, target.rowId);
|
|
116
|
+
if (stored?.scopes[variable] !== value) continue;
|
|
117
|
+
const table = schema.tables.get(target.table)!;
|
|
118
|
+
for (const blobId of blobIdsInRow(
|
|
119
|
+
table,
|
|
120
|
+
decodeRow(table.columns, stored.payload),
|
|
121
|
+
)) {
|
|
122
|
+
blobIds.add(blobId);
|
|
123
|
+
}
|
|
124
|
+
operations.push({
|
|
125
|
+
table: target.table,
|
|
126
|
+
op: 'delete',
|
|
127
|
+
rowId: target.rowId,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
rowsErased = operations.length;
|
|
131
|
+
return operations;
|
|
132
|
+
},
|
|
133
|
+
);
|
|
134
|
+
const { frame } = processed;
|
|
135
|
+
if (frame.status !== 'applied') {
|
|
136
|
+
const failed = frame.results.find((result) => 'code' in result);
|
|
137
|
+
throw failed !== undefined && 'code' in failed
|
|
138
|
+
? new SyncError(failed.code, failed.message)
|
|
139
|
+
: new Error('eraseScopeValue: the erasure commit was not applied');
|
|
140
|
+
}
|
|
141
|
+
const blobsErased: string[] = [];
|
|
142
|
+
for (const blobId of blobIds) {
|
|
143
|
+
if ((await listReferences(partition, blobId)).length > 0) continue;
|
|
144
|
+
await config.blobs?.delete(partition, blobId);
|
|
145
|
+
blobsErased.push(blobId);
|
|
146
|
+
}
|
|
147
|
+
return {
|
|
148
|
+
rowsErased,
|
|
149
|
+
...(frame.commitSeq !== undefined ? { commitSeq: frame.commitSeq } : {}),
|
|
150
|
+
historyErased: 0,
|
|
151
|
+
blobsErased,
|
|
152
|
+
done: false,
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const throughSeq = await storage.getMaxCommitSeq(partition);
|
|
157
|
+
let historyErased = 0;
|
|
158
|
+
for (const table of tables) {
|
|
159
|
+
historyErased += await eraseHistory(partition, {
|
|
160
|
+
table: table.name,
|
|
161
|
+
variable,
|
|
162
|
+
value,
|
|
163
|
+
throughSeq,
|
|
164
|
+
limit: maxRows,
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
return {
|
|
168
|
+
rowsErased: 0,
|
|
169
|
+
historyErased,
|
|
170
|
+
blobsErased: [],
|
|
171
|
+
done: historyErased === 0,
|
|
172
|
+
};
|
|
173
|
+
}
|
package/src/index.ts
CHANGED