@capybara-hq/device 0.1.0-rc.0 → 0.1.0-rc.10
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 +187 -44
- package/dist/api.d.ts +6 -1
- package/dist/args.d.ts +14 -3
- package/dist/args.js +74 -10
- package/dist/cli.d.ts +14 -2
- package/dist/cli.js +59 -10
- package/dist/client.d.ts +14 -3
- package/dist/client.js +92 -18
- package/dist/command-log.d.ts +8 -0
- package/dist/commands/drain.d.ts +13 -0
- package/dist/commands/drain.js +28 -0
- package/dist/commands/login.js +68 -11
- package/dist/commands/mode.d.ts +52 -0
- package/dist/commands/mode.js +108 -0
- package/dist/commands/policy.d.ts +13 -4
- package/dist/commands/policy.js +162 -33
- package/dist/commands/service.d.ts +18 -3
- package/dist/commands/service.js +175 -9
- package/dist/commands/start.d.ts +14 -3
- package/dist/commands/start.js +37 -5
- package/dist/commands/status.js +12 -4
- package/dist/commands/stop.d.ts +9 -2
- package/dist/commands/stop.js +13 -2
- package/dist/exec/docker.d.ts +41 -13
- package/dist/exec/docker.js +123 -57
- package/dist/exec/fs-helper.d.ts +13 -8
- package/dist/exec/fs-helper.js +31 -13
- package/dist/exec/groups.d.ts +42 -0
- package/dist/exec/groups.js +100 -0
- package/dist/exec/host.d.ts +53 -0
- package/dist/exec/host.js +183 -0
- package/dist/exec/os.d.ts +85 -15
- package/dist/exec/os.js +208 -36
- package/dist/exec/reap.d.ts +41 -0
- package/dist/exec/reap.js +89 -0
- package/dist/exec/sandbox-messages.d.ts +14 -0
- package/dist/exec/sandbox-messages.js +21 -0
- package/dist/exec/shared.d.ts +42 -13
- package/dist/exec/shared.js +94 -16
- package/dist/exec/switch.d.ts +91 -0
- package/dist/exec/switch.js +164 -0
- package/dist/exec/types.d.ts +28 -4
- package/dist/index.d.ts +1 -1
- package/dist/network.d.ts +45 -0
- package/dist/network.js +154 -0
- package/dist/pid.d.ts +13 -1
- package/dist/pid.js +54 -7
- package/dist/policy-ops.d.ts +47 -0
- package/dist/policy-ops.js +90 -0
- package/dist/policy-store.d.ts +43 -0
- package/dist/policy-store.js +94 -0
- package/dist/policy.d.ts +36 -16
- package/dist/policy.js +77 -19
- package/dist/public-suffix.d.ts +6 -0
- package/dist/public-suffix.js +79 -0
- package/dist/server-ops.d.ts +46 -7
- package/dist/server-ops.js +285 -29
- package/dist/service/installed.d.ts +5 -0
- package/dist/service/installed.js +14 -0
- package/dist/service/launchd.d.ts +11 -1
- package/dist/service/launchd.js +14 -5
- package/dist/state.d.ts +50 -6
- package/dist/state.js +195 -16
- package/package.json +3 -3
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
export declare const LAUNCHD_LABEL = "top.capybara.device";
|
|
2
|
+
/**
|
|
3
|
+
* Minimum seconds between launchd restarts of the agent. Together with unconditional KeepAlive
|
|
4
|
+
* this restarts the program after any exit, without spinning when it crashes during startup.
|
|
5
|
+
*/
|
|
6
|
+
export declare const LAUNCHD_THROTTLE_INTERVAL_SECONDS = 30;
|
|
2
7
|
export interface ServiceSpec {
|
|
3
8
|
/** Absolute path of the node binary that runs the program. */
|
|
4
9
|
nodePath: string;
|
|
@@ -10,7 +15,12 @@ export interface ServiceSpec {
|
|
|
10
15
|
env: Record<string, string>;
|
|
11
16
|
}
|
|
12
17
|
export declare function plistPath(home: string): string;
|
|
13
|
-
/**
|
|
18
|
+
/**
|
|
19
|
+
* The launchd agent: `node <bin> start`, at login and after every exit. `KeepAlive` is
|
|
20
|
+
* unconditional on purpose: the program only exits for a shutdown or a terminal condition, and a
|
|
21
|
+
* clean exit must not leave the machine offline until someone bootstraps the agent again.
|
|
22
|
+
* `ThrottleInterval` keeps a fast crash loop from spinning.
|
|
23
|
+
*/
|
|
14
24
|
export declare function plistContent(spec: ServiceSpec): string;
|
|
15
25
|
export declare const SERVICE_LOG_MAX_BYTES: number;
|
|
16
26
|
/** Keeps `service.log` from growing without bound: past 10 MiB it is copied to `.1` and emptied. */
|
package/dist/service/launchd.js
CHANGED
|
@@ -1,13 +1,23 @@
|
|
|
1
1
|
import { copyFileSync, statSync, truncateSync } from "node:fs";
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
export const LAUNCHD_LABEL = "top.capybara.device";
|
|
4
|
+
/**
|
|
5
|
+
* Minimum seconds between launchd restarts of the agent. Together with unconditional KeepAlive
|
|
6
|
+
* this restarts the program after any exit, without spinning when it crashes during startup.
|
|
7
|
+
*/
|
|
8
|
+
export const LAUNCHD_THROTTLE_INTERVAL_SECONDS = 30;
|
|
4
9
|
export function plistPath(home) {
|
|
5
10
|
return join(home, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
|
|
6
11
|
}
|
|
7
12
|
function xml(s) {
|
|
8
13
|
return s.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
|
|
9
14
|
}
|
|
10
|
-
/**
|
|
15
|
+
/**
|
|
16
|
+
* The launchd agent: `node <bin> start`, at login and after every exit. `KeepAlive` is
|
|
17
|
+
* unconditional on purpose: the program only exits for a shutdown or a terminal condition, and a
|
|
18
|
+
* clean exit must not leave the machine offline until someone bootstraps the agent again.
|
|
19
|
+
* `ThrottleInterval` keeps a fast crash loop from spinning.
|
|
20
|
+
*/
|
|
11
21
|
export function plistContent(spec) {
|
|
12
22
|
const env = Object.entries(spec.env)
|
|
13
23
|
.map(([k, v]) => ` <key>${xml(k)}</key>\n <string>${xml(v)}</string>`)
|
|
@@ -27,10 +37,9 @@ export function plistContent(spec) {
|
|
|
27
37
|
<key>RunAtLoad</key>
|
|
28
38
|
<true/>
|
|
29
39
|
<key>KeepAlive</key>
|
|
30
|
-
<
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
</dict>
|
|
40
|
+
<true/>
|
|
41
|
+
<key>ThrottleInterval</key>
|
|
42
|
+
<integer>${LAUNCHD_THROTTLE_INTERVAL_SECONDS}</integer>
|
|
34
43
|
<key>EnvironmentVariables</key>
|
|
35
44
|
<dict>
|
|
36
45
|
${env}
|
package/dist/state.d.ts
CHANGED
|
@@ -5,20 +5,31 @@ export interface Credential {
|
|
|
5
5
|
connectUrl: string;
|
|
6
6
|
credential: string;
|
|
7
7
|
orgId: string;
|
|
8
|
-
|
|
8
|
+
deviceId: string;
|
|
9
9
|
dir: string;
|
|
10
10
|
mode: DeviceMode;
|
|
11
|
-
/** The deployment's `
|
|
11
|
+
/** The deployment's `devices.local.reconnectGraceSeconds`, returned with the credential. */
|
|
12
12
|
reconnectGraceSeconds: number;
|
|
13
|
-
/** The deployment's `
|
|
13
|
+
/** The deployment's `devices.local.maxFrameBytes`: no frame this program sends is larger. */
|
|
14
14
|
maxFrameBytes: number;
|
|
15
15
|
}
|
|
16
|
+
/**
|
|
17
|
+
* How commands run on this machine: `auto` (no OS sandbox; the owner's files, credentials and
|
|
18
|
+
* network, with every command reviewed by the deployment) or `sandbox` (today's strict
|
|
19
|
+
* `sandbox-runtime` profile). Not `DeviceMode`, which is the run mode (`os | docker`).
|
|
20
|
+
*/
|
|
21
|
+
export type SandboxMode = "auto" | "sandbox";
|
|
16
22
|
/** Local limits the person sets for this machine. */
|
|
17
23
|
export interface Policy {
|
|
18
24
|
allowedDomains: string[];
|
|
19
25
|
allowCredentials: string[];
|
|
20
26
|
cpu: number | null;
|
|
21
27
|
memoryMb: number | null;
|
|
28
|
+
/**
|
|
29
|
+
* The mode the owner chose for this machine. The kernel's `limits.mode` can only narrow it: a
|
|
30
|
+
* sandbox-mode machine never runs auto because the organization allows it.
|
|
31
|
+
*/
|
|
32
|
+
mode: SandboxMode;
|
|
22
33
|
}
|
|
23
34
|
export declare const DEFAULT_MAX_FRAME_BYTES: number;
|
|
24
35
|
export declare const DEFAULT_POLICY: Policy;
|
|
@@ -27,8 +38,12 @@ type Env = Record<string, string | undefined>;
|
|
|
27
38
|
export declare function stateDir(env?: Env, home?: string): string;
|
|
28
39
|
export declare function credentialPath(dir: string): string;
|
|
29
40
|
export declare function policyPath(dir: string): string;
|
|
30
|
-
/** The
|
|
31
|
-
export declare function
|
|
41
|
+
/** The outcomes of the latest `policy` ops by op id (written under the policy lock). */
|
|
42
|
+
export declare function policyOpsPath(dir: string): string;
|
|
43
|
+
/** The lock file that serializes read-modify-writes of policy.json across processes. */
|
|
44
|
+
export declare function policyLockPath(dir: string): string;
|
|
45
|
+
/** The default working directory of a device: `~/capybara-device/<deviceId>`. */
|
|
46
|
+
export declare function defaultWorkDir(deviceId: string, home?: string): string;
|
|
32
47
|
export declare function writePrivate(file: string, text: string): void;
|
|
33
48
|
export declare function writeCredential(dir: string, cred: Credential): void;
|
|
34
49
|
/** The stored credential; undefined when absent. Throws on a file other users can read, or on bad content. */
|
|
@@ -36,5 +51,34 @@ export declare function readCredential(dir: string): Credential | undefined;
|
|
|
36
51
|
export declare function removeCredential(dir: string): boolean;
|
|
37
52
|
/** The local policy (defaults when absent). Throws, naming the file, on bad JSON or field types. */
|
|
38
53
|
export declare function readPolicy(dir: string): Policy;
|
|
39
|
-
|
|
54
|
+
/** {@link readPolicyFile}'s result. */
|
|
55
|
+
export interface PolicyFile {
|
|
56
|
+
policy: Policy;
|
|
57
|
+
/** The file's keys this version does not know (legacy keys excluded). */
|
|
58
|
+
extra: Record<string, unknown>;
|
|
59
|
+
/**
|
|
60
|
+
* The file was written before auto mode (it has no `mode`): the mode was derived from its legacy
|
|
61
|
+
* keys and the file is rewritten in the new vocabulary at the next change (worth a notice at
|
|
62
|
+
* start).
|
|
63
|
+
*/
|
|
64
|
+
legacy: boolean;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* The local policy plus the file's keys this version does not know (kept on every write, so an
|
|
68
|
+
* older program never drops a newer one's settings). Throws like {@link readPolicy}.
|
|
69
|
+
*/
|
|
70
|
+
export declare function readPolicyFile(dir: string): PolicyFile;
|
|
71
|
+
/** Writes policy.json atomically (owner-only); `extra` are unknown keys to keep (never legacy ones). */
|
|
72
|
+
export declare function writePolicy(dir: string, policy: Policy, extra?: Record<string, unknown>): void;
|
|
73
|
+
/**
|
|
74
|
+
* Runs `fn` holding policy.json.lock (created with O_EXCL), so a read-modify-write of the policy
|
|
75
|
+
* by this program and a concurrent `capybara-device policy` never loses an update. A lock older
|
|
76
|
+
* than 10 s whose holder pid no longer runs is stale and taken over; a held one is retried for
|
|
77
|
+
* about 2 s, then this throws. The lock is removed at the end only while it is still this
|
|
78
|
+
* holder's file.
|
|
79
|
+
*/
|
|
80
|
+
export declare function withPolicyLock<T>(dir: string, fn: () => T, opts?: {
|
|
81
|
+
waitMs?: number;
|
|
82
|
+
now?: () => number;
|
|
83
|
+
}): T;
|
|
40
84
|
export {};
|
package/dist/state.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { chmodSync, closeSync, existsSync, fstatSync, linkSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, writeSync, } from "node:fs";
|
|
2
3
|
import { homedir } from "node:os";
|
|
3
4
|
import { join } from "node:path";
|
|
4
5
|
const DEFAULT_RECONNECT_GRACE_SECONDS = 120;
|
|
@@ -8,6 +9,7 @@ export const DEFAULT_POLICY = {
|
|
|
8
9
|
allowCredentials: [],
|
|
9
10
|
cpu: null,
|
|
10
11
|
memoryMb: null,
|
|
12
|
+
mode: "auto",
|
|
11
13
|
};
|
|
12
14
|
/** `$XDG_CONFIG_HOME/capybara-device`, or `~/.config/capybara-device`. */
|
|
13
15
|
export function stateDir(env = process.env, home = homedir()) {
|
|
@@ -21,9 +23,17 @@ export function credentialPath(dir) {
|
|
|
21
23
|
export function policyPath(dir) {
|
|
22
24
|
return join(dir, "policy.json");
|
|
23
25
|
}
|
|
24
|
-
/** The
|
|
25
|
-
export function
|
|
26
|
-
return join(
|
|
26
|
+
/** The outcomes of the latest `policy` ops by op id (written under the policy lock). */
|
|
27
|
+
export function policyOpsPath(dir) {
|
|
28
|
+
return join(dir, "policy-ops.json");
|
|
29
|
+
}
|
|
30
|
+
/** The lock file that serializes read-modify-writes of policy.json across processes. */
|
|
31
|
+
export function policyLockPath(dir) {
|
|
32
|
+
return join(dir, "policy.json.lock");
|
|
33
|
+
}
|
|
34
|
+
/** The default working directory of a device: `~/capybara-device/<deviceId>`. */
|
|
35
|
+
export function defaultWorkDir(deviceId, home = homedir()) {
|
|
36
|
+
return join(home, "capybara-device", deviceId);
|
|
27
37
|
}
|
|
28
38
|
export function writePrivate(file, text) {
|
|
29
39
|
mkdirSync(join(file, ".."), { recursive: true, mode: 0o700 });
|
|
@@ -56,7 +66,7 @@ export function readCredential(dir) {
|
|
|
56
66
|
catch (e) {
|
|
57
67
|
throw new Error(`${file} is not valid JSON (${e.message})`);
|
|
58
68
|
}
|
|
59
|
-
for (const key of ["url", "connectUrl", "credential", "orgId", "
|
|
69
|
+
for (const key of ["url", "connectUrl", "credential", "orgId", "deviceId", "dir", "mode"]) {
|
|
60
70
|
if (typeof raw[key] !== "string") {
|
|
61
71
|
throw new Error(`${file} is invalid: missing ${key}; log in again`);
|
|
62
72
|
}
|
|
@@ -80,11 +90,35 @@ export function removeCredential(dir) {
|
|
|
80
90
|
}
|
|
81
91
|
const isStringList = (v) => Array.isArray(v) && v.every((x) => typeof x === "string");
|
|
82
92
|
const isCeiling = (v) => v === null || (typeof v === "number" && Number.isFinite(v) && v > 0);
|
|
93
|
+
const POLICY_KEYS = Object.keys(DEFAULT_POLICY);
|
|
94
|
+
/**
|
|
95
|
+
* Keys of older policy files: ignored on read and dropped on the next write. `tier` / `isolation` /
|
|
96
|
+
* `localhost` / `remoteGrants` are the auto-mode migration (spec §4.4): a file without `mode` runs
|
|
97
|
+
* in auto when it asked for no sandbox, else in sandbox.
|
|
98
|
+
*/
|
|
99
|
+
const LEGACY_POLICY_KEYS = [
|
|
100
|
+
"network",
|
|
101
|
+
"allowLocalBinding",
|
|
102
|
+
"allowUnixSockets",
|
|
103
|
+
"tier",
|
|
104
|
+
"isolation",
|
|
105
|
+
"localhost",
|
|
106
|
+
"remoteGrants",
|
|
107
|
+
];
|
|
108
|
+
const isMode = (v) => v === "auto" || v === "sandbox";
|
|
83
109
|
/** The local policy (defaults when absent). Throws, naming the file, on bad JSON or field types. */
|
|
84
110
|
export function readPolicy(dir) {
|
|
111
|
+
return readPolicyFile(dir).policy;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* The local policy plus the file's keys this version does not know (kept on every write, so an
|
|
115
|
+
* older program never drops a newer one's settings). Throws like {@link readPolicy}.
|
|
116
|
+
*/
|
|
117
|
+
export function readPolicyFile(dir) {
|
|
85
118
|
const file = policyPath(dir);
|
|
86
|
-
if (!existsSync(file))
|
|
87
|
-
return { ...DEFAULT_POLICY };
|
|
119
|
+
if (!existsSync(file)) {
|
|
120
|
+
return { policy: { ...DEFAULT_POLICY }, extra: {}, legacy: false };
|
|
121
|
+
}
|
|
88
122
|
let raw;
|
|
89
123
|
try {
|
|
90
124
|
raw = JSON.parse(readFileSync(file, "utf8"));
|
|
@@ -95,8 +129,25 @@ export function readPolicy(dir) {
|
|
|
95
129
|
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
96
130
|
throw new Error(`${file} is invalid: expected a JSON object`);
|
|
97
131
|
}
|
|
98
|
-
const
|
|
132
|
+
const o = raw;
|
|
99
133
|
const bad = (key, want) => new Error(`${file} is invalid: ${key} must be ${want} (fix or delete the file)`);
|
|
134
|
+
// Lenient read (spec §4.4): no `mode` means an older file; `isolation: none` or `tier: open`
|
|
135
|
+
// asked for no sandbox, so it becomes auto, anything else sandbox.
|
|
136
|
+
const legacy = o.mode === undefined;
|
|
137
|
+
const rawMode = legacy
|
|
138
|
+
? o.isolation === "none" || o.tier === "open"
|
|
139
|
+
? "auto"
|
|
140
|
+
: "sandbox"
|
|
141
|
+
: o.mode;
|
|
142
|
+
if (!isMode(rawMode))
|
|
143
|
+
throw bad("mode", '"auto" or "sandbox"');
|
|
144
|
+
const policy = {
|
|
145
|
+
allowedDomains: o.allowedDomains === undefined ? [] : o.allowedDomains,
|
|
146
|
+
allowCredentials: o.allowCredentials === undefined ? [] : o.allowCredentials,
|
|
147
|
+
cpu: o.cpu === undefined ? null : o.cpu,
|
|
148
|
+
memoryMb: o.memoryMb === undefined ? null : o.memoryMb,
|
|
149
|
+
mode: rawMode,
|
|
150
|
+
};
|
|
100
151
|
if (!isStringList(policy.allowedDomains))
|
|
101
152
|
throw bad("allowedDomains", "a list of strings");
|
|
102
153
|
if (!isStringList(policy.allowCredentials))
|
|
@@ -105,13 +156,141 @@ export function readPolicy(dir) {
|
|
|
105
156
|
throw bad("cpu", "a positive number or null");
|
|
106
157
|
if (!isCeiling(policy.memoryMb))
|
|
107
158
|
throw bad("memoryMb", "a positive number or null");
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
};
|
|
159
|
+
const extra = {};
|
|
160
|
+
for (const [k, v] of Object.entries(o)) {
|
|
161
|
+
if (!POLICY_KEYS.includes(k) && !LEGACY_POLICY_KEYS.includes(k))
|
|
162
|
+
extra[k] = v;
|
|
163
|
+
}
|
|
164
|
+
return { policy, extra, legacy };
|
|
165
|
+
}
|
|
166
|
+
/** Writes policy.json atomically (owner-only); `extra` are unknown keys to keep (never legacy ones). */
|
|
167
|
+
export function writePolicy(dir, policy, extra = {}) {
|
|
168
|
+
const kept = Object.fromEntries(Object.entries(extra).filter(([k]) => !LEGACY_POLICY_KEYS.includes(k)));
|
|
169
|
+
writePrivate(policyPath(dir), `${JSON.stringify({ ...kept, ...policy }, null, 2)}\n`);
|
|
170
|
+
}
|
|
171
|
+
/** A lock file older than this is left over by a crashed process and is taken over. */
|
|
172
|
+
const POLICY_LOCK_STALE_MS = 10_000;
|
|
173
|
+
const POLICY_LOCK_WAIT_MS = 2_000;
|
|
174
|
+
const POLICY_LOCK_RETRY_MS = 25;
|
|
175
|
+
function sleepSync(ms) {
|
|
176
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
114
177
|
}
|
|
115
|
-
|
|
116
|
-
|
|
178
|
+
/** Whether the pid written in a lock file names a running process (EPERM: someone else's). */
|
|
179
|
+
function holderAlive(lock) {
|
|
180
|
+
let pid;
|
|
181
|
+
try {
|
|
182
|
+
pid = Number(readFileSync(lock, "utf8").trim());
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
187
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
188
|
+
return false;
|
|
189
|
+
try {
|
|
190
|
+
process.kill(pid, 0);
|
|
191
|
+
return true;
|
|
192
|
+
}
|
|
193
|
+
catch (e) {
|
|
194
|
+
return e.code === "EPERM";
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Takes a stale lock out of the way atomically: renames it aside (only one taker can), then
|
|
199
|
+
* checks the renamed file is the one judged stale. If a fresh lock was renamed instead, it is
|
|
200
|
+
* linked back (unless a new one exists already). The caller then retries the exclusive create.
|
|
201
|
+
*/
|
|
202
|
+
function takeOver(lock, judged) {
|
|
203
|
+
const aside = `${lock}.${process.pid}.${randomBytes(6).toString("hex")}.stale`;
|
|
204
|
+
try {
|
|
205
|
+
renameSync(lock, aside);
|
|
206
|
+
}
|
|
207
|
+
catch (e) {
|
|
208
|
+
if (e.code === "ENOENT")
|
|
209
|
+
return;
|
|
210
|
+
throw e;
|
|
211
|
+
}
|
|
212
|
+
try {
|
|
213
|
+
const st = statSync(aside);
|
|
214
|
+
if (st.ino !== judged.ino || st.mtimeMs !== judged.mtimeMs) {
|
|
215
|
+
try {
|
|
216
|
+
linkSync(aside, lock);
|
|
217
|
+
}
|
|
218
|
+
catch {
|
|
219
|
+
// A new lock exists already; its holder goes on.
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
finally {
|
|
224
|
+
rmSync(aside, { force: true });
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Runs `fn` holding policy.json.lock (created with O_EXCL), so a read-modify-write of the policy
|
|
229
|
+
* by this program and a concurrent `capybara-device policy` never loses an update. A lock older
|
|
230
|
+
* than 10 s whose holder pid no longer runs is stale and taken over; a held one is retried for
|
|
231
|
+
* about 2 s, then this throws. The lock is removed at the end only while it is still this
|
|
232
|
+
* holder's file.
|
|
233
|
+
*/
|
|
234
|
+
export function withPolicyLock(dir, fn, opts = {}) {
|
|
235
|
+
const lock = policyLockPath(dir);
|
|
236
|
+
const now = opts.now ?? Date.now;
|
|
237
|
+
const deadline = Date.now() + (opts.waitMs ?? POLICY_LOCK_WAIT_MS);
|
|
238
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
239
|
+
for (;;) {
|
|
240
|
+
let fd;
|
|
241
|
+
try {
|
|
242
|
+
fd = openSync(lock, "wx", 0o600);
|
|
243
|
+
}
|
|
244
|
+
catch (e) {
|
|
245
|
+
if (e.code !== "EEXIST")
|
|
246
|
+
throw e;
|
|
247
|
+
let st;
|
|
248
|
+
try {
|
|
249
|
+
st = statSync(lock);
|
|
250
|
+
}
|
|
251
|
+
catch {
|
|
252
|
+
// Released between the open and the stat: try again at once.
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
if (now() - st.mtimeMs >= POLICY_LOCK_STALE_MS && !holderAlive(lock)) {
|
|
256
|
+
takeOver(lock, st);
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
if (Date.now() >= deadline) {
|
|
260
|
+
throw new Error(`${lock} is held by another capybara-device process; try again in a moment ` +
|
|
261
|
+
`(delete the file if no other capybara-device is running)`);
|
|
262
|
+
}
|
|
263
|
+
sleepSync(POLICY_LOCK_RETRY_MS);
|
|
264
|
+
continue;
|
|
265
|
+
}
|
|
266
|
+
let ino;
|
|
267
|
+
try {
|
|
268
|
+
writeSync(fd, String(process.pid));
|
|
269
|
+
ino = fstatSync(fd).ino;
|
|
270
|
+
}
|
|
271
|
+
catch (e) {
|
|
272
|
+
closeSync(fd);
|
|
273
|
+
rmSync(lock, { force: true });
|
|
274
|
+
throw e;
|
|
275
|
+
}
|
|
276
|
+
try {
|
|
277
|
+
return fn();
|
|
278
|
+
}
|
|
279
|
+
finally {
|
|
280
|
+
try {
|
|
281
|
+
// Another process may have taken the lock over meanwhile: leave its file alone.
|
|
282
|
+
if (statSync(lock).ino === ino)
|
|
283
|
+
rmSync(lock, { force: true });
|
|
284
|
+
}
|
|
285
|
+
catch {
|
|
286
|
+
// Already gone.
|
|
287
|
+
}
|
|
288
|
+
try {
|
|
289
|
+
closeSync(fd);
|
|
290
|
+
}
|
|
291
|
+
catch {
|
|
292
|
+
// `fn` ran (a policy write may have happened): a failed close must not turn it into an error
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
117
296
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@capybara-hq/device",
|
|
3
|
-
"version": "0.1.0-rc.
|
|
4
|
-
"description": "capybara-device: connects a laptop or server to a Capybara deployment as
|
|
3
|
+
"version": "0.1.0-rc.10",
|
|
4
|
+
"description": "capybara-device: connects a laptop or server to a Capybara deployment as a device",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
"dependencies": {
|
|
35
35
|
"@anthropic-ai/sandbox-runtime": "0.0.81",
|
|
36
36
|
"ws": "^8.18.0",
|
|
37
|
-
"@capybara-hq/plugin-sdk": "^0.1.0-rc.
|
|
37
|
+
"@capybara-hq/plugin-sdk": "^0.1.0-rc.22"
|
|
38
38
|
},
|
|
39
39
|
"devDependencies": {
|
|
40
40
|
"@types/ws": "^8.5.13"
|