@astrofoundry/pi-astro 0.40.83 → 0.40.84
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/package.json
CHANGED
package/skills/arcane/SKILL.md
CHANGED
|
@@ -7,7 +7,7 @@ description: How the Arcane specialist operates the Arcane container platform an
|
|
|
7
7
|
|
|
8
8
|
Arcane manages the Docker host on VM 100 (`10.0.40.30`). Every app is a Compose project synced from the GitOps repository `astronaute77/arcane`, branch `main`, into `/opt/docker`. The `arcane` tool wraps `arcane-cli` with a fresh short-lived token on every call and adds `git` subcommands for the repository checkout. `arcane-cli gitops ...` (server-side syncs) passes through untouched.
|
|
9
9
|
|
|
10
|
-
Since 2026-11-09 a second environment, `mira`, runs the `media-mira` project on media-mira (`10.1.40.30`, VM 111 on SPACE-X at Mira) through an Arcane agent (v3.0.1, a gRPC tunnel to the manager). `stack-update`, `stack-rollback`, `deployment`, and `release-notes` find a stack's environment themselves; `update-report`, `container-watch`, and `project-status` cover every environment and name the remote one in `environment`. A raw arcane-cli call on Mira needs `--agent f1968df8-bce3-4a65-966f-72934727ae86`; a call without `--agent` goes to the manager's own host (agent `0`). arcane-cli 3 calls them agents (`agents list`, `agents version <id>`), not environments. The `host` commands reach VM 100 only.
|
|
10
|
+
Since 2026-11-09 a second environment, `mira`, runs the `media-mira` project on media-mira (`10.1.40.30`, VM 111 on SPACE-X at Mira) through an Arcane agent (v3.0.1, a gRPC tunnel to the manager). `stack-update`, `stack-rollback`, `deployment`, and `release-notes` find a stack's environment themselves; `update-report`, `container-watch`, and `project-status` cover every environment and name the remote one in `environment`. A raw arcane-cli call on Mira needs `--agent f1968df8-bce3-4a65-966f-72934727ae86`; a call without `--agent` goes to the manager's own host (agent `0`). arcane-cli 3 calls them agents (`agents list`, `agents version <id>`), not environments. The `host` commands reach VM 100 only; for a container on Mira, read its log with `["container-logs", "<name>", "<since>", "<until>"]` (below).
|
|
11
11
|
|
|
12
12
|
## Calling the tool
|
|
13
13
|
|
|
@@ -106,6 +106,8 @@ When the bridge's Upgrade carefully thread gives you a plan task, read the notes
|
|
|
106
106
|
|
|
107
107
|
`["change-origin", "<path>", "<sha256|->", "<utc>"]` answers whether a deployment-file change Wazuh saw on the Arcane VM (`/opt/docker/<project>/compose.yaml`, `docker-compose.yml`, or `pre-deploy.sh`; rule 100020) is ours. `known` when the new content (its SHA-256 from the alert's `syscheck.sha256_after`), or `-` for a deletion, equals a commit of `<project>/<file>` at origin, any author, CI included; or when our `stack-update`, `manager-upgrade`, `manager-rollback`, or `host db-restore` on that stack ran then (the specialists' audit log). Otherwise `unknown`, with the newest commit touching the file. Arcane syncs the files verbatim, so a GitOps deploy always matches. The Discord bridge calls it for every such alert; an `unknown` change pages the owner.
|
|
108
108
|
|
|
109
|
+
`["container-logs", "<name>", "<since>", "<until>"]` (UTC `YYYY-MM-DDTHH:MM:SSZ`) reads the newest 300 lines of that window for a container on any agent, Mira's included, through Arcane's log download, with credentials masked like `host container-logs ... text`; call them redacted log lines. Use it for Mira's containers (such as `radarr-mira`), where `host container-logs` cannot reach.
|
|
110
|
+
|
|
109
111
|
`["container-watch"]` lists every container with its state, health, exit code, and uptime; containers started or created in the last 30 minutes also carry the start time, the Compose project, and the `operation` (our stack-update, manager-upgrade, manager-rollback, or host db-restore on that stack) whose run covers the start. The Discord bridge polls it every five minutes to detect restarts and redeploys; when it asks you to investigate a container that keeps restarting, read only and propose the fix.
|
|
110
112
|
|
|
111
113
|
`["project-status"]` (or with a project name) lists projects with their GitOps sync: commit, state, hook state, without error text. `["deployment", "check"|"wait", "<project>", "--commit", "<sha>", "--container", "NAME=sha256:ID", ...]` compares the sync and each container's project, image ID, state, and health; `wait` polls every 10 s up to `--timeout` (default 600 s). Read `status` in the answer.
|
package/specialists/AGENTS.md
CHANGED
|
@@ -54,6 +54,7 @@ Wrappers ship as TypeScript and run under Node 24 type stripping: erasable synta
|
|
|
54
54
|
- `REFUSED_PREFIXES` protects only the wrapper itself (`config`, `auth`, `self-update`, `completion`). The GitOps-first rule for managed projects lives in the skill and the agent prompt, not in code, because unmanaged projects and emergencies need the direct CLI.
|
|
55
55
|
- The wrapper's repository commands are the `git` group; `gitops` must stay free because it is an `arcane-cli` command group (server-side syncs).
|
|
56
56
|
- Arcane and arcane-cli run 3.x since 2026-11-16. Without `--agent`, arcane-cli 3 runs a command on every agent and wraps each answer in `{success, agents}`, and asks before a change on all of them; `withAgent` therefore names the agent on every call (`--agent 0`, the manager's own host, unless the call names another), which keeps the plain output shape (`RunScoped` in the CLI's `cmdutil/scope.go`, read at v3.0.1). `environments` is `agents` and `--env` is `--agent` in 3.x. `envContent` (Git sync environment values) is in `ARCANE_DENIED_KEYS`.
|
|
57
|
+
- `arcane container-logs <name> <since> <until>` (0.40.84, `lib/arcane-logs.ts`) finds the container on any agent through `containers list --all` and streams `GET /api/agents/<id>/containers/<containerId>/logs/download` (Arcane 3: the whole log with timestamps, `containers:logs`) with the federated token, keeping the newest 300 stamped lines inside `[since, until)` and stopping at the first line past `until`. `redactText` mirrors `redact_text` of the arcane repository's `host/spc-arcane-probes/incident_probe.py`; change both together. It exists because the `host` commands reach only VM 100, so Radarr's v7 migration log on Mira was out of reach on 2026-11-16.
|
|
57
58
|
- Every call runs with the federated token in `ARCANE_TOKEN`, which arcane-cli 3 uses ahead of any credential in `arcanecli.yml` (`client.New`); the per-call config copy with `jwt_token` that 2.x needed is gone (0.40.83). `cliFailure` names the exit code and the filtered stdout as well as stderr, because a failure can carry nothing else on stderr (the media update on 2026-11-02).
|
|
58
59
|
- Every wrapper answers `--help` without reading config, so agents can discover subcommands before anything else is set up.
|
|
59
60
|
- `entry/specialist-install.sh` runs as root, so it runs only `/usr/bin`, `/bin`, `/usr/sbin`, `/sbin` and the Node it installed, never Homebrew or anything else the main user can write; it checks that `/usr/local/libexec/specialist-node` (and each `specialist-<tool>` folder) and its parents belong to root and are writable by nobody else. Arguments are checked before the root test (tests exercise that part). Downloads go to a root-only temporary directory and are verified before use: Node against `SHASUMS256.txt` and the LTS flag in `index.json`, npm tarballs against the registry's `sha512` integrity, arcane-cli against the release's checksums file. Inside `/Users/specialist` it works only as `specialist` (`sudo -u specialist -H`), from a staging directory root hands over, so a link the specialist plants cannot redirect a root write. Each component switches by rename after a check (every installed wrapper's `--help`, `--version` of the new binary) and restores the previous copy when the check fails. Older versions are refused; `rollback` swaps current and previous. `python`, `gcloud`, `bw`, and `jq` follow the same rules: version folders under `/usr/local/libexec/specialist-<tool>/` behind the links `current` and `previous`, sealed `root:wheel` and not writable by others, smoke-tested as `specialist` before `current` moves; `python` refuses a switch that breaks the current gcloud. Consumers use the `current` paths: `provision.sh` for `bw` and `jq`, `edge.json` for `gcloud` and `gcloudPython`. Nothing a wrapper runs with secrets may come from Homebrew.
|
|
@@ -6,6 +6,7 @@ import { type CommitVersion, coveringOperation, judgeChange, parseChangeQuery, r
|
|
|
6
6
|
import { failedChecks, MANAGER_COMPOSE, MANAGER_IMAGE, normalizeVersion, olderThan, pinCompose, projectSync, syncId, syncReady, utcStamp, type VerifyCheck } from "../lib/arcane-manager.ts";
|
|
7
7
|
import { readConfig } from "../lib/config.ts";
|
|
8
8
|
import { isRecent, listContainer, type WatchedContainer, withDetail } from "../lib/container-watch.ts";
|
|
9
|
+
import { LogWindow } from "../lib/arcane-logs.ts";
|
|
9
10
|
import { containerFacts, deploymentChecks, listRows, parseDeploymentArgs, syncFacts, type DeploymentExpectation } from "../lib/deployment.ts";
|
|
10
11
|
import { ServiceError, UsageError } from "../lib/errors.ts";
|
|
11
12
|
import { withLock } from "../lib/lock.ts";
|
|
@@ -134,6 +135,9 @@ ${Object.entries(HOST_COMMANDS)
|
|
|
134
135
|
docker-compose.yml, pre-deploy.sh) is ours: known when the new content, or the deletion,
|
|
135
136
|
is a commit of <project>/<file> in the GitOps repository, or when our stack-update,
|
|
136
137
|
manager-upgrade, manager-rollback, or host db-restore on that stack ran then (audit log)
|
|
138
|
+
container-logs <name> <since> <until>
|
|
139
|
+
the newest 300 log lines of a UTC window (YYYY-MM-DDTHH:MM:SSZ) of a container on any agent,
|
|
140
|
+
Mira's included, through Arcane's log download; credentials masked (redacted log lines)
|
|
137
141
|
container-watch every container's state in every environment, health, exit code, and uptime; for those started or created in
|
|
138
142
|
the last 30 minutes also the start time, the Compose project, and our stack-update,
|
|
139
143
|
manager-upgrade, manager-rollback, or host db-restore whose run covers the start (JSON)
|
|
@@ -401,6 +405,61 @@ async function changeOrigin(config: ArcaneConfig, args: string[]): Promise<numbe
|
|
|
401
405
|
}
|
|
402
406
|
|
|
403
407
|
/** Container state for the Discord bridge's restart and redeploy checks: one list, plus details only for recent starts. */
|
|
408
|
+
const LOG_UTC = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/;
|
|
409
|
+
const LOG_DOWNLOAD_TIMEOUT_MS = 5 * 60_000;
|
|
410
|
+
|
|
411
|
+
/** A container's log window on any agent, through Arcane's log download, with credentials masked like `host container-logs ... text`. */
|
|
412
|
+
async function containerLogs(config: ArcaneConfig, args: string[]): Promise<number> {
|
|
413
|
+
const usage = "container-logs <name> <since> <until> (UTC YYYY-MM-DDTHH:MM:SSZ, until after since)";
|
|
414
|
+
if (args.length !== 3 || !NAME.test(args[0]) || !LOG_UTC.test(args[1]) || !LOG_UTC.test(args[2])) throw new UsageError(usage);
|
|
415
|
+
const sinceMs = Date.parse(args[1]);
|
|
416
|
+
const untilMs = Date.parse(args[2]);
|
|
417
|
+
if (!(untilMs > sinceMs)) throw new UsageError(usage);
|
|
418
|
+
const found = await withCli(
|
|
419
|
+
config,
|
|
420
|
+
async (cli) => {
|
|
421
|
+
const hits: { env: ArcaneEnv; id: string }[] = [];
|
|
422
|
+
for (const env of await arcaneEnvs(cli)) {
|
|
423
|
+
for (const row of listRows(await cliJson(cli, [...envArgs(env), "containers", "list", "--all"]))) {
|
|
424
|
+
const c = listContainer(row);
|
|
425
|
+
if (c?.name === args[0]) hits.push({ env, id: c.id });
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
return hits;
|
|
429
|
+
},
|
|
430
|
+
undefined,
|
|
431
|
+
);
|
|
432
|
+
if (found.length !== 1) throw new UsageError(found.length === 0 ? `no container named ${args[0]}` : `${args[0]} exists on several agents: ${found.map((f) => f.env.name).join(", ")}`);
|
|
433
|
+
const { env, id } = found[0];
|
|
434
|
+
const token = await federatedToken(config);
|
|
435
|
+
const res = await fetch(`${config.serverUrl}/api/agents/${encodeURIComponent(env.id)}/containers/${encodeURIComponent(id)}/logs/download`, {
|
|
436
|
+
headers: { authorization: `Bearer ${token}` },
|
|
437
|
+
signal: AbortSignal.timeout(LOG_DOWNLOAD_TIMEOUT_MS),
|
|
438
|
+
});
|
|
439
|
+
if (!res.ok || res.body === null) throw new ServiceError(`log download for ${args[0]} answered ${res.status}`);
|
|
440
|
+
const window = new LogWindow(sinceMs, untilMs);
|
|
441
|
+
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
|
|
442
|
+
let rest = "";
|
|
443
|
+
let open = true;
|
|
444
|
+
while (open) {
|
|
445
|
+
const { value, done } = await reader.read();
|
|
446
|
+
if (done) break;
|
|
447
|
+
const parts = (rest + value).split("\n");
|
|
448
|
+
rest = parts.pop() ?? "";
|
|
449
|
+
for (const line of parts) {
|
|
450
|
+
if (!window.push(line.replace(/\r$/, ""))) {
|
|
451
|
+
open = false;
|
|
452
|
+
break;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
if (open && rest.length > 0) window.push(rest);
|
|
457
|
+
await reader.cancel().catch(() => undefined);
|
|
458
|
+
const { lines, omittedOlderLines } = window.result();
|
|
459
|
+
printJson({ name: args[0], agent: env.name, container_id: id, since: args[1], until: args[2], source: "text", redacted: true, omitted_older_lines: omittedOlderLines, lines });
|
|
460
|
+
return 0;
|
|
461
|
+
}
|
|
462
|
+
|
|
404
463
|
async function containerWatch(config: ArcaneConfig, args: string[]): Promise<number> {
|
|
405
464
|
if (args.length > 0) throw new UsageError("container-watch takes no arguments");
|
|
406
465
|
let audit: string;
|
|
@@ -972,6 +1031,7 @@ export async function command(args: string[]): Promise<number> {
|
|
|
972
1031
|
if (args[0] === "release-notes") return releaseNotes(config, args.slice(1));
|
|
973
1032
|
if (args[0] === "change-origin") return changeOrigin(config, args.slice(1));
|
|
974
1033
|
if (args[0] === "container-watch") return containerWatch(config, args.slice(1));
|
|
1034
|
+
if (args[0] === "container-logs") return containerLogs(config, args.slice(1));
|
|
975
1035
|
if (args[0] === "host") return hostCommand(config, args.slice(1));
|
|
976
1036
|
if (args[0] === "project-status") return projectStatus(config, args.slice(1));
|
|
977
1037
|
if (args[0] === "deployment") return deployment(config, args.slice(1));
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { LogWindow, redactText, stampMs, TEXT_CHARS, TEXT_LINES } from "./arcane-logs.ts";
|
|
3
|
+
|
|
4
|
+
const SECRET = "SYNTHETIC_SECRET_MUST_NOT_APPEAR";
|
|
5
|
+
|
|
6
|
+
describe("redactText", () => {
|
|
7
|
+
it("keeps the message and masks credentials", () => {
|
|
8
|
+
const out = redactText(`Startup failed: password=${SECRET} for https://user:${SECRET}@db.example/x, Authorization: Bearer ${SECRET}`);
|
|
9
|
+
expect(out).toContain("Startup failed");
|
|
10
|
+
expect(out).not.toContain(SECRET);
|
|
11
|
+
expect(out).toContain("https://[redacted]@db.example/x");
|
|
12
|
+
});
|
|
13
|
+
it("masks JWTs and long random tokens", () => {
|
|
14
|
+
const jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.c2lnbmF0dXJlc2lnbmF0dXJl";
|
|
15
|
+
expect(redactText(`token ${jwt}`)).not.toContain("eyJhbGci");
|
|
16
|
+
expect(redactText("id a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8")).toBe("id [redacted]");
|
|
17
|
+
});
|
|
18
|
+
it("strips ANSI colors and control characters", () => {
|
|
19
|
+
expect(redactText(`${String.fromCharCode(27)}[92mINF${String.fromCharCode(27)}[0m started\tok`)).toBe("INF started ok");
|
|
20
|
+
});
|
|
21
|
+
it("cuts long messages without keeping a split word", () => {
|
|
22
|
+
const out = redactText(`${"word ".repeat(2000)}tail`);
|
|
23
|
+
expect(out.endsWith(" [cut]")).toBe(true);
|
|
24
|
+
expect(out.length).toBe(TEXT_CHARS + " [cut]".length);
|
|
25
|
+
});
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
describe("stampMs", () => {
|
|
29
|
+
it("reads Docker's nanosecond timestamps", () => {
|
|
30
|
+
expect(stampMs("2026-11-16T05:55:28.150475752Z")).toBe(Date.parse("2026-11-16T05:55:28.150Z"));
|
|
31
|
+
expect(stampMs("2026-11-16T05:55:28Z")).toBe(Date.parse("2026-11-16T05:55:28Z"));
|
|
32
|
+
expect(stampMs("not-a-time")).toBeNull();
|
|
33
|
+
});
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
describe("LogWindow", () => {
|
|
37
|
+
const since = Date.parse("2026-11-16T05:00:00Z");
|
|
38
|
+
const until = Date.parse("2026-11-16T06:00:00Z");
|
|
39
|
+
|
|
40
|
+
it("keeps lines inside the window and stops past its end", () => {
|
|
41
|
+
const w = new LogWindow(since, until);
|
|
42
|
+
expect(w.push("2026-11-16T04:59:59.9Z before")).toBe(true);
|
|
43
|
+
expect(w.push("2026-11-16T05:30:00.123456789Z inside")).toBe(true);
|
|
44
|
+
expect(w.push("unstamped continuation")).toBe(true);
|
|
45
|
+
expect(w.push("2026-11-16T06:00:00Z after")).toBe(false);
|
|
46
|
+
expect(w.result()).toEqual({ lines: [{ timestamp: "2026-11-16T05:30:00.123456789Z", text: "inside" }], omittedOlderLines: 0 });
|
|
47
|
+
});
|
|
48
|
+
it("keeps the newest lines and counts the older ones", () => {
|
|
49
|
+
const w = new LogWindow(since, until);
|
|
50
|
+
for (let i = 0; i < TEXT_LINES + 5; i++) w.push(`2026-11-16T05:${String(Math.floor(i / 60)).padStart(2, "0")}:${String(i % 60).padStart(2, "0")}Z line ${i}`);
|
|
51
|
+
const { lines, omittedOlderLines } = w.result();
|
|
52
|
+
expect(lines).toHaveLength(TEXT_LINES);
|
|
53
|
+
expect(omittedOlderLines).toBe(5);
|
|
54
|
+
expect(lines[0].text).toBe("line 5");
|
|
55
|
+
});
|
|
56
|
+
});
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Container log lines read through Arcane's API, so a container on any agent
|
|
3
|
+
* (Mira's included) can be read like `host container-logs ... text` reads one
|
|
4
|
+
* on the manager's own host: the newest lines of a UTC window, credentials
|
|
5
|
+
* masked. The masking mirrors `redact_text` in the arcane repository's
|
|
6
|
+
* `host/spc-arcane-probes/incident_probe.py`; keep the two in step.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export const TEXT_LINES = 300;
|
|
10
|
+
export const TEXT_CHARS = 500;
|
|
11
|
+
const REDACTED = "[redacted]";
|
|
12
|
+
const SECRET_WORD = String.raw`(?:secret|token|passw(?:or)?d|pwd|pass|api[_-]?key|key|auth\w*|credential|cookie|session|signature|sig|salt|hash)`;
|
|
13
|
+
|
|
14
|
+
const TEXT_REDACTIONS: readonly [RegExp, string][] = [
|
|
15
|
+
[/-----BEGIN [A-Z ]*PRIVATE KEY-----.*/gi, REDACTED],
|
|
16
|
+
[/\b([a-z][a-z0-9+.-]*:\/\/)[^\s/@:]*:[^\s/@]*@/gi, `$1${REDACTED}@`],
|
|
17
|
+
[/\b(bearer|basic|digest|token)(\s+)[A-Za-z0-9._~+/=-]{8,}/gi, `$1$2${REDACTED}`],
|
|
18
|
+
[/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]*/g, REDACTED],
|
|
19
|
+
[new RegExp(String.raw`([A-Za-z0-9_.-]*${SECRET_WORD}[A-Za-z0-9_.-]*["']?\s*[:=]\s*["']?)[^\s"',;&)}\]]+`, "gi"), `$1${REDACTED}`],
|
|
20
|
+
[/(?<![A-Za-z0-9+/_-])(?=[A-Za-z0-9+/_-]*[0-9])(?=[A-Za-z0-9+/_-]*[A-Za-z])[A-Za-z0-9+/_-]{32,}={0,2}/g, REDACTED],
|
|
21
|
+
];
|
|
22
|
+
|
|
23
|
+
/** ANSI escape sequences, built from the escape character so the pattern holds no control character. */
|
|
24
|
+
const ANSI = new RegExp(`${String.fromCharCode(27)}\\[[0-?]*[ -/]*[@-~]`, "g");
|
|
25
|
+
|
|
26
|
+
/** Masks credentials in one log message; it over-masks rather than let a secret through. */
|
|
27
|
+
export function redactText(message: string): string {
|
|
28
|
+
const cut = message.length > 8 * TEXT_CHARS;
|
|
29
|
+
let text = message;
|
|
30
|
+
if (cut) {
|
|
31
|
+
// Drop the word split by the cut: a partial secret would be too short to match a pattern.
|
|
32
|
+
const head = text.slice(0, 8 * TEXT_CHARS);
|
|
33
|
+
const space = head.lastIndexOf(" ");
|
|
34
|
+
text = space >= 0 ? head.slice(0, space) : head;
|
|
35
|
+
}
|
|
36
|
+
text = text.replace(ANSI, "").replace(/[\p{C}\p{Z}]/gu, " ");
|
|
37
|
+
for (const [pattern, replacement] of TEXT_REDACTIONS) text = text.replace(pattern, replacement);
|
|
38
|
+
return cut || text.length > TEXT_CHARS ? `${text.slice(0, TEXT_CHARS)} [cut]` : text;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const STAMP = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d+))?Z$/;
|
|
42
|
+
|
|
43
|
+
/** Milliseconds of a Docker timestamp (nanosecond fraction allowed), or null. */
|
|
44
|
+
export function stampMs(stamp: string): number | null {
|
|
45
|
+
const m = STAMP.exec(stamp);
|
|
46
|
+
if (!m) return null;
|
|
47
|
+
const ms = Date.parse(`${m[1]}.${(m[2] ?? "").padEnd(3, "0").slice(0, 3)}Z`);
|
|
48
|
+
return Number.isNaN(ms) ? null : ms;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface LogRow {
|
|
52
|
+
timestamp: string;
|
|
53
|
+
text: string;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Collects the newest TEXT_LINES stamped lines inside [since, until) from a
|
|
58
|
+
* chronological stream. `push` returns false once a line is past `until`, so
|
|
59
|
+
* the caller can stop reading.
|
|
60
|
+
*/
|
|
61
|
+
export class LogWindow {
|
|
62
|
+
private readonly rows: [string, string][] = [];
|
|
63
|
+
private omitted = 0;
|
|
64
|
+
private readonly sinceMs: number;
|
|
65
|
+
private readonly untilMs: number;
|
|
66
|
+
|
|
67
|
+
constructor(sinceMs: number, untilMs: number) {
|
|
68
|
+
this.sinceMs = sinceMs;
|
|
69
|
+
this.untilMs = untilMs;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
push(line: string): boolean {
|
|
73
|
+
const space = line.indexOf(" ");
|
|
74
|
+
if (space <= 0) return true;
|
|
75
|
+
const stamp = line.slice(0, space);
|
|
76
|
+
const ms = stampMs(stamp);
|
|
77
|
+
if (ms === null || ms < this.sinceMs) return true;
|
|
78
|
+
if (ms >= this.untilMs) return false;
|
|
79
|
+
this.rows.push([stamp, line.slice(space + 1)]);
|
|
80
|
+
if (this.rows.length > TEXT_LINES) {
|
|
81
|
+
this.rows.shift();
|
|
82
|
+
this.omitted++;
|
|
83
|
+
}
|
|
84
|
+
return true;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
result(): { lines: LogRow[]; omittedOlderLines: number } {
|
|
88
|
+
return { lines: this.rows.map(([timestamp, message]) => ({ timestamp, text: redactText(message) })), omittedOlderLines: this.omitted };
|
|
89
|
+
}
|
|
90
|
+
}
|