shelving 1.273.1 → 1.274.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.
@@ -4,6 +4,7 @@ import type { Identifier, Item } from "../../util/item.js";
4
4
  import type { Query } from "../../util/query.js";
5
5
  import type { Updates } from "../../util/update.js";
6
6
  import type { Collection } from "../collection/Collection.js";
7
+ import type { DBProvider } from "./DBProvider.js";
7
8
  import { ThroughDBProvider } from "./ThroughDBProvider.js";
8
9
  /**
9
10
  * Structured log entry recording a single database write performed through a `ChangesDBProvider`.
@@ -50,4 +51,6 @@ export declare class ChangesDBProvider<I extends Identifier, T extends Data> ext
50
51
  updateQuery<II extends I, TT extends T>(collection: Collection<string, II, TT>, query: Query<Item<II, TT>>, updates: Updates<TT>): Promise<void>;
51
52
  /** Log a `"delete"` change after writing. */
52
53
  deleteQuery<II extends I, TT extends T>(collection: Collection<string, II, TT>, query: Query<Item<II, TT>>): Promise<void>;
54
+ cloneWith(source: DBProvider<I, T>): this;
55
+ transact<X>(callback: (provider: DBProvider<I, T>) => Promise<X>): Promise<X>;
53
56
  }
@@ -53,4 +53,19 @@ export class ChangesDBProvider extends ThroughDBProvider {
53
53
  await super.deleteQuery(collection, query);
54
54
  this._changes.push({ action: "delete", collection: collection.name, query });
55
55
  }
56
+ // Override so that transaction copies get their own log.
57
+ cloneWith(source) {
58
+ const clone = super.cloneWith(source);
59
+ Object.defineProperty(clone, "_changes", { value: [], enumerable: false });
60
+ return clone;
61
+ }
62
+ // Override to log the transaction's writes after it commits — a failed transaction logs nothing.
63
+ // The merge must happen after `source.transact()` resolves: backends may retry the callback or fail the commit itself, and only the committed attempt's writes belong in the log.
64
+ async transact(callback) {
65
+ let transaction;
66
+ const result = await this.source.transact(provider => callback((transaction = this.cloneWith(provider))));
67
+ if (transaction)
68
+ this._changes.push(...transaction.changes);
69
+ return result;
70
+ }
56
71
  }
@@ -167,5 +167,22 @@ export declare abstract class DBProvider<I extends Identifier = Identifier, T ex
167
167
  * @see https://shelving.cc/db/DBProvider/requireFirst
168
168
  */
169
169
  requireFirst<II extends I, TT extends T>(collection: Collection<string, II, TT>, query: Query<Item<II, TT>>): Promise<Item<II, TT>>;
170
+ /**
171
+ * Run a callback as a single atomic transaction — every write made through the callback's provider is committed together, or not at all.
172
+ *
173
+ * - The callback receives a transaction-scoped `DBProvider`; reads and writes made through it belong to the transaction.
174
+ * - Reads see a consistent snapshot of the data from before the transaction, and do not see the transaction's own uncommitted writes.
175
+ * - If the callback throws, nothing is committed and the error is rethrown.
176
+ * - The callback may run more than once if the backend retries on contention, so it must have no side effects other than through its provider.
177
+ * - Inside a transaction, realtime sequences and nested `transact()` calls throw `UnsupportedError`.
178
+ * - Not every provider supports transactions — the base implementation throws `UnsupportedError`.
179
+ *
180
+ * @param callback Function that performs the transaction's reads and writes through the provider it receives.
181
+ * @returns The value returned by the callback.
182
+ * @throws `UnsupportedError` if this provider does not support transactions.
183
+ * @example await provider.transact(async db => void (await db.updateItem(users, 123, { logins: { sum: 1 } })));
184
+ * @see https://shelving.cc/db/DBProvider/transact
185
+ */
186
+ transact<X>(callback: (provider: DBProvider<I, T>) => Promise<X>): Promise<X>;
170
187
  [Symbol.asyncDispose](): Promise<void>;
171
188
  }
@@ -1,4 +1,5 @@
1
1
  import { RequiredError } from "../../error/RequiredError.js";
2
+ import { UnsupportedError } from "../../error/UnsupportedError.js";
2
3
  import { countArray, getFirst } from "../../util/array.js";
3
4
  import { awaitDispose } from "../../util/dispose.js";
4
5
  /**
@@ -81,6 +82,29 @@ export class DBProvider {
81
82
  });
82
83
  return first;
83
84
  }
85
+ /**
86
+ * Run a callback as a single atomic transaction — every write made through the callback's provider is committed together, or not at all.
87
+ *
88
+ * - The callback receives a transaction-scoped `DBProvider`; reads and writes made through it belong to the transaction.
89
+ * - Reads see a consistent snapshot of the data from before the transaction, and do not see the transaction's own uncommitted writes.
90
+ * - If the callback throws, nothing is committed and the error is rethrown.
91
+ * - The callback may run more than once if the backend retries on contention, so it must have no side effects other than through its provider.
92
+ * - Inside a transaction, realtime sequences and nested `transact()` calls throw `UnsupportedError`.
93
+ * - Not every provider supports transactions — the base implementation throws `UnsupportedError`.
94
+ *
95
+ * @param callback Function that performs the transaction's reads and writes through the provider it receives.
96
+ * @returns The value returned by the callback.
97
+ * @throws `UnsupportedError` if this provider does not support transactions.
98
+ * @example await provider.transact(async db => void (await db.updateItem(users, 123, { logins: { sum: 1 } })));
99
+ * @see https://shelving.cc/db/DBProvider/transact
100
+ */
101
+ transact(callback) {
102
+ throw new UnsupportedError(`${this.constructor.name} does not support transactions`, {
103
+ provider: this,
104
+ received: callback,
105
+ caller: this.transact,
106
+ });
107
+ }
84
108
  // Implement `AsyncDisposable`
85
109
  async [Symbol.asyncDispose]() {
86
110
  await awaitDispose(
@@ -3,6 +3,7 @@ import type { Identifier, Item, Items, ItemsSequence, OptionalItem, OptionalItem
3
3
  import type { Query } from "../../util/query.js";
4
4
  import type { Updates } from "../../util/update.js";
5
5
  import type { Collection } from "../collection/Collection.js";
6
+ import type { DBProvider } from "./DBProvider.js";
6
7
  import { ThroughDBProvider } from "./ThroughDBProvider.js";
7
8
  /**
8
9
  * Database provider that logs every operation it performs to the console for debugging.
@@ -29,4 +30,6 @@ export declare class DebugDBProvider<I extends Identifier, T extends Data> exten
29
30
  setQuery<II extends I, TT extends T>(collection: Collection<string, II, TT>, query: Query<Item<II, TT>>, data: TT): Promise<void>;
30
31
  updateQuery<II extends I, TT extends T>(collection: Collection<string, II, TT>, query: Query<Item<II, TT>>, updates: Updates<TT>): Promise<void>;
31
32
  deleteQuery<II extends I, TT extends T>(collection: Collection<string, II, TT>, query: Query<Item<II, TT>>): Promise<void>;
33
+ /** Adds TRANSACT logging around the base behaviour, which re-wraps so operations inside the transaction are logged too. */
34
+ transact<X>(callback: (provider: DBProvider<I, T>) => Promise<X>): Promise<X>;
32
35
  }
@@ -153,4 +153,17 @@ export class DebugDBProvider extends ThroughDBProvider {
153
153
  throw reason;
154
154
  }
155
155
  }
156
+ /** Adds TRANSACT logging around the base behaviour, which re-wraps so operations inside the transaction are logged too. */
157
+ async transact(callback) {
158
+ try {
159
+ console.debug(`${ANSI_RIGHT} TRANSACT`);
160
+ const result = await super.transact(callback);
161
+ console.debug(`${ANSI_SUCCESS} TRANSACT`);
162
+ return result;
163
+ }
164
+ catch (reason) {
165
+ console.error(`${ANSI_FAILURE} TRANSACT`, reason);
166
+ throw reason;
167
+ }
168
+ }
156
169
  }
@@ -36,5 +36,8 @@ export declare class ThroughDBProvider<I extends Identifier, T extends Data> imp
36
36
  deleteQuery<II extends I, TT extends T>(collection: Collection<string, II, TT>, query: Query<Item<II, TT>>): Promise<void>;
37
37
  getFirst<II extends I, TT extends T>(collection: Collection<string, II, TT>, query: Query<Item<II, TT>>): Promise<OptionalItem<II, TT>>;
38
38
  requireFirst<II extends I, TT extends T>(collection: Collection<string, II, TT>, query: Query<Item<II, TT>>): Promise<Item<II, TT>>;
39
+ transact<X>(callback: (provider: DBProvider<I, T>) => Promise<X>): Promise<X>;
40
+ /** Clone this provider with different `source`. */
41
+ cloneWith(source: DBProvider<I, T>): this;
39
42
  [Symbol.asyncDispose](): Promise<void>;
40
43
  }
@@ -62,6 +62,14 @@ export class ThroughDBProvider {
62
62
  requireFirst(collection, query) {
63
63
  return this.source.requireFirst(collection, query);
64
64
  }
65
+ // Run the transaction against the wrapped `source` provider, keeping this provider's behaviour inside the transaction.
66
+ transact(callback) {
67
+ return this.source.transact(transaction => callback(this.cloneWith(transaction)));
68
+ }
69
+ /** Clone this provider with different `source`. */
70
+ cloneWith(source) {
71
+ return Object.create(this, { source: { value: source, enumerable: true } });
72
+ }
65
73
  // Implement `AsyncDisposable`
66
74
  async [Symbol.asyncDispose]() {
67
75
  await awaitDispose(this.source);
@@ -10,6 +10,7 @@ import { ThroughDBProvider } from "./ThroughDBProvider.js";
10
10
  * - Wraps a `source` provider (which may have any type, because validation guarantees the type) and runs every value through the relevant `Collection` schema before writing and after reading.
11
11
  * - Written data is validated against the collection's data schema; read data is validated against the item schema, so trusted, correctly-typed values reach the rest of the app.
12
12
  * - Validation failures here are program-state errors, so they throw a typed `ValueError` rather than a raw validation `string`.
13
+ * - Applies inside `transact()` too — the transaction provider the callback receives validates its reads and writes the same way.
13
14
  *
14
15
  * @see https://shelving.cc/db/ValidationDBProvider
15
16
  */
@@ -8,6 +8,7 @@ import { ThroughDBProvider } from "./ThroughDBProvider.js";
8
8
  * - Wraps a `source` provider (which may have any type, because validation guarantees the type) and runs every value through the relevant `Collection` schema before writing and after reading.
9
9
  * - Written data is validated against the collection's data schema; read data is validated against the item schema, so trusted, correctly-typed values reach the rest of the app.
10
10
  * - Validation failures here are program-state errors, so they throw a typed `ValueError` rather than a raw validation `string`.
11
+ * - Applies inside `transact()` too — the transaction provider the callback receives validates its reads and writes the same way.
11
12
  *
12
13
  * @see https://shelving.cc/db/ValidationDBProvider
13
14
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shelving",
3
- "version": "1.273.1",
3
+ "version": "1.274.0",
4
4
  "author": "Dave Houlbrooke <dave@shax.com>",
5
5
  "repository": {
6
6
  "type": "git",
@@ -0,0 +1,15 @@
1
+ import type { DBProvider } from "../db/provider/DBProvider.js";
2
+ import { MemoryDBProvider } from "../db/provider/MemoryDBProvider.js";
3
+ import type { Data } from "../util/data.js";
4
+ import type { Identifier } from "../util/item.js";
5
+ /**
6
+ * In-memory provider for testing wrapping providers' `transact()` — runs the callback directly against itself.
7
+ *
8
+ * - No atomicity or rollback: writes apply immediately and are kept even if the callback throws.
9
+ * - Use it as the `source` of a wrapping provider to test how the wrapper behaves inside transactions, not to test transaction semantics themselves.
10
+ *
11
+ * @see https://shelving.cc/test/TransactionTestDBProvider
12
+ */
13
+ export declare class TransactionTestDBProvider<I extends Identifier = Identifier, T extends Data = Data> extends MemoryDBProvider<I, T> {
14
+ transact<X>(callback: (provider: DBProvider<I, T>) => Promise<X>): Promise<X>;
15
+ }
@@ -0,0 +1,14 @@
1
+ import { MemoryDBProvider } from "../db/provider/MemoryDBProvider.js";
2
+ /**
3
+ * In-memory provider for testing wrapping providers' `transact()` — runs the callback directly against itself.
4
+ *
5
+ * - No atomicity or rollback: writes apply immediately and are kept even if the callback throws.
6
+ * - Use it as the `source` of a wrapping provider to test how the wrapper behaves inside transactions, not to test transaction semantics themselves.
7
+ *
8
+ * @see https://shelving.cc/test/TransactionTestDBProvider
9
+ */
10
+ export class TransactionTestDBProvider extends MemoryDBProvider {
11
+ async transact(callback) {
12
+ return await callback(this);
13
+ }
14
+ }
package/test/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Collection } from "../db/collection/Collection.js";
2
2
  export * from "./basics.js";
3
3
  export * from "./people.js";
4
+ export * from "./TransactionTestDBProvider.js";
4
5
  export * from "./util.js";
5
6
  export declare const BASICS_COLLECTION: Collection<"basics", string, {
6
7
  str: string;
package/test/index.js CHANGED
@@ -4,6 +4,7 @@ import { BASIC_SCHEMA } from "./basics.js";
4
4
  import { PERSON_SCHEMA } from "./people.js";
5
5
  export * from "./basics.js";
6
6
  export * from "./people.js";
7
+ export * from "./TransactionTestDBProvider.js";
7
8
  export * from "./util.js";
8
9
  export const BASICS_COLLECTION = new Collection("basics", STRING, BASIC_SCHEMA);
9
10
  export const PEOPLE_COLLECTION = new Collection("people", STRING, PERSON_SCHEMA);