@niwa-labs/client 0.0.0-stage → 0.0.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/LICENSE +21 -0
- package/README.md +4 -2
- package/package.json +11 -4
- package/src/client-types.ts +80 -0
- package/src/client.ts +949 -0
- package/src/holder.ts +58 -0
- package/src/home.ts +11 -0
- package/src/index.ts +10 -0
- package/src/live.ts +141 -0
- package/src/observation.ts +181 -0
- package/src/pause.ts +30 -0
- package/src/token.ts +38 -0
- package/src/wire.ts +315 -0
- package/src/working-directory.ts +28 -0
- package/test/connection-leak.test.ts +17 -0
- package/test/fixtures/owner-token-of.ts +5 -0
- package/test/helpers.ts +54 -0
- package/test/line-decoder.test.ts +37 -0
- package/test/live-cancel.test.ts +24 -0
- package/test/live-feed.test.ts +49 -0
- package/test/no-sqlite.test.ts +79 -0
- package/test/owner-token.test.ts +31 -0
- package/test/query-refused.test.ts +20 -0
- package/test/retry-pause.test.ts +19 -0
- package/test/write-failure.test.ts +54 -0
- package/tsconfig.json +6 -0
package/src/holder.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Who holds the journal of a home. A pid and lock probe of the host's home, for a client that must
|
|
3
|
+
* tell a running host from a stale one without opening the journal as a writer.
|
|
4
|
+
*
|
|
5
|
+
* `bun:sqlite` is loaded when the probe runs, not when this module is: a client that never asks
|
|
6
|
+
* does not pull the database in, and the contracts and the client entry stay free of it.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { existsSync } from "node:fs";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
|
|
12
|
+
import { expandHome } from "./home.ts";
|
|
13
|
+
|
|
14
|
+
/** The row of the one writer of the journal: the part of `journal.ts`'s table this probe reads. */
|
|
15
|
+
interface WriterRow {
|
|
16
|
+
epoch: number;
|
|
17
|
+
pid: number;
|
|
18
|
+
instance: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function errorCode(error: unknown): string | undefined {
|
|
22
|
+
if (typeof error !== "object" || error === null) return undefined;
|
|
23
|
+
const code: unknown = Reflect.get(error, "code");
|
|
24
|
+
return typeof code === "string" ? code : undefined;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Is that process alive? `process.kill(pid, 0)` sends no signal; it throws ESRCH when there is no
|
|
29
|
+
* such process and EPERM when there is one we may not signal — a living writer we cannot see.
|
|
30
|
+
* Only ESRCH means dead.
|
|
31
|
+
*/
|
|
32
|
+
function isProcessAlive(pid: number): boolean {
|
|
33
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
34
|
+
try {
|
|
35
|
+
process.kill(pid, 0);
|
|
36
|
+
return true;
|
|
37
|
+
} catch (error) {
|
|
38
|
+
return errorCode(error) !== "ESRCH";
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The pid of the living process that holds the journal of a home, or nothing when the journal is
|
|
44
|
+
* free: the same condition `openJournal` refuses on. Read-only: it takes no lock.
|
|
45
|
+
*/
|
|
46
|
+
export function livingHolderPid(home: string): number | undefined {
|
|
47
|
+
const file = join(expandHome(home), "journal.db");
|
|
48
|
+
if (!existsSync(file)) return undefined;
|
|
49
|
+
const { Database } = require("bun:sqlite") as typeof import("bun:sqlite");
|
|
50
|
+
const db = new Database(file, { readonly: true });
|
|
51
|
+
try {
|
|
52
|
+
db.run("PRAGMA busy_timeout = 5000");
|
|
53
|
+
const row = db.query<WriterRow, []>("SELECT epoch, pid, instance FROM writer WHERE id = 1").get() ?? undefined;
|
|
54
|
+
return row !== undefined && isProcessAlive(row.pid) ? row.pid : undefined;
|
|
55
|
+
} finally {
|
|
56
|
+
db.close();
|
|
57
|
+
}
|
|
58
|
+
}
|
package/src/home.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** The way a client reads the path of a home. */
|
|
2
|
+
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
|
|
6
|
+
/** `~` at the start of a home is the user's home directory — the same rule the host uses. */
|
|
7
|
+
export function expandHome(home: string): string {
|
|
8
|
+
if (home === "~") return homedir();
|
|
9
|
+
if (home.startsWith("~/")) return join(homedir(), home.slice(2));
|
|
10
|
+
return home;
|
|
11
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// The client entry: how a process talks to a host, and the wire it speaks.
|
|
2
|
+
|
|
3
|
+
export * from "./client.ts";
|
|
4
|
+
export * from "./wire.ts";
|
|
5
|
+
export * from "./live.ts";
|
|
6
|
+
export * from "./observation.ts";
|
|
7
|
+
export * from "./client-types.ts";
|
|
8
|
+
export * from "./token.ts";
|
|
9
|
+
export * from "./holder.ts";
|
|
10
|
+
export * from "./working-directory.ts";
|
package/src/live.ts
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* live.ts — the live stream of frames that are not recorded.
|
|
3
|
+
*
|
|
4
|
+
* A frame is never a source of truth and never reaches the journal. A subscriber that is not
|
|
5
|
+
* listening when a frame is sent misses it: there is no history, no cursor and no replay.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { LiveFrame } from "@niwa-labs/core";
|
|
9
|
+
|
|
10
|
+
import type { LiveSubscription } from "./client-types.ts";
|
|
11
|
+
|
|
12
|
+
/** The name of a channel: a key that travels through the socket, so no empty name and no whitespace. */
|
|
13
|
+
export function channelName(value: string): string {
|
|
14
|
+
if (typeof value !== "string") {
|
|
15
|
+
throw new TypeError(`a channel name must be a string, got ${typeof value}`);
|
|
16
|
+
}
|
|
17
|
+
if (value.trim().length === 0) {
|
|
18
|
+
throw new TypeError("a channel name must not be empty");
|
|
19
|
+
}
|
|
20
|
+
if (/\s/.test(value)) {
|
|
21
|
+
throw new TypeError(`a channel name must not contain whitespace: ${JSON.stringify(value)}`);
|
|
22
|
+
}
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The frame that goes on a channel. The frame names its own channel and it must agree with the
|
|
28
|
+
* one it is sent on: a frame for another channel is a bug in the sender, not something to move.
|
|
29
|
+
*/
|
|
30
|
+
export function frameFor(channel: string, frame: LiveFrame): LiveFrame {
|
|
31
|
+
const name = channelName(channel);
|
|
32
|
+
if (frame.channel !== name) {
|
|
33
|
+
throw new TypeError(`the frame names the channel "${frame.channel}" but it is sent on "${name}"`);
|
|
34
|
+
}
|
|
35
|
+
return { channel: name, data: frame.data };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Frames a listener holds for a consumer that reads slowly; past it the oldest frame is dropped. */
|
|
39
|
+
export const MAX_QUEUED_FRAMES = 1024;
|
|
40
|
+
|
|
41
|
+
/** One listener of one channel: the frames are queued until the consumer takes them. */
|
|
42
|
+
export class LiveFeed {
|
|
43
|
+
private readonly queue: LiveFrame[] = [];
|
|
44
|
+
private readonly waiters: Array<() => void> = [];
|
|
45
|
+
private closed = false;
|
|
46
|
+
|
|
47
|
+
constructor(private readonly onClose: () => void) {}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The frames from now on, until the feed is closed. Returning from the iterator closes the feed
|
|
51
|
+
* first, so a read that waits on a quiet channel ends with it, and a feed that was never read
|
|
52
|
+
* leaves its channel all the same. The feed is registered already: it is ready.
|
|
53
|
+
*/
|
|
54
|
+
iterate(): LiveSubscription {
|
|
55
|
+
const frames = this.frames();
|
|
56
|
+
const subscription: LiveSubscription = {
|
|
57
|
+
[Symbol.asyncIterator]() { return this; },
|
|
58
|
+
next: () => frames.next(),
|
|
59
|
+
return: () => {
|
|
60
|
+
this.close();
|
|
61
|
+
return frames.return();
|
|
62
|
+
},
|
|
63
|
+
ready: Promise.resolve(),
|
|
64
|
+
};
|
|
65
|
+
return subscription;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
private async *frames(): AsyncGenerator<LiveFrame, void, undefined> {
|
|
69
|
+
try {
|
|
70
|
+
for (;;) {
|
|
71
|
+
const frame = this.queue.shift();
|
|
72
|
+
if (frame !== undefined) {
|
|
73
|
+
yield frame;
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
if (this.closed) return;
|
|
77
|
+
await new Promise<void>((resolve) => this.waiters.push(resolve));
|
|
78
|
+
}
|
|
79
|
+
} finally {
|
|
80
|
+
this.close();
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
push(frame: LiveFrame): void {
|
|
85
|
+
if (this.closed) return;
|
|
86
|
+
if (this.queue.length >= MAX_QUEUED_FRAMES) this.queue.shift();
|
|
87
|
+
this.queue.push(frame);
|
|
88
|
+
this.wake();
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** No more frames come; the feed leaves its channel. */
|
|
92
|
+
close(): void {
|
|
93
|
+
if (this.closed) return;
|
|
94
|
+
this.closed = true;
|
|
95
|
+
this.onClose();
|
|
96
|
+
this.wake();
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
private wake(): void {
|
|
100
|
+
for (const resolve of this.waiters.splice(0)) resolve();
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** The channels, and the feeds listening to each. A channel nobody listens to does not exist. */
|
|
105
|
+
export class LiveBus {
|
|
106
|
+
private readonly channels = new Map<string, Set<LiveFeed>>();
|
|
107
|
+
private closed = false;
|
|
108
|
+
|
|
109
|
+
/** Hand the frame to the feeds listening right now. */
|
|
110
|
+
send(channel: string, frame: LiveFrame): void {
|
|
111
|
+
for (const feed of this.channels.get(channel) ?? []) feed.push(frame);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Listen to a channel. The feed is registered before it is returned. */
|
|
115
|
+
subscribe(channel: string): LiveFeed {
|
|
116
|
+
const feed: LiveFeed = new LiveFeed(() => {
|
|
117
|
+
const feeds = this.channels.get(channel);
|
|
118
|
+
feeds?.delete(feed);
|
|
119
|
+
if (feeds?.size === 0) this.channels.delete(channel);
|
|
120
|
+
});
|
|
121
|
+
if (this.closed) {
|
|
122
|
+
feed.close();
|
|
123
|
+
return feed;
|
|
124
|
+
}
|
|
125
|
+
let feeds = this.channels.get(channel);
|
|
126
|
+
if (feeds === undefined) {
|
|
127
|
+
feeds = new Set<LiveFeed>();
|
|
128
|
+
this.channels.set(channel, feeds);
|
|
129
|
+
}
|
|
130
|
+
feeds.add(feed);
|
|
131
|
+
return feed;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Every feed ends. */
|
|
135
|
+
close(): void {
|
|
136
|
+
this.closed = true;
|
|
137
|
+
for (const feeds of [...this.channels.values()]) {
|
|
138
|
+
for (const feed of [...feeds]) feed.close();
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Observation as actions: the ways to read what happened, declared by the core itself.
|
|
3
|
+
*
|
|
4
|
+
* Reading the journal is something the system does, so it is declared as an action like any
|
|
5
|
+
* other. The surfaces generate their tools and their commands from the list of actions, so an
|
|
6
|
+
* observation action is a tool and a command with no change to either surface — and a surface
|
|
7
|
+
* that kept a list of reading tools of its own would be a second source for the same thing.
|
|
8
|
+
*
|
|
9
|
+
* The actions read and write nothing: they answer with what is committed now.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { z } from "zod";
|
|
13
|
+
|
|
14
|
+
import { actionName, DataFilterSchema, JsonSchemaValue, RecordFilterInput, TypeSelectorSchema } from "@niwa-labs/core";
|
|
15
|
+
import { descriptionSchema, storedRecordSchema, tracedRecordSchema } from "./wire.ts";
|
|
16
|
+
import type { ActionName } from "@niwa-labs/core";
|
|
17
|
+
|
|
18
|
+
/** The action that reads the records of the journal. */
|
|
19
|
+
export const RECORDS_READ_ACTION: ActionName = actionName("niwa.records.read");
|
|
20
|
+
|
|
21
|
+
/** The action that searches the records of the journal as a person does. */
|
|
22
|
+
export const RECORDS_SEARCH_ACTION: ActionName = actionName("niwa.records.search");
|
|
23
|
+
|
|
24
|
+
/** The action that walks down from a record: what grew from it. */
|
|
25
|
+
export const TRACE_ACTION: ActionName = actionName("niwa.trace");
|
|
26
|
+
|
|
27
|
+
/** The action that walks up from a record: what it depends on. */
|
|
28
|
+
export const CAUSES_ACTION: ActionName = actionName("niwa.causes");
|
|
29
|
+
|
|
30
|
+
/** The action that says what niwa is: its actions and its record types. */
|
|
31
|
+
export const DESCRIBE_ACTION: ActionName = actionName("niwa.describe");
|
|
32
|
+
|
|
33
|
+
/** The action that says whether the host is up and what it holds. */
|
|
34
|
+
export const STATUS_ACTION: ActionName = actionName("niwa.host.status");
|
|
35
|
+
|
|
36
|
+
/** The action that stops the host. */
|
|
37
|
+
export const STOP_ACTION: ActionName = actionName("niwa.host.stop");
|
|
38
|
+
|
|
39
|
+
/** The action that lists the cockpit modules the plugins offer. */
|
|
40
|
+
export const CATALOG_ACTION: ActionName = actionName("niwa.cockpit.catalog");
|
|
41
|
+
|
|
42
|
+
/** What the host lists of a cockpit module: who offers it, where its source is, and the hash of its code. */
|
|
43
|
+
export const CockpitModuleListing = z.object({
|
|
44
|
+
/** The id of the module. */
|
|
45
|
+
id: z.string().min(1),
|
|
46
|
+
/** The plugin that offers it, and the version of that plugin. */
|
|
47
|
+
plugin: z.string().min(1),
|
|
48
|
+
version: z.string().min(1),
|
|
49
|
+
/** The module's entry file on the host's machine. */
|
|
50
|
+
entry: z.string().min(1),
|
|
51
|
+
/** The sha256 of the entry file and of every local file it imports, in hex. */
|
|
52
|
+
hash: z.string().regex(/^[0-9a-f]{64}$/),
|
|
53
|
+
/** The stylesheets of the module, each with its own hash. */
|
|
54
|
+
styles: z.array(z.object({ file: z.string().min(1), hash: z.string().regex(/^[0-9a-f]{64}$/) })),
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
export const CatalogOutput = z.object({ modules: z.array(CockpitModuleListing) });
|
|
58
|
+
export type CatalogAnswer = z.output<typeof CatalogOutput>;
|
|
59
|
+
|
|
60
|
+
/** What the host answers about itself: its process, its home, its journal and what each plugin holds. */
|
|
61
|
+
export const StatusOutput = z.object({
|
|
62
|
+
pid: z.number().int(),
|
|
63
|
+
home: z.string(),
|
|
64
|
+
/** The position of the last record of the journal. */
|
|
65
|
+
seq: z.number().int().nonnegative(),
|
|
66
|
+
plugins: z.array(
|
|
67
|
+
z.object({
|
|
68
|
+
name: z.string(),
|
|
69
|
+
version: z.string(),
|
|
70
|
+
/** What the plugin counts: runs by state, open requests, live sessions. */
|
|
71
|
+
summary: z.record(z.string(), z.number()).optional(),
|
|
72
|
+
}),
|
|
73
|
+
),
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
/** What a read of the history asks for: a record query, and how much of what answers it. */
|
|
77
|
+
export const RecordsReadInput = z.strictObject({
|
|
78
|
+
/** The position to read after; 0 is the start of the journal. */
|
|
79
|
+
from: z.number().int().nonnegative().optional(),
|
|
80
|
+
/** The record types to read, as exact names or families written `prefix.*`; every type when absent. */
|
|
81
|
+
types: z.array(TypeSelectorSchema).optional(),
|
|
82
|
+
/** Equality on fields of the data, by field name or dotted path. */
|
|
83
|
+
filter: DataFilterSchema.optional(),
|
|
84
|
+
/** The stream to read; every stream when absent. */
|
|
85
|
+
stream: z.string().min(1).optional(),
|
|
86
|
+
/** At most this many records: the first ones. */
|
|
87
|
+
limit: z.number().int().positive().optional(),
|
|
88
|
+
/** The last this many records that answer, not the first. */
|
|
89
|
+
tail: z.number().int().positive().optional(),
|
|
90
|
+
/** When no record answers, wait up to this long, in milliseconds, for one to be committed. */
|
|
91
|
+
waitMs: z.number().int().positive().optional(),
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* What a search of the history asks for: what a person looks for, not a record query. Type
|
|
96
|
+
* patterns, an actor, a subject (a run with everything it grew into, a session, a request, a
|
|
97
|
+
* task), a text in the data, a span of time or of positions.
|
|
98
|
+
*/
|
|
99
|
+
export const RecordsSearchInput = z.strictObject({
|
|
100
|
+
/** The position to search after; 0 is the start of the journal. */
|
|
101
|
+
from: z.number().int().nonnegative().optional(),
|
|
102
|
+
/** The stream to search; every stream when absent. */
|
|
103
|
+
stream: z.string().min(1).optional(),
|
|
104
|
+
/** At most this many records: the first ones. */
|
|
105
|
+
limit: z.number().int().positive().optional(),
|
|
106
|
+
/** The last this many records that match, not the first. */
|
|
107
|
+
tail: z.number().int().positive().optional(),
|
|
108
|
+
/** What the records are about. */
|
|
109
|
+
filter: RecordFilterInput.optional(),
|
|
110
|
+
/** When no record matches, wait up to this long, in milliseconds, for one to be committed. */
|
|
111
|
+
waitMs: z.number().int().positive().optional(),
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
/** What a walk from a record asks for. */
|
|
115
|
+
export const RecordWalkInput = z.object({
|
|
116
|
+
/** The id of the record to walk from. */
|
|
117
|
+
id: z.string().min(1),
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* A record as the actions carry it: the data may be absent.
|
|
122
|
+
*
|
|
123
|
+
* The wire's own schema cannot be rendered as JSON Schema — `default(undefined)` has no JSON
|
|
124
|
+
* Schema form — and the schema of an action is rendered for the surfaces, so the data field is
|
|
125
|
+
* optional here.
|
|
126
|
+
*/
|
|
127
|
+
const RecordOutput = storedRecordSchema.extend({ data: z.unknown().optional() });
|
|
128
|
+
|
|
129
|
+
/** A list of records, as a walk up from a record answers. */
|
|
130
|
+
export const RecordList = z.array(RecordOutput);
|
|
131
|
+
|
|
132
|
+
/** One record as an action answers with it: what a surface that only shows records reads. */
|
|
133
|
+
export type RecordAnswer = z.output<typeof RecordOutput>;
|
|
134
|
+
|
|
135
|
+
/** The records a read answers with, and the position to read after next time. */
|
|
136
|
+
export const RecordsOutput = z.object({
|
|
137
|
+
records: RecordList,
|
|
138
|
+
/** The position the read reached: the `from` of the next read, so none is missed and none read twice. */
|
|
139
|
+
next: z.number().int().nonnegative(),
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
/** The records a trace answers with, each with the depth it was found at. */
|
|
143
|
+
export const TracedRecordsOutput = z.array(
|
|
144
|
+
tracedRecordSchema.extend({ data: z.unknown().optional() }),
|
|
145
|
+
);
|
|
146
|
+
|
|
147
|
+
/** One record of a trace as an action answers with it. */
|
|
148
|
+
export type TracedRecordAnswer = z.output<typeof TracedRecordsOutput>[number];
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* What the description answers with.
|
|
152
|
+
*
|
|
153
|
+
* The wire's own description schema cannot be rendered as JSON Schema — the schemas inside it
|
|
154
|
+
* are plain values, and a plain value has no JSON Schema form — so the action carries its own
|
|
155
|
+
* shape, and the description the action answers with is the same one the wire carries.
|
|
156
|
+
*/
|
|
157
|
+
export const DescriptionOutput = z.object({
|
|
158
|
+
actions: z.array(
|
|
159
|
+
z.object({
|
|
160
|
+
name: z.string(),
|
|
161
|
+
description: z.string(),
|
|
162
|
+
recovery: z.enum(["repeat", "repeat-with-key", "do-not-repeat"]),
|
|
163
|
+
effect: z.enum(["read", "record", "write", "irreversible"]),
|
|
164
|
+
world: z.enum(["niwa", "local", "external"]).optional(),
|
|
165
|
+
idempotent: z.boolean().optional(),
|
|
166
|
+
destructive: z.boolean().optional(),
|
|
167
|
+
input: JsonSchemaValue,
|
|
168
|
+
output: JsonSchemaValue,
|
|
169
|
+
}),
|
|
170
|
+
),
|
|
171
|
+
types: z.array(
|
|
172
|
+
z.object({
|
|
173
|
+
name: z.string(),
|
|
174
|
+
version: z.number().int().positive(),
|
|
175
|
+
schema: JsonSchemaValue,
|
|
176
|
+
}),
|
|
177
|
+
),
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
/** The description as an action answers with it: what a surface that only shows it reads. */
|
|
181
|
+
export type DescriptionAnswer = z.output<typeof DescriptionOutput>;
|
package/src/pause.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pause.ts — the wait between two reconnect attempts of a subscription.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
/** Delay between reconnect attempts of a subscription whose connection dropped. */
|
|
6
|
+
export const RECONNECT_INTERVAL_MS = 100;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* One wait at a time that a cancel cuts short. When the wait ends, by the timer or by the cancel,
|
|
10
|
+
* nothing of it is left: no timer, no handler waiting for a later cancel.
|
|
11
|
+
*/
|
|
12
|
+
export class RetryPause {
|
|
13
|
+
private end: (() => void) | null = null;
|
|
14
|
+
|
|
15
|
+
wait(ms: number = RECONNECT_INTERVAL_MS): Promise<void> {
|
|
16
|
+
return new Promise<void>((resolve) => {
|
|
17
|
+
const timer = setTimeout(() => this.cancel(), ms);
|
|
18
|
+
this.end = () => {
|
|
19
|
+
clearTimeout(timer);
|
|
20
|
+
this.end = null;
|
|
21
|
+
resolve();
|
|
22
|
+
};
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** End the wait now, if there is one. */
|
|
27
|
+
cancel(): void {
|
|
28
|
+
this.end?.();
|
|
29
|
+
}
|
|
30
|
+
}
|
package/src/token.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tokens as a client holds them: read from the environment or the home of the owner.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
6
|
+
|
|
7
|
+
import { OWNER_TOKEN_FILE, TOKEN_ENV } from "@niwa-labs/core";
|
|
8
|
+
import { expandHome } from "./home.ts";
|
|
9
|
+
import type { Token } from "@niwa-labs/core";
|
|
10
|
+
|
|
11
|
+
/** A token is 1 to 4 letters or digits. */
|
|
12
|
+
const TOKEN_PATTERN = /^[A-Za-z0-9]{1,4}$/;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* A token, from a string a client sent or a file held.
|
|
16
|
+
*
|
|
17
|
+
* @throws when the text is not a token: more than 4 characters, or characters outside letters and digits.
|
|
18
|
+
*/
|
|
19
|
+
export function token(text: string): Token {
|
|
20
|
+
if (typeof text !== "string" || !TOKEN_PATTERN.test(text)) {
|
|
21
|
+
throw new TypeError("a token is 1 to 4 letters or digits");
|
|
22
|
+
}
|
|
23
|
+
return text as Token;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** The token a surface of the owner shows: the one in `NIWA_ID`, else the owner's own. */
|
|
27
|
+
export function tokenOf(home: string, env: Readonly<Record<string, string | undefined>> = process.env): Token | undefined {
|
|
28
|
+
const given = env[TOKEN_ENV]?.trim();
|
|
29
|
+
if (given !== undefined && given !== "") return token(given);
|
|
30
|
+
return readOwnerToken(home);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The token of the owner of this home, when the host has made one. */
|
|
34
|
+
export function readOwnerToken(home: string): Token | undefined {
|
|
35
|
+
const path = `${expandHome(home)}/${OWNER_TOKEN_FILE}`;
|
|
36
|
+
if (!existsSync(path)) return undefined;
|
|
37
|
+
return token(readFileSync(path, "utf8").trim());
|
|
38
|
+
}
|