@syncular/server 0.34.0 → 0.36.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.
@@ -189,12 +189,19 @@ async function downloadBlob(ctx, blobId) {
189
189
  // Unreachable: presign not configured ⇒ `entry` was loaded above.
190
190
  throw syncError('blob.not_found', 'blob bytes unavailable (§5.9.5)');
191
191
  }
192
- // §5.9.5: inline bytes are always octet-stream. The stored media type
193
- // would make a JSON blob indistinguishable from the signed-URL envelope.
192
+ // §5.9.5: inline bytes carry the stored media type, so an <img> or <a>
193
+ // pointed at the route renders them. A JSON type stays octet-stream: a
194
+ // JSON body is reserved for the signed-URL envelope.
195
+ const mediaType = entry?.record.mediaType;
194
196
  return {
195
197
  bytes,
196
198
  headers: {
197
- 'Content-Type': 'application/octet-stream',
199
+ 'Content-Type': mediaType === undefined ||
200
+ mediaType.toLowerCase().includes('application/json')
201
+ ? 'application/octet-stream'
202
+ : mediaType,
203
+ 'X-Content-Type-Options': 'nosniff',
204
+ 'Content-Security-Policy': "sandbox; default-src 'none'",
198
205
  ETag: `"${blobId}"`,
199
206
  'Cache-Control': 'private, max-age=0',
200
207
  Vary: 'Authorization, Accept-Encoding',
@@ -37,7 +37,9 @@ export interface BlobStoreStats {
37
37
  export interface BlobStore {
38
38
  /**
39
39
  * Store blob bytes under `blobId` (idempotent — same id ⇒ no-op success,
40
- * §5.9.3). The caller has already verified the content address matches.
40
+ * §5.9.3). A re-upload that declares a media type records it on a blob
41
+ * stored without one; a recorded media type never changes. The caller has
42
+ * already verified the content address matches.
41
43
  */
42
44
  put(partition: string, blobId: string, bytes: Uint8Array, nowMs: number, mediaType?: string): Promise<BlobRecord>;
43
45
  /** Presence check for the push existence rule (§5.9.6) and download. */
@@ -53,6 +55,11 @@ export interface BlobStore {
53
55
  * Returns the deleted blobIds.
54
56
  */
55
57
  sweepOrphans(partition: string, olderThanMs: number, referencedBlobIds: ReadonlySet<string>): Promise<string[]>;
58
+ /**
59
+ * §4.6.1 erasure: delete one blob whose last reference is gone. Deleting a
60
+ * missing blob is a no-op.
61
+ */
62
+ delete(partition: string, blobId: string): Promise<void>;
56
63
  /** Admin/console counters (work item §2.5) — ADDITIVE, optional. */
57
64
  stats?(partition: string): Promise<BlobStoreStats>;
58
65
  }
@@ -68,6 +75,7 @@ export declare class MemoryBlobStore implements BlobStore {
68
75
  bytes: Uint8Array;
69
76
  } | undefined>;
70
77
  sweepOrphans(partition: string, olderThanMs: number, referencedBlobIds: ReadonlySet<string>): Promise<string[]>;
78
+ delete(partition: string, blobId: string): Promise<void>;
71
79
  stats(partition: string): Promise<BlobStoreStats>;
72
80
  }
73
81
  export interface SweepOrphanBlobsOptions {
Binary file
@@ -51,6 +51,7 @@ export declare class BucketBlobStore implements BlobStore {
51
51
  */
52
52
  objectKeyFor(partition: string, blobId: string): string;
53
53
  put(partition: string, blobId: string, bytes: Uint8Array, nowMs: number, mediaType?: string): Promise<BlobRecord>;
54
+ delete(partition: string, blobId: string): Promise<void>;
54
55
  has(partition: string, blobId: string): Promise<boolean>;
55
56
  get(partition: string, blobId: string): Promise<{
56
57
  record: BlobRecord;
@@ -141,25 +141,28 @@ export class BucketBlobStore {
141
141
  // blob once, and preserve the FIRST createdAtMs so the sweep's grace clock
142
142
  // is not reset by a re-upload (§5.9.2 upload age).
143
143
  const preexisting = await this.#bucket.head(objectKey);
144
- if (preexisting !== undefined) {
145
- const meta = preexisting.metadata[BLOB_META_KEY];
146
- if (meta !== undefined) {
147
- const existing = parseMetaJson(base64urlToUtf8(meta), blobId, this.#label);
148
- return {
149
- blobId,
150
- partition,
151
- byteLength: existing.byteLength,
152
- ...(existing.mediaType !== undefined
153
- ? { mediaType: existing.mediaType }
154
- : {}),
155
- createdAtMs: existing.createdAtMs,
156
- };
157
- }
144
+ const storedMeta = preexisting?.metadata[BLOB_META_KEY];
145
+ const existing = storedMeta === undefined
146
+ ? undefined
147
+ : parseMetaJson(base64urlToUtf8(storedMeta), blobId, this.#label);
148
+ if (existing !== undefined &&
149
+ (existing.mediaType !== undefined || mediaType === undefined)) {
150
+ return {
151
+ blobId,
152
+ partition,
153
+ byteLength: existing.byteLength,
154
+ ...(existing.mediaType !== undefined
155
+ ? { mediaType: existing.mediaType }
156
+ : {}),
157
+ createdAtMs: existing.createdAtMs,
158
+ };
158
159
  }
160
+ // A re-upload that names the media type an earlier upload left out
161
+ // rewrites the object under the same precondition, keeping its age.
159
162
  const meta = {
160
163
  byteLength: bytes.length,
161
164
  ...(mediaType !== undefined ? { mediaType } : {}),
162
- createdAtMs: nowMs,
165
+ createdAtMs: existing?.createdAtMs ?? nowMs,
163
166
  };
164
167
  // Conditional write: of two concurrent uploads of the same blob exactly
165
168
  // one lands, so the first createdAtMs survives and the blob counts once.
@@ -176,7 +179,10 @@ export class BucketBlobStore {
176
179
  return this.put(partition, blobId, bytes, nowMs, mediaType);
177
180
  if (preexisting === undefined)
178
181
  await this.#bumpStats({ count: 1, bytes: bytes.length });
179
- return record;
182
+ return { ...record, createdAtMs: meta.createdAtMs };
183
+ }
184
+ async delete(partition, blobId) {
185
+ await this.#bucket.delete(this.objectKeyFor(partition, blobId));
180
186
  }
181
187
  async has(partition, blobId) {
182
188
  if (!BLOB_ID_PATTERN.test(blobId))
@@ -42,7 +42,7 @@ import type { CommitPruneQuery, CommitPruneResult } from './storage.js';
42
42
  */
43
43
  import { type ScopeMap } from '@syncular/core';
44
44
  import type { CompiledSchema, CompiledTable } from './schema.js';
45
- 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';
45
+ 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';
46
46
  export interface D1PreparedStatement {
47
47
  bind(...values: unknown[]): D1PreparedStatement;
48
48
  first<T = Record<string, unknown>>(): Promise<T | null>;
@@ -134,6 +134,8 @@ export declare class D1ServerStorage implements ServerStorage {
134
134
  readonly scopes: Record<string, string>;
135
135
  }[]>;
136
136
  listReferencedBlobIds(partition: string): Promise<string[]>;
137
+ listScopeValueRows(partition: string, query: ScopeValueQuery): Promise<string[]>;
138
+ eraseScopeValueHistory(partition: string, query: ScopeValueHistoryQuery): Promise<number>;
137
139
  listClientRecords(partition: string): Promise<ClientRecord[]>;
138
140
  listCommitMetadata(partition: string, query: CommitMetadataQuery): Promise<CommitMetadata[]>;
139
141
  getCommit(partition: string, commitSeq: number): Promise<CommitDetail | undefined>;
@@ -47,7 +47,7 @@ import { bindAuthoritativePartition, prepareAuthoritativeQuery, } from './author
47
47
  import { syncError } from './errors.js';
48
48
  import { assertAppendOnlyMigration, 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, tableColumnNames, toSqlValue, upsertSql, upsertValues, } from './relational-rows.js';
49
49
  import { matchesEffective } from './scopes.js';
50
- import { asUint8Array, collectCommitWindowPage, deserializePushResult, placeholders, serializePushResult, sqliteDdlStatements, toStoredChange, toStoredRow, } from './sqlite-dialect.js';
50
+ import { asUint8Array, collectCommitWindowPage, deserializePushResult, placeholders, ERASE_SCOPE_VALUE_HISTORY_SQLITE_SQL, eraseScopeValueHistoryParams, LIST_SCOPE_VALUE_ROWS_SQLITE_SQL, serializePushResult, sqliteDdlStatements, toStoredChange, toStoredRow, } from './sqlite-dialect.js';
51
51
  import { isD1ConstraintError, StorageConstraintError } from './storage-errors.js';
52
52
  import { assertScopeIndexedScan, resolveIndexRowScan } from './storage-query.js';
53
53
  function toStoredReaction(record) {
@@ -1654,6 +1654,30 @@ export class D1ServerStorage {
1654
1654
  .all();
1655
1655
  return results.map((r) => r.blob_id);
1656
1656
  }
1657
+ async listScopeValueRows(partition, query) {
1658
+ const { results } = await this.#db
1659
+ .prepare(LIST_SCOPE_VALUE_ROWS_SQLITE_SQL)
1660
+ .bind(partition, query.table, query.variable, query.value, query.limit)
1661
+ .all();
1662
+ return results.map((row) => row.row_id);
1663
+ }
1664
+ async eraseScopeValueHistory(partition, query) {
1665
+ if (!this.#pushApplySerialized)
1666
+ throw new Error('D1 erasure requires externally serialized partition writes');
1667
+ const params = eraseScopeValueHistoryParams(partition, query);
1668
+ const results = await this.#db.batch(ERASE_SCOPE_VALUE_HISTORY_SQLITE_SQL.map((sql) => this.#db.prepare(sql).bind(...params)));
1669
+ let removed = 0;
1670
+ for (const result of results) {
1671
+ if (typeof result !== 'object' ||
1672
+ result === null ||
1673
+ !('results' in result) ||
1674
+ !Array.isArray(result.results)) {
1675
+ throw new Error('D1 erasure returned an invalid batch result');
1676
+ }
1677
+ removed += result.results.length;
1678
+ }
1679
+ return removed;
1680
+ }
1657
1681
  // -- admin/console read surface --------------------------------------------
1658
1682
  async listClientRecords(partition) {
1659
1683
  const { results } = await this.#db
@@ -0,0 +1,28 @@
1
+ import { type SyncServerConfig } from './context.js';
2
+ export interface EraseScopeValueOptions {
3
+ readonly partition: string;
4
+ /** The scope variable as declared by the schema's scope patterns. */
5
+ readonly variable: string;
6
+ readonly value: string;
7
+ /**
8
+ * Rows deleted per call, and change records removed per table per call
9
+ * (default 200, at most the push operation cap).
10
+ */
11
+ readonly maxRows?: number;
12
+ /** Actor recorded on the erasure commits (default `syncular.erase`). */
13
+ readonly actorId?: string;
14
+ }
15
+ export interface EraseScopeValueResult {
16
+ /** Rows the erasure commit of this call deleted. */
17
+ readonly rowsErased: number;
18
+ /** The erasure commit of this call, when it deleted rows. */
19
+ readonly commitSeq?: number;
20
+ /** Change log records this call removed. */
21
+ readonly historyErased: number;
22
+ /** Blobs whose last reference this call removed; their bytes are gone. */
23
+ readonly blobsErased: readonly string[];
24
+ /** Nothing of the binding is left; further calls change nothing. */
25
+ readonly done: boolean;
26
+ }
27
+ /** Erase one scope binding of one partition, one budgeted step per call. */
28
+ export declare function eraseScopeValue(config: SyncServerConfig, options: EraseScopeValueOptions): Promise<EraseScopeValueResult>;
package/dist/erase.js ADDED
@@ -0,0 +1,122 @@
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 } from '@syncular/core';
14
+ import { limitsOf } from './context.js';
15
+ import { SyncError } from './errors.js';
16
+ import { blobIdsInRow, processPushOperationsWithTrace } from './push.js';
17
+ import { compileSchema } from './schema.js';
18
+ import { StorageQueryError } from './storage-errors.js';
19
+ /** Erase one scope binding of one partition, one budgeted step per call. */
20
+ export async function eraseScopeValue(config, options) {
21
+ const { storage } = config;
22
+ const { partition, variable, value } = options;
23
+ const maxRows = options.maxRows ?? 200;
24
+ const listRows = storage.listScopeValueRows?.bind(storage);
25
+ const eraseHistory = storage.eraseScopeValueHistory?.bind(storage);
26
+ const listReferences = storage.listRowsReferencingBlob?.bind(storage);
27
+ if (listRows === undefined ||
28
+ eraseHistory === undefined ||
29
+ listReferences === undefined) {
30
+ throw new StorageQueryError('sync.storage.erase_unsupported');
31
+ }
32
+ const schema = compileSchema(config.schema);
33
+ const tables = [...schema.tables.values()].filter((table) => table.scopePatterns.some((pattern) => pattern.variable === variable));
34
+ if (tables.length === 0 ||
35
+ value.length === 0 ||
36
+ !Number.isSafeInteger(maxRows) ||
37
+ maxRows < 1 ||
38
+ maxRows > limitsOf(config).maxOperationsPerRequest) {
39
+ throw new StorageQueryError('sync.storage.invalid_erase_query');
40
+ }
41
+ if ((await storage.getPartitionLogEpoch(partition)) === undefined) {
42
+ return { rowsErased: 0, historyErased: 0, blobsErased: [], done: true };
43
+ }
44
+ await storage.ensureSchema(schema, config.checkpoints);
45
+ const targets = [];
46
+ for (const table of tables) {
47
+ const limit = maxRows - targets.length;
48
+ if (limit === 0)
49
+ break;
50
+ const query = { table: table.name, variable, value, limit };
51
+ for (const rowId of await listRows(partition, query)) {
52
+ targets.push({ table: table.name, rowId });
53
+ }
54
+ }
55
+ if (targets.length > 0) {
56
+ // Erasure is the operator's act: app validators do not gate it.
57
+ const { validators, commitValidator, ...trusted } = config;
58
+ const blobIds = new Set();
59
+ let rowsErased = 0;
60
+ const processed = await processPushOperationsWithTrace({ ...trusted, partition, actorId: options.actorId ?? 'syncular.erase' }, schema, {
61
+ ok: true,
62
+ allowed: Object.fromEntries([...schema.tables.values()].flatMap((table) => table.scopePatterns.map((pattern) => [pattern.variable, ['*']]))),
63
+ }, 'syncular.erase', crypto.randomUUID(), async (tx) => {
64
+ const operations = [];
65
+ for (const target of targets) {
66
+ // Re-read under the partition lock: a row may have moved or gone.
67
+ const stored = await tx.getRow(target.table, target.rowId);
68
+ if (stored?.scopes[variable] !== value)
69
+ continue;
70
+ const table = schema.tables.get(target.table);
71
+ for (const blobId of blobIdsInRow(table, decodeRow(table.columns, stored.payload))) {
72
+ blobIds.add(blobId);
73
+ }
74
+ operations.push({
75
+ table: target.table,
76
+ op: 'delete',
77
+ rowId: target.rowId,
78
+ });
79
+ }
80
+ rowsErased = operations.length;
81
+ return operations;
82
+ });
83
+ const { frame } = processed;
84
+ if (frame.status !== 'applied') {
85
+ const failed = frame.results.find((result) => 'code' in result);
86
+ throw failed !== undefined && 'code' in failed
87
+ ? new SyncError(failed.code, failed.message)
88
+ : new Error('eraseScopeValue: the erasure commit was not applied');
89
+ }
90
+ const blobsErased = [];
91
+ for (const blobId of blobIds) {
92
+ if ((await listReferences(partition, blobId)).length > 0)
93
+ continue;
94
+ await config.blobs?.delete(partition, blobId);
95
+ blobsErased.push(blobId);
96
+ }
97
+ return {
98
+ rowsErased,
99
+ ...(frame.commitSeq !== undefined ? { commitSeq: frame.commitSeq } : {}),
100
+ historyErased: 0,
101
+ blobsErased,
102
+ done: false,
103
+ };
104
+ }
105
+ const throughSeq = await storage.getMaxCommitSeq(partition);
106
+ let historyErased = 0;
107
+ for (const table of tables) {
108
+ historyErased += await eraseHistory(partition, {
109
+ table: table.name,
110
+ variable,
111
+ value,
112
+ throughSeq,
113
+ limit: maxRows,
114
+ });
115
+ }
116
+ return {
117
+ rowsErased: 0,
118
+ historyErased,
119
+ blobsErased: [],
120
+ done: historyErased === 0,
121
+ };
122
+ }
package/dist/index.d.ts CHANGED
@@ -17,6 +17,7 @@ export * from './content-encoding.js';
17
17
  export * from './context.js';
18
18
  export * from './crdt-merger.js';
19
19
  export * from './d1-storage.js';
20
+ export * from './erase.js';
20
21
  export * from './errors.js';
21
22
  export * from './events.js';
22
23
  export * from './events-ring.js';
package/dist/index.js CHANGED
@@ -17,6 +17,7 @@ export * from './content-encoding.js';
17
17
  export * from './context.js';
18
18
  export * from './crdt-merger.js';
19
19
  export * from './d1-storage.js';
20
+ export * from './erase.js';
20
21
  export * from './errors.js';
21
22
  export * from './events.js';
22
23
  export * from './events-ring.js';
@@ -39,7 +39,7 @@ import type { CommitPruneQuery, CommitPruneResult } from './storage.js';
39
39
  import type { ScopeMap } from '@syncular/core';
40
40
  import { type PgExecutor } from './pg-executor.js';
41
41
  import type { CompiledSchema, CompiledTable } from './schema.js';
42
- 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, StoredCheckpoint, StoredCommit, StoredPushResult, StoredReaction, StoredRow } from './storage.js';
42
+ 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, StoredCheckpoint, StoredCommit, StoredPushResult, StoredReaction, StoredRow } from './storage.js';
43
43
  /**
44
44
  * Schema DDL. Applied by `PostgresServerStorage.migrate()` (idempotent).
45
45
  *
@@ -73,7 +73,13 @@ export declare const POSTGRES_DDL = "\nCREATE TABLE IF NOT EXISTS sync_partition
73
73
  export declare class PostgresServerStorage implements ServerStorage {
74
74
  #private;
75
75
  constructor(exec: PgExecutor);
76
- /** Apply the schema DDL (idempotent). Call once before use. */
76
+ /**
77
+ * Apply the schema DDL (idempotent). Call once before use. The last
78
+ * statement records a fingerprint of the applied DDL as the comment of
79
+ * `sync_schema_meta`; a database that carries the current fingerprint
80
+ * costs one catalog read instead of the DDL round trips, so a new storage
81
+ * instance (a Worker isolate, a Durable Object wake) starts fast.
82
+ */
77
83
  migrate(): Promise<void>;
78
84
  /** Resolve a table's compiled schema; row operations require `ensureSchema`. */
79
85
  table(name: string): CompiledTable;
@@ -134,6 +140,8 @@ export declare class PostgresServerStorage implements ServerStorage {
134
140
  readonly scopes: Record<string, string>;
135
141
  }[]>;
136
142
  listReferencedBlobIds(partition: string): Promise<string[]>;
143
+ listScopeValueRows(partition: string, query: ScopeValueQuery): Promise<string[]>;
144
+ eraseScopeValueHistory(partition: string, query: ScopeValueHistoryQuery): Promise<number>;
137
145
  listClientRecords(partition: string): Promise<ClientRecord[]>;
138
146
  listCommitMetadata(partition: string, query: CommitMetadataQuery): Promise<CommitMetadata[]>;
139
147
  getCommit(partition: string, commitSeq: number): Promise<CommitDetail | undefined>;