@pritzlaff/nano-core 0.2.0 → 0.5.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/README.md +6 -28
- package/application/apply.d.ts +7 -0
- package/application/compose.d.ts +17 -0
- package/application/connection.d.ts +11 -0
- package/application/context.d.ts +19 -0
- package/application/emit.d.ts +19 -0
- package/application/index.d.ts +61 -0
- package/application/instances.d.ts +27 -0
- package/application/iterate.d.ts +18 -0
- package/application/listen.d.ts +10 -0
- package/application/load.d.ts +15 -0
- package/application/lookup.d.ts +34 -0
- package/application/messages.d.ts +83 -0
- package/application/pod-changes.d.ts +9 -0
- package/application/resolve.d.ts +92 -0
- package/application/sources.d.ts +12 -0
- package/application/start.d.ts +30 -0
- package/application/stream.d.ts +74 -0
- package/context.d.ts +73 -0
- package/coord.d.ts +65 -0
- package/deployment-edit.d.ts +45 -0
- package/deployment-policy.d.ts +19 -0
- package/deployment.d.ts +36 -0
- package/iface.d.ts +82 -0
- package/implementation.d.ts +82 -0
- package/index.d.ts +24 -4
- package/index.js +1694 -250
- package/index.js.map +37 -8
- package/op.d.ts +36 -0
- package/package.json +7 -2
- package/plain.d.ts +30 -0
- package/pod.d.ts +25 -0
- package/pods.d.ts +44 -0
- package/policy.d.ts +58 -0
- package/provider.d.ts +59 -0
- package/registry.d.ts +58 -25
- package/result.d.ts +22 -0
- package/runtime.d.ts +35 -57
- package/schema.d.ts +23 -0
- package/selector.d.ts +40 -0
- package/component.d.ts +0 -42
- package/data.d.ts +0 -72
- package/env.d.ts +0 -25
package/index.js
CHANGED
|
@@ -1,228 +1,1588 @@
|
|
|
1
|
-
// packages/
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
1
|
+
// packages/nano/src/schema.ts
|
|
2
|
+
import { blake3 } from "@noble/hashes/blake3";
|
|
3
|
+
import { utf8ToBytes, bytesToHex } from "@noble/hashes/utils";
|
|
4
|
+
import { canonicalize } from "json-canonicalize";
|
|
5
|
+
import { Compile } from "typebox/compile";
|
|
6
|
+
var canonical = (value) => canonicalize(value);
|
|
7
|
+
var hashOf = (text) => bytesToHex(blake3(utf8ToBytes(text)));
|
|
8
|
+
var NOTES = new Set(["description", "title", "examples", "$comment"]);
|
|
9
|
+
var DATA = new Set(["const", "enum", "default"]);
|
|
10
|
+
var MAPS = new Set(["properties", "patternProperties", "$defs"]);
|
|
11
|
+
function strip(node, isMap = false) {
|
|
12
|
+
if (Array.isArray(node))
|
|
13
|
+
return node.map((n) => strip(n));
|
|
14
|
+
if (node === null || typeof node !== "object")
|
|
15
|
+
return node;
|
|
16
|
+
const out = {};
|
|
17
|
+
for (const [k, v] of Object.entries(node)) {
|
|
18
|
+
if (!isMap && NOTES.has(k))
|
|
19
|
+
continue;
|
|
20
|
+
out[k] = isMap ? strip(v) : DATA.has(k) ? v : k === "required" && Array.isArray(v) ? [...v].sort() : strip(v, MAPS.has(k));
|
|
21
|
+
}
|
|
22
|
+
return out;
|
|
23
|
+
}
|
|
24
|
+
function isJson(v, seen = new Set) {
|
|
25
|
+
if (v === null || typeof v === "string" || typeof v === "boolean")
|
|
26
|
+
return true;
|
|
27
|
+
if (typeof v === "number")
|
|
28
|
+
return Number.isFinite(v);
|
|
29
|
+
if (typeof v !== "object" || seen.has(v))
|
|
30
|
+
return false;
|
|
31
|
+
const proto = Object.getPrototypeOf(v);
|
|
32
|
+
if (!Array.isArray(v) && proto !== Object.prototype && proto !== null)
|
|
33
|
+
return false;
|
|
34
|
+
seen.add(v);
|
|
35
|
+
const ok = Object.values(v).every((x) => isJson(x, seen));
|
|
36
|
+
seen.delete(v);
|
|
37
|
+
return ok;
|
|
38
|
+
}
|
|
39
|
+
var canonicalSchema = (schema) => canonical(strip(schema));
|
|
40
|
+
var defs = new WeakSet;
|
|
41
|
+
function hasFunction(node, seen = new Set) {
|
|
42
|
+
if (typeof node === "function")
|
|
43
|
+
return true;
|
|
44
|
+
if (node === null || typeof node !== "object" || seen.has(node) || defs.has(node))
|
|
45
|
+
return false;
|
|
46
|
+
seen.add(node);
|
|
47
|
+
return Reflect.ownKeys(node).some((k) => hasFunction(node[k], seen));
|
|
48
|
+
}
|
|
49
|
+
function define(schema, label) {
|
|
50
|
+
if (hasFunction(schema))
|
|
51
|
+
throw new Error(`${label ?? "schema"}: schema is not JSON`);
|
|
52
|
+
let compiled;
|
|
53
|
+
const check = (v) => (compiled ??= Compile(schema)).Check(v);
|
|
54
|
+
const members = {
|
|
55
|
+
...label !== undefined && { label },
|
|
56
|
+
schema,
|
|
57
|
+
hash: hashOf(canonicalSchema(schema)),
|
|
58
|
+
check,
|
|
59
|
+
encode: (v) => JSON.stringify(v),
|
|
60
|
+
decode(json) {
|
|
61
|
+
try {
|
|
62
|
+
const v = JSON.parse(json);
|
|
63
|
+
return check(v) ? v : undefined;
|
|
64
|
+
} catch {
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
const def = Object.defineProperties({}, Object.getOwnPropertyDescriptors(schema));
|
|
70
|
+
for (const [k, value] of Object.entries(members))
|
|
71
|
+
Object.defineProperty(def, k, { value });
|
|
72
|
+
defs.add(def);
|
|
73
|
+
return def;
|
|
74
|
+
}
|
|
75
|
+
var Schema = { define };
|
|
76
|
+
// packages/nano/src/op.ts
|
|
77
|
+
var def = (g) => ("hash" in g) && ("check" in g) ? g : Schema.define(g);
|
|
78
|
+
function make(kind, given, out, o) {
|
|
79
|
+
const input = given && def(given);
|
|
80
|
+
return { kind, ...input && { input }, output: def(out), ...o?.description !== undefined && { description: o.description } };
|
|
81
|
+
}
|
|
82
|
+
var Op = {
|
|
83
|
+
action: (input, output, o) => make("action", input, output, o),
|
|
84
|
+
event: (data, o) => make("event", undefined, data, o)
|
|
11
85
|
};
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
86
|
+
function fits(source, action) {
|
|
87
|
+
if (!source.output || !action.input)
|
|
88
|
+
return false;
|
|
89
|
+
return source.output.hash === action.input.hash || canonicalSchema(action.input.schema) === "{}";
|
|
90
|
+
}
|
|
91
|
+
// packages/nano/src/coord.ts
|
|
92
|
+
var NS = /^[a-zA-Z][a-zA-Z0-9-]*([./][a-zA-Z0-9-]+)*$/;
|
|
93
|
+
var NAME = /^[a-zA-Z0-9-]+$/;
|
|
94
|
+
var ID = /^[^/@\s#\x00-\x1f\x7f]{1,64}$/;
|
|
95
|
+
var POD = /^[^/@.\s#\x00-\x1f\x7f]{1,64}$/;
|
|
96
|
+
var check = (ok, what, v) => {
|
|
97
|
+
if (!ok)
|
|
98
|
+
throw new Error(`bad ${what} ${JSON.stringify(v)}`);
|
|
99
|
+
};
|
|
100
|
+
var value = (v, text) => Object.freeze(Object.assign(v, { toString: () => text, toJSON: () => text }));
|
|
101
|
+
function namespace(name) {
|
|
102
|
+
check(NS.test(name), "namespace", name);
|
|
103
|
+
const ns = value({
|
|
104
|
+
kind: "namespace",
|
|
105
|
+
name,
|
|
106
|
+
interfaceId: (n) => {
|
|
107
|
+
check(NAME.test(n), "name", n);
|
|
108
|
+
return value({ kind: "interface", ns, name: n }, `${name}.${n}`);
|
|
109
|
+
},
|
|
110
|
+
implementationId: (n) => {
|
|
111
|
+
check(NAME.test(n), "name", n);
|
|
112
|
+
return value({ kind: "implementation", ns, name: n }, `${name}/${n}`);
|
|
113
|
+
}
|
|
114
|
+
}, name);
|
|
115
|
+
return ns;
|
|
116
|
+
}
|
|
117
|
+
function port(i, op) {
|
|
118
|
+
check(NAME.test(op), "op name", op);
|
|
119
|
+
return value({ kind: "port", interface: i, op }, `${i}/${op}`);
|
|
120
|
+
}
|
|
121
|
+
function runtime(id) {
|
|
122
|
+
check(ID.test(id), "runtime", id);
|
|
123
|
+
return value({ kind: "runtime", id }, id);
|
|
124
|
+
}
|
|
125
|
+
function pod(implementation, runtime2, name) {
|
|
126
|
+
check(POD.test(name), "pod", name);
|
|
127
|
+
return value({ kind: "pod", implementation, runtime: runtime2, pod: name }, `${implementation}@${runtime2}/${name}`);
|
|
128
|
+
}
|
|
129
|
+
var cut = (s, sep) => {
|
|
130
|
+
const at = s.lastIndexOf(sep);
|
|
131
|
+
return at > 0 ? [s.slice(0, at), s.slice(at + 1)] : undefined;
|
|
132
|
+
};
|
|
133
|
+
function read(kind, s) {
|
|
134
|
+
const bad = () => {
|
|
135
|
+
throw new Error(`bad ${kind} coordinate ${JSON.stringify(s)}`);
|
|
136
|
+
};
|
|
137
|
+
const attempt = (f) => {
|
|
138
|
+
try {
|
|
139
|
+
return f();
|
|
140
|
+
} catch {
|
|
141
|
+
return bad();
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
switch (kind) {
|
|
145
|
+
case "namespace":
|
|
146
|
+
return attempt(() => namespace(s));
|
|
147
|
+
case "interface": {
|
|
148
|
+
const [ns, n] = cut(s, ".") ?? bad();
|
|
149
|
+
return attempt(() => namespace(ns).interfaceId(n));
|
|
150
|
+
}
|
|
151
|
+
case "implementation": {
|
|
152
|
+
const [ns, n] = cut(s, "/") ?? bad();
|
|
153
|
+
return attempt(() => namespace(ns).implementationId(n));
|
|
154
|
+
}
|
|
155
|
+
case "port": {
|
|
156
|
+
const [i, op] = cut(s, "/") ?? bad();
|
|
157
|
+
return attempt(() => port(read("interface", i), op));
|
|
158
|
+
}
|
|
159
|
+
case "runtime":
|
|
160
|
+
return attempt(() => runtime(s));
|
|
161
|
+
default: {
|
|
162
|
+
const at = s.indexOf("@"), slash = s.indexOf("/", at);
|
|
163
|
+
if (at < 0 || slash < 0)
|
|
164
|
+
bad();
|
|
165
|
+
return attempt(() => pod(read("implementation", s.slice(0, at)), runtime(s.slice(at + 1, slash)), s.slice(slash + 1)));
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
var Coord = { namespace, port, runtime, pod, parse: read };
|
|
170
|
+
|
|
171
|
+
// packages/nano/src/result.ts
|
|
172
|
+
var success = (value2) => ({ ok: true, value: value2 });
|
|
173
|
+
var failure = (type, reason, coord) => ({
|
|
174
|
+
ok: false,
|
|
175
|
+
fail: coord === undefined ? { type, reason } : { type, reason, coord }
|
|
176
|
+
});
|
|
177
|
+
function isNanoResult(v) {
|
|
178
|
+
if (v === null || typeof v !== "object")
|
|
179
|
+
return false;
|
|
180
|
+
const r = v;
|
|
181
|
+
if (r.ok === true)
|
|
182
|
+
return "value" in r;
|
|
183
|
+
return r.ok === false && typeof r.fail?.type === "string" && typeof r.fail.reason === "string";
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// packages/nano/src/plain.ts
|
|
187
|
+
function handlers(i, obj) {
|
|
188
|
+
const methods = obj;
|
|
189
|
+
const out = {};
|
|
190
|
+
for (const o of Object.values(i.ops)) {
|
|
191
|
+
if (o.kind !== "action" || typeof methods[o.name] !== "function")
|
|
192
|
+
continue;
|
|
193
|
+
out[o.name] = async (input, ctx) => {
|
|
194
|
+
try {
|
|
195
|
+
return success(await methods[o.name].call(obj, input, ctx) ?? null);
|
|
196
|
+
} catch (e) {
|
|
197
|
+
const fail = e?.fail;
|
|
198
|
+
return fail ? { ok: false, fail } : failure("threw", e instanceof Error ? e.message : String(e));
|
|
42
199
|
}
|
|
43
200
|
};
|
|
44
201
|
}
|
|
45
|
-
|
|
202
|
+
return out;
|
|
203
|
+
}
|
|
204
|
+
var thrown = (fail) => Object.assign(new Error(`${fail.type}: ${fail.reason}`), { fail });
|
|
205
|
+
function plain(i, client) {
|
|
206
|
+
return new Proxy({}, {
|
|
207
|
+
get: (_, name) => {
|
|
208
|
+
if (typeof name !== "string" || name === "then")
|
|
209
|
+
return;
|
|
210
|
+
const ev = i?.ops[name]?.kind === "event" ? i.ops[name] : undefined;
|
|
211
|
+
if (ev)
|
|
212
|
+
return () => {
|
|
213
|
+
const c = client();
|
|
214
|
+
if (!c.ok)
|
|
215
|
+
throw thrown(c.fail);
|
|
216
|
+
const emissions = c.value.on(ev);
|
|
217
|
+
return { async* [Symbol.asyncIterator]() {
|
|
218
|
+
for await (const e of emissions)
|
|
219
|
+
yield e.output;
|
|
220
|
+
} };
|
|
221
|
+
};
|
|
222
|
+
return async (input) => {
|
|
223
|
+
const c = client();
|
|
224
|
+
if (!c.ok)
|
|
225
|
+
throw thrown(c.fail);
|
|
226
|
+
const r = await c.value.call[name](input ?? null);
|
|
227
|
+
if (r.ok)
|
|
228
|
+
return r.value;
|
|
229
|
+
throw thrown(r.fail);
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
function lift(i, obj) {
|
|
235
|
+
const methods = obj, sources = new Map;
|
|
236
|
+
for (const o of Object.values(i.ops)) {
|
|
237
|
+
const m = methods[o.name];
|
|
238
|
+
if (o.kind === "event" && typeof m === "function")
|
|
239
|
+
sources.set(port2(i, o), { op: o, run: () => m.call(obj) });
|
|
240
|
+
}
|
|
241
|
+
return { ...provide(i, handlers(i, obj)), sources };
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// packages/nano/src/selector.ts
|
|
245
|
+
var isInterface = (s) => ("byCoord" in s);
|
|
246
|
+
function selectorData(s) {
|
|
247
|
+
if (!isInterface(s))
|
|
248
|
+
return s;
|
|
249
|
+
const { tags, implementation, provider, runtime: runtime2 } = s;
|
|
250
|
+
return {
|
|
251
|
+
implements: Coord.parse("interface", s.coord),
|
|
252
|
+
...tags && { tags },
|
|
253
|
+
...implementation !== undefined && { implementation },
|
|
254
|
+
...provider !== undefined && { provider },
|
|
255
|
+
...runtime2 !== undefined && { runtime: runtime2 }
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
var of = (i, s = {}) => ({ ...i, ...s, implements: Coord.parse("interface", i.coord) });
|
|
259
|
+
var matches = (s, t) => (s.implements === undefined || t.provides.has(String(s.implements))) && (s.tags ?? []).every((tag) => t.tags.has(tag)) && (s.implementation === undefined || String(s.implementation) === t.implementation) && (s.provider === undefined || String(s.provider) === t.provider) && (s.runtime === undefined || String(s.runtime) === t.runtime);
|
|
260
|
+
var Selector = { of };
|
|
261
|
+
|
|
262
|
+
// packages/nano/src/implementation.ts
|
|
263
|
+
var isInterface2 = (s) => ("ops" in s) ? s : undefined;
|
|
264
|
+
function provide(i, handlers2) {
|
|
265
|
+
const byName = handlers2;
|
|
266
|
+
const out = new Map;
|
|
267
|
+
for (const o of Object.values(i.ops)) {
|
|
268
|
+
const h = o.kind === "event" ? undefined : byName[o.name];
|
|
269
|
+
if (h)
|
|
270
|
+
out.set(port2(i, o), h);
|
|
271
|
+
}
|
|
272
|
+
return { iface: i, handlers: out };
|
|
273
|
+
}
|
|
274
|
+
function define2(at, spec) {
|
|
275
|
+
const coord = String(at);
|
|
276
|
+
const slash = coord.lastIndexOf("/");
|
|
277
|
+
if (!COORD.test(coord) || slash < 0)
|
|
278
|
+
throw new Error(`bad implementation coordinate ${coord}`);
|
|
279
|
+
const calls = {};
|
|
280
|
+
for (const [op, byRole] of Object.entries(spec.calls ?? {})) {
|
|
281
|
+
if (!spec.provides.some((i) => (op in i.ops)))
|
|
282
|
+
throw new Error(`${coord}: ${op} is not an op this implementation provides`);
|
|
283
|
+
calls[op] = Object.entries(byRole).flatMap(([role, ops]) => {
|
|
284
|
+
const dep = spec.dependencies?.[role];
|
|
285
|
+
if (!dep)
|
|
286
|
+
throw new Error(`${coord}: ${role} is not a dependency`);
|
|
287
|
+
const iface = isInterface2(dep);
|
|
288
|
+
return ops.map((o) => {
|
|
289
|
+
if (iface && !iface.byCoord.has(o.coord))
|
|
290
|
+
throw new Error(`${coord}: ${iface.coord} has no op ${o.name}`);
|
|
291
|
+
return `${role}.${o.name}`;
|
|
292
|
+
});
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
return {
|
|
296
|
+
coord,
|
|
297
|
+
calls,
|
|
298
|
+
provider: coord.slice(0, slash),
|
|
299
|
+
provides: spec.provides,
|
|
300
|
+
dependencies: Object.fromEntries(Object.entries(spec.dependencies ?? {}).map(([role, s]) => [role, selectorData(s)])),
|
|
301
|
+
...spec.config && { config: spec.config },
|
|
302
|
+
...spec.description !== undefined && { description: spec.description },
|
|
303
|
+
async make(base, config) {
|
|
304
|
+
const withDeps = (c) => Object.assign(Object.create(c), { deps: Object.fromEntries(Object.keys(spec.dependencies ?? {}).map((role) => [role, plain(isInterface2(spec.dependencies[role]), () => c.one(selectorData(spec.dependencies[role])))])) });
|
|
305
|
+
const ctx = withDeps(base);
|
|
306
|
+
const made = await spec.make(ctx, config);
|
|
307
|
+
if (!Array.isArray(made) && spec.provides.length !== 1)
|
|
308
|
+
throw new Error(`${coord}: a plain object provides exactly one interface`);
|
|
309
|
+
const parts = Array.isArray(made) ? made : [lift(spec.provides[0], made)];
|
|
310
|
+
const declared = new Set(spec.provides.map((i) => i.coord));
|
|
311
|
+
const given = new Set;
|
|
312
|
+
const out = new Map, sources = new Map;
|
|
313
|
+
for (const part of parts) {
|
|
314
|
+
const ic = part.iface.coord;
|
|
315
|
+
if (!declared.has(ic))
|
|
316
|
+
throw new Error(`${coord}: ${ic} is not provided`);
|
|
317
|
+
if (given.has(ic))
|
|
318
|
+
throw new Error(`${coord}: ${ic} is provided twice`);
|
|
319
|
+
given.add(ic);
|
|
320
|
+
for (const [p, h] of part.handlers)
|
|
321
|
+
out.set(p, (input, inv) => h(input, withDeps(inv)));
|
|
322
|
+
for (const [p, src] of part.sources ?? [])
|
|
323
|
+
sources.set(p, src);
|
|
324
|
+
}
|
|
325
|
+
for (const i of spec.provides)
|
|
326
|
+
for (const o of Object.values(i.ops))
|
|
327
|
+
if (o.kind !== "event" && !out.has(port2(i, o)))
|
|
328
|
+
throw new Error(`${coord}: missing ${port2(i, o)}`);
|
|
329
|
+
return { handlers: out, sources };
|
|
330
|
+
}
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
var Implementation = { define: define2 };
|
|
46
334
|
|
|
47
|
-
// packages/
|
|
48
|
-
var
|
|
49
|
-
|
|
50
|
-
const
|
|
51
|
-
|
|
52
|
-
|
|
335
|
+
// packages/nano/src/iface.ts
|
|
336
|
+
var asDef = (s) => ("hash" in s) && ("check" in s) ? s : Schema.define(s);
|
|
337
|
+
function builder(api, at, steps = { deps: {} }) {
|
|
338
|
+
const { deps, config, description } = steps;
|
|
339
|
+
const build = (lifts) => Object.assign(Implementation.define(at, {
|
|
340
|
+
provides: lifts.map(([i]) => i),
|
|
341
|
+
dependencies: deps,
|
|
342
|
+
...config && { config },
|
|
343
|
+
...description !== undefined && { description },
|
|
344
|
+
async make(ctx, cfg) {
|
|
345
|
+
const c = Object.assign(Object.create(ctx), { config: cfg });
|
|
346
|
+
const parts = [];
|
|
347
|
+
for (const [i, f] of lifts) {
|
|
348
|
+
parts.push(lift(i, await f(c)));
|
|
349
|
+
}
|
|
350
|
+
return parts;
|
|
351
|
+
}
|
|
352
|
+
}), { satisfies: (j, f) => build([...lifts, [j, f]]) });
|
|
353
|
+
return {
|
|
354
|
+
needs: (d) => builder(api, at, { ...steps, deps: d }),
|
|
355
|
+
config: (s) => builder(api, at, { ...steps, config: asDef(s) }),
|
|
356
|
+
description: (text) => builder(api, at, { ...steps, description: text }),
|
|
357
|
+
make: (f) => build([[api, f]]),
|
|
358
|
+
create: (spec) => builder(api, at, {
|
|
359
|
+
deps: spec.needs ?? {},
|
|
360
|
+
...spec.config && { config: asDef(spec.config) },
|
|
361
|
+
...spec.description !== undefined && { description: spec.description }
|
|
362
|
+
}).make(spec.make)
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
var COORD = /^[a-zA-Z][a-zA-Z0-9-]*([./][a-zA-Z0-9-]+)+$/;
|
|
366
|
+
var port2 = (i, o) => `${i.coord}/${o.name}`;
|
|
367
|
+
function define3(at, unnamed) {
|
|
368
|
+
const coord = String(at);
|
|
53
369
|
try {
|
|
54
|
-
|
|
55
|
-
} catch
|
|
56
|
-
|
|
370
|
+
Coord.parse("interface", coord);
|
|
371
|
+
} catch {
|
|
372
|
+
throw new Error(`bad interface coordinate ${coord}`);
|
|
57
373
|
}
|
|
374
|
+
const ops = Object.fromEntries(Object.entries(unnamed).map(([name, o]) => [name, { ...o, name, coord: hashOf(canonical({ name, input: o.input?.hash ?? null, output: o.output.hash })) }]));
|
|
375
|
+
const api = { coord, ops, byCoord: new Map(Object.values(ops).map((o) => [o.coord, o])), impl: (at2) => builder(api, at2) };
|
|
376
|
+
return api;
|
|
58
377
|
}
|
|
59
|
-
var
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
378
|
+
var Interface = { define: define3 };
|
|
379
|
+
// packages/nano/src/provider.ts
|
|
380
|
+
function define4(at, implementations, meta = {}) {
|
|
381
|
+
const coord = String(at);
|
|
382
|
+
const byCoord = new Map;
|
|
383
|
+
for (const i of implementations) {
|
|
384
|
+
if (i.provider !== coord)
|
|
385
|
+
throw new Error(`${i.coord} is not under ${coord}`);
|
|
386
|
+
if (byCoord.has(i.coord))
|
|
387
|
+
throw new Error(`${i.coord} is listed twice`);
|
|
388
|
+
byCoord.set(i.coord, i);
|
|
389
|
+
}
|
|
390
|
+
return { coord, implementations: byCoord, meta };
|
|
391
|
+
}
|
|
392
|
+
var Provider = { define: define4 };
|
|
393
|
+
function namespace2(name) {
|
|
394
|
+
const pure = Coord.namespace(name);
|
|
395
|
+
const ns = Object.freeze({
|
|
396
|
+
...pure,
|
|
397
|
+
interfaceId: (n) => Object.freeze({ ...pure.interfaceId(n), ns }),
|
|
398
|
+
implementationId: (n) => Object.freeze({ ...pure.implementationId(n), ns }),
|
|
399
|
+
interface: (n, ops) => Interface.define(ns.interfaceId(n), ops),
|
|
400
|
+
provider: (implementations, meta) => define4(ns, implementations, meta)
|
|
401
|
+
});
|
|
402
|
+
return ns;
|
|
403
|
+
}
|
|
404
|
+
var Coord2 = { ...Coord, namespace: namespace2 };
|
|
405
|
+
// packages/nano/src/registry.ts
|
|
406
|
+
var opSet = (i) => [...i.byCoord.keys()].sort().join();
|
|
407
|
+
var byCoord = (a, b) => a.coord < b.coord ? -1 : a.coord > b.coord ? 1 : 0;
|
|
408
|
+
function create() {
|
|
409
|
+
const providers = new Map;
|
|
410
|
+
const impls = new Map;
|
|
411
|
+
const ifaces = new Map;
|
|
412
|
+
const ops = new Map;
|
|
413
|
+
const implsOf = new Map;
|
|
414
|
+
return {
|
|
415
|
+
add(p) {
|
|
416
|
+
if (providers.has(p.coord))
|
|
417
|
+
return failure("invalid-input", `provider ${p.coord} is already registered`);
|
|
418
|
+
const seen = new Map;
|
|
419
|
+
for (const impl of p.implementations.values()) {
|
|
420
|
+
for (const i of impl.provides) {
|
|
421
|
+
const known = ifaces.get(i.coord) ?? seen.get(i.coord);
|
|
422
|
+
if (known && opSet(known) !== opSet(i))
|
|
423
|
+
return failure("invalid-input", `interface ${i.coord} differs`);
|
|
424
|
+
seen.set(i.coord, known ?? i);
|
|
425
|
+
}
|
|
70
426
|
}
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
const failed = [];
|
|
83
|
-
for (const op of emits) {
|
|
84
|
-
const read = await run(inst, Ops.key(op), undefined);
|
|
85
|
-
if (!isOk(read)) {
|
|
86
|
-
failed.push(read);
|
|
87
|
-
continue;
|
|
427
|
+
providers.set(p.coord, p);
|
|
428
|
+
for (const impl of p.implementations.values()) {
|
|
429
|
+
impls.set(impl.coord, impl);
|
|
430
|
+
for (const i of impl.provides) {
|
|
431
|
+
if (!ifaces.has(i.coord))
|
|
432
|
+
ifaces.set(i.coord, i);
|
|
433
|
+
for (const o of i.byCoord.values())
|
|
434
|
+
if (!ops.has(o.coord))
|
|
435
|
+
ops.set(o.coord, o);
|
|
436
|
+
implsOf.set(i.coord, [...implsOf.get(i.coord) ?? [], impl]);
|
|
437
|
+
}
|
|
88
438
|
}
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
439
|
+
return success(undefined);
|
|
440
|
+
},
|
|
441
|
+
manifest: () => ({
|
|
442
|
+
providers: [...providers.values()].sort(byCoord).map((p) => ({ coord: p.coord, implementations: [...p.implementations.keys()].sort() })),
|
|
443
|
+
implementations: [...impls.values()].sort(byCoord).map((i) => ({
|
|
444
|
+
coord: i.coord,
|
|
445
|
+
provides: i.provides.map((x) => x.coord).sort(),
|
|
446
|
+
dependencies: JSON.parse(JSON.stringify(i.dependencies))
|
|
447
|
+
})),
|
|
448
|
+
interfaces: [...ifaces.values()].sort(byCoord).map((i) => ({
|
|
449
|
+
coord: i.coord,
|
|
450
|
+
ops: Object.values(i.ops).map((o) => ({
|
|
451
|
+
name: o.name,
|
|
452
|
+
kind: o.kind,
|
|
453
|
+
coord: o.coord,
|
|
454
|
+
...o.input && { input: o.input.hash },
|
|
455
|
+
...o.output && { output: o.output.hash }
|
|
456
|
+
}))
|
|
457
|
+
}))
|
|
458
|
+
}),
|
|
459
|
+
provider: (c) => providers.get(c),
|
|
460
|
+
implementation: (c) => impls.get(c),
|
|
461
|
+
implementationsOf: (c) => implsOf.get(c) ?? [],
|
|
462
|
+
interface: (c) => ifaces.get(c),
|
|
463
|
+
op: (c) => ops.get(c)
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
async function load(modules, base) {
|
|
467
|
+
const registry = create();
|
|
468
|
+
const exports = {};
|
|
469
|
+
for (const [ns, path] of Object.entries(modules)) {
|
|
470
|
+
let mod;
|
|
471
|
+
try {
|
|
472
|
+
mod = await import(new URL(path, base).href);
|
|
473
|
+
} catch (e) {
|
|
474
|
+
return failure("not-found", `${ns} (${path}): ${e instanceof Error ? e.message : String(e)}`);
|
|
475
|
+
}
|
|
476
|
+
const p = mod.default;
|
|
477
|
+
const q = p;
|
|
478
|
+
const added = q && typeof q.coord === "string" && q.implementations instanceof Map ? registry.add(q) : failure("invalid-input", `${path} has no default Provider`);
|
|
479
|
+
if (!added.ok)
|
|
480
|
+
return added;
|
|
481
|
+
exports[ns] = mod;
|
|
482
|
+
}
|
|
483
|
+
return success({ registry, exports });
|
|
484
|
+
}
|
|
485
|
+
var Registry = { create, load };
|
|
486
|
+
// packages/nano/src/policy.ts
|
|
487
|
+
import { Type } from "typebox";
|
|
488
|
+
var ALLOW_ALL = Object.freeze({ isAllowed: () => ({ approved: true }) });
|
|
489
|
+
var Policies = {
|
|
490
|
+
allowAll: () => ALLOW_ALL
|
|
491
|
+
};
|
|
492
|
+
var Kind = Type.Union([Type.Literal("call"), Type.Literal("pipe"), Type.Literal("on"), Type.Literal("subscribe"), Type.Literal("unsubscribe"), Type.Literal("lifecycle"), Type.Literal("start"), Type.Literal("*")]);
|
|
493
|
+
var Kinds = Type.Union([Kind, Type.Array(Kind)]);
|
|
494
|
+
var Match = {
|
|
495
|
+
from: Type.Optional(Type.String()),
|
|
496
|
+
toPod: Type.Optional(Type.String()),
|
|
497
|
+
toInterface: Type.Optional(Type.String()),
|
|
498
|
+
toPort: Type.Optional(Type.String()),
|
|
499
|
+
outside: Type.Optional(Type.Boolean())
|
|
500
|
+
};
|
|
501
|
+
var Rule = Type.Union([
|
|
502
|
+
Type.Object({ allow: Kinds, ...Match }, { additionalProperties: false }),
|
|
503
|
+
Type.Object({ deny: Kinds, ...Match }, { additionalProperties: false })
|
|
504
|
+
]);
|
|
505
|
+
var any = (v, x) => v === undefined || v === "*" || v === x;
|
|
506
|
+
var fits2 = (c, a, iface) => (c.kinds.has("*") || c.kinds.has(a.kind)) && any(c.r.toPod, a.to) && any(c.r.toInterface, iface) && any(c.r.toPort, a.port) && (c.r.outside === undefined || c.r.outside === a.outside);
|
|
507
|
+
function PolicyRules(rules) {
|
|
508
|
+
const byFrom = new Map, anyFrom = [];
|
|
509
|
+
rules.forEach((r, i) => {
|
|
510
|
+
const c = { i, allow: "allow" in r, kinds: new Set(["allow" in r ? r.allow : r.deny].flat()), r };
|
|
511
|
+
if (r.from === undefined || r.from === "*")
|
|
512
|
+
anyFrom.push(c);
|
|
513
|
+
else {
|
|
514
|
+
const l = byFrom.get(r.from);
|
|
515
|
+
if (l)
|
|
516
|
+
l.push(c);
|
|
517
|
+
else
|
|
518
|
+
byFrom.set(r.from, [c]);
|
|
519
|
+
}
|
|
520
|
+
});
|
|
521
|
+
return { isAllowed: (ask) => {
|
|
522
|
+
const iface = ask.port?.slice(0, ask.port.lastIndexOf("/"));
|
|
523
|
+
const named = byFrom.get(ask.from) ?? [];
|
|
524
|
+
let a = 0, b = 0, hit;
|
|
525
|
+
while (!hit && (a < named.length || b < anyFrom.length)) {
|
|
526
|
+
const c = b >= anyFrom.length || a < named.length && named[a].i < anyFrom[b].i ? named[a++] : anyFrom[b++];
|
|
527
|
+
if (fits2(c, ask, iface))
|
|
528
|
+
hit = c;
|
|
529
|
+
}
|
|
530
|
+
if (!hit)
|
|
531
|
+
return { approved: false, reason: "no rule allows it" };
|
|
532
|
+
return hit.allow ? { approved: true } : { approved: false, reason: `rules[${hit.i}]` };
|
|
533
|
+
} };
|
|
534
|
+
}
|
|
535
|
+
// packages/nano/src/deployment-policy.ts
|
|
536
|
+
var ALLOW_ALL2 = Object.freeze({ isAllowed: () => ({ approved: true }) });
|
|
537
|
+
var DeploymentPolicies = {
|
|
538
|
+
allowAll: () => ALLOW_ALL2
|
|
539
|
+
};
|
|
540
|
+
// packages/nano/src/pod.ts
|
|
541
|
+
var describe = (eager) => (impl, opts = {}) => ({
|
|
542
|
+
implementation: impl.coord,
|
|
543
|
+
...opts.config !== undefined && { config: opts.config },
|
|
544
|
+
eager,
|
|
545
|
+
...opts.isolation !== undefined && opts.isolation !== "host" && { isolation: opts.isolation }
|
|
546
|
+
});
|
|
547
|
+
var Pod = { lazy: describe(false), eager: describe(true) };
|
|
548
|
+
// packages/nano/src/pods.ts
|
|
549
|
+
import { Type as Type2 } from "typebox";
|
|
550
|
+
import { Value } from "typebox/value";
|
|
551
|
+
var Id = Type2.String({ pattern: /^[^/\s#\x00-\x1f\x7f]{1,64}$/.source });
|
|
552
|
+
var PodName = Type2.String({ pattern: /^[^/.\s#\x00-\x1f\x7f]{1,64}$/.source });
|
|
553
|
+
var strict = { additionalProperties: false };
|
|
554
|
+
var Shape = Type2.Record(PodName, Type2.Object({
|
|
555
|
+
implementation: Type2.String(),
|
|
556
|
+
config: Type2.Optional(Type2.Unknown()),
|
|
557
|
+
eager: Type2.Boolean(),
|
|
558
|
+
isolation: Type2.Optional(Type2.Union([Type2.Literal("host"), Type2.Literal("sandbox"), Type2.Literal("isolated-sandbox"), Type2.Literal("home-origin")]))
|
|
559
|
+
}, strict), { ...strict, maxProperties: 5000 });
|
|
560
|
+
var Tags = Type2.Record(Id, Type2.Array(Type2.String()), strict);
|
|
561
|
+
function shapeError(schema, d, what) {
|
|
562
|
+
const e = Value.Errors(schema, d)[0];
|
|
563
|
+
if (!e)
|
|
564
|
+
return;
|
|
565
|
+
const why = e.message === "schema is false" ? "not allowed here (an unknown key, or a name breaking the id rule)" : e.message;
|
|
566
|
+
return `${what} ${e.instancePath || "/"}: ${why}`;
|
|
567
|
+
}
|
|
568
|
+
var origins = new WeakMap;
|
|
569
|
+
var originOf = (pods) => origins.get(pods);
|
|
570
|
+
function view(all, registry, root, tags) {
|
|
571
|
+
const pods = Object.freeze({
|
|
572
|
+
names: () => [...all.keys()],
|
|
573
|
+
get: (name) => structuredClone(all.get(name)),
|
|
574
|
+
select(names) {
|
|
575
|
+
if (!Array.isArray(names) || names.some((n) => typeof n !== "string"))
|
|
576
|
+
return failure("invalid-input", "select takes pod names");
|
|
577
|
+
const seen = new Set, dup = names.find((n) => seen.size === seen.add(n).size), unknown = names.find((n) => !all.has(n));
|
|
578
|
+
if (dup !== undefined)
|
|
579
|
+
return failure("invalid-input", `pod ${dup} is selected twice`);
|
|
580
|
+
if (unknown !== undefined)
|
|
581
|
+
return failure("not-found", `no pod ${unknown}`);
|
|
582
|
+
const kept = tags && Object.fromEntries(names.filter((n) => Object.hasOwn(tags, n)).map((n) => [n, tags[n]]));
|
|
583
|
+
return success(view(new Map(names.map((n) => [n, all.get(n)])), registry, root ?? pods, kept));
|
|
584
|
+
},
|
|
585
|
+
deployment: () => structuredClone(Object.fromEntries(all))
|
|
586
|
+
});
|
|
587
|
+
origins.set(pods, Object.freeze({ registry, root: root ?? pods, ...tags && { tags }, pods: all }));
|
|
588
|
+
return pods;
|
|
589
|
+
}
|
|
590
|
+
function create2(d, opts) {
|
|
591
|
+
try {
|
|
592
|
+
const copy = structuredClone(d), tags = structuredClone(opts.tags);
|
|
593
|
+
const why = shapeError(Shape, copy, "pods") ?? (tags === undefined ? undefined : shapeError(Tags, tags, "tags"));
|
|
594
|
+
if (why)
|
|
595
|
+
return failure("invalid-input", why);
|
|
596
|
+
const stray = Object.keys(tags ?? {}).find((n) => !Object.hasOwn(copy, n));
|
|
597
|
+
if (stray !== undefined)
|
|
598
|
+
return failure("invalid-input", `tags: no pod ${stray}`);
|
|
599
|
+
for (const [name, p] of Object.entries(copy)) {
|
|
600
|
+
if (name === "host")
|
|
601
|
+
return failure("invalid-input", "pod name 'host' is reserved for the host");
|
|
602
|
+
const impl = opts.registry.implementation(p.implementation);
|
|
603
|
+
if (!impl)
|
|
604
|
+
return failure("not-found", `pod ${name}: no implementation ${p.implementation}`);
|
|
605
|
+
if (impl.config && !impl.config.check(p.config))
|
|
606
|
+
return failure("invalid-input", `pod ${name}: config does not fit ${impl.config.label ?? "its schema"}`);
|
|
607
|
+
}
|
|
608
|
+
return success(view(new Map(Object.entries(copy)), opts.registry, undefined, tags));
|
|
609
|
+
} catch (e) {
|
|
610
|
+
return failure("invalid-input", `unreadable pods: ${e instanceof Error ? e.message : String(e)}`);
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
var Pods = { create: create2 };
|
|
614
|
+
// packages/nano/src/runtime.ts
|
|
615
|
+
import { Type as Type3 } from "typebox";
|
|
616
|
+
var strict2 = { additionalProperties: false };
|
|
617
|
+
var Shape2 = Type3.Object({
|
|
618
|
+
pods: Type3.Array(Type3.String()),
|
|
619
|
+
subscriptions: Type3.Array(Type3.Union([
|
|
620
|
+
Type3.Object({
|
|
621
|
+
kind: Type3.Literal("call"),
|
|
622
|
+
from: Type3.String(),
|
|
623
|
+
to: Type3.String(),
|
|
624
|
+
ops: Type3.Optional(Type3.Array(Type3.Object({ source: Type3.String(), target: Type3.String() }, strict2), { maxItems: 2000 }))
|
|
625
|
+
}, strict2),
|
|
626
|
+
Type3.Object({ kind: Type3.Literal("pipe"), from: Type3.String(), source: Type3.String(), to: Type3.String(), target: Type3.String() }, strict2)
|
|
627
|
+
]), { maxItems: 2000 }),
|
|
628
|
+
policy: Type3.Optional(Type3.Union([
|
|
629
|
+
Type3.Object({ kind: Type3.Literal("allow-all") }, strict2),
|
|
630
|
+
Type3.Object({ kind: Type3.Literal("rules"), rules: Type3.Array(Rule, { maxItems: 2000 }) }, strict2)
|
|
631
|
+
]))
|
|
632
|
+
}, strict2);
|
|
633
|
+
var label = (s) => s.kind === "call" ? `${s.from}->${s.to}` : `${s.from}->${s.to} (${s.source} to ${s.target})`;
|
|
634
|
+
var ports = new WeakMap;
|
|
635
|
+
var opAt = (impl, p) => {
|
|
636
|
+
let m = ports.get(impl);
|
|
637
|
+
if (!m) {
|
|
638
|
+
m = new Map;
|
|
639
|
+
for (const i of impl.provides)
|
|
640
|
+
for (const o of Object.values(i.ops))
|
|
641
|
+
if (!m.has(port2(i, o)))
|
|
642
|
+
m.set(port2(i, o), o);
|
|
643
|
+
ports.set(impl, m);
|
|
644
|
+
}
|
|
645
|
+
return m.get(p);
|
|
646
|
+
};
|
|
647
|
+
function unfit(s, from, to) {
|
|
648
|
+
if (s.kind === "call") {
|
|
649
|
+
const deps = Object.values(from.dependencies).flatMap((d) => d.implements === undefined ? [] : [String(d.implements)]);
|
|
650
|
+
if (deps.length && !to.provides.some((i) => deps.includes(i.coord)))
|
|
651
|
+
return `${s.to} provides none of ${s.from}'s dependencies`;
|
|
652
|
+
const pairs = new Set;
|
|
653
|
+
for (const o of s.ops ?? []) {
|
|
654
|
+
if (!opAt(from, o.source))
|
|
655
|
+
return `${o.source} is not an op of ${s.from}`;
|
|
656
|
+
if (opAt(to, o.target)?.kind !== "action")
|
|
657
|
+
return `${o.target} is not an action of ${s.to}`;
|
|
658
|
+
if (pairs.size === pairs.add(JSON.stringify([o.source, o.target])).size)
|
|
659
|
+
return `${o.source} to ${o.target} is there twice`;
|
|
660
|
+
}
|
|
661
|
+
return;
|
|
662
|
+
}
|
|
663
|
+
const source = opAt(from, s.source), target = opAt(to, s.target);
|
|
664
|
+
if (!source)
|
|
665
|
+
return `${s.source} is not an event or action of ${s.from}`;
|
|
666
|
+
if (target?.kind !== "action")
|
|
667
|
+
return `${s.target} is not an action of ${s.to}`;
|
|
668
|
+
return fits(source, target) ? undefined : `${s.source} does not fit ${s.target}`;
|
|
669
|
+
}
|
|
670
|
+
function check2(id, r, pods) {
|
|
671
|
+
const origin = originOf(pods);
|
|
672
|
+
if (!origin)
|
|
673
|
+
return `runtime ${id}: its pods do not come from Pods.create`;
|
|
674
|
+
const placed = new Set, seen = new Set;
|
|
675
|
+
for (const name of r.pods) {
|
|
676
|
+
if (!origin.pods.has(name))
|
|
677
|
+
return `runtime ${id}: no pod ${name}`;
|
|
678
|
+
if (placed.size === placed.add(name).size)
|
|
679
|
+
return `runtime ${id}: ${name} is placed twice`;
|
|
680
|
+
}
|
|
681
|
+
for (const s of r.subscriptions) {
|
|
682
|
+
if (!origin.pods.has(s.from))
|
|
683
|
+
return `runtime ${id}: ${label(s)}: no pod ${s.from}`;
|
|
684
|
+
const end = (s.kind === "call" ? [s.to] : [s.from, s.to]).find((n) => !placed.has(n));
|
|
685
|
+
if (end !== undefined)
|
|
686
|
+
return `runtime ${id}: ${label(s)}: ${end} is not placed here`;
|
|
687
|
+
const key = JSON.stringify(s.kind === "call" ? [s.from, s.to] : [s.from, s.to, s.source, s.target]);
|
|
688
|
+
if (seen.has(key))
|
|
689
|
+
return `runtime ${id}: ${label(s)} is there twice`;
|
|
690
|
+
seen.add(key);
|
|
691
|
+
const impl = (n) => origin.registry.implementation(origin.pods.get(n).implementation);
|
|
692
|
+
const why = unfit(s, impl(s.from), impl(s.to));
|
|
693
|
+
if (why)
|
|
694
|
+
return `runtime ${id}: ${label(s)}: ${why}`;
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
var made = new WeakSet;
|
|
698
|
+
var isRuntime = (r) => made.has(r);
|
|
699
|
+
function create3(id, d, pods) {
|
|
700
|
+
try {
|
|
701
|
+
const copy = structuredClone(d);
|
|
702
|
+
const why = shapeError(Shape2, copy, `runtime ${id}`) ?? check2(id, copy, pods);
|
|
703
|
+
if (why)
|
|
704
|
+
return failure("invalid-input", why);
|
|
705
|
+
const runtime2 = Object.freeze({ id, pods, deployment: () => structuredClone(copy) });
|
|
706
|
+
made.add(runtime2);
|
|
707
|
+
return success(runtime2);
|
|
708
|
+
} catch (e) {
|
|
709
|
+
return failure("invalid-input", `unreadable runtime ${id}: ${e instanceof Error ? e.message : String(e)}`);
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
var Runtime = { create: create3 };
|
|
713
|
+
// packages/nano/src/deployment.ts
|
|
714
|
+
import { Type as Type4 } from "typebox";
|
|
715
|
+
|
|
716
|
+
// packages/nano/src/deployment-edit.ts
|
|
717
|
+
function edit(base, registry) {
|
|
718
|
+
const d = structuredClone(base);
|
|
719
|
+
const runtime2 = (id) => d.runtimes[id] ??= { pods: [], subscriptions: [] };
|
|
720
|
+
const fail = (type, reason) => {
|
|
721
|
+
throw thrown({ type, reason });
|
|
722
|
+
};
|
|
723
|
+
function place(impl, w) {
|
|
724
|
+
if (Object.hasOwn(d.pods, w.pod))
|
|
725
|
+
fail("invalid-input", `pod ${w.pod} is already in the deployment`);
|
|
726
|
+
d.pods[w.pod] = { implementation: impl.coord, eager: w.eager ?? false };
|
|
727
|
+
runtime2(w.in).pods.push(w.pod);
|
|
728
|
+
}
|
|
729
|
+
function handle(at, pod2, api) {
|
|
730
|
+
return { runtime: at, pod: pod2, implementation: d.pods[pod2].implementation, create(impl, w) {
|
|
731
|
+
place(impl, w);
|
|
732
|
+
const r = runtime2(at);
|
|
733
|
+
r.subscriptions.push({ kind: "call", from: w.pod, to: pod2 });
|
|
734
|
+
if (r.policy?.kind === "rules")
|
|
735
|
+
r.policy.rules.unshift({ allow: ["call", "subscribe"], from: w.pod, outside: !r.pods.includes(w.pod), toInterface: api.coord });
|
|
736
|
+
const own = impl.provides[0];
|
|
737
|
+
return own ? handle(w.in, w.pod, own) : fail("invalid-input", `${impl.coord} provides no interface`);
|
|
738
|
+
} };
|
|
739
|
+
}
|
|
740
|
+
function resolve(at, api) {
|
|
741
|
+
const found = (d.runtimes[at]?.pods ?? []).filter((p) => registry.implementation(d.pods[p]?.implementation ?? "")?.provides.some((i) => i.coord === api.coord));
|
|
742
|
+
if (found.length === 0)
|
|
743
|
+
return fail("not-found", `no pod provides ${api.coord} in ${at}`);
|
|
744
|
+
if (found.length > 1)
|
|
745
|
+
return fail("not-unique", `${found.length} pods provide ${api.coord} in ${at}`);
|
|
746
|
+
return handle(at, found[0], api);
|
|
747
|
+
}
|
|
748
|
+
const same = (a, s) => s.kind === "pipe" && s.from === a.from && s.source === a.source && s.to === a.to && s.target === a.target;
|
|
749
|
+
function pipe(at, p) {
|
|
750
|
+
const r = d.runtimes[at];
|
|
751
|
+
if (!r)
|
|
752
|
+
return fail("not-found", `no runtime ${at}`);
|
|
753
|
+
for (const pod2 of [p.from, p.to])
|
|
754
|
+
if (!r.pods.includes(pod2))
|
|
755
|
+
fail("not-found", `${pod2} is not placed in ${at}`);
|
|
756
|
+
if (r.subscriptions.some((s) => same(p, s)))
|
|
757
|
+
fail("invalid-input", `${p.from} ${p.source} is already piped to ${p.to} ${p.target} in ${at}`);
|
|
758
|
+
r.subscriptions.push({ kind: "pipe", ...p });
|
|
759
|
+
}
|
|
760
|
+
function unpipe(at, p) {
|
|
761
|
+
const r = d.runtimes[at], i = r ? r.subscriptions.findIndex((s) => same(p, s)) : -1;
|
|
762
|
+
if (!r || i < 0)
|
|
763
|
+
return fail("not-found", `no such pipe in ${at}`);
|
|
764
|
+
r.subscriptions.splice(i, 1);
|
|
765
|
+
}
|
|
766
|
+
return { place, resolve, pipe, unpipe, deployment: () => structuredClone(d) };
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
// packages/nano/src/deployment.ts
|
|
770
|
+
var strict3 = { additionalProperties: false };
|
|
771
|
+
var RuntimeIds = Type4.Record(Id, Type4.Unknown(), { ...strict3, maxProperties: 50 });
|
|
772
|
+
var Shape3 = Type4.Object({
|
|
773
|
+
pods: Type4.Unknown(),
|
|
774
|
+
runtimes: RuntimeIds,
|
|
775
|
+
tags: Type4.Optional(Type4.Record(Id, Type4.Array(Type4.String()), strict3)),
|
|
776
|
+
modules: Type4.Optional(Type4.Record(Id, Type4.String({ minLength: 1 }), strict3)),
|
|
777
|
+
views: Type4.Optional(Type4.Record(Id, Type4.String({ minLength: 1 }), strict3)),
|
|
778
|
+
frames: Type4.Optional(Type4.Record(Id, Type4.String({ minLength: 1 }), strict3)),
|
|
779
|
+
layout: Type4.Optional(Type4.Record(Type4.String(), Type4.Unknown()))
|
|
780
|
+
}, strict3);
|
|
781
|
+
function assemble(d, registry) {
|
|
782
|
+
try {
|
|
783
|
+
const copy = structuredClone(d);
|
|
784
|
+
const why = shapeError(Shape3, copy, "deployment");
|
|
785
|
+
if (why)
|
|
786
|
+
return failure("invalid-input", why);
|
|
787
|
+
const { pods: podDeployment, runtimes, tags } = copy;
|
|
788
|
+
const pods = Pods.create(podDeployment, { registry, tags });
|
|
789
|
+
if (!pods.ok)
|
|
790
|
+
return pods;
|
|
791
|
+
const out = Object.create(null);
|
|
792
|
+
for (const [id, r] of Object.entries(runtimes)) {
|
|
793
|
+
const froms = Array.isArray(r?.subscriptions) ? r.subscriptions.flatMap((s) => s?.kind === "call" && pods.value.names().includes(s.from) ? [s.from] : []) : [];
|
|
794
|
+
const scope = pods.value.select(Array.isArray(r?.pods) ? [...new Set([...r.pods.filter((n) => typeof n === "string"), ...froms])] : []);
|
|
795
|
+
if (!scope.ok)
|
|
796
|
+
return failure("invalid-input", `runtime ${id}: ${scope.fail.reason}`);
|
|
797
|
+
const runtime2 = Runtime.create(id, r, scope.value);
|
|
798
|
+
if (!runtime2.ok)
|
|
799
|
+
return runtime2;
|
|
800
|
+
out[id] = runtime2.value;
|
|
801
|
+
}
|
|
802
|
+
return success(out);
|
|
803
|
+
} catch (e) {
|
|
804
|
+
return failure("invalid-input", `unreadable deployment: ${e instanceof Error ? e.message : String(e)}`);
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
var AppDeployment = { assemble, edit };
|
|
808
|
+
// packages/nano/src/application/apply.ts
|
|
809
|
+
import { Value as Value2 } from "typebox/value";
|
|
810
|
+
function diff(a, b) {
|
|
811
|
+
const names = (o, p) => Object.keys(o).filter((k) => !(k in p));
|
|
812
|
+
const runtimes = [...new Set([...Object.keys(a.runtimes), ...Object.keys(b.runtimes)])];
|
|
813
|
+
return {
|
|
814
|
+
added: names(b.pods, a.pods),
|
|
815
|
+
removed: names(a.pods, b.pods),
|
|
816
|
+
changed: Object.keys(b.pods).filter((k) => (k in a.pods) && !Value2.Equal(a.pods[k], b.pods[k])),
|
|
817
|
+
rewired: runtimes.filter((id) => !Value2.Equal(a.runtimes[id]?.pods, b.runtimes[id]?.pods) || !Value2.Equal(a.runtimes[id]?.subscriptions, b.runtimes[id]?.subscriptions))
|
|
818
|
+
};
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
// packages/nano/src/application/load.ts
|
|
822
|
+
var why = (e) => e instanceof Error ? e.message : String(e);
|
|
823
|
+
async function loaded(url) {
|
|
824
|
+
let deployment;
|
|
825
|
+
try {
|
|
826
|
+
const res = await fetch(url);
|
|
827
|
+
if (!res.ok)
|
|
828
|
+
return failure("not-found", `${url}: ${res.status} ${res.statusText}`);
|
|
829
|
+
deployment = await res.json();
|
|
830
|
+
} catch (e) {
|
|
831
|
+
return failure("invalid-input", `${url}: ${why(e)}`);
|
|
832
|
+
}
|
|
833
|
+
const d = deployment;
|
|
834
|
+
if (!d || typeof d.pods !== "object" || !d.pods || typeof d.runtimes !== "object" || !d.runtimes)
|
|
835
|
+
return failure("invalid-input", `${url}: a deployment has pods and runtimes`);
|
|
836
|
+
const { pods: _p, runtimes: _r, tags: _t, ...host } = d;
|
|
837
|
+
const top = AppDeployment.assemble({ ...host, pods: {}, runtimes: {} }, Registry.create());
|
|
838
|
+
if (!top.ok)
|
|
839
|
+
return failure("invalid-input", `${url}: ${top.fail.reason}`);
|
|
840
|
+
const loadedModules = await Registry.load(deployment.modules ?? {}, url);
|
|
841
|
+
if (!loadedModules.ok)
|
|
842
|
+
return loadedModules;
|
|
843
|
+
const { registry } = loadedModules.value;
|
|
844
|
+
return success({ deployment, registry });
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
// packages/nano/src/application/compose.ts
|
|
848
|
+
function compose(runtimes, policies = {}) {
|
|
849
|
+
try {
|
|
850
|
+
const why2 = shapeError(RuntimeIds, runtimes, "runtimes");
|
|
851
|
+
if (why2)
|
|
852
|
+
return failure("invalid-input", why2);
|
|
853
|
+
const out = Object.create(null), placed = new Map;
|
|
854
|
+
const tags = Object.create(null);
|
|
855
|
+
let root;
|
|
856
|
+
for (const [id, r] of Object.entries(runtimes)) {
|
|
857
|
+
if (!isRuntime(r))
|
|
858
|
+
return failure("invalid-input", `runtime ${id}: not made by Runtime.create`);
|
|
859
|
+
if (r.id !== id)
|
|
860
|
+
return failure("invalid-input", `runtime ${id}: its id is ${r.id}`);
|
|
861
|
+
const origin = originOf(r.pods);
|
|
862
|
+
if ((root ??= origin.root) !== origin.root)
|
|
863
|
+
return failure("invalid-input", `runtime ${id}: its pods come from another Pods`);
|
|
864
|
+
out[id] = r.deployment();
|
|
865
|
+
if (out[id].policy && Object.hasOwn(policies, id))
|
|
866
|
+
return failure("invalid-input", `runtime ${id}: has a policy in code and in its deployment`);
|
|
867
|
+
for (const n of out[id].pods)
|
|
868
|
+
if (origin.tags && Object.hasOwn(origin.tags, n))
|
|
869
|
+
tags[n] = structuredClone(origin.tags[n]);
|
|
870
|
+
for (const name of out[id].pods)
|
|
871
|
+
placed.set(name, origin.pods.get(name));
|
|
872
|
+
}
|
|
873
|
+
for (const [id, r] of Object.entries(out))
|
|
874
|
+
for (const s of r.subscriptions)
|
|
875
|
+
if (!placed.has(s.from))
|
|
876
|
+
return failure("invalid-input", `runtime ${id}: ${s.from}->${s.to}: ${s.from} is placed in no runtime`);
|
|
877
|
+
const pods = Object.create(null);
|
|
878
|
+
for (const name of root?.names() ?? [])
|
|
879
|
+
if (placed.has(name))
|
|
880
|
+
pods[name] = structuredClone(placed.get(name));
|
|
881
|
+
const from = root && originOf(root);
|
|
882
|
+
return success({ deployment: { pods, runtimes: out, ...from?.tags && { tags } }, registry: from?.registry });
|
|
883
|
+
} catch (e) {
|
|
884
|
+
return failure("invalid-input", `unreadable runtimes: ${e instanceof Error ? e.message : String(e)}`);
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
// packages/nano/src/application/lookup.ts
|
|
889
|
+
var cache = new WeakMap;
|
|
890
|
+
var push = (m, k, v) => {
|
|
891
|
+
const l = m.get(k);
|
|
892
|
+
if (l)
|
|
893
|
+
l.push(v);
|
|
894
|
+
else
|
|
895
|
+
m.set(k, [v]);
|
|
896
|
+
};
|
|
897
|
+
function lookup(d) {
|
|
898
|
+
const hit = cache.get(d);
|
|
899
|
+
if (hit)
|
|
900
|
+
return hit;
|
|
901
|
+
const placed = new Map, placedIn = new Map, callsFrom = new Map;
|
|
902
|
+
const calls = new Set, pipes = new Map, policies = new Map;
|
|
903
|
+
for (const [id, r] of Object.entries(d.runtimes)) {
|
|
904
|
+
placed.set(id, new Set(r.pods));
|
|
905
|
+
for (const p of r.pods)
|
|
906
|
+
push(placedIn, p, id);
|
|
907
|
+
for (const s of r.subscriptions) {
|
|
908
|
+
if (s.kind === "call") {
|
|
909
|
+
calls.add(`${id} ${s.from} ${s.to}`);
|
|
910
|
+
push(callsFrom, s.from, { runtime: id, to: s.to });
|
|
911
|
+
} else
|
|
912
|
+
push(pipes, `${s.from} ${s.source}`, { runtime: id, to: s.to, target: s.target });
|
|
92
913
|
}
|
|
93
|
-
|
|
914
|
+
policies.set(id, r.policy?.kind === "rules" ? PolicyRules(r.policy.rules) : Policies.allowAll());
|
|
915
|
+
}
|
|
916
|
+
const made2 = { placed, placedIn, callsFrom, calls, pipes, policy: (id) => policies.get(id) ?? Policies.allowAll() };
|
|
917
|
+
cache.set(d, made2);
|
|
918
|
+
return made2;
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
// packages/nano/src/application/messages.ts
|
|
922
|
+
var msg = (e) => e instanceof Error ? e.message : String(e);
|
|
923
|
+
var TIMEOUT = Symbol("timeout");
|
|
924
|
+
async function within(work, ms, what) {
|
|
925
|
+
let timer;
|
|
926
|
+
const late = new Promise((_, reject) => {
|
|
927
|
+
timer = setTimeout(() => reject(TIMEOUT), ms);
|
|
928
|
+
});
|
|
929
|
+
try {
|
|
930
|
+
return success(await Promise.race([Promise.resolve().then(work), late]));
|
|
931
|
+
} catch (e) {
|
|
932
|
+
return e === TIMEOUT ? failure("timeout", `${what} took over ${ms}ms`) : failure("threw", `${what}: ${msg(e)}`);
|
|
933
|
+
} finally {
|
|
934
|
+
clearTimeout(timer);
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
async function attempt(live, pod2, what, work) {
|
|
938
|
+
const r = await within(work, live.timeoutMs, what);
|
|
939
|
+
if (!r.ok)
|
|
940
|
+
live.trace.emit({ type: "failure", pod: pod2, reason: r.fail.reason });
|
|
941
|
+
return r;
|
|
942
|
+
}
|
|
943
|
+
var impl = (live, pod2) => live.registry.implementation(live.now().pods[pod2]?.implementation ?? "");
|
|
944
|
+
var placedIn = (live, pod2) => {
|
|
945
|
+
const d = live.now();
|
|
946
|
+
return (lookup(d).placedIn.get(pod2) ?? []).map((id) => [id, d.runtimes[id]]);
|
|
947
|
+
};
|
|
948
|
+
var action = (i, p) => {
|
|
949
|
+
const o = i && opAt(i, p);
|
|
950
|
+
return o?.kind === "action" ? o : undefined;
|
|
951
|
+
};
|
|
952
|
+
function refusal(live, ask, d = live.now()) {
|
|
953
|
+
const l = lookup(d);
|
|
954
|
+
const policy = Object.hasOwn(live.policies, ask.runtime) ? live.policies[ask.runtime] : l.policy(ask.runtime);
|
|
955
|
+
try {
|
|
956
|
+
const outside = ask.from === "host" || !l.placed.get(ask.runtime)?.has(ask.from);
|
|
957
|
+
const v = policy.isAllowed({ ...ask, outside });
|
|
958
|
+
if (typeof v?.then === "function") {
|
|
959
|
+
Promise.resolve(v).catch(() => {});
|
|
960
|
+
return "policy gave no verdict";
|
|
961
|
+
}
|
|
962
|
+
if (v?.approved === true)
|
|
963
|
+
return;
|
|
964
|
+
return v?.approved === false && typeof v.reason === "string" ? v.reason : "policy gave no verdict";
|
|
965
|
+
} catch (e) {
|
|
966
|
+
return `policy threw: ${msg(e)}`;
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
async function deliver(live, to, p, input, m) {
|
|
970
|
+
const asked = action(impl(live, to), p);
|
|
971
|
+
if (!asked)
|
|
972
|
+
return failure("unknown-op", `${to} has no action ${p}`);
|
|
973
|
+
if (asked.input && !asked.input.check(input))
|
|
974
|
+
return failure("invalid-input", `${p}: input does not fit ${asked.input.label ?? "its schema"}`);
|
|
975
|
+
const made2 = await live.instance(to);
|
|
976
|
+
if (!made2.ok)
|
|
977
|
+
return made2;
|
|
978
|
+
const o = action(made2.value.implementation, p), h = made2.value.handlers.get(p);
|
|
979
|
+
if (!o || !h)
|
|
980
|
+
return failure("unknown-op", `${to} has no action ${p}`);
|
|
981
|
+
if (o.input && !o.input.check(input))
|
|
982
|
+
return failure("invalid-input", `${p}: input does not fit ${o.input.label ?? "its schema"}`);
|
|
983
|
+
const ran = await attempt(live, to, `${to} ${p}`, () => h(input, contextFor(live, to, made2.value.onClose, { ...m, port: p })));
|
|
984
|
+
if (!ran.ok)
|
|
985
|
+
return ran;
|
|
986
|
+
const r = ran.value;
|
|
987
|
+
if (!isNanoResult(r))
|
|
988
|
+
return failure("invalid-output", `${p}: returned something other than a NanoResult`);
|
|
989
|
+
if (r.ok && o.output && !o.output.check(r.value))
|
|
990
|
+
return failure("invalid-output", `${p}: output does not fit ${o.output.label ?? "its schema"}`);
|
|
991
|
+
return r;
|
|
992
|
+
}
|
|
993
|
+
async function send(live, runtime2, from, to, p, input, how = { kind: "call" }) {
|
|
994
|
+
const { trace } = live, { kind, id = trace.id(), cause, work } = how, correlation = how.correlation ?? id;
|
|
995
|
+
trace.emit({ type: "sent", id, runtime: runtime2, kind, from, to, port: p, correlation, ...cause !== undefined && { cause }, ...input !== undefined && { input } });
|
|
996
|
+
const reason = refusal(live, { runtime: runtime2, kind, from, to, port: p, data: input });
|
|
997
|
+
if (reason !== undefined) {
|
|
998
|
+
trace.emit({ type: "denied", id, reason });
|
|
999
|
+
return failure("denied", reason);
|
|
94
1000
|
}
|
|
1001
|
+
const t0 = performance.now();
|
|
1002
|
+
const r = await (work ? work() : deliver(live, to, p, input, { id, correlation })).catch((e) => failure("invalid-input", `${p}: unreadable input: ${msg(e)}`));
|
|
1003
|
+
trace.emit({ type: "delivered", id, result: r, ms: performance.now() - t0 });
|
|
1004
|
+
return r;
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
// packages/nano/src/application/emit.ts
|
|
1008
|
+
var fly = (live, p) => {
|
|
1009
|
+
const done = () => {
|
|
1010
|
+
live.flying.delete(p);
|
|
1011
|
+
};
|
|
1012
|
+
live.flying.add(p);
|
|
1013
|
+
p.then(done, done);
|
|
1014
|
+
return p;
|
|
95
1015
|
};
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
1016
|
+
async function act(live, runtime2, from, to, p, input, kind, chain = {}) {
|
|
1017
|
+
const id = chain.id ?? live.trace.id(), correlation = chain.correlation ?? id;
|
|
1018
|
+
const r = await send(live, runtime2, from, to, p, input, { ...chain, kind, id, correlation });
|
|
1019
|
+
if (r.ok)
|
|
1020
|
+
emit(live, to, p, { input, output: r.value }, { correlation, cause: id }, runtime2);
|
|
1021
|
+
return r;
|
|
1022
|
+
}
|
|
1023
|
+
function emit(live, from, port3, e, chain, travelled) {
|
|
1024
|
+
if (live.closed())
|
|
1025
|
+
return Promise.resolve();
|
|
1026
|
+
let first;
|
|
1027
|
+
const link = () => chain ?? (first ? { correlation: first } : { id: first = live.trace.id(), correlation: first });
|
|
1028
|
+
const pipes = (lookup(live.now()).pipes.get(`${from} ${port3}`) ?? []).map((s) => fly(live, act(live, s.runtime, from, s.to, s.target, e.output, "pipe", link())));
|
|
1029
|
+
for (const o of [...live.listeners.heard.get(`${from} ${port3}`) ?? []]) {
|
|
1030
|
+
if (o.from !== from || o.port !== port3 || travelled !== undefined && o.runtime !== travelled)
|
|
1031
|
+
continue;
|
|
1032
|
+
const work = async () => {
|
|
1033
|
+
const r = await attempt(live, o.to, `${o.to} hearing ${port3}`, () => o.fn(e));
|
|
1034
|
+
return r.ok ? success(undefined) : r;
|
|
111
1035
|
};
|
|
1036
|
+
fly(live, send(live, o.runtime, from, o.to, port3, e.output, { kind: "on", ...link(), work }));
|
|
1037
|
+
}
|
|
1038
|
+
return Promise.all(pipes);
|
|
1039
|
+
}
|
|
1040
|
+
function client(live, runtime2, from, to, gone, chain) {
|
|
1041
|
+
const call = async (name, input) => {
|
|
1042
|
+
const why2 = gone();
|
|
1043
|
+
if (why2)
|
|
1044
|
+
return why2;
|
|
1045
|
+
const provides = (impl(live, to)?.provides ?? []).filter((i) => Object.values(i.ops).some((o) => o.kind === "action" && o.name === name));
|
|
1046
|
+
const ports2 = provides.map((i) => port2(i, i.ops[name]));
|
|
1047
|
+
if (ports2.length === 0)
|
|
1048
|
+
return failure("unknown-op", `${to} has no action ${name}`);
|
|
1049
|
+
if (ports2.length > 1)
|
|
1050
|
+
return failure("not-unique", `${to}: ${name} is an action of more than one interface`);
|
|
1051
|
+
return act(live, runtime2, from, to, ports2[0], input, "call", chain);
|
|
1052
|
+
};
|
|
1053
|
+
return new Proxy({}, { get: (_, name) => typeof name === "string" && name !== "then" ? (input) => call(name, input) : undefined });
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
// packages/nano/src/application/connection.ts
|
|
1057
|
+
function connect(live, w, ended = () => {}) {
|
|
1058
|
+
const { trace } = live, id = trace.id();
|
|
1059
|
+
const say = (kind, mid) => trace.emit({ type: "sent", id: mid, runtime: w.runtime, kind, from: w.to, to: w.from, port: w.port, correlation: id, ...mid !== id && { cause: id } });
|
|
1060
|
+
say("subscribe", id);
|
|
1061
|
+
const why2 = refusal(live, { runtime: w.runtime, kind: "subscribe", from: w.to, to: w.from, port: w.port });
|
|
1062
|
+
if (why2 !== undefined) {
|
|
1063
|
+
trace.emit({ type: "denied", id, reason: why2 });
|
|
1064
|
+
return failure("denied", why2);
|
|
1065
|
+
}
|
|
1066
|
+
trace.emit({ type: "delivered", id, result: success(undefined), ms: 0 });
|
|
1067
|
+
let open = true;
|
|
1068
|
+
const key = `${w.from} ${w.port}`;
|
|
1069
|
+
const on = { ...w, end(fail) {
|
|
1070
|
+
if (!open)
|
|
1071
|
+
return;
|
|
1072
|
+
open = false;
|
|
1073
|
+
live.listeners.ons.delete(on);
|
|
1074
|
+
const set2 = live.listeners.heard.get(key);
|
|
1075
|
+
if (set2?.delete(on) && set2.size === 0)
|
|
1076
|
+
live.listeners.heard.delete(key);
|
|
1077
|
+
const u = trace.id();
|
|
1078
|
+
say("unsubscribe", u);
|
|
1079
|
+
trace.emit({ type: "delivered", id: u, result: fail ? { ok: false, fail } : success(undefined), ms: 0 });
|
|
1080
|
+
ended(fail);
|
|
1081
|
+
} };
|
|
1082
|
+
live.listeners.ons.add(on);
|
|
1083
|
+
const set = live.listeners.heard.get(key);
|
|
1084
|
+
if (set)
|
|
1085
|
+
set.add(on);
|
|
1086
|
+
else
|
|
1087
|
+
live.listeners.heard.set(key, new Set([on]));
|
|
1088
|
+
return success(on);
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
// packages/nano/src/application/iterate.ts
|
|
1092
|
+
function iterate(listen, ended) {
|
|
1093
|
+
const queue = [];
|
|
1094
|
+
let done = false, failed, wake, used = false;
|
|
1095
|
+
const stop = (fail) => {
|
|
1096
|
+
if (!done)
|
|
1097
|
+
failed = fail;
|
|
1098
|
+
done = true;
|
|
1099
|
+
wake?.();
|
|
1100
|
+
};
|
|
1101
|
+
ended(stop);
|
|
1102
|
+
const off = listen((v) => {
|
|
1103
|
+
queue.push(v);
|
|
1104
|
+
wake?.();
|
|
1105
|
+
});
|
|
1106
|
+
return { [Symbol.asyncIterator]() {
|
|
1107
|
+
if (used)
|
|
1108
|
+
throw new Error("iterable: iterate once; subscribe again for another");
|
|
1109
|
+
used = true;
|
|
112
1110
|
return {
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
const inst = instances.get(i);
|
|
124
|
-
if (!inst)
|
|
125
|
-
return err(`no instance ${i} in ${id}`);
|
|
126
|
-
for (const s of [...subs.values()])
|
|
127
|
-
if (s.listener === i)
|
|
128
|
-
close(s);
|
|
129
|
-
instances.delete(i);
|
|
130
|
-
emit({ type: "instance-removed", instance: i, ops: keys(inst) });
|
|
131
|
-
return ok(undefined);
|
|
132
|
-
},
|
|
133
|
-
subscribe(s) {
|
|
134
|
-
if (!instances.has(s.listener))
|
|
135
|
-
return err(`no listener ${s.listener} in ${id}`);
|
|
136
|
-
const sub = { id: crypto.randomUUID(), ...s };
|
|
137
|
-
subs.set(sub.id, sub);
|
|
138
|
-
bucket(sub.source, sub.op).add(sub);
|
|
139
|
-
seq.set(sub, n++);
|
|
140
|
-
emit({ type: "subscription-opened", subscription: sub });
|
|
141
|
-
return ok(sub);
|
|
1111
|
+
async next() {
|
|
1112
|
+
while (!queue.length && !done)
|
|
1113
|
+
await new Promise((r) => {
|
|
1114
|
+
wake = r;
|
|
1115
|
+
});
|
|
1116
|
+
if (queue.length)
|
|
1117
|
+
return { done: false, value: queue.shift() };
|
|
1118
|
+
if (failed)
|
|
1119
|
+
throw thrown(failed);
|
|
1120
|
+
return { done: true, value: undefined };
|
|
142
1121
|
},
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
close(s);
|
|
148
|
-
return ok(undefined);
|
|
149
|
-
},
|
|
150
|
-
announce(i, type, op) {
|
|
151
|
-
if (!instances.has(i))
|
|
152
|
-
return err(`no instance ${i} in ${id}`);
|
|
153
|
-
emit({ type, instance: i, op: Ops.key(op) });
|
|
154
|
-
return ok(undefined);
|
|
155
|
-
},
|
|
156
|
-
matching: (source, op) => [...index.get(`* ${op}`) ?? [], ...source === "*" ? [] : index.get(`${source} ${op}`) ?? []].sort((a, b) => seq.get(a) - seq.get(b)),
|
|
157
|
-
snapshot: () => ({
|
|
158
|
-
id,
|
|
159
|
-
instances: [...instances].map(([i, inst]) => ({ id: i, ops: [...inst.actions.values()].map((a) => a.op) })),
|
|
160
|
-
subscriptions: [...subs.values()]
|
|
161
|
-
}),
|
|
162
|
-
listen(fn) {
|
|
163
|
-
listeners.add(fn);
|
|
164
|
-
return () => {
|
|
165
|
-
listeners.delete(fn);
|
|
166
|
-
};
|
|
1122
|
+
async return() {
|
|
1123
|
+
off();
|
|
1124
|
+
stop();
|
|
1125
|
+
return { done: true, value: undefined };
|
|
167
1126
|
}
|
|
168
1127
|
};
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
var RegistryOps = {
|
|
177
|
-
add: Ops.action("composable", "add", Type.Object({ id: Type.String(), instance: any }), any),
|
|
178
|
-
remove: Ops.action("composable", "remove", Type.String(), any),
|
|
179
|
-
subscribe: Ops.action("composable", "subscribe", Type.Object({ source: Type.String(), op: Type.String(), listener: Type.String(), target: Type.String() }), any),
|
|
180
|
-
unsubscribe: Ops.action("composable", "unsubscribe", Type.String(), any),
|
|
181
|
-
snapshot: Ops.action("composable", "snapshot", Type.Null(), any),
|
|
182
|
-
deltas: Object.fromEntries(deltas.map((d) => [d, Ops.source("composable", d, any)]))
|
|
1128
|
+
} };
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
// packages/nano/src/application/context.ts
|
|
1132
|
+
var portOf = (live, pod2, o) => {
|
|
1133
|
+
const i = impl(live, pod2)?.provides.find((i2) => i2.byCoord.has(o?.coord));
|
|
1134
|
+
return i && port2(i, o);
|
|
183
1135
|
};
|
|
184
|
-
var
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
1136
|
+
var dataOf = (s) => typeof s === "object" && s ? selectorData(s) : undefined;
|
|
1137
|
+
var fitsData = (o, data) => {
|
|
1138
|
+
try {
|
|
1139
|
+
return !o.output || o.output.check(data);
|
|
1140
|
+
} catch {
|
|
1141
|
+
return false;
|
|
1142
|
+
}
|
|
188
1143
|
};
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
1144
|
+
var builds = new WeakMap;
|
|
1145
|
+
function buildOf(live, onClose) {
|
|
1146
|
+
const known = builds.get(onClose);
|
|
1147
|
+
if (known)
|
|
1148
|
+
return known;
|
|
1149
|
+
const b = { mine: new Set, heard: new Set };
|
|
1150
|
+
builds.set(onClose, b);
|
|
1151
|
+
onClose(() => {
|
|
1152
|
+
for (const o of [...b.mine])
|
|
1153
|
+
o.end();
|
|
1154
|
+
b.mine = undefined;
|
|
1155
|
+
for (const h of b.heard)
|
|
1156
|
+
live.listeners.podChanges.delete(h);
|
|
1157
|
+
});
|
|
1158
|
+
return b;
|
|
1159
|
+
}
|
|
1160
|
+
function contextFor(live, name, onClose, invoked) {
|
|
1161
|
+
const b = buildOf(live, onClose), chain = invoked && { correlation: invoked.correlation, cause: invoked.id };
|
|
1162
|
+
const selection = (runtime2, to) => {
|
|
1163
|
+
const gone = () => lookup(live.now()).calls.has(`${runtime2} ${name} ${to}`) ? undefined : failure("not-found", `${name}->${to} is no longer in ${runtime2}`);
|
|
1164
|
+
return { pod: to, runtime: runtime2, call: client(live, runtime2, name, to, gone, chain), on(o, fn) {
|
|
1165
|
+
let stop;
|
|
1166
|
+
const connect2 = (fn2) => {
|
|
1167
|
+
const p = portOf(live, to, o);
|
|
1168
|
+
if (!p)
|
|
1169
|
+
throw thrown({ type: "unknown-op", reason: `${name}: ${o?.name} is not an op of ${to}` });
|
|
1170
|
+
const why2 = !b.mine ? failure("not-found", `${name}: this build is closed`) : gone();
|
|
1171
|
+
if (why2 && !why2.ok)
|
|
1172
|
+
throw thrown(why2.fail);
|
|
1173
|
+
const c = connect(live, { runtime: runtime2, from: to, port: p, to: name, gone, fn: fn2 }, (f) => stop?.(f));
|
|
1174
|
+
if (!c.ok)
|
|
1175
|
+
throw thrown(c.fail);
|
|
1176
|
+
const sub = c.value;
|
|
1177
|
+
b.mine.add(sub);
|
|
1178
|
+
return () => {
|
|
1179
|
+
b.mine?.delete(sub);
|
|
1180
|
+
sub.end();
|
|
1181
|
+
};
|
|
1182
|
+
};
|
|
1183
|
+
return fn ? connect2(fn) : iterate(connect2, (s) => {
|
|
1184
|
+
stop = s;
|
|
1185
|
+
});
|
|
1186
|
+
} };
|
|
1187
|
+
};
|
|
1188
|
+
const selections = (s) => {
|
|
1189
|
+
const want = dataOf(s), d = live.now();
|
|
1190
|
+
if (!want)
|
|
1191
|
+
return [];
|
|
1192
|
+
return (lookup(d).callsFrom.get(name) ?? []).flatMap(({ runtime: runtime2, to }) => {
|
|
1193
|
+
const sub = { to };
|
|
1194
|
+
const i = impl(live, sub.to);
|
|
1195
|
+
const target = {
|
|
1196
|
+
name: sub.to,
|
|
1197
|
+
runtime: runtime2,
|
|
1198
|
+
implementation: i.coord,
|
|
1199
|
+
provider: i.provider,
|
|
1200
|
+
provides: new Set(i.provides.map((i2) => i2.coord)),
|
|
1201
|
+
tags: new Set(d.tags?.[sub.to] ?? [])
|
|
1202
|
+
};
|
|
1203
|
+
return matches(want, target) ? [selection(runtime2, sub.to)] : [];
|
|
1204
|
+
});
|
|
1205
|
+
};
|
|
1206
|
+
const ctx = {
|
|
1207
|
+
self: name,
|
|
1208
|
+
...invoked && { callingOp: invoked.port },
|
|
1209
|
+
get runtimes() {
|
|
1210
|
+
return placedIn(live, name).map(([id]) => id);
|
|
1211
|
+
},
|
|
1212
|
+
one(s) {
|
|
1213
|
+
const all = selections(s), what = JSON.stringify(dataOf(s));
|
|
1214
|
+
if (all.length === 0)
|
|
1215
|
+
return failure("not-found", `${name}: nothing wired matches ${what}`);
|
|
1216
|
+
if (all.length > 1)
|
|
1217
|
+
return failure("not-unique", `${name}: ${all.length} wired match ${what}`);
|
|
1218
|
+
return success(all[0]);
|
|
1219
|
+
},
|
|
1220
|
+
all: selections,
|
|
1221
|
+
async publish(o, data) {
|
|
1222
|
+
const p = portOf(live, name, o);
|
|
1223
|
+
if (!p || o.kind !== "event")
|
|
1224
|
+
return live.trace.emit({ type: "warning", reason: `${name}: ${o?.name} is not one of its events` });
|
|
1225
|
+
if (!fitsData(o, data))
|
|
1226
|
+
return live.trace.emit({ type: "failure", pod: name, reason: `${name}: ${o.name} data does not fit ${o.output?.label ?? "its schema"}` });
|
|
1227
|
+
await emit(live, name, p, { output: data }, chain);
|
|
1228
|
+
},
|
|
1229
|
+
addOnPodChangeListener(fn) {
|
|
1230
|
+
if (!b.mine)
|
|
1231
|
+
return;
|
|
1232
|
+
const h = { pod: name, fn };
|
|
1233
|
+
b.heard.add(h);
|
|
1234
|
+
live.listeners.podChanges.add(h);
|
|
1235
|
+
},
|
|
1236
|
+
addOnCloseListener: onClose
|
|
1237
|
+
};
|
|
1238
|
+
return ctx;
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
// packages/nano/src/application/sources.ts
|
|
1242
|
+
function start(live, pod2, ctx, sources, onClose) {
|
|
1243
|
+
for (const { op, run } of sources.values()) {
|
|
1244
|
+
const it = run()[Symbol.asyncIterator]();
|
|
1245
|
+
onClose(() => {
|
|
1246
|
+
it.return?.();
|
|
1247
|
+
});
|
|
1248
|
+
(async () => {
|
|
1249
|
+
try {
|
|
1250
|
+
for (let r = await it.next();!r.done; r = await it.next())
|
|
1251
|
+
await ctx.publish(op, r.value);
|
|
1252
|
+
} catch (e) {
|
|
1253
|
+
live.trace.emit({ type: "failure", pod: pod2, reason: `${op.name} threw ${e instanceof Error ? e.message : String(e)}` });
|
|
1254
|
+
}
|
|
1255
|
+
})();
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
// packages/nano/src/application/instances.ts
|
|
1260
|
+
function closer(live, pod2) {
|
|
1261
|
+
const listeners = [];
|
|
1262
|
+
let reason, closing;
|
|
1263
|
+
const run = (fn) => attempt(live, pod2, `closing ${pod2}`, () => fn({ reason }));
|
|
1264
|
+
return {
|
|
1265
|
+
add(fn) {
|
|
1266
|
+
if (reason)
|
|
1267
|
+
run(fn);
|
|
1268
|
+
else
|
|
1269
|
+
listeners.push(fn);
|
|
1270
|
+
},
|
|
1271
|
+
began: () => reason !== undefined,
|
|
1272
|
+
close: (why2) => closing ??= (async () => {
|
|
1273
|
+
reason = why2;
|
|
1274
|
+
for (const fn of listeners)
|
|
1275
|
+
await run(fn);
|
|
1276
|
+
live.trace.emit({ type: "closed", pod: pod2, reason: why2 });
|
|
1277
|
+
})()
|
|
1278
|
+
};
|
|
1279
|
+
}
|
|
1280
|
+
async function implementationOf(live, name, pod2) {
|
|
1281
|
+
if ((pod2.isolation ?? "host") === "host") {
|
|
1282
|
+
const i = live.registry.implementation(pod2.implementation);
|
|
1283
|
+
return i && success(i);
|
|
1284
|
+
}
|
|
1285
|
+
const { isolate } = live;
|
|
1286
|
+
if (!isolate)
|
|
1287
|
+
return failure("invalid-input", `no host for isolation ${pod2.isolation}`);
|
|
1288
|
+
const r = await within(() => isolate(name, structuredClone(pod2)), live.timeoutMs, `isolating ${name}`);
|
|
1289
|
+
if (!r.ok || r.value.coord === pod2.implementation)
|
|
1290
|
+
return r;
|
|
1291
|
+
return failure("invalid-input", `isolate gave ${r.value.coord} for ${pod2.implementation}`);
|
|
1292
|
+
}
|
|
1293
|
+
function instances(live) {
|
|
1294
|
+
const made2 = new Map;
|
|
1295
|
+
const closing = new Map;
|
|
1296
|
+
const outcome = new Map;
|
|
1297
|
+
let closed = false;
|
|
1298
|
+
async function build(name, c) {
|
|
1299
|
+
await closing.get(name);
|
|
1300
|
+
if (c.began())
|
|
1301
|
+
return failure("not-found", `${name} was closed before it was built`);
|
|
1302
|
+
const pod2 = live.now().pods[name];
|
|
1303
|
+
const found = pod2 && await implementationOf(live, name, pod2);
|
|
1304
|
+
if (!pod2 || !found)
|
|
1305
|
+
return failure("not-found", `no pod ${name}`);
|
|
1306
|
+
if (!found.ok) {
|
|
1307
|
+
live.trace.emit({ type: "failure", pod: name, reason: found.fail.reason });
|
|
1308
|
+
await c.close("closed");
|
|
1309
|
+
return found;
|
|
1310
|
+
}
|
|
1311
|
+
const impl2 = found.value;
|
|
1312
|
+
const ctx = contextFor(live, name, c.add);
|
|
1313
|
+
const r = await within(() => impl2.make(ctx, pod2.config), live.timeoutMs, `building ${name}`);
|
|
1314
|
+
if (closed)
|
|
1315
|
+
return failure("not-found", "application is closed");
|
|
1316
|
+
live.trace.emit(r.ok ? { type: "built", pod: name } : { type: "failure", pod: name, reason: r.fail.reason });
|
|
1317
|
+
if (!r.ok)
|
|
1318
|
+
await c.close("closed");
|
|
1319
|
+
if (!r.ok)
|
|
1320
|
+
return r;
|
|
1321
|
+
start(live, name, ctx, r.value.sources, c.add);
|
|
1322
|
+
return success({ implementation: impl2, handlers: r.value.handlers, onClose: c.add });
|
|
1323
|
+
}
|
|
1324
|
+
async function forget(name, why2) {
|
|
1325
|
+
const e = made2.get(name);
|
|
1326
|
+
outcome.delete(name);
|
|
1327
|
+
if (!e)
|
|
1328
|
+
return;
|
|
1329
|
+
made2.delete(name);
|
|
1330
|
+
const p = Promise.all([closing.get(name), e.close(why2)]).then(() => {});
|
|
1331
|
+
closing.set(name, p);
|
|
1332
|
+
await p;
|
|
1333
|
+
if (closing.get(name) === p)
|
|
1334
|
+
closing.delete(name);
|
|
1335
|
+
}
|
|
1336
|
+
return {
|
|
1337
|
+
get(name) {
|
|
1338
|
+
if (closed)
|
|
1339
|
+
return Promise.resolve(failure("not-found", "application is closed"));
|
|
1340
|
+
let e = made2.get(name);
|
|
1341
|
+
if (!e) {
|
|
1342
|
+
const c = closer(live, name), mine = { build: build(name, c), close: c.close };
|
|
1343
|
+
made2.set(name, e = mine);
|
|
1344
|
+
mine.build.then((r) => {
|
|
1345
|
+
if (made2.get(name) !== mine)
|
|
1346
|
+
return;
|
|
1347
|
+
outcome.set(name, r.ok ? "running" : "failed");
|
|
1348
|
+
if (!r.ok)
|
|
1349
|
+
made2.delete(name);
|
|
1350
|
+
});
|
|
1351
|
+
}
|
|
1352
|
+
return e.build;
|
|
1353
|
+
},
|
|
1354
|
+
forget,
|
|
1355
|
+
status: (name) => closed ? "stopped" : outcome.get(name) ?? "not started",
|
|
1356
|
+
async close() {
|
|
1357
|
+
closed = true;
|
|
1358
|
+
const builds2 = [...made2.values()].map((e) => e.build);
|
|
1359
|
+
await Promise.all([...[...made2.keys()].map((n) => forget(n, "closed")), ...builds2]);
|
|
1360
|
+
}
|
|
1361
|
+
};
|
|
1362
|
+
}
|
|
1363
|
+
|
|
1364
|
+
// packages/nano/src/application/pod-changes.ts
|
|
1365
|
+
async function notifyPodChanges(live, before) {
|
|
1366
|
+
const after = live.now(), told = new Set;
|
|
1367
|
+
for (const id of new Set([...Object.keys(before.runtimes), ...Object.keys(after.runtimes)])) {
|
|
1368
|
+
const was = before.runtimes[id]?.pods ?? [], is = after.runtimes[id]?.pods ?? [];
|
|
1369
|
+
const changes = [
|
|
1370
|
+
...is.filter((p) => !was.includes(p)).map((p) => ({ type: "added", p, d: after })),
|
|
1371
|
+
...was.filter((p) => !is.includes(p)).map((p) => ({ type: "removed", p, d: before }))
|
|
1372
|
+
];
|
|
1373
|
+
for (const l of [...live.listeners.podChanges]) {
|
|
1374
|
+
if (!is.includes(l.pod))
|
|
1375
|
+
continue;
|
|
1376
|
+
for (const c of changes) {
|
|
1377
|
+
if (c.p === l.pod)
|
|
1378
|
+
continue;
|
|
1379
|
+
const why2 = refusal(live, { runtime: id, kind: "lifecycle", from: l.pod, to: c.p });
|
|
1380
|
+
if (why2 !== undefined) {
|
|
1381
|
+
if (!told.has(l)) {
|
|
1382
|
+
told.add(l);
|
|
1383
|
+
live.trace.emit({ type: "denied", id: live.trace.id(), reason: why2 });
|
|
1384
|
+
}
|
|
1385
|
+
continue;
|
|
1386
|
+
}
|
|
1387
|
+
const implementation = live.registry.implementation(c.d.pods[c.p]?.implementation ?? "")?.coord ?? "";
|
|
1388
|
+
const p = attempt(live, l.pod, `${l.pod} hearing ${c.type} ${c.p}`, () => l.fn({ type: c.type, runtime: id, pod: c.p, implementation }));
|
|
1389
|
+
const done = () => {
|
|
1390
|
+
live.flying.delete(p);
|
|
1391
|
+
};
|
|
1392
|
+
live.flying.add(p);
|
|
1393
|
+
p.then(done, done);
|
|
1394
|
+
}
|
|
210
1395
|
}
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
|
|
1399
|
+
// packages/nano/src/application/listen.ts
|
|
1400
|
+
function listen(live, runtime2, fn) {
|
|
1401
|
+
const mine = new Set;
|
|
1402
|
+
const seen = new Set;
|
|
1403
|
+
const refresh = () => {
|
|
1404
|
+
for (const p of live.now().runtimes[runtime2]?.pods ?? [])
|
|
1405
|
+
seen.add(p);
|
|
1406
|
+
};
|
|
1407
|
+
refresh();
|
|
1408
|
+
return live.trace.listen((e) => {
|
|
1409
|
+
refresh();
|
|
1410
|
+
if (e.type === "sent") {
|
|
1411
|
+
if (e.runtime === runtime2) {
|
|
1412
|
+
mine.add(e.id);
|
|
1413
|
+
fn(e);
|
|
1414
|
+
}
|
|
1415
|
+
} else if (e.type === "delivered" || e.type === "denied") {
|
|
1416
|
+
if (mine.delete(e.id))
|
|
1417
|
+
fn(e);
|
|
1418
|
+
} else if (e.type === "applied") {
|
|
1419
|
+
const keep = (l) => l.filter((p) => seen.has(p));
|
|
1420
|
+
const n = { added: keep(e.added), removed: keep(e.removed), changed: keep(e.changed), rewired: keep(e.rewired) };
|
|
1421
|
+
if (Object.values(n).some((l) => l.length))
|
|
1422
|
+
fn({ type: "applied", caller: e.caller, ...n });
|
|
1423
|
+
const here = live.now().runtimes[runtime2]?.pods ?? [];
|
|
1424
|
+
for (const p of seen)
|
|
1425
|
+
if (!here.includes(p))
|
|
1426
|
+
seen.delete(p);
|
|
1427
|
+
} else if (e.type !== "warning" && e.pod !== undefined && seen.has(e.pod))
|
|
1428
|
+
fn(e);
|
|
211
1429
|
});
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
// packages/nano/src/application/start.ts
|
|
1433
|
+
var pending = new WeakMap;
|
|
1434
|
+
function starter(live, at, status, call) {
|
|
1435
|
+
const under = pending.get(live) ?? new Map;
|
|
1436
|
+
pending.set(live, under);
|
|
1437
|
+
async function send2(runtime2, pod2) {
|
|
1438
|
+
const id = live.trace.id();
|
|
1439
|
+
live.trace.emit({ type: "sent", id, runtime: runtime2, kind: "start", from: "host", to: pod2, correlation: id });
|
|
1440
|
+
const reason = refusal(live, { runtime: runtime2, kind: "start", from: "host", to: pod2 });
|
|
1441
|
+
if (reason !== undefined) {
|
|
1442
|
+
live.trace.emit({ type: "denied", id, reason });
|
|
1443
|
+
return failure("denied", reason);
|
|
1444
|
+
}
|
|
1445
|
+
const t0 = performance.now();
|
|
1446
|
+
const made2 = await live.instance(pod2);
|
|
1447
|
+
const r = made2.ok ? success(undefined) : made2;
|
|
1448
|
+
live.trace.emit({ type: "delivered", id, result: r, ms: performance.now() - t0 });
|
|
1449
|
+
return r;
|
|
1450
|
+
}
|
|
1451
|
+
async function begin(pod2) {
|
|
1452
|
+
const r = at();
|
|
1453
|
+
if (!r.ok)
|
|
1454
|
+
return r;
|
|
1455
|
+
if (live.closed())
|
|
1456
|
+
return failure("not-found", "application is closed");
|
|
1457
|
+
if (!lookup(live.now()).placed.get(r.value)?.has(pod2))
|
|
1458
|
+
return failure("not-found", `${pod2} is not placed in ${r.value}`);
|
|
1459
|
+
const key = `${r.value}|${pod2}`, other = under.get(key);
|
|
1460
|
+
if (other) {
|
|
1461
|
+
const o = await other;
|
|
1462
|
+
return o.ok ? success({ started: false }) : o;
|
|
1463
|
+
}
|
|
1464
|
+
if (status(pod2) === "running")
|
|
1465
|
+
return success({ started: false });
|
|
1466
|
+
const mine = send2(r.value, pod2);
|
|
1467
|
+
under.set(key, mine);
|
|
1468
|
+
try {
|
|
1469
|
+
const m = await mine;
|
|
1470
|
+
return m.ok ? success({ started: true }) : m;
|
|
1471
|
+
} finally {
|
|
1472
|
+
if (under.get(key) === mine)
|
|
1473
|
+
under.delete(key);
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
return {
|
|
1477
|
+
async start(pod2) {
|
|
1478
|
+
const r = await begin(pod2);
|
|
1479
|
+
return !r.ok ? r : r.value.started ? success(undefined) : failure("invalid-input", `${pod2} is already running`);
|
|
1480
|
+
},
|
|
1481
|
+
async getOrCreate(pod2) {
|
|
1482
|
+
const r = await begin(pod2);
|
|
1483
|
+
return r.ok ? success({ started: r.value.started, pod: call(pod2) }) : r;
|
|
1484
|
+
}
|
|
219
1485
|
};
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1488
|
+
// packages/nano/src/application/resolve.ts
|
|
1489
|
+
var miss = (type, reason) => ({ ok: false, fail: { type, reason } });
|
|
1490
|
+
function placement(live, runtime2, api, where) {
|
|
1491
|
+
const found = [];
|
|
1492
|
+
const named = where.pod !== undefined && lookup(live.now()).placed.get(runtime2)?.has(where.pod) ? [where.pod] : undefined;
|
|
1493
|
+
for (const pod2 of named ?? (where.pod !== undefined ? [] : live.now().runtimes[runtime2]?.pods ?? [])) {
|
|
1494
|
+
const i = impl(live, pod2);
|
|
1495
|
+
if ((where.pod ?? pod2) === pod2 && i?.provides.some((x) => x.coord === api.coord))
|
|
1496
|
+
found.push({ pod: pod2, runtime: runtime2, implementation: i.coord });
|
|
1497
|
+
}
|
|
1498
|
+
const what = `${api.coord} in ${runtime2}${where.pod ? ` at ${where.pod}` : ""}`;
|
|
1499
|
+
if (!found.length)
|
|
1500
|
+
return miss("not-found", `no pod provides ${what}`);
|
|
1501
|
+
return found.length === 1 ? { ok: true, value: found[0] } : miss("not-unique", `${found.length} pods provide ${what}`);
|
|
1502
|
+
}
|
|
1503
|
+
var throws = (fail) => () => {
|
|
1504
|
+
throw thrown(fail);
|
|
1505
|
+
};
|
|
1506
|
+
function runtimeView(live, status, id) {
|
|
1507
|
+
const at = () => id === undefined ? only(live) : named(live, id);
|
|
1508
|
+
const call = (pod2) => {
|
|
1509
|
+
const r = at(), id2 = r.ok ? r.value : "";
|
|
1510
|
+
return client(live, id2, "host", pod2, () => {
|
|
1511
|
+
const now = at();
|
|
1512
|
+
return !now.ok ? now : now.value !== id2 ? failure("not-found", `runtime ${now.value} is not the one this client was made for`) : live.closed() ? failure("not-found", "application is closed") : lookup(live.now()).placed.get(id2)?.has(pod2) ? undefined : failure("not-found", `${pod2} is not placed in ${id2}`);
|
|
1513
|
+
});
|
|
1514
|
+
};
|
|
1515
|
+
const found = (api, where) => {
|
|
1516
|
+
const r = at();
|
|
1517
|
+
if (!r.ok)
|
|
1518
|
+
return r;
|
|
1519
|
+
const p = placement(live, r.value, api, where);
|
|
1520
|
+
if (!p.ok)
|
|
1521
|
+
return p;
|
|
1522
|
+
const reachable = Object.values(api.ops).some((o) => refusal(live, { runtime: r.value, kind: o.kind === "event" ? "subscribe" : "call", from: "host", to: p.value.pod, port: port2(api, o) }) === undefined);
|
|
1523
|
+
return reachable ? p : miss("denied", `${r.value}'s policy lets the host reach no op of ${api.coord}`);
|
|
1524
|
+
};
|
|
1525
|
+
const resolve = (api, where = {}) => {
|
|
1526
|
+
const now = found(api, where);
|
|
1527
|
+
if (!now.ok)
|
|
1528
|
+
return { ok: false, reason: now.fail.type, fail: now.fail, getOrThrow: throws(now.fail) };
|
|
1529
|
+
const value2 = plain(api, () => {
|
|
1530
|
+
const p = found(api, where);
|
|
1531
|
+
return p.ok ? success({ call: call(p.value.pod), on: (op) => hear(op, undefined, { pod: p.value.pod }) }) : p;
|
|
1532
|
+
});
|
|
1533
|
+
return { ok: true, ...now.value, value: value2, getOrThrow: () => value2 };
|
|
1534
|
+
};
|
|
1535
|
+
const hear = (op, fn, where) => {
|
|
1536
|
+
let stop;
|
|
1537
|
+
const connect2 = (fn2) => {
|
|
1538
|
+
const r = at();
|
|
1539
|
+
if (!r.ok)
|
|
1540
|
+
return throws(r.fail)();
|
|
1541
|
+
const runtime2 = r.value;
|
|
1542
|
+
const api = (live.now().runtimes[runtime2]?.pods ?? []).flatMap((p2) => impl(live, p2)?.provides ?? []).find((i) => i.byCoord.has(op.coord));
|
|
1543
|
+
if (!api)
|
|
1544
|
+
return throws(miss("not-found", `no pod provides ${op.coord} in ${runtime2}`).fail)();
|
|
1545
|
+
const p = placement(live, runtime2, api, where);
|
|
1546
|
+
if (!p.ok)
|
|
1547
|
+
return throws(p.fail)();
|
|
1548
|
+
const from = p.value.pod;
|
|
1549
|
+
const gone = () => !lookup(live.now()).placed.get(runtime2)?.has(from);
|
|
1550
|
+
const c = connect(live, { runtime: runtime2, from, port: port2(api, op), to: "host", gone, fn: fn2 }, (f) => stop?.(f));
|
|
1551
|
+
if (!c.ok)
|
|
1552
|
+
throw thrown(c.fail);
|
|
1553
|
+
return () => c.value.end();
|
|
1554
|
+
};
|
|
1555
|
+
return fn ? connect2(fn) : iterate(connect2, (s) => {
|
|
1556
|
+
stop = s;
|
|
1557
|
+
});
|
|
1558
|
+
};
|
|
1559
|
+
const subscribe = (op, fn) => hear(op, fn, {});
|
|
1560
|
+
const watch = (fn) => {
|
|
1561
|
+
const r = at();
|
|
1562
|
+
return r.ok ? listen(live, r.value, fn) : throws(r.fail)();
|
|
1563
|
+
};
|
|
1564
|
+
const statusOf = (pod2) => {
|
|
1565
|
+
const r = at();
|
|
1566
|
+
return !r.ok ? r : lookup(live.now()).placed.get(r.value)?.has(pod2) ? success(status(pod2)) : failure("not-found", `${pod2} is not placed in ${r.value}`);
|
|
1567
|
+
};
|
|
1568
|
+
return { resolve, get: (api, where) => resolve(api, where).getOrThrow(), call, subscribe, listen: watch, status: statusOf, ...starter(live, at, status, call) };
|
|
1569
|
+
}
|
|
1570
|
+
var named = (live, id) => Object.hasOwn(live.now().runtimes, id) ? { ok: true, value: id } : miss("not-found", `no runtime ${id}`);
|
|
1571
|
+
var only = (live) => {
|
|
1572
|
+
const ids = Object.keys(live.now().runtimes);
|
|
1573
|
+
return ids.length === 1 ? { ok: true, value: ids[0] } : miss(ids.length ? "not-unique" : "not-found", `${ids.length} runtimes: name a runtime`);
|
|
1574
|
+
};
|
|
1575
|
+
|
|
1576
|
+
// packages/nano/src/application/stream.ts
|
|
1577
|
+
function stream() {
|
|
1578
|
+
const listeners = new Set;
|
|
1579
|
+
let n = 0;
|
|
1580
|
+
return {
|
|
1581
|
+
emit(e) {
|
|
1582
|
+
for (const fn of [...listeners])
|
|
1583
|
+
try {
|
|
1584
|
+
fn(e);
|
|
1585
|
+
} catch {}
|
|
226
1586
|
},
|
|
227
1587
|
listen(fn) {
|
|
228
1588
|
listeners.add(fn);
|
|
@@ -230,60 +1590,144 @@ function create(registry, policy) {
|
|
|
230
1590
|
listeners.delete(fn);
|
|
231
1591
|
};
|
|
232
1592
|
},
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
1593
|
+
id: () => `m${++n}`
|
|
1594
|
+
};
|
|
1595
|
+
}
|
|
1596
|
+
|
|
1597
|
+
// packages/nano/src/application/index.ts
|
|
1598
|
+
async function create4(runtimes, opts = {}) {
|
|
1599
|
+
const composed = compose(runtimes, opts.policies);
|
|
1600
|
+
if (!composed.ok)
|
|
1601
|
+
return composed;
|
|
1602
|
+
const registry = composed.value.registry ?? Registry.create();
|
|
1603
|
+
let current = composed.value.deployment, queue = Promise.resolve();
|
|
1604
|
+
let closing;
|
|
1605
|
+
const trace = stream();
|
|
1606
|
+
const live = {
|
|
1607
|
+
now: () => current,
|
|
1608
|
+
registry,
|
|
1609
|
+
policies: opts.policies ?? {},
|
|
1610
|
+
timeoutMs: opts.timeoutMs ?? 30000,
|
|
1611
|
+
trace,
|
|
1612
|
+
instance: (name) => pods.get(name),
|
|
1613
|
+
listeners: { ons: new Set, heard: new Map, podChanges: new Set },
|
|
1614
|
+
flying: new Set,
|
|
1615
|
+
closed: () => closing !== undefined,
|
|
1616
|
+
isolate: opts.isolate
|
|
1617
|
+
};
|
|
1618
|
+
const pods = instances(live);
|
|
1619
|
+
const buildEager = (names) => Promise.all(names.filter((n) => current.pods[n].eager).map((n) => pods.get(n)));
|
|
1620
|
+
await buildEager(Object.keys(current.pods));
|
|
1621
|
+
function adopt(d) {
|
|
1622
|
+
const assembled = AppDeployment.assemble(d, registry);
|
|
1623
|
+
if (!assembled.ok)
|
|
1624
|
+
return assembled;
|
|
1625
|
+
const next = compose(assembled.value, live.policies);
|
|
1626
|
+
return next.ok ? success(next.value.deployment) : next;
|
|
1627
|
+
}
|
|
1628
|
+
const shut = () => failure("invalid-input", "application is closed");
|
|
1629
|
+
function queued(work) {
|
|
1630
|
+
const done = queue.then(work);
|
|
1631
|
+
queue = done.catch(() => {
|
|
1632
|
+
return;
|
|
1633
|
+
});
|
|
1634
|
+
return done;
|
|
1635
|
+
}
|
|
1636
|
+
async function reconcile(d, caller) {
|
|
1637
|
+
const checked = adopt(d);
|
|
1638
|
+
if (!checked.ok)
|
|
1639
|
+
return checked;
|
|
1640
|
+
const verdict = await Promise.resolve().then(() => (opts.deploymentPolicy ?? DeploymentPolicies.allowAll()).isAllowed({ caller, deployment: d })).catch((e) => ({ approved: false, reason: `policy threw: ${e instanceof Error ? e.message : String(e)}` }));
|
|
1641
|
+
if (verdict?.approved !== true)
|
|
1642
|
+
return failure("denied", verdict?.approved === false && typeof verdict.reason === "string" ? verdict.reason : "policy gave no verdict");
|
|
1643
|
+
const changes = diff(current, checked.value), before = current;
|
|
1644
|
+
current = checked.value;
|
|
1645
|
+
for (const o of [...live.listeners.ons]) {
|
|
1646
|
+
if (o.gone()) {
|
|
1647
|
+
o.end();
|
|
1648
|
+
continue;
|
|
249
1649
|
}
|
|
250
|
-
const
|
|
251
|
-
|
|
252
|
-
|
|
1650
|
+
const why2 = refusal(live, { runtime: o.runtime, kind: "subscribe", from: o.to, to: o.from, port: o.port });
|
|
1651
|
+
if (why2 !== undefined)
|
|
1652
|
+
o.end({ type: "denied", reason: why2 });
|
|
253
1653
|
}
|
|
1654
|
+
await Promise.all([...changes.removed.map((n) => pods.forget(n, "removed")), ...changes.changed.map((n) => pods.forget(n, "changed"))]);
|
|
1655
|
+
await buildEager([...changes.added, ...changes.changed]);
|
|
1656
|
+
await notifyPodChanges(live, before);
|
|
1657
|
+
trace.emit({ type: "applied", caller, ...changes });
|
|
1658
|
+
return success(undefined);
|
|
1659
|
+
}
|
|
1660
|
+
const one = runtimeView(live, pods.status);
|
|
1661
|
+
const app = {
|
|
1662
|
+
runtime: (id) => runtimeView(live, pods.status, id),
|
|
1663
|
+
resolve: (api, where) => one.resolve(api, where),
|
|
1664
|
+
get: (api, where) => one.get(api, where),
|
|
1665
|
+
subscribe: one.subscribe,
|
|
1666
|
+
call: (...at) => at.length === 1 ? one.call(at[0]) : app.runtime(at[0]).call(at[1]),
|
|
1667
|
+
apply: (next, o) => closing ? Promise.resolve(shut()) : queued(() => reconcile(next, o?.caller ?? "host")),
|
|
1668
|
+
restart: (pod2) => closing ? Promise.resolve(shut()) : queued(async () => {
|
|
1669
|
+
if (!current.pods[pod2])
|
|
1670
|
+
return failure("not-found", `no pod ${pod2}`);
|
|
1671
|
+
await pods.forget(pod2, "restarted");
|
|
1672
|
+
trace.emit({ type: "restarted", pod: pod2 });
|
|
1673
|
+
if (current.pods[pod2].eager)
|
|
1674
|
+
await pods.get(pod2);
|
|
1675
|
+
return success(undefined);
|
|
1676
|
+
}),
|
|
1677
|
+
deployment: () => structuredClone(current),
|
|
1678
|
+
listen: trace.listen,
|
|
1679
|
+
close: () => closing ??= queued(async () => {
|
|
1680
|
+
await Promise.all([pods.close(), ...live.flying]);
|
|
1681
|
+
for (const o of [...live.listeners.ons])
|
|
1682
|
+
o.end();
|
|
1683
|
+
live.listeners.podChanges.clear();
|
|
1684
|
+
return success(undefined);
|
|
1685
|
+
})
|
|
254
1686
|
};
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
}
|
|
265
|
-
if (d.type === "instance-removed") {
|
|
266
|
-
envs.get(d.instance)?.removed(at(d.instance));
|
|
267
|
-
envs.delete(d.instance);
|
|
268
|
-
}
|
|
269
|
-
outer.notify({ from: at("registry"), op: `composable/${d.type}`, data: d });
|
|
270
|
-
});
|
|
271
|
-
registry.add("registry", Components.instantiate(registryComponent(registry)));
|
|
272
|
-
return outer;
|
|
1687
|
+
return success(app);
|
|
1688
|
+
}
|
|
1689
|
+
async function load2(url, opts = {}) {
|
|
1690
|
+
const l = await loaded(url);
|
|
1691
|
+
const r = l.ok ? AppDeployment.assemble(l.value.deployment, l.value.registry) : l;
|
|
1692
|
+
const app = r.ok ? await create4(r.value, opts) : r;
|
|
1693
|
+
if (!app.ok)
|
|
1694
|
+
throw Object.assign(new Error(`${app.fail.type}: ${app.fail.reason}`), { fail: app.fail });
|
|
1695
|
+
return app.value;
|
|
273
1696
|
}
|
|
274
|
-
var
|
|
1697
|
+
var Application = { create: create4, load: load2 };
|
|
275
1698
|
export {
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
1699
|
+
success,
|
|
1700
|
+
selectorData,
|
|
1701
|
+
provide,
|
|
1702
|
+
port2 as port,
|
|
1703
|
+
matches,
|
|
1704
|
+
lookup,
|
|
1705
|
+
isNanoResult,
|
|
1706
|
+
isJson,
|
|
1707
|
+
hashOf,
|
|
1708
|
+
fits,
|
|
1709
|
+
failure,
|
|
1710
|
+
canonicalSchema,
|
|
279
1711
|
canonical,
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
1712
|
+
Selector,
|
|
1713
|
+
Schema,
|
|
1714
|
+
Runtime,
|
|
1715
|
+
Rule,
|
|
1716
|
+
Registry,
|
|
1717
|
+
Provider,
|
|
1718
|
+
PolicyRules,
|
|
1719
|
+
Policies,
|
|
1720
|
+
Pods,
|
|
1721
|
+
Pod,
|
|
1722
|
+
Op,
|
|
1723
|
+
Interface,
|
|
1724
|
+
Implementation,
|
|
1725
|
+
DeploymentPolicies,
|
|
1726
|
+
Coord2 as Coord,
|
|
1727
|
+
COORD,
|
|
1728
|
+
Application,
|
|
1729
|
+
AppDeployment
|
|
286
1730
|
};
|
|
287
1731
|
|
|
288
|
-
//# debugId=
|
|
1732
|
+
//# debugId=78F269783047682B64756E2164756E21
|
|
289
1733
|
//# sourceMappingURL=index.js.map
|