@smthrs/kernel 0.0.0-stage → 1.0.0-rc.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +206 -0
- package/LICENSE +21 -0
- package/README.md +154 -2
- package/dist/cjs/CapabilitySet.d.ts +6 -0
- package/dist/cjs/CapabilitySet.d.ts.map +1 -0
- package/dist/cjs/CapabilitySet.js +19 -0
- package/dist/cjs/CapabilitySet.js.map +7 -0
- package/dist/cjs/ChildProcessEnvironment.d.ts +60 -0
- package/dist/cjs/ChildProcessEnvironment.d.ts.map +1 -0
- package/dist/cjs/ChildProcessEnvironment.js +61 -0
- package/dist/cjs/ChildProcessEnvironment.js.map +7 -0
- package/dist/cjs/ChildProcessSpawner.d.ts +100 -0
- package/dist/cjs/ChildProcessSpawner.d.ts.map +1 -0
- package/dist/cjs/ChildProcessSpawner.js +291 -0
- package/dist/cjs/ChildProcessSpawner.js.map +7 -0
- package/dist/cjs/CommandLine.d.ts +173 -0
- package/dist/cjs/CommandLine.d.ts.map +1 -0
- package/dist/cjs/CommandLine.js +54 -0
- package/dist/cjs/CommandLine.js.map +7 -0
- package/dist/cjs/ContainedSpawner.d.ts +135 -0
- package/dist/cjs/ContainedSpawner.d.ts.map +1 -0
- package/dist/cjs/ContainedSpawner.js +141 -0
- package/dist/cjs/ContainedSpawner.js.map +7 -0
- package/dist/cjs/FileSystem.d.ts +452 -0
- package/dist/cjs/FileSystem.d.ts.map +1 -0
- package/dist/cjs/FileSystem.js +890 -0
- package/dist/cjs/FileSystem.js.map +7 -0
- package/dist/cjs/FileSystemBatch.d.ts +94 -0
- package/dist/cjs/FileSystemBatch.d.ts.map +1 -0
- package/dist/cjs/FileSystemBatch.js +31 -0
- package/dist/cjs/FileSystemBatch.js.map +7 -0
- package/dist/cjs/GrantEvent.d.ts +240 -0
- package/dist/cjs/GrantEvent.d.ts.map +1 -0
- package/dist/cjs/GrantEvent.js +115 -0
- package/dist/cjs/GrantEvent.js.map +7 -0
- package/dist/cjs/GrantStore.d.ts +270 -0
- package/dist/cjs/GrantStore.d.ts.map +1 -0
- package/dist/cjs/GrantStore.js +857 -0
- package/dist/cjs/GrantStore.js.map +7 -0
- package/dist/cjs/HostError.d.ts +36 -0
- package/dist/cjs/HostError.d.ts.map +1 -0
- package/dist/cjs/HostError.js +17 -0
- package/dist/cjs/HostError.js.map +7 -0
- package/dist/cjs/HostServices.d.ts +101 -0
- package/dist/cjs/HostServices.d.ts.map +1 -0
- package/dist/cjs/HostServices.js +66 -0
- package/dist/cjs/HostServices.js.map +7 -0
- package/dist/cjs/HttpClient.d.ts +177 -0
- package/dist/cjs/HttpClient.d.ts.map +1 -0
- package/dist/cjs/HttpClient.js +217 -0
- package/dist/cjs/HttpClient.js.map +7 -0
- package/dist/cjs/Jj.d.ts +67 -0
- package/dist/cjs/Jj.d.ts.map +1 -0
- package/dist/cjs/Jj.js +118 -0
- package/dist/cjs/Jj.js.map +7 -0
- package/dist/cjs/JournalGrantStore.d.ts +65 -0
- package/dist/cjs/JournalGrantStore.d.ts.map +1 -0
- package/dist/cjs/JournalGrantStore.js +354 -0
- package/dist/cjs/JournalGrantStore.js.map +7 -0
- package/dist/cjs/Path.d.ts +37 -0
- package/dist/cjs/Path.d.ts.map +1 -0
- package/dist/cjs/Path.js +46 -0
- package/dist/cjs/Path.js.map +7 -0
- package/dist/cjs/ProcessConfinement.d.ts +55 -0
- package/dist/cjs/ProcessConfinement.d.ts.map +1 -0
- package/dist/cjs/ProcessConfinement.js +94 -0
- package/dist/cjs/ProcessConfinement.js.map +7 -0
- package/dist/cjs/ProcessLedger.d.ts +260 -0
- package/dist/cjs/ProcessLedger.d.ts.map +1 -0
- package/dist/cjs/ProcessLedger.js +190 -0
- package/dist/cjs/ProcessLedger.js.map +7 -0
- package/dist/cjs/Rooted.d.ts +53 -0
- package/dist/cjs/Rooted.d.ts.map +1 -0
- package/dist/cjs/Rooted.js +101 -0
- package/dist/cjs/Rooted.js.map +7 -0
- package/dist/cjs/Unreachable.d.ts +27 -0
- package/dist/cjs/Unreachable.d.ts.map +1 -0
- package/dist/cjs/Unreachable.js +43 -0
- package/dist/cjs/Unreachable.js.map +7 -0
- package/dist/cjs/Workspace.d.ts +62 -0
- package/dist/cjs/Workspace.d.ts.map +1 -0
- package/dist/cjs/Workspace.js +35 -0
- package/dist/cjs/Workspace.js.map +7 -0
- package/dist/cjs/index.d.ts +161 -0
- package/dist/cjs/index.d.ts.map +1 -0
- package/dist/cjs/index.js +73 -0
- package/dist/cjs/index.js.map +7 -0
- package/dist/cjs/internal/Containment.d.ts +24 -0
- package/dist/cjs/internal/Containment.d.ts.map +1 -0
- package/dist/cjs/internal/Containment.js +30 -0
- package/dist/cjs/internal/Containment.js.map +7 -0
- package/dist/cjs/internal/Pipeline.d.ts +18 -0
- package/dist/cjs/internal/Pipeline.d.ts.map +1 -0
- package/dist/cjs/internal/Pipeline.js +90 -0
- package/dist/cjs/internal/Pipeline.js.map +7 -0
- package/dist/cjs/internal/makeCapability.d.ts +16 -0
- package/dist/cjs/internal/makeCapability.d.ts.map +1 -0
- package/dist/cjs/internal/makeCapability.js +44 -0
- package/dist/cjs/internal/makeCapability.js.map +7 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/test/FileSystemBatchContract.d.ts +15 -0
- package/dist/cjs/test/FileSystemBatchContract.d.ts.map +1 -0
- package/dist/cjs/test/FileSystemBatchContract.js +76 -0
- package/dist/cjs/test/FileSystemBatchContract.js.map +7 -0
- package/dist/cjs/test/HostContract.d.ts +225 -0
- package/dist/cjs/test/HostContract.d.ts.map +1 -0
- package/dist/cjs/test/HostContract.js +489 -0
- package/dist/cjs/test/HostContract.js.map +7 -0
- package/dist/cjs/test/TestGrantStore.d.ts +31 -0
- package/dist/cjs/test/TestGrantStore.d.ts.map +1 -0
- package/dist/cjs/test/TestGrantStore.js +65 -0
- package/dist/cjs/test/TestGrantStore.js.map +7 -0
- package/dist/esm/CapabilitySet.d.ts +6 -0
- package/dist/esm/CapabilitySet.d.ts.map +1 -0
- package/dist/esm/CapabilitySet.js +6 -0
- package/dist/esm/CapabilitySet.js.map +1 -0
- package/dist/esm/ChildProcessEnvironment.d.ts +60 -0
- package/dist/esm/ChildProcessEnvironment.d.ts.map +1 -0
- package/dist/esm/ChildProcessEnvironment.js +91 -0
- package/dist/esm/ChildProcessEnvironment.js.map +1 -0
- package/dist/esm/ChildProcessSpawner.d.ts +100 -0
- package/dist/esm/ChildProcessSpawner.d.ts.map +1 -0
- package/dist/esm/ChildProcessSpawner.js +342 -0
- package/dist/esm/ChildProcessSpawner.js.map +1 -0
- package/dist/esm/CommandLine.d.ts +173 -0
- package/dist/esm/CommandLine.d.ts.map +1 -0
- package/dist/esm/CommandLine.js +195 -0
- package/dist/esm/CommandLine.js.map +1 -0
- package/dist/esm/ContainedSpawner.d.ts +135 -0
- package/dist/esm/ContainedSpawner.d.ts.map +1 -0
- package/dist/esm/ContainedSpawner.js +180 -0
- package/dist/esm/ContainedSpawner.js.map +1 -0
- package/dist/esm/FileSystem.d.ts +452 -0
- package/dist/esm/FileSystem.d.ts.map +1 -0
- package/dist/esm/FileSystem.js +989 -0
- package/dist/esm/FileSystem.js.map +1 -0
- package/dist/esm/FileSystemBatch.d.ts +94 -0
- package/dist/esm/FileSystemBatch.d.ts.map +1 -0
- package/dist/esm/FileSystemBatch.js +26 -0
- package/dist/esm/FileSystemBatch.js.map +1 -0
- package/dist/esm/GrantEvent.d.ts +240 -0
- package/dist/esm/GrantEvent.d.ts.map +1 -0
- package/dist/esm/GrantEvent.js +155 -0
- package/dist/esm/GrantEvent.js.map +1 -0
- package/dist/esm/GrantStore.d.ts +270 -0
- package/dist/esm/GrantStore.d.ts.map +1 -0
- package/dist/esm/GrantStore.js +951 -0
- package/dist/esm/GrantStore.js.map +1 -0
- package/dist/esm/HostError.d.ts +36 -0
- package/dist/esm/HostError.d.ts.map +1 -0
- package/dist/esm/HostError.js +20 -0
- package/dist/esm/HostError.js.map +1 -0
- package/dist/esm/HostServices.d.ts +101 -0
- package/dist/esm/HostServices.d.ts.map +1 -0
- package/dist/esm/HostServices.js +76 -0
- package/dist/esm/HostServices.js.map +1 -0
- package/dist/esm/HttpClient.d.ts +177 -0
- package/dist/esm/HttpClient.d.ts.map +1 -0
- package/dist/esm/HttpClient.js +299 -0
- package/dist/esm/HttpClient.js.map +1 -0
- package/dist/esm/Jj.d.ts +67 -0
- package/dist/esm/Jj.d.ts.map +1 -0
- package/dist/esm/Jj.js +111 -0
- package/dist/esm/Jj.js.map +1 -0
- package/dist/esm/JournalGrantStore.d.ts +65 -0
- package/dist/esm/JournalGrantStore.d.ts.map +1 -0
- package/dist/esm/JournalGrantStore.js +350 -0
- package/dist/esm/JournalGrantStore.js.map +1 -0
- package/dist/esm/Path.d.ts +37 -0
- package/dist/esm/Path.d.ts.map +1 -0
- package/dist/esm/Path.js +34 -0
- package/dist/esm/Path.js.map +1 -0
- package/dist/esm/ProcessConfinement.d.ts +55 -0
- package/dist/esm/ProcessConfinement.d.ts.map +1 -0
- package/dist/esm/ProcessConfinement.js +106 -0
- package/dist/esm/ProcessConfinement.js.map +1 -0
- package/dist/esm/ProcessLedger.d.ts +260 -0
- package/dist/esm/ProcessLedger.d.ts.map +1 -0
- package/dist/esm/ProcessLedger.js +283 -0
- package/dist/esm/ProcessLedger.js.map +1 -0
- package/dist/esm/Rooted.d.ts +53 -0
- package/dist/esm/Rooted.d.ts.map +1 -0
- package/dist/esm/Rooted.js +104 -0
- package/dist/esm/Rooted.js.map +1 -0
- package/dist/esm/Unreachable.d.ts +27 -0
- package/dist/esm/Unreachable.d.ts.map +1 -0
- package/dist/esm/Unreachable.js +26 -0
- package/dist/esm/Unreachable.js.map +1 -0
- package/dist/esm/Workspace.d.ts +62 -0
- package/dist/esm/Workspace.d.ts.map +1 -0
- package/dist/esm/Workspace.js +51 -0
- package/dist/esm/Workspace.js.map +1 -0
- package/dist/esm/index.d.ts +161 -0
- package/dist/esm/index.d.ts.map +1 -0
- package/dist/esm/index.js +151 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/internal/Containment.d.ts +24 -0
- package/dist/esm/internal/Containment.d.ts.map +1 -0
- package/dist/esm/internal/Containment.js +27 -0
- package/dist/esm/internal/Containment.js.map +1 -0
- package/dist/esm/internal/Pipeline.d.ts +18 -0
- package/dist/esm/internal/Pipeline.d.ts.map +1 -0
- package/dist/esm/internal/Pipeline.js +68 -0
- package/dist/esm/internal/Pipeline.js.map +1 -0
- package/dist/esm/internal/makeCapability.d.ts +16 -0
- package/dist/esm/internal/makeCapability.d.ts.map +1 -0
- package/dist/esm/internal/makeCapability.js +22 -0
- package/dist/esm/internal/makeCapability.js.map +1 -0
- package/dist/esm/test/FileSystemBatchContract.d.ts +15 -0
- package/dist/esm/test/FileSystemBatchContract.d.ts.map +1 -0
- package/dist/esm/test/FileSystemBatchContract.js +57 -0
- package/dist/esm/test/FileSystemBatchContract.js.map +1 -0
- package/dist/esm/test/HostContract.d.ts +225 -0
- package/dist/esm/test/HostContract.d.ts.map +1 -0
- package/dist/esm/test/HostContract.js +460 -0
- package/dist/esm/test/HostContract.js.map +1 -0
- package/dist/esm/test/TestGrantStore.d.ts +31 -0
- package/dist/esm/test/TestGrantStore.d.ts.map +1 -0
- package/dist/esm/test/TestGrantStore.js +57 -0
- package/dist/esm/test/TestGrantStore.js.map +1 -0
- package/docs/README.md +162 -0
- package/docs/api.md +1532 -0
- package/docs/concepts/decoration-in-place.md +117 -0
- package/docs/concepts/filesystem-batches.md +58 -0
- package/docs/concepts/filesystem-confinement.md +168 -0
- package/docs/concepts/grant-decisions.md +181 -0
- package/docs/concepts/process-containment.md +155 -0
- package/docs/contract.md +14 -0
- package/docs/guides/adapt-a-new-host-platform.md +148 -0
- package/docs/guides/answer-permission-requests.md +151 -0
- package/docs/guides/authorize-network-and-model-calls.md +118 -0
- package/docs/guides/contain-spawned-processes.md +118 -0
- package/docs/guides/guard-a-host-bundle.md +109 -0
- package/docs/guides/persist-grants-across-restarts.md +135 -0
- package/docs/guides/write-a-capability-policy.md +159 -0
- package/docs/installation.md +115 -0
- package/docs/quickstart.md +182 -0
- package/docs/testing.md +108 -0
- package/docs/troubleshooting.md +281 -0
- package/package.json +344 -3
- package/src/CapabilitySet.ts +6 -0
- package/src/ChildProcessEnvironment.ts +98 -0
- package/src/ChildProcessSpawner.ts +414 -0
- package/src/CommandLine.ts +250 -0
- package/src/ContainedSpawner.ts +284 -0
- package/src/FileSystem.ts +1655 -0
- package/src/FileSystemBatch.ts +90 -0
- package/src/GrantEvent.ts +174 -0
- package/src/GrantStore.ts +1345 -0
- package/src/HostError.ts +37 -0
- package/src/HostServices.ts +133 -0
- package/src/HttpClient.ts +406 -0
- package/src/Jj.ts +159 -0
- package/src/JournalGrantStore.ts +461 -0
- package/src/Path.ts +47 -0
- package/src/ProcessConfinement.ts +156 -0
- package/src/ProcessLedger.ts +423 -0
- package/src/Rooted.ts +128 -0
- package/src/Unreachable.ts +30 -0
- package/src/Workspace.ts +65 -0
- package/src/index.ts +181 -0
- package/src/internal/Containment.ts +37 -0
- package/src/internal/Pipeline.ts +85 -0
- package/src/internal/makeCapability.ts +26 -0
- package/src/test/FileSystemBatchContract.ts +59 -0
- package/src/test/HostContract.ts +785 -0
- package/src/test/TestGrantStore.ts +73 -0
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
var ProcessConfinement_exports = {};
|
|
20
|
+
__export(ProcessConfinement_exports, {
|
|
21
|
+
ProcessConfinement: () => ProcessConfinement,
|
|
22
|
+
layerNoop: () => layerNoop,
|
|
23
|
+
makeNoop: () => makeNoop,
|
|
24
|
+
profile: () => profile
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(ProcessConfinement_exports);
|
|
27
|
+
var import_Capability = require("@smthrs/capability/Capability");
|
|
28
|
+
var import_effect = require("effect");
|
|
29
|
+
class ProcessConfinement extends import_effect.Context.Service()("@smthrs/kernel/ProcessConfinement") {
|
|
30
|
+
}
|
|
31
|
+
const makeNoop = ProcessConfinement.of({ confine: (command) => import_effect.Effect.succeed(command) });
|
|
32
|
+
const layerNoop = import_effect.Layer.succeed(ProcessConfinement)(makeNoop);
|
|
33
|
+
const decidable = (pattern, action) => (0, import_Capability.withinMatchBudget)(pattern, new import_Capability.Capability({ action, resource: "x".repeat(import_Capability.maxResourceLength) }));
|
|
34
|
+
const universal = (pattern) => pattern.resource === "*" ? new import_Capability.CapabilityPattern({ action: pattern.action, resource: "**" }) : pattern;
|
|
35
|
+
const coversCeiling = (ceiling, target) => ceiling.groups.every(
|
|
36
|
+
(group) => group.some((pattern) => decidable(pattern, target.action) && (0, import_Capability.subsumes)(universal(pattern), target))
|
|
37
|
+
);
|
|
38
|
+
const actionRelevant = (pattern, action) => (0, import_Capability.matches)(new import_Capability.CapabilityPattern({ action: pattern.action, resource: "**" }), new import_Capability.Capability({ action, resource: "" }));
|
|
39
|
+
const prove = (policy, target) => {
|
|
40
|
+
if (!coversCeiling(policy.ceiling, target)) return false;
|
|
41
|
+
let decision = "ask";
|
|
42
|
+
let configured = "ask";
|
|
43
|
+
for (const [index, group] of policy.groups.entries()) {
|
|
44
|
+
for (const { rule, ceiling } of group) {
|
|
45
|
+
if (!decidable(rule.pattern, target.action)) return false;
|
|
46
|
+
if (!actionRelevant(rule.pattern, target.action)) continue;
|
|
47
|
+
if (target.action === "net:private" && rule.effect === "allow" && rule.pattern.action !== "net:private") continue;
|
|
48
|
+
if (coversCeiling(ceiling, target) && (0, import_Capability.subsumes)(universal(rule.pattern), target)) decision = rule.effect;
|
|
49
|
+
else if (rule.effect !== "allow") decision = "unknown";
|
|
50
|
+
if (index === 0) configured = decision;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return configured !== "deny" && configured !== "unknown" && decision === "allow";
|
|
54
|
+
};
|
|
55
|
+
const profile = (grants, workspaceRoot, path) => import_effect.Effect.gen(function* () {
|
|
56
|
+
const policy = yield* grants.policy;
|
|
57
|
+
const root = path.resolve(workspaceRoot);
|
|
58
|
+
const resources = [
|
|
59
|
+
...policy.groups.flatMap(
|
|
60
|
+
(group) => group.flatMap(({ rule, ceiling }) => [rule.pattern, ...ceiling.groups.flat()])
|
|
61
|
+
),
|
|
62
|
+
...policy.ceiling.groups.flat()
|
|
63
|
+
];
|
|
64
|
+
const candidates = /* @__PURE__ */ new Set();
|
|
65
|
+
for (const { resource } of resources) {
|
|
66
|
+
if (resource === "**" || resource === "*") {
|
|
67
|
+
candidates.add(".");
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
if (!resource.endsWith("/**") || /[*?]/.test(resource.slice(0, -3))) continue;
|
|
71
|
+
const base = resource.slice(0, -3);
|
|
72
|
+
if (!path.isAbsolute(base) || path.normalize(base) !== base) continue;
|
|
73
|
+
const relative = path.relative(root, base);
|
|
74
|
+
if (path.isAbsolute(relative) || relative.split(path.sep)[0] === "..") continue;
|
|
75
|
+
candidates.add(relative === "" ? "." : relative.split(path.sep).join("/"));
|
|
76
|
+
}
|
|
77
|
+
const opened = (action) => [...candidates].filter((relative) => {
|
|
78
|
+
const directory = relative === "." ? root : path.resolve(root, relative);
|
|
79
|
+
const resource = `${directory}/**`;
|
|
80
|
+
return prove(policy, new import_Capability.CapabilityPattern({ action, resource })) && (action !== "fs:write" || prove(policy, new import_Capability.CapabilityPattern({ action: "fs:read", resource })) && prove(policy, new import_Capability.CapabilityPattern({ action: "fs:write", resource: directory })));
|
|
81
|
+
}).filter(
|
|
82
|
+
(relative, _, all) => !all.some((parent) => parent !== relative && (parent === "." || relative.startsWith(`${parent}/`)))
|
|
83
|
+
).sort();
|
|
84
|
+
return Object.freeze({
|
|
85
|
+
workspaceRoot: root,
|
|
86
|
+
reads: Object.freeze(opened("fs:read")),
|
|
87
|
+
writes: Object.freeze(opened("fs:write")),
|
|
88
|
+
readOnly: Object.freeze([]),
|
|
89
|
+
network: ["net:get", "net:post", "net:private"].every(
|
|
90
|
+
(action) => prove(policy, new import_Capability.CapabilityPattern({ action, resource: "**" }))
|
|
91
|
+
) ? "open" : "none"
|
|
92
|
+
});
|
|
93
|
+
});
|
|
94
|
+
//# sourceMappingURL=ProcessConfinement.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/ProcessConfinement.ts"],
|
|
4
|
+
"sourcesContent": ["/** Operating-system confinement derived conservatively from effective grants.\n * @since 1.0.0-rc.1\n */\n\nimport {\n type Action,\n Capability,\n CapabilityPattern,\n matches,\n maxResourceLength,\n subsumes,\n withinMatchBudget\n} from \"@smthrs/capability/Capability\"\nimport type { GrantStoreError } from \"@smthrs/capability/Permission\"\nimport { Context, Effect, Layer, type Path, type Scope } from \"effect\"\nimport type { PlatformError } from \"effect/PlatformError\"\nimport type * as ChildProcess from \"effect/unstable/process/ChildProcess\"\nimport type { Policy, PolicyRule, Service as GrantService } from \"./GrantStore.ts\"\n\n/** Workspace-relative trees; `.` names the workspace. No path opens its parent.\n * @category models\n * @since 1.0.0-rc.1\n */\nexport interface Profile {\n readonly workspaceRoot: string\n readonly reads: ReadonlyArray<string>\n readonly writes: ReadonlyArray<string>\n readonly readOnly: ReadonlyArray<string>\n readonly network: \"none\" | \"open\"\n}\n/** Host wrapper for one process stage. Failure must occur before spawning.\n * @category models\n * @since 1.0.0-rc.1\n */\nexport interface Service {\n readonly confine: (\n command: ChildProcess.StandardCommand,\n profile: Profile\n ) => Effect.Effect<ChildProcess.StandardCommand, PlatformError, Scope.Scope>\n}\n/** Host confinement seam; missing service refuses spawning.\n * @category services\n * @since 1.0.0-rc.1\n */\nexport class ProcessConfinement\n extends Context.Service<ProcessConfinement, Service>()(\"@smthrs/kernel/ProcessConfinement\")\n{}\n/** Explicit unconfined composition.\n * @category constructors\n * @since 1.0.0-rc.1\n */\nexport const makeNoop: Service = ProcessConfinement.of({ confine: (command) => Effect.succeed(command) })\n/** Explicit unconfined layer.\n * @category layers\n * @since 1.0.0-rc.1\n */\nexport const layerNoop: Layer.Layer<ProcessConfinement> = Layer.succeed(ProcessConfinement)(makeNoop)\n\nconst decidable = (pattern: CapabilityPattern, action: Action) =>\n withinMatchBudget(pattern, new Capability({ action, resource: \"x\".repeat(maxResourceLength) }))\n\n// The capability matcher permits a single star to cross separators. Only\n// this universal spelling is equivalent to **; arbitrary globs stay closed.\nconst universal = (pattern: CapabilityPattern): CapabilityPattern =>\n pattern.resource === \"*\" ? new CapabilityPattern({ action: pattern.action, resource: \"**\" }) : pattern\n\nconst coversCeiling = (ceiling: PolicyRule[\"ceiling\"], target: CapabilityPattern): boolean =>\n ceiling.groups.every((group) =>\n group.some((pattern) => decidable(pattern, target.action as Action) && subsumes(universal(pattern), target))\n )\nconst actionRelevant = (pattern: CapabilityPattern, action: Action): boolean =>\n matches(new CapabilityPattern({ action: pattern.action, resource: \"**\" }), new Capability({ action, resource: \"\" }))\n\n// A covering rule resolves the complete region. A narrower/conditional refusal\n// makes it unknown until a later covering rule resolves it. Unknown configured\n// denial vetoes all later grant groups, just as evaluate's configured veto does.\nconst prove = (policy: Policy, target: CapabilityPattern): boolean => {\n if (!coversCeiling(policy.ceiling, target)) return false\n let decision: \"allow\" | \"deny\" | \"ask\" | \"unknown\" = \"ask\"\n let configured: \"allow\" | \"deny\" | \"ask\" | \"unknown\" = \"ask\"\n for (const [index, group] of policy.groups.entries()) {\n for (const { rule, ceiling } of group) {\n if (!decidable(rule.pattern, target.action as Action)) return false\n if (!actionRelevant(rule.pattern, target.action as Action)) continue\n if (target.action === \"net:private\" && rule.effect === \"allow\" && rule.pattern.action !== \"net:private\") continue\n if (coversCeiling(ceiling, target) && subsumes(universal(rule.pattern), target)) decision = rule.effect\n else if (rule.effect !== \"allow\") decision = \"unknown\"\n if (index === 0) configured = decision\n }\n }\n return configured !== \"deny\" && configured !== \"unknown\" && decision === \"allow\"\n}\n\n/** Derives a subset of authority, never a widening. Literal filesystem grants,\n * complex globs and unrepresentable restrictions conservatively open nothing.\n * Writable trees also require read authority and write authority over their\n * exact directory root: native mounts permit reads and directory metadata\n * changes. Only whole-tree grants prove filesystem trees; unrestricted\n * authority for each of get/post/private is required to open network access.\n * @category resolution\n * @since 1.0.0-rc.1\n */\nexport const profile = (\n grants: GrantService,\n workspaceRoot: string,\n path: Path.Path\n): Effect.Effect<Profile, GrantStoreError> =>\n Effect.gen(function*() {\n const policy = yield* grants.policy\n const root = path.resolve(workspaceRoot)\n const resources = [\n ...policy.groups.flatMap((group) =>\n group.flatMap(({ rule, ceiling }) => [rule.pattern, ...ceiling.groups.flat()])\n ),\n ...policy.ceiling.groups.flat()\n ]\n const candidates = new Set<string>()\n for (const { resource } of resources) {\n if (resource === \"**\" || resource === \"*\") {\n candidates.add(\".\")\n continue\n }\n if (!resource.endsWith(\"/**\") || /[*?]/.test(resource.slice(0, -3))) continue\n const base = resource.slice(0, -3)\n // Relative policy resources do not authorize absolute kernel resources.\n if (!path.isAbsolute(base) || path.normalize(base) !== base) continue\n const relative = path.relative(root, base)\n if (path.isAbsolute(relative) || relative.split(path.sep)[0] === \"..\") continue\n candidates.add(relative === \"\" ? \".\" : relative.split(path.sep).join(\"/\"))\n }\n const opened = (action: Action) =>\n [...candidates].filter((relative) => {\n const directory = relative === \".\" ? root : path.resolve(root, relative)\n const resource = `${directory}/**`\n return prove(policy, new CapabilityPattern({ action, resource })) &&\n (action !== \"fs:write\" || (\n prove(policy, new CapabilityPattern({ action: \"fs:read\", resource })) &&\n prove(policy, new CapabilityPattern({ action: \"fs:write\", resource: directory }))\n ))\n })\n .filter((relative, _, all) =>\n !all.some((parent) => parent !== relative && (parent === \".\" || relative.startsWith(`${parent}/`)))\n )\n .sort()\n return Object.freeze({\n workspaceRoot: root,\n reads: Object.freeze(opened(\"fs:read\")),\n writes: Object.freeze(opened(\"fs:write\")),\n readOnly: Object.freeze([]),\n network: ([\"net:get\", \"net:post\", \"net:private\"] as const).every((action) =>\n prove(policy, new CapabilityPattern({ action, resource: \"**\" }))\n ) ?\n \"open\" as const :\n \"none\" as const\n })\n })\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,wBAQO;AAEP,oBAA8D;AA8BvD,MAAM,2BACH,sBAAQ,QAAqC,EAAE,mCAAmC,EAC5F;AAAC;AAKM,MAAM,WAAoB,mBAAmB,GAAG,EAAE,SAAS,CAAC,YAAY,qBAAO,QAAQ,OAAO,EAAE,CAAC;AAKjG,MAAM,YAA6C,oBAAM,QAAQ,kBAAkB,EAAE,QAAQ;AAEpG,MAAM,YAAY,CAAC,SAA4B,eAC7C,qCAAkB,SAAS,IAAI,6BAAW,EAAE,QAAQ,UAAU,IAAI,OAAO,mCAAiB,EAAE,CAAC,CAAC;AAIhG,MAAM,YAAY,CAAC,YACjB,QAAQ,aAAa,MAAM,IAAI,oCAAkB,EAAE,QAAQ,QAAQ,QAAQ,UAAU,KAAK,CAAC,IAAI;AAEjG,MAAM,gBAAgB,CAAC,SAAg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AA,EACpG,EACC,KAAK;AACV,SAAO,OAAO,OAAO;AAAA,IACnB,eAAe;AAAA,IACf,OAAO,OAAO,OAAO,OAAO,SAAS,CAAC;AAAA,IACtC,QAAQ,OAAO,OAAO,OAAO,UAAU,CAAC;AAAA,IACxC,UAAU,OAAO,OAAO,CAAC,CAAC;AAAA,IAC1B,SAAU,CAAC,WAAW,YAAY,aAAa,EAAY;AAAA,MAAM,CAAC,WAC9D,MAAM,QAAQ,IAAI,oCAAkB,EAAE,QAAQ,UAAU,KAAK,CAAC,CAAC;AAAA,IACjE,IACA,SACA;AAAA,EACJ,CAAC;AACH,CAAC;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The host's ledger of the processes it spawned.
|
|
3
|
+
*
|
|
4
|
+
* A cancelled run must not leave a child agent running, and the engine cannot
|
|
5
|
+
* do anything about that on its own: cancellation interrupts fibers, and a
|
|
6
|
+
* fiber closing its scope only reaches the processes THIS incarnation of the
|
|
7
|
+
* host still holds a handle for. A host that crashed left its children with no
|
|
8
|
+
* one holding anything.
|
|
9
|
+
*
|
|
10
|
+
* The ledger is the missing half. Every spawn is recorded here in memory and
|
|
11
|
+
* written to the journal as an ownerless durable record. It is ownerless
|
|
12
|
+
* because it describes the host rather than a run, and first-writer-wins is
|
|
13
|
+
* exactly the semantics a spawn record wants. The next incarnation of the same
|
|
14
|
+
* `hostId` replays those records, subtracts the ones that reported an exit,
|
|
15
|
+
* and is left with {@link Service.orphans}: the process groups a dead owner
|
|
16
|
+
* abandoned, which a platform reaper can then signal.
|
|
17
|
+
*
|
|
18
|
+
* The kernel stays BELOW the engine: this module records pids and process
|
|
19
|
+
* groups and knows nothing about runs, attempts, or ownership fences. It also
|
|
20
|
+
* stays platform-neutral, because signalling a process group is a platform
|
|
21
|
+
* concern and lives in `@smthrs/platform-node`.
|
|
22
|
+
*
|
|
23
|
+
* Governing design:
|
|
24
|
+
* `docs/specs/Concepts/Host Adapters.md` and
|
|
25
|
+
* `docs/specs/Concepts/Journal Queue.md`.
|
|
26
|
+
*
|
|
27
|
+
* @since 1.0.0-rc.0
|
|
28
|
+
*/
|
|
29
|
+
import * as JournalModule from "@smthrs/journal/Journal";
|
|
30
|
+
import type { JournalError } from "@smthrs/journal/Journal";
|
|
31
|
+
import * as JournalEvent from "@smthrs/journal/JournalEvent";
|
|
32
|
+
import * as Context from "effect/Context";
|
|
33
|
+
import * as Effect from "effect/Effect";
|
|
34
|
+
import * as Layer from "effect/Layer";
|
|
35
|
+
import * as Schema from "effect/Schema";
|
|
36
|
+
/**
|
|
37
|
+
* The event type recording that a host started a process.
|
|
38
|
+
*
|
|
39
|
+
* @category models
|
|
40
|
+
* @since 1.0.0-rc.0
|
|
41
|
+
*/
|
|
42
|
+
export declare const SpawnedEventType = "flows.host.process-spawned.v1";
|
|
43
|
+
/**
|
|
44
|
+
* The event type recording that a recorded process ended.
|
|
45
|
+
*
|
|
46
|
+
* @category models
|
|
47
|
+
* @since 1.0.0-rc.0
|
|
48
|
+
*/
|
|
49
|
+
export declare const ExitedEventType = "flows.host.process-exited.v1";
|
|
50
|
+
/**
|
|
51
|
+
* The event type recording that a later incarnation killed an abandoned
|
|
52
|
+
* process group.
|
|
53
|
+
*
|
|
54
|
+
* @category models
|
|
55
|
+
* @since 1.0.0-rc.0
|
|
56
|
+
*/
|
|
57
|
+
export declare const ReapedEventType = "flows.host.process-reaped.v1";
|
|
58
|
+
/**
|
|
59
|
+
* The event type recording that a later incarnation retired a record WITHOUT
|
|
60
|
+
* signalling anything.
|
|
61
|
+
*
|
|
62
|
+
* A stored pid outlives the process that wrote it, so a reaper that cannot
|
|
63
|
+
* prove the number still names the process the record describes must not
|
|
64
|
+
* signal it. Retiring the record is still correct: nothing will ever be able
|
|
65
|
+
* to prove it again, and leaving it would make every later incarnation
|
|
66
|
+
* re-examine a number the operating system has moved on from.
|
|
67
|
+
*
|
|
68
|
+
* @category models
|
|
69
|
+
* @since 1.0.0-rc.0
|
|
70
|
+
*/
|
|
71
|
+
export declare const SkippedEventType = "flows.host.process-reap-skipped.v1";
|
|
72
|
+
/**
|
|
73
|
+
* The producer id every ledger record is written under.
|
|
74
|
+
*
|
|
75
|
+
* Replay checks it: a record forged by another producer cannot make a host
|
|
76
|
+
* signal a process group.
|
|
77
|
+
*
|
|
78
|
+
* @category models
|
|
79
|
+
* @since 1.0.0-rc.0
|
|
80
|
+
*/
|
|
81
|
+
export declare const sourceId = "@smthrs/kernel/ProcessLedger";
|
|
82
|
+
/**
|
|
83
|
+
* The journal run a host's process records live on.
|
|
84
|
+
*
|
|
85
|
+
* Process records describe a host, not a run, so they get a run of their own,
|
|
86
|
+
* named after the host. Two incarnations of one `hostId` therefore share a
|
|
87
|
+
* history, which is what makes an abandoned process discoverable.
|
|
88
|
+
*
|
|
89
|
+
* @category constructors
|
|
90
|
+
* @since 1.0.0-rc.0
|
|
91
|
+
*/
|
|
92
|
+
export declare const hostRunId: (hostId: string) => JournalEvent.RunId;
|
|
93
|
+
/**
|
|
94
|
+
* What the spawner knows about a process the moment it starts.
|
|
95
|
+
*
|
|
96
|
+
* `pgid` is `null` when the child shares the host's own process group. Such a
|
|
97
|
+
* process cannot be group-signalled — signalling that group would signal the
|
|
98
|
+
* host itself — so the ledger records the absence rather than a number a
|
|
99
|
+
* reaper could misread.
|
|
100
|
+
*
|
|
101
|
+
* `commandDigest` names the executable and nothing else, as
|
|
102
|
+
* `CommandLine.executable` renders it. Arguments carry credentials
|
|
103
|
+
* (`curl -u user:password`, `mysql -phunter2`) and these records are permanent
|
|
104
|
+
* journal entries, so the ledger never writes an argument down. A reader that
|
|
105
|
+
* has to act on a record matches it by pid and process group; the program name
|
|
106
|
+
* is there to make the row legible.
|
|
107
|
+
*
|
|
108
|
+
* @category models
|
|
109
|
+
* @since 1.0.0-rc.0
|
|
110
|
+
*/
|
|
111
|
+
export interface Spawned {
|
|
112
|
+
readonly pid: number;
|
|
113
|
+
readonly pgid: number | null;
|
|
114
|
+
readonly commandDigest: string;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Schema for a recorded process, as it round-trips through the journal.
|
|
118
|
+
*
|
|
119
|
+
* @category schemas
|
|
120
|
+
* @since 1.0.0-rc.0
|
|
121
|
+
*/
|
|
122
|
+
export declare const ProcessRecord: Schema.Struct<{
|
|
123
|
+
readonly pid: Schema.Int;
|
|
124
|
+
readonly pgid: Schema.NullOr<Schema.Int>;
|
|
125
|
+
readonly hostId: Schema.String;
|
|
126
|
+
readonly ownerPid: Schema.Int;
|
|
127
|
+
readonly startedAtMs: Schema.Int;
|
|
128
|
+
readonly commandDigest: Schema.String;
|
|
129
|
+
}>;
|
|
130
|
+
/**
|
|
131
|
+
* One process a host started, with the identity of the incarnation that
|
|
132
|
+
* started it.
|
|
133
|
+
*
|
|
134
|
+
* @category models
|
|
135
|
+
* @since 1.0.0-rc.0
|
|
136
|
+
*/
|
|
137
|
+
export type ProcessRecord = typeof ProcessRecord.Type;
|
|
138
|
+
/**
|
|
139
|
+
* Why a ledger history could not be replayed.
|
|
140
|
+
*
|
|
141
|
+
* - `journal_unreadable`: a page of the host's history could not be read.
|
|
142
|
+
* - `cursor_stalled`: the journal reported more history but did not advance.
|
|
143
|
+
*
|
|
144
|
+
* @category models
|
|
145
|
+
* @since 1.0.0-rc.1
|
|
146
|
+
*/
|
|
147
|
+
export declare const ProcessLedgerReplayErrorCode: Schema.Literals<readonly ["journal_unreadable", "cursor_stalled"]>;
|
|
148
|
+
declare const ProcessLedgerReplayError_base: Schema.Class<ProcessLedgerReplayError, Schema.TaggedStruct<"@smthrs/kernel/ProcessLedgerReplayError", {
|
|
149
|
+
readonly code: Schema.Literals<readonly ["journal_unreadable", "cursor_stalled"]>;
|
|
150
|
+
readonly message: Schema.String;
|
|
151
|
+
readonly cause: Schema.optional<Schema.Defect>;
|
|
152
|
+
}>, import("effect/Cause").YieldableError>;
|
|
153
|
+
/**
|
|
154
|
+
* The ledger could not read a previous incarnation's history to its end.
|
|
155
|
+
*
|
|
156
|
+
* An unread history is never reported as an empty one: a caller that treated
|
|
157
|
+
* it as empty would leave every abandoned child running with no owner.
|
|
158
|
+
*
|
|
159
|
+
* @category errors
|
|
160
|
+
* @since 1.0.0-rc.1
|
|
161
|
+
*/
|
|
162
|
+
export declare class ProcessLedgerReplayError extends ProcessLedgerReplayError_base {
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Ledger operations.
|
|
166
|
+
*
|
|
167
|
+
* Every write that has a durable half REPORTS whether that half committed.
|
|
168
|
+
* The in-memory set is still updated first, so a caller that decides to carry
|
|
169
|
+
* on has an accurate view of this incarnation, but the failure is not
|
|
170
|
+
* swallowed: a spawn whose record did not commit is a child that no later
|
|
171
|
+
* incarnation can discover, which is the exact hole this ledger exists to
|
|
172
|
+
* close. {@link ContainedSpawner} therefore refuses such a spawn, and the
|
|
173
|
+
* reaper leaves a record it could not retire in place so a later incarnation
|
|
174
|
+
* tries again.
|
|
175
|
+
*
|
|
176
|
+
* A ledger built with no journal ({@link makeMemory}) never fails: it promises
|
|
177
|
+
* nothing durable in the first place.
|
|
178
|
+
*
|
|
179
|
+
* @category services
|
|
180
|
+
* @since 1.0.0-rc.0
|
|
181
|
+
*/
|
|
182
|
+
export interface Service {
|
|
183
|
+
/** Records a started process and returns the durable record written for it. */
|
|
184
|
+
readonly record: (spawned: Spawned) => Effect.Effect<ProcessRecord, JournalError>;
|
|
185
|
+
/** Records that a process ended, and drops it from {@link Service.live}. */
|
|
186
|
+
readonly release: (record: ProcessRecord) => Effect.Effect<void, JournalError>;
|
|
187
|
+
/** Records that an abandoned process group was signalled by this host. */
|
|
188
|
+
readonly reaped: (record: ProcessRecord) => Effect.Effect<void, JournalError>;
|
|
189
|
+
/**
|
|
190
|
+
* Retires a record this host refused to signal, naming why. The record
|
|
191
|
+
* leaves {@link Service.orphans} without anything having been killed.
|
|
192
|
+
*/
|
|
193
|
+
readonly skipped: (record: ProcessRecord, reason: string) => Effect.Effect<void, JournalError>;
|
|
194
|
+
/** The processes this incarnation started and has not yet released. */
|
|
195
|
+
readonly live: Effect.Effect<ReadonlyArray<ProcessRecord>>;
|
|
196
|
+
/**
|
|
197
|
+
* The processes a previous incarnation of this host left running.
|
|
198
|
+
*
|
|
199
|
+
* Fails when that history cannot be read to its end, so an unreadable
|
|
200
|
+
* history is never mistaken for one with nothing left running.
|
|
201
|
+
*/
|
|
202
|
+
readonly orphans: Effect.Effect<ReadonlyArray<ProcessRecord>, ProcessLedgerReplayError>;
|
|
203
|
+
}
|
|
204
|
+
declare const ProcessLedger_base: Context.ServiceClass<ProcessLedger, "@smthrs/kernel/ProcessLedger", Service>;
|
|
205
|
+
/**
|
|
206
|
+
* The process-ledger service tag.
|
|
207
|
+
*
|
|
208
|
+
* @category services
|
|
209
|
+
* @since 1.0.0-rc.0
|
|
210
|
+
*/
|
|
211
|
+
export declare class ProcessLedger extends ProcessLedger_base {
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Ledger configuration.
|
|
215
|
+
*
|
|
216
|
+
* `hostId` is the durable identity two incarnations share; `ownerPid` is the
|
|
217
|
+
* process id of THIS incarnation, which is how a replay tells its own live
|
|
218
|
+
* processes from an abandoned one's.
|
|
219
|
+
*
|
|
220
|
+
* @category models
|
|
221
|
+
* @since 1.0.0-rc.0
|
|
222
|
+
*/
|
|
223
|
+
export interface Options {
|
|
224
|
+
readonly hostId: string;
|
|
225
|
+
readonly ownerPid: number;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Builds a journal-backed ledger.
|
|
229
|
+
*
|
|
230
|
+
* @category constructors
|
|
231
|
+
* @since 1.0.0-rc.0
|
|
232
|
+
*/
|
|
233
|
+
export declare const make: (options: Options) => Effect.Effect<Service, never, JournalModule.Journal>;
|
|
234
|
+
/**
|
|
235
|
+
* Builds a ledger that records nothing durably.
|
|
236
|
+
*
|
|
237
|
+
* A host without a journal still contains the processes it holds handles for —
|
|
238
|
+
* scope closure does that — but it inherits nothing from a previous
|
|
239
|
+
* incarnation, so {@link Service.orphans} is always empty.
|
|
240
|
+
*
|
|
241
|
+
* @category constructors
|
|
242
|
+
* @since 1.0.0-rc.0
|
|
243
|
+
*/
|
|
244
|
+
export declare const makeMemory: (options: Options) => Effect.Effect<Service>;
|
|
245
|
+
/**
|
|
246
|
+
* Provides a journal-backed ledger.
|
|
247
|
+
*
|
|
248
|
+
* @category layers
|
|
249
|
+
* @since 1.0.0-rc.0
|
|
250
|
+
*/
|
|
251
|
+
export declare const layer: (options: Options) => Layer.Layer<ProcessLedger, never, JournalModule.Journal>;
|
|
252
|
+
/**
|
|
253
|
+
* Provides a ledger that records nothing durably.
|
|
254
|
+
*
|
|
255
|
+
* @category layers
|
|
256
|
+
* @since 1.0.0-rc.0
|
|
257
|
+
*/
|
|
258
|
+
export declare const layerMemory: (options: Options) => Layer.Layer<ProcessLedger>;
|
|
259
|
+
export {};
|
|
260
|
+
//# sourceMappingURL=ProcessLedger.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ProcessLedger.d.ts","sourceRoot":"","sources":["../../src/ProcessLedger.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH,OAAO,KAAK,aAAa,MAAM,yBAAyB,CAAA;AACxD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAA;AAC3D,OAAO,KAAK,YAAY,MAAM,8BAA8B,CAAA;AAC5D,OAAO,KAAK,OAAO,MAAM,gBAAgB,CAAA;AACzC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AACrC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AAEvC;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,kCAAkC,CAAA;AAE/D;;;;;GAKG;AACH,eAAO,MAAM,eAAe,iCAAiC,CAAA;AAE7D;;;;;;GAMG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C,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,MAAM,KAAK,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,YAAY,CAAC,CAAA;IAC9F,uEAAuE;IACvE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,aAAa,CAAC,CAAC,CAAA;IAC1D;;;;;OAKG;IACH,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,aAAa,CAAC,EAAE,wBAAwB,CAAC,CAAA;CACxF;;AAED;;;;;GAKG;AACH,qBAAa,aAAc,SAAQ,kBAAyE;CAAG;AAE/G;;;;;;;;;GASG;AACH,MAAM,WAAW,OAAO;IACtB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;CAC1B;AA+ID;;;;;GAKG;AACH,eAAO,MAAM,IAAI,GAAI,SAAS,OAAO,KAAG,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,KAAK,EAAE,aAAa,CAAC,OAAO,CACO,CAAA;AAElG;;;;;;;;;GASG;AACH,eAAO,MAAM,UAAU,GAAI,SAAS,OAAO,KAAG,MAAM,CAAC,MAAM,CAAC,OAAO,CAAqD,CAAA;AAExH;;;;;GAKG;AACH,eAAO,MAAM,KAAK,GAAI,SAAS,OAAO,KAAG,KAAK,CAAC,KAAK,CAAC,aAAa,EAAE,KAAK,EAAE,aAAa,CAAC,OAAO,CACpD,CAAA;AAE5C;;;;;GAKG;AACH,eAAO,MAAM,WAAW,GAAI,SAAS,OAAO,KAAG,KAAK,CAAC,KAAK,CAAC,aAAa,CACtB,CAAA"}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
var ProcessLedger_exports = {};
|
|
30
|
+
__export(ProcessLedger_exports, {
|
|
31
|
+
ExitedEventType: () => ExitedEventType,
|
|
32
|
+
ProcessLedger: () => ProcessLedger,
|
|
33
|
+
ProcessLedgerReplayError: () => ProcessLedgerReplayError,
|
|
34
|
+
ProcessLedgerReplayErrorCode: () => ProcessLedgerReplayErrorCode,
|
|
35
|
+
ProcessRecord: () => ProcessRecord,
|
|
36
|
+
ReapedEventType: () => ReapedEventType,
|
|
37
|
+
SkippedEventType: () => SkippedEventType,
|
|
38
|
+
SpawnedEventType: () => SpawnedEventType,
|
|
39
|
+
hostRunId: () => hostRunId,
|
|
40
|
+
layer: () => layer,
|
|
41
|
+
layerMemory: () => layerMemory,
|
|
42
|
+
make: () => make,
|
|
43
|
+
makeMemory: () => makeMemory,
|
|
44
|
+
sourceId: () => sourceId
|
|
45
|
+
});
|
|
46
|
+
module.exports = __toCommonJS(ProcessLedger_exports);
|
|
47
|
+
var JournalModule = __toESM(require("@smthrs/journal/Journal"), 1);
|
|
48
|
+
var JournalEvent = __toESM(require("@smthrs/journal/JournalEvent"), 1);
|
|
49
|
+
var Context = __toESM(require("effect/Context"), 1);
|
|
50
|
+
var Effect = __toESM(require("effect/Effect"), 1);
|
|
51
|
+
var Layer = __toESM(require("effect/Layer"), 1);
|
|
52
|
+
var Schema = __toESM(require("effect/Schema"), 1);
|
|
53
|
+
const SpawnedEventType = "flows.host.process-spawned.v1";
|
|
54
|
+
const ExitedEventType = "flows.host.process-exited.v1";
|
|
55
|
+
const ReapedEventType = "flows.host.process-reaped.v1";
|
|
56
|
+
const SkippedEventType = "flows.host.process-reap-skipped.v1";
|
|
57
|
+
const sourceId = "@smthrs/kernel/ProcessLedger";
|
|
58
|
+
const hostRunId = (hostId) => `flows.host:${hostId}`;
|
|
59
|
+
const ProcessRecord = Schema.Struct({
|
|
60
|
+
pid: Schema.Int,
|
|
61
|
+
pgid: Schema.NullOr(Schema.Int),
|
|
62
|
+
hostId: Schema.String,
|
|
63
|
+
ownerPid: Schema.Int,
|
|
64
|
+
startedAtMs: Schema.Int,
|
|
65
|
+
commandDigest: Schema.String
|
|
66
|
+
});
|
|
67
|
+
const ProcessLedgerReplayErrorCode = Schema.Literals(["journal_unreadable", "cursor_stalled"]);
|
|
68
|
+
class ProcessLedgerReplayError extends Schema.TaggedError()(
|
|
69
|
+
"@smthrs/kernel/ProcessLedgerReplayError",
|
|
70
|
+
{
|
|
71
|
+
code: ProcessLedgerReplayErrorCode,
|
|
72
|
+
message: Schema.String,
|
|
73
|
+
cause: Schema.optional(Schema.Defect())
|
|
74
|
+
}
|
|
75
|
+
) {
|
|
76
|
+
}
|
|
77
|
+
const decodeRecord = Schema.decodeUnknownResult(ProcessRecord);
|
|
78
|
+
const encodeRecord = Schema.encodeSync(ProcessRecord);
|
|
79
|
+
class ProcessLedger extends Context.Service()("@smthrs/kernel/ProcessLedger") {
|
|
80
|
+
}
|
|
81
|
+
const retires = (eventType) => eventType === ExitedEventType || eventType === ReapedEventType || eventType === SkippedEventType;
|
|
82
|
+
const identity = (record) => `${record.pid}:${record.startedAtMs}`;
|
|
83
|
+
const apply = (live, entry) => {
|
|
84
|
+
if (entry.sourceId !== sourceId) return void 0;
|
|
85
|
+
if (entry.eventType !== SpawnedEventType && !retires(entry.eventType)) return void 0;
|
|
86
|
+
const decoded = decodeRecord(entry.payload);
|
|
87
|
+
if (decoded._tag === "Failure") return entry;
|
|
88
|
+
if (entry.eventType === SpawnedEventType) {
|
|
89
|
+
live.set(identity(decoded.success), decoded.success);
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
live.delete(identity(decoded.success));
|
|
93
|
+
return void 0;
|
|
94
|
+
};
|
|
95
|
+
const PAGE = 256;
|
|
96
|
+
const journalSink = (options, journal) => ({
|
|
97
|
+
append: (eventType, record, extra) => journal.emitDurableUnfenced(
|
|
98
|
+
new JournalEvent.Input({
|
|
99
|
+
runId: hostRunId(options.hostId),
|
|
100
|
+
sourceId,
|
|
101
|
+
eventType,
|
|
102
|
+
payload: extra === void 0 ? encodeRecord(record) : { ...encodeRecord(record), ...extra }
|
|
103
|
+
})
|
|
104
|
+
).pipe(
|
|
105
|
+
// The failure is REPORTED, not logged away. A swallowed write leaves a
|
|
106
|
+
// child that no incarnation of this host can discover, which is the one
|
|
107
|
+
// outcome containment exists to prevent; the caller decides what to do
|
|
108
|
+
// about it, and every caller in this repository declines to pretend the
|
|
109
|
+
// process was recorded.
|
|
110
|
+
Effect.tapCause((cause) => Effect.logWarning(`process ledger could not journal ${eventType}`, cause)),
|
|
111
|
+
Effect.asVoid
|
|
112
|
+
),
|
|
113
|
+
replay: Effect.gen(function* () {
|
|
114
|
+
const live = /* @__PURE__ */ new Map();
|
|
115
|
+
let after;
|
|
116
|
+
for (; ; ) {
|
|
117
|
+
const page = yield* journal.entries({
|
|
118
|
+
runId: hostRunId(options.hostId),
|
|
119
|
+
limit: PAGE,
|
|
120
|
+
...after === void 0 ? {} : { after }
|
|
121
|
+
}).pipe(
|
|
122
|
+
Effect.mapError(
|
|
123
|
+
(cause) => new ProcessLedgerReplayError({
|
|
124
|
+
code: "journal_unreadable",
|
|
125
|
+
message: `process ledger could not read the history of host ${options.hostId}`,
|
|
126
|
+
cause
|
|
127
|
+
})
|
|
128
|
+
)
|
|
129
|
+
);
|
|
130
|
+
for (const entry of page.entries) {
|
|
131
|
+
const malformed = apply(live, entry);
|
|
132
|
+
if (malformed !== void 0) {
|
|
133
|
+
yield* Effect.logWarning(
|
|
134
|
+
`process ledger skipped an undecodable ${malformed.eventType} record at seq ${malformed.seq}`
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
const last = page.entries.at(-1);
|
|
139
|
+
if (last === void 0 || !page.hasMore) break;
|
|
140
|
+
if (after !== void 0 && last.seq <= after) {
|
|
141
|
+
return yield* Effect.fail(
|
|
142
|
+
new ProcessLedgerReplayError({
|
|
143
|
+
code: "cursor_stalled",
|
|
144
|
+
message: `process ledger history of host ${options.hostId} stopped advancing at seq ${last.seq}`
|
|
145
|
+
})
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
after = last.seq;
|
|
149
|
+
}
|
|
150
|
+
return [...live.values()];
|
|
151
|
+
})
|
|
152
|
+
});
|
|
153
|
+
const memorySink = {
|
|
154
|
+
append: () => Effect.void,
|
|
155
|
+
replay: Effect.succeed([])
|
|
156
|
+
};
|
|
157
|
+
const makeWith = (options, sink) => {
|
|
158
|
+
const live = /* @__PURE__ */ new Map();
|
|
159
|
+
return ProcessLedger.of({
|
|
160
|
+
record: (spawned) => Effect.gen(function* () {
|
|
161
|
+
const startedAtMs = yield* Effect.clockWith((clock) => clock.currentTimeMillis);
|
|
162
|
+
const record = {
|
|
163
|
+
pid: spawned.pid,
|
|
164
|
+
pgid: spawned.pgid,
|
|
165
|
+
hostId: options.hostId,
|
|
166
|
+
ownerPid: options.ownerPid,
|
|
167
|
+
startedAtMs,
|
|
168
|
+
commandDigest: spawned.commandDigest
|
|
169
|
+
};
|
|
170
|
+
live.set(identity(record), record);
|
|
171
|
+
yield* sink.append(SpawnedEventType, record).pipe(
|
|
172
|
+
Effect.tapCause(() => Effect.sync(() => live.delete(identity(record))))
|
|
173
|
+
);
|
|
174
|
+
return record;
|
|
175
|
+
}),
|
|
176
|
+
release: (record) => Effect.suspend(() => {
|
|
177
|
+
live.delete(identity(record));
|
|
178
|
+
return sink.append(ExitedEventType, record);
|
|
179
|
+
}),
|
|
180
|
+
reaped: (record) => sink.append(ReapedEventType, record),
|
|
181
|
+
skipped: (record, reason) => sink.append(SkippedEventType, record, { reason }),
|
|
182
|
+
live: Effect.sync(() => [...live.values()]),
|
|
183
|
+
orphans: Effect.map(sink.replay, (records) => records.filter((record) => record.ownerPid !== options.ownerPid))
|
|
184
|
+
});
|
|
185
|
+
};
|
|
186
|
+
const make = (options) => Effect.map(JournalModule.Journal, (journal) => makeWith(options, journalSink(options, journal)));
|
|
187
|
+
const makeMemory = (options) => Effect.sync(() => makeWith(options, memorySink));
|
|
188
|
+
const layer = (options) => Layer.effect(ProcessLedger, make(options));
|
|
189
|
+
const layerMemory = (options) => Layer.effect(ProcessLedger, makeMemory(options));
|
|
190
|
+
//# sourceMappingURL=ProcessLedger.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/ProcessLedger.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * The host's ledger of the processes it spawned.\n *\n * A cancelled run must not leave a child agent running, and the engine cannot\n * do anything about that on its own: cancellation interrupts fibers, and a\n * fiber closing its scope only reaches the processes THIS incarnation of the\n * host still holds a handle for. A host that crashed left its children with no\n * one holding anything.\n *\n * The ledger is the missing half. Every spawn is recorded here in memory and\n * written to the journal as an ownerless durable record. It is ownerless\n * because it describes the host rather than a run, and first-writer-wins is\n * exactly the semantics a spawn record wants. The next incarnation of the same\n * `hostId` replays those records, subtracts the ones that reported an exit,\n * and is left with {@link Service.orphans}: the process groups a dead owner\n * abandoned, which a platform reaper can then signal.\n *\n * The kernel stays BELOW the engine: this module records pids and process\n * groups and knows nothing about runs, attempts, or ownership fences. It also\n * stays platform-neutral, because signalling a process group is a platform\n * concern and lives in `@smthrs/platform-node`.\n *\n * Governing design:\n * `docs/specs/Concepts/Host Adapters.md` and\n * `docs/specs/Concepts/Journal Queue.md`.\n *\n * @since 1.0.0-rc.0\n */\n\nimport * as JournalModule from \"@smthrs/journal/Journal\"\nimport type { JournalError } from \"@smthrs/journal/Journal\"\nimport * as JournalEvent from \"@smthrs/journal/JournalEvent\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Schema from \"effect/Schema\"\n\n/**\n * The event type recording that a host started a process.\n *\n * @category models\n * @since 1.0.0-rc.0\n */\nexport const SpawnedEventType = \"flows.host.process-spawned.v1\"\n\n/**\n * The event type recording that a recorded process ended.\n *\n * @category models\n * @since 1.0.0-rc.0\n */\nexport const ExitedEventType = \"flows.host.process-exited.v1\"\n\n/**\n * The event type recording that a later incarnation killed an abandoned\n * process group.\n *\n * @category models\n * @since 1.0.0-rc.0\n */\nexport const ReapedEventType = \"flows.host.process-reaped.v1\"\n\n/**\n * The event type recording that a later incarnation retired a record WITHOUT\n * signalling anything.\n *\n * A stored pid outlives the process that wrote it, so a reaper that cannot\n * prove the number still names the process the record describes must not\n * signal it. Retiring the record is still correct: nothing will ever be able\n * to prove it again, and leaving it would make every later incarnation\n * re-examine a number the operating system has moved on from.\n *\n * @category models\n * @since 1.0.0-rc.0\n */\nexport const SkippedEventType = \"flows.host.process-reap-skipped.v1\"\n\n/**\n * The producer id every ledger record is written under.\n *\n * Replay checks it: a record forged by another producer cannot make a host\n * signal a process group.\n *\n * @category models\n * @since 1.0.0-rc.0\n */\nexport const sourceId = \"@smthrs/kernel/ProcessLedger\"\n\n/**\n * The journal run a host's process records live on.\n *\n * Process records describe a host, not a run, so they get a run of their own,\n * named after the host. Two incarnations of one `hostId` therefore share a\n * history, which is what makes an abandoned process discoverable.\n *\n * @category constructors\n * @since 1.0.0-rc.0\n */\nexport const hostRunId = (hostId: string): JournalEvent.RunId => `flows.host:${hostId}` as JournalEvent.RunId\n\n/**\n * What the spawner knows about a process the moment it starts.\n *\n * `pgid` is `null` when the child shares the host's own process group. Such a\n * process cannot be group-signalled \u2014 signalling that group would signal the\n * host itself \u2014 so the ledger records the absence rather than a number a\n * reaper could misread.\n *\n * `commandDigest` names the executable and nothing else, as\n * `CommandLine.executable` renders it. Arguments carry credentials\n * (`curl -u user:password`, `mysql -phunter2`) and these records are permanent\n * journal entries, so the ledger never writes an argument down. A reader that\n * has to act on a record matches it by pid and process group; the program name\n * is there to make the row legible.\n *\n * @category models\n * @since 1.0.0-rc.0\n */\nexport interface Spawned {\n readonly pid: number\n readonly pgid: number | null\n readonly commandDigest: string\n}\n\n/**\n * Schema for a recorded process, as it round-trips through the journal.\n *\n * @category schemas\n * @since 1.0.0-rc.0\n */\nexport const ProcessRecord = Schema.Struct({\n pid: Schema.Int,\n pgid: Schema.NullOr(Schema.Int),\n hostId: Schema.String,\n ownerPid: Schema.Int,\n startedAtMs: Schema.Int,\n commandDigest: Schema.String\n})\n\n/**\n * One process a host started, with the identity of the incarnation that\n * started it.\n *\n * @category models\n * @since 1.0.0-rc.0\n */\nexport type ProcessRecord = typeof ProcessRecord.Type\n\n/**\n * Why a ledger history could not be replayed.\n *\n * - `journal_unreadable`: a page of the host's history could not be read.\n * - `cursor_stalled`: the journal reported more history but did not advance.\n *\n * @category models\n * @since 1.0.0-rc.1\n */\nexport const ProcessLedgerReplayErrorCode = Schema.Literals([\"journal_unreadable\", \"cursor_stalled\"])\n\n/**\n * The ledger could not read a previous incarnation's history to its end.\n *\n * An unread history is never reported as an empty one: a caller that treated\n * it as empty would leave every abandoned child running with no owner.\n *\n * @category errors\n * @since 1.0.0-rc.1\n */\nexport class ProcessLedgerReplayError extends Schema.TaggedError<ProcessLedgerReplayError>()(\n \"@smthrs/kernel/ProcessLedgerReplayError\",\n {\n code: ProcessLedgerReplayErrorCode,\n message: Schema.String,\n cause: Schema.optional(Schema.Defect())\n }\n) {}\n\nconst decodeRecord = Schema.decodeUnknownResult(ProcessRecord)\nconst encodeRecord = Schema.encodeSync(ProcessRecord)\n\n/**\n * Ledger operations.\n *\n * Every write that has a durable half REPORTS whether that half committed.\n * The in-memory set is still updated first, so a caller that decides to carry\n * on has an accurate view of this incarnation, but the failure is not\n * swallowed: a spawn whose record did not commit is a child that no later\n * incarnation can discover, which is the exact hole this ledger exists to\n * close. {@link ContainedSpawner} therefore refuses such a spawn, and the\n * reaper leaves a record it could not retire in place so a later incarnation\n * tries again.\n *\n * A ledger built with no journal ({@link makeMemory}) never fails: it promises\n * nothing durable in the first place.\n *\n * @category services\n * @since 1.0.0-rc.0\n */\nexport interface Service {\n /** Records a started process and returns the durable record written for it. */\n readonly record: (spawned: Spawned) => Effect.Effect<ProcessRecord, JournalError>\n /** Records that a process ended, and drops it from {@link Service.live}. */\n readonly release: (record: ProcessRecord) => Effect.Effect<void, JournalError>\n /** Records that an abandoned process group was signalled by this host. */\n readonly reaped: (record: ProcessRecord) => Effect.Effect<void, JournalError>\n /**\n * Retires a record this host refused to signal, naming why. The record\n * leaves {@link Service.orphans} without anything having been killed.\n */\n readonly skipped: (record: ProcessRecord, reason: string) => Effect.Effect<void, JournalError>\n /** The processes this incarnation started and has not yet released. */\n readonly live: Effect.Effect<ReadonlyArray<ProcessRecord>>\n /**\n * The processes a previous incarnation of this host left running.\n *\n * Fails when that history cannot be read to its end, so an unreadable\n * history is never mistaken for one with nothing left running.\n */\n readonly orphans: Effect.Effect<ReadonlyArray<ProcessRecord>, ProcessLedgerReplayError>\n}\n\n/**\n * The process-ledger service tag.\n *\n * @category services\n * @since 1.0.0-rc.0\n */\nexport class ProcessLedger extends Context.Service<ProcessLedger, Service>()(\"@smthrs/kernel/ProcessLedger\") {}\n\n/**\n * Ledger configuration.\n *\n * `hostId` is the durable identity two incarnations share; `ownerPid` is the\n * process id of THIS incarnation, which is how a replay tells its own live\n * processes from an abandoned one's.\n *\n * @category models\n * @since 1.0.0-rc.0\n */\nexport interface Options {\n readonly hostId: string\n readonly ownerPid: number\n}\n\n/** Where records are appended, and where a previous incarnation's are read. */\ninterface Sink {\n readonly append: (\n eventType: string,\n record: ProcessRecord,\n extra?: Record<string, unknown>\n ) => Effect.Effect<void, JournalError>\n readonly replay: Effect.Effect<ReadonlyArray<ProcessRecord>, ProcessLedgerReplayError>\n}\n\n/** The event types that retire a record from the inherited set. */\nconst retires = (eventType: string): boolean =>\n eventType === ExitedEventType || eventType === ReapedEventType || eventType === SkippedEventType\n\n/** A pid may be reused before the previous process's scope releases its record. */\nconst identity = (record: ProcessRecord): string => `${record.pid}:${record.startedAtMs}`\n\n/**\n * One entry folded onto the live set.\n *\n * Returns the entry when it is one of the ledger's own records but its payload\n * does not decode, so replay can report it. Such an entry names no process\n * that could be signalled, so failing the whole replay over it would stop\n * every later incarnation from reaping the well-formed records beside it.\n */\nconst apply = (live: Map<string, ProcessRecord>, entry: JournalEvent.Entry): JournalEvent.Entry | undefined => {\n if (entry.sourceId !== sourceId) return undefined\n if (entry.eventType !== SpawnedEventType && !retires(entry.eventType)) return undefined\n const decoded = decodeRecord(entry.payload)\n if (decoded._tag === \"Failure\") return entry\n if (entry.eventType === SpawnedEventType) {\n live.set(identity(decoded.success), decoded.success)\n return\n }\n live.delete(identity(decoded.success))\n return undefined\n}\n\nconst PAGE = 256\n\nconst journalSink = (options: Options, journal: JournalModule.Service): Sink => ({\n append: (eventType, record, extra) =>\n journal.emitDurableUnfenced(\n new JournalEvent.Input({\n runId: hostRunId(options.hostId),\n sourceId: sourceId as JournalEvent.SourceId,\n eventType,\n payload: extra === undefined ? encodeRecord(record) : { ...encodeRecord(record), ...extra }\n })\n ).pipe(\n // The failure is REPORTED, not logged away. A swallowed write leaves a\n // child that no incarnation of this host can discover, which is the one\n // outcome containment exists to prevent; the caller decides what to do\n // about it, and every caller in this repository declines to pretend the\n // process was recorded.\n Effect.tapCause((cause) => Effect.logWarning(`process ledger could not journal ${eventType}`, cause)),\n Effect.asVoid\n ),\n replay: Effect.gen(function*() {\n const live = new Map<string, ProcessRecord>()\n let after: JournalEvent.Seq | undefined\n for (;;) {\n const page = yield* journal.entries({\n runId: hostRunId(options.hostId),\n limit: PAGE,\n ...(after === undefined ? {} : { after })\n }).pipe(\n Effect.mapError((cause) =>\n new ProcessLedgerReplayError({\n code: \"journal_unreadable\",\n message: `process ledger could not read the history of host ${options.hostId}`,\n cause\n })\n )\n )\n for (const entry of page.entries) {\n const malformed = apply(live, entry)\n if (malformed !== undefined) {\n yield* Effect.logWarning(\n `process ledger skipped an undecodable ${malformed.eventType} record at seq ${malformed.seq}`\n )\n }\n }\n const last = page.entries.at(-1)\n if (last === undefined || !page.hasMore) break\n // A page that ends where the previous one did would be replayed\n // forever, and stopping there would report a partial history as whole.\n if (after !== undefined && last.seq <= after) {\n return yield* Effect.fail(\n new ProcessLedgerReplayError({\n code: \"cursor_stalled\",\n message: `process ledger history of host ${options.hostId} stopped advancing at seq ${last.seq}`\n })\n )\n }\n after = last.seq\n }\n return [...live.values()]\n })\n})\n\nconst memorySink: Sink = {\n append: () => Effect.void,\n replay: Effect.succeed([])\n}\n\nconst makeWith = (options: Options, sink: Sink): Service => {\n const live = new Map<string, ProcessRecord>()\n return ProcessLedger.of({\n record: (spawned) =>\n Effect.gen(function*() {\n const startedAtMs = yield* Effect.clockWith((clock) => clock.currentTimeMillis)\n const record: ProcessRecord = {\n pid: spawned.pid,\n pgid: spawned.pgid,\n hostId: options.hostId,\n ownerPid: options.ownerPid,\n startedAtMs,\n commandDigest: spawned.commandDigest\n }\n live.set(identity(record), record)\n // A failed append tells the caller the spawn was not recorded, and the\n // caller kills the child. Keeping it live would lie to every later\n // reader about a process this incarnation still holds.\n yield* sink.append(SpawnedEventType, record).pipe(\n Effect.tapCause(() => Effect.sync(() => live.delete(identity(record))))\n )\n return record\n }),\n release: (record) =>\n Effect.suspend(() => {\n live.delete(identity(record))\n return sink.append(ExitedEventType, record)\n }),\n reaped: (record) => sink.append(ReapedEventType, record),\n skipped: (record, reason) => sink.append(SkippedEventType, record, { reason }),\n live: Effect.sync(() => [...live.values()]),\n orphans: Effect.map(sink.replay, (records) => records.filter((record) => record.ownerPid !== options.ownerPid))\n })\n}\n\n/**\n * Builds a journal-backed ledger.\n *\n * @category constructors\n * @since 1.0.0-rc.0\n */\nexport const make = (options: Options): Effect.Effect<Service, never, JournalModule.Journal> =>\n Effect.map(JournalModule.Journal, (journal) => makeWith(options, journalSink(options, journal)))\n\n/**\n * Builds a ledger that records nothing durably.\n *\n * A host without a journal still contains the processes it holds handles for \u2014\n * scope closure does that \u2014 but it inherits nothing from a previous\n * incarnation, so {@link Service.orphans} is always empty.\n *\n * @category constructors\n * @since 1.0.0-rc.0\n */\nexport const makeMemory = (options: Options): Effect.Effect<Service> => Effect.sync(() => makeWith(options, memorySink))\n\n/**\n * Provides a journal-backed ledger.\n *\n * @category layers\n * @since 1.0.0-rc.0\n */\nexport const layer = (options: Options): Layer.Layer<ProcessLedger, never, JournalModule.Journal> =>\n Layer.effect(ProcessLedger, make(options))\n\n/**\n * Provides a ledger that records nothing durably.\n *\n * @category layers\n * @since 1.0.0-rc.0\n */\nexport const layerMemory = (options: Options): Layer.Layer<ProcessLedger> =>\n Layer.effect(ProcessLedger, makeMemory(options))\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;A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