@mark1russell7/service 0.8.19 → 0.9.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 -2
- package/build/backoff.d.ts +44 -2
- package/build/{builder-zO48Vgoj.d.ts → builder.d.ts} +14 -101
- package/build/builder.js +499 -0
- package/build/builder.js.map +1 -0
- package/build/{call-context-DDhcVvn5.d.ts → call-context.d.ts} +3 -4
- package/build/channel.d.ts +1 -1
- package/build/channel.js.map +1 -1
- package/build/{core-BSzt4RI2.d.ts → client/core.d.ts} +32 -61
- package/build/{machine-BhVeHr_m.js → client/core.js} +4 -153
- package/build/client/core.js.map +1 -0
- package/build/{dial-ChwIcvd4.d.ts → client/dial.d.ts} +3 -4
- package/build/client/dial.js +52 -0
- package/build/client/dial.js.map +1 -0
- package/build/client/machine.js +29 -0
- package/build/client/machine.js.map +1 -0
- package/build/client/meets.d.ts +35 -0
- package/build/client/meets.js +78 -0
- package/build/client/meets.js.map +1 -0
- package/build/clock.d.ts +2 -2
- package/build/clock.js +1 -1
- package/build/conformance.d.ts +122 -0
- package/build/conformance.js +469 -0
- package/build/conformance.js.map +1 -0
- package/build/contract.d.ts +28 -0
- package/build/contract.js +184 -0
- package/build/contract.js.map +1 -0
- package/build/description.d.ts +161 -0
- package/build/description.js +11 -0
- package/build/description.js.map +1 -0
- package/build/drains.js +35 -0
- package/build/drains.js.map +1 -0
- package/build/events.d.ts +25 -0
- package/build/fakes.d.ts +43 -0
- package/build/fakes.js +93 -0
- package/build/fakes.js.map +1 -0
- package/build/grpc/client.d.ts +153 -0
- package/build/grpc/client.js +474 -0
- package/build/grpc/client.js.map +1 -0
- package/build/grpc/connection.d.ts +97 -0
- package/build/grpc/connection.js +59 -0
- package/build/grpc/connection.js.map +1 -0
- package/build/grpc/machine.d.ts +12 -0
- package/build/grpc/machine.js +149 -0
- package/build/grpc/machine.js.map +1 -0
- package/build/grpc/meets.d.ts +14 -0
- package/build/grpc/meets.js +105 -0
- package/build/grpc/meets.js.map +1 -0
- package/build/grpc/starting.d.ts +33 -0
- package/build/grpc/starting.js +89 -0
- package/build/grpc/starting.js.map +1 -0
- package/build/grpc.d.ts +9 -303
- package/build/grpc.js +7 -854
- package/build/health.d.ts +93 -0
- package/build/health.js +225 -0
- package/build/health.js.map +1 -0
- package/build/heartbeat.d.ts +6 -2
- package/build/heartbeat.js.map +1 -1
- package/build/host/discovery.d.ts +61 -0
- package/build/host/discovery.js +113 -0
- package/build/host/discovery.js.map +1 -0
- package/build/host/env.d.ts +14 -0
- package/build/host/env.js +57 -0
- package/build/host/env.js.map +1 -0
- package/build/host/fakes.d.ts +82 -0
- package/build/host/fakes.js +239 -0
- package/build/host/fakes.js.map +1 -0
- package/build/host/group.d.ts +142 -0
- package/build/host/group.js +524 -0
- package/build/host/group.js.map +1 -0
- package/build/host/install.d.ts +96 -0
- package/build/host/install.js +330 -0
- package/build/host/install.js.map +1 -0
- package/build/host/lock.d.ts +78 -0
- package/build/host/lock.js +190 -0
- package/build/host/lock.js.map +1 -0
- package/build/host/logs.d.ts +26 -0
- package/build/host/logs.js +48 -0
- package/build/host/logs.js.map +1 -0
- package/build/host/node.d.ts +14 -0
- package/build/host/node.js +309 -0
- package/build/host/node.js.map +1 -0
- package/build/{ports-B1ayTL-j.d.ts → host/ports.d.ts} +15 -16
- package/build/host/ports.js +17 -0
- package/build/host/ports.js.map +1 -0
- package/build/host/probes.d.ts +51 -0
- package/build/host/probes.js +139 -0
- package/build/host/probes.js.map +1 -0
- package/build/host/processes.d.ts +32 -0
- package/build/host/processes.js +63 -0
- package/build/host/processes.js.map +1 -0
- package/build/host/render.d.ts +84 -0
- package/build/host/render.js +235 -0
- package/build/host/render.js.map +1 -0
- package/build/host/watch.d.ts +90 -0
- package/build/host/watch.js +165 -0
- package/build/host/watch.js.map +1 -0
- package/build/host.d.ts +13 -671
- package/build/host.js +12 -2126
- package/build/http/answers.js +29 -0
- package/build/http/answers.js.map +1 -0
- package/build/http/fake-server.js +61 -0
- package/build/http/fake-server.js.map +1 -0
- package/build/http/outcome.d.ts +115 -0
- package/build/http/outcome.js +325 -0
- package/build/http/outcome.js.map +1 -0
- package/build/http/probes.d.ts +83 -0
- package/build/http/probes.js +232 -0
- package/build/http/probes.js.map +1 -0
- package/build/http/transport.d.ts +165 -0
- package/build/http/transport.js +518 -0
- package/build/http/transport.js.map +1 -0
- package/build/http-client/client.d.ts +121 -0
- package/build/http-client/client.js +330 -0
- package/build/http-client/client.js.map +1 -0
- package/build/http-client/connection.d.ts +78 -0
- package/build/http-client/connection.js +54 -0
- package/build/http-client/connection.js.map +1 -0
- package/build/http-client/machine.d.ts +14 -0
- package/build/http-client/machine.js +109 -0
- package/build/http-client/machine.js.map +1 -0
- package/build/http-client/meets.d.ts +11 -0
- package/build/http-client/meets.js +74 -0
- package/build/http-client/meets.js.map +1 -0
- package/build/http-client/session.d.ts +87 -0
- package/build/http-client/session.js +99 -0
- package/build/http-client/session.js.map +1 -0
- package/build/http-client/starting.d.ts +25 -0
- package/build/http-client/starting.js +65 -0
- package/build/http-client/starting.js.map +1 -0
- package/build/http-client.d.ts +9 -330
- package/build/http-client.js +8 -707
- package/build/http.d.ts +5 -353
- package/build/http.js +3 -1086
- package/build/identity.d.ts +16 -0
- package/build/identity.js +44 -0
- package/build/identity.js.map +1 -0
- package/build/index.d.ts +35 -412
- package/build/index.js +25 -3278
- package/build/knobs.d.ts +1 -0
- package/build/{knobs-BJcz6m01.js → knobs.js} +2 -34
- package/build/knobs.js.map +1 -0
- package/build/latch.d.ts +29 -0
- package/build/latch.js +122 -0
- package/build/latch.js.map +1 -0
- package/build/{rules-HyFCBStQ.d.ts → law.d.ts} +19 -37
- package/build/law.js +149 -0
- package/build/law.js.map +1 -0
- package/build/lifecycle.d.ts +144 -0
- package/build/lifecycle.js +411 -0
- package/build/lifecycle.js.map +1 -0
- package/build/limiter/machine.d.ts +40 -0
- package/build/limiter/machine.js +279 -0
- package/build/limiter/machine.js.map +1 -0
- package/build/{policy-CBcK2XGg.d.ts → limiter/policy.d.ts} +28 -29
- package/build/{policy-UYALkqVq.js → limiter/policy.js} +10 -9
- package/build/limiter/policy.js.map +1 -0
- package/build/{limiter-BNKnwzeY.d.ts → limiter/quota.d.ts} +32 -74
- package/build/{limiter-DrM0PQV9.js → limiter/quota.js} +3 -418
- package/build/limiter/quota.js.map +1 -0
- package/build/{store-DFwFKrsB.d.ts → limiter/store.d.ts} +10 -11
- package/build/limiter/store.js +145 -0
- package/build/limiter/store.js.map +1 -0
- package/build/limiter.d.ts +4 -3
- package/build/limiter.js +4 -2
- package/build/lint.d.ts +152 -0
- package/build/lint.js +576 -0
- package/build/lint.js.map +1 -0
- package/build/logger.d.ts +71 -0
- package/build/logger.js +183 -0
- package/build/logger.js.map +1 -0
- package/build/machines.d.ts +41 -0
- package/build/machines.js +451 -0
- package/build/machines.js.map +1 -0
- package/build/metrics.d.ts +53 -0
- package/build/metrics.js +111 -0
- package/build/metrics.js.map +1 -0
- package/build/mongodb/client.d.ts +131 -0
- package/build/mongodb/client.js +388 -0
- package/build/mongodb/client.js.map +1 -0
- package/build/mongodb/connection.d.ts +112 -0
- package/build/mongodb/connection.js +12 -0
- package/build/mongodb/connection.js.map +1 -0
- package/build/mongodb/machine.d.ts +14 -0
- package/build/mongodb/machine.js +122 -0
- package/build/mongodb/machine.js.map +1 -0
- package/build/mongodb/meets.d.ts +15 -0
- package/build/mongodb/meets.js +103 -0
- package/build/mongodb/meets.js.map +1 -0
- package/build/mongodb/starting.d.ts +29 -0
- package/build/mongodb/starting.js +77 -0
- package/build/mongodb/starting.js.map +1 -0
- package/build/mongodb.d.ts +8 -296
- package/build/mongodb.js +7 -682
- package/build/operation.d.ts +27 -0
- package/build/{operation-DF73RZOI.js → operation.js} +2 -2
- package/build/operation.js.map +1 -0
- package/build/otel.d.ts +2 -2
- package/build/pg/client.d.ts +96 -0
- package/build/pg/client.js +277 -0
- package/build/pg/client.js.map +1 -0
- package/build/pg/connection.d.ts +75 -0
- package/build/pg/connection.js +11 -0
- package/build/pg/connection.js.map +1 -0
- package/build/pg/machine.d.ts +13 -0
- package/build/pg/machine.js +111 -0
- package/build/pg/machine.js.map +1 -0
- package/build/pg/meets.d.ts +14 -0
- package/build/pg/meets.js +83 -0
- package/build/pg/meets.js.map +1 -0
- package/build/pg/starting.d.ts +26 -0
- package/build/pg/starting.js +62 -0
- package/build/pg/starting.js.map +1 -0
- package/build/pg.d.ts +8 -219
- package/build/pg.js +7 -525
- package/build/poller.d.ts +9 -0
- package/build/poller.js +154 -0
- package/build/poller.js.map +1 -0
- package/build/process.d.ts +114 -0
- package/build/process.js +170 -0
- package/build/process.js.map +1 -0
- package/build/profiles.d.ts +68 -0
- package/build/profiles.js +120 -0
- package/build/profiles.js.map +1 -0
- package/build/{queue-DXdw1vLO.d.ts → queue.d.ts} +16 -29
- package/build/queue.js +279 -0
- package/build/queue.js.map +1 -0
- package/build/rabbitmq/client.d.ts +144 -0
- package/build/rabbitmq/client.js +426 -0
- package/build/rabbitmq/client.js.map +1 -0
- package/build/rabbitmq/connection.d.ts +91 -0
- package/build/rabbitmq/connection.js +15 -0
- package/build/rabbitmq/connection.js.map +1 -0
- package/build/rabbitmq/machine.d.ts +13 -0
- package/build/rabbitmq/machine.js +159 -0
- package/build/rabbitmq/machine.js.map +1 -0
- package/build/rabbitmq/meets.d.ts +12 -0
- package/build/rabbitmq/meets.js +96 -0
- package/build/rabbitmq/meets.js.map +1 -0
- package/build/rabbitmq/starting.d.ts +27 -0
- package/build/rabbitmq/starting.js +67 -0
- package/build/rabbitmq/starting.js.map +1 -0
- package/build/rabbitmq.d.ts +8 -283
- package/build/rabbitmq.js +7 -742
- package/build/redis/client.d.ts +86 -0
- package/build/redis/client.js +285 -0
- package/build/redis/client.js.map +1 -0
- package/build/redis/connection.d.ts +57 -0
- package/build/redis/connection.js +11 -0
- package/build/redis/connection.js.map +1 -0
- package/build/redis/limiter.d.ts +43 -0
- package/build/redis/limiter.js +164 -0
- package/build/redis/limiter.js.map +1 -0
- package/build/redis/machine.d.ts +12 -0
- package/build/redis/machine.js +144 -0
- package/build/redis/machine.js.map +1 -0
- package/build/redis/meets.d.ts +11 -0
- package/build/redis/meets.js +75 -0
- package/build/redis/meets.js.map +1 -0
- package/build/redis/operations.d.ts +5 -0
- package/build/redis/operations.js +114 -0
- package/build/redis/operations.js.map +1 -0
- package/build/redis.d.ts +10 -207
- package/build/redis.js +9 -771
- package/build/requests.d.ts +66 -0
- package/build/requests.js +279 -0
- package/build/requests.js.map +1 -0
- package/build/retrier.d.ts +62 -0
- package/build/{retrier-Dnjhvxol.js → retrier.js} +2 -2
- package/build/retrier.js.map +1 -0
- package/build/routes.d.ts +35 -0
- package/build/routes.js +77 -0
- package/build/routes.js.map +1 -0
- package/build/rules.d.ts +19 -2
- package/build/stops.d.ts +51 -0
- package/build/stops.js +86 -0
- package/build/stops.js.map +1 -0
- package/build/testing.d.ts +8 -270
- package/build/testing.js +4 -1027
- package/build/testing.js.map +1 -1
- package/build/timing.d.ts +63 -0
- package/build/{timing-DZl36uXs.js → timing.js} +2 -2
- package/build/timing.js.map +1 -0
- package/build/units.d.ts +17 -0
- package/build/units.js +236 -0
- package/build/units.js.map +1 -0
- package/build/watchdog.d.ts +38 -0
- package/build/watchdog.js +57 -0
- package/build/watchdog.js.map +1 -0
- package/build/websocket/client.d.ts +136 -0
- package/build/websocket/client.js +422 -0
- package/build/websocket/client.js.map +1 -0
- package/build/websocket/connection.d.ts +83 -0
- package/build/websocket/connection.js +57 -0
- package/build/websocket/connection.js.map +1 -0
- package/build/websocket/machine.d.ts +12 -0
- package/build/websocket/machine.js +155 -0
- package/build/websocket/machine.js.map +1 -0
- package/build/websocket/meets.d.ts +14 -0
- package/build/websocket/meets.js +92 -0
- package/build/websocket/meets.js.map +1 -0
- package/build/websocket/starting.d.ts +25 -0
- package/build/websocket/starting.js +69 -0
- package/build/websocket/starting.js.map +1 -0
- package/build/websocket.d.ts +9 -264
- package/build/websocket.js +8 -774
- package/build/worker.d.ts +92 -0
- package/build/worker.js +153 -0
- package/build/worker.js.map +1 -0
- package/package.json +5 -4
- package/build/backoff-QTRGfkEK.d.ts +0 -45
- package/build/clock-DpVgpY4h.d.ts +0 -2
- package/build/grpc.js.map +0 -1
- package/build/host.js.map +0 -1
- package/build/http-client.js.map +0 -1
- package/build/http.js.map +0 -1
- package/build/index.js.map +0 -1
- package/build/knobs-BJcz6m01.js.map +0 -1
- package/build/lifecycle-D0J-zwZF.d.ts +0 -374
- package/build/limiter-DrM0PQV9.js.map +0 -1
- package/build/logger-B6drv9w0.d.ts +0 -488
- package/build/machine-BhVeHr_m.js.map +0 -1
- package/build/mongodb.js.map +0 -1
- package/build/operation-DF73RZOI.js.map +0 -1
- package/build/pg.js.map +0 -1
- package/build/policy-UYALkqVq.js.map +0 -1
- package/build/process-7R9M29wN.js +0 -437
- package/build/process-7R9M29wN.js.map +0 -1
- package/build/rabbitmq.js.map +0 -1
- package/build/redis.js.map +0 -1
- package/build/requests-DD2ALv0_.js +0 -583
- package/build/requests-DD2ALv0_.js.map +0 -1
- package/build/retrier-Dnjhvxol.js.map +0 -1
- package/build/timing-DZl36uXs.js.map +0 -1
- package/build/websocket.js.map +0 -1
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { sameProcess } from "./processes.js";
|
|
2
|
+
import { delay } from "@mark1russell7/algebra/clock";
|
|
3
|
+
// src/host/lock.ts
|
|
4
|
+
const isMark = (value) => {
|
|
5
|
+
if (typeof value !== "object" || value === null) return false;
|
|
6
|
+
const { pid, startedAt } = value;
|
|
7
|
+
return typeof pid === "number" && Number.isInteger(pid) && pid > 0 && typeof startedAt === "number" && Number.isFinite(startedAt);
|
|
8
|
+
};
|
|
9
|
+
/** This function reads a lock owner from the text of a lock file, or gives null for a text that is not a record. */
|
|
10
|
+
const parseLockOwner = (text) => {
|
|
11
|
+
try {
|
|
12
|
+
const value = JSON.parse(text);
|
|
13
|
+
if (!isMark(value)) return null;
|
|
14
|
+
const child = value.child;
|
|
15
|
+
if (child !== void 0 && child !== null && !isMark(child)) return null;
|
|
16
|
+
return {
|
|
17
|
+
pid: value.pid,
|
|
18
|
+
startedAt: value.startedAt,
|
|
19
|
+
...isMark(child) ? { child: {
|
|
20
|
+
pid: child.pid,
|
|
21
|
+
startedAt: child.startedAt
|
|
22
|
+
} } : {}
|
|
23
|
+
};
|
|
24
|
+
} catch {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
/** This function gives the text of a lock file for an owner. */
|
|
29
|
+
const lockText = (owner) => `${JSON.stringify(owner)}\n`;
|
|
30
|
+
/** This function tells if the owner of a lock is alive: its process, or its child. */
|
|
31
|
+
const ownerAlive = async (owner, ports) => await sameProcess(owner, ports) || owner.child !== void 0 && await sameProcess(owner.child, ports);
|
|
32
|
+
/**
|
|
33
|
+
* This function removes a file only when it has this text: a lock file or a discovery file. The
|
|
34
|
+
* removal holds the removal lock `<path>.rm` for its read and its delete. Thus two processes that find
|
|
35
|
+
* the same stale file do not remove each other's new file. A removal lock whose owner stopped goes first.
|
|
36
|
+
*/
|
|
37
|
+
const removeIfSame = async (path, text, ports) => {
|
|
38
|
+
const removal = `${path}.rm`;
|
|
39
|
+
const mine = lockText({
|
|
40
|
+
pid: ports.self.pid,
|
|
41
|
+
startedAt: ports.self.startedAt
|
|
42
|
+
});
|
|
43
|
+
if (!await ports.files.create(removal, mine)) {
|
|
44
|
+
const other = parseLockOwner(await ports.files.read(removal) ?? "");
|
|
45
|
+
if (other !== null && await ownerAlive(other, ports)) return false;
|
|
46
|
+
await ports.files.remove(removal);
|
|
47
|
+
if (!await ports.files.create(removal, mine)) return false;
|
|
48
|
+
}
|
|
49
|
+
try {
|
|
50
|
+
if (await ports.files.read(path) !== text) return false;
|
|
51
|
+
await ports.files.remove(path);
|
|
52
|
+
return true;
|
|
53
|
+
} finally {
|
|
54
|
+
if (await ports.files.read(removal) === mine) await ports.files.remove(removal);
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
/** This function examines a lock file. It does not throw. */
|
|
58
|
+
const inspectInstanceLock = async (path, ports) => {
|
|
59
|
+
try {
|
|
60
|
+
const text = await ports.files.read(path);
|
|
61
|
+
if (text === null) return { kind: "free" };
|
|
62
|
+
const owner = parseLockOwner(text);
|
|
63
|
+
if (owner === null) return {
|
|
64
|
+
kind: "malformed",
|
|
65
|
+
problem: "the lock file is not a lock record"
|
|
66
|
+
};
|
|
67
|
+
if (await ownerAlive(owner, ports)) return {
|
|
68
|
+
kind: "held",
|
|
69
|
+
owner
|
|
70
|
+
};
|
|
71
|
+
return {
|
|
72
|
+
kind: "stale",
|
|
73
|
+
owner,
|
|
74
|
+
why: `the owner process ${owner.pid} stopped`
|
|
75
|
+
};
|
|
76
|
+
} catch (error) {
|
|
77
|
+
return {
|
|
78
|
+
kind: "malformed",
|
|
79
|
+
problem: `the read failed: ${error instanceof Error ? error.message : String(error)}`
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
/**
|
|
84
|
+
* This function takes the lock of one instance: a lock file with the record of this process. Thus a
|
|
85
|
+
* second instance does not start. It does not throw.
|
|
86
|
+
* - A file whose owner and child stopped is stale: it goes, and the take tries again.
|
|
87
|
+
* - A malformed file can be the file of a take that writes at this time. The take reads it again after
|
|
88
|
+
* a pause, and after `tries` reads, it removes it.
|
|
89
|
+
* - A file whose owner or child is alive gives `held`.
|
|
90
|
+
*/
|
|
91
|
+
const acquireInstanceLock = async (path, ports, options = {}) => {
|
|
92
|
+
const tries = options.tries ?? 3;
|
|
93
|
+
const pause = options.pause ?? 100;
|
|
94
|
+
const owner = {
|
|
95
|
+
pid: ports.self.pid,
|
|
96
|
+
startedAt: ports.self.startedAt,
|
|
97
|
+
...options.child === void 0 ? {} : { child: options.child }
|
|
98
|
+
};
|
|
99
|
+
let recovered = null;
|
|
100
|
+
let malformed = 0;
|
|
101
|
+
try {
|
|
102
|
+
for (let attempt = 0; attempt < tries + 3; attempt += 1) {
|
|
103
|
+
const text = lockText(owner);
|
|
104
|
+
if (await ports.files.create(path, text)) {
|
|
105
|
+
ports.logger?.log("info", `the host took the lock ${path}`, {
|
|
106
|
+
path,
|
|
107
|
+
pid: owner.pid,
|
|
108
|
+
...recovered === null ? {} : { recovered }
|
|
109
|
+
});
|
|
110
|
+
return {
|
|
111
|
+
kind: "acquired",
|
|
112
|
+
lock: held(path, owner, text, ports),
|
|
113
|
+
recovered
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
const found = await ports.files.read(path);
|
|
117
|
+
if (found === null) continue;
|
|
118
|
+
const other = parseLockOwner(found);
|
|
119
|
+
if (other === null) {
|
|
120
|
+
malformed += 1;
|
|
121
|
+
if (malformed < tries) {
|
|
122
|
+
await delay(ports.clock, pause);
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
if (await removeIfSame(path, found, ports)) recovered = "the lock file was not a lock record";
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
if (await ownerAlive(other, ports)) return {
|
|
129
|
+
kind: "held",
|
|
130
|
+
owner: other
|
|
131
|
+
};
|
|
132
|
+
if (await removeIfSame(path, found, ports)) {
|
|
133
|
+
recovered = `the owner process ${other.pid} stopped`;
|
|
134
|
+
ports.logger?.log("warn", `the host removed the stale lock ${path}: ${recovered}`, {
|
|
135
|
+
path,
|
|
136
|
+
owner: other
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return {
|
|
141
|
+
kind: "failed",
|
|
142
|
+
problem: `the lock ${path} did not come free after ${tries + 3} tries`
|
|
143
|
+
};
|
|
144
|
+
} catch (error) {
|
|
145
|
+
return {
|
|
146
|
+
kind: "failed",
|
|
147
|
+
problem: `the file system failed: ${error instanceof Error ? error.message : String(error)}`
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
/** This function gives the handle of a lock that this process holds. */
|
|
152
|
+
const held = (path, first, firstText, ports) => {
|
|
153
|
+
let owner = first;
|
|
154
|
+
let text = firstText;
|
|
155
|
+
let released = false;
|
|
156
|
+
let queue = Promise.resolve();
|
|
157
|
+
const enqueue = (work) => {
|
|
158
|
+
const next = queue.then(work);
|
|
159
|
+
queue = next.catch(() => {});
|
|
160
|
+
return next;
|
|
161
|
+
};
|
|
162
|
+
return {
|
|
163
|
+
path,
|
|
164
|
+
get owner() {
|
|
165
|
+
return owner;
|
|
166
|
+
},
|
|
167
|
+
update: (child) => enqueue(async () => {
|
|
168
|
+
if (released) return;
|
|
169
|
+
const next = {
|
|
170
|
+
pid: owner.pid,
|
|
171
|
+
startedAt: owner.startedAt,
|
|
172
|
+
...child === null ? {} : { child }
|
|
173
|
+
};
|
|
174
|
+
const nextText = lockText(next);
|
|
175
|
+
await ports.files.write(path, nextText);
|
|
176
|
+
owner = next;
|
|
177
|
+
text = nextText;
|
|
178
|
+
}),
|
|
179
|
+
release: () => enqueue(async () => {
|
|
180
|
+
if (released) return;
|
|
181
|
+
released = true;
|
|
182
|
+
try {
|
|
183
|
+
await removeIfSame(path, text, ports);
|
|
184
|
+
} catch {}
|
|
185
|
+
})
|
|
186
|
+
};
|
|
187
|
+
};
|
|
188
|
+
export { acquireInstanceLock, inspectInstanceLock, lockText, parseLockOwner, removeIfSame };
|
|
189
|
+
|
|
190
|
+
//# sourceMappingURL=lock.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lock.js","names":[],"sources":["../../src/host/lock.ts"],"sourcesContent":["import { delay } from \"@mark1russell7/algebra/clock\";\nimport type { HostPorts, ProcessMark } from \"./ports.ts\";\nimport { sameProcess } from \"./processes.ts\";\n\n/**\n * A lock owner is the record in a lock file: the process that holds the lock. The record can also\n * have the child process that it holds the lock for. The lock is held while one of the two is alive.\n */\nexport interface LockOwner extends ProcessMark {\n readonly child?: ProcessMark | undefined;\n}\n\n/** An instance lock is a lock that this process holds. */\nexport interface InstanceLock {\n readonly path: string;\n readonly owner: LockOwner;\n /** This method writes a new child process in the record, or no child with null. */\n update(child: ProcessMark | null): Promise<void>;\n /** This method removes the lock file, when it still has the record of this lock. A second use does nothing. */\n release(): Promise<void>;\n}\n\n/**\n * A lock result tells what a try to take the lock found.\n * - `acquired`: this process holds the lock. `recovered` tells why a stale lock went first, or it is null.\n * - `held`: a live process holds the lock. Its owner is in the result.\n * - `failed`: the lock did not come free, or the file system failed. The problem tells why.\n */\nexport type LockResult =\n | { readonly kind: \"acquired\"; readonly lock: InstanceLock; readonly recovered: string | null }\n | { readonly kind: \"held\"; readonly owner: LockOwner }\n | { readonly kind: \"failed\"; readonly problem: string };\n\n/**\n * A lock state is what an examination of a lock file found. An examination does not throw.\n * - `free`: no file.\n * - `held`: the record names a live process.\n * - `stale`: the record names processes that stopped. The next take removes the file.\n * - `malformed`: the file is not a record, or the read failed.\n */\nexport type LockState =\n | { readonly kind: \"free\" }\n | { readonly kind: \"held\"; readonly owner: LockOwner }\n | { readonly kind: \"stale\"; readonly owner: LockOwner; readonly why: string }\n | { readonly kind: \"malformed\"; readonly problem: string };\n\n/** These options go with a take of the lock. */\nexport interface LockOptions {\n /** This count is the number of reads of a malformed file before the take removes it. The default is 3. */\n readonly tries?: number | undefined;\n /** This time is the pause between two reads of a malformed file, in milliseconds. The default is 100. */\n readonly pause?: number | undefined;\n /** This child process goes in the record at the take. */\n readonly child?: ProcessMark | undefined;\n}\n\nconst isMark = (value: unknown): value is ProcessMark => {\n if (typeof value !== \"object\" || value === null) return false;\n const { pid, startedAt } = value as { pid?: unknown; startedAt?: unknown };\n return typeof pid === \"number\" && Number.isInteger(pid) && pid > 0 && typeof startedAt === \"number\" && Number.isFinite(startedAt);\n};\n\n/** This function reads a lock owner from the text of a lock file, or gives null for a text that is not a record. */\nexport const parseLockOwner = (text: string): LockOwner | null => {\n try {\n const value = JSON.parse(text) as unknown;\n if (!isMark(value)) return null;\n const child = (value as { child?: unknown }).child;\n if (child !== undefined && child !== null && !isMark(child)) return null;\n return { pid: value.pid, startedAt: value.startedAt, ...(isMark(child) ? { child: { pid: child.pid, startedAt: child.startedAt } } : {}) };\n } catch {\n return null;\n }\n};\n\n/** This function gives the text of a lock file for an owner. */\nexport const lockText = (owner: LockOwner): string => `${JSON.stringify(owner)}\\n`;\n\n/** This function tells if the owner of a lock is alive: its process, or its child. */\nconst ownerAlive = async (owner: LockOwner, ports: HostPorts): Promise<boolean> =>\n (await sameProcess(owner, ports)) || (owner.child !== undefined && (await sameProcess(owner.child, ports)));\n\n/**\n * This function removes a file only when it has this text: a lock file or a discovery file. The\n * removal holds the removal lock `<path>.rm` for its read and its delete. Thus two processes that find\n * the same stale file do not remove each other's new file. A removal lock whose owner stopped goes first.\n */\nexport const removeIfSame = async (path: string, text: string, ports: HostPorts): Promise<boolean> => {\n const removal = `${path}.rm`;\n const mine = lockText({ pid: ports.self.pid, startedAt: ports.self.startedAt });\n if (!(await ports.files.create(removal, mine))) {\n const other = parseLockOwner((await ports.files.read(removal)) ?? \"\");\n if (other !== null && (await ownerAlive(other, ports))) return false;\n await ports.files.remove(removal);\n if (!(await ports.files.create(removal, mine))) return false;\n }\n try {\n if ((await ports.files.read(path)) !== text) return false;\n await ports.files.remove(path);\n return true;\n } finally {\n if ((await ports.files.read(removal)) === mine) await ports.files.remove(removal);\n }\n};\n\n/** This function examines a lock file. It does not throw. */\nexport const inspectInstanceLock = async (path: string, ports: HostPorts): Promise<LockState> => {\n try {\n const text = await ports.files.read(path);\n if (text === null) return { kind: \"free\" };\n const owner = parseLockOwner(text);\n if (owner === null) return { kind: \"malformed\", problem: \"the lock file is not a lock record\" };\n if (await ownerAlive(owner, ports)) return { kind: \"held\", owner };\n return { kind: \"stale\", owner, why: `the owner process ${owner.pid} stopped` };\n } catch (error) {\n return { kind: \"malformed\", problem: `the read failed: ${error instanceof Error ? error.message : String(error)}` };\n }\n};\n\n/**\n * This function takes the lock of one instance: a lock file with the record of this process. Thus a\n * second instance does not start. It does not throw.\n * - A file whose owner and child stopped is stale: it goes, and the take tries again.\n * - A malformed file can be the file of a take that writes at this time. The take reads it again after\n * a pause, and after `tries` reads, it removes it.\n * - A file whose owner or child is alive gives `held`.\n */\nexport const acquireInstanceLock = async (path: string, ports: HostPorts, options: LockOptions = {}): Promise<LockResult> => {\n const tries = options.tries ?? 3;\n const pause = options.pause ?? 100;\n const owner: LockOwner = { pid: ports.self.pid, startedAt: ports.self.startedAt, ...(options.child === undefined ? {} : { child: options.child }) };\n let recovered: string | null = null;\n let malformed = 0;\n try {\n for (let attempt = 0; attempt < tries + 3; attempt += 1) {\n const text = lockText(owner);\n if (await ports.files.create(path, text)) {\n ports.logger?.log(\"info\", `the host took the lock ${path}`, { path, pid: owner.pid, ...(recovered === null ? {} : { recovered }) });\n return { kind: \"acquired\", lock: held(path, owner, text, ports), recovered };\n }\n const found = await ports.files.read(path);\n if (found === null) continue;\n const other = parseLockOwner(found);\n if (other === null) {\n malformed += 1;\n if (malformed < tries) {\n await delay(ports.clock, pause);\n continue;\n }\n if (await removeIfSame(path, found, ports)) recovered = \"the lock file was not a lock record\";\n continue;\n }\n if (await ownerAlive(other, ports)) return { kind: \"held\", owner: other };\n if (await removeIfSame(path, found, ports)) {\n recovered = `the owner process ${other.pid} stopped`;\n ports.logger?.log(\"warn\", `the host removed the stale lock ${path}: ${recovered}`, { path, owner: other });\n }\n }\n return { kind: \"failed\", problem: `the lock ${path} did not come free after ${tries + 3} tries` };\n } catch (error) {\n return { kind: \"failed\", problem: `the file system failed: ${error instanceof Error ? error.message : String(error)}` };\n }\n};\n\n/** This function gives the handle of a lock that this process holds. */\nconst held = (path: string, first: LockOwner, firstText: string, ports: HostPorts): InstanceLock => {\n let owner = first;\n let text = firstText;\n let released = false;\n // the updates and the release occur in sequence, thus a late write does not make the file again after the release\n let queue: Promise<void> = Promise.resolve();\n const enqueue = (work: () => Promise<void>): Promise<void> => {\n const next = queue.then(work);\n queue = next.catch(() => {});\n return next;\n };\n return {\n path,\n get owner() {\n return owner;\n },\n update: (child) =>\n enqueue(async () => {\n if (released) return;\n const next: LockOwner = { pid: owner.pid, startedAt: owner.startedAt, ...(child === null ? {} : { child }) };\n const nextText = lockText(next);\n await ports.files.write(path, nextText);\n owner = next;\n text = nextText;\n }),\n release: () =>\n enqueue(async () => {\n if (released) return;\n released = true;\n try {\n await removeIfSame(path, text, ports);\n } catch {\n // a lock file that stays is stale after the exit of this process\n }\n }),\n };\n};\n"],"mappings":";;;AAwDA,MAAM,UAAU,UAAyC;CACvD,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,MAAM,EAAE,KAAK,cAAc;CAC3B,OAAO,OAAO,QAAQ,YAAY,OAAO,UAAU,GAAG,KAAK,MAAM,KAAK,OAAO,cAAc,YAAY,OAAO,SAAS,SAAS;AAClI;;AAGA,MAAa,kBAAkB,SAAmC;CAChE,IAAI;EACF,MAAM,QAAQ,KAAK,MAAM,IAAI;EAC7B,IAAI,CAAC,OAAO,KAAK,GAAG,OAAO;EAC3B,MAAM,QAAS,MAA8B;EAC7C,IAAI,UAAU,KAAA,KAAa,UAAU,QAAQ,CAAC,OAAO,KAAK,GAAG,OAAO;EACpE,OAAO;GAAE,KAAK,MAAM;GAAK,WAAW,MAAM;GAAW,GAAI,OAAO,KAAK,IAAI,EAAE,OAAO;IAAE,KAAK,MAAM;IAAK,WAAW,MAAM;GAAU,EAAE,IAAI,CAAC;EAAG;CAC3I,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,MAAa,YAAY,UAA6B,GAAG,KAAK,UAAU,KAAK,EAAE;;AAG/E,MAAM,aAAa,OAAO,OAAkB,UACzC,MAAM,YAAY,OAAO,KAAK,KAAO,MAAM,UAAU,KAAA,KAAc,MAAM,YAAY,MAAM,OAAO,KAAK;;;;;;AAO1G,MAAa,eAAe,OAAO,MAAc,MAAc,UAAuC;CACpG,MAAM,UAAU,GAAG,KAAK;CACxB,MAAM,OAAO,SAAS;EAAE,KAAK,MAAM,KAAK;EAAK,WAAW,MAAM,KAAK;CAAU,CAAC;CAC9E,IAA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AAQ,MAAc,OAAkB,WAAmB,UAAmC;CAClG,IAAI,QAAQ;CACZ,IAAI,OAAO;CACX,IAAI,WAAW;CAEf,IAAI,QAAuB,QAAQ,QAAQ;CAC3C,MAAM,WAAW,SAA6C;EAC5D,MAAM,OAAO,MAAM,KAAK,IAAI;EAC5B,QAAQ,KAAK,YAAY,CAAC,CAAC;EAC3B,OAAO;CACT;CACA,OAAO;EACL;EACA,IAAI,QAAQ;GACV,OAAO;EACT;EACA,SAAS,UACP,QAAQ,YAAY;GAClB,IAAI,UAAU;GACd,MAAM,OAAkB;IAAE,KAAK,MAAM;IAAK,WAAW,MAAM;IAAW,GAAI,UAAU,OAAO,CAAC,IAAI,EAAE,MAAM;GAAG;GAC3G,MAAM,WAAW,SAAS,IAAI;GAC9B,MAAM,MAAM,MAAM,MAAM,MAAM,QAAQ;GACtC,QAAQ;GACR,OAAO;EACT,CAAC;EACH,eACE,QAAQ,YAAY;GAClB,IAAI,UAAU;GACd,WAAW;GACX,IAAI;IACF,MAAM,aAAa,MAAM,MAAM,KAAK;GACtC,QAAQ,CAER;EACF,CAAC;CACL;AACF"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { FilePort } from "./ports.js";
|
|
2
|
+
import { Quantity } from "@mark1russell7/quantity";
|
|
3
|
+
/** A log spec tells where the output of a program goes, and when the file rotates. */
|
|
4
|
+
export interface LogSpec {
|
|
5
|
+
/** This path is the log file. */
|
|
6
|
+
readonly path: string;
|
|
7
|
+
/** This size is the most that the file gets before it rotates, for example `{ value: 10, unit: "MB" }`. */
|
|
8
|
+
readonly maxSize: Quantity;
|
|
9
|
+
/** This count is the number of old files that stay: `<path>.1` is the newest. 0 keeps no old file. */
|
|
10
|
+
readonly keep: number;
|
|
11
|
+
}
|
|
12
|
+
/** A rotating log writes data to a file, and rotates the file at its size. */
|
|
13
|
+
export interface RotatingLog {
|
|
14
|
+
/** This method adds data to the log. The writes occur in sequence. A failed write does not throw. */
|
|
15
|
+
write(chunk: string | Uint8Array): void;
|
|
16
|
+
/** This promise ends when each write before it is done. */
|
|
17
|
+
flush(): Promise<void>;
|
|
18
|
+
/** This count is the number of writes that failed. */
|
|
19
|
+
readonly failures: number;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* This function makes a rotating log on a file port. Before a write that makes the file larger than
|
|
23
|
+
* `maxSize`, the file rotates: `<path>.<keep>` goes, each `<path>.<n>` becomes `<path>.<n + 1>`, and the
|
|
24
|
+
* file becomes `<path>.1`. A chunk larger than the size goes into a new file of its own.
|
|
25
|
+
*/
|
|
26
|
+
export declare const rotatingLog: (spec: LogSpec, files: FilePort) => RotatingLog;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { valueIn } from "@mark1russell7/quantity";
|
|
2
|
+
// src/host/logs.ts
|
|
3
|
+
const byteLength = (chunk) => typeof chunk === "string" ? new TextEncoder().encode(chunk).length : chunk.length;
|
|
4
|
+
/**
|
|
5
|
+
* This function makes a rotating log on a file port. Before a write that makes the file larger than
|
|
6
|
+
* `maxSize`, the file rotates: `<path>.<keep>` goes, each `<path>.<n>` becomes `<path>.<n + 1>`, and the
|
|
7
|
+
* file becomes `<path>.1`. A chunk larger than the size goes into a new file of its own.
|
|
8
|
+
*/
|
|
9
|
+
const rotatingLog = (spec, files) => {
|
|
10
|
+
const max = valueIn(spec.maxSize, "B");
|
|
11
|
+
let chain = Promise.resolve();
|
|
12
|
+
let size = null;
|
|
13
|
+
let failures = 0;
|
|
14
|
+
const rotate = async () => {
|
|
15
|
+
if (spec.keep <= 0) {
|
|
16
|
+
await files.remove(spec.path);
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
await files.remove(`${spec.path}.${spec.keep}`);
|
|
20
|
+
for (let at = spec.keep - 1; at >= 1; at -= 1) if (await files.size(`${spec.path}.${at}`) !== null) await files.rename(`${spec.path}.${at}`, `${spec.path}.${at + 1}`);
|
|
21
|
+
await files.rename(spec.path, `${spec.path}.1`);
|
|
22
|
+
};
|
|
23
|
+
const append = async (chunk) => {
|
|
24
|
+
const length = byteLength(chunk);
|
|
25
|
+
size ??= await files.size(spec.path) ?? 0;
|
|
26
|
+
if (size > 0 && size + length > max) {
|
|
27
|
+
await rotate();
|
|
28
|
+
size = 0;
|
|
29
|
+
}
|
|
30
|
+
await files.append(spec.path, chunk);
|
|
31
|
+
size += length;
|
|
32
|
+
};
|
|
33
|
+
return {
|
|
34
|
+
write(chunk) {
|
|
35
|
+
chain = chain.then(() => append(chunk)).catch(() => {
|
|
36
|
+
failures += 1;
|
|
37
|
+
size = null;
|
|
38
|
+
});
|
|
39
|
+
},
|
|
40
|
+
flush: () => chain,
|
|
41
|
+
get failures() {
|
|
42
|
+
return failures;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
};
|
|
46
|
+
export { rotatingLog };
|
|
47
|
+
|
|
48
|
+
//# sourceMappingURL=logs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"logs.js","names":[],"sources":["../../src/host/logs.ts"],"sourcesContent":["import type { Quantity } from \"@mark1russell7/quantity\";\nimport { valueIn } from \"@mark1russell7/quantity\";\nimport type { FilePort } from \"./ports.ts\";\n\n/** A log spec tells where the output of a program goes, and when the file rotates. */\nexport interface LogSpec {\n /** This path is the log file. */\n readonly path: string;\n /** This size is the most that the file gets before it rotates, for example `{ value: 10, unit: \"MB\" }`. */\n readonly maxSize: Quantity;\n /** This count is the number of old files that stay: `<path>.1` is the newest. 0 keeps no old file. */\n readonly keep: number;\n}\n\n/** A rotating log writes data to a file, and rotates the file at its size. */\nexport interface RotatingLog {\n /** This method adds data to the log. The writes occur in sequence. A failed write does not throw. */\n write(chunk: string | Uint8Array): void;\n /** This promise ends when each write before it is done. */\n flush(): Promise<void>;\n /** This count is the number of writes that failed. */\n readonly failures: number;\n}\n\nconst byteLength = (chunk: string | Uint8Array): number => (typeof chunk === \"string\" ? new TextEncoder().encode(chunk).length : chunk.length);\n\n/**\n * This function makes a rotating log on a file port. Before a write that makes the file larger than\n * `maxSize`, the file rotates: `<path>.<keep>` goes, each `<path>.<n>` becomes `<path>.<n + 1>`, and the\n * file becomes `<path>.1`. A chunk larger than the size goes into a new file of its own.\n */\nexport const rotatingLog = (spec: LogSpec, files: FilePort): RotatingLog => {\n const max = valueIn(spec.maxSize, \"B\");\n let chain: Promise<void> = Promise.resolve();\n let size: number | null = null;\n let failures = 0;\n const rotate = async (): Promise<void> => {\n if (spec.keep <= 0) {\n await files.remove(spec.path);\n return;\n }\n await files.remove(`${spec.path}.${spec.keep}`);\n for (let at = spec.keep - 1; at >= 1; at -= 1)\n if ((await files.size(`${spec.path}.${at}`)) !== null) await files.rename(`${spec.path}.${at}`, `${spec.path}.${at + 1}`);\n await files.rename(spec.path, `${spec.path}.1`);\n };\n const append = async (chunk: string | Uint8Array): Promise<void> => {\n const length = byteLength(chunk);\n size ??= (await files.size(spec.path)) ?? 0;\n if (size > 0 && size + length > max) {\n await rotate();\n size = 0;\n }\n await files.append(spec.path, chunk);\n size += length;\n };\n return {\n write(chunk) {\n chain = chain.then(() => append(chunk)).catch(() => {\n failures += 1;\n // the size is not known after a failure: the next write reads it again\n size = null;\n });\n },\n flush: () => chain,\n get failures() {\n return failures;\n },\n };\n};\n"],"mappings":";;AAwBA,MAAM,cAAc,UAAwC,OAAO,UAAU,WAAW,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,SAAS,MAAM;;;;;;AAOvI,MAAa,eAAe,MAAe,UAAiC;CAC1E,MAAM,MAAM,QAAQ,KAAK,SAAS,GAAG;CACrC,IAAI,QAAuB,QAAQ,QAAQ;CAC3C,IAAI,OAAsB;CAC1B,IAAI,WAAW;CACf,MAAM,SAAS,YAA2B;EACxC,IAAI,KAAK,QAAQ,GAAG;GAClB,MAAM,MAAM,OAAO,KAAK,IAAI;GAC5B;EACF;EACA,MAAM,MAAM,OAAO,GAAG,KAAK,KAAK,GAAG,KAAK,MAAM;EAC9C,KAAK,IAAI,KAAK,KAAK,OAAO,GAAG,MAAM,GAAG,MAAM,GAC1C,IAAK,MAAM,MAAM,KAAK,GAAG,KAAK,KAAK,GAAG,IAAI,MAAO,MAAM,MAAM,MAAM,OAAO,GAAG,KAAK,KAAK,GAAG,MAAM,GAAG,KAAK,KAAK,GAAG,KAAK,GAAG;EAC1H,MAAM,MAAM,OAAO,KAAK,MAAM,GAAG,KAAK,KAAK,GAAG;CAChD;CACA,MAAM,SAAS,OAAO,UAA8C;EAClE,MAAM,SAAS,WAAW,KAAK;EAC/B,SAAU,MAAM,MAAM,KAAK,KAAK,IAAI,KAAM;EAC1C,IAAI,OAAO,KAAK,OAAO,SAAS,KAAK;GACnC,MAAM,OAAO;GACb,OAAO;EACT;EACA,MAAM,MAAM,OAAO,KAAK,MAAM,KAAK;EACnC,QAAQ;CACV;CACA,OAAO;EACL,MAAM,OAAO;GACX,QAAQ,MAAM,WAAW,OAAO,KAAK,CAAC,CAAC,CAAC,YAAY;IAClD,YAAY;IAEZ,OAAO;GACT,CAAC;EACH;EACA,aAAa;EACb,IAAI,WAAW;GACb,OAAO;EACT;CACF;AACF"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { Clock } from "../clock.js";
|
|
2
|
+
import { Logger } from "../logger.js";
|
|
3
|
+
import { HostPorts } from "./ports.js";
|
|
4
|
+
/** These options go with the ports of Node. */
|
|
5
|
+
export interface NodeHostOptions {
|
|
6
|
+
readonly logger?: Logger | undefined;
|
|
7
|
+
/** This clock gives the time and the timers. The default is `realClock`. */
|
|
8
|
+
readonly clock?: Clock | undefined;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* This function gives the host ports of Node: `child_process`, `fs/promises`, `net`, `fetch` and `process`.
|
|
12
|
+
* Only a program uses it. A test gives `fakeHost()` of `./testing`, thus it starts no process and installs no task.
|
|
13
|
+
*/
|
|
14
|
+
export declare const nodeHostPorts: (options?: NodeHostOptions) => HostPorts;
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
import { realClock } from "../clock.js";
|
|
2
|
+
import { connect } from "node:net";
|
|
3
|
+
import { execFile, spawn } from "node:child_process";
|
|
4
|
+
import { appendFile, mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
5
|
+
import { homedir, userInfo } from "node:os";
|
|
6
|
+
import { dirname } from "node:path";
|
|
7
|
+
// src/host/node.ts
|
|
8
|
+
const codeOf = (error) => typeof error === "object" && error !== null && "code" in error ? String(error.code) : void 0;
|
|
9
|
+
const missing = (error) => codeOf(error) === "ENOENT";
|
|
10
|
+
const nodeCommands = { run: (file, args, options = {}) => new Promise((resolve) => {
|
|
11
|
+
execFile(file, [...args], {
|
|
12
|
+
...options.cwd === void 0 ? {} : { cwd: options.cwd },
|
|
13
|
+
timeout: options.timeout ?? 0,
|
|
14
|
+
windowsHide: true,
|
|
15
|
+
encoding: "utf8",
|
|
16
|
+
maxBuffer: 16777216
|
|
17
|
+
}, (error, stdout, stderr) => {
|
|
18
|
+
const out = `${stdout}${stderr}`;
|
|
19
|
+
if (error === null) {
|
|
20
|
+
resolve({
|
|
21
|
+
code: 0,
|
|
22
|
+
out
|
|
23
|
+
});
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
if (missing(error)) resolve({
|
|
27
|
+
code: 127,
|
|
28
|
+
out: error.message
|
|
29
|
+
});
|
|
30
|
+
else if (error.killed === true && options.timeout !== void 0) resolve({
|
|
31
|
+
code: 124,
|
|
32
|
+
out
|
|
33
|
+
});
|
|
34
|
+
else resolve({
|
|
35
|
+
code: typeof error.code === "number" ? error.code : 1,
|
|
36
|
+
out: out === "" ? error.message : out
|
|
37
|
+
});
|
|
38
|
+
});
|
|
39
|
+
}) };
|
|
40
|
+
let serial = 0;
|
|
41
|
+
const nodeFiles = {
|
|
42
|
+
async read(path) {
|
|
43
|
+
try {
|
|
44
|
+
return await readFile(path, "utf8");
|
|
45
|
+
} catch (error) {
|
|
46
|
+
if (missing(error)) return null;
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
async write(path, data) {
|
|
51
|
+
await mkdir(dirname(path), { recursive: true });
|
|
52
|
+
serial += 1;
|
|
53
|
+
const temporary = `${path}.${process.pid}.${serial}.tmp`;
|
|
54
|
+
await writeFile(temporary, data);
|
|
55
|
+
try {
|
|
56
|
+
await rename(temporary, path);
|
|
57
|
+
} catch (error) {
|
|
58
|
+
await rm(temporary, { force: true });
|
|
59
|
+
throw error;
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
async create(path, data) {
|
|
63
|
+
await mkdir(dirname(path), { recursive: true });
|
|
64
|
+
try {
|
|
65
|
+
await writeFile(path, data, { flag: "wx" });
|
|
66
|
+
return true;
|
|
67
|
+
} catch (error) {
|
|
68
|
+
if (codeOf(error) === "EEXIST") return false;
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
async append(path, data) {
|
|
73
|
+
await mkdir(dirname(path), { recursive: true });
|
|
74
|
+
await appendFile(path, data);
|
|
75
|
+
},
|
|
76
|
+
async size(path) {
|
|
77
|
+
try {
|
|
78
|
+
return (await stat(path)).size;
|
|
79
|
+
} catch (error) {
|
|
80
|
+
if (missing(error)) return null;
|
|
81
|
+
throw error;
|
|
82
|
+
}
|
|
83
|
+
},
|
|
84
|
+
rename: (from, to) => rename(from, to),
|
|
85
|
+
remove: (path) => rm(path, { force: true })
|
|
86
|
+
};
|
|
87
|
+
/** This difference is the time from the start of the Windows file time (1601) to the start of the epoch (1970), in milliseconds. */
|
|
88
|
+
const FILETIME_EPOCH_MS = 11644473600000n;
|
|
89
|
+
/**
|
|
90
|
+
* This limit is the longest time of the query of a start time on Windows, in milliseconds. A cold start of PowerShell
|
|
91
|
+
* on a loaded host can take more than 10 seconds (SYS-47). After the limit the start time is null, and the lock then
|
|
92
|
+
* counts a live process ID as its owner. Thus a short limit can hold a stale lock, and the limit is wide.
|
|
93
|
+
*/
|
|
94
|
+
const WINDOWS_START_LIMIT_MS = 3e4;
|
|
95
|
+
/** This function gives the start time of a Windows process from PowerShell, in milliseconds after the epoch, or null. */
|
|
96
|
+
const windowsStart = async (pid) => {
|
|
97
|
+
const result = await nodeCommands.run("powershell.exe", [
|
|
98
|
+
"-NoProfile",
|
|
99
|
+
"-NonInteractive",
|
|
100
|
+
"-Command",
|
|
101
|
+
`(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToFileTimeUtc()`
|
|
102
|
+
], { timeout: WINDOWS_START_LIMIT_MS });
|
|
103
|
+
const text = result.out.trim();
|
|
104
|
+
if (result.code !== 0 || !/^\d+$/.test(text)) return null;
|
|
105
|
+
return Number(BigInt(text) / 10000n - FILETIME_EPOCH_MS);
|
|
106
|
+
};
|
|
107
|
+
/** This count is the number of clock ticks in one second on Linux. It is 100 on each common kernel. */
|
|
108
|
+
const LINUX_TICKS = 100;
|
|
109
|
+
/** This function gives the start time of a Linux process from `/proc`, in milliseconds after the epoch, or null. */
|
|
110
|
+
const linuxStart = async (pid) => {
|
|
111
|
+
const record = await readFile(`/proc/${pid}/stat`, "utf8");
|
|
112
|
+
const fields = record.slice(record.lastIndexOf(")") + 2).split(" ");
|
|
113
|
+
const ticks = Number(fields[19]);
|
|
114
|
+
const boot = /^btime (\d+)$/m.exec(await readFile("/proc/stat", "utf8"));
|
|
115
|
+
if (!Number.isFinite(ticks) || boot === null) return null;
|
|
116
|
+
return Number(boot[1]) * 1e3 + ticks * 1e3 / LINUX_TICKS;
|
|
117
|
+
};
|
|
118
|
+
const sendSignal = (pid, signal) => {
|
|
119
|
+
try {
|
|
120
|
+
return process.kill(pid, signal);
|
|
121
|
+
} catch {
|
|
122
|
+
return false;
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
const nodeSpawn = (request) => {
|
|
126
|
+
const outputs = [];
|
|
127
|
+
const exits = [];
|
|
128
|
+
let end = null;
|
|
129
|
+
const finish = (code, signal) => {
|
|
130
|
+
if (end !== null) return;
|
|
131
|
+
end = {
|
|
132
|
+
code,
|
|
133
|
+
signal
|
|
134
|
+
};
|
|
135
|
+
for (const handler of exits) handler(code, signal);
|
|
136
|
+
};
|
|
137
|
+
const child = spawn(request.program, [...request.args], {
|
|
138
|
+
...request.cwd === void 0 ? {} : { cwd: request.cwd },
|
|
139
|
+
env: { ...request.env },
|
|
140
|
+
stdio: request.ipc ? [
|
|
141
|
+
"ignore",
|
|
142
|
+
"pipe",
|
|
143
|
+
"pipe",
|
|
144
|
+
"ipc"
|
|
145
|
+
] : [
|
|
146
|
+
"ignore",
|
|
147
|
+
"pipe",
|
|
148
|
+
"pipe"
|
|
149
|
+
],
|
|
150
|
+
detached: process.platform !== "win32",
|
|
151
|
+
windowsHide: true
|
|
152
|
+
});
|
|
153
|
+
child.stdout?.on("data", (chunk) => {
|
|
154
|
+
for (const handler of outputs) handler("stdout", chunk);
|
|
155
|
+
});
|
|
156
|
+
child.stderr?.on("data", (chunk) => {
|
|
157
|
+
for (const handler of outputs) handler("stderr", chunk);
|
|
158
|
+
});
|
|
159
|
+
child.on("error", () => {
|
|
160
|
+
if (child.pid === void 0) finish(null, null);
|
|
161
|
+
});
|
|
162
|
+
child.on("exit", (code, signal) => finish(code, signal));
|
|
163
|
+
return {
|
|
164
|
+
pid: child.pid ?? null,
|
|
165
|
+
ipc: request.ipc,
|
|
166
|
+
onOutput(handler) {
|
|
167
|
+
outputs.push(handler);
|
|
168
|
+
},
|
|
169
|
+
onExit(handler) {
|
|
170
|
+
exits.push(handler);
|
|
171
|
+
if (end !== null) handler(end.code, end.signal);
|
|
172
|
+
},
|
|
173
|
+
send(message) {
|
|
174
|
+
if (!child.connected) return false;
|
|
175
|
+
try {
|
|
176
|
+
return child.send(message);
|
|
177
|
+
} catch {
|
|
178
|
+
return false;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
};
|
|
183
|
+
const nodeProcesses = {
|
|
184
|
+
alive(pid) {
|
|
185
|
+
try {
|
|
186
|
+
process.kill(pid, 0);
|
|
187
|
+
return true;
|
|
188
|
+
} catch (error) {
|
|
189
|
+
return codeOf(error) === "EPERM";
|
|
190
|
+
}
|
|
191
|
+
},
|
|
192
|
+
async startOf(pid) {
|
|
193
|
+
try {
|
|
194
|
+
if (process.platform === "win32") return await windowsStart(pid);
|
|
195
|
+
if (process.platform === "linux") return await linuxStart(pid);
|
|
196
|
+
return null;
|
|
197
|
+
} catch {
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
},
|
|
201
|
+
signal: (pid, signal) => sendSignal(pid, signal),
|
|
202
|
+
signalGroup: (pid, signal) => process.platform !== "win32" && sendSignal(-pid, signal),
|
|
203
|
+
spawn: nodeSpawn
|
|
204
|
+
};
|
|
205
|
+
/**
|
|
206
|
+
* This function sends a GET request that does not follow a redirect. The timeout also stops the
|
|
207
|
+
* read of the body. The status read and the text read use it, thus they have one timeout.
|
|
208
|
+
*/
|
|
209
|
+
const get = (url, timeout) => fetch(url, {
|
|
210
|
+
signal: AbortSignal.timeout(timeout),
|
|
211
|
+
redirect: "manual"
|
|
212
|
+
});
|
|
213
|
+
/**
|
|
214
|
+
* This function reads the body of an answer up to `limit` bytes, and gives the status and the text.
|
|
215
|
+
* At the limit, it cancels the body, and `complete` is false. The decoder keeps the bytes of a
|
|
216
|
+
* character that two parts of the body split. The unit tests give it answers with no network.
|
|
217
|
+
*/
|
|
218
|
+
const answerText = async (response, limit) => {
|
|
219
|
+
const reader = response.body?.getReader();
|
|
220
|
+
if (reader === void 0) return {
|
|
221
|
+
status: response.status,
|
|
222
|
+
body: "",
|
|
223
|
+
complete: true
|
|
224
|
+
};
|
|
225
|
+
const decoder = new TextDecoder();
|
|
226
|
+
let body = "";
|
|
227
|
+
let size = 0;
|
|
228
|
+
for (;;) {
|
|
229
|
+
const read = await reader.read();
|
|
230
|
+
if (read.done) return {
|
|
231
|
+
status: response.status,
|
|
232
|
+
body: body + decoder.decode(),
|
|
233
|
+
complete: true
|
|
234
|
+
};
|
|
235
|
+
if (size + read.value.byteLength > limit) {
|
|
236
|
+
body += decoder.decode(read.value.subarray(0, limit - size));
|
|
237
|
+
await reader.cancel();
|
|
238
|
+
return {
|
|
239
|
+
status: response.status,
|
|
240
|
+
body,
|
|
241
|
+
complete: false
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
body += decoder.decode(read.value, { stream: true });
|
|
245
|
+
size += read.value.byteLength;
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
const nodeNet = {
|
|
249
|
+
async httpStatus(url, timeout) {
|
|
250
|
+
try {
|
|
251
|
+
const response = await get(url, timeout);
|
|
252
|
+
await response.body?.cancel();
|
|
253
|
+
return response.status;
|
|
254
|
+
} catch {
|
|
255
|
+
return null;
|
|
256
|
+
}
|
|
257
|
+
},
|
|
258
|
+
async httpText(url, timeout, limit) {
|
|
259
|
+
try {
|
|
260
|
+
return await answerText(await get(url, timeout), limit);
|
|
261
|
+
} catch {
|
|
262
|
+
return null;
|
|
263
|
+
}
|
|
264
|
+
},
|
|
265
|
+
tcpConnect: (host, port, timeout) => new Promise((resolve) => {
|
|
266
|
+
const socket = connect({
|
|
267
|
+
host,
|
|
268
|
+
port
|
|
269
|
+
});
|
|
270
|
+
const done = (open) => {
|
|
271
|
+
socket.destroy();
|
|
272
|
+
resolve(open);
|
|
273
|
+
};
|
|
274
|
+
socket.setTimeout(timeout, () => done(false));
|
|
275
|
+
socket.once("connect", () => done(true));
|
|
276
|
+
socket.once("error", () => done(false));
|
|
277
|
+
})
|
|
278
|
+
};
|
|
279
|
+
/**
|
|
280
|
+
* This function gives the host ports of Node: `child_process`, `fs/promises`, `net`, `fetch` and `process`.
|
|
281
|
+
* Only a program uses it. A test gives `fakeHost()` of `./testing`, thus it starts no process and installs no task.
|
|
282
|
+
*/
|
|
283
|
+
const nodeHostPorts = (options = {}) => {
|
|
284
|
+
const user = () => {
|
|
285
|
+
const name = userInfo().username;
|
|
286
|
+
const domain = process.env["USERDOMAIN"];
|
|
287
|
+
return process.platform === "win32" && domain !== void 0 && domain !== "" ? `${domain}\\${name}` : name;
|
|
288
|
+
};
|
|
289
|
+
return {
|
|
290
|
+
platform: process.platform,
|
|
291
|
+
commands: nodeCommands,
|
|
292
|
+
files: nodeFiles,
|
|
293
|
+
processes: nodeProcesses,
|
|
294
|
+
net: nodeNet,
|
|
295
|
+
clock: options.clock ?? realClock,
|
|
296
|
+
wall: () => Date.now(),
|
|
297
|
+
self: {
|
|
298
|
+
pid: process.pid,
|
|
299
|
+
startedAt: Math.round(Date.now() - process.uptime() * 1e3)
|
|
300
|
+
},
|
|
301
|
+
env: process.env,
|
|
302
|
+
homeDir: homedir(),
|
|
303
|
+
user,
|
|
304
|
+
...options.logger === void 0 ? {} : { logger: options.logger }
|
|
305
|
+
};
|
|
306
|
+
};
|
|
307
|
+
export { answerText, nodeHostPorts };
|
|
308
|
+
|
|
309
|
+
//# sourceMappingURL=node.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"node.js","names":["spawnChild"],"sources":["../../src/host/node.ts"],"sourcesContent":["import type { Serializable } from \"node:child_process\";\nimport { execFile, spawn as spawnChild } from \"node:child_process\";\nimport { appendFile, mkdir, readFile, rename, rm, stat, writeFile } from \"node:fs/promises\";\nimport { connect } from \"node:net\";\nimport { homedir, userInfo } from \"node:os\";\nimport { dirname } from \"node:path\";\nimport type { Clock } from \"../clock.ts\";\nimport { realClock } from \"../clock.ts\";\nimport type { Logger } from \"../logger.ts\";\nimport type { ChildHandle, CommandPort, FilePort, HostPorts, HttpAnswer, NetPort, ProcessesPort, SpawnRequest, StopSignal } from \"./ports.ts\";\n\n/** These options go with the ports of Node. */\nexport interface NodeHostOptions {\n readonly logger?: Logger | undefined;\n /** This clock gives the time and the timers. The default is `realClock`. */\n readonly clock?: Clock | undefined;\n}\n\nconst codeOf = (error: unknown): string | undefined =>\n typeof error === \"object\" && error !== null && \"code\" in error ? String((error as { code: unknown }).code) : undefined;\n\nconst missing = (error: unknown): boolean => codeOf(error) === \"ENOENT\";\n\nconst nodeCommands: CommandPort = {\n run: (file, args, options = {}) =>\n new Promise((resolve) => {\n execFile(\n file,\n [...args],\n { ...(options.cwd === undefined ? {} : { cwd: options.cwd }), timeout: options.timeout ?? 0, windowsHide: true, encoding: \"utf8\", maxBuffer: 16 * 1024 * 1024 },\n (error, stdout, stderr) => {\n const out = `${stdout}${stderr}`;\n if (error === null) {\n resolve({ code: 0, out });\n return;\n }\n if (missing(error)) resolve({ code: 127, out: error.message });\n else if (error.killed === true && options.timeout !== undefined) resolve({ code: 124, out });\n else resolve({ code: typeof error.code === \"number\" ? error.code : 1, out: out === \"\" ? error.message : out });\n },\n );\n }),\n};\n\nlet serial = 0;\n\nconst nodeFiles: FilePort = {\n async read(path) {\n try {\n return await readFile(path, \"utf8\");\n } catch (error) {\n if (missing(error)) return null;\n throw error;\n }\n },\n async write(path, data) {\n await mkdir(dirname(path), { recursive: true });\n serial += 1;\n const temporary = `${path}.${process.pid}.${serial}.tmp`;\n await writeFile(temporary, data);\n try {\n await rename(temporary, path);\n } catch (error) {\n await rm(temporary, { force: true });\n throw error;\n }\n },\n async create(path, data) {\n await mkdir(dirname(path), { recursive: true });\n try {\n await writeFile(path, data, { flag: \"wx\" });\n return true;\n } catch (error) {\n if (codeOf(error) === \"EEXIST\") return false;\n throw error;\n }\n },\n async append(path, data) {\n await mkdir(dirname(path), { recursive: true });\n await appendFile(path, data);\n },\n async size(path) {\n try {\n return (await stat(path)).size;\n } catch (error) {\n if (missing(error)) return null;\n throw error;\n }\n },\n rename: (from, to) => rename(from, to),\n remove: (path) => rm(path, { force: true }),\n};\n\n/** This difference is the time from the start of the Windows file time (1601) to the start of the epoch (1970), in milliseconds. */\nconst FILETIME_EPOCH_MS = 11_644_473_600_000n;\n\n/**\n * This limit is the longest time of the query of a start time on Windows, in milliseconds. A cold start of PowerShell\n * on a loaded host can take more than 10 seconds (SYS-47). After the limit the start time is null, and the lock then\n * counts a live process ID as its owner. Thus a short limit can hold a stale lock, and the limit is wide.\n */\nconst WINDOWS_START_LIMIT_MS = 30_000;\n\n/** This function gives the start time of a Windows process from PowerShell, in milliseconds after the epoch, or null. */\nconst windowsStart = async (pid: number): Promise<number | null> => {\n const result = await nodeCommands.run(\n \"powershell.exe\",\n [\"-NoProfile\", \"-NonInteractive\", \"-Command\", `(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToFileTimeUtc()`],\n { timeout: WINDOWS_START_LIMIT_MS },\n );\n const text = result.out.trim();\n if (result.code !== 0 || !/^\\d+$/.test(text)) return null;\n return Number(BigInt(text) / 10_000n - FILETIME_EPOCH_MS);\n};\n\n/** This count is the number of clock ticks in one second on Linux. It is 100 on each common kernel. */\nconst LINUX_TICKS = 100;\n\n/** This function gives the start time of a Linux process from `/proc`, in milliseconds after the epoch, or null. */\nconst linuxStart = async (pid: number): Promise<number | null> => {\n const record = await readFile(`/proc/${pid}/stat`, \"utf8\");\n // the name of the program is in parentheses and can have spaces: the fields start after the last \")\"\n const fields = record.slice(record.lastIndexOf(\")\") + 2).split(\" \");\n const ticks = Number(fields[19]);\n const boot = /^btime (\\d+)$/m.exec(await readFile(\"/proc/stat\", \"utf8\"));\n if (!Number.isFinite(ticks) || boot === null) return null;\n return Number(boot[1]) * 1000 + (ticks * 1000) / LINUX_TICKS;\n};\n\nconst sendSignal = (pid: number, signal: StopSignal | 0): boolean => {\n try {\n return process.kill(pid, signal);\n } catch {\n return false;\n }\n};\n\nconst nodeSpawn = (request: SpawnRequest): ChildHandle => {\n const outputs: Array<(stream: \"stdout\" | \"stderr\", chunk: string | Uint8Array) => void> = [];\n const exits: Array<(code: number | null, signal: string | null) => void> = [];\n let end: { code: number | null; signal: string | null } | null = null;\n const finish = (code: number | null, signal: string | null): void => {\n if (end !== null) return;\n end = { code, signal };\n for (const handler of exits) handler(code, signal);\n };\n const child = spawnChild(request.program, [...request.args], {\n ...(request.cwd === undefined ? {} : { cwd: request.cwd }),\n env: { ...request.env },\n stdio: request.ipc ? [\"ignore\", \"pipe\", \"pipe\", \"ipc\"] : [\"ignore\", \"pipe\", \"pipe\"],\n // on Linux the child leads its own process group, thus the tree stop reaches each process under it\n detached: process.platform !== \"win32\",\n windowsHide: true,\n });\n child.stdout?.on(\"data\", (chunk: Uint8Array) => {\n for (const handler of outputs) handler(\"stdout\", chunk);\n });\n child.stderr?.on(\"data\", (chunk: Uint8Array) => {\n for (const handler of outputs) handler(\"stderr\", chunk);\n });\n child.on(\"error\", () => {\n if (child.pid === undefined) finish(null, null);\n });\n child.on(\"exit\", (code, signal) => finish(code, signal));\n return {\n pid: child.pid ?? null,\n ipc: request.ipc,\n onOutput(handler) {\n outputs.push(handler);\n },\n onExit(handler) {\n exits.push(handler);\n if (end !== null) handler(end.code, end.signal);\n },\n send(message) {\n if (!child.connected) return false;\n try {\n return child.send(message as Serializable);\n } catch {\n return false;\n }\n },\n };\n};\n\nconst nodeProcesses: ProcessesPort = {\n alive(pid) {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n // a process of a different user is alive, and the signal does not go to it\n return codeOf(error) === \"EPERM\";\n }\n },\n async startOf(pid) {\n try {\n if (process.platform === \"win32\") return await windowsStart(pid);\n if (process.platform === \"linux\") return await linuxStart(pid);\n return null;\n } catch {\n return null;\n }\n },\n signal: (pid, signal) => sendSignal(pid, signal),\n signalGroup: (pid, signal) => process.platform !== \"win32\" && sendSignal(-pid, signal),\n spawn: nodeSpawn,\n};\n\n/**\n * This function sends a GET request that does not follow a redirect. The timeout also stops the\n * read of the body. The status read and the text read use it, thus they have one timeout.\n */\nconst get = (url: string, timeout: number): Promise<Response> => fetch(url, { signal: AbortSignal.timeout(timeout), redirect: \"manual\" });\n\n/**\n * This function reads the body of an answer up to `limit` bytes, and gives the status and the text.\n * At the limit, it cancels the body, and `complete` is false. The decoder keeps the bytes of a\n * character that two parts of the body split. The unit tests give it answers with no network.\n */\nexport const answerText = async (response: Response, limit: number): Promise<HttpAnswer> => {\n const reader = response.body?.getReader();\n if (reader === undefined) return { status: response.status, body: \"\", complete: true };\n const decoder = new TextDecoder();\n let body = \"\";\n let size = 0;\n for (;;) {\n const read = await reader.read();\n if (read.done) return { status: response.status, body: body + decoder.decode(), complete: true };\n if (size + read.value.byteLength > limit) {\n body += decoder.decode(read.value.subarray(0, limit - size));\n await reader.cancel();\n return { status: response.status, body, complete: false };\n }\n body += decoder.decode(read.value, { stream: true });\n size += read.value.byteLength;\n }\n};\n\nconst nodeNet: NetPort = {\n async httpStatus(url, timeout) {\n try {\n const response = await get(url, timeout);\n await response.body?.cancel();\n return response.status;\n } catch {\n return null;\n }\n },\n async httpText(url, timeout, limit) {\n try {\n return await answerText(await get(url, timeout), limit);\n } catch {\n return null;\n }\n },\n tcpConnect: (host, port, timeout) =>\n new Promise((resolve) => {\n const socket = connect({ host, port });\n const done = (open: boolean): void => {\n socket.destroy();\n resolve(open);\n };\n socket.setTimeout(timeout, () => done(false));\n socket.once(\"connect\", () => done(true));\n socket.once(\"error\", () => done(false));\n }),\n};\n\n/**\n * This function gives the host ports of Node: `child_process`, `fs/promises`, `net`, `fetch` and `process`.\n * Only a program uses it. A test gives `fakeHost()` of `./testing`, thus it starts no process and installs no task.\n */\nexport const nodeHostPorts = (options: NodeHostOptions = {}): HostPorts => {\n const user = (): string => {\n const name = userInfo().username;\n const domain = process.env[\"USERDOMAIN\"];\n return process.platform === \"win32\" && domain !== undefined && domain !== \"\" ? `${domain}\\\\${name}` : name;\n };\n return {\n platform: process.platform,\n commands: nodeCommands,\n files: nodeFiles,\n processes: nodeProcesses,\n net: nodeNet,\n clock: options.clock ?? realClock,\n wall: () => Date.now(),\n self: { pid: process.pid, startedAt: Math.round(Date.now() - process.uptime() * 1000) },\n env: process.env,\n homeDir: homedir(),\n user,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n };\n};\n"],"mappings":";;;;;;;AAkBA,MAAM,UAAU,UACd,OAAO,UAAU,YAAY,UAAU,QAAQ,UAAU,QAAQ,OAAQ,MAA4B,IAAI,IAAI,KAAA;AAE/G,M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