dynamo-bao 0.9.0 → 0.10.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.
@@ -0,0 +1,195 @@
1
+ /**
2
+ * Named, versioned procedures and the registry the executor serves them from.
3
+ * @module remote/procedures
4
+ */
5
+ const { findNonJson, deepFreeze, jsonClone } = require("./json");
6
+
7
+ /**
8
+ * What a resend after an `unknown` outcome does. Frozen vocabulary: see
9
+ * tutorials/11-remote-procedures.md.
10
+ * - `idempotent`: no writes, or writes whose repeat has no further effect.
11
+ * - `conditional`: every write is a guarded state transition, so a repeat
12
+ * fails its condition and the procedure reports that.
13
+ * - `needs-ledger`: an unguarded write or a counter; the procedure keeps its
14
+ * own marker keyed by `ctx.operationId`. The client never resends it.
15
+ */
16
+ const REPLAY_CLASSES = Object.freeze(["idempotent", "conditional", "needs-ledger"]);
17
+
18
+ /**
19
+ * Which model sets a procedure receives. `app`: `ctx.models` only. `admin` and
20
+ * `both`: also `ctx.adminModels`, bound to the admin partition the context
21
+ * resolver names.
22
+ */
23
+ const SCOPES = Object.freeze(["app", "admin", "both"]);
24
+
25
+ const NAME = /^[A-Za-z][A-Za-z0-9_.-]*$/;
26
+ const ID = /^([A-Za-z][A-Za-z0-9_.-]*)@([1-9][0-9]*)$/;
27
+ const DESCRIPTOR_KEYS = new Set(["name", "version", "scope", "replay", "args", "run"]);
28
+ const DESCRIPTORS = new WeakSet();
29
+
30
+ /**
31
+ * Define a procedure. The returned descriptor is what the registry serves and
32
+ * what a caller passes to `remote(...).call`.
33
+ * @param {Object} spec
34
+ * @param {string} spec.name - Dotted name, e.g. "rateLimit.reserve". No "@".
35
+ * @param {number} spec.version - Positive integer. Bump it when args or the
36
+ * result shape change; keep the previous descriptor registered for one
37
+ * deploy so callers built against it keep working.
38
+ * @param {"app"|"admin"|"both"} spec.scope
39
+ * @param {"idempotent"|"conditional"|"needs-ledger"} spec.replay
40
+ * @param {Object} [spec.args] - JSON description of the arguments (for
41
+ * example a JSON Schema). Not interpreted; published by `manifest()`.
42
+ * @param {function(Object, *): Promise<*>} spec.run
43
+ * @returns {Readonly<Object>} The descriptor.
44
+ */
45
+ function defineProcedure(spec) {
46
+ if (!spec || typeof spec !== "object") {
47
+ throw new TypeError("defineProcedure needs a descriptor object");
48
+ }
49
+ for (const key of Object.keys(spec)) {
50
+ if (!DESCRIPTOR_KEYS.has(key)) {
51
+ throw new TypeError(
52
+ `defineProcedure: unknown key "${key}"; expected ${[...DESCRIPTOR_KEYS].join(", ")}`,
53
+ );
54
+ }
55
+ }
56
+ const { name, version, scope, replay, args = null, run } = spec;
57
+ if (typeof name !== "string" || !NAME.test(name)) {
58
+ throw new TypeError(
59
+ `defineProcedure: name ${JSON.stringify(name)} must start with a letter and contain only letters, digits, ".", "_" or "-"`,
60
+ );
61
+ }
62
+ if (!Number.isInteger(version) || version < 1) {
63
+ throw new TypeError(`defineProcedure ${name}: version must be a positive integer`);
64
+ }
65
+ if (!SCOPES.includes(scope)) {
66
+ throw new TypeError(
67
+ `defineProcedure ${name}@${version}: scope must be one of ${SCOPES.join(", ")}`,
68
+ );
69
+ }
70
+ if (!REPLAY_CLASSES.includes(replay)) {
71
+ throw new TypeError(
72
+ `defineProcedure ${name}@${version}: replay class must be one of ${REPLAY_CLASSES.join(", ")}`,
73
+ );
74
+ }
75
+ if (typeof run !== "function") {
76
+ throw new TypeError(`defineProcedure ${name}@${version}: run must be a function`);
77
+ }
78
+ const bad = args === null ? null : findNonJson(args);
79
+ if (bad || (args !== null && typeof args !== "object")) {
80
+ throw new TypeError(
81
+ `defineProcedure ${name}@${version}: args must be a plain JSON description${bad ? ` (found ${bad.found} at ${bad.path})` : ""}`,
82
+ );
83
+ }
84
+ const descriptor = Object.freeze({
85
+ id: `${name}@${version}`,
86
+ name,
87
+ version,
88
+ scope,
89
+ replay,
90
+ args: args === null ? null : deepFreeze(jsonClone(args)),
91
+ run,
92
+ });
93
+ DESCRIPTORS.add(descriptor);
94
+ return descriptor;
95
+ }
96
+
97
+ function isDescriptor(value) {
98
+ return DESCRIPTORS.has(value);
99
+ }
100
+
101
+ /**
102
+ * The set of procedures one deployment serves.
103
+ *
104
+ * Previous-version serving is the application's obligation: the registry
105
+ * serves `name@1` beside `name@2` only while both descriptors are passed in.
106
+ * Keep the previous version registered for one deploy of the callers, then
107
+ * drop it. Versions of one name must be contiguous; a gap is refused so a
108
+ * dropped middle version can't go unnoticed.
109
+ */
110
+ class ProcedureRegistry {
111
+ /** @param {Object[]} descriptors - Results of defineProcedure. */
112
+ constructor(descriptors) {
113
+ if (!Array.isArray(descriptors)) {
114
+ throw new TypeError("ProcedureRegistry needs an array of descriptors");
115
+ }
116
+ const byId = new Map();
117
+ const byName = new Map();
118
+ for (const d of descriptors) {
119
+ if (!isDescriptor(d)) {
120
+ throw new TypeError(
121
+ "ProcedureRegistry: every entry must come from defineProcedure",
122
+ );
123
+ }
124
+ if (byId.has(d.id)) {
125
+ throw new Error(`ProcedureRegistry: ${d.id} is registered twice`);
126
+ }
127
+ byId.set(d.id, d);
128
+ if (!byName.has(d.name)) byName.set(d.name, []);
129
+ byName.get(d.name).push(d.version);
130
+ }
131
+ for (const [name, versions] of byName) {
132
+ versions.sort((a, b) => a - b);
133
+ for (let i = 1; i < versions.length; i++) {
134
+ if (versions[i] !== versions[i - 1] + 1) {
135
+ throw new Error(
136
+ `ProcedureRegistry: version gap for ${name}: has ${versions.join(", ")}, missing ${versions[i - 1] + 1}`,
137
+ );
138
+ }
139
+ }
140
+ Object.freeze(versions);
141
+ }
142
+ this._byId = byId;
143
+ this._byName = byName;
144
+ Object.freeze(this);
145
+ }
146
+
147
+ /** @returns {Object|undefined} The descriptor for "name@version". */
148
+ get(id) {
149
+ if (typeof id !== "string" || !ID.test(id)) return undefined;
150
+ return this._byId.get(id);
151
+ }
152
+
153
+ has(id) {
154
+ return this.get(id) !== undefined;
155
+ }
156
+
157
+ /** @returns {number[]} Registered versions of `name`, ascending. */
158
+ versions(name) {
159
+ return [...(this._byName.get(name) || [])];
160
+ }
161
+
162
+ /** @returns {Object|undefined} The highest registered version of `name`. */
163
+ latest(name) {
164
+ const versions = this._byName.get(name);
165
+ return versions ? this._byId.get(`${name}@${versions[versions.length - 1]}`) : undefined;
166
+ }
167
+
168
+ /**
169
+ * Plain-JSON listing of every registered procedure, sorted by id, for a
170
+ * build step that publishes argument schemas across bundles.
171
+ * @returns {Array<{id: string, name: string, version: number, scope: string, replay: string, args: ?Object}>}
172
+ */
173
+ manifest() {
174
+ return [...this._byId.values()]
175
+ .sort((a, b) =>
176
+ a.name === b.name ? a.version - b.version : a.name < b.name ? -1 : 1,
177
+ )
178
+ .map(({ id, name, version, scope, replay, args }) => ({
179
+ id,
180
+ name,
181
+ version,
182
+ scope,
183
+ replay,
184
+ args: args === null ? null : jsonClone(args),
185
+ }));
186
+ }
187
+ }
188
+
189
+ module.exports = {
190
+ defineProcedure,
191
+ ProcedureRegistry,
192
+ REPLAY_CLASSES,
193
+ SCOPES,
194
+ isDescriptor,
195
+ };