dynamo-bao 0.9.0 → 0.11.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/CHANGELOG.md CHANGED
@@ -9,6 +9,138 @@ Each version heading links to the tag that was published to npm. Entries before
9
9
 
10
10
  ## [Unreleased]
11
11
 
12
+ ## [0.11.0] - 2026-12-03
13
+
14
+ Semver minor (0.11.0). Adds multi-model atomic transactions via
15
+ `transact([...ops])` and model op builders; nothing existing changes behavior.
16
+
17
+ **Key format: no key code changed.** Primary keys, GSI keys, unique
18
+ constraint keys, iteration keys, `_searchText`, and tenant prefixes are built
19
+ identically to 0.10.0.
20
+
21
+ ### Added
22
+
23
+ - **`transact(ops, options?)`** exported from the root `dynamo-bao` entry point
24
+ for committing writes across multiple models atomically in a single DynamoDB
25
+ `TransactWriteItems` call.
26
+ - Enforces single-tenant transactions (refusing mixed ambient tenants or
27
+ mixed app/admin tenant-bound models), matching `documentClient` instances,
28
+ DynamoDB's 100-item flattened limit (counting unique-constraint items), and
29
+ distinct flattened `(TableName, _pk, _sk)` keys before sending.
30
+ - Reuses a single `ClientRequestToken` (caller-supplied or generated ULID)
31
+ and frozen `TransactItems` payload across network retries and jittered
32
+ backoff retries on pure `TransactionConflict` cancellations (default
33
+ `maxAttempts: 3`, `baseDelayMs: 25`). Condition check failures and mixed
34
+ conflict/condition cancellations are not retried.
35
+ - Accumulates write capacity into `getBatchContextCapacity().write`,
36
+ invalidates request batch context loader cache entries for mutated items
37
+ (including clearing cached `ObjectNotFound` misses on `createOp` and
38
+ propagating out of `fresh()`), and fires `afterSave` / `afterDelete` hooks
39
+ once per op in order only after commit (avoiding read-back on blind/atomic
40
+ updates unless an `afterSave` hook is registered).
41
+ - **Model op builders**: `Model.createOp(data, options?)`,
42
+ `Model.updateOp(id, changes, options?)`, `Model.deleteOp(id, options?)`, and
43
+ `Model.conditionCheckOp(id, condition)`. Each snapshots the active tenant
44
+ context at construction time (failing closed when tenancy is enabled without
45
+ a tenant) and shares write preparation with single-item `create()`,
46
+ `update()`, and `delete()`.
47
+ - **`Model.create(data, options?)`** now accepts optional `{ condition }` for
48
+ symmetry with `createOp`.
49
+ - **`TransactionCanceledError`** (exported on `exceptions`), mapping DynamoDB's
50
+ flat `CancellationReasons` back to logical `opIndex` with `code`/`reason`,
51
+ `failures` (including `role`, `constraintField`, and `itemNotFound`), and the
52
+ unmarshalled `ReturnValuesOnConditionCheckFailure` `item`.
53
+ - **Bundled DynamoDB client** (`src/dynamodb-client.js`): added
54
+ `ConditionCheck` marshalling in `TransactWriteCommand` and unmarshalling of
55
+ `CancellationReasons[i].Item` on `TransactionCanceledException`.
56
+ - **`tutorials/12-transactions.md`** and README documentation.
57
+
58
+ ## [0.10.0] - 2026-11-07
59
+
60
+ Semver minor (0.10.0). Adds the `dynamo-bao/remote` entry point; nothing
61
+ existing changes behavior.
62
+
63
+ **Key format: no key code changed.** Primary keys, GSI keys, unique
64
+ constraint keys, iteration keys and tenant prefixes are built exactly as in
65
+ 0.9.0. Outside `src/remote/`, the only source changes are additions to
66
+ `src/model.js` (`fromRemote`, `isDetached`, and a guard at the top of
67
+ `save`, `loadRelatedData` and `getOrLoadRelatedField` that only fires on
68
+ instances `fromRemote` created) and one new exception class. The root
69
+ `dynamo-bao` entry exports the same names as before.
70
+
71
+ ### Added
72
+
73
+ - **`dynamo-bao/remote`**, a new entry point (`require("dynamo-bao/remote")`
74
+ or `import ... from "dynamo-bao/remote"`) for running named, versioned
75
+ procedures next to DynamoDB and calling them from far away in one round
76
+ trip. See `tutorials/11-remote-procedures.md`, which freezes
77
+ `ProcedureContext`, `Actor`, the outcome tags (`ok` / `error` /
78
+ `unknown`) and the replay classes (`idempotent` / `conditional` /
79
+ `needs-ledger`). Exports:
80
+ - `defineProcedure`, `ProcedureRegistry` (with `get`, `has`, `versions`,
81
+ `latest`, `manifest`), `REPLAY_CLASSES`, `SCOPES`: registration by name,
82
+ version, scope and replay class. A procedure without a replay class or
83
+ scope is refused, and so is a version gap. Previous-version serving is
84
+ the application's obligation: the registry serves `@1` beside `@2` while
85
+ both descriptors are registered.
86
+ - `createContext`, `fresh`, `bindModelsToTenant`: the procedure context
87
+ (models, admin models bound to the resolver's admin partition, which is
88
+ required for `admin` and `both` scopes, tenant as
89
+ a value, actor passed through, request and operation ids, a logger bound
90
+ to request id and tenant, `now()`, `fresh` with capacity merge and
91
+ outer-cache priming, `waitUntil` with a 30 s cap, frozen config).
92
+ - `encodeValue`, `decodeRow`, `CodecError`: the wire codec, covering every
93
+ field type in `fields.js`. Dates and TTLs travel as epoch milliseconds,
94
+ `BinaryField` as `{ $binary }`, `StringSetField` as an array; any
95
+ non-JSON value is refused with its path.
96
+ - `createExecutor({ procedures, context, ingress, budget, region,
97
+ plainReturns })`: the fetch handler. Envelope validation, unknown
98
+ procedure and scope refusal, the actor check (the actor's `appId` must
99
+ equal the call tenant; no other actor field is read), concurrent and
100
+ isolated calls, tagged outcomes with capacity and duration, placement
101
+ echo, budget and ingress refusal, `drain()`. An error raised after `run`
102
+ returned (encoding its result, or `ResponseTooLarge`) carries
103
+ `executed: true`; an executor refusal carries `refused: true`.
104
+ - `remote(transport, { actor, retries, headers })` with `call` and
105
+ `batch`, and `inProcess(executor, { env, headers, ctx })`: `unknown` on
106
+ transport failure, no automatic resend of `needs-ledger` calls, reported
107
+ capacity added to the caller's batch context, and the executor's
108
+ `placement` (`{ colo, region }`) on each `ok` and `error` outcome.
109
+ - `DetachedInstanceError` (also in `exceptions`).
110
+ - **`Model.fromRemote(row)`** hydrates a detached, read-only instance from an
111
+ encoded row, and **`instance.isDetached()`** reports it. On a detached
112
+ instance `save`, `update`, `delete`, `loadRelatedData` and
113
+ `getOrLoadRelatedField` throw `DetachedInstanceError`.
114
+ - **TypeScript declarations** for the entry point in `src/remote/index.d.ts`
115
+ (`ProcedureContext`, `ContextResolver`, `Actor`, the descriptor, outcome
116
+ and replay types, and every export). A caller's `ok` is typed as it
117
+ arrives (`WireResult<Result>`: model instances as `EncodedRow`), and
118
+ `defineProcedure` is a type error when its result can hold a `Date`,
119
+ `Map`, `Set`, function or other non-JSON value. Resolvable with `moduleResolution`
120
+ `node`, `node16` and `bundler`. The package `exports` map gains
121
+ `./remote`, and `typesVersions` maps it for `moduleResolution: node`.
122
+ - **`examples/cloudflare-remote-executor/`**: a data worker with the
123
+ placement line, the `DATA` self-binding and the ingress secret, tested in
124
+ workerd with `@cloudflare/vitest-pool-workers` (`npm run test:workerd`).
125
+ - `tutorials/11-remote-procedures.md`.
126
+
127
+ ### Codec refusals
128
+
129
+ The codec refuses one model shape: a **custom field whose stored value is
130
+ not JSON** (for example a custom field whose `toDy` returns a `Map`). Such a
131
+ row throws `CodecError` naming the model and field. Every built-in field
132
+ type encodes. A `Date` anywhere in a procedure result is refused; return
133
+ epoch milliseconds.
134
+
135
+ ### For consumers adopting the executor
136
+
137
+ The Spike 6 audit's consumer-facing lists (the callers that cross the
138
+ boundary with a `Date` or a model instance, the memberships-cache
139
+ invalidation sites, and the activity-gate helpers) were handed over on
140
+ issue #18 on 2026-11-07:
141
+ https://github.com/aag1024/dynamo-bao/issues/18#issuecomment-6703195120
142
+
143
+
12
144
  ## [0.9.0] - 2026-10-28
13
145
 
14
146
  ### Security
@@ -567,7 +699,9 @@ Initial release: single-table models with fields, GSIs, unique constraints,
567
699
  related fields, counters, TTL, filters, pagination, batch loading, hooks,
568
700
  YAML codegen and a table creation tool.
569
701
 
570
- [Unreleased]: https://github.com/aag1024/dynamo-bao/compare/v0.9.0...HEAD
702
+ [Unreleased]: https://github.com/aag1024/dynamo-bao/compare/v0.11.0...HEAD
703
+ [0.11.0]: https://github.com/aag1024/dynamo-bao/compare/v0.10.0...v0.11.0
704
+ [0.10.0]: https://github.com/aag1024/dynamo-bao/compare/v0.9.0...v0.10.0
571
705
  [0.9.0]: https://github.com/aag1024/dynamo-bao/compare/v0.8.2...v0.9.0
572
706
  [0.8.2]: https://github.com/aag1024/dynamo-bao/compare/v0.8.1...v0.8.2
573
707
  [0.8.1]: https://github.com/aag1024/dynamo-bao/compare/v0.8.0...v0.8.1
package/README.md CHANGED
@@ -21,6 +21,7 @@ Release notes are in [CHANGELOG.md](https://github.com/aag1024/dynamo-bao/blob/m
21
21
  - Model 1:1, 1:N, N:M relationships between objects
22
22
  - Efficiently load data: load related objects in parallel, cache data using loading contexts
23
23
  - Minimize race conditions: save diffs, version checks on save, atomic counters
24
+ - Atomic multi-model transactions with `transact([...ops])`, op builders (`createOp`, `updateOp`, `deleteOp`, `conditionCheckOp`), and conflict retries
24
25
  - Enforce unique constraints and use them for lookups
25
26
  - Built-in multi-tenancy support with complete data isolation and concurrency safety
26
27
  - Return total read/write consumed capacity (even when multiple operations were performed)
@@ -190,6 +191,65 @@ export default {
190
191
 
191
192
  For production Cloudflare Workers deployments, always use `runWithBatchContext` to get both safety and optimal performance.
192
193
 
194
+ ### Remote Procedures (`dynamo-bao/remote`)
195
+
196
+ When code runs far from the table (Durable Objects near users, Workflows), each DynamoDB call pays a cross-region round trip. `dynamo-bao/remote` lets you register named, versioned procedures on a Worker placed next to DynamoDB and call them in one trip:
197
+
198
+ ```javascript
199
+ const { defineProcedure, ProcedureRegistry, createExecutor, remote } = require("dynamo-bao/remote");
200
+
201
+ const getUser = defineProcedure({
202
+ name: "user.get", version: 1, scope: "app", replay: "idempotent",
203
+ async run(ctx, { userId }) {
204
+ const user = await ctx.models.User.find(userId);
205
+ return user.exists() ? { name: user.name } : null;
206
+ },
207
+ });
208
+
209
+ // Data worker, next to DynamoDB:
210
+ const executor = createExecutor({
211
+ procedures: new ProcedureRegistry([getUser]),
212
+ context: (call, env) => ({ models: getModels(env) }),
213
+ ingress: (request, env) => request.headers.get("x-data-binding") === env.DATA_BINDING_SECRET,
214
+ });
215
+
216
+ // Caller, anywhere:
217
+ const r = await remote(env.DATA, { actor, headers }).call(getUser, { userId }, { tenant: appId });
218
+ if ("ok" in r) console.log(r.ok.name);
219
+ ```
220
+
221
+ See [tutorial 11](tutorials/11-remote-procedures.md) for the contract (context, actor, outcomes, replay classes) and [`examples/cloudflare-remote-executor/`](examples/cloudflare-remote-executor/) for a complete Worker. TypeScript declarations ship with the entry point.
222
+
223
+ ### Multi-Model Transactions (`transact`)
224
+
225
+ Commit changes across multiple models atomically in a single DynamoDB `TransactWriteItems` call using op builders (`createOp`, `updateOp`, `deleteOp`, `conditionCheckOp`):
226
+
227
+ ```javascript
228
+ const { transact } = require("dynamo-bao");
229
+ const { TransactionCanceledError } = require("dynamo-bao").exceptions;
230
+
231
+ try {
232
+ await transact([
233
+ Document.updateOp(
234
+ docId,
235
+ { directShareCount: "+1" },
236
+ { condition: { directShareCount: { $lt: 1000 } } },
237
+ ),
238
+ DocumentPermission.createOp({ docId, userId, role: "editor" }),
239
+ ]);
240
+ } catch (err) {
241
+ if (err instanceof TransactionCanceledError) {
242
+ console.log("Cancelled at op", err.opIndex, err.code, err.item);
243
+ }
244
+ }
245
+ ```
246
+
247
+ - All-or-nothing commit with unique-constraint items, GSI keys, iteration keys, generated fields, and tenant prefixes built identically to single-item writes.
248
+ - Maps `TransactionCanceledException` reasons back to logical op indexes (including `ReturnValuesOnConditionCheckFailure` items) and retries `TransactionConflict` with jittered backoff.
249
+ - Runs `afterSave`/`afterDelete` hooks once per op in order only after commit, invalidates the request batch context cache, and refuses mixed tenants, duplicate keys, or more than 100 items.
250
+
251
+ See [tutorial 12](tutorials/12-transactions.md) for full details, options, error shapes, and limits.
252
+
193
253
  ### Batch Context Configuration
194
254
 
195
255
  DynamoBao provides flexible batch context behavior that can be configured based on your application's needs:
File without changes
package/package.json CHANGED
@@ -1,19 +1,31 @@
1
1
  {
2
2
  "name": "dynamo-bao",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
4
4
  "description": "Simple powerful data modeling primitives for DynamoDB in JavaScript.",
5
5
  "main": "src/index.js",
6
6
  "exports": {
7
7
  ".": "./src/index.js",
8
+ "./remote": {
9
+ "types": "./src/remote/index.d.ts",
10
+ "default": "./src/remote/index.js"
11
+ },
8
12
  "./src/*": "./src/*",
9
13
  "./package.json": "./package.json"
10
14
  },
15
+ "typesVersions": {
16
+ "*": {
17
+ "remote": [
18
+ "src/remote/index.d.ts"
19
+ ]
20
+ }
21
+ },
11
22
  "scripts": {
12
23
  "test": "LOG_LEVEL=OFF jest",
13
24
  "test:debug": "LOG_LEVEL=DEBUG jest",
14
25
  "create-table": "node bin/dynamo-bao-create-table.js",
15
26
  "watch": "node bin/watch.js",
16
- "docs": "jsdoc -c jsdoc.json --verbose"
27
+ "docs": "jsdoc -c jsdoc.json --verbose",
28
+ "test:workerd": "npm --prefix examples/cloudflare-remote-executor install --no-audit --no-fund && npm --prefix examples/cloudflare-remote-executor test"
17
29
  },
18
30
  "files": [
19
31
  "bin/",
@@ -51,7 +63,8 @@
51
63
  "gh-pages": "^6.2.0",
52
64
  "jest": "^29.7.0",
53
65
  "jsdoc": "^4.0.4",
54
- "prettier": "3.4.2"
66
+ "prettier": "3.4.2",
67
+ "typescript": "^5.9.3"
55
68
  },
56
69
  "bin": {
57
70
  "bao-init": "bin/dynamo-bao-create-table.js",
@@ -238,7 +238,12 @@ class DynamoDBClient {
238
238
 
239
239
  // Add specific properties based on error type
240
240
  if (errorName === 'TransactionCanceledException' && errorBody.CancellationReasons) {
241
- error.CancellationReasons = errorBody.CancellationReasons;
241
+ error.CancellationReasons = errorBody.CancellationReasons.map(reason => {
242
+ if (reason && reason.Item) {
243
+ return { ...reason, Item: unmarshallItem(reason.Item) };
244
+ }
245
+ return reason;
246
+ });
242
247
  }
243
248
 
244
249
  // With ReturnValuesOnConditionCheckFailure, a failed condition check
@@ -421,6 +426,23 @@ class DynamoDBDocumentClient {
421
426
  newItem.Delete.ExpressionAttributeValues = marshalledValues;
422
427
  }
423
428
  }
429
+ if (item.ConditionCheck) {
430
+ const checkKey = {};
431
+ Object.keys(item.ConditionCheck.Key).forEach(key => {
432
+ checkKey[key] = marshall(item.ConditionCheck.Key[key]);
433
+ });
434
+ newItem.ConditionCheck = {
435
+ ...item.ConditionCheck,
436
+ Key: checkKey
437
+ };
438
+ if (item.ConditionCheck.ExpressionAttributeValues) {
439
+ const marshalledValues = {};
440
+ Object.keys(item.ConditionCheck.ExpressionAttributeValues).forEach(key => {
441
+ marshalledValues[key] = marshall(item.ConditionCheck.ExpressionAttributeValues[key]);
442
+ });
443
+ newItem.ConditionCheck.ExpressionAttributeValues = marshalledValues;
444
+ }
445
+ }
424
446
  return newItem;
425
447
  });
426
448
  }
package/src/exceptions.js CHANGED
@@ -86,6 +86,42 @@ class DataFormatError extends BaoError {
86
86
  }
87
87
  }
88
88
 
89
+ /**
90
+ * Thrown by a persistence method called on an instance hydrated with
91
+ * `Model.fromRemote()`. Such an instance is a read-only view of a row a
92
+ * remote procedure returned; writes and related loads belong in a procedure.
93
+ */
94
+ class DetachedInstanceError extends BaoError {
95
+ constructor(modelName, method) {
96
+ super(
97
+ `${modelName}.${method}() was called on a detached instance (hydrated with fromRemote). ` +
98
+ "Detached rows are read-only; do the write or load in a procedure and call it with remote(...).call().",
99
+ );
100
+ this.modelName = modelName;
101
+ this.method = method;
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Thrown when a DynamoDB TransactWriteItems call is cancelled (e.g.
107
+ * ConditionalCheckFailed, TransactionConflict). Maps DynamoDB's flat
108
+ * CancellationReasons back to the caller's logical op indexes.
109
+ */
110
+ class TransactionCanceledError extends BaoError {
111
+ constructor(message, { failures = [], cancellationReasons = [], cause = null } = {}) {
112
+ const primary = failures[0] || null;
113
+ super(message, primary ? primary.code : null);
114
+ this.failures = failures;
115
+ this.cancellationReasons = cancellationReasons;
116
+ this.opIndex = primary ? primary.opIndex : null;
117
+ this.reason = primary ? primary.code : null;
118
+ this.item = primary && primary.item !== undefined ? primary.item : undefined;
119
+ if (cause) {
120
+ this.cause = cause;
121
+ }
122
+ }
123
+ }
124
+
89
125
  module.exports = {
90
126
  BaoError,
91
127
  ConfigurationError,
@@ -94,4 +130,6 @@ module.exports = {
94
130
  ItemNotFoundError,
95
131
  ConditionalError,
96
132
  DataFormatError,
133
+ DetachedInstanceError,
134
+ TransactionCanceledError,
97
135
  };
package/src/index.js CHANGED
@@ -21,6 +21,7 @@ const {
21
21
  runWithBatchContext,
22
22
  getBatchContextCapacity,
23
23
  } = require("./mixins/batch-loading-mixin");
24
+ const { transact } = require("./transact");
24
25
 
25
26
  function findModelFiles(dir) {
26
27
  let results = [];
@@ -229,6 +230,9 @@ const firstExport = {
229
230
  runWithBatchContext,
230
231
  getBatchContextCapacity,
231
232
 
233
+ // Multi-model transactions
234
+ transact,
235
+
232
236
  // Configurations
233
237
  PrimaryKeyConfig,
234
238
  IndexConfig,