@overcy/hive 0.0.0-stage → 0.2.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 +213 -2
- package/dist/api.d.ts +31 -0
- package/dist/api.js +83 -0
- package/dist/atomic.d.ts +1 -0
- package/dist/atomic.js +24 -0
- package/dist/binding.d.ts +5 -0
- package/dist/binding.js +16 -0
- package/dist/bootstrap/deps.d.ts +3 -0
- package/dist/bootstrap/deps.js +35 -0
- package/dist/bootstrap/doctor.d.ts +29 -0
- package/dist/bootstrap/doctor.js +80 -0
- package/dist/bootstrap/engine.d.ts +29 -0
- package/dist/bootstrap/engine.js +160 -0
- package/dist/bootstrap/forwarder.d.ts +11 -0
- package/dist/bootstrap/forwarder.js +30 -0
- package/dist/bootstrap/identity.d.ts +7 -0
- package/dist/bootstrap/identity.js +52 -0
- package/dist/bootstrap/index.d.ts +36 -0
- package/dist/bootstrap/index.js +40 -0
- package/dist/bootstrap/kit.d.ts +9 -0
- package/dist/bootstrap/kit.js +56 -0
- package/dist/bootstrap/manifest.d.ts +73 -0
- package/dist/bootstrap/manifest.js +309 -0
- package/dist/bootstrap/model-access.d.ts +43 -0
- package/dist/bootstrap/model-access.js +74 -0
- package/dist/bootstrap/pin.d.ts +2 -0
- package/dist/bootstrap/pin.js +16 -0
- package/dist/bootstrap/plan.d.ts +49 -0
- package/dist/bootstrap/plan.js +69 -0
- package/dist/bootstrap/prompt.d.ts +3 -0
- package/dist/bootstrap/prompt.js +35 -0
- package/dist/bootstrap/registry.d.ts +85 -0
- package/dist/bootstrap/registry.js +38 -0
- package/dist/bootstrap/secrets.d.ts +11 -0
- package/dist/bootstrap/secrets.js +105 -0
- package/dist/bootstrap/steps/agents.d.ts +9 -0
- package/dist/bootstrap/steps/agents.js +75 -0
- package/dist/bootstrap/steps/auth.d.ts +8 -0
- package/dist/bootstrap/steps/auth.js +138 -0
- package/dist/bootstrap/steps/cron.d.ts +7 -0
- package/dist/bootstrap/steps/cron.js +74 -0
- package/dist/bootstrap/steps/drift.d.ts +5 -0
- package/dist/bootstrap/steps/drift.js +67 -0
- package/dist/bootstrap/steps/env.d.ts +6 -0
- package/dist/bootstrap/steps/env.js +108 -0
- package/dist/bootstrap/steps/files.d.ts +7 -0
- package/dist/bootstrap/steps/files.js +28 -0
- package/dist/bootstrap/steps/lanes.d.ts +14 -0
- package/dist/bootstrap/steps/lanes.js +153 -0
- package/dist/bootstrap/steps/model-access.d.ts +10 -0
- package/dist/bootstrap/steps/model-access.js +122 -0
- package/dist/bootstrap/steps/preflight.d.ts +3 -0
- package/dist/bootstrap/steps/preflight.js +49 -0
- package/dist/bootstrap/steps/reporter.d.ts +12 -0
- package/dist/bootstrap/steps/reporter.js +155 -0
- package/dist/bootstrap/system.d.ts +5 -0
- package/dist/bootstrap/system.js +69 -0
- package/dist/bootstrap/types.d.ts +157 -0
- package/dist/bootstrap/types.js +14 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +23 -0
- package/dist/collect.d.ts +28 -0
- package/dist/collect.js +63 -0
- package/dist/commands/connect.d.ts +33 -0
- package/dist/commands/connect.js +306 -0
- package/dist/commands/doctor.d.ts +7 -0
- package/dist/commands/doctor.js +13 -0
- package/dist/commands/login.d.ts +3 -0
- package/dist/commands/login.js +118 -0
- package/dist/commands/logout.d.ts +2 -0
- package/dist/commands/logout.js +37 -0
- package/dist/commands/node-add.d.ts +7 -0
- package/dist/commands/node-add.js +56 -0
- package/dist/commands/node.d.ts +19 -0
- package/dist/commands/node.js +43 -0
- package/dist/commands/prEvents.d.ts +7 -0
- package/dist/commands/prEvents.js +32 -0
- package/dist/commands/setup.d.ts +15 -0
- package/dist/commands/setup.js +35 -0
- package/dist/commands/status.d.ts +18 -0
- package/dist/commands/status.js +71 -0
- package/dist/commands/threads.d.ts +6 -0
- package/dist/commands/threads.js +36 -0
- package/dist/config.d.ts +71 -0
- package/dist/config.js +121 -0
- package/dist/context.d.ts +26 -0
- package/dist/context.js +31 -0
- package/dist/crypto.d.ts +7 -0
- package/dist/crypto.js +50 -0
- package/dist/machine.d.ts +66 -0
- package/dist/machine.js +103 -0
- package/dist/node/cli.d.ts +25 -0
- package/dist/node/cli.js +130 -0
- package/dist/node/engine.d.ts +47 -0
- package/dist/node/engine.js +463 -0
- package/dist/node/ingress.d.ts +102 -0
- package/dist/node/ingress.js +473 -0
- package/dist/node/layout.d.ts +56 -0
- package/dist/node/layout.js +55 -0
- package/dist/node/leave.d.ts +8 -0
- package/dist/node/leave.js +32 -0
- package/dist/node/lock.d.ts +19 -0
- package/dist/node/lock.js +99 -0
- package/dist/node/modelAccess.d.ts +2 -0
- package/dist/node/modelAccess.js +44 -0
- package/dist/node/repair.d.ts +28 -0
- package/dist/node/repair.js +78 -0
- package/dist/node/services.d.ts +58 -0
- package/dist/node/services.js +171 -0
- package/dist/node/state.d.ts +127 -0
- package/dist/node/state.js +95 -0
- package/dist/node/steps.d.ts +74 -0
- package/dist/node/steps.js +158 -0
- package/dist/node/supervisor.d.ts +22 -0
- package/dist/node/supervisor.js +95 -0
- package/dist/node/tick.d.ts +47 -0
- package/dist/node/tick.js +278 -0
- package/dist/node/toolchain.d.ts +50 -0
- package/dist/node/toolchain.js +230 -0
- package/dist/nodeContract.d.ts +101 -0
- package/dist/nodeContract.js +192 -0
- package/dist/package.d.ts +3 -0
- package/dist/package.js +5 -0
- package/dist/prEvents.d.ts +109 -0
- package/dist/prEvents.js +374 -0
- package/dist/run.d.ts +19 -0
- package/dist/run.js +487 -0
- package/dist/specs/device-client.json +920 -0
- package/dist/threads.d.ts +88 -0
- package/dist/threads.js +268 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +1 -0
- package/package.json +35 -4
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Context, Io } from '../context.ts';
|
|
2
|
+
import type { Role, SetupDeps } from '../bootstrap/types.ts';
|
|
3
|
+
export type SetupOptions = {
|
|
4
|
+
role?: Role;
|
|
5
|
+
server?: string;
|
|
6
|
+
yes: boolean;
|
|
7
|
+
installProxy: boolean;
|
|
8
|
+
configureAgents: boolean;
|
|
9
|
+
dryRun: boolean;
|
|
10
|
+
json: boolean;
|
|
11
|
+
name?: string;
|
|
12
|
+
team?: string;
|
|
13
|
+
token?: string;
|
|
14
|
+
};
|
|
15
|
+
export declare function setup(ctx: Context, opts: SetupOptions, signal: AbortSignal, io: Io, overrides?: Partial<SetupDeps>): Promise<number>;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { bootstrapNode, renderReport } from "../bootstrap/index.js";
|
|
2
|
+
import { makeSetupDeps } from "../bootstrap/deps.js";
|
|
3
|
+
import { nodeMode } from "../node/layout.js";
|
|
4
|
+
import { renderNodeReport, repairNow } from "../node/repair.js";
|
|
5
|
+
export async function setup(ctx, opts, signal, io, overrides = {}) {
|
|
6
|
+
const interactive = !opts.yes && !opts.json && !opts.dryRun && Boolean(process.stdin.isTTY);
|
|
7
|
+
const deps = await makeSetupDeps(ctx, interactive, overrides);
|
|
8
|
+
const report = await bootstrapNode({
|
|
9
|
+
apiUrl: ctx.url,
|
|
10
|
+
hiveProxy: opts.installProxy ? 'install' : 'skip',
|
|
11
|
+
dryRun: opts.dryRun,
|
|
12
|
+
configureAgents: opts.configureAgents,
|
|
13
|
+
saveApiUrl: opts.server !== undefined,
|
|
14
|
+
...(opts.role ? { role: opts.role } : {}),
|
|
15
|
+
...(opts.name ? { name: opts.name } : {}),
|
|
16
|
+
...(opts.team ? { team: opts.team } : {}),
|
|
17
|
+
...(opts.token ? { registrationToken: opts.token } : {}),
|
|
18
|
+
}, { ...deps, ctx, signal });
|
|
19
|
+
if (opts.json)
|
|
20
|
+
io.out(JSON.stringify(report));
|
|
21
|
+
else
|
|
22
|
+
for (const line of renderReport(report, ctx.url))
|
|
23
|
+
(line.startsWith('failed:') ? io.err : io.out)(line);
|
|
24
|
+
if (!report.ok || opts.dryRun || !nodeMode(ctx.env))
|
|
25
|
+
return report.ok ? 0 : 1;
|
|
26
|
+
// On a node, setup hands the repair to the supervisor and waits for the report that shows it was handled.
|
|
27
|
+
const outcome = await repairNow(ctx, 'setup', signal);
|
|
28
|
+
if (!outcome.ok) {
|
|
29
|
+
ctx.io.err(outcome.error);
|
|
30
|
+
return outcome.code;
|
|
31
|
+
}
|
|
32
|
+
for (const line of renderNodeReport(outcome.report))
|
|
33
|
+
ctx.io.out(line);
|
|
34
|
+
return 0;
|
|
35
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Context } from '../context.ts';
|
|
2
|
+
type NodeView = {
|
|
3
|
+
id?: number;
|
|
4
|
+
name: string;
|
|
5
|
+
node_id?: number | null;
|
|
6
|
+
state: string;
|
|
7
|
+
kind: string;
|
|
8
|
+
last_seen_at: string | null;
|
|
9
|
+
hostname: string | null;
|
|
10
|
+
slot_frees_at?: string | null;
|
|
11
|
+
cores?: number | null;
|
|
12
|
+
ram_gb?: number | null;
|
|
13
|
+
role?: string | null;
|
|
14
|
+
slots?: number | null;
|
|
15
|
+
};
|
|
16
|
+
export declare function enrollmentFacts(item: NodeView): string;
|
|
17
|
+
export declare function status(ctx: Context, team?: string): Promise<number>;
|
|
18
|
+
export {};
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { ApiError, NetworkError } from "../api.js";
|
|
2
|
+
import { boundToServer } from "../binding.js";
|
|
3
|
+
import { classifyFailure } from "../machine.js";
|
|
4
|
+
const describe = (error) => (error instanceof ApiError ? `${error.message} (${error.code})` : error instanceof NetworkError ? error.message : String(error));
|
|
5
|
+
export function enrollmentFacts(item) {
|
|
6
|
+
const facts = [
|
|
7
|
+
item.role ? `role ${item.role}` : null,
|
|
8
|
+
item.slots !== null && item.slots !== undefined ? `${item.slots} slots` : null,
|
|
9
|
+
item.cores ? `${item.cores} cores` : null,
|
|
10
|
+
item.ram_gb ? `${item.ram_gb} GB` : null,
|
|
11
|
+
].filter((fact) => fact !== null);
|
|
12
|
+
return facts.length === 0 ? '' : ` ${facts.join(', ')}`;
|
|
13
|
+
}
|
|
14
|
+
/** The Hive node id (nodes.id) that this node's stream tokens carry. node.json keeps the connection id, a different number. */
|
|
15
|
+
const hiveNodeLine = (id) => `Hive node id: ${id} (the node_id in this node's stream tokens)`;
|
|
16
|
+
function nodeLine(item, mine) {
|
|
17
|
+
const base = ` ${item.name}${mine ? ' (this machine)' : ''} ${item.state}${enrollmentFacts(item)}`;
|
|
18
|
+
return item.slot_frees_at ? `${base} slot frees at ${item.slot_frees_at}` : `${base} last seen ${item.last_seen_at ?? 'never'}`;
|
|
19
|
+
}
|
|
20
|
+
export async function status(ctx, team) {
|
|
21
|
+
const local = await ctx.store.state();
|
|
22
|
+
ctx.io.out(`Connection: ${local.state}${local.last_error ? ` (last error: ${local.last_error})` : ''}`);
|
|
23
|
+
const user = boundToServer(ctx, await ctx.store.read('user.json'), 'sign-in');
|
|
24
|
+
const node = boundToServer(ctx, await ctx.store.read('node.json'), 'node identity');
|
|
25
|
+
const key = await ctx.store.read('key.json');
|
|
26
|
+
if (user) {
|
|
27
|
+
try {
|
|
28
|
+
const listing = await ctx.api.json('GET', `/api/v0/nodes${team ? `?team=${encodeURIComponent(team)}` : ''}`, { token: user.token });
|
|
29
|
+
ctx.io.out(`Signed in as ${listing.user.name} <${listing.user.email}>`);
|
|
30
|
+
ctx.io.out(`Team: ${listing.team.name} (${listing.team.slug})`);
|
|
31
|
+
ctx.io.out(`Plan: ${listing.plan.name}, ${listing.plan.used} of ${listing.plan.max_nodes ?? 'unlimited'} plan slots used`);
|
|
32
|
+
if (listing.nodes.length === 0)
|
|
33
|
+
ctx.io.out('Nodes: none');
|
|
34
|
+
for (const item of listing.nodes)
|
|
35
|
+
ctx.io.out(nodeLine(item, node !== null && item.name === node.name));
|
|
36
|
+
const mine = node ? listing.nodes.find((item) => item.id === node.node_id) : undefined;
|
|
37
|
+
if (typeof mine?.node_id === 'number')
|
|
38
|
+
ctx.io.out(hiveNodeLine(mine.node_id));
|
|
39
|
+
return 0;
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
if (!(error instanceof ApiError) || classifyFailure(error.status, error.code) !== 'HTTP_401') {
|
|
43
|
+
ctx.io.err(describe(error));
|
|
44
|
+
return 1;
|
|
45
|
+
}
|
|
46
|
+
ctx.io.out(`Your sign-in has expired (${error.message}). Run \`hive login\`. Reporting does not need it.`);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
if (node && key) {
|
|
50
|
+
try {
|
|
51
|
+
const self = await ctx.api.json('GET', '/api/v0/nodes/me', { token: node.token, key });
|
|
52
|
+
ctx.io.out(`Node: ${self.node.name} ${self.node.state}${enrollmentFacts(self.node)} last seen ${self.node.last_seen_at ?? 'never'}`);
|
|
53
|
+
if (typeof self.node.node_id === 'number')
|
|
54
|
+
ctx.io.out(hiveNodeLine(self.node.node_id));
|
|
55
|
+
ctx.io.out(`Team: ${self.team.name} (${self.team.slug})`);
|
|
56
|
+
ctx.io.out(`Plan: ${self.plan.name}, ${self.plan.used} of ${self.plan.max_nodes ?? 'unlimited'} plan slots used`);
|
|
57
|
+
return 0;
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
if (error instanceof ApiError && classifyFailure(error.status, error.code) === 'HTTP_401') {
|
|
61
|
+
await ctx.store.applyIfLegal('HTTP_401', { lastError: error.message });
|
|
62
|
+
ctx.io.err(`${error.message} Run \`hive logout\`, then \`hive login\` and \`hive connect\`.`);
|
|
63
|
+
return 1;
|
|
64
|
+
}
|
|
65
|
+
ctx.io.err(describe(error));
|
|
66
|
+
return 1;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
ctx.io.out(user ? 'No node identity yet. Run `hive connect`.' : 'Not signed in. Run `hive login`.');
|
|
70
|
+
return 1;
|
|
71
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { ApiError } from "../api.js";
|
|
2
|
+
import { collectThreads, relayThreads } from "../threads.js";
|
|
3
|
+
const ABSENT = 'No T3 Code state found, so there are no threads to relay. Set HIVE_T3_HOME to the T3 Code home, the directory that holds userdata/statev2.sqlite.';
|
|
4
|
+
export function relayFailure(error) {
|
|
5
|
+
return error instanceof ApiError ? `${error.message} (${error.code})` : error instanceof Error ? error.message : String(error);
|
|
6
|
+
}
|
|
7
|
+
export async function threads(ctx, options, signal) {
|
|
8
|
+
if (!options.once && !options.dryRun) {
|
|
9
|
+
ctx.io.err('Use `hive threads --once` to relay one time, or `hive threads --dry-run` to print the batch without sending it. `hive connect` relays with every status post.');
|
|
10
|
+
return 1;
|
|
11
|
+
}
|
|
12
|
+
try {
|
|
13
|
+
if (options.dryRun) {
|
|
14
|
+
const collected = await collectThreads(ctx);
|
|
15
|
+
ctx.io.out(collected === null ? ABSENT : JSON.stringify(collected.batch, null, 2));
|
|
16
|
+
return 0;
|
|
17
|
+
}
|
|
18
|
+
const node = await ctx.store.read('node.json');
|
|
19
|
+
const key = await ctx.store.read('key.json');
|
|
20
|
+
if (node === null || key === null) {
|
|
21
|
+
ctx.io.err('This machine is not connected. Run `hive connect` first.');
|
|
22
|
+
return 1;
|
|
23
|
+
}
|
|
24
|
+
const result = await relayThreads(ctx, node, key, signal);
|
|
25
|
+
if (result.kind === 'absent') {
|
|
26
|
+
ctx.io.out(ABSENT);
|
|
27
|
+
return 0;
|
|
28
|
+
}
|
|
29
|
+
ctx.io.out(`Relayed ${result.threads} threads and ${result.removed} removals (created ${String(result.response.created ?? 0)}, updated ${String(result.response.updated ?? 0)}, removed ${String(result.response.removed ?? 0)}).`);
|
|
30
|
+
return 0;
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
ctx.io.err(`Thread relay failed: ${relayFailure(error)}`);
|
|
34
|
+
return 1;
|
|
35
|
+
}
|
|
36
|
+
}
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { type ConnectionEvent, type ConnectionAction, type ConnectionGuard, type ConnectionState, type Resolution } from './machine.ts';
|
|
2
|
+
export declare const DEFAULT_URL = "https://hive.overcy.ai";
|
|
3
|
+
export type UserFile = {
|
|
4
|
+
url: string;
|
|
5
|
+
token: string;
|
|
6
|
+
expires_at: string;
|
|
7
|
+
user: {
|
|
8
|
+
id: number;
|
|
9
|
+
name: string;
|
|
10
|
+
email: string;
|
|
11
|
+
};
|
|
12
|
+
};
|
|
13
|
+
export type NodeFile = {
|
|
14
|
+
url: string;
|
|
15
|
+
node_id: number;
|
|
16
|
+
name: string;
|
|
17
|
+
kind: 'machine' | 'session';
|
|
18
|
+
token: string;
|
|
19
|
+
team: {
|
|
20
|
+
id: number;
|
|
21
|
+
name: string;
|
|
22
|
+
slug: string;
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
export type RegistrationFile = {
|
|
26
|
+
registration_id: string;
|
|
27
|
+
name: string;
|
|
28
|
+
team?: string;
|
|
29
|
+
};
|
|
30
|
+
export type KeyFile = {
|
|
31
|
+
private_key_pem: string;
|
|
32
|
+
public_key: string;
|
|
33
|
+
};
|
|
34
|
+
export declare const PENDING_KEY = "key.pending.json";
|
|
35
|
+
export type ApplyOptions = {
|
|
36
|
+
guards?: readonly ConnectionGuard[];
|
|
37
|
+
lastError?: string | null;
|
|
38
|
+
};
|
|
39
|
+
export type StateFile = {
|
|
40
|
+
state: ConnectionState;
|
|
41
|
+
since: string;
|
|
42
|
+
last_error: string | null;
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Where the node identity (`node.json`, `key.json`, `state.json`) lives. Every command asks here, so enrolling and
|
|
46
|
+
* `hive node run` always agree. An explicit `HIVE_CONFIG_DIR` wins. Next comes `<state root>/node` on a machine in
|
|
47
|
+
* node mode (see `nodeMode`). Otherwise it is `~/.config/hive`.
|
|
48
|
+
*/
|
|
49
|
+
export declare function configDir(env: NodeJS.ProcessEnv): string;
|
|
50
|
+
export declare const SHARED_CONFIG = "config.json";
|
|
51
|
+
export declare function serverUrl(env: NodeJS.ProcessEnv): string;
|
|
52
|
+
export declare class UnreadableFileError extends Error {
|
|
53
|
+
constructor(path: string);
|
|
54
|
+
}
|
|
55
|
+
export declare class Store {
|
|
56
|
+
readonly dir: string;
|
|
57
|
+
constructor(dir: string);
|
|
58
|
+
private path;
|
|
59
|
+
read<T>(name: string): Promise<T | null>;
|
|
60
|
+
write(name: string, value: unknown): Promise<void>;
|
|
61
|
+
remove(name: string): Promise<void>;
|
|
62
|
+
state(): Promise<StateFile>;
|
|
63
|
+
heldGuards(): Promise<ConnectionGuard[]>;
|
|
64
|
+
applyIfLegal(event: ConnectionEvent, options?: ApplyOptions): Promise<ConnectionState>;
|
|
65
|
+
apply(event: ConnectionEvent, options?: ApplyOptions): Promise<Resolution>;
|
|
66
|
+
savePendingKey(key: KeyFile): Promise<void>;
|
|
67
|
+
promotePendingKey(): Promise<void>;
|
|
68
|
+
discardPendingKey(): Promise<void>;
|
|
69
|
+
applyAndRun(event: ConnectionEvent, options?: ApplyOptions): Promise<Resolution>;
|
|
70
|
+
runActions(actions: readonly ConnectionAction[]): Promise<void>;
|
|
71
|
+
}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { chmod, mkdir, readFile, rm } from 'node:fs/promises';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { writeAtomic } from "./atomic.js";
|
|
6
|
+
import { layoutOf, nodeMode } from "./node/layout.js";
|
|
7
|
+
import { allows, transition } from "./machine.js";
|
|
8
|
+
export const DEFAULT_URL = 'https://hive.overcy.ai';
|
|
9
|
+
export const PENDING_KEY = 'key.pending.json';
|
|
10
|
+
/**
|
|
11
|
+
* Where the node identity (`node.json`, `key.json`, `state.json`) lives. Every command asks here, so enrolling and
|
|
12
|
+
* `hive node run` always agree. An explicit `HIVE_CONFIG_DIR` wins. Next comes `<state root>/node` on a machine in
|
|
13
|
+
* node mode (see `nodeMode`). Otherwise it is `~/.config/hive`.
|
|
14
|
+
*/
|
|
15
|
+
export function configDir(env) {
|
|
16
|
+
if (env.HIVE_CONFIG_DIR && env.HIVE_CONFIG_DIR !== '')
|
|
17
|
+
return env.HIVE_CONFIG_DIR;
|
|
18
|
+
if (nodeMode(env))
|
|
19
|
+
return layoutOf(env).nodeDir;
|
|
20
|
+
return join(homedir(), '.config', 'hive');
|
|
21
|
+
}
|
|
22
|
+
export const SHARED_CONFIG = 'config.json';
|
|
23
|
+
function savedServer(env) {
|
|
24
|
+
try {
|
|
25
|
+
const parsed = JSON.parse(readFileSync(join(configDir(env), SHARED_CONFIG), 'utf8'));
|
|
26
|
+
return typeof parsed.url === 'string' && parsed.url !== '' ? parsed.url : null;
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export function serverUrl(env) {
|
|
33
|
+
return (env.HIVE_URL && env.HIVE_URL !== '' ? env.HIVE_URL : (savedServer(env) ?? DEFAULT_URL)).replace(/\/+$/, '');
|
|
34
|
+
}
|
|
35
|
+
export class UnreadableFileError extends Error {
|
|
36
|
+
constructor(path) {
|
|
37
|
+
super(`${path} is not valid JSON, so the saved state cannot be read. Nothing was changed. Fix or delete that file, then run the same command again.`);
|
|
38
|
+
this.name = 'UnreadableFileError';
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
export class Store {
|
|
42
|
+
dir;
|
|
43
|
+
constructor(dir) {
|
|
44
|
+
this.dir = dir;
|
|
45
|
+
}
|
|
46
|
+
path(name) {
|
|
47
|
+
return join(this.dir, name);
|
|
48
|
+
}
|
|
49
|
+
async read(name) {
|
|
50
|
+
try {
|
|
51
|
+
return JSON.parse(await readFile(this.path(name), 'utf8'));
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
if (error.code === 'ENOENT')
|
|
55
|
+
return null;
|
|
56
|
+
if (error instanceof SyntaxError)
|
|
57
|
+
throw new UnreadableFileError(this.path(name));
|
|
58
|
+
throw error;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
async write(name, value) {
|
|
62
|
+
await mkdir(this.dir, { recursive: true, mode: 0o700 });
|
|
63
|
+
await chmod(this.dir, 0o700);
|
|
64
|
+
await writeAtomic(this.path(name), `${JSON.stringify(value, null, 2)}\n`, 0o600);
|
|
65
|
+
}
|
|
66
|
+
async remove(name) {
|
|
67
|
+
await rm(this.path(name), { force: true });
|
|
68
|
+
}
|
|
69
|
+
async state() {
|
|
70
|
+
return (await this.read('state.json')) ?? { state: 'unconfigured', since: new Date(0).toISOString(), last_error: null };
|
|
71
|
+
}
|
|
72
|
+
async heldGuards() {
|
|
73
|
+
const guards = [];
|
|
74
|
+
if ((await this.read('user.json')) !== null)
|
|
75
|
+
guards.push('has_user_token');
|
|
76
|
+
if ((await this.read('node.json')) !== null && (await this.read('key.json')) !== null)
|
|
77
|
+
guards.push('device_token_stored');
|
|
78
|
+
if ((await this.read(PENDING_KEY)) !== null)
|
|
79
|
+
guards.push('pending_key_stored');
|
|
80
|
+
return guards;
|
|
81
|
+
}
|
|
82
|
+
async applyIfLegal(event, options = {}) {
|
|
83
|
+
const current = await this.state();
|
|
84
|
+
return allows(current.state, event, options.guards) ? (await this.apply(event, options)).state : current.state;
|
|
85
|
+
}
|
|
86
|
+
async apply(event, options = {}) {
|
|
87
|
+
const current = await this.state();
|
|
88
|
+
const step = transition(current.state, event, options.guards);
|
|
89
|
+
await this.write('state.json', { state: step.state, since: step.state === current.state ? current.since : new Date().toISOString(), last_error: options.lastError ?? null });
|
|
90
|
+
return step;
|
|
91
|
+
}
|
|
92
|
+
async savePendingKey(key) {
|
|
93
|
+
await this.write(PENDING_KEY, key);
|
|
94
|
+
}
|
|
95
|
+
async promotePendingKey() {
|
|
96
|
+
const pending = await this.read(PENDING_KEY);
|
|
97
|
+
if (pending === null)
|
|
98
|
+
throw new Error(`${this.path(PENDING_KEY)} does not exist.`);
|
|
99
|
+
await this.write('key.json', pending);
|
|
100
|
+
await this.remove(PENDING_KEY);
|
|
101
|
+
}
|
|
102
|
+
async discardPendingKey() {
|
|
103
|
+
await this.remove(PENDING_KEY);
|
|
104
|
+
}
|
|
105
|
+
async applyAndRun(event, options = {}) {
|
|
106
|
+
const step = await this.apply(event, options);
|
|
107
|
+
await this.runActions(step.actions);
|
|
108
|
+
return step;
|
|
109
|
+
}
|
|
110
|
+
async runActions(actions) {
|
|
111
|
+
if (actions.includes('forget_user_token'))
|
|
112
|
+
await this.remove('user.json');
|
|
113
|
+
if (actions.includes('forget_device'))
|
|
114
|
+
for (const name of ['key.json', PENDING_KEY, 'node.json', 'registration.json'])
|
|
115
|
+
await this.remove(name);
|
|
116
|
+
if (actions.includes('discard_new_keypair')) {
|
|
117
|
+
await this.discardPendingKey();
|
|
118
|
+
await this.remove('registration.json');
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { Api, type Fetch } from './api.ts';
|
|
2
|
+
import { Store } from './config.ts';
|
|
3
|
+
export type Io = {
|
|
4
|
+
out: (line: string) => void;
|
|
5
|
+
err: (line: string) => void;
|
|
6
|
+
};
|
|
7
|
+
export type Context = {
|
|
8
|
+
env: NodeJS.ProcessEnv;
|
|
9
|
+
io: Io;
|
|
10
|
+
store: Store;
|
|
11
|
+
api: Api;
|
|
12
|
+
apiFor: (url: string) => Api;
|
|
13
|
+
url: string;
|
|
14
|
+
sleep: (ms: number, signal?: AbortSignal) => Promise<void>;
|
|
15
|
+
now: () => Date;
|
|
16
|
+
registrationTimeoutMs: number;
|
|
17
|
+
random: () => number;
|
|
18
|
+
};
|
|
19
|
+
export declare function abortableSleep(ms: number, signal?: AbortSignal): Promise<void>;
|
|
20
|
+
export declare function makeContext(env: NodeJS.ProcessEnv, io: Io, overrides?: {
|
|
21
|
+
fetch?: Fetch;
|
|
22
|
+
sleep?: Context['sleep'];
|
|
23
|
+
now?: Context['now'];
|
|
24
|
+
registrationTimeoutMs?: number;
|
|
25
|
+
random?: () => number;
|
|
26
|
+
}): Context;
|
package/dist/context.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { Api } from "./api.js";
|
|
2
|
+
import { REGISTRATION_TIMEOUT_MS } from "./machine.js";
|
|
3
|
+
import { configDir, serverUrl, Store } from "./config.js";
|
|
4
|
+
export function abortableSleep(ms, signal) {
|
|
5
|
+
return new Promise((resolve) => {
|
|
6
|
+
if (signal?.aborted)
|
|
7
|
+
return resolve();
|
|
8
|
+
const timer = setTimeout(done, ms);
|
|
9
|
+
function done() {
|
|
10
|
+
clearTimeout(timer);
|
|
11
|
+
signal?.removeEventListener('abort', done);
|
|
12
|
+
resolve();
|
|
13
|
+
}
|
|
14
|
+
signal?.addEventListener('abort', done, { once: true });
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
export function makeContext(env, io, overrides = {}) {
|
|
18
|
+
const url = serverUrl(env);
|
|
19
|
+
return {
|
|
20
|
+
env,
|
|
21
|
+
io,
|
|
22
|
+
store: new Store(configDir(env)),
|
|
23
|
+
api: new Api(url, overrides.fetch),
|
|
24
|
+
apiFor: (target) => new Api(target, overrides.fetch),
|
|
25
|
+
url,
|
|
26
|
+
sleep: overrides.sleep ?? abortableSleep,
|
|
27
|
+
now: overrides.now ?? (() => new Date()),
|
|
28
|
+
random: overrides.random ?? Math.random,
|
|
29
|
+
registrationTimeoutMs: overrides.registrationTimeoutMs ?? REGISTRATION_TIMEOUT_MS,
|
|
30
|
+
};
|
|
31
|
+
}
|
package/dist/crypto.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { KeyFile } from './config.ts';
|
|
2
|
+
export declare function generateKey(): KeyFile;
|
|
3
|
+
export declare function publicKeyOf(key: KeyFile): string;
|
|
4
|
+
export declare function canonical(method: string, path: string, timestamp: string, nonce: string, body: string): string;
|
|
5
|
+
export type SignedHeaders = Record<'x-hive-timestamp' | 'x-hive-nonce' | 'x-hive-signature', string>;
|
|
6
|
+
export declare function signRequest(key: KeyFile, method: string, path: string, body: string, now?: Date): SignedHeaders;
|
|
7
|
+
export declare function machineIdHash(): Promise<string | null>;
|
package/dist/crypto.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes, sign } from 'node:crypto';
|
|
2
|
+
import { execFile } from 'node:child_process';
|
|
3
|
+
import { readFile } from 'node:fs/promises';
|
|
4
|
+
import { promisify } from 'node:util';
|
|
5
|
+
const run = promisify(execFile);
|
|
6
|
+
export function generateKey() {
|
|
7
|
+
const { privateKey, publicKey } = generateKeyPairSync('ed25519');
|
|
8
|
+
const jwk = publicKey.export({ format: 'jwk' });
|
|
9
|
+
return {
|
|
10
|
+
private_key_pem: privateKey.export({ format: 'pem', type: 'pkcs8' }).toString(),
|
|
11
|
+
public_key: Buffer.from(String(jwk.x), 'base64url').toString('base64'),
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
export function publicKeyOf(key) {
|
|
15
|
+
const jwk = createPublicKey(createPrivateKey(key.private_key_pem)).export({ format: 'jwk' });
|
|
16
|
+
return Buffer.from(String(jwk.x), 'base64url').toString('base64');
|
|
17
|
+
}
|
|
18
|
+
export function canonical(method, path, timestamp, nonce, body) {
|
|
19
|
+
return ['hive-v0', method.toUpperCase(), path, timestamp, nonce, createHash('sha256').update(body).digest('hex')].join('\n');
|
|
20
|
+
}
|
|
21
|
+
export function signRequest(key, method, path, body, now = new Date()) {
|
|
22
|
+
const timestamp = String(Math.floor(now.getTime() / 1000));
|
|
23
|
+
const nonce = randomBytes(16).toString('hex');
|
|
24
|
+
const signature = sign(null, Buffer.from(canonical(method, path, timestamp, nonce, body)), createPrivateKey(key.private_key_pem));
|
|
25
|
+
return { 'x-hive-timestamp': timestamp, 'x-hive-nonce': nonce, 'x-hive-signature': signature.toString('base64') };
|
|
26
|
+
}
|
|
27
|
+
export async function machineIdHash() {
|
|
28
|
+
const raw = await readMachineId();
|
|
29
|
+
return raw === null ? null : createHash('sha256').update(raw.trim()).digest('hex');
|
|
30
|
+
}
|
|
31
|
+
async function readMachineId() {
|
|
32
|
+
for (const file of ['/etc/machine-id', '/var/lib/dbus/machine-id']) {
|
|
33
|
+
try {
|
|
34
|
+
return await readFile(file, 'utf8');
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
if (process.platform === 'darwin') {
|
|
41
|
+
try {
|
|
42
|
+
const { stdout } = await run('ioreg', ['-rd1', '-c', 'IOPlatformExpertDevice']);
|
|
43
|
+
return /"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(stdout)?.[1] ?? null;
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
export declare const CONNECTION_STATES: readonly ["unconfigured", "authorizing", "logged_in", "connecting", "rotating", "recovering", "connected", "degraded", "paused", "revoked"];
|
|
2
|
+
export type ConnectionState = (typeof CONNECTION_STATES)[number];
|
|
3
|
+
export declare const CONNECTION_EVENTS: readonly ["LOGIN_STARTED", "LOGIN_APPROVED", "LOGIN_FAILED", "CONNECT", "CONNECT_WITH_TOKEN", "RECONNECT_WITH_CODE", "REBIND", "REGISTERED", "REGISTRATION_REFUSED", "REGISTRATION_FAILED", "POST_OK", "POST_FAILED", "HTTP_402", "HTTP_403_FLAGGED", "HTTP_401", "BACKOFF_ELAPSED", "RETRY_DUE", "ROTATED", "LOGOUT", "USER_TOKEN_EXPIRED"];
|
|
4
|
+
export type ConnectionEvent = (typeof CONNECTION_EVENTS)[number];
|
|
5
|
+
export declare const CONNECTION_GUARDS: readonly ["has_user_token", "device_token_stored", "pending_key_stored"];
|
|
6
|
+
export type ConnectionGuard = (typeof CONNECTION_GUARDS)[number];
|
|
7
|
+
export declare const CONNECTION_ACTIONS: readonly ["generate_keypair", "store_user_token", "store_device_token", "discard_new_keypair", "post_status", "double_backoff", "forget_user_token", "resume_request", "forget_device"];
|
|
8
|
+
export type ConnectionAction = (typeof CONNECTION_ACTIONS)[number];
|
|
9
|
+
type SpecTransition = {
|
|
10
|
+
target: ConnectionState;
|
|
11
|
+
guards?: ConnectionGuard[];
|
|
12
|
+
actions?: ConnectionAction[];
|
|
13
|
+
};
|
|
14
|
+
type SpecState = {
|
|
15
|
+
on?: Partial<Record<ConnectionEvent, SpecTransition[]>>;
|
|
16
|
+
timeouts?: {
|
|
17
|
+
after: string;
|
|
18
|
+
event: ConnectionEvent;
|
|
19
|
+
}[];
|
|
20
|
+
};
|
|
21
|
+
type Spec = {
|
|
22
|
+
id: string;
|
|
23
|
+
events: Record<ConnectionEvent, {
|
|
24
|
+
not_built?: boolean;
|
|
25
|
+
}>;
|
|
26
|
+
revision: number;
|
|
27
|
+
initial: ConnectionState;
|
|
28
|
+
states: Record<ConnectionState, SpecState>;
|
|
29
|
+
};
|
|
30
|
+
export type Row = {
|
|
31
|
+
readonly state: ConnectionState;
|
|
32
|
+
readonly event: ConnectionEvent;
|
|
33
|
+
readonly order: number;
|
|
34
|
+
readonly guards: readonly ConnectionGuard[];
|
|
35
|
+
readonly target: ConnectionState;
|
|
36
|
+
readonly actions: readonly ConnectionAction[];
|
|
37
|
+
};
|
|
38
|
+
export type Resolution = {
|
|
39
|
+
readonly state: ConnectionState;
|
|
40
|
+
readonly actions: readonly ConnectionAction[];
|
|
41
|
+
};
|
|
42
|
+
export declare const SPEC: Spec;
|
|
43
|
+
export declare const NOT_BUILT_EVENTS: readonly ConnectionEvent[];
|
|
44
|
+
export declare const CONNECTION_TABLE: readonly Row[];
|
|
45
|
+
export declare class IllegalTransition extends Error {
|
|
46
|
+
readonly from: ConnectionState;
|
|
47
|
+
readonly event: ConnectionEvent;
|
|
48
|
+
constructor(from: ConnectionState, event: ConnectionEvent);
|
|
49
|
+
}
|
|
50
|
+
export declare function resolve(from: ConnectionState, event: ConnectionEvent, holding?: readonly ConnectionGuard[]): Resolution | null;
|
|
51
|
+
export declare function allows(from: ConnectionState, event: ConnectionEvent, holding?: readonly ConnectionGuard[]): boolean;
|
|
52
|
+
export declare function transition(from: ConnectionState, event: ConnectionEvent, holding?: readonly ConnectionGuard[]): Resolution;
|
|
53
|
+
export declare function parseDuration(iso: string): number;
|
|
54
|
+
export declare function timeoutOf(state: ConnectionState): {
|
|
55
|
+
afterMs: number;
|
|
56
|
+
event: ConnectionEvent;
|
|
57
|
+
} | null;
|
|
58
|
+
export declare const REGISTRATION_TIMEOUT_MS: number;
|
|
59
|
+
export type FailureEvent = 'HTTP_402' | 'HTTP_403_FLAGGED' | 'HTTP_401' | 'POST_FAILED';
|
|
60
|
+
export declare function classifyFailure(status: number, code: string): FailureEvent;
|
|
61
|
+
export declare const BASE_INTERVAL_SECONDS = 60;
|
|
62
|
+
export declare const MAX_BACKOFF_SECONDS = 900;
|
|
63
|
+
export declare const PAUSED_RETRY_SECONDS: number;
|
|
64
|
+
export declare const JITTER = 0.2;
|
|
65
|
+
export declare function nextDelaySeconds(state: ConnectionState, consecutiveFailures: number, random?: () => number): number;
|
|
66
|
+
export {};
|
package/dist/machine.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import specJson from './specs/device-client.json' with { type: 'json' };
|
|
2
|
+
export const CONNECTION_STATES = ['unconfigured', 'authorizing', 'logged_in', 'connecting', 'rotating', 'recovering', 'connected', 'degraded', 'paused', 'revoked'];
|
|
3
|
+
export const CONNECTION_EVENTS = [
|
|
4
|
+
'LOGIN_STARTED',
|
|
5
|
+
'LOGIN_APPROVED',
|
|
6
|
+
'LOGIN_FAILED',
|
|
7
|
+
'CONNECT',
|
|
8
|
+
'CONNECT_WITH_TOKEN',
|
|
9
|
+
'RECONNECT_WITH_CODE',
|
|
10
|
+
'REBIND',
|
|
11
|
+
'REGISTERED',
|
|
12
|
+
'REGISTRATION_REFUSED',
|
|
13
|
+
'REGISTRATION_FAILED',
|
|
14
|
+
'POST_OK',
|
|
15
|
+
'POST_FAILED',
|
|
16
|
+
'HTTP_402',
|
|
17
|
+
'HTTP_403_FLAGGED',
|
|
18
|
+
'HTTP_401',
|
|
19
|
+
'BACKOFF_ELAPSED',
|
|
20
|
+
'RETRY_DUE',
|
|
21
|
+
'ROTATED',
|
|
22
|
+
'LOGOUT',
|
|
23
|
+
'USER_TOKEN_EXPIRED',
|
|
24
|
+
];
|
|
25
|
+
export const CONNECTION_GUARDS = ['has_user_token', 'device_token_stored', 'pending_key_stored'];
|
|
26
|
+
export const CONNECTION_ACTIONS = ['generate_keypair', 'store_user_token', 'store_device_token', 'discard_new_keypair', 'post_status', 'double_backoff', 'forget_user_token', 'resume_request', 'forget_device'];
|
|
27
|
+
export const SPEC = specJson;
|
|
28
|
+
export const NOT_BUILT_EVENTS = CONNECTION_EVENTS.filter((event) => SPEC.events[event].not_built === true);
|
|
29
|
+
function flatten(spec) {
|
|
30
|
+
const rows = [];
|
|
31
|
+
for (const state of Object.keys(spec.states).sort()) {
|
|
32
|
+
const on = spec.states[state].on ?? {};
|
|
33
|
+
for (const event of Object.keys(on).sort()) {
|
|
34
|
+
(on[event] ?? []).forEach((transition, order) => {
|
|
35
|
+
rows.push({ state, event, order, guards: transition.guards ?? [], target: transition.target, actions: transition.actions ?? [] });
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return rows;
|
|
40
|
+
}
|
|
41
|
+
export const CONNECTION_TABLE = flatten(SPEC);
|
|
42
|
+
const rowKey = (state, event) => `${state}\u0000${event}`;
|
|
43
|
+
const ROWS = new Map();
|
|
44
|
+
for (const row of CONNECTION_TABLE) {
|
|
45
|
+
const key = rowKey(row.state, row.event);
|
|
46
|
+
ROWS.set(key, [...(ROWS.get(key) ?? []), row]);
|
|
47
|
+
}
|
|
48
|
+
export class IllegalTransition extends Error {
|
|
49
|
+
from;
|
|
50
|
+
event;
|
|
51
|
+
constructor(from, event) {
|
|
52
|
+
super(`connection: event [${event}] is not allowed from state [${from}]`);
|
|
53
|
+
this.name = 'IllegalTransition';
|
|
54
|
+
this.from = from;
|
|
55
|
+
this.event = event;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
export function resolve(from, event, holding = []) {
|
|
59
|
+
const row = ROWS.get(rowKey(from, event))?.find((candidate) => candidate.guards.every((guard) => holding.includes(guard)));
|
|
60
|
+
return row ? { state: row.target, actions: row.actions } : null;
|
|
61
|
+
}
|
|
62
|
+
export function allows(from, event, holding = []) {
|
|
63
|
+
return resolve(from, event, holding) !== null;
|
|
64
|
+
}
|
|
65
|
+
export function transition(from, event, holding = []) {
|
|
66
|
+
const resolution = resolve(from, event, holding);
|
|
67
|
+
if (resolution === null)
|
|
68
|
+
throw new IllegalTransition(from, event);
|
|
69
|
+
return resolution;
|
|
70
|
+
}
|
|
71
|
+
export function parseDuration(iso) {
|
|
72
|
+
const match = /^PT(?:(\d+)M)?(?:(\d+)S)?$/.exec(iso);
|
|
73
|
+
if (match === null)
|
|
74
|
+
throw new Error(`unsupported duration ${iso}`);
|
|
75
|
+
return (Number(match[1] ?? 0) * 60 + Number(match[2] ?? 0)) * 1000;
|
|
76
|
+
}
|
|
77
|
+
export function timeoutOf(state) {
|
|
78
|
+
const timeout = SPEC.states[state].timeouts?.[0];
|
|
79
|
+
return timeout ? { afterMs: parseDuration(timeout.after), event: timeout.event } : null;
|
|
80
|
+
}
|
|
81
|
+
export const REGISTRATION_TIMEOUT_MS = timeoutOf('connecting')?.afterMs ?? 60_000;
|
|
82
|
+
const REVOKING_CODES = new Set(['token_invalid', 'unauthenticated', 'node_removed']);
|
|
83
|
+
export function classifyFailure(status, code) {
|
|
84
|
+
if (status === 402)
|
|
85
|
+
return 'HTTP_402';
|
|
86
|
+
if (status === 403 && code === 'node_flagged')
|
|
87
|
+
return 'HTTP_403_FLAGGED';
|
|
88
|
+
if (status === 401 && REVOKING_CODES.has(code))
|
|
89
|
+
return 'HTTP_401';
|
|
90
|
+
return 'POST_FAILED';
|
|
91
|
+
}
|
|
92
|
+
export const BASE_INTERVAL_SECONDS = 60;
|
|
93
|
+
export const MAX_BACKOFF_SECONDS = 900;
|
|
94
|
+
export const PAUSED_RETRY_SECONDS = parseDuration(SPEC.states.paused.timeouts?.[0]?.after ?? 'PT5M') / 1000;
|
|
95
|
+
export const JITTER = 0.2;
|
|
96
|
+
export function nextDelaySeconds(state, consecutiveFailures, random = () => 0.5) {
|
|
97
|
+
if (state === 'paused')
|
|
98
|
+
return PAUSED_RETRY_SECONDS;
|
|
99
|
+
if (state !== 'degraded')
|
|
100
|
+
return BASE_INTERVAL_SECONDS;
|
|
101
|
+
const base = Math.min(BASE_INTERVAL_SECONDS * 2 ** consecutiveFailures, MAX_BACKOFF_SECONDS);
|
|
102
|
+
return Math.min(base * (1 + JITTER * (2 * random() - 1)), MAX_BACKOFF_SECONDS);
|
|
103
|
+
}
|