@chroxy/server 0.10.0 → 0.11.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONFIG.md +602 -19
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +416 -11
- package/package.json +20 -23
- package/sidecar/Dockerfile +1 -1
- package/sidecar/PROTOCOL.md +9 -1
- package/sidecar/agent.js +102 -10
- package/sidecar/package-lock.json +3 -3
- package/src/acp-config.js +206 -0
- package/src/acp-session.js +954 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +293 -0
- package/src/agent-control/client.js +1616 -0
- package/src/agent-control/events.js +547 -0
- package/src/agent-control/local-connection.js +275 -0
- package/src/agent-control/mcp-server.js +545 -0
- package/src/anthropic-compatible-config.js +29 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-openai-shim.js +0 -1
- package/src/archive-continuation.js +164 -0
- package/src/assistant-response.js +24 -0
- package/src/auth-probes.js +120 -13
- package/src/background-shell-tracker.js +27 -0
- package/src/base-session.js +1353 -41
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +24 -1
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +101 -0
- package/src/bound-client-policy.js +279 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +74 -9
- package/src/built-in-tools/tool-transforms.js +1113 -13
- package/src/byok-compose-state.js +6 -9
- package/src/byok-credentials.js +2 -3
- package/src/byok-mcp-client.js +1153 -20
- package/src/byok-mcp-config.js +1712 -8
- package/src/byok-mcp-fleet.js +416 -29
- package/src/byok-mcp-oauth-store.js +329 -0
- package/src/byok-mcp-oauth.js +635 -0
- package/src/byok-mcp-trust.js +257 -40
- package/src/byok-session.js +1400 -149
- package/src/byok-tool-executor.js +2681 -38
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +96 -51
- package/src/chroxy-host-metadata.js +122 -0
- package/src/claude-channel-session.js +16 -10
- package/src/claude-model-catalog.js +131 -16
- package/src/claude-model-refresh.js +385 -0
- package/src/claude-model-request.js +103 -0
- package/src/claude-stream-parser.js +109 -3
- package/src/claude-tui/diagnostic-tail.js +83 -0
- package/src/claude-tui/form-driver.js +44 -7
- package/src/claude-tui/model-error.js +41 -0
- package/src/claude-tui/pty-driver.js +223 -60
- package/src/claude-tui/sanitize-question-payload.js +109 -0
- package/src/claude-tui/usage-limit.js +239 -0
- package/src/claude-tui-session.js +3611 -286
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +6 -6
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/deploy-cmd.js +46 -11
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/init-cmd.js +16 -17
- package/src/cli/providers-cmd.js +6 -6
- package/src/cli/schedule-cmd.js +804 -0
- package/src/cli/server-cmd.js +64 -2
- package/src/cli/service-cmd.js +70 -27
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +168 -14
- package/src/cli/tokens-cmd.js +212 -0
- package/src/cli/tunnel-cmd.js +256 -25
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1117 -116
- package/src/cli.js +8 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +2108 -101
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-model-catalog.js +548 -0
- package/src/codex-model-rejections.js +87 -0
- package/src/codex-native-resume.js +104 -0
- package/src/codex-protocol-capabilities.js +188 -0
- package/src/codex-session.js +571 -45
- package/src/config-dir-migration.js +444 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +738 -52
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +5 -9
- package/src/connection-locality.js +60 -0
- package/src/container-liveness-monitor.js +189 -0
- package/src/continuation-metadata-worker.js +17 -0
- package/src/continuations.js +114 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +23 -30
- package/src/control-room/skills-inventory.js +8 -3
- package/src/control-room/survey.js +32 -0
- package/src/conversation-scanner.js +40 -18
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +24 -22
- package/src/credential-store.js +279 -29
- package/src/daemon-commit.js +92 -0
- package/src/daemon-idle-state.js +171 -0
- package/src/daemon-update-status.js +314 -0
- package/src/dashboard-build.js +70 -0
- package/src/declared-status.js +90 -0
- package/src/deepseek-credentials.js +2 -3
- package/src/dev-preview.js +169 -182
- package/src/device-preferences.js +2 -2
- package/src/diagnostics.js +3 -0
- package/src/diff-parser.js +87 -0
- package/src/discord-credentials.js +2 -3
- package/src/docker-byok-pool.js +3 -1
- package/src/docker-byok-session.js +678 -78
- package/src/docker-image-allowlist.js +23 -1
- package/src/docker-sdk-session.js +188 -4
- package/src/docker-session.js +293 -10
- package/src/doctor.js +783 -66
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +95 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +39 -10
- package/src/environments/backends/k8s.js +58 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +137 -14
- package/src/event-normalizer.js +363 -110
- package/src/external-session-registry.js +0 -0
- package/src/gemini-session.js +100 -7
- package/src/github-webhook.js +188 -4
- package/src/handler-utils.js +563 -62
- package/src/handlers/checkpoint-handlers.js +162 -20
- package/src/handlers/control-room-handlers.js +99 -29
- package/src/handlers/conversation-handlers.js +563 -25
- package/src/handlers/credential-handlers.js +43 -2
- package/src/handlers/daemon-update-handlers.js +81 -0
- package/src/handlers/evaluator-handlers.js +14 -1
- package/src/handlers/feature-handlers.js +186 -69
- package/src/handlers/file-handlers.js +101 -13
- package/src/handlers/github-webhook-handlers.js +204 -0
- package/src/handlers/input-handlers.js +689 -48
- package/src/handlers/orchestration-handlers.js +238 -0
- package/src/handlers/scheduler-handlers.js +584 -0
- package/src/handlers/session-handlers.js +546 -16
- package/src/handlers/session-pr-status-handlers.js +283 -0
- package/src/handlers/session-pr-threads-handlers.js +247 -0
- package/src/handlers/settings-handlers.js +822 -35
- package/src/handlers/skills-handlers.js +13 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/handlers/token-handlers.js +11 -2
- package/src/health-proof.js +40 -0
- package/src/history-page.js +104 -0
- package/src/http-routes.js +286 -8
- package/src/ide/search.js +24 -6
- package/src/ide/symbols.js +20 -6
- package/src/input-context.js +117 -0
- package/src/instruction-policy-compiler.js +229 -0
- package/src/instruction-policy.js +250 -0
- package/src/jsonl-reader.js +309 -48
- package/src/jsonl-subprocess-session.js +122 -9
- package/src/keychain.js +160 -13
- package/src/logger.js +240 -31
- package/src/mailbox-route.js +11 -22
- package/src/message-wire.js +386 -0
- package/src/model-discovery.js +43 -3
- package/src/models.js +1276 -174
- package/src/notification-prefs.js +100 -10
- package/src/notifications/discord-billing-sink.js +22 -5
- package/src/notifications/discord-ci-sink.js +243 -0
- package/src/notifications/discord-webhook-client.js +71 -0
- package/src/notifications/discord-webhook-sink.js +82 -12
- package/src/notifications/expo-push-sink.js +85 -6
- package/src/notifications/ready-body.js +16 -5
- package/src/ollama-session.js +34 -2
- package/src/orchestration/build-manager.js +63 -0
- package/src/orchestration/decision-contract.js +245 -0
- package/src/orchestration/git-ops.js +381 -0
- package/src/orchestration/orchestration-manager.js +1342 -0
- package/src/orchestration/permission-gate.js +121 -0
- package/src/orchestration/role-prompts.js +136 -0
- package/src/orchestration/run-budget.js +81 -0
- package/src/orchestration/run-ledger.js +487 -0
- package/src/orchestration/run-model.js +206 -0
- package/src/orchestration/run-record.js +336 -0
- package/src/orchestration/run-report.js +194 -0
- package/src/orchestration/to-wire.js +201 -0
- package/src/orchestration/turn-driver.js +422 -0
- package/src/orphan-reaper.js +413 -0
- package/src/outgoing-policy.js +183 -0
- package/src/pairing.js +236 -12
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-audit.js +79 -3
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1770 -0
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +1175 -94
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolver.js +174 -12
- package/src/permission-rule-store.js +411 -0
- package/src/permission-scope.js +43 -0
- package/src/platform.js +483 -23
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +228 -6
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +360 -8
- package/src/roster-broadcast.js +186 -0
- package/src/schedule-parser.js +311 -0
- package/src/scheduled-task-store.js +945 -0
- package/src/scheduler.js +1099 -0
- package/src/sdk-session.js +2374 -168
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +11 -2
- package/src/server-cli/server-orchestrator.js +50 -4
- package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +760 -62
- package/src/server-identity.js +42 -14
- package/src/service.js +682 -53
- package/src/session-archive-limits.js +15 -0
- package/src/session-archive.js +1029 -0
- package/src/session-busy-state.js +72 -0
- package/src/session-ci-watcher.js +926 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +3879 -308
- package/src/session-message-history.js +749 -37
- package/src/session-pr-status.js +654 -0
- package/src/session-pr-threads.js +271 -0
- package/src/session-preset-trust.js +3 -3
- package/src/session-preset.js +10 -5
- package/src/session-state-persistence.js +94 -17
- package/src/session-timeout-manager.js +20 -0
- package/src/session-title.js +168 -0
- package/src/session-token-store.js +70 -36
- package/src/session-wake.js +240 -0
- package/src/shell-approval-info.js +2 -2
- package/src/shell-approval-store.js +3 -1
- package/src/skills-loader.js +7 -4
- package/src/skills-manager.js +2 -2
- package/src/skills-trust.js +95 -13
- package/src/skills-usage.js +22 -5
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +596 -0
- package/src/subagent-counter.js +9 -1
- package/src/summarize-session.js +51 -4
- package/src/supervisor.js +99 -38
- package/src/sweep-stale-provider-dirs.js +95 -0
- package/src/thinking-level-wire.js +39 -0
- package/src/thinking-stream.js +179 -0
- package/src/token-manager.js +39 -9
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +413 -31
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +145 -35
- package/src/tunnel/index.js +13 -1
- package/src/tunnel/preview.js +64 -0
- package/src/tunnel-check.js +1 -1
- package/src/turn-outcome.js +137 -0
- package/src/turn-tracker.js +0 -0
- package/src/usage-normalize.js +122 -0
- package/src/user-shell-session.js +157 -37
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +741 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +597 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +25 -0
- package/src/utils/bounded-regex.js +153 -0
- package/src/utils/claude-binary.js +43 -0
- package/src/utils/claude-config-dir.js +245 -0
- package/src/utils/claude-login-command.js +16 -0
- package/src/utils/claude-native-route.js +81 -0
- package/src/utils/componentwise-resolver.js +301 -0
- package/src/utils/composite-key.js +45 -0
- package/src/utils/deploy-control-files.js +87 -0
- package/src/utils/exec-failure-reason.js +21 -0
- package/src/utils/git-repo.js +42 -0
- package/src/utils/is-entry-point.js +137 -0
- package/src/utils/iso-datetime.js +51 -0
- package/src/utils/node-pty-probe.js +95 -0
- package/src/utils/node-pty-support.js +118 -0
- package/src/utils/opened-file-path.js +167 -0
- package/src/utils/path-containment.js +165 -0
- package/src/utils/permission-mode-sidecar.js +51 -0
- package/src/utils/preflight.js +485 -29
- package/src/utils/read-limiter.js +217 -0
- package/src/utils/regular-file.js +375 -0
- package/src/utils/safe-regex.js +113 -0
- package/src/utils/small-file.js +129 -0
- package/src/utils/spawn-env.js +196 -5
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-binary.js +276 -0
- package/src/utils/verify-provenance.js +634 -0
- package/src/utils/wire-counters.js +48 -0
- package/src/web-task-manager.js +256 -16
- package/src/worktree-gc.js +11 -3
- package/src/ws-auth.js +69 -21
- package/src/ws-broadcaster.js +14 -2
- package/src/ws-client-manager.js +16 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +370 -66
- package/src/ws-file-ops/common.js +384 -11
- package/src/ws-file-ops/git.js +615 -44
- package/src/ws-file-ops/index.js +7 -0
- package/src/ws-file-ops/memory.js +460 -0
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +676 -94
- package/src/ws-forwarding.js +373 -55
- package/src/ws-handler-context.js +89 -2
- package/src/ws-history.js +1018 -177
- package/src/ws-message-handlers.js +23 -1
- package/src/ws-outbound-schemas.js +207 -0
- package/src/ws-permissions.js +589 -38
- package/src/ws-schemas.js +6 -0
- package/src/ws-server.js +936 -105
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
- package/src/dashboard-next/dist/index.html +0 -13
|
@@ -0,0 +1,1029 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto'
|
|
2
|
+
import { chmodSync, closeSync, constants as fsConstants, existsSync, fstatSync, mkdirSync, openSync, readdirSync, readFileSync, unlinkSync } from 'node:fs'
|
|
3
|
+
import { open } from 'node:fs/promises'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
import { promisify } from 'node:util'
|
|
6
|
+
import { gunzip, gunzipSync, gzip, gzipSync } from 'node:zlib'
|
|
7
|
+
import { createLogger } from './logger.js'
|
|
8
|
+
import { isWindows, writeFileRestricted } from './platform.js'
|
|
9
|
+
import { pageHistory } from './history-page.js'
|
|
10
|
+
import { SessionMessageHistory } from './session-message-history.js'
|
|
11
|
+
import { SESSION_ARCHIVE_MAX_ENTRIES, savedHasHistory } from './session-archive-limits.js'
|
|
12
|
+
|
|
13
|
+
const log = createLogger('session-archive')
|
|
14
|
+
|
|
15
|
+
const gzipAsync = promisify(gzip)
|
|
16
|
+
const gunzipAsync = promisify(gunzip)
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Provider-neutral session archive.
|
|
20
|
+
*
|
|
21
|
+
* When a session leaves the live set, the history chroxy itself holds (the
|
|
22
|
+
* `history` array of its persisted entry) used to vanish with it. A Claude
|
|
23
|
+
* session can be resumed from the provider's own transcript, but a Codex /
|
|
24
|
+
* Gemini / BYOK session cannot, so for those the content was gone for good.
|
|
25
|
+
* The archive keeps one compressed record per ended session so it stays
|
|
26
|
+
* READABLE (paged, oldest first, through the same bounded reader the
|
|
27
|
+
* failed-restore view uses). It resumes nothing and creates nothing.
|
|
28
|
+
*
|
|
29
|
+
* Storage under `dir`:
|
|
30
|
+
* - `<archiveId>.json.gz` gzip(JSON { version: 1, archivedAt, reason, saved })
|
|
31
|
+
* - `index.json` { version: 1, entries: [meta...], tombstones: [...] }
|
|
32
|
+
* For the ROWS the index is a cache of the record files: a missing or corrupt
|
|
33
|
+
* index is rebuilt from the files, a row whose file is gone is dropped, and a
|
|
34
|
+
* file the index does not know (an index write lost to a crash) is adopted
|
|
35
|
+
* unless a tombstone covers it. The TOMBSTONES (what was deleted or aged out)
|
|
36
|
+
* exist only in the index, so a corrupt or lost index rebuilds with none; a
|
|
37
|
+
* deleted snapshot still present in an older session-state backup could then
|
|
38
|
+
* be archived again. That is a known limit.
|
|
39
|
+
*
|
|
40
|
+
* SECURITY: the archive directory holds transcript content, so files are 0600
|
|
41
|
+
* and the directory 0700. An `archiveId` is a random 128-bit token that this
|
|
42
|
+
* class generates; NO path is ever built from a session id or any other
|
|
43
|
+
* client-supplied string. A client-supplied id must match ARCHIVE_ID_RE AND be
|
|
44
|
+
* present in the index before any filesystem access happens.
|
|
45
|
+
*
|
|
46
|
+
* OUTCOMES. `archiveOutcome()` (synchronous) reports `archived | duplicate |
|
|
47
|
+
* skipped | failed`, so a caller that is about to DROP the only copy of a
|
|
48
|
+
* session (a TTL prune, a dismissed failed restore, a stale boot entry) can
|
|
49
|
+
* keep it when the write `failed`. `archive()` is the meta-or-null shorthand.
|
|
50
|
+
*
|
|
51
|
+
* RUNTIME PATH. A user closing a session must not stall the daemon, so
|
|
52
|
+
* `enqueue()` takes the snapshot's JSON synchronously (the same cost the state
|
|
53
|
+
* persist already pays), then compresses (gzip level 1) and writes on a serial
|
|
54
|
+
* queue off the event loop; `whenIdle()` awaits it and `drainSync()` finishes
|
|
55
|
+
* whatever is queued synchronously (called on shutdown). RESIDUAL WINDOW: a
|
|
56
|
+
* hard kill while a just-closed session is still compressing loses that one
|
|
57
|
+
* archive — the session was being closed anyway, and the clean-exit path
|
|
58
|
+
* drains the queue.
|
|
59
|
+
*
|
|
60
|
+
* DISPOSITIONS. The index also keeps bounded tombstones (sessionId +
|
|
61
|
+
* lastActivityAt + historyLength) of every record removed by delete, delete-all
|
|
62
|
+
* or retention, so a state backup that still carries the source entry cannot
|
|
63
|
+
* resurrect a record the operator deleted or that aged out.
|
|
64
|
+
*
|
|
65
|
+
* SIZE. A record's JSON is bounded by MAX_RECORD_BYTES on write AND read (one
|
|
66
|
+
* constant): when a history would not fit, the OLDEST entries are omitted and
|
|
67
|
+
* counted in `omittedOldest`, rather than writing a record the reader refuses.
|
|
68
|
+
*
|
|
69
|
+
* DURABILITY. A removal (delete, delete-all, retention) writes the index WITH
|
|
70
|
+
* the tombstone first and unlinks the record only after that write succeeded;
|
|
71
|
+
* the synchronous boot-path writes are fsync'd (`durable`) so a record is on
|
|
72
|
+
* disk before the state flush that drops its source.
|
|
73
|
+
*
|
|
74
|
+
* DOCUMENTED LIMITS. The boot paths (stale entries, the failed-restore TTL
|
|
75
|
+
* prune) and `clearFailedRestore` archive SYNCHRONOUSLY, because they need the
|
|
76
|
+
* outcome before they may drop the source, so a very large history stalls the
|
|
77
|
+
* event loop once there. A read still `JSON.parse`s a whole record
|
|
78
|
+
* synchronously after the (asynchronous) read and inflate.
|
|
79
|
+
*/
|
|
80
|
+
|
|
81
|
+
const ARCHIVE_ID_RE = /^[0-9a-f]{32}$/
|
|
82
|
+
const RECORD_SUFFIX = '.json.gz'
|
|
83
|
+
const RECORD_FILE_RE = /^([0-9a-f]{32})\.json\.gz$/
|
|
84
|
+
const INDEX_FILE = 'index.json'
|
|
85
|
+
const FORMAT_VERSION = 1
|
|
86
|
+
const DAY_MS = 24 * 60 * 60 * 1000
|
|
87
|
+
const MIB = 1024 * 1024
|
|
88
|
+
// ONE bound on a record's uncompressed JSON, applied by the writer (which omits
|
|
89
|
+
// the oldest entries to fit) and by the reader (gunzip maxOutputLength), so a
|
|
90
|
+
// record that was written can always be read.
|
|
91
|
+
const MAX_RECORD_BYTES = 128 * MIB
|
|
92
|
+
const MAX_TOMBSTONES = 1000
|
|
93
|
+
// Level 1: the archive is about not losing text, not about density, and the
|
|
94
|
+
// default level costs several times the CPU.
|
|
95
|
+
const GZIP_OPTS = Object.freeze({ level: 1 })
|
|
96
|
+
|
|
97
|
+
export { SESSION_ARCHIVE_MAX_ENTRIES }
|
|
98
|
+
|
|
99
|
+
// Opening with O_NOFOLLOW means a symlink planted where the index or a record
|
|
100
|
+
// should be is refused (ELOOP) rather than followed. Absent on win32. O_NONBLOCK
|
|
101
|
+
// keeps a FIFO planted at the path from blocking the open forever (a synchronous
|
|
102
|
+
// open blocks the whole event loop); a regular file is unaffected, and the
|
|
103
|
+
// opened handle is checked to BE a regular file before anything is read.
|
|
104
|
+
const O_NOFOLLOW = typeof fsConstants.O_NOFOLLOW === 'number' ? fsConstants.O_NOFOLLOW : 0
|
|
105
|
+
const O_NONBLOCK = typeof fsConstants.O_NONBLOCK === 'number' ? fsConstants.O_NONBLOCK : 0
|
|
106
|
+
const OPEN_FLAGS = fsConstants.O_RDONLY | O_NOFOLLOW | O_NONBLOCK
|
|
107
|
+
const TMP_FILE_RE = /^(?:[0-9a-f]{32}\.json\.gz|index\.json)\.tmp-.+$/
|
|
108
|
+
|
|
109
|
+
const notRegular = (path) => Object.assign(new Error(`not a regular file: ${path}`), { code: 'ENOTREG' })
|
|
110
|
+
|
|
111
|
+
function readFileNoFollowSync(path) {
|
|
112
|
+
const fd = openSync(path, OPEN_FLAGS)
|
|
113
|
+
try {
|
|
114
|
+
if (!fstatSync(fd).isFile()) throw notRegular(path)
|
|
115
|
+
return readFileSync(fd)
|
|
116
|
+
} finally {
|
|
117
|
+
closeSync(fd)
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async function readFileNoFollow(path) {
|
|
122
|
+
const handle = await open(path, OPEN_FLAGS)
|
|
123
|
+
try {
|
|
124
|
+
if (!(await handle.stat()).isFile()) throw notRegular(path)
|
|
125
|
+
return await handle.readFile()
|
|
126
|
+
} finally {
|
|
127
|
+
await handle.close()
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** A log-safe tag for a read/parse error: never its message, which can quote file content. */
|
|
132
|
+
function errTag(err) {
|
|
133
|
+
return err?.code || err?.name || 'error'
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export const SESSION_ARCHIVE_DEFAULTS = Object.freeze({
|
|
137
|
+
enabled: true,
|
|
138
|
+
maxEntries: 100,
|
|
139
|
+
maxAgeDays: 30,
|
|
140
|
+
maxMegabytes: 256,
|
|
141
|
+
})
|
|
142
|
+
|
|
143
|
+
export const ARCHIVE_NOT_FOUND_CODE = 'ARCHIVED_SESSION_NOT_FOUND'
|
|
144
|
+
export const ARCHIVE_MAX_RECORD_BYTES = MAX_RECORD_BYTES
|
|
145
|
+
|
|
146
|
+
// Bounds on the strings copied into an index row, so a hand-edited or
|
|
147
|
+
// abnormal saved entry cannot make the roster (sent in one frame) large.
|
|
148
|
+
const MAX_ID_CHARS = 256
|
|
149
|
+
const MAX_NAME_CHARS = 256
|
|
150
|
+
const MAX_PROVIDER_CHARS = 64
|
|
151
|
+
const MAX_CWD_CHARS = 4096
|
|
152
|
+
const MAX_MODEL_CHARS = 256
|
|
153
|
+
const MAX_REASON_CHARS = 64
|
|
154
|
+
|
|
155
|
+
function boundedString(value, max) {
|
|
156
|
+
return typeof value === 'string' ? value.slice(0, max) : null
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function finiteOrNull(value) {
|
|
160
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : null
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Does the saved entry still name a provider-side conversation it could resume
|
|
165
|
+
* from (#8866)? A Claude-family entry carries `sdkSessionId` (a claude-tui id
|
|
166
|
+
* that was minted but never written to disk is `conversationPersisted: false`);
|
|
167
|
+
* a Codex app-server entry carries `nativeResume`. This only says a locator was
|
|
168
|
+
* RECORDED: whether the transcript / thread still exists is checked when a
|
|
169
|
+
* restore is attempted.
|
|
170
|
+
*/
|
|
171
|
+
function savedHasLocator(saved) {
|
|
172
|
+
if (saved?.nativeResume && typeof saved.nativeResume === 'object') return true
|
|
173
|
+
return typeof saved?.sdkSessionId === 'string' && saved.sdkSessionId.length > 0 && saved.conversationPersisted !== false
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function positiveNumber(value, fallback, name, { integer = false, max = Infinity } = {}) {
|
|
177
|
+
if (value === undefined) return fallback
|
|
178
|
+
const ok = typeof value === 'number' && Number.isFinite(value) && value > 0 && (!integer || Number.isInteger(value))
|
|
179
|
+
if (ok && value > max) {
|
|
180
|
+
log.warn(`sessionArchive.${name}: ${value} is above the maximum — clamped to ${max}`)
|
|
181
|
+
return max
|
|
182
|
+
}
|
|
183
|
+
if (ok) return value
|
|
184
|
+
log.warn(`sessionArchive.${name}: expected a positive ${integer ? 'integer' : 'number'}, got ${JSON.stringify(value)} — using the default (${fallback})`)
|
|
185
|
+
return fallback
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Copy ONLY the typed fields of a roster row from a saved session entry.
|
|
190
|
+
* @returns {object|null} null when the entry has no usable session id
|
|
191
|
+
*/
|
|
192
|
+
function metaFrom(saved, { archiveId, reason, archivedAt, bytes, omittedOldest = 0 }) {
|
|
193
|
+
const sessionId = boundedString(saved?.id ?? saved?.sessionId, MAX_ID_CHARS)
|
|
194
|
+
if (!sessionId) return null
|
|
195
|
+
return {
|
|
196
|
+
archiveId,
|
|
197
|
+
sessionId,
|
|
198
|
+
name: boundedString(saved.name, MAX_NAME_CHARS),
|
|
199
|
+
provider: boundedString(saved.provider, MAX_PROVIDER_CHARS),
|
|
200
|
+
cwd: boundedString(saved.cwd, MAX_CWD_CHARS),
|
|
201
|
+
model: boundedString(saved.model, MAX_MODEL_CHARS),
|
|
202
|
+
reason: boundedString(reason, MAX_REASON_CHARS) || 'closed',
|
|
203
|
+
archivedAt: finiteOrNull(archivedAt),
|
|
204
|
+
lastActivityAt: finiteOrNull(saved.lastActivityAt),
|
|
205
|
+
createdAt: finiteOrNull(saved.createdAt),
|
|
206
|
+
historyLength: Array.isArray(saved.history) ? saved.history.length : 0,
|
|
207
|
+
omittedOldest: Number.isInteger(omittedOldest) && omittedOldest > 0 ? omittedOldest : 0,
|
|
208
|
+
bytes: finiteOrNull(bytes) ?? 0,
|
|
209
|
+
// Internal restore hints (#8866); SessionManager folds them into the wire
|
|
210
|
+
// `restore` field and strips them, so the roster never carries these keys.
|
|
211
|
+
locator: savedHasLocator(saved),
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** Re-validate an index row read back from disk (it is not trusted either). */
|
|
216
|
+
function metaFromIndexRow(row) {
|
|
217
|
+
if (!row || typeof row !== 'object' || typeof row.archiveId !== 'string' || !ARCHIVE_ID_RE.test(row.archiveId)) return null
|
|
218
|
+
const historyLength = Number.isInteger(row.historyLength) && row.historyLength >= 0 ? row.historyLength : 0
|
|
219
|
+
const meta = metaFrom(
|
|
220
|
+
{
|
|
221
|
+
id: row.sessionId,
|
|
222
|
+
name: row.name,
|
|
223
|
+
provider: row.provider,
|
|
224
|
+
cwd: row.cwd,
|
|
225
|
+
model: row.model,
|
|
226
|
+
lastActivityAt: row.lastActivityAt,
|
|
227
|
+
createdAt: row.createdAt,
|
|
228
|
+
history: [],
|
|
229
|
+
},
|
|
230
|
+
{ archiveId: row.archiveId, reason: row.reason, archivedAt: row.archivedAt, bytes: row.bytes, omittedOldest: row.omittedOldest },
|
|
231
|
+
)
|
|
232
|
+
if (!meta) return null
|
|
233
|
+
meta.historyLength = historyLength
|
|
234
|
+
// A row written before #8866 has no hints: `null` = unknown, decided when a
|
|
235
|
+
// restore is attempted, rather than a false "no locator".
|
|
236
|
+
meta.locator = typeof row.locator === 'boolean' ? row.locator : null
|
|
237
|
+
return meta
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** Re-validate a tombstone read back from disk. */
|
|
241
|
+
function tombstoneFromIndexRow(row) {
|
|
242
|
+
if (!row || typeof row !== 'object') return null
|
|
243
|
+
const sessionId = boundedString(row.sessionId, MAX_ID_CHARS)
|
|
244
|
+
if (!sessionId) return null
|
|
245
|
+
if (!Number.isInteger(row.historyLength) || row.historyLength < 0) return null
|
|
246
|
+
return {
|
|
247
|
+
sessionId,
|
|
248
|
+
lastActivityAt: finiteOrNull(row.lastActivityAt),
|
|
249
|
+
historyLength: row.historyLength,
|
|
250
|
+
at: finiteOrNull(row.at) ?? 0,
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** Source history length of an indexed row (kept entries plus omitted-for-size ones). */
|
|
255
|
+
function rowSourceLength(row) {
|
|
256
|
+
return row.historyLength + (row.omittedOldest || 0)
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Does `existing` already account for the candidate snapshot? Same session and
|
|
261
|
+
* an equal-or-NEWER state: a later `lastActivityAt`, or the same one with at
|
|
262
|
+
* least as much history. That covers a source that outlives its (deleted or
|
|
263
|
+
* evicted) record in a state backup at an OLDER point of the same session —
|
|
264
|
+
* the backup is superseded, not new. When either timestamp is unknown only an
|
|
265
|
+
* exact (timestamp, length) match counts.
|
|
266
|
+
* @param {{sessionId: string, lastActivityAt: number|null, length: number}} existing
|
|
267
|
+
* @param {{sessionId: string, lastActivityAt: number|null, length: number}} candidate
|
|
268
|
+
*/
|
|
269
|
+
function snapshotCovers(existing, candidate) {
|
|
270
|
+
if (existing.sessionId !== candidate.sessionId) return false
|
|
271
|
+
const a = existing.lastActivityAt
|
|
272
|
+
const b = candidate.lastActivityAt
|
|
273
|
+
if (typeof a === 'number' && typeof b === 'number') {
|
|
274
|
+
if (a !== b) return a > b
|
|
275
|
+
return existing.length >= candidate.length
|
|
276
|
+
}
|
|
277
|
+
return a === b && existing.length === candidate.length
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
const tombstoneAsSnapshot = (t) => ({ sessionId: t.sessionId, lastActivityAt: t.lastActivityAt, length: t.historyLength })
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Serialise one record's JSON, omitting the OLDEST history entries until it
|
|
284
|
+
* fits `maxBytes`. Each entry is stringified once; the record is assembled from
|
|
285
|
+
* those pieces rather than stringified a second time.
|
|
286
|
+
* @returns {{ json: string, omittedOldest: number, kept: number } | null} null
|
|
287
|
+
* when not even the newest entry fits
|
|
288
|
+
*/
|
|
289
|
+
function buildRecordJson(saved, { archivedAt, reason }, maxBytes) {
|
|
290
|
+
const { history, ...rest } = saved
|
|
291
|
+
const parts = history.map((entry) => JSON.stringify(entry) ?? 'null')
|
|
292
|
+
const sizes = parts.map((part) => Buffer.byteLength(part))
|
|
293
|
+
const restJson = JSON.stringify(rest)
|
|
294
|
+
const sep = restJson === '{}' ? '' : ','
|
|
295
|
+
const historyOpen = `${sep}"history":[`
|
|
296
|
+
const prefix = (omitted) => `{"version":${FORMAT_VERSION},"archivedAt":${JSON.stringify(archivedAt)},"reason":${JSON.stringify(reason)},"omittedOldest":${omitted},"saved":`
|
|
297
|
+
const fixed = Buffer.byteLength(restJson) - 1 + Buffer.byteLength(historyOpen) + 3
|
|
298
|
+
let keptBytes = sizes.reduce((sum, n) => sum + n, 0)
|
|
299
|
+
// The EXACT size for each candidate start (the digit width of `omittedOldest`
|
|
300
|
+
// included), so an entry is never discarded on an over-estimate.
|
|
301
|
+
const totalFor = (from) => Buffer.byteLength(prefix(from)) + fixed + keptBytes + Math.max(0, parts.length - from - 1)
|
|
302
|
+
let start = 0
|
|
303
|
+
while (start < parts.length && totalFor(start) > maxBytes) {
|
|
304
|
+
keptBytes -= sizes[start]
|
|
305
|
+
start++
|
|
306
|
+
}
|
|
307
|
+
if (start >= parts.length) return null
|
|
308
|
+
const kept = parts.slice(start)
|
|
309
|
+
const savedJson = `${restJson.slice(0, -1)}${historyOpen}${kept.join(',')}]}`
|
|
310
|
+
return { json: `${prefix(start)}${savedJson}}`, omittedOldest: start, kept: kept.length }
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
export class SessionArchive {
|
|
314
|
+
/**
|
|
315
|
+
* @param {object} options
|
|
316
|
+
* @param {string} options.dir - archive directory (created lazily on first write)
|
|
317
|
+
* @param {boolean} [options.enabled=true] - off switch: stops NEW writes only;
|
|
318
|
+
* retention still runs so old data keeps ageing out
|
|
319
|
+
* @param {number} [options.maxEntries=100] - clamped to SESSION_ARCHIVE_MAX_ENTRIES
|
|
320
|
+
* @param {number} [options.maxAgeDays=30]
|
|
321
|
+
* @param {number} [options.maxMegabytes=256]
|
|
322
|
+
* @param {() => number} [options.now] - clock seam for tests
|
|
323
|
+
* @param {{ truncateEntry: (entry: object) => object }} [options.historyHelper] -
|
|
324
|
+
* the history truncator the pager uses; defaults to a private one
|
|
325
|
+
* @param {number} [options.maxRecordBytes] - test seam for MAX_RECORD_BYTES
|
|
326
|
+
* (NOT a config key)
|
|
327
|
+
* @param {typeof writeFileRestricted} [options.writeFile] - test seam for the
|
|
328
|
+
* atomic file write (NOT a config key)
|
|
329
|
+
*/
|
|
330
|
+
constructor({ dir, enabled, maxEntries, maxAgeDays, maxMegabytes, now = () => Date.now(), historyHelper, maxRecordBytes, writeFile = writeFileRestricted } = {}) {
|
|
331
|
+
this._dirValid = typeof dir === 'string' && dir.length > 0
|
|
332
|
+
if (!this._dirValid) log.warn('SessionArchive: no archive directory given — archiving is disabled')
|
|
333
|
+
this._dir = this._dirValid ? dir : null
|
|
334
|
+
if (enabled !== undefined && typeof enabled !== 'boolean') {
|
|
335
|
+
log.warn(`sessionArchive.enabled: expected a boolean, got ${JSON.stringify(enabled)} — using the default (${SESSION_ARCHIVE_DEFAULTS.enabled})`)
|
|
336
|
+
}
|
|
337
|
+
this._enabled = this._dirValid && (typeof enabled === 'boolean' ? enabled : SESSION_ARCHIVE_DEFAULTS.enabled)
|
|
338
|
+
this._maxEntries = positiveNumber(maxEntries, SESSION_ARCHIVE_DEFAULTS.maxEntries, 'maxEntries', { integer: true, max: SESSION_ARCHIVE_MAX_ENTRIES })
|
|
339
|
+
this._maxAgeDays = positiveNumber(maxAgeDays, SESSION_ARCHIVE_DEFAULTS.maxAgeDays, 'maxAgeDays')
|
|
340
|
+
this._maxMegabytes = positiveNumber(maxMegabytes, SESSION_ARCHIVE_DEFAULTS.maxMegabytes, 'maxMegabytes')
|
|
341
|
+
this._maxRecordBytes = typeof maxRecordBytes === 'number' && Number.isFinite(maxRecordBytes) && maxRecordBytes > 0 ? maxRecordBytes : MAX_RECORD_BYTES
|
|
342
|
+
this._now = typeof now === 'function' ? now : () => Date.now()
|
|
343
|
+
this._historyHelper = historyHelper || new SessionMessageHistory({})
|
|
344
|
+
this._writeFile = typeof writeFile === 'function' ? writeFile : writeFileRestricted
|
|
345
|
+
this._tmpSuffix = `.tmp-${process.pid}`
|
|
346
|
+
/** @type {object[]|null} null until a load SUCCEEDS (a failed load is retried) */
|
|
347
|
+
this._index = null
|
|
348
|
+
/** @type {object[]} bounded FIFO of removed records' fingerprints */
|
|
349
|
+
this._tombstones = []
|
|
350
|
+
/** one decoded record, so paging does not gunzip on every page */
|
|
351
|
+
this._cache = null
|
|
352
|
+
/** snapshots taken by enqueue() that are not in the index yet */
|
|
353
|
+
this._pending = []
|
|
354
|
+
this._pumping = null
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** @returns {{ enabled: boolean, maxEntries: number, maxAgeDays: number, maxMegabytes: number }} */
|
|
358
|
+
retentionPolicy() {
|
|
359
|
+
return {
|
|
360
|
+
enabled: this._enabled,
|
|
361
|
+
maxEntries: this._maxEntries,
|
|
362
|
+
maxAgeDays: this._maxAgeDays,
|
|
363
|
+
maxMegabytes: this._maxMegabytes,
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* Replace the retention policy at runtime and re-run retention so lowered
|
|
369
|
+
* limits take effect now. The caller validates (config.js
|
|
370
|
+
* validateSessionArchivePolicy); `enabled` is still ANDed with the directory.
|
|
371
|
+
* @param {{ enabled: boolean, maxEntries: number, maxAgeDays: number, maxMegabytes: number }} policy
|
|
372
|
+
* @returns {ReturnType<SessionArchive['retentionPolicy']>} the applied policy
|
|
373
|
+
*/
|
|
374
|
+
setRetentionPolicy({ enabled, maxEntries, maxAgeDays, maxMegabytes }) {
|
|
375
|
+
this._enabled = this._dirValid && enabled === true
|
|
376
|
+
this._maxEntries = maxEntries
|
|
377
|
+
this._maxAgeDays = maxAgeDays
|
|
378
|
+
this._maxMegabytes = maxMegabytes
|
|
379
|
+
this.prune()
|
|
380
|
+
return this.retentionPolicy()
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* Archive one ended session SYNCHRONOUSLY and say what happened. NEVER
|
|
385
|
+
* throws: archiving must not be able to break a teardown.
|
|
386
|
+
*
|
|
387
|
+
* archived a record was written (`meta` is its roster row)
|
|
388
|
+
* duplicate this snapshot (or a newer one of the same session) is already
|
|
389
|
+
* archived, was archived and since removed (tombstone), or is
|
|
390
|
+
* queued — nothing to do
|
|
391
|
+
* skipped nothing to keep: archiving is off, the history is empty, or
|
|
392
|
+
* the record alone is larger than the user's own byte cap (it is
|
|
393
|
+
* not written and NOTHING is evicted to make room)
|
|
394
|
+
* failed the write (or the serialisation, or loading the archive)
|
|
395
|
+
* threw — the caller must NOT drop the only copy of the session
|
|
396
|
+
* if it has a choice
|
|
397
|
+
*
|
|
398
|
+
* The write is fsync'd: this is the path the boot-time callers use, and they
|
|
399
|
+
* drop the source right after.
|
|
400
|
+
*
|
|
401
|
+
* @param {object} saved - a serialized session entry (SessionManager._serializeSessionEntry)
|
|
402
|
+
* @param {string} [reason='closed']
|
|
403
|
+
* @returns {{ status: 'archived'|'duplicate'|'skipped'|'failed', meta?: object }}
|
|
404
|
+
*/
|
|
405
|
+
archiveOutcome(saved, reason = 'closed') {
|
|
406
|
+
try {
|
|
407
|
+
const prepared = this._prepare(saved, reason)
|
|
408
|
+
if (!prepared.job) return prepared
|
|
409
|
+
const job = prepared.job
|
|
410
|
+
const gz = gzipSync(job.json, GZIP_OPTS)
|
|
411
|
+
job.done = true
|
|
412
|
+
const meta = this._commit(job, gz, { durable: true })
|
|
413
|
+
return meta ? { status: 'archived', meta } : { status: 'skipped' }
|
|
414
|
+
} catch (err) {
|
|
415
|
+
log.warn(`Failed to archive session: ${err?.message || err}`)
|
|
416
|
+
return { status: 'failed' }
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* Archive one ended session (synchronous).
|
|
422
|
+
* @param {object} saved
|
|
423
|
+
* @param {string} [reason='closed']
|
|
424
|
+
* @returns {object|null} the roster row, or null when nothing was archived
|
|
425
|
+
*/
|
|
426
|
+
archive(saved, reason = 'closed') {
|
|
427
|
+
const outcome = this.archiveOutcome(saved, reason)
|
|
428
|
+
return outcome.status === 'archived' ? outcome.meta : null
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* Queue one ended session for archiving off the event loop. The snapshot's
|
|
433
|
+
* JSON is taken NOW (so the live session can be torn down immediately); the
|
|
434
|
+
* compression and the write happen on a serial queue. NEVER throws.
|
|
435
|
+
* @returns {{ status: 'queued'|'duplicate'|'skipped'|'failed' }}
|
|
436
|
+
*/
|
|
437
|
+
enqueue(saved, reason = 'closed') {
|
|
438
|
+
try {
|
|
439
|
+
const prepared = this._prepare(saved, reason)
|
|
440
|
+
if (!prepared.job) return prepared
|
|
441
|
+
this._pending.push(prepared.job)
|
|
442
|
+
this._schedule()
|
|
443
|
+
return { status: 'queued' }
|
|
444
|
+
} catch (err) {
|
|
445
|
+
log.warn(`Failed to queue session for the archive: ${err?.message || err}`)
|
|
446
|
+
return { status: 'failed' }
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** Resolves when every queued snapshot has been written (or has failed). */
|
|
451
|
+
async whenIdle() {
|
|
452
|
+
while (this._pumping) await this._pumping
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* Finish every queued snapshot synchronously. Called on shutdown so a clean
|
|
457
|
+
* exit does not lose a session that was closed moments ago. NEVER throws.
|
|
458
|
+
*/
|
|
459
|
+
drainSync() {
|
|
460
|
+
for (const job of [...this._pending]) {
|
|
461
|
+
if (job.done) continue
|
|
462
|
+
try {
|
|
463
|
+
const gz = gzipSync(job.json, GZIP_OPTS)
|
|
464
|
+
job.done = true
|
|
465
|
+
this._commit(job, gz, { durable: true })
|
|
466
|
+
} catch (err) {
|
|
467
|
+
job.done = true
|
|
468
|
+
log.warn(`Failed to archive a queued session at shutdown: ${err?.message || err}`)
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
this._pending = this._pending.filter((job) => !job.done)
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/**
|
|
475
|
+
* Load the archive and apply retention now, even with archiving turned off.
|
|
476
|
+
* Called at daemon boot and on a timer so records age out without waiting
|
|
477
|
+
* for a new session to end. NEVER throws.
|
|
478
|
+
*/
|
|
479
|
+
prune() {
|
|
480
|
+
try {
|
|
481
|
+
this._ensureLoaded()
|
|
482
|
+
this._sweep()
|
|
483
|
+
} catch (err) {
|
|
484
|
+
log.warn(`Failed to prune the session archive: ${err?.message || err}`)
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/** @returns {object[]} roster rows, newest first */
|
|
489
|
+
list() {
|
|
490
|
+
try {
|
|
491
|
+
this._ensureLoaded()
|
|
492
|
+
this._sweep()
|
|
493
|
+
} catch (err) {
|
|
494
|
+
log.warn(`Failed to load session archive: ${err?.message || err}`)
|
|
495
|
+
return []
|
|
496
|
+
}
|
|
497
|
+
return [...this._index]
|
|
498
|
+
.sort((a, b) => (b.archivedAt ?? 0) - (a.archivedAt ?? 0) || (a.archiveId < b.archiveId ? -1 : 1))
|
|
499
|
+
.map((row) => ({ ...row }))
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/**
|
|
503
|
+
* One bounded page of an archived session's history, oldest first. The
|
|
504
|
+
* record is read and inflated off the event loop.
|
|
505
|
+
* @param {string} archiveId
|
|
506
|
+
* @param {{ offset?: number, limit?: number }} [opts]
|
|
507
|
+
* @returns {Promise<{ok: true, total: number, offset: number, entries: object[]} | {ok: false, code: string, message: string}>}
|
|
508
|
+
*/
|
|
509
|
+
async getHistoryPage(archiveId, { offset, limit } = {}) {
|
|
510
|
+
const notFound = {
|
|
511
|
+
ok: false,
|
|
512
|
+
code: ARCHIVE_NOT_FOUND_CODE,
|
|
513
|
+
message: 'No archived session with that id',
|
|
514
|
+
}
|
|
515
|
+
try {
|
|
516
|
+
this._ensureLoaded()
|
|
517
|
+
this._sweep() // an expired record is never served
|
|
518
|
+
if (!this._knows(archiveId)) return notFound
|
|
519
|
+
const record = await this._readRecord(archiveId)
|
|
520
|
+
// Re-checked AFTER the await on every path, a cache hit included: the
|
|
521
|
+
// record may have been deleted or aged out while this read was in flight.
|
|
522
|
+
if (!record || !this._knows(archiveId)) return notFound
|
|
523
|
+
return { ok: true, ...pageHistory(record.saved?.history, { offset, limit }, this._historyHelper) }
|
|
524
|
+
} catch (err) {
|
|
525
|
+
log.warn(`Failed to read archived session: ${err?.message || err}`)
|
|
526
|
+
return notFound
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/**
|
|
531
|
+
* The saved session entry of one record, for a restore (#8866). The returned
|
|
532
|
+
* object belongs to the caller (the one-record cache is dropped), because a
|
|
533
|
+
* restore seeds history onto it and must not leave the cached copy mutated.
|
|
534
|
+
* @param {string} archiveId
|
|
535
|
+
* @returns {Promise<{ok: true, saved: object, meta: object} | {ok: false, code: string, message: string}>}
|
|
536
|
+
*/
|
|
537
|
+
async getSaved(archiveId) {
|
|
538
|
+
const notFound = { ok: false, code: ARCHIVE_NOT_FOUND_CODE, message: 'No archived session with that id' }
|
|
539
|
+
try {
|
|
540
|
+
this._ensureLoaded()
|
|
541
|
+
this._sweep()
|
|
542
|
+
if (!this._knows(archiveId)) return notFound
|
|
543
|
+
const record = await this._readRecord(archiveId)
|
|
544
|
+
if (!record || !this._knows(archiveId) || !record.saved || typeof record.saved !== 'object') return notFound
|
|
545
|
+
this._invalidate(archiveId)
|
|
546
|
+
const row = this._index.find((r) => r.archiveId === archiveId)
|
|
547
|
+
return { ok: true, saved: record.saved, meta: { ...row } }
|
|
548
|
+
} catch (err) {
|
|
549
|
+
log.warn(`Failed to read archived session for restore: ${err?.message || err}`)
|
|
550
|
+
return notFound
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/**
|
|
555
|
+
* Remove a record WITHOUT a tombstone: the session it held is live again
|
|
556
|
+
* (#8866), so a later close must be free to archive it afresh. A tombstone
|
|
557
|
+
* would make that archive (and a dismissed failed restore of the same
|
|
558
|
+
* snapshot) dedupe to `duplicate` and drop the only copy.
|
|
559
|
+
*
|
|
560
|
+
* The file goes first: if the index write then fails the row is orphaned and
|
|
561
|
+
* dropped at the next load (its file is gone); the other order would leave a
|
|
562
|
+
* file the next load re-adopts.
|
|
563
|
+
* @param {string} archiveId
|
|
564
|
+
* @returns {'released'|'not_found'|'failed'}
|
|
565
|
+
*/
|
|
566
|
+
release(archiveId) {
|
|
567
|
+
try {
|
|
568
|
+
this._ensureLoaded()
|
|
569
|
+
this._sweep()
|
|
570
|
+
if (!this._knows(archiveId)) return 'not_found'
|
|
571
|
+
if (!this._unlinkRecord(archiveId)) return 'failed'
|
|
572
|
+
this._invalidate(archiveId)
|
|
573
|
+
this._index = this._index.filter((row) => row.archiveId !== archiveId)
|
|
574
|
+
this._writeIndex({ durable: true })
|
|
575
|
+
return 'released'
|
|
576
|
+
} catch (err) {
|
|
577
|
+
log.warn(`Failed to release archived session: ${err?.message || err}`)
|
|
578
|
+
return 'failed'
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/**
|
|
583
|
+
* @param {string} archiveId
|
|
584
|
+
* @returns {'deleted'|'not_found'|'failed'} `failed` means the record could
|
|
585
|
+
* not be removed durably (its tombstone could not be written, or its file
|
|
586
|
+
* could not be unlinked): it is still listed
|
|
587
|
+
*/
|
|
588
|
+
delete(archiveId) {
|
|
589
|
+
try {
|
|
590
|
+
this._ensureLoaded()
|
|
591
|
+
this._sweep()
|
|
592
|
+
if (!this._knows(archiveId)) return 'not_found'
|
|
593
|
+
const row = this._index.find((r) => r.archiveId === archiveId)
|
|
594
|
+
const { removed } = this._removeRows([row])
|
|
595
|
+
return removed.length > 0 ? 'deleted' : 'failed'
|
|
596
|
+
} catch (err) {
|
|
597
|
+
log.warn(`Failed to delete archived session: ${err?.message || err}`)
|
|
598
|
+
return 'failed'
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/**
|
|
603
|
+
* Delete every record, AND cancel every snapshot still queued (a session
|
|
604
|
+
* closed just before the request must not reappear after it).
|
|
605
|
+
* @returns {{ deleted: number, failed: number }} `failed` counts records that
|
|
606
|
+
* are still on disk
|
|
607
|
+
*/
|
|
608
|
+
deleteAll() {
|
|
609
|
+
let deleted = 0
|
|
610
|
+
let failed = 0
|
|
611
|
+
try {
|
|
612
|
+
this._ensureLoaded()
|
|
613
|
+
this._sweep()
|
|
614
|
+
const cancelled = this._cancelPending()
|
|
615
|
+
const rows = [...this._index]
|
|
616
|
+
const { removed, failed: stuck } = this._removeRows(rows)
|
|
617
|
+
// Rows were written with the cancelled snapshots' tombstones; with no rows
|
|
618
|
+
// the tombstones still need to reach disk.
|
|
619
|
+
if (cancelled > 0 && rows.length === 0) this._writeIndex({ durable: true, create: true })
|
|
620
|
+
deleted = cancelled + removed.length
|
|
621
|
+
failed = stuck.length
|
|
622
|
+
} catch (err) {
|
|
623
|
+
log.warn(`Failed to delete archived sessions: ${err?.message || err}`)
|
|
624
|
+
failed++
|
|
625
|
+
}
|
|
626
|
+
return { deleted, failed }
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
// -- internals ------------------------------------------------------------
|
|
630
|
+
|
|
631
|
+
/**
|
|
632
|
+
* Everything an archive attempt does BEFORE compression, synchronously:
|
|
633
|
+
* load, retention, the skip rules, the dedupe, and the size-bounded JSON.
|
|
634
|
+
* @returns {{ status: string } | { job: object }}
|
|
635
|
+
*/
|
|
636
|
+
_prepare(saved, reason) {
|
|
637
|
+
this._ensureLoaded()
|
|
638
|
+
this._sweep() // the off switch stops new writes; it must not stop old data ageing out
|
|
639
|
+
if (!this._enabled) return { status: 'skipped' }
|
|
640
|
+
if (!savedHasHistory(saved)) return { status: 'skipped' }
|
|
641
|
+
const archivedAt = this._now()
|
|
642
|
+
const probe = metaFrom(saved, { archiveId: '0'.repeat(32), reason, archivedAt, bytes: 0 })
|
|
643
|
+
if (!probe) return { status: 'skipped' }
|
|
644
|
+
// The same snapshot — or an older one of the same session — again: a crash
|
|
645
|
+
// between archive and the state flush, a stale entry seen on two boots, a
|
|
646
|
+
// backup that still carries a source whose archive was since deleted
|
|
647
|
+
// (tombstone), or one still being compressed.
|
|
648
|
+
const candidate = { sessionId: probe.sessionId, lastActivityAt: probe.lastActivityAt, length: probe.historyLength }
|
|
649
|
+
if (this._isKnownSnapshot(candidate)) return { status: 'duplicate' }
|
|
650
|
+
|
|
651
|
+
const built = buildRecordJson(saved, { archivedAt, reason: probe.reason }, this._maxRecordBytes)
|
|
652
|
+
if (!built) throw new Error(`no history entry fits the ${this._maxRecordBytes}-byte record bound`)
|
|
653
|
+
if (built.omittedOldest > 0) {
|
|
654
|
+
log.warn(`Archiving session ${probe.sessionId}: the ${built.omittedOldest} oldest history entries exceed the record size bound and were omitted`)
|
|
655
|
+
}
|
|
656
|
+
const archiveId = randomBytes(16).toString('hex')
|
|
657
|
+
return {
|
|
658
|
+
job: {
|
|
659
|
+
archiveId,
|
|
660
|
+
json: built.json,
|
|
661
|
+
candidate,
|
|
662
|
+
done: false,
|
|
663
|
+
meta: { ...probe, archiveId, historyLength: built.kept, omittedOldest: built.omittedOldest },
|
|
664
|
+
},
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
_isKnownSnapshot(candidate) {
|
|
669
|
+
return this._index.some((row) => snapshotCovers({ sessionId: row.sessionId, lastActivityAt: row.lastActivityAt, length: rowSourceLength(row) }, candidate))
|
|
670
|
+
|| this._tombstones.some((t) => snapshotCovers(tombstoneAsSnapshot(t), candidate))
|
|
671
|
+
|| this._pending.some((job) => snapshotCovers(job.candidate, candidate))
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
/**
|
|
675
|
+
* Write a prepared job's compressed record and index it. THROWS on a failed
|
|
676
|
+
* write (after removing the temp file the failed write may have left).
|
|
677
|
+
* @returns {object|null} the roster row; null (nothing written, NOTHING
|
|
678
|
+
* evicted) when the record alone exceeds the user's byte cap
|
|
679
|
+
*/
|
|
680
|
+
_commit(job, gz, { durable = false } = {}) {
|
|
681
|
+
if (gz.length > this._maxMegabytes * MIB) {
|
|
682
|
+
log.warn(`Not archiving session ${job.meta.sessionId}: its ${gz.length}-byte record alone exceeds the sessionArchive.maxMegabytes cap (${this._maxMegabytes})`)
|
|
683
|
+
return null
|
|
684
|
+
}
|
|
685
|
+
mkdirSync(this._dir, { recursive: true, mode: 0o700 })
|
|
686
|
+
// mkdir's mode only applies to a directory it creates, and is masked by the
|
|
687
|
+
// umask; make the guarantee explicit for one that already existed.
|
|
688
|
+
if (!isWindows) {
|
|
689
|
+
try { chmodSync(this._dir, 0o700) } catch { /* best effort */ }
|
|
690
|
+
}
|
|
691
|
+
const path = this._recordPath(job.archiveId)
|
|
692
|
+
try {
|
|
693
|
+
this._writeFile(path, gz, { tmpSuffix: this._tmpSuffix, durable })
|
|
694
|
+
} catch (err) {
|
|
695
|
+
this._unlinkTemp(path)
|
|
696
|
+
throw err
|
|
697
|
+
}
|
|
698
|
+
const meta = { ...job.meta, bytes: gz.length }
|
|
699
|
+
this._index.push(meta)
|
|
700
|
+
this._enforceRetention(job.archiveId)
|
|
701
|
+
this._writeIndex({ durable })
|
|
702
|
+
return { ...meta }
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
_schedule() {
|
|
706
|
+
if (this._pumping) return
|
|
707
|
+
this._pumping = (async () => {
|
|
708
|
+
try {
|
|
709
|
+
for (;;) {
|
|
710
|
+
const job = this._pending.find((j) => !j.done)
|
|
711
|
+
if (!job) break
|
|
712
|
+
await this._runJob(job)
|
|
713
|
+
}
|
|
714
|
+
} finally {
|
|
715
|
+
this._pumping = null
|
|
716
|
+
}
|
|
717
|
+
})()
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
async _runJob(job) {
|
|
721
|
+
try {
|
|
722
|
+
const gz = await gzipAsync(job.json, GZIP_OPTS)
|
|
723
|
+
if (job.done) return // drainSync() finished it, or deleteAll() cancelled it, while we compressed
|
|
724
|
+
job.done = true
|
|
725
|
+
this._commit(job, gz)
|
|
726
|
+
} catch (err) {
|
|
727
|
+
job.done = true
|
|
728
|
+
log.warn(`Failed to archive a closed session: ${err?.message || err}`)
|
|
729
|
+
} finally {
|
|
730
|
+
this._pending = this._pending.filter((j) => j !== job)
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
/** Cancel every queued snapshot and tombstone it. @returns {number} how many */
|
|
735
|
+
_cancelPending() {
|
|
736
|
+
let cancelled = 0
|
|
737
|
+
for (const job of this._pending) {
|
|
738
|
+
if (job.done) continue
|
|
739
|
+
job.done = true
|
|
740
|
+
this._addTombstone(job.candidate.sessionId, job.candidate.lastActivityAt, job.candidate.length)
|
|
741
|
+
cancelled++
|
|
742
|
+
}
|
|
743
|
+
this._pending = []
|
|
744
|
+
return cancelled
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
/** Apply retention now (it persists the index itself when it drops anything). */
|
|
748
|
+
_sweep() {
|
|
749
|
+
this._enforceRetention()
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
_addTombstone(sessionId, lastActivityAt, length) {
|
|
753
|
+
const tombstone = { sessionId, lastActivityAt, historyLength: length, at: this._now() }
|
|
754
|
+
this._tombstones.push(tombstone)
|
|
755
|
+
if (this._tombstones.length > MAX_TOMBSTONES) this._tombstones.splice(0, this._tombstones.length - MAX_TOMBSTONES)
|
|
756
|
+
return tombstone
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
/**
|
|
760
|
+
* Remove rows DURABLY: the index (without the rows, with their tombstones) is
|
|
761
|
+
* written FIRST and the record files are unlinked only after that succeeded,
|
|
762
|
+
* so a crash or a failed write can never leave a deleted record without its
|
|
763
|
+
* tombstone. A row whose file could not be unlinked is put back (and its
|
|
764
|
+
* tombstone dropped) so it stays visible and is retried.
|
|
765
|
+
* @param {object[]} rows
|
|
766
|
+
* @returns {{ removed: object[], failed: object[] }}
|
|
767
|
+
*/
|
|
768
|
+
_removeRows(rows) {
|
|
769
|
+
if (rows.length === 0) return { removed: [], failed: [] }
|
|
770
|
+
const ids = new Set(rows.map((row) => row.archiveId))
|
|
771
|
+
const prevIndex = this._index
|
|
772
|
+
const prevTombstones = this._tombstones
|
|
773
|
+
this._index = prevIndex.filter((row) => !ids.has(row.archiveId))
|
|
774
|
+
this._tombstones = [...prevTombstones]
|
|
775
|
+
const added = new Map()
|
|
776
|
+
for (const row of rows) added.set(row.archiveId, this._addTombstone(row.sessionId, row.lastActivityAt, rowSourceLength(row)))
|
|
777
|
+
if (!this._writeIndex({ durable: true })) {
|
|
778
|
+
this._index = prevIndex
|
|
779
|
+
this._tombstones = prevTombstones
|
|
780
|
+
return { removed: [], failed: rows }
|
|
781
|
+
}
|
|
782
|
+
const removed = []
|
|
783
|
+
const failed = []
|
|
784
|
+
for (const row of rows) {
|
|
785
|
+
if (this._unlinkRecord(row.archiveId)) {
|
|
786
|
+
removed.push(row)
|
|
787
|
+
this._invalidate(row.archiveId)
|
|
788
|
+
} else {
|
|
789
|
+
failed.push(row)
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
if (failed.length > 0) {
|
|
793
|
+
const stuck = new Set(failed.map((row) => added.get(row.archiveId)))
|
|
794
|
+
this._index = [...this._index, ...failed]
|
|
795
|
+
this._tombstones = this._tombstones.filter((t) => !stuck.has(t))
|
|
796
|
+
this._writeIndex({ durable: true })
|
|
797
|
+
}
|
|
798
|
+
return { removed, failed }
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
/** A client-supplied id is only ever used after BOTH checks. */
|
|
802
|
+
_knows(archiveId) {
|
|
803
|
+
return typeof archiveId === 'string'
|
|
804
|
+
&& ARCHIVE_ID_RE.test(archiveId)
|
|
805
|
+
&& this._index.some((row) => row.archiveId === archiveId)
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
_recordPath(archiveId) {
|
|
809
|
+
// Only ever called with an id this class generated or one that passed _knows.
|
|
810
|
+
return join(this._dir, `${archiveId}${RECORD_SUFFIX}`)
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
_invalidate(archiveId) {
|
|
814
|
+
if (this._cache?.archiveId === archiveId) this._cache = null
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
_unlinkTemp(path) {
|
|
818
|
+
try { unlinkSync(`${path}${this._tmpSuffix}`) } catch { /* nothing left to remove */ }
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
/** @returns {boolean} true when the file is gone afterwards */
|
|
822
|
+
_unlinkRecord(archiveId) {
|
|
823
|
+
try {
|
|
824
|
+
unlinkSync(this._recordPath(archiveId))
|
|
825
|
+
return true
|
|
826
|
+
} catch (err) {
|
|
827
|
+
if (err?.code === 'ENOENT') return true
|
|
828
|
+
log.warn(`Failed to remove archive record ${archiveId}: ${err?.message || err}`)
|
|
829
|
+
return false
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
async _readRecord(archiveId) {
|
|
834
|
+
if (this._cache?.archiveId === archiveId) return this._cache.record
|
|
835
|
+
let record
|
|
836
|
+
try {
|
|
837
|
+
const raw = await gunzipAsync(await readFileNoFollow(this._recordPath(archiveId)), { maxOutputLength: this._maxRecordBytes })
|
|
838
|
+
record = JSON.parse(raw.toString('utf8'))
|
|
839
|
+
} catch (err) {
|
|
840
|
+
log.warn(`Unreadable archive record ${archiveId}: ${errTag(err)}`)
|
|
841
|
+
return null
|
|
842
|
+
}
|
|
843
|
+
if (!record || typeof record !== 'object') return null
|
|
844
|
+
// The record may have been deleted or aged out while it was being read.
|
|
845
|
+
if (!this._knows(archiveId)) return null
|
|
846
|
+
this._cache = { archiveId, record }
|
|
847
|
+
return record
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
/**
|
|
851
|
+
* Persist the index and tombstones. The record files are the authority for
|
|
852
|
+
* rows (a lost index is rebuilt), but TOMBSTONES exist nowhere else, so
|
|
853
|
+
* callers that depend on one check the result.
|
|
854
|
+
* @returns {boolean} false when the write failed (its temp file is removed)
|
|
855
|
+
*/
|
|
856
|
+
_writeIndex({ durable = false, create = false } = {}) {
|
|
857
|
+
if (!existsSync(this._dir)) {
|
|
858
|
+
if (!create) return true
|
|
859
|
+
try { mkdirSync(this._dir, { recursive: true, mode: 0o700 }) } catch (err) {
|
|
860
|
+
log.warn(`Failed to create the session archive directory: ${err?.message || err}`)
|
|
861
|
+
return false
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
const path = join(this._dir, INDEX_FILE)
|
|
865
|
+
try {
|
|
866
|
+
this._writeFile(path, JSON.stringify({ version: FORMAT_VERSION, entries: this._index, tombstones: this._tombstones }), { tmpSuffix: this._tmpSuffix, durable })
|
|
867
|
+
return true
|
|
868
|
+
} catch (err) {
|
|
869
|
+
this._unlinkTemp(path)
|
|
870
|
+
log.warn(`Failed to write the session archive index: ${err?.message || err}`)
|
|
871
|
+
return false
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
/**
|
|
876
|
+
* Read the index, reconcile it with the record files, then apply retention.
|
|
877
|
+
* Only a MISSING directory (or index) means "empty": any other read error
|
|
878
|
+
* THROWS, leaving the archive unloaded so the next call retries, instead of
|
|
879
|
+
* caching an empty index that the next write would persist over real data.
|
|
880
|
+
*/
|
|
881
|
+
_ensureLoaded() {
|
|
882
|
+
if (this._index) return
|
|
883
|
+
if (!this._dirValid) {
|
|
884
|
+
this._index = []
|
|
885
|
+
return
|
|
886
|
+
}
|
|
887
|
+
let names
|
|
888
|
+
try {
|
|
889
|
+
names = readdirSync(this._dir)
|
|
890
|
+
} catch (err) {
|
|
891
|
+
// ENOTDIR: a path component is a file, so there is no archive here either.
|
|
892
|
+
if (err?.code === 'ENOENT' || err?.code === 'ENOTDIR') {
|
|
893
|
+
this._index = []
|
|
894
|
+
this._tombstones = []
|
|
895
|
+
return
|
|
896
|
+
}
|
|
897
|
+
throw err
|
|
898
|
+
}
|
|
899
|
+
const onDisk = new Set()
|
|
900
|
+
for (const name of names) {
|
|
901
|
+
const m = RECORD_FILE_RE.exec(name)
|
|
902
|
+
if (m) {
|
|
903
|
+
onDisk.add(m[1])
|
|
904
|
+
} else if (TMP_FILE_RE.test(name)) {
|
|
905
|
+
// A temp left by a write that died mid-way. Load precedes this process's
|
|
906
|
+
// own writes, so it cannot be ours in flight; it can hold transcript bytes.
|
|
907
|
+
try { unlinkSync(join(this._dir, name)) } catch { /* best effort */ }
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
let indexed = []
|
|
912
|
+
let tombstones = []
|
|
913
|
+
let dirty = false
|
|
914
|
+
let indexExisted = true
|
|
915
|
+
try {
|
|
916
|
+
const parsed = JSON.parse(readFileNoFollowSync(join(this._dir, INDEX_FILE)).toString('utf8'))
|
|
917
|
+
if (!parsed || !Array.isArray(parsed.entries)) throw new Error('malformed index')
|
|
918
|
+
const seen = new Set()
|
|
919
|
+
for (const row of parsed.entries) {
|
|
920
|
+
const meta = metaFromIndexRow(row)
|
|
921
|
+
if (!meta || seen.has(meta.archiveId)) { dirty = true; continue }
|
|
922
|
+
seen.add(meta.archiveId)
|
|
923
|
+
indexed.push(meta)
|
|
924
|
+
}
|
|
925
|
+
if (Array.isArray(parsed.tombstones)) {
|
|
926
|
+
const valid = parsed.tombstones.map(tombstoneFromIndexRow).filter(Boolean)
|
|
927
|
+
if (valid.length !== parsed.tombstones.length) dirty = true
|
|
928
|
+
tombstones = valid.slice(-MAX_TOMBSTONES)
|
|
929
|
+
}
|
|
930
|
+
} catch (err) {
|
|
931
|
+
if (err?.code === 'ENOENT') {
|
|
932
|
+
indexExisted = false
|
|
933
|
+
} else if (err?.name === 'SyntaxError' || err?.code === 'ELOOP' || err?.code === 'ENOTREG' || err?.message === 'malformed index') {
|
|
934
|
+
// Corrupt (or a planted symlink): rebuild from the record files. Log the
|
|
935
|
+
// class of error only — a parse message can quote the file's content.
|
|
936
|
+
log.warn(`Session archive index unreadable (${errTag(err)}) — rebuilding from the record files`)
|
|
937
|
+
} else {
|
|
938
|
+
throw err // EACCES, EIO, ...: not "empty" — do not overwrite what we cannot read
|
|
939
|
+
}
|
|
940
|
+
indexed = []
|
|
941
|
+
tombstones = []
|
|
942
|
+
dirty = true
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
// Drop rows whose file is gone.
|
|
946
|
+
const reconciled = indexed.filter((meta) => onDisk.has(meta.archiveId))
|
|
947
|
+
if (reconciled.length !== indexed.length) dirty = true
|
|
948
|
+
// Adopt record files the index does not know — unless a tombstone says the
|
|
949
|
+
// record was deleted (its unlink never ran: a crash between the two).
|
|
950
|
+
const known = new Set(reconciled.map((meta) => meta.archiveId))
|
|
951
|
+
for (const archiveId of onDisk) {
|
|
952
|
+
if (known.has(archiveId)) continue
|
|
953
|
+
const adopted = this._deriveMeta(archiveId)
|
|
954
|
+
if (!adopted) continue
|
|
955
|
+
const candidate = { sessionId: adopted.sessionId, lastActivityAt: adopted.lastActivityAt, length: rowSourceLength(adopted) }
|
|
956
|
+
if (tombstones.some((t) => snapshotCovers(tombstoneAsSnapshot(t), candidate))) {
|
|
957
|
+
this._unlinkRecord(archiveId)
|
|
958
|
+
continue
|
|
959
|
+
}
|
|
960
|
+
reconciled.push(adopted)
|
|
961
|
+
dirty = true
|
|
962
|
+
}
|
|
963
|
+
this._index = reconciled
|
|
964
|
+
this._tombstones = tombstones
|
|
965
|
+
this._enforceRetention()
|
|
966
|
+
// An empty directory with no index is simply empty: do not create a file.
|
|
967
|
+
if (dirty && (indexExisted || this._index.length > 0)) this._writeIndex()
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
/** Derive a roster row from a record file the index does not know. */
|
|
971
|
+
_deriveMeta(archiveId) {
|
|
972
|
+
try {
|
|
973
|
+
const compressed = readFileNoFollowSync(this._recordPath(archiveId))
|
|
974
|
+
const raw = gunzipSync(compressed, { maxOutputLength: this._maxRecordBytes })
|
|
975
|
+
const record = JSON.parse(raw.toString('utf8'))
|
|
976
|
+
if (!record || typeof record !== 'object' || !record.saved || typeof record.saved !== 'object') return null
|
|
977
|
+
return metaFrom(record.saved, {
|
|
978
|
+
archiveId,
|
|
979
|
+
reason: record.reason,
|
|
980
|
+
archivedAt: record.archivedAt,
|
|
981
|
+
bytes: compressed.length,
|
|
982
|
+
omittedOldest: record.omittedOldest,
|
|
983
|
+
})
|
|
984
|
+
} catch (err) {
|
|
985
|
+
log.warn(`Skipping unreadable archive record ${archiveId}: ${errTag(err)}`)
|
|
986
|
+
return null
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
/**
|
|
991
|
+
* Age, then count, then total bytes — oldest first each time — through
|
|
992
|
+
* `_removeRows`, so each dropped row's tombstone is on disk before its file is
|
|
993
|
+
* unlinked. Only as many rows as needed are dropped, and `protectId` (the
|
|
994
|
+
* record being committed) is never evicted to satisfy the COUNT or BYTE cap
|
|
995
|
+
* (a record that is itself past maxAge ages out at the next sweep as usual). A pass whose index write
|
|
996
|
+
* failed drops nothing and is retried by the next one.
|
|
997
|
+
* @param {string} [protectId]
|
|
998
|
+
* @returns {number} how many rows were dropped
|
|
999
|
+
*/
|
|
1000
|
+
_enforceRetention(protectId) {
|
|
1001
|
+
if (!this._index || this._index.length === 0) return 0
|
|
1002
|
+
const now = this._now()
|
|
1003
|
+
const maxAgeMs = this._maxAgeDays * DAY_MS
|
|
1004
|
+
const maxBytes = this._maxMegabytes * MIB
|
|
1005
|
+
const oldestFirst = [...this._index].sort((a, b) => (a.archivedAt ?? 0) - (b.archivedAt ?? 0) || (a.archiveId < b.archiveId ? -1 : 1))
|
|
1006
|
+
const drop = new Set()
|
|
1007
|
+
for (const row of oldestFirst) {
|
|
1008
|
+
if (typeof row.archivedAt === 'number' && now - row.archivedAt > maxAgeMs) drop.add(row.archiveId)
|
|
1009
|
+
}
|
|
1010
|
+
const kept = oldestFirst.filter((row) => !drop.has(row.archiveId))
|
|
1011
|
+
const evictable = () => kept.find((row) => row.archiveId !== protectId)
|
|
1012
|
+
while (kept.length > this._maxEntries) {
|
|
1013
|
+
const victim = evictable()
|
|
1014
|
+
if (!victim) break
|
|
1015
|
+
drop.add(victim.archiveId)
|
|
1016
|
+
kept.splice(kept.indexOf(victim), 1)
|
|
1017
|
+
}
|
|
1018
|
+
let total = kept.reduce((sum, row) => sum + (row.bytes || 0), 0)
|
|
1019
|
+
while (total > maxBytes) {
|
|
1020
|
+
const victim = evictable()
|
|
1021
|
+
if (!victim) break
|
|
1022
|
+
drop.add(victim.archiveId)
|
|
1023
|
+
kept.splice(kept.indexOf(victim), 1)
|
|
1024
|
+
total -= victim.bytes || 0
|
|
1025
|
+
}
|
|
1026
|
+
if (drop.size === 0) return 0
|
|
1027
|
+
return this._removeRows(oldestFirst.filter((row) => drop.has(row.archiveId))).removed.length
|
|
1028
|
+
}
|
|
1029
|
+
}
|