@fedify/pglite 2.5.0-dev.2761 → 2.5.0-dev.2811

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/README.md CHANGED
@@ -1,5 +1,3 @@
1
- <!-- deno-fmt-ignore-file -->
2
-
3
1
  @fedify/pglite: PGlite driver for Fedify
4
2
  ========================================
5
3
 
@@ -7,7 +5,7 @@
7
5
  [![JSR][JSR badge]][JSR]
8
6
 
9
7
  This package provides [`PgliteKvStore`], a PGlite-backed implementation of
10
- Fedify's [`KvStore`]:
8
+ Fedify's [`AtomicKvStore`]:
11
9
 
12
10
  ~~~~ typescript
13
11
  import { PGlite } from "@electric-sql/pglite";
@@ -35,7 +33,7 @@ rolling restart. See [PGlite issue #489] and [PGlite pull request #892].
35
33
  [JSR badge]: https://jsr.io/badges/@fedify/pglite
36
34
  [JSR]: https://jsr.io/@fedify/pglite
37
35
  [`PgliteKvStore`]: https://jsr.io/@fedify/pglite/doc/~/PgliteKvStore
38
- [`KvStore`]: https://jsr.io/@fedify/fedify/doc/federation/~/KvStore
36
+ [`AtomicKvStore`]: https://jsr.io/@fedify/fedify/doc/federation/~/AtomicKvStore
39
37
  [PGlite issue #489]: https://github.com/electric-sql/pglite/issues/489#issuecomment-2587892190
40
38
  [PGlite pull request #892]: https://github.com/electric-sql/pglite/pull/892
41
39
 
@@ -50,3 +48,86 @@ yarn add @fedify/pglite @electric-sql/pglite # Yarn
50
48
  bun add @fedify/pglite @electric-sql/pglite # Bun
51
49
  deno add jsr:@fedify/pglite npm:@electric-sql/pglite # Deno
52
50
  ~~~~
51
+
52
+
53
+ Atomic operations
54
+ -----------------
55
+
56
+ Since Fedify 2.5.0, `PgliteKvStore` implements `AtomicKvStore`. Use
57
+ `getMany()` for an ordered snapshot and `casMany()` to compare and change
58
+ related keys together. A comparison mismatch returns `false` without changing
59
+ values or TTLs; reread and re-evaluate the application rule before retrying.
60
+ `setMany()` and `deleteMany()` also commit as complete batches.
61
+
62
+ For example, compare a generation and its associated state before replacing
63
+ both. The application computes the replacement from its own rule:
64
+
65
+ ~~~~ typescript
66
+ const store = new PgliteKvStore(pg);
67
+ const keys = [["example", "generation"], ["example", "state"]] as const;
68
+ const [generation, state] = await store.getMany(keys);
69
+ const committed = await store.casMany([
70
+ { key: keys[0], expectedValue: generation, newValue: crypto.randomUUID() },
71
+ { key: keys[1], expectedValue: state, newValue: { status: "ready" } },
72
+ ]);
73
+ ~~~~
74
+
75
+ All wrappers for a table must share one caller-owned PGlite instance. Each
76
+ batch uses PGlite's transaction callback, which excludes other normal queries
77
+ and transactions on that instance, including when a compared key is absent.
78
+ Do not call store methods from inside the owner's transaction callback, issue
79
+ manual transaction commands, or use concurrent raw protocol operations.
80
+ Independent PGlite owners and processes must not open the same data directory.
81
+ The standard text-array and JSONB codecs are required; custom parser or
82
+ serializer overrides are outside this guarantee.
83
+
84
+ Values use `JSON.stringify()` followed by PostgreSQL JSONB input, and CAS uses
85
+ JSONB equality. Object member order is ignored and array order matters.
86
+ JSON `null` remains a value; `undefined` checks absence or deletes in CAS and
87
+ cannot be stored. JSON serialization can omit unsupported object properties
88
+ or convert nonfinite numbers to `null`; cyclic values and `bigint` reject.
89
+ JSONB also rejects U+0000 and invalid surrogate sequences. Keys must contain
90
+ one or more well-formed Unicode strings without U+0000. Mutation batches
91
+ reject duplicate keys and sparse inputs before writing.
92
+
93
+ Each entry has its own TTL, and every operation uses one transaction-start
94
+ expiry cutoff. Omitting a replacement TTL clears the previous expiry. Zero
95
+ TTL expires immediately; negative durations reject, as do durations whose
96
+ addition exceeds the timestamp range. TTL uses PostgreSQL calendar intervals
97
+ with microsecond rounding and the session time zone; the host clock may have
98
+ only millisecond resolution. CAS deletion must not specify a non-null TTL.
99
+
100
+ There is no fixed adapter batch-entry limit. Statements run sequentially in
101
+ one transaction, so a large batch occupies the shared instance and consumes
102
+ memory proportional to its input and results. New keys are subject to the
103
+ engine's B-tree entry limit, about 2700 bytes after compression with its default
104
+ 8 KiB pages; this is a storage constraint rather than an adapter input cap.
105
+ A mismatching CAS batch can return `false` without attempting an insertion or
106
+ proving that insertion would fit. An insertion error that actually occurs
107
+ rejects and rolls back the complete batch. Deterministically invalid keys,
108
+ JSONB values and TTLs still reject even on a comparison mismatch.
109
+
110
+ Atomic execution does not promise crash durability or exactly-once effects.
111
+ The supported scope is a normal PGlite instance on Node.js, Bun, or Deno,
112
+ using memory or the host filesystem. Worker proxies and browser persistence
113
+ are outside this scope. Host-filesystem storage supports clean close/reopen;
114
+ memory-only instances remain ephemeral. After a mutation transaction completes,
115
+ the adapter awaits the owner's `syncToFs()` outside the transaction, preserving
116
+ the synchronization policy previously used by `set()`, `delete()`, and `cas()`.
117
+ This includes a nonempty CAS call whose comparisons mismatch: its read-only
118
+ transaction still completes, and a backend synchronization failure rejects
119
+ instead of returning `false`.
120
+ PGlite 0.5.8 does not perform that post-commit synchronization itself.
121
+ The owner's filesystem and `relaxedDurability` setting determine what this
122
+ call guarantees. A synchronization failure rejects after transaction
123
+ completion; any committed mutations remain applied. A lost response or commit
124
+ failure can also leave commit status unknown. Do not automatically replay an
125
+ uncertain change; use a non-reused version or an operation receipt when the
126
+ application needs it.
127
+
128
+ Mutation housekeeping is part of the same transaction. A legacy row with an
129
+ overflowing TTL can make expiry cleanup fail; other mutations then roll back
130
+ until all offending keys are removed together with `deleteMany()` or direct
131
+ SQL. Inspect the raw key, creation time, and TTL columns through direct SQL
132
+ without adding the TTL. Malformed legacy keys, such as empty arrays or SQL
133
+ null segments, require direct SQL remediation.
package/dist/kv.cjs CHANGED
@@ -19,9 +19,59 @@ function serializeJson(value) {
19
19
  if (serialized == null) throw new TypeError("PGlite cannot store a value that is not valid JSON");
20
20
  return serialized;
21
21
  }
22
+ function captureKey(key) {
23
+ const parts = captureArray(key);
24
+ if (parts.length === 0 || parts.some((part) => typeof part !== "string" || !part.isWellFormed() || part.includes("\0"))) throw new TypeError("Keys must be nonempty arrays of well-formed strings without NUL.");
25
+ return parts;
26
+ }
27
+ function captureArray(items) {
28
+ if (!Array.isArray(items)) throw new TypeError("A batch must be an array.");
29
+ for (let i = 0; i < items.length; i++) if (!Object.hasOwn(items, i)) throw new TypeError("Sparse arrays are not supported.");
30
+ return Array.from(items);
31
+ }
32
+ function captureKeys(keys, unique = false) {
33
+ const captured = captureArray(keys).map(captureKey);
34
+ if (unique && new Set(captured.map((key) => JSON.stringify(key))).size !== captured.length) throw new TypeError("Duplicate keys in an atomic mutation.");
35
+ return captured;
36
+ }
37
+ function serializeTtl(options) {
38
+ if (options?.ttl == null) return null;
39
+ const ttl = Temporal.Duration.from(options.ttl);
40
+ if (ttl.sign < 0) throw new RangeError("The TTL must not be negative.");
41
+ return ttl.toString();
42
+ }
22
43
  /**
23
44
  * A key–value store backed by an embedded PGlite database.
24
45
  *
46
+ * Since Fedify 2.5.0, this implements {@link AtomicKvStore}. All keys in one
47
+ * table share an atomic scope when wrappers share one normal PGlite owner,
48
+ * using its standard text-array and JSONB codecs. Do not invoke store methods
49
+ * inside the owner's transaction callback or concurrently bypass its normal
50
+ * query/transaction queue with raw protocol or manual transaction control.
51
+ * Worker proxies and independent owners sharing a directory are outside this
52
+ * scope.
53
+ *
54
+ * Values use JSON.stringify() and JSONB equality: object member order is
55
+ * ignored, array order matters, and JSON null differs from absence. Keys must
56
+ * be nonempty arrays of well-formed strings without NUL. Unsupported JSONB
57
+ * values, duplicate mutation keys, sparse arrays, negative TTLs, timestamp
58
+ * overflow, and TTLs on CAS deletion reject. Omitting a replacement TTL clears
59
+ * expiry. Zero TTL expires immediately; intervals round to microseconds on a
60
+ * host clock that may resolve only milliseconds. Calendar units use the
61
+ * session time zone. Each operation uses one transaction-start expiry cutoff.
62
+ *
63
+ * No fixed batch-entry limit is imposed; large batches occupy the shared
64
+ * owner and consume its finite memory. Engine insertion limits depend on
65
+ * compression and are checked when writes are attempted. A mismatch does not
66
+ * prove hypothetical insertability. Statement failures reject and roll back;
67
+ * commit or post-commit synchronization failures may leave committed changes
68
+ * despite rejection and must not trigger replay. Successful mutation
69
+ * transactions await the owner's syncToFs() policy outside the transaction,
70
+ * including read-only CAS mismatches. Backend synchronization failures reject
71
+ * rather than returning false.
72
+ * Atomicity does not promise crash durability; see the package README for
73
+ * supported storage and the owner's durability policy.
74
+ *
25
75
  * The caller owns the PGlite instance and is responsible for closing it after
26
76
  * every operation using the store has completed. Use only one PGlite instance
27
77
  * for a data directory within a runtime isolate.
@@ -60,107 +110,158 @@ var PgliteKvStore = class {
60
110
  this.#quotedTableName = quoteIdentifier(this.#tableName);
61
111
  this.#initialized = options.initialized ?? false;
62
112
  }
63
- async #expire() {
64
- await this.#pg.query(`
113
+ async #expire(tx) {
114
+ await tx.query(`
65
115
  DELETE FROM ${this.#quotedTableName}
66
116
  WHERE ttl IS NOT NULL AND created + ttl < CURRENT_TIMESTAMP;
67
117
  `);
68
118
  }
119
+ async #write(tx, entry) {
120
+ await tx.query(`
121
+ INSERT INTO ${this.#quotedTableName} (key, value, created, ttl)
122
+ VALUES ($1::text[], $2::text::jsonb, CURRENT_TIMESTAMP, $3::text::interval)
123
+ ON CONFLICT (key)
124
+ DO UPDATE SET value = EXCLUDED.value,
125
+ created = EXCLUDED.created, ttl = EXCLUDED.ttl;
126
+ `, [
127
+ entry.key,
128
+ entry.value,
129
+ entry.ttl
130
+ ]);
131
+ }
132
+ async #remove(tx, key) {
133
+ await tx.query(`DELETE FROM ${this.#quotedTableName} WHERE key = $1::text[];`, [key]);
134
+ }
135
+ /** {@inheritDoc AtomicKvStore.get} */
69
136
  async get(key) {
137
+ const captured = captureKey(key);
70
138
  await this.initialize();
71
139
  return (await this.#pg.query(`
72
- SELECT value
73
- FROM ${this.#quotedTableName}
140
+ SELECT value FROM ${this.#quotedTableName}
74
141
  WHERE key = $1::text[]
75
142
  AND (ttl IS NULL OR created + ttl > CURRENT_TIMESTAMP);
76
- `, [key])).rows[0]?.value;
143
+ `, [captured])).rows[0]?.value;
77
144
  }
78
- async set(key, value, options) {
79
- await this.initialize();
80
- const ttl = options?.ttl == null ? null : Temporal.Duration.from(options.ttl).toString();
81
- await this.#pg.query(`
82
- INSERT INTO ${this.#quotedTableName} (key, value, ttl)
83
- VALUES ($1::text[], $2::text::jsonb, $3::text::interval)
84
- ON CONFLICT (key)
85
- DO UPDATE SET
86
- value = EXCLUDED.value,
87
- created = CURRENT_TIMESTAMP,
88
- ttl = EXCLUDED.ttl;
89
- `, [
145
+ /** {@inheritDoc AtomicKvStore.set} */
146
+ set(key, value, options) {
147
+ return this.setMany([{
90
148
  key,
91
- serializeJson(value),
92
- ttl
93
- ]);
94
- await this.#expire();
149
+ value,
150
+ options
151
+ }]);
152
+ }
153
+ /** {@inheritDoc AtomicKvStore.delete} */
154
+ delete(key) {
155
+ return this.deleteMany([key]);
156
+ }
157
+ /** {@inheritDoc AtomicKvStore.cas} */
158
+ cas(key, expectedValue, newValue, options) {
159
+ return this.casMany([{
160
+ key,
161
+ expectedValue,
162
+ newValue,
163
+ options
164
+ }]);
165
+ }
166
+ /**
167
+ * {@inheritDoc AtomicKvStore.getMany}
168
+ * @since 2.5.0
169
+ */
170
+ async getMany(keys) {
171
+ const captured = captureKeys(keys);
172
+ if (captured.length === 0) return [];
173
+ await this.initialize();
174
+ return await this.#pg.transaction(async (tx) => {
175
+ const values = [];
176
+ for (const key of captured) {
177
+ const result = await tx.query(`SELECT value FROM ${this.#quotedTableName}
178
+ WHERE key = $1::text[]
179
+ AND (ttl IS NULL OR created + ttl > CURRENT_TIMESTAMP);`, [key]);
180
+ values.push(result.rows[0]?.value);
181
+ }
182
+ return values;
183
+ });
95
184
  }
96
- async delete(key) {
185
+ /**
186
+ * {@inheritDoc AtomicKvStore.setMany}
187
+ * @since 2.5.0
188
+ */
189
+ async setMany(entries) {
190
+ const captured = captureArray(entries);
191
+ const keys = captureKeys(captured.map((entry) => entry.key), true);
192
+ const writes = captured.map((entry, index) => ({
193
+ key: keys[index],
194
+ value: serializeJson(entry.value),
195
+ ttl: serializeTtl(entry.options)
196
+ }));
197
+ if (writes.length === 0) return;
97
198
  await this.initialize();
98
- await this.#pg.query(`
99
- DELETE FROM ${this.#quotedTableName}
100
- WHERE key = $1::text[];
101
- `, [key]);
102
- await this.#expire();
199
+ await this.#pg.transaction(async (tx) => {
200
+ for (const entry of writes) await tx.query("SELECT (CURRENT_TIMESTAMP + $1::text::interval) IS NULL;", [entry.ttl]);
201
+ for (const entry of writes) await this.#write(tx, entry);
202
+ await this.#expire(tx);
203
+ });
204
+ await this.#pg.syncToFs();
103
205
  }
104
- /** {@inheritDoc KvStore.cas} */
105
- async cas(key, expectedValue, newValue, options) {
206
+ /**
207
+ * {@inheritDoc AtomicKvStore.deleteMany}
208
+ * @since 2.5.0
209
+ */
210
+ async deleteMany(keys) {
211
+ const captured = captureKeys(keys, true);
212
+ if (captured.length === 0) return;
106
213
  await this.initialize();
107
- const ttl = options?.ttl == null ? null : Temporal.Duration.from(options.ttl).toString();
108
- if (expectedValue === void 0 && newValue === void 0) {
109
- const matched = await this.get(key) === void 0;
110
- await this.#expire();
111
- return matched;
112
- }
113
- let rowCount;
114
- if (expectedValue === void 0) rowCount = (await this.#pg.query(`
115
- INSERT INTO ${this.#quotedTableName} AS existing
116
- (key, value, created, ttl)
117
- VALUES (
118
- $1::text[],
119
- $2::text::jsonb,
120
- CURRENT_TIMESTAMP,
121
- $3::text::interval
122
- )
123
- ON CONFLICT (key)
124
- DO UPDATE SET
125
- value = EXCLUDED.value,
126
- created = EXCLUDED.created,
127
- ttl = EXCLUDED.ttl
128
- WHERE existing.ttl IS NOT NULL
129
- AND existing.created + existing.ttl <= CURRENT_TIMESTAMP
130
- RETURNING key;
131
- `, [
132
- key,
133
- serializeJson(newValue),
134
- ttl
135
- ])).rows.length;
136
- else if (newValue === void 0) rowCount = (await this.#pg.query(`
137
- DELETE FROM ${this.#quotedTableName}
138
- WHERE key = $1::text[]
139
- AND (ttl IS NULL OR created + ttl > CURRENT_TIMESTAMP)
140
- AND value = $2::text::jsonb
141
- RETURNING key;
142
- `, [key, serializeJson(expectedValue)])).rows.length;
143
- else rowCount = (await this.#pg.query(`
144
- UPDATE ${this.#quotedTableName}
145
- SET
146
- value = $3::text::jsonb,
147
- created = CURRENT_TIMESTAMP,
148
- ttl = $4::text::interval
149
- WHERE key = $1::text[]
150
- AND (ttl IS NULL OR created + ttl > CURRENT_TIMESTAMP)
151
- AND value = $2::text::jsonb
152
- RETURNING key;
153
- `, [
154
- key,
155
- serializeJson(expectedValue),
156
- serializeJson(newValue),
157
- ttl
158
- ])).rows.length;
159
- await this.#expire();
160
- return rowCount > 0;
214
+ await this.#pg.transaction(async (tx) => {
215
+ for (const key of captured) await this.#remove(tx, key);
216
+ await this.#expire(tx);
217
+ });
218
+ await this.#pg.syncToFs();
219
+ }
220
+ /**
221
+ * {@inheritDoc AtomicKvStore.casMany}
222
+ * @since 2.5.0
223
+ */
224
+ async casMany(entries) {
225
+ const captured = captureArray(entries);
226
+ const keys = captureKeys(captured.map((entry) => entry.key), true);
227
+ const changes = captured.map((entry, index) => {
228
+ if (entry.newValue === void 0 && entry.options?.ttl != null) throw new TypeError("A CAS deletion must not specify a TTL.");
229
+ return {
230
+ key: keys[index],
231
+ expected: entry.expectedValue === void 0 ? void 0 : serializeJson(entry.expectedValue),
232
+ value: entry.newValue === void 0 ? void 0 : serializeJson(entry.newValue),
233
+ ttl: serializeTtl(entry.options)
234
+ };
235
+ });
236
+ if (changes.length === 0) return true;
237
+ await this.initialize();
238
+ const committed = await this.#pg.transaction(async (tx) => {
239
+ for (const entry of changes) await tx.query(`SELECT ($1::text::jsonb) IS NULL, ($2::text::jsonb) IS NULL,
240
+ (CURRENT_TIMESTAMP + $3::text::interval) IS NULL;`, [
241
+ entry.expected ?? null,
242
+ entry.value ?? null,
243
+ entry.ttl
244
+ ]);
245
+ for (const entry of changes) if (!(await tx.query(`SELECT ${entry.expected === void 0 ? "NOT " : ""}EXISTS (
246
+ SELECT 1 FROM ${this.#quotedTableName}
247
+ WHERE key = $1::text[]
248
+ AND (ttl IS NULL OR created + ttl > CURRENT_TIMESTAMP)
249
+ ${entry.expected === void 0 ? "" : "AND value = $2::text::jsonb"}
250
+ ) AS matched;`, entry.expected === void 0 ? [entry.key] : [entry.key, entry.expected])).rows[0].matched) return false;
251
+ for (const entry of changes) if (entry.value === void 0) await this.#remove(tx, entry.key);
252
+ else await this.#write(tx, {
253
+ ...entry,
254
+ value: entry.value
255
+ });
256
+ await this.#expire(tx);
257
+ return true;
258
+ });
259
+ await this.#pg.syncToFs();
260
+ return committed;
161
261
  }
162
- /** {@inheritDoc KvStore.list} */
262
+ /** {@inheritDoc AtomicKvStore.list} */
163
263
  async *list(prefix) {
264
+ if (prefix != null && (!Array.isArray(prefix) || prefix.length > 0)) prefix = captureKey(prefix);
164
265
  await this.initialize();
165
266
  const result = prefix == null || prefix.length === 0 ? await this.#pg.query(`
166
267
  SELECT key, value
package/dist/kv.d.cts CHANGED
@@ -1,7 +1,7 @@
1
1
  /// <reference types="emscripten" />
2
2
  /// <reference lib="esnext.temporal" />
3
3
  import { PGliteInterface } from "@electric-sql/pglite";
4
- import { KvKey, KvStore, KvStoreListEntry, KvStoreSetOptions } from "@fedify/fedify";
4
+ import { AtomicKvStore, KvKey, KvStoreCasEntry, KvStoreListEntry, KvStoreSetEntry, KvStoreSetOptions } from "@fedify/fedify";
5
5
 
6
6
  //#region src/kv.d.ts
7
7
  /**
@@ -25,6 +25,35 @@ interface PgliteKvStoreOptions {
25
25
  /**
26
26
  * A key–value store backed by an embedded PGlite database.
27
27
  *
28
+ * Since Fedify 2.5.0, this implements {@link AtomicKvStore}. All keys in one
29
+ * table share an atomic scope when wrappers share one normal PGlite owner,
30
+ * using its standard text-array and JSONB codecs. Do not invoke store methods
31
+ * inside the owner's transaction callback or concurrently bypass its normal
32
+ * query/transaction queue with raw protocol or manual transaction control.
33
+ * Worker proxies and independent owners sharing a directory are outside this
34
+ * scope.
35
+ *
36
+ * Values use JSON.stringify() and JSONB equality: object member order is
37
+ * ignored, array order matters, and JSON null differs from absence. Keys must
38
+ * be nonempty arrays of well-formed strings without NUL. Unsupported JSONB
39
+ * values, duplicate mutation keys, sparse arrays, negative TTLs, timestamp
40
+ * overflow, and TTLs on CAS deletion reject. Omitting a replacement TTL clears
41
+ * expiry. Zero TTL expires immediately; intervals round to microseconds on a
42
+ * host clock that may resolve only milliseconds. Calendar units use the
43
+ * session time zone. Each operation uses one transaction-start expiry cutoff.
44
+ *
45
+ * No fixed batch-entry limit is imposed; large batches occupy the shared
46
+ * owner and consume its finite memory. Engine insertion limits depend on
47
+ * compression and are checked when writes are attempted. A mismatch does not
48
+ * prove hypothetical insertability. Statement failures reject and roll back;
49
+ * commit or post-commit synchronization failures may leave committed changes
50
+ * despite rejection and must not trigger replay. Successful mutation
51
+ * transactions await the owner's syncToFs() policy outside the transaction,
52
+ * including read-only CAS mismatches. Backend synchronization failures reject
53
+ * rather than returning false.
54
+ * Atomicity does not promise crash durability; see the package README for
55
+ * supported storage and the owner's durability policy.
56
+ *
28
57
  * The caller owns the PGlite instance and is responsible for closing it after
29
58
  * every operation using the store has completed. Use only one PGlite instance
30
59
  * for a data directory within a runtime isolate.
@@ -46,7 +75,7 @@ interface PgliteKvStoreOptions {
46
75
  * ```
47
76
  * @since 2.4.0
48
77
  */
49
- declare class PgliteKvStore implements KvStore {
78
+ declare class PgliteKvStore implements AtomicKvStore {
50
79
  #private;
51
80
  /**
52
81
  * Creates a new PGlite key–value store.
@@ -54,12 +83,35 @@ declare class PgliteKvStore implements KvStore {
54
83
  * @param options The options for the key–value store.
55
84
  */
56
85
  constructor(pg: PGliteInterface, options?: PgliteKvStoreOptions);
86
+ /** {@inheritDoc AtomicKvStore.get} */
57
87
  get<T = unknown>(key: KvKey): Promise<T | undefined>;
88
+ /** {@inheritDoc AtomicKvStore.set} */
58
89
  set(key: KvKey, value: unknown, options?: KvStoreSetOptions): Promise<void>;
90
+ /** {@inheritDoc AtomicKvStore.delete} */
59
91
  delete(key: KvKey): Promise<void>;
60
- /** {@inheritDoc KvStore.cas} */
92
+ /** {@inheritDoc AtomicKvStore.cas} */
61
93
  cas(key: KvKey, expectedValue: unknown, newValue: unknown, options?: KvStoreSetOptions): Promise<boolean>;
62
- /** {@inheritDoc KvStore.list} */
94
+ /**
95
+ * {@inheritDoc AtomicKvStore.getMany}
96
+ * @since 2.5.0
97
+ */
98
+ getMany<T = unknown>(keys: readonly KvKey[]): Promise<(T | undefined)[]>;
99
+ /**
100
+ * {@inheritDoc AtomicKvStore.setMany}
101
+ * @since 2.5.0
102
+ */
103
+ setMany(entries: readonly KvStoreSetEntry[]): Promise<void>;
104
+ /**
105
+ * {@inheritDoc AtomicKvStore.deleteMany}
106
+ * @since 2.5.0
107
+ */
108
+ deleteMany(keys: readonly KvKey[]): Promise<void>;
109
+ /**
110
+ * {@inheritDoc AtomicKvStore.casMany}
111
+ * @since 2.5.0
112
+ */
113
+ casMany(entries: readonly KvStoreCasEntry[]): Promise<boolean>;
114
+ /** {@inheritDoc AtomicKvStore.list} */
63
115
  list(prefix?: KvKey): AsyncIterable<KvStoreListEntry>;
64
116
  /**
65
117
  * Creates the table used by the store if it does not already exist.
package/dist/kv.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /// <reference types="emscripten" />
2
2
  /// <reference lib="esnext.temporal" />
3
3
  import { PGliteInterface } from "@electric-sql/pglite";
4
- import { KvKey, KvStore, KvStoreListEntry, KvStoreSetOptions } from "@fedify/fedify";
4
+ import { AtomicKvStore, KvKey, KvStoreCasEntry, KvStoreListEntry, KvStoreSetEntry, KvStoreSetOptions } from "@fedify/fedify";
5
5
 
6
6
  //#region src/kv.d.ts
7
7
  /**
@@ -25,6 +25,35 @@ interface PgliteKvStoreOptions {
25
25
  /**
26
26
  * A key–value store backed by an embedded PGlite database.
27
27
  *
28
+ * Since Fedify 2.5.0, this implements {@link AtomicKvStore}. All keys in one
29
+ * table share an atomic scope when wrappers share one normal PGlite owner,
30
+ * using its standard text-array and JSONB codecs. Do not invoke store methods
31
+ * inside the owner's transaction callback or concurrently bypass its normal
32
+ * query/transaction queue with raw protocol or manual transaction control.
33
+ * Worker proxies and independent owners sharing a directory are outside this
34
+ * scope.
35
+ *
36
+ * Values use JSON.stringify() and JSONB equality: object member order is
37
+ * ignored, array order matters, and JSON null differs from absence. Keys must
38
+ * be nonempty arrays of well-formed strings without NUL. Unsupported JSONB
39
+ * values, duplicate mutation keys, sparse arrays, negative TTLs, timestamp
40
+ * overflow, and TTLs on CAS deletion reject. Omitting a replacement TTL clears
41
+ * expiry. Zero TTL expires immediately; intervals round to microseconds on a
42
+ * host clock that may resolve only milliseconds. Calendar units use the
43
+ * session time zone. Each operation uses one transaction-start expiry cutoff.
44
+ *
45
+ * No fixed batch-entry limit is imposed; large batches occupy the shared
46
+ * owner and consume its finite memory. Engine insertion limits depend on
47
+ * compression and are checked when writes are attempted. A mismatch does not
48
+ * prove hypothetical insertability. Statement failures reject and roll back;
49
+ * commit or post-commit synchronization failures may leave committed changes
50
+ * despite rejection and must not trigger replay. Successful mutation
51
+ * transactions await the owner's syncToFs() policy outside the transaction,
52
+ * including read-only CAS mismatches. Backend synchronization failures reject
53
+ * rather than returning false.
54
+ * Atomicity does not promise crash durability; see the package README for
55
+ * supported storage and the owner's durability policy.
56
+ *
28
57
  * The caller owns the PGlite instance and is responsible for closing it after
29
58
  * every operation using the store has completed. Use only one PGlite instance
30
59
  * for a data directory within a runtime isolate.
@@ -46,7 +75,7 @@ interface PgliteKvStoreOptions {
46
75
  * ```
47
76
  * @since 2.4.0
48
77
  */
49
- declare class PgliteKvStore implements KvStore {
78
+ declare class PgliteKvStore implements AtomicKvStore {
50
79
  #private;
51
80
  /**
52
81
  * Creates a new PGlite key–value store.
@@ -54,12 +83,35 @@ declare class PgliteKvStore implements KvStore {
54
83
  * @param options The options for the key–value store.
55
84
  */
56
85
  constructor(pg: PGliteInterface, options?: PgliteKvStoreOptions);
86
+ /** {@inheritDoc AtomicKvStore.get} */
57
87
  get<T = unknown>(key: KvKey): Promise<T | undefined>;
88
+ /** {@inheritDoc AtomicKvStore.set} */
58
89
  set(key: KvKey, value: unknown, options?: KvStoreSetOptions): Promise<void>;
90
+ /** {@inheritDoc AtomicKvStore.delete} */
59
91
  delete(key: KvKey): Promise<void>;
60
- /** {@inheritDoc KvStore.cas} */
92
+ /** {@inheritDoc AtomicKvStore.cas} */
61
93
  cas(key: KvKey, expectedValue: unknown, newValue: unknown, options?: KvStoreSetOptions): Promise<boolean>;
62
- /** {@inheritDoc KvStore.list} */
94
+ /**
95
+ * {@inheritDoc AtomicKvStore.getMany}
96
+ * @since 2.5.0
97
+ */
98
+ getMany<T = unknown>(keys: readonly KvKey[]): Promise<(T | undefined)[]>;
99
+ /**
100
+ * {@inheritDoc AtomicKvStore.setMany}
101
+ * @since 2.5.0
102
+ */
103
+ setMany(entries: readonly KvStoreSetEntry[]): Promise<void>;
104
+ /**
105
+ * {@inheritDoc AtomicKvStore.deleteMany}
106
+ * @since 2.5.0
107
+ */
108
+ deleteMany(keys: readonly KvKey[]): Promise<void>;
109
+ /**
110
+ * {@inheritDoc AtomicKvStore.casMany}
111
+ * @since 2.5.0
112
+ */
113
+ casMany(entries: readonly KvStoreCasEntry[]): Promise<boolean>;
114
+ /** {@inheritDoc AtomicKvStore.list} */
63
115
  list(prefix?: KvKey): AsyncIterable<KvStoreListEntry>;
64
116
  /**
65
117
  * Creates the table used by the store if it does not already exist.
package/dist/kv.js CHANGED
@@ -16,9 +16,59 @@ function serializeJson(value) {
16
16
  if (serialized == null) throw new TypeError("PGlite cannot store a value that is not valid JSON");
17
17
  return serialized;
18
18
  }
19
+ function captureKey(key) {
20
+ const parts = captureArray(key);
21
+ if (parts.length === 0 || parts.some((part) => typeof part !== "string" || !part.isWellFormed() || part.includes("\0"))) throw new TypeError("Keys must be nonempty arrays of well-formed strings without NUL.");
22
+ return parts;
23
+ }
24
+ function captureArray(items) {
25
+ if (!Array.isArray(items)) throw new TypeError("A batch must be an array.");
26
+ for (let i = 0; i < items.length; i++) if (!Object.hasOwn(items, i)) throw new TypeError("Sparse arrays are not supported.");
27
+ return Array.from(items);
28
+ }
29
+ function captureKeys(keys, unique = false) {
30
+ const captured = captureArray(keys).map(captureKey);
31
+ if (unique && new Set(captured.map((key) => JSON.stringify(key))).size !== captured.length) throw new TypeError("Duplicate keys in an atomic mutation.");
32
+ return captured;
33
+ }
34
+ function serializeTtl(options) {
35
+ if (options?.ttl == null) return null;
36
+ const ttl = Temporal.Duration.from(options.ttl);
37
+ if (ttl.sign < 0) throw new RangeError("The TTL must not be negative.");
38
+ return ttl.toString();
39
+ }
19
40
  /**
20
41
  * A key–value store backed by an embedded PGlite database.
21
42
  *
43
+ * Since Fedify 2.5.0, this implements {@link AtomicKvStore}. All keys in one
44
+ * table share an atomic scope when wrappers share one normal PGlite owner,
45
+ * using its standard text-array and JSONB codecs. Do not invoke store methods
46
+ * inside the owner's transaction callback or concurrently bypass its normal
47
+ * query/transaction queue with raw protocol or manual transaction control.
48
+ * Worker proxies and independent owners sharing a directory are outside this
49
+ * scope.
50
+ *
51
+ * Values use JSON.stringify() and JSONB equality: object member order is
52
+ * ignored, array order matters, and JSON null differs from absence. Keys must
53
+ * be nonempty arrays of well-formed strings without NUL. Unsupported JSONB
54
+ * values, duplicate mutation keys, sparse arrays, negative TTLs, timestamp
55
+ * overflow, and TTLs on CAS deletion reject. Omitting a replacement TTL clears
56
+ * expiry. Zero TTL expires immediately; intervals round to microseconds on a
57
+ * host clock that may resolve only milliseconds. Calendar units use the
58
+ * session time zone. Each operation uses one transaction-start expiry cutoff.
59
+ *
60
+ * No fixed batch-entry limit is imposed; large batches occupy the shared
61
+ * owner and consume its finite memory. Engine insertion limits depend on
62
+ * compression and are checked when writes are attempted. A mismatch does not
63
+ * prove hypothetical insertability. Statement failures reject and roll back;
64
+ * commit or post-commit synchronization failures may leave committed changes
65
+ * despite rejection and must not trigger replay. Successful mutation
66
+ * transactions await the owner's syncToFs() policy outside the transaction,
67
+ * including read-only CAS mismatches. Backend synchronization failures reject
68
+ * rather than returning false.
69
+ * Atomicity does not promise crash durability; see the package README for
70
+ * supported storage and the owner's durability policy.
71
+ *
22
72
  * The caller owns the PGlite instance and is responsible for closing it after
23
73
  * every operation using the store has completed. Use only one PGlite instance
24
74
  * for a data directory within a runtime isolate.
@@ -57,107 +107,158 @@ var PgliteKvStore = class {
57
107
  this.#quotedTableName = quoteIdentifier(this.#tableName);
58
108
  this.#initialized = options.initialized ?? false;
59
109
  }
60
- async #expire() {
61
- await this.#pg.query(`
110
+ async #expire(tx) {
111
+ await tx.query(`
62
112
  DELETE FROM ${this.#quotedTableName}
63
113
  WHERE ttl IS NOT NULL AND created + ttl < CURRENT_TIMESTAMP;
64
114
  `);
65
115
  }
116
+ async #write(tx, entry) {
117
+ await tx.query(`
118
+ INSERT INTO ${this.#quotedTableName} (key, value, created, ttl)
119
+ VALUES ($1::text[], $2::text::jsonb, CURRENT_TIMESTAMP, $3::text::interval)
120
+ ON CONFLICT (key)
121
+ DO UPDATE SET value = EXCLUDED.value,
122
+ created = EXCLUDED.created, ttl = EXCLUDED.ttl;
123
+ `, [
124
+ entry.key,
125
+ entry.value,
126
+ entry.ttl
127
+ ]);
128
+ }
129
+ async #remove(tx, key) {
130
+ await tx.query(`DELETE FROM ${this.#quotedTableName} WHERE key = $1::text[];`, [key]);
131
+ }
132
+ /** {@inheritDoc AtomicKvStore.get} */
66
133
  async get(key) {
134
+ const captured = captureKey(key);
67
135
  await this.initialize();
68
136
  return (await this.#pg.query(`
69
- SELECT value
70
- FROM ${this.#quotedTableName}
137
+ SELECT value FROM ${this.#quotedTableName}
71
138
  WHERE key = $1::text[]
72
139
  AND (ttl IS NULL OR created + ttl > CURRENT_TIMESTAMP);
73
- `, [key])).rows[0]?.value;
140
+ `, [captured])).rows[0]?.value;
74
141
  }
75
- async set(key, value, options) {
76
- await this.initialize();
77
- const ttl = options?.ttl == null ? null : Temporal.Duration.from(options.ttl).toString();
78
- await this.#pg.query(`
79
- INSERT INTO ${this.#quotedTableName} (key, value, ttl)
80
- VALUES ($1::text[], $2::text::jsonb, $3::text::interval)
81
- ON CONFLICT (key)
82
- DO UPDATE SET
83
- value = EXCLUDED.value,
84
- created = CURRENT_TIMESTAMP,
85
- ttl = EXCLUDED.ttl;
86
- `, [
142
+ /** {@inheritDoc AtomicKvStore.set} */
143
+ set(key, value, options) {
144
+ return this.setMany([{
87
145
  key,
88
- serializeJson(value),
89
- ttl
90
- ]);
91
- await this.#expire();
146
+ value,
147
+ options
148
+ }]);
149
+ }
150
+ /** {@inheritDoc AtomicKvStore.delete} */
151
+ delete(key) {
152
+ return this.deleteMany([key]);
153
+ }
154
+ /** {@inheritDoc AtomicKvStore.cas} */
155
+ cas(key, expectedValue, newValue, options) {
156
+ return this.casMany([{
157
+ key,
158
+ expectedValue,
159
+ newValue,
160
+ options
161
+ }]);
162
+ }
163
+ /**
164
+ * {@inheritDoc AtomicKvStore.getMany}
165
+ * @since 2.5.0
166
+ */
167
+ async getMany(keys) {
168
+ const captured = captureKeys(keys);
169
+ if (captured.length === 0) return [];
170
+ await this.initialize();
171
+ return await this.#pg.transaction(async (tx) => {
172
+ const values = [];
173
+ for (const key of captured) {
174
+ const result = await tx.query(`SELECT value FROM ${this.#quotedTableName}
175
+ WHERE key = $1::text[]
176
+ AND (ttl IS NULL OR created + ttl > CURRENT_TIMESTAMP);`, [key]);
177
+ values.push(result.rows[0]?.value);
178
+ }
179
+ return values;
180
+ });
92
181
  }
93
- async delete(key) {
182
+ /**
183
+ * {@inheritDoc AtomicKvStore.setMany}
184
+ * @since 2.5.0
185
+ */
186
+ async setMany(entries) {
187
+ const captured = captureArray(entries);
188
+ const keys = captureKeys(captured.map((entry) => entry.key), true);
189
+ const writes = captured.map((entry, index) => ({
190
+ key: keys[index],
191
+ value: serializeJson(entry.value),
192
+ ttl: serializeTtl(entry.options)
193
+ }));
194
+ if (writes.length === 0) return;
94
195
  await this.initialize();
95
- await this.#pg.query(`
96
- DELETE FROM ${this.#quotedTableName}
97
- WHERE key = $1::text[];
98
- `, [key]);
99
- await this.#expire();
196
+ await this.#pg.transaction(async (tx) => {
197
+ for (const entry of writes) await tx.query("SELECT (CURRENT_TIMESTAMP + $1::text::interval) IS NULL;", [entry.ttl]);
198
+ for (const entry of writes) await this.#write(tx, entry);
199
+ await this.#expire(tx);
200
+ });
201
+ await this.#pg.syncToFs();
100
202
  }
101
- /** {@inheritDoc KvStore.cas} */
102
- async cas(key, expectedValue, newValue, options) {
203
+ /**
204
+ * {@inheritDoc AtomicKvStore.deleteMany}
205
+ * @since 2.5.0
206
+ */
207
+ async deleteMany(keys) {
208
+ const captured = captureKeys(keys, true);
209
+ if (captured.length === 0) return;
103
210
  await this.initialize();
104
- const ttl = options?.ttl == null ? null : Temporal.Duration.from(options.ttl).toString();
105
- if (expectedValue === void 0 && newValue === void 0) {
106
- const matched = await this.get(key) === void 0;
107
- await this.#expire();
108
- return matched;
109
- }
110
- let rowCount;
111
- if (expectedValue === void 0) rowCount = (await this.#pg.query(`
112
- INSERT INTO ${this.#quotedTableName} AS existing
113
- (key, value, created, ttl)
114
- VALUES (
115
- $1::text[],
116
- $2::text::jsonb,
117
- CURRENT_TIMESTAMP,
118
- $3::text::interval
119
- )
120
- ON CONFLICT (key)
121
- DO UPDATE SET
122
- value = EXCLUDED.value,
123
- created = EXCLUDED.created,
124
- ttl = EXCLUDED.ttl
125
- WHERE existing.ttl IS NOT NULL
126
- AND existing.created + existing.ttl <= CURRENT_TIMESTAMP
127
- RETURNING key;
128
- `, [
129
- key,
130
- serializeJson(newValue),
131
- ttl
132
- ])).rows.length;
133
- else if (newValue === void 0) rowCount = (await this.#pg.query(`
134
- DELETE FROM ${this.#quotedTableName}
135
- WHERE key = $1::text[]
136
- AND (ttl IS NULL OR created + ttl > CURRENT_TIMESTAMP)
137
- AND value = $2::text::jsonb
138
- RETURNING key;
139
- `, [key, serializeJson(expectedValue)])).rows.length;
140
- else rowCount = (await this.#pg.query(`
141
- UPDATE ${this.#quotedTableName}
142
- SET
143
- value = $3::text::jsonb,
144
- created = CURRENT_TIMESTAMP,
145
- ttl = $4::text::interval
146
- WHERE key = $1::text[]
147
- AND (ttl IS NULL OR created + ttl > CURRENT_TIMESTAMP)
148
- AND value = $2::text::jsonb
149
- RETURNING key;
150
- `, [
151
- key,
152
- serializeJson(expectedValue),
153
- serializeJson(newValue),
154
- ttl
155
- ])).rows.length;
156
- await this.#expire();
157
- return rowCount > 0;
211
+ await this.#pg.transaction(async (tx) => {
212
+ for (const key of captured) await this.#remove(tx, key);
213
+ await this.#expire(tx);
214
+ });
215
+ await this.#pg.syncToFs();
216
+ }
217
+ /**
218
+ * {@inheritDoc AtomicKvStore.casMany}
219
+ * @since 2.5.0
220
+ */
221
+ async casMany(entries) {
222
+ const captured = captureArray(entries);
223
+ const keys = captureKeys(captured.map((entry) => entry.key), true);
224
+ const changes = captured.map((entry, index) => {
225
+ if (entry.newValue === void 0 && entry.options?.ttl != null) throw new TypeError("A CAS deletion must not specify a TTL.");
226
+ return {
227
+ key: keys[index],
228
+ expected: entry.expectedValue === void 0 ? void 0 : serializeJson(entry.expectedValue),
229
+ value: entry.newValue === void 0 ? void 0 : serializeJson(entry.newValue),
230
+ ttl: serializeTtl(entry.options)
231
+ };
232
+ });
233
+ if (changes.length === 0) return true;
234
+ await this.initialize();
235
+ const committed = await this.#pg.transaction(async (tx) => {
236
+ for (const entry of changes) await tx.query(`SELECT ($1::text::jsonb) IS NULL, ($2::text::jsonb) IS NULL,
237
+ (CURRENT_TIMESTAMP + $3::text::interval) IS NULL;`, [
238
+ entry.expected ?? null,
239
+ entry.value ?? null,
240
+ entry.ttl
241
+ ]);
242
+ for (const entry of changes) if (!(await tx.query(`SELECT ${entry.expected === void 0 ? "NOT " : ""}EXISTS (
243
+ SELECT 1 FROM ${this.#quotedTableName}
244
+ WHERE key = $1::text[]
245
+ AND (ttl IS NULL OR created + ttl > CURRENT_TIMESTAMP)
246
+ ${entry.expected === void 0 ? "" : "AND value = $2::text::jsonb"}
247
+ ) AS matched;`, entry.expected === void 0 ? [entry.key] : [entry.key, entry.expected])).rows[0].matched) return false;
248
+ for (const entry of changes) if (entry.value === void 0) await this.#remove(tx, entry.key);
249
+ else await this.#write(tx, {
250
+ ...entry,
251
+ value: entry.value
252
+ });
253
+ await this.#expire(tx);
254
+ return true;
255
+ });
256
+ await this.#pg.syncToFs();
257
+ return committed;
158
258
  }
159
- /** {@inheritDoc KvStore.list} */
259
+ /** {@inheritDoc AtomicKvStore.list} */
160
260
  async *list(prefix) {
261
+ if (prefix != null && (!Array.isArray(prefix) || prefix.length > 0)) prefix = captureKey(prefix);
161
262
  await this.initialize();
162
263
  const result = prefix == null || prefix.length === 0 ? await this.#pg.query(`
163
264
  SELECT key, value
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fedify/pglite",
3
- "version": "2.5.0-dev.2761+03854982",
3
+ "version": "2.5.0-dev.2811+71b5c016",
4
4
  "description": "PGlite driver for Fedify",
5
5
  "keywords": [
6
6
  "fedify",
@@ -76,14 +76,14 @@
76
76
  },
77
77
  "peerDependencies": {
78
78
  "@electric-sql/pglite": "^0.5.8",
79
- "@fedify/fedify": "^2.5.0-dev.2761+03854982"
79
+ "@fedify/fedify": "^2.5.0-dev.2811+71b5c016"
80
80
  },
81
81
  "devDependencies": {
82
82
  "@js-temporal/polyfill": "^0.5.1",
83
83
  "tsdown": "^0.22.0",
84
84
  "typescript": "^6.0.3",
85
85
  "@fedify/fixture": "^2.0.0",
86
- "@fedify/testing": "^2.5.0-dev.2761+03854982"
86
+ "@fedify/testing": "^2.5.0-dev.2811+71b5c016"
87
87
  },
88
88
  "scripts": {
89
89
  "build:self": "tsdown",