@peer2peer/cli 0.0.0-stage → 0.1.1
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 +201 -0
- package/README.md +370 -2
- package/dist/ancestry.d.ts +13 -0
- package/dist/ancestry.js +71 -0
- package/dist/app.d.ts +368 -0
- package/dist/app.js +1181 -0
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +56 -0
- package/dist/circle-ops.d.ts +402 -0
- package/dist/circle-ops.js +1725 -0
- package/dist/cli.d.ts +660 -0
- package/dist/cli.js +1787 -0
- package/dist/codes.d.ts +231 -0
- package/dist/codes.js +998 -0
- package/dist/config.d.ts +159 -0
- package/dist/config.js +294 -0
- package/dist/doctor.d.ts +113 -0
- package/dist/doctor.js +930 -0
- package/dist/errors.d.ts +8 -0
- package/dist/errors.js +29 -0
- package/dist/ext-host.d.ts +38 -0
- package/dist/ext-host.js +293 -0
- package/dist/extensions.d.ts +487 -0
- package/dist/extensions.js +406 -0
- package/dist/features.d.ts +91 -0
- package/dist/features.js +164 -0
- package/dist/format.d.ts +57 -0
- package/dist/format.js +248 -0
- package/dist/graph-memory.d.ts +107 -0
- package/dist/graph-memory.js +393 -0
- package/dist/history.d.ts +155 -0
- package/dist/history.js +697 -0
- package/dist/identity.d.ts +239 -0
- package/dist/identity.js +759 -0
- package/dist/inbound.d.ts +32 -0
- package/dist/inbound.js +261 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +14 -0
- package/dist/ix-local.d.ts +76 -0
- package/dist/ix-local.js +203 -0
- package/dist/join-answers.d.ts +49 -0
- package/dist/join-answers.js +149 -0
- package/dist/outbox.d.ts +109 -0
- package/dist/outbox.js +337 -0
- package/dist/pretty.d.ts +100 -0
- package/dist/pretty.js +256 -0
- package/dist/procstart.d.ts +1 -0
- package/dist/procstart.js +66 -0
- package/dist/progress.d.ts +30 -0
- package/dist/progress.js +78 -0
- package/dist/projects.d.ts +491 -0
- package/dist/projects.js +1383 -0
- package/dist/prompt/picker.d.ts +64 -0
- package/dist/prompt/picker.js +152 -0
- package/dist/prompt/tty.d.ts +29 -0
- package/dist/prompt/tty.js +122 -0
- package/dist/readonly.d.ts +20 -0
- package/dist/readonly.js +50 -0
- package/dist/receipts.d.ts +99 -0
- package/dist/receipts.js +182 -0
- package/dist/relay-client.d.ts +277 -0
- package/dist/relay-client.js +873 -0
- package/dist/relay-info.d.ts +24 -0
- package/dist/relay-info.js +53 -0
- package/dist/rotation.d.ts +402 -0
- package/dist/rotation.js +2054 -0
- package/dist/running.d.ts +5 -0
- package/dist/running.js +74 -0
- package/dist/sessions.d.ts +355 -0
- package/dist/sessions.js +1247 -0
- package/dist/shortcode.d.ts +149 -0
- package/dist/shortcode.js +465 -0
- package/dist/social.d.ts +139 -0
- package/dist/social.js +485 -0
- package/dist/state.d.ts +509 -0
- package/dist/state.js +220 -0
- package/dist/stdin.d.ts +17 -0
- package/dist/stdin.js +46 -0
- package/dist/sync.d.ts +77 -0
- package/dist/sync.js +375 -0
- package/dist/transient.d.ts +1 -0
- package/dist/transient.js +28 -0
- package/dist/trust.d.ts +37 -0
- package/dist/trust.js +134 -0
- package/dist/tty-confirm.d.ts +2 -0
- package/dist/tty-confirm.js +53 -0
- package/dist/tui/command.d.ts +20 -0
- package/dist/tui/command.js +70 -0
- package/dist/tui/frame.d.ts +43 -0
- package/dist/tui/frame.js +111 -0
- package/dist/tui/model.d.ts +221 -0
- package/dist/tui/model.js +259 -0
- package/dist/tui/sanitize.d.ts +13 -0
- package/dist/tui/sanitize.js +151 -0
- package/dist/tui/terminal.d.ts +88 -0
- package/dist/tui/terminal.js +354 -0
- package/dist/tui/tui.d.ts +78 -0
- package/dist/tui/tui.js +612 -0
- package/dist/tui/view.d.ts +4 -0
- package/dist/tui/view.js +358 -0
- package/dist/unknown-kinds.d.ts +12 -0
- package/dist/unknown-kinds.js +66 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +5 -0
- package/dist/want-pow.d.ts +12 -0
- package/dist/want-pow.js +46 -0
- package/dist/watch.d.ts +35 -0
- package/dist/watch.js +331 -0
- package/dist/xstate.d.ts +125 -0
- package/dist/xstate.js +422 -0
- package/package.json +60 -4
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
// Copyright 2026 Ix Infrastructure Inc.
|
|
2
|
+
//
|
|
3
|
+
// Graph memory (epic #41 piece 2): while a session runs, its context goes into the person's
|
|
4
|
+
// LOCAL Ix graph: its record (start, end, repo, branch), its status one-liners and the files it
|
|
5
|
+
// edits. Notes peers share go there only when the person imports them (`p2p ix import`, ext-ix).
|
|
6
|
+
// Message bodies never do.
|
|
7
|
+
//
|
|
8
|
+
// Off the hook path, best effort:
|
|
9
|
+
// - Nothing on the hook path changes. `p2p status` already keeps this device's own statuses
|
|
10
|
+
// (`peers`, self); `p2p watch`, the one long-running command, reads them every
|
|
11
|
+
// GRAPH_MEMORY_TICK_MS, turns what changed since it last looked into items, and queues them
|
|
12
|
+
// (`graphMemory`, under the state lock, so two watches never queue the same thing twice).
|
|
13
|
+
// - The queue is bounded (GRAPH_MEMORY_QUEUE_MAX): past it, new items are dropped and counted
|
|
14
|
+
// (`p2p doctor` says how many, and why). So are items a write refused or failed.
|
|
15
|
+
// - The same watch drains it, a batch at a time, one at a time per process, through the
|
|
16
|
+
// extension's memory writer (ExtMemory: ext-ix's runs OSS `ix note` / `ix session`).
|
|
17
|
+
// - Without the Ix extension, without Ix, or with an Ix that has no local `ix note` (or whose
|
|
18
|
+
// `ix note` is Ix Pro's, the cloud), nothing is gathered at all: nothing changes. The doctor
|
|
19
|
+
// says why.
|
|
20
|
+
//
|
|
21
|
+
// Local only: each batch is for one session, and its graph target (projects.ts graphTarget, the
|
|
22
|
+
// chokepoint) must be local, or the batch is dropped (`not_local`) and nothing is asked of the
|
|
23
|
+
// extension. The extension checks the target again. No shared target exists today; the refusal
|
|
24
|
+
// is explicit so a later shared graph can't receive memory by accident.
|
|
25
|
+
import { sanitizePeerText } from "@peer2peer/core/v3";
|
|
26
|
+
import { graphMemoryEnabled } from "./config.js";
|
|
27
|
+
import { extContext } from "./ext-host.js";
|
|
28
|
+
import { memoryOf } from "./extensions.js";
|
|
29
|
+
import { graphTarget, sessionCeiling, sessionDirs } from "./projects.js";
|
|
30
|
+
import { sessionEnded } from "./running.js";
|
|
31
|
+
/** How often `p2p watch` gathers and drains (P2P_IX_MEMORY_TICK_MS, 1-60 s, for tests). */
|
|
32
|
+
export const GRAPH_MEMORY_TICK_MS = 5_000;
|
|
33
|
+
/** At most this many items wait; past it, new ones are dropped (counted as `queue_full`). */
|
|
34
|
+
export const GRAPH_MEMORY_QUEUE_MAX = 64;
|
|
35
|
+
/** At most this many items are handed over in one drain. */
|
|
36
|
+
export const GRAPH_MEMORY_BATCH = 16;
|
|
37
|
+
/** At most this many sessions are tracked (the oldest ended ones go first). */
|
|
38
|
+
export const GRAPH_MEMORY_SESSIONS_MAX = 64;
|
|
39
|
+
/** At most this many files are remembered as recorded per session. */
|
|
40
|
+
export const GRAPH_MEMORY_FILES_MAX = 200;
|
|
41
|
+
/** A session first seen with no status newer than this isn't recorded (one from before an upgrade). */
|
|
42
|
+
export const GRAPH_MEMORY_FRESH_MS = 6 * 3600_000;
|
|
43
|
+
/** While memory is unavailable, it is asked again this often (Ix installed or upgraded meanwhile). */
|
|
44
|
+
export const GRAPH_MEMORY_RECHECK_MS = 5 * 60_000;
|
|
45
|
+
/** One drain gives up waiting on the extension after this long (its `ix` calls are bounded too). */
|
|
46
|
+
export const GRAPH_MEMORY_DRAIN_MS = 120_000;
|
|
47
|
+
const emptyDoc = () => ({ v: 1, sessions: {}, queue: [], written: 0, dropped: {} });
|
|
48
|
+
function docOf(cur) {
|
|
49
|
+
if (!cur || cur.v !== 1 || typeof cur !== "object")
|
|
50
|
+
return emptyDoc();
|
|
51
|
+
return {
|
|
52
|
+
v: 1,
|
|
53
|
+
sessions: cur.sessions && typeof cur.sessions === "object" ? { ...cur.sessions } : {},
|
|
54
|
+
queue: Array.isArray(cur.queue) ? [...cur.queue] : [],
|
|
55
|
+
written: typeof cur.written === "number" ? cur.written : 0,
|
|
56
|
+
dropped: cur.dropped && typeof cur.dropped === "object" ? { ...cur.dropped } : {},
|
|
57
|
+
...(cur.lastWriteAt ? { lastWriteAt: cur.lastWriteAt } : {}),
|
|
58
|
+
...(cur.lastDropAt ? { lastDropAt: cur.lastDropAt } : {}),
|
|
59
|
+
...(cur.unavailable ? { unavailable: cur.unavailable } : {}),
|
|
60
|
+
...(cur.leases && typeof cur.leases === "object" ? { leases: { ...cur.leases } } : {}),
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
const short = (s, max) => (typeof s === "string" ? sanitizePeerText(s, max).trim() : "");
|
|
64
|
+
/** Every file a status names: its own and its agents'. */
|
|
65
|
+
function statusFiles(rec) {
|
|
66
|
+
const out = new Set();
|
|
67
|
+
for (const f of rec.status.files ?? [])
|
|
68
|
+
if (typeof f === "string")
|
|
69
|
+
out.add(f);
|
|
70
|
+
for (const a of rec.status.agents ?? [])
|
|
71
|
+
for (const f of a.files ?? [])
|
|
72
|
+
if (typeof f === "string")
|
|
73
|
+
out.add(f);
|
|
74
|
+
return [...out];
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* What changed in this device's own sessions since the last look, as items, queued (pure, for
|
|
78
|
+
* tests: `ended` says whether a session's watch is gone). Returns the next doc and how many were
|
|
79
|
+
* queued and dropped. Only sessions `recordable` says yes to are gathered: a session whose project
|
|
80
|
+
* ceiling isn't shared (a private or unmapped project, `.p2p-private`, not bound yet) is never
|
|
81
|
+
* recorded, and one that becomes so stops being recorded (fail closed: its context never reaches a
|
|
82
|
+
* graph that a shared session's agent could read and pass on).
|
|
83
|
+
*/
|
|
84
|
+
export function gather(doc, recs, ended, now = Date.now(), recordable = () => true) {
|
|
85
|
+
const next = docOf(doc);
|
|
86
|
+
let queued = 0;
|
|
87
|
+
let dropped = 0;
|
|
88
|
+
const push = (item) => {
|
|
89
|
+
if (next.queue.length >= GRAPH_MEMORY_QUEUE_MAX) {
|
|
90
|
+
next.dropped.queue_full = (next.dropped.queue_full ?? 0) + 1;
|
|
91
|
+
next.lastDropAt = now;
|
|
92
|
+
dropped++;
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
next.queue.push(item);
|
|
96
|
+
queued++;
|
|
97
|
+
};
|
|
98
|
+
for (const rec of recs) {
|
|
99
|
+
const sid = rec.sid;
|
|
100
|
+
if (!recordable(sid))
|
|
101
|
+
continue;
|
|
102
|
+
let s = next.sessions[sid];
|
|
103
|
+
const isEnded = ended(sid);
|
|
104
|
+
if (!s) {
|
|
105
|
+
// A session from before this ran (or one already over): not recorded after the fact.
|
|
106
|
+
if (isEnded || now - rec.ts > GRAPH_MEMORY_FRESH_MS)
|
|
107
|
+
continue;
|
|
108
|
+
s = { start: now, files: [] };
|
|
109
|
+
push({ sid, kind: "start", at: rec.ts, label: short(rec.status.label, 64) || "session", ...(rec.status.repo ? { repo: short(rec.status.repo, 200) } : {}), ...(rec.status.branch ? { branch: short(rec.status.branch, 128) } : {}) });
|
|
110
|
+
}
|
|
111
|
+
if (s.ended)
|
|
112
|
+
continue;
|
|
113
|
+
const summary = short(rec.status.summary, 280);
|
|
114
|
+
if (summary && summary !== s.summary) {
|
|
115
|
+
push({ sid, kind: "status", at: rec.status.summaryAt ?? rec.ts, summary });
|
|
116
|
+
s = { ...s, summary };
|
|
117
|
+
}
|
|
118
|
+
const known = new Set(s.files);
|
|
119
|
+
const fresh = statusFiles(rec).filter((f) => !known.has(f));
|
|
120
|
+
if (fresh.length > 0) {
|
|
121
|
+
push({ sid, kind: "files", at: rec.ts, files: fresh });
|
|
122
|
+
s = { ...s, files: [...s.files, ...fresh].slice(-GRAPH_MEMORY_FILES_MAX) };
|
|
123
|
+
}
|
|
124
|
+
if (isEnded) {
|
|
125
|
+
push({ sid, kind: "end", at: rec.ts });
|
|
126
|
+
s = { ...s, ended: now };
|
|
127
|
+
}
|
|
128
|
+
next.sessions[sid] = s;
|
|
129
|
+
}
|
|
130
|
+
// Bounded: ended sessions a day old go, then the oldest.
|
|
131
|
+
const entries = Object.entries(next.sessions).filter(([, s]) => !(s.ended && now - s.ended > 24 * 3600_000));
|
|
132
|
+
entries.sort((a, b) => a[1].start - b[1].start);
|
|
133
|
+
next.sessions = Object.fromEntries(entries.slice(-GRAPH_MEMORY_SESSIONS_MAX));
|
|
134
|
+
return { doc: next, queued, dropped };
|
|
135
|
+
}
|
|
136
|
+
/** This device's own sessions' last statuses. */
|
|
137
|
+
async function ownRecs(app) {
|
|
138
|
+
const peers = (await app.state.get("peers")) ?? {};
|
|
139
|
+
return Object.values(peers).filter((r) => r && r.self === true && r.own === app.userId && r.did === app.did && typeof r.sid === "string" && r.status && typeof r.status === "object");
|
|
140
|
+
}
|
|
141
|
+
/** Gathers and queues what changed (under the state lock). */
|
|
142
|
+
export async function gatherGraphMemory(app, now = Date.now()) {
|
|
143
|
+
const recs = await ownRecs(app);
|
|
144
|
+
if (recs.length === 0)
|
|
145
|
+
return { queued: 0, dropped: 0 };
|
|
146
|
+
// Only sessions whose project ceiling is shared (projects.ts sessionCeiling): private ones never.
|
|
147
|
+
const shared = new Set();
|
|
148
|
+
for (const r of recs)
|
|
149
|
+
if ((await sessionCeiling(app, r.sid).catch(() => ({ kind: "private" }))).kind === "shared")
|
|
150
|
+
shared.add(r.sid);
|
|
151
|
+
return app.state.update("graphMemory", (cur) => {
|
|
152
|
+
const before = docOf(cur);
|
|
153
|
+
const r = gather(before, recs, (sid) => sessionEnded(app, sid), now, (sid) => shared.has(sid));
|
|
154
|
+
// Unchanged: nothing written (this runs every few seconds).
|
|
155
|
+
const changed = JSON.stringify(r.doc) !== JSON.stringify(before);
|
|
156
|
+
return { ...(changed ? { next: r.doc } : {}), result: { queued: r.queued, dropped: r.dropped } };
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
/** Counts `n` dropped items under `reason`. */
|
|
160
|
+
async function countDropped(app, reason, n) {
|
|
161
|
+
if (n <= 0)
|
|
162
|
+
return;
|
|
163
|
+
const key = /^[a-z_]{1,32}$/.test(reason) ? reason : "other";
|
|
164
|
+
await app.state.update("graphMemory", (cur) => {
|
|
165
|
+
const d = docOf(cur);
|
|
166
|
+
d.dropped[key] = (d.dropped[key] ?? 0) + n;
|
|
167
|
+
d.lastDropAt = Date.now();
|
|
168
|
+
return { next: d, result: undefined };
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
/** Records why memory is off (or that it is on again). */
|
|
172
|
+
async function noteAvailability(app, u) {
|
|
173
|
+
await app.state.update("graphMemory", (cur) => {
|
|
174
|
+
const d = docOf(cur);
|
|
175
|
+
const was = d.unavailable;
|
|
176
|
+
if (!u && !was)
|
|
177
|
+
return { result: undefined };
|
|
178
|
+
if (u && was && was.reason === u.reason)
|
|
179
|
+
return { result: undefined };
|
|
180
|
+
if (u)
|
|
181
|
+
d.unavailable = { reason: short(u.reason, 32) || "unavailable", message: short(u.message, 300), at: Date.now() };
|
|
182
|
+
else
|
|
183
|
+
delete d.unavailable;
|
|
184
|
+
return { next: d, result: undefined };
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
/** After a timed-out batch is aborted, how long the drain waits for the writer to settle before giving up on it. */
|
|
188
|
+
export const GRAPH_MEMORY_SETTLE_MS = 30_000;
|
|
189
|
+
/** How long a session's lease lasts: past every drain's own bound, then free again (a crashed writer). */
|
|
190
|
+
export const GRAPH_MEMORY_LEASE_MS = 2 * GRAPH_MEMORY_DRAIN_MS + 60_000;
|
|
191
|
+
/**
|
|
192
|
+
* One batch: up to GRAPH_MEMORY_BATCH items taken off the queue (they are the taker's now), of
|
|
193
|
+
* sessions no other drain holds a lease on; their leases are taken with them, under the state lock.
|
|
194
|
+
*/
|
|
195
|
+
async function take(app, now = Date.now()) {
|
|
196
|
+
return app.state.update("graphMemory", (cur) => {
|
|
197
|
+
const d = docOf(cur);
|
|
198
|
+
if (d.queue.length === 0)
|
|
199
|
+
return { result: [] };
|
|
200
|
+
const leases = Object.fromEntries(Object.entries(d.leases ?? {}).filter(([, until]) => typeof until === "number" && until > now));
|
|
201
|
+
const batch = [];
|
|
202
|
+
const rest = [];
|
|
203
|
+
for (const it of d.queue)
|
|
204
|
+
(batch.length < GRAPH_MEMORY_BATCH && !leases[it.sid] ? batch : rest).push(it);
|
|
205
|
+
if (batch.length === 0)
|
|
206
|
+
return { result: [] };
|
|
207
|
+
for (const it of batch)
|
|
208
|
+
leases[it.sid] = now + GRAPH_MEMORY_LEASE_MS;
|
|
209
|
+
d.queue = rest;
|
|
210
|
+
d.leases = leases;
|
|
211
|
+
return { next: d, result: batch };
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
/** Gives the leases of `sids` back. */
|
|
215
|
+
async function release(app, sids) {
|
|
216
|
+
await app.state.update("graphMemory", (cur) => {
|
|
217
|
+
const d = docOf(cur);
|
|
218
|
+
if (!d.leases)
|
|
219
|
+
return { result: undefined };
|
|
220
|
+
for (const sid of sids)
|
|
221
|
+
delete d.leases[sid];
|
|
222
|
+
if (Object.keys(d.leases).length === 0)
|
|
223
|
+
delete d.leases;
|
|
224
|
+
return { next: d, result: undefined };
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
/** `p`, or "timeout" after `ms` (the work goes on: the caller aborts it and waits for it to settle). */
|
|
228
|
+
const within = (p, ms) => Promise.race([p, new Promise((r) => setTimeout(() => r("timeout"), ms).unref())]);
|
|
229
|
+
/**
|
|
230
|
+
* Hands the next batch to the extension, a session at a time. A session whose graph target isn't
|
|
231
|
+
* local is never handed over: its items are dropped as `not_local`. Returns what happened.
|
|
232
|
+
*/
|
|
233
|
+
export async function drainGraphMemory(app, ext, mem, deps = {}) {
|
|
234
|
+
const batch = await take(app);
|
|
235
|
+
if (batch.length === 0)
|
|
236
|
+
return { written: 0, dropped: 0 };
|
|
237
|
+
// A writer that never settled after its abort keeps its session's lease until it expires (no one
|
|
238
|
+
// else writes that session meanwhile); every other lease goes back now.
|
|
239
|
+
const abandoned = new Set();
|
|
240
|
+
try {
|
|
241
|
+
return await drainBatch(app, ext, mem, batch, deps, abandoned);
|
|
242
|
+
}
|
|
243
|
+
finally {
|
|
244
|
+
await release(app, [...new Set(batch.map((i) => i.sid))].filter((s) => !abandoned.has(s))).catch(() => undefined);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
async function drainBatch(app, ext, mem, batch, deps, abandoned) {
|
|
248
|
+
const ctx = extContext(app, ext, { out: () => { }, err: (s) => deps.log?.(s) }, true, async () => false);
|
|
249
|
+
const target = deps.target ??
|
|
250
|
+
((sid) => {
|
|
251
|
+
const { dirs, over } = sessionDirs(app.env);
|
|
252
|
+
return graphTarget(app, { sid, dirs, over });
|
|
253
|
+
});
|
|
254
|
+
let written = 0;
|
|
255
|
+
let dropped = 0;
|
|
256
|
+
const bySid = new Map();
|
|
257
|
+
for (const { sid, ...item } of batch)
|
|
258
|
+
bySid.set(sid, [...(bySid.get(sid) ?? []), item]);
|
|
259
|
+
const groups = [...bySid];
|
|
260
|
+
for (let g = 0; g < groups.length; g++) {
|
|
261
|
+
const [sid, items] = groups[g];
|
|
262
|
+
let t;
|
|
263
|
+
try {
|
|
264
|
+
t = await target(sid);
|
|
265
|
+
}
|
|
266
|
+
catch {
|
|
267
|
+
t = { kind: "shared", circle: "?", endpoint: "" };
|
|
268
|
+
}
|
|
269
|
+
if (t.kind !== "local") {
|
|
270
|
+
// Explicit: graph memory goes to the local graph only.
|
|
271
|
+
await countDropped(app, "not_local", items.length);
|
|
272
|
+
dropped += items.length;
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
// Gathered while shared; written only if it still is (a session can turn private in between).
|
|
276
|
+
if ((await sessionCeiling(app, sid).catch(() => ({ kind: "private" }))).kind !== "shared") {
|
|
277
|
+
await countDropped(app, "not_shared", items.length);
|
|
278
|
+
dropped += items.length;
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
281
|
+
// A real deadline: past it the writer is told to stop (it checks the signal before every write),
|
|
282
|
+
// and this waits for it to settle, so no write overlaps the next batch or follows the timeout.
|
|
283
|
+
const stop = new AbortController();
|
|
284
|
+
const writing = Promise.resolve()
|
|
285
|
+
.then(() => mem.write(ctx, { sid, items, signal: stop.signal }))
|
|
286
|
+
.catch(() => undefined);
|
|
287
|
+
let r = await within(writing, deps.deadlineMs ?? GRAPH_MEMORY_DRAIN_MS);
|
|
288
|
+
if (r === "timeout") {
|
|
289
|
+
stop.abort();
|
|
290
|
+
// Bounded: a writer that ignores the abort is given up on (its lease runs out; nothing else waits for it).
|
|
291
|
+
const late = await within(writing, deps.settleMs ?? GRAPH_MEMORY_SETTLE_MS);
|
|
292
|
+
if (late === "timeout") {
|
|
293
|
+
abandoned.add(sid);
|
|
294
|
+
await countDropped(app, "timeout", items.length);
|
|
295
|
+
dropped += items.length;
|
|
296
|
+
continue;
|
|
297
|
+
}
|
|
298
|
+
// What it wrote before it stopped still counts; the rest timed out.
|
|
299
|
+
const lateOk = late && typeof late === "object" ? Math.max(0, Math.min(items.length, Number(late.written) || 0)) : 0;
|
|
300
|
+
r = { written: lateOk, failed: [{ reason: "timeout", n: items.length - lateOk }] };
|
|
301
|
+
}
|
|
302
|
+
if (r === undefined || typeof r !== "object") {
|
|
303
|
+
await countDropped(app, "ext_failed", items.length);
|
|
304
|
+
dropped += items.length;
|
|
305
|
+
continue;
|
|
306
|
+
}
|
|
307
|
+
const ok = Math.max(0, Math.min(items.length, Number(r.written) || 0));
|
|
308
|
+
written += ok;
|
|
309
|
+
if (ok > 0) {
|
|
310
|
+
await app.state.update("graphMemory", (cur) => {
|
|
311
|
+
const d = docOf(cur);
|
|
312
|
+
d.written += ok;
|
|
313
|
+
d.lastWriteAt = Date.now();
|
|
314
|
+
return { next: d, result: undefined };
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
for (const f of Array.isArray(r.failed) ? r.failed : []) {
|
|
318
|
+
const n = Math.max(0, Math.min(items.length, Number(f?.n) || 0));
|
|
319
|
+
await countDropped(app, String(f?.reason ?? "other"), n);
|
|
320
|
+
dropped += n;
|
|
321
|
+
}
|
|
322
|
+
if (r.unavailable) {
|
|
323
|
+
// Whatever is still queued would meet the same answer: off until it is asked again. This
|
|
324
|
+
// batch's other sessions are dropped (counted), never handed over.
|
|
325
|
+
await noteAvailability(app, r.unavailable);
|
|
326
|
+
const left = groups.slice(g + 1).reduce((a, [, its]) => a + its.length, 0);
|
|
327
|
+
await countDropped(app, short(r.unavailable.reason, 32) || "unavailable", left);
|
|
328
|
+
return { written, dropped: dropped + left, unavailable: r.unavailable };
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
return { written, dropped };
|
|
332
|
+
}
|
|
333
|
+
/** The tick interval (P2P_IX_MEMORY_TICK_MS, 1-60 s). */
|
|
334
|
+
export function graphMemoryTickMs(env) {
|
|
335
|
+
const n = Number(env.P2P_IX_MEMORY_TICK_MS);
|
|
336
|
+
return Number.isInteger(n) && n >= 1000 && n <= 60_000 ? n : GRAPH_MEMORY_TICK_MS;
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* The loop `p2p watch` runs: `tick()` gathers and drains when memory is on and available (asked of
|
|
340
|
+
* the extension at most every GRAPH_MEMORY_RECHECK_MS while it isn't). Never throws; one tick at a
|
|
341
|
+
* time.
|
|
342
|
+
*/
|
|
343
|
+
export function graphMemoryLoop(app, deps = {}) {
|
|
344
|
+
let busy = false;
|
|
345
|
+
let okUntil = 0;
|
|
346
|
+
let offUntil = 0;
|
|
347
|
+
return {
|
|
348
|
+
tick: async () => {
|
|
349
|
+
if (busy)
|
|
350
|
+
return;
|
|
351
|
+
busy = true;
|
|
352
|
+
try {
|
|
353
|
+
if (!graphMemoryEnabled(app.env, app.home))
|
|
354
|
+
return;
|
|
355
|
+
const ext = app.extensions?.get("ix");
|
|
356
|
+
const mem = memoryOf(ext);
|
|
357
|
+
if (!ext || !mem)
|
|
358
|
+
return;
|
|
359
|
+
const now = Date.now();
|
|
360
|
+
if (now < offUntil)
|
|
361
|
+
return;
|
|
362
|
+
if (now >= okUntil) {
|
|
363
|
+
const ctx = extContext(app, ext, { out: () => { }, err: (s) => deps.log?.(s) }, true, async () => false);
|
|
364
|
+
const a = await within(mem.available(ctx).catch((e) => ({ ok: false, reason: "ext_failed", message: String(e?.message ?? e) })), GRAPH_MEMORY_DRAIN_MS);
|
|
365
|
+
const u = a === "timeout" ? { ok: false, reason: "timeout", message: "Ix didn't answer in time" } : a.ok ? undefined : a;
|
|
366
|
+
await noteAvailability(app, u);
|
|
367
|
+
if (u) {
|
|
368
|
+
offUntil = now + GRAPH_MEMORY_RECHECK_MS;
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
okUntil = now + GRAPH_MEMORY_RECHECK_MS;
|
|
372
|
+
}
|
|
373
|
+
await gatherGraphMemory(app);
|
|
374
|
+
const r = await drainGraphMemory(app, ext, mem, deps);
|
|
375
|
+
if (r.unavailable) {
|
|
376
|
+
okUntil = 0;
|
|
377
|
+
offUntil = Date.now() + GRAPH_MEMORY_RECHECK_MS;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
catch (e) {
|
|
381
|
+
deps.log?.(`p2p watch: graph memory: ${sanitizePeerText(String(e?.message ?? e), 200)}`);
|
|
382
|
+
}
|
|
383
|
+
finally {
|
|
384
|
+
busy = false;
|
|
385
|
+
}
|
|
386
|
+
},
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
/** What `p2p doctor` says about graph memory (undefined: nothing recorded yet). */
|
|
390
|
+
export async function graphMemoryReport(app) {
|
|
391
|
+
const d = await app.state.get("graphMemory");
|
|
392
|
+
return d ? docOf(d) : undefined;
|
|
393
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import type { App } from "./app.js";
|
|
2
|
+
import type { EventRec } from "./state.js";
|
|
3
|
+
/** Kept this long by default (config.json `history.retentionDays`). */
|
|
4
|
+
export declare const HISTORY_RETENTION_DAYS = 30;
|
|
5
|
+
export declare const HISTORY_RETENTION_MIN_DAYS = 1;
|
|
6
|
+
export declare const HISTORY_RETENTION_MAX_DAYS = 365;
|
|
7
|
+
/** At most this many bytes of records by default (config.json `history.maxBytes`). */
|
|
8
|
+
export declare const HISTORY_MAX_BYTES: number;
|
|
9
|
+
export declare const HISTORY_MIN_BYTES: number;
|
|
10
|
+
export declare const HISTORY_MAX_BYTES_CAP: number;
|
|
11
|
+
/** A segment is closed past this many bytes of records (each write rewrites only the newest). */
|
|
12
|
+
export declare const SEGMENT_BYTES: number;
|
|
13
|
+
/** One record's text is at most this long (a message is at most 24 KiB anyway). */
|
|
14
|
+
export declare const MAX_RECORD_TEXT: number;
|
|
15
|
+
/** `p2p history` lists at most this many by default, the newest. */
|
|
16
|
+
export declare const HISTORY_LIST_DEFAULT = 50;
|
|
17
|
+
export declare const HISTORY_LIST_MAX = 1000;
|
|
18
|
+
export interface HistoryRec {
|
|
19
|
+
/** The event id for one received (what `p2p watch` printed), or `out:<random>`. */
|
|
20
|
+
id: string;
|
|
21
|
+
/** When it was recorded here (ms, this device's clock): retention, `--since` and the boundary check use it. */
|
|
22
|
+
at: number;
|
|
23
|
+
/** Received: when the sender says it sent it (the envelope's ts, the sender's clock). */
|
|
24
|
+
sentAt?: number;
|
|
25
|
+
dir: "in" | "out";
|
|
26
|
+
type: "message" | "ext";
|
|
27
|
+
/**
|
|
28
|
+
* The local session it belongs to: the one it went into or was sent from. Absent: sent to this
|
|
29
|
+
* user with no session (the person's inbox, as session `tui` is).
|
|
30
|
+
*/
|
|
31
|
+
session?: string;
|
|
32
|
+
/** The other side (for a message between two of your own sessions, you). */
|
|
33
|
+
peer: {
|
|
34
|
+
userId: string;
|
|
35
|
+
address: string;
|
|
36
|
+
self?: true;
|
|
37
|
+
};
|
|
38
|
+
/** Their session (or ours, for a message into a session of ours), when known. */
|
|
39
|
+
peerSession?: {
|
|
40
|
+
own: string;
|
|
41
|
+
sid: string;
|
|
42
|
+
ref: string;
|
|
43
|
+
};
|
|
44
|
+
/** The circle the peer session's roster names, when it has one. */
|
|
45
|
+
circle?: string;
|
|
46
|
+
/** Message text as sent or received (peer data), or an extension kind's fallback line. */
|
|
47
|
+
text: string;
|
|
48
|
+
/** Extension kinds: the kind (`x:<ns>.<type>`). */
|
|
49
|
+
ext?: string;
|
|
50
|
+
/** Sends: what became of it when it was sent. */
|
|
51
|
+
state?: "sent" | "offline" | "outbox";
|
|
52
|
+
/**
|
|
53
|
+
* The session's projects when it was recorded (projects.ts), for the boundary check on reads.
|
|
54
|
+
* UNBOUND when the session had none, or they couldn't be read: such a record is never shown to a
|
|
55
|
+
* session's reader, only to the person.
|
|
56
|
+
*/
|
|
57
|
+
projects?: string[];
|
|
58
|
+
}
|
|
59
|
+
export interface HistorySettings {
|
|
60
|
+
enabled: boolean;
|
|
61
|
+
retentionDays: number;
|
|
62
|
+
maxBytes: number;
|
|
63
|
+
}
|
|
64
|
+
/** What config.json and P2P_HISTORY say (out-of-range values are clamped; a broken config.json: the defaults). */
|
|
65
|
+
export declare function historySettings(app: Pick<App, "env" | "home">): HistorySettings;
|
|
66
|
+
export declare function historyKeyFile(home: string): string;
|
|
67
|
+
/** At most this many set-aside files are kept (each also goes once it is past retention). */
|
|
68
|
+
export declare const MAX_QUARANTINED = 16;
|
|
69
|
+
/**
|
|
70
|
+
* Appends records, then prunes by age and size, under the state lock. Never throws: history is a
|
|
71
|
+
* convenience, and a full disk or a missing key must not fail a send or a delivery.
|
|
72
|
+
*/
|
|
73
|
+
export declare function recordHistory(app: App, recs: readonly HistoryRec[], now?: number): Promise<void>;
|
|
74
|
+
/**
|
|
75
|
+
* `p2p history --clear`: every segment, the index and its copy, set-aside files and the key, and the
|
|
76
|
+
* messages and extension notices in the event log `p2p watch` reads (events.json), so no copy of
|
|
77
|
+
* their text is left in P2P_HOME. A message a session's watch hasn't printed yet is gone with it.
|
|
78
|
+
*/
|
|
79
|
+
export declare function clearHistory(app: App): Promise<{
|
|
80
|
+
cleared: number;
|
|
81
|
+
events: number;
|
|
82
|
+
}>;
|
|
83
|
+
/** The marker a record carries when its session's projects were unknown (fail closed: the person's only). */
|
|
84
|
+
export declare const UNBOUND = "!unbound";
|
|
85
|
+
/** Received messages and extension notices among events just added to the log (inbound.ts). */
|
|
86
|
+
export declare function recordEvents(app: App, events: readonly EventRec[]): Promise<void>;
|
|
87
|
+
/** A send this device made (sessions.ts sendMessage, sendExtension). */
|
|
88
|
+
export declare function recordSent(app: App, o: {
|
|
89
|
+
fromSession: string;
|
|
90
|
+
to: {
|
|
91
|
+
userId: string;
|
|
92
|
+
address: string;
|
|
93
|
+
own: string;
|
|
94
|
+
sid: string;
|
|
95
|
+
ref: string;
|
|
96
|
+
};
|
|
97
|
+
text: string;
|
|
98
|
+
ext?: string;
|
|
99
|
+
state?: HistoryRec["state"];
|
|
100
|
+
}): Promise<void>;
|
|
101
|
+
/** Whether a record is the person's own inbox: to no session, or the `tui` session's. */
|
|
102
|
+
export declare function isPersonRecord(r: HistoryRec): boolean;
|
|
103
|
+
export type HistoryReader = {
|
|
104
|
+
person: true;
|
|
105
|
+
} | {
|
|
106
|
+
person: false;
|
|
107
|
+
sid: string;
|
|
108
|
+
projects: Set<string>;
|
|
109
|
+
since: number;
|
|
110
|
+
};
|
|
111
|
+
/**
|
|
112
|
+
* Who may read: the person (every record), or one session (its own records, within its projects).
|
|
113
|
+
* `sid` absent or `tui`: the person's own view. The gates are the existing ones (projects.ts):
|
|
114
|
+
* assertPersonForWidening for the person, the registration a front end made for a session.
|
|
115
|
+
*/
|
|
116
|
+
export declare function assertHistoryReader(app: App, sid: string | undefined): Promise<HistoryReader>;
|
|
117
|
+
/**
|
|
118
|
+
* Whether `reader` may see `r`. A session sees only its own: recorded since its binding began (a
|
|
119
|
+
* binding made anew, after the old one expired, inherits nothing), with projects known (never
|
|
120
|
+
* UNBOUND or none), all of which it is still bound to.
|
|
121
|
+
*/
|
|
122
|
+
export declare function mayRead(reader: HistoryReader, r: HistoryRec): boolean;
|
|
123
|
+
export interface HistoryQuery {
|
|
124
|
+
session?: string;
|
|
125
|
+
peer?: string;
|
|
126
|
+
circle?: string;
|
|
127
|
+
since?: number;
|
|
128
|
+
limit?: number;
|
|
129
|
+
/** The person's view only: just their inbox (session tui, or none). */
|
|
130
|
+
inbox?: boolean;
|
|
131
|
+
}
|
|
132
|
+
export interface HistoryResult {
|
|
133
|
+
messages: (HistoryRec & {
|
|
134
|
+
inbox?: true;
|
|
135
|
+
})[];
|
|
136
|
+
/** More matched than `limit`: the oldest of them were left out. */
|
|
137
|
+
truncated: boolean;
|
|
138
|
+
/** History documents that couldn't be opened (set aside at the next write). */
|
|
139
|
+
unreadable?: number;
|
|
140
|
+
retention: {
|
|
141
|
+
days: number;
|
|
142
|
+
maxBytes: number;
|
|
143
|
+
enabled: boolean;
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
/** Parses `--since`: `30m`, `12h`, `7d`, `2w`, or a date (ISO 8601). */
|
|
147
|
+
export declare function parseSince(s: string, now?: number): number;
|
|
148
|
+
/** `p2p history`: the records `reader` may see that match `q`, oldest first, at most `limit` (the newest). */
|
|
149
|
+
export declare function readHistory(app: App, reader: HistoryReader, q?: HistoryQuery, now?: number): Promise<HistoryResult>;
|
|
150
|
+
/** One record as a terminal line: peer text sanitized (no control, bidi or format characters, one line). */
|
|
151
|
+
export declare function historyLine(r: HistoryRec): string;
|
|
152
|
+
/** What one record shows at most, in a terminal or to a model (the rest: `--json`). */
|
|
153
|
+
export declare const HISTORY_SHOW_MAX = 4000;
|
|
154
|
+
/** `s` cut at HISTORY_SHOW_MAX characters, saying so. */
|
|
155
|
+
export declare function capText(s: string, max?: number): string;
|