@myrialabs/clopen 0.4.47 → 0.4.49
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -11
- package/backend/artifacts/project/sources.ts +1 -1
- package/backend/auth/auth-service.ts +52 -358
- package/backend/auth/onboarding.test.ts +2 -3
- package/backend/auth/permissions.test.ts +10 -20
- package/backend/auth/permissions.ts +4 -290
- package/backend/auth/rate-limiter.test.ts +8 -9
- package/backend/auth/rate-limiter.ts +0 -2
- package/backend/auth/tokens.ts +1 -8
- package/backend/bootstrap.ts +7 -0
- package/backend/chat/attachments.test.ts +88 -0
- package/backend/chat/attachments.ts +159 -0
- package/backend/chat/engine-handoff.test.ts +0 -2
- package/backend/chat/message-pages.test.ts +163 -0
- package/backend/chat/message-pages.ts +233 -0
- package/backend/chat/stream-manager.ts +91 -67
- package/backend/chat/turn-answer.test.ts +64 -0
- package/backend/chat/turn-answer.ts +125 -0
- package/backend/chat-apps/awaiting.test.ts +39 -0
- package/backend/chat-apps/awaiting.ts +49 -0
- package/backend/chat-apps/conversation.ts +746 -0
- package/backend/chat-apps/inbound.ts +324 -0
- package/backend/chat-apps/index.ts +309 -0
- package/backend/chat-apps/link-events.ts +20 -0
- package/backend/chat-apps/media.test.ts +62 -0
- package/backend/chat-apps/media.ts +208 -0
- package/backend/chat-apps/messages.test.ts +229 -0
- package/backend/chat-apps/messages.ts +365 -0
- package/backend/chat-apps/outbound.ts +243 -0
- package/backend/chat-apps/pairing.test.ts +45 -0
- package/backend/chat-apps/pairing.ts +74 -0
- package/backend/chat-apps/platforms/index.ts +20 -0
- package/backend/chat-apps/platforms/telegram.test.ts +35 -0
- package/backend/chat-apps/platforms/telegram.ts +191 -0
- package/backend/chat-apps/platforms/types.ts +114 -0
- package/backend/chat-apps/questions.ts +133 -0
- package/backend/chat-apps/runtime.ts +572 -0
- package/backend/chat-apps/storage.test.ts +201 -0
- package/backend/chat-apps/turns.test.ts +45 -0
- package/backend/chat-apps/turns.ts +208 -0
- package/backend/containers/pty.ts +3 -11
- package/backend/control/actions/accounts.ts +89 -0
- package/backend/control/actions/files.ts +116 -0
- package/backend/control/actions/models.ts +188 -0
- package/backend/control/actions/projects.ts +272 -0
- package/backend/control/actions/sessions.ts +280 -0
- package/backend/control/actions/skills.ts +111 -0
- package/backend/control/control.test.ts +169 -0
- package/backend/control/define.ts +20 -0
- package/backend/control/folders.test.ts +67 -0
- package/backend/control/index.ts +213 -0
- package/backend/control/invoke.ts +44 -0
- package/backend/control/links.ts +35 -0
- package/backend/control/paging.ts +26 -0
- package/backend/control/types.ts +117 -0
- package/backend/control/workspace.ts +127 -0
- package/backend/database/migrations/084_create_channel_links.ts +71 -0
- package/backend/database/migrations/085_add_home_projects.ts +36 -0
- package/backend/database/migrations/086_single_owner.ts +418 -0
- package/backend/database/migrations/087_create_blob_line_stats.ts +37 -0
- package/backend/database/migrations/index.ts +28 -0
- package/backend/database/queries/auth-queries.ts +7 -85
- package/backend/database/queries/blob-line-stats-queries.ts +48 -0
- package/backend/database/queries/channel-queries.ts +270 -0
- package/backend/database/queries/db-client-connection-queries.ts +18 -56
- package/backend/database/queries/file-share-queries.ts +5 -23
- package/backend/database/queries/git-identity-queries.ts +31 -42
- package/backend/database/queries/graph-queries.ts +1 -1
- package/backend/database/queries/index.ts +15 -1
- package/backend/database/queries/message-queries.test.ts +146 -0
- package/backend/database/queries/message-queries.ts +42 -1
- package/backend/database/queries/permission-set-queries.ts +1 -1
- package/backend/database/queries/profile-queries.ts +1 -1
- package/backend/database/queries/project-mcp-trust-queries.ts +1 -1
- package/backend/database/queries/project-queries.ts +50 -63
- package/backend/database/queries/session-queries.ts +28 -56
- package/backend/database/queries/ssh-connection-queries.ts +18 -41
- package/backend/db-client/env/diff.ts +9 -33
- package/backend/db-client/env/env.test.ts +8 -8
- package/backend/db-client/env/service.ts +1 -1
- package/backend/db-client/integrations/projector.ts +0 -5
- package/backend/engine/adapters/claude/message-converter.test.ts +47 -0
- package/backend/engine/adapters/claude/message-converter.ts +25 -2
- package/backend/engine/adapters/cline/message-converter.ts +0 -1
- package/backend/engine/adapters/cline/stream.ts +11 -15
- package/backend/engine/adapters/codex/message-converter.ts +0 -2
- package/backend/engine/adapters/copilot/message-converter.ts +1 -2
- package/backend/engine/adapters/cursor/message-converter.ts +0 -1
- package/backend/engine/adapters/opencode/message-converter.ts +2 -4
- package/backend/engine/adapters/opencode/stream.ts +11 -0
- package/backend/engine/adapters/parent-scope.test.ts +38 -0
- package/backend/engine/adapters/parent-scope.ts +44 -0
- package/backend/engine/adapters/pi/message-converter.ts +0 -1
- package/backend/engine/adapters/pi/stream.ts +4 -5
- package/backend/engine/adapters/qwen/message-converter.ts +0 -2
- package/backend/engine/bootstrap-default-engine.ts +2 -2
- package/backend/engine/docs/adapter-contract.md +8 -1
- package/backend/engine/install-runner.ts +8 -17
- package/backend/files/file-shares.ts +20 -44
- package/backend/files/file-size-limit.ts +3 -3
- package/backend/files/file-watcher.ts +19 -0
- package/backend/files/image-processing.ts +1 -1
- package/backend/files/os-clipboard.ts +2 -2
- package/backend/git/contributors.test.ts +35 -0
- package/backend/git/contributors.ts +46 -0
- package/backend/git/git-executor.ts +25 -5
- package/backend/git/git-service.ts +420 -19
- package/backend/git/identity/credential-helper.test.ts +2 -7
- package/backend/git/identity/import-local.test.ts +11 -16
- package/backend/git/identity/import-local.ts +12 -12
- package/backend/git/identity/index.ts +10 -24
- package/backend/git/identity/resolve.ts +13 -14
- package/backend/git/identity/scope-config.ts +33 -28
- package/backend/git/identity/service.ts +44 -47
- package/backend/git/op-lock.test.ts +111 -0
- package/backend/git/op-lock.ts +180 -0
- package/backend/git/remote-sync.test.ts +249 -0
- package/backend/host/metrics.ts +1 -1
- package/backend/http/bearer-auth.ts +1 -2
- package/backend/http/files-download.test.ts +8 -9
- package/backend/http/files-download.ts +2 -2
- package/backend/http/files-shared.test.ts +62 -89
- package/backend/http/files-shared.ts +2 -2
- package/backend/http/files-upload.test.ts +3 -7
- package/backend/http/files-upload.ts +3 -3
- package/backend/http/notes-images.test.ts +15 -38
- package/backend/http/notes-images.ts +6 -8
- package/backend/http/ssh-sftp.ts +5 -10
- package/backend/http/static-assets.test.ts +78 -0
- package/backend/http/static-assets.ts +104 -0
- package/backend/index.ts +32 -16
- package/backend/integrations/accounts.ts +61 -3
- package/backend/integrations/index.ts +2 -2
- package/backend/integrations/registry/define.ts +15 -0
- package/backend/integrations/registry/index.ts +2 -0
- package/backend/integrations/registry/providers/telegram.ts +54 -0
- package/backend/integrations/registry/types.ts +21 -1
- package/backend/integrations/webhooks/gateway.ts +7 -6
- package/backend/integrations/webhooks/verify.test.ts +30 -0
- package/backend/integrations/webhooks/verify.ts +4 -0
- package/backend/mcp/external/project.ts +1 -1
- package/backend/mcp/internal/remote-server.test.ts +1 -3
- package/backend/mcp/internal/remote-server.ts +4 -4
- package/backend/mcp/internal/servers/browser-automation/actions/dialogs.ts +67 -0
- package/backend/mcp/internal/servers/browser-automation/actions/index.ts +3 -1
- package/backend/mcp/internal/servers/browser-automation/actions/input.ts +5 -5
- package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +157 -28
- package/backend/mcp/internal/servers/browser-automation/context.ts +1 -0
- package/backend/mcp/internal/servers/browser-automation/description.ts +5 -2
- package/backend/mcp/internal/servers/browser-automation/format.ts +24 -1
- package/backend/mcp/internal/servers/browser-automation/runner.ts +68 -3
- package/backend/memory/redact.ts +1 -1
- package/backend/notes/access.test.ts +28 -29
- package/backend/notes/access.ts +6 -11
- package/backend/permissions/service.ts +1 -1
- package/backend/preview/browser/browser-clipboard.test.ts +46 -0
- package/backend/preview/browser/browser-clipboard.ts +67 -0
- package/backend/preview/browser/browser-dialog-handler.ts +95 -6
- package/backend/preview/browser/browser-host-bridge.ts +9 -0
- package/backend/preview/browser/browser-interaction-handler.ts +316 -86
- package/backend/preview/browser/browser-mcp-control.ts +34 -0
- package/backend/preview/browser/browser-pool.ts +67 -6
- package/backend/preview/browser/browser-preview-service.ts +383 -29
- package/backend/preview/browser/browser-tab-manager.ts +66 -23
- package/backend/preview/browser/browser-video-capture.ts +92 -5
- package/backend/preview/browser/element-locator.ts +190 -17
- package/backend/preview/browser/keyboard-chords.test.ts +68 -0
- package/backend/preview/browser/keyboard-chords.ts +132 -0
- package/backend/preview/browser/paste.ts +81 -0
- package/backend/preview/browser/process-usage.ts +142 -0
- package/backend/preview/browser/profile-lock.ts +209 -0
- package/backend/preview/browser/scripts/host-bridge.ts +59 -0
- package/backend/preview/browser/scripts/video-stream.ts +58 -0
- package/backend/preview/browser/types.ts +40 -2
- package/backend/preview/browser/viewport.test.ts +45 -0
- package/backend/preview/browser/viewport.ts +96 -0
- package/backend/profiles/service.ts +2 -2
- package/backend/project/status-manager.ts +43 -172
- package/backend/projects/home.ts +61 -0
- package/backend/projects/project-cleanup.integration.test.ts +2 -2
- package/backend/projects/project-cleanup.ts +0 -8
- package/backend/skills/service.ts +2 -3
- package/backend/snapshot/blob-store.ts +9 -1
- package/backend/snapshot/helpers.ts +3 -11
- package/backend/snapshot/line-stats.test.ts +80 -0
- package/backend/snapshot/line-stats.ts +64 -0
- package/backend/snapshot/restore.ts +252 -0
- package/backend/snapshot/snapshot-service.ts +14 -27
- package/backend/snapshot/turn-changes.test.ts +10 -5
- package/backend/snapshot/turn-changes.ts +78 -40
- package/backend/ssh/ptykit.ts +1 -2
- package/backend/terminal/ptykit.ts +10 -8
- package/backend/tunnel/public-origin.ts +31 -20
- package/backend/utils/user-helpers.ts +0 -55
- package/backend/utils/ws-wire.test.ts +87 -0
- package/backend/utils/ws-wire.ts +189 -0
- package/backend/utils/ws.ts +101 -192
- package/backend/worktrees/branching/engine.ts +3 -16
- package/backend/worktrees/branching/index.ts +1 -1
- package/backend/worktrees/branching/projector.ts +1 -1
- package/backend/worktrees/branching/service.ts +13 -25
- package/backend/ws/access.ts +12 -21
- package/backend/ws/artifacts/generate.ts +2 -2
- package/backend/ws/auth/device.ts +16 -71
- package/backend/ws/auth/index.ts +4 -22
- package/backend/ws/auth/login.test.ts +14 -60
- package/backend/ws/auth/login.ts +24 -124
- package/backend/ws/auth/status.ts +0 -1
- package/backend/ws/chat/composer.ts +118 -118
- package/backend/ws/chat/stream.ts +105 -57
- package/backend/ws/chat-apps/index.ts +117 -0
- package/backend/ws/containers/actions.ts +11 -25
- package/backend/ws/containers/index.ts +3 -4
- package/backend/ws/containers/list.ts +10 -36
- package/backend/ws/containers/logs.ts +2 -2
- package/backend/ws/containers/tunnel.ts +1 -2
- package/backend/ws/db-client/access.ts +2 -16
- package/backend/ws/db-client/accounts.ts +5 -15
- package/backend/ws/db-client/connections.ts +17 -25
- package/backend/ws/db-client/context.ts +1 -1
- package/backend/ws/db-client/env.ts +7 -10
- package/backend/ws/db-client/index.ts +2 -2
- package/backend/ws/db-client/io.ts +5 -5
- package/backend/ws/db-client/query-history-retention.test.ts +8 -8
- package/backend/ws/db-client/query.ts +18 -17
- package/backend/ws/db-client/schema.ts +13 -13
- package/backend/ws/db-client/structure.ts +35 -35
- package/backend/ws/db-client/supabase.ts +4 -21
- package/backend/ws/deployments/context.ts +1 -1
- package/backend/ws/deployments/crud.ts +0 -5
- package/backend/ws/engine/access.ts +7 -20
- package/backend/ws/engine/claude/accounts.ts +4 -4
- package/backend/ws/engine/cline/accounts.ts +5 -5
- package/backend/ws/engine/codex/accounts.ts +3 -3
- package/backend/ws/engine/pi/accounts.ts +5 -5
- package/backend/ws/files/clipboard.ts +8 -27
- package/backend/ws/files/image-edit.ts +6 -6
- package/backend/ws/files/index.ts +1 -1
- package/backend/ws/files/path-access.test.ts +32 -131
- package/backend/ws/files/path-access.ts +8 -87
- package/backend/ws/files/read.ts +45 -19
- package/backend/ws/files/reveal.ts +3 -3
- package/backend/ws/files/search.ts +7 -7
- package/backend/ws/files/share.ts +9 -13
- package/backend/ws/files/state.ts +9 -12
- package/backend/ws/files/watch.ts +3 -3
- package/backend/ws/files/write.ts +30 -31
- package/backend/ws/git/branch.ts +80 -59
- package/backend/ws/git/commit.ts +63 -44
- package/backend/ws/git/conflict.ts +16 -18
- package/backend/ws/git/identity-context.ts +8 -17
- package/backend/ws/git/identity.ts +17 -27
- package/backend/ws/git/index.ts +3 -1
- package/backend/ws/git/log.ts +52 -0
- package/backend/ws/git/op-state.ts +139 -0
- package/backend/ws/git/remote.ts +241 -141
- package/backend/ws/git/repo-context.ts +67 -0
- package/backend/ws/git/staging.ts +18 -28
- package/backend/ws/git/status.ts +5 -2
- package/backend/ws/index.ts +5 -1
- package/backend/ws/instructions/crud.ts +1 -1
- package/backend/ws/integrations/crud.ts +1 -3
- package/backend/ws/mcp/crud.ts +3 -5
- package/backend/ws/mcp/tools.ts +1 -1
- package/backend/ws/memory/crud.ts +14 -46
- package/backend/ws/memory/index.ts +2 -2
- package/backend/ws/messages/crud.ts +78 -8
- package/backend/ws/notes/index.ts +33 -39
- package/backend/ws/permissions/crud.ts +3 -4
- package/backend/ws/ports/index.ts +1 -2
- package/backend/ws/ports/kill.ts +5 -10
- package/backend/ws/ports/list.ts +4 -10
- package/backend/ws/preview/access.ts +1 -1
- package/backend/ws/preview/browser/interact.ts +52 -79
- package/backend/ws/preview/browser/native-ui.ts +24 -0
- package/backend/ws/preview/browser/stats.ts +98 -1
- package/backend/ws/preview/browser/tab-info.ts +15 -0
- package/backend/ws/preview/browser/tab.ts +19 -4
- package/backend/ws/preview/index.ts +29 -0
- package/backend/ws/preview/watchers.ts +84 -0
- package/backend/ws/profiles/crud.ts +6 -8
- package/backend/ws/project-artifacts/index.ts +30 -31
- package/backend/ws/projects/crud.ts +33 -35
- package/backend/ws/projects/index.ts +3 -8
- package/backend/ws/projects/info.ts +3 -3
- package/backend/ws/projects/overview.ts +19 -30
- package/backend/ws/projects/status.ts +17 -57
- package/backend/ws/sessions/crud.ts +42 -57
- package/backend/ws/sessions/index.ts +1 -1
- package/backend/ws/settings/crud.ts +1 -1
- package/backend/ws/skills/crud.ts +3 -4
- package/backend/ws/skills/index.ts +1 -1
- package/backend/ws/snapshot/changes.ts +12 -13
- package/backend/ws/snapshot/restore.ts +11 -295
- package/backend/ws/snapshot/timeline.ts +2 -4
- package/backend/ws/ssh/access.ts +6 -21
- package/backend/ws/ssh/connections.ts +21 -31
- package/backend/ws/ssh/forwards.ts +12 -12
- package/backend/ws/ssh/sftp.ts +34 -34
- package/backend/ws/ssh/tunnel.ts +1 -2
- package/backend/ws/stack/install.ts +7 -17
- package/backend/ws/subagents/crud.ts +1 -1
- package/backend/ws/terminal/tunnel.ts +2 -2
- package/backend/ws/tunnel/share.ts +0 -2
- package/backend/ws/user/crud.ts +1 -59
- package/backend/ws/user/index.ts +1 -1
- package/backend/ws/work/context.ts +1 -1
- package/backend/ws/work/crud.ts +0 -5
- package/backend/ws/workspace/state.ts +10 -13
- package/backend/ws/worktrees/branching.ts +7 -36
- package/backend/ws/worktrees/crud.ts +2 -2
- package/bin/clopen.ts +46 -41
- package/dist/assets/addon-clipboard-wHJhZAA4.js.br +0 -0
- package/dist/assets/addon-clipboard-wHJhZAA4.js.gz +0 -0
- package/dist/assets/addon-fit-DX4qG4td.js.br +1 -0
- package/dist/assets/addon-fit-DX4qG4td.js.gz +0 -0
- package/dist/assets/addon-ligatures-DpDY8N_X.js.br +0 -0
- package/dist/assets/addon-ligatures-DpDY8N_X.js.gz +0 -0
- package/dist/assets/addon-unicode11-Bt8F3D7-.js.br +0 -0
- package/dist/assets/addon-unicode11-Bt8F3D7-.js.gz +0 -0
- package/dist/assets/addon-web-links-DIbG5aQx.js.br +0 -0
- package/dist/assets/addon-web-links-DIbG5aQx.js.gz +0 -0
- package/dist/assets/diff.worker-BoHLxmr2.js +7 -0
- package/dist/assets/diff.worker-BoHLxmr2.js.br +0 -0
- package/dist/assets/diff.worker-BoHLxmr2.js.gz +0 -0
- package/dist/assets/graph-layout.worker-CRFqN7ZQ.js.br +0 -0
- package/dist/assets/graph-layout.worker-CRFqN7ZQ.js.gz +0 -0
- package/dist/assets/{index-CwuKQelV.js → index-CrVWZH_D.js} +1 -1
- package/dist/assets/index-CrVWZH_D.js.br +0 -0
- package/dist/assets/index-CrVWZH_D.js.gz +0 -0
- package/dist/assets/{index-BTcR1byF.js → index-DD0-3EWg.js} +1 -1
- package/dist/assets/index-DD0-3EWg.js.br +0 -0
- package/dist/assets/index-DD0-3EWg.js.gz +0 -0
- package/dist/assets/main-D2_TmcwQ.js +1240 -0
- package/dist/assets/main-D2_TmcwQ.js.br +0 -0
- package/dist/assets/main-D2_TmcwQ.js.gz +0 -0
- package/dist/assets/main-Yucigcmf.css +1 -0
- package/dist/assets/main-Yucigcmf.css.br +0 -0
- package/dist/assets/main-Yucigcmf.css.gz +0 -0
- package/dist/assets/preview-video.worker-DcpDhCWL.js.br +0 -0
- package/dist/assets/preview-video.worker-DcpDhCWL.js.gz +0 -0
- package/dist/assets/xterm-B-qIQCd3.js.br +0 -0
- package/dist/assets/xterm-B-qIQCd3.js.gz +0 -0
- package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.br +0 -0
- package/dist/assets/zipkit-engine-CaR0t_Uy.wasm.gz +0 -0
- package/dist/fonts/dm-sans.css.br +0 -0
- package/dist/fonts/dm-sans.css.gz +0 -0
- package/dist/index.html +2 -2
- package/dist/index.html.br +0 -0
- package/dist/index.html.gz +0 -0
- package/dist/sw.js.br +0 -0
- package/dist/sw.js.gz +0 -0
- package/package.json +3 -3
- package/shared/constants/attachments.ts +14 -0
- package/shared/constants/engine-tools.ts +1 -1
- package/shared/constants/preview.test.ts +259 -0
- package/shared/constants/preview.ts +1018 -57
- package/shared/constants/tool-icons.ts +5 -0
- package/shared/types/containers/container.ts +1 -1
- package/shared/types/database/schema.ts +9 -6
- package/shared/types/git-identity.ts +1 -1
- package/shared/types/git.ts +116 -0
- package/shared/types/integrations.ts +7 -0
- package/shared/types/stores/settings.ts +1 -1
- package/shared/types/unified/index.ts +1 -1
- package/shared/types/unified/message.ts +0 -7
- package/shared/types/unified/stream.ts +13 -5
- package/shared/types/unified/tool.ts +15 -1
- package/shared/utils/ask-user-question.test.ts +319 -0
- package/shared/utils/ask-user-question.ts +154 -0
- package/shared/utils/diff-calculator.test.ts +178 -41
- package/shared/utils/diff-calculator.ts +383 -100
- package/shared/utils/home-project.ts +25 -0
- package/shared/utils/logger.ts +2 -0
- package/shared/utils/process-supervisor.test.ts +172 -0
- package/shared/utils/process-supervisor.ts +251 -0
- package/shared/utils/ws-chunk.test.ts +33 -0
- package/shared/utils/ws-chunk.ts +73 -0
- package/shared/utils/ws-client-chunks.test.ts +45 -0
- package/shared/utils/ws-client.ts +43 -0
- package/shared/utils/ws-server.ts +49 -21
- package/backend/auth/session-invalidation.test.ts +0 -112
- package/backend/auth/session-invalidation.ts +0 -77
- package/backend/project/status-manager.test.ts +0 -32
- package/backend/ws/auth/invites.ts +0 -94
- package/backend/ws/auth/users.ts +0 -112
- package/backend/ws/projects/presence.ts +0 -46
- package/backend/ws/stack/access.ts +0 -31
- package/dist/assets/main-BiDNMWb3.css +0 -1
- package/dist/assets/main-BlhKWz2B.js +0 -1241
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The supervisor that keeps the Clopen server (and the dev frontend/backend)
|
|
3
|
+
* running: a child killed from outside comes back, a requested stop does not,
|
|
4
|
+
* and the child lives in its own process group so a signal aimed at it cannot
|
|
5
|
+
* reach the supervisor.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { afterAll, describe, expect, test } from 'bun:test';
|
|
9
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
|
10
|
+
import { tmpdir } from 'node:os';
|
|
11
|
+
import { join } from 'node:path';
|
|
12
|
+
|
|
13
|
+
import { elapsedSeconds, supervise } from './process-supervisor';
|
|
14
|
+
|
|
15
|
+
const posix = process.platform !== 'win32';
|
|
16
|
+
const dir = mkdtempSync(join(tmpdir(), 'clopen-supervisor-'));
|
|
17
|
+
afterAll(() => rmSync(dir, { recursive: true, force: true }));
|
|
18
|
+
|
|
19
|
+
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
20
|
+
|
|
21
|
+
/** A child that prints its pid and process group, then waits. */
|
|
22
|
+
const LONG_RUNNING = ['sh', '-c', 'echo "pid=$$ pgid=$(ps -o pgid= -p $$ | tr -d " ")"; sleep 30'];
|
|
23
|
+
|
|
24
|
+
function collect() {
|
|
25
|
+
const lines: string[] = [];
|
|
26
|
+
const decoder = new TextDecoder();
|
|
27
|
+
return { lines, sink: (chunk: Uint8Array) => lines.push(...decoder.decode(chunk).split('\n').filter(Boolean)) };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function waitFor(check: () => boolean, timeoutMs = 5000) {
|
|
31
|
+
const deadline = Date.now() + timeoutMs;
|
|
32
|
+
while (!check()) {
|
|
33
|
+
if (Date.now() > deadline) throw new Error('timed out');
|
|
34
|
+
await sleep(20);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const pidsIn = (lines: string[]) =>
|
|
39
|
+
lines.map((line) => /pid=(\d+) pgid=(\d+)/.exec(line)).filter(Boolean).map((m) => ({ pid: Number(m![1]), pgid: Number(m![2]) }));
|
|
40
|
+
|
|
41
|
+
describe.if(posix)('supervise', () => {
|
|
42
|
+
test('runs the child in its own process group', async () => {
|
|
43
|
+
const out = collect();
|
|
44
|
+
const s = supervise({ name: 't', cmd: LONG_RUNNING, onStdout: out.sink, log: () => {} });
|
|
45
|
+
await waitFor(() => pidsIn(out.lines).length > 0);
|
|
46
|
+
const [{ pid, pgid }] = pidsIn(out.lines);
|
|
47
|
+
expect(pgid).toBe(pid);
|
|
48
|
+
expect(pgid).not.toBe(Number(Bun.spawnSync(['ps', '-o', 'pgid=', '-p', String(process.pid)]).stdout.toString().trim()));
|
|
49
|
+
await s.stop();
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
test('restarts a child killed from outside, and writes a report', async () => {
|
|
53
|
+
const out = collect();
|
|
54
|
+
const logs: string[] = [];
|
|
55
|
+
const reportFile = join(dir, 'report.log');
|
|
56
|
+
const s = supervise({
|
|
57
|
+
name: 'server',
|
|
58
|
+
cmd: LONG_RUNNING,
|
|
59
|
+
onStdout: out.sink,
|
|
60
|
+
log: (line) => logs.push(line),
|
|
61
|
+
reportFile,
|
|
62
|
+
restartDelayMs: 50
|
|
63
|
+
});
|
|
64
|
+
await waitFor(() => pidsIn(out.lines).length === 1);
|
|
65
|
+
const [first] = pidsIn(out.lines);
|
|
66
|
+
|
|
67
|
+
// A stray SIGTERM to the child's whole group — what took the server down.
|
|
68
|
+
process.kill(-first.pgid, 'SIGTERM');
|
|
69
|
+
|
|
70
|
+
await waitFor(() => pidsIn(out.lines).length === 2);
|
|
71
|
+
const [, second] = pidsIn(out.lines);
|
|
72
|
+
expect(second.pid).not.toBe(first.pid);
|
|
73
|
+
expect(logs.some((line) => line.includes('restarting'))).toBe(true);
|
|
74
|
+
expect(existsSync(reportFile)).toBe(true);
|
|
75
|
+
expect(readFileSync(reportFile, 'utf8')).toContain('exited without being asked to (signal SIGTERM)');
|
|
76
|
+
await s.stop();
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
test('a requested stop reaches the whole group and is not restarted', async () => {
|
|
80
|
+
const out = collect();
|
|
81
|
+
const s = supervise({
|
|
82
|
+
name: 't',
|
|
83
|
+
// The child starts a grandchild that reports its pid, then both wait.
|
|
84
|
+
cmd: ['sh', '-c', 'sleep 30 & echo "grandchild=$!"; wait'],
|
|
85
|
+
onStdout: out.sink,
|
|
86
|
+
log: () => {},
|
|
87
|
+
restartDelayMs: 50
|
|
88
|
+
});
|
|
89
|
+
await waitFor(() => out.lines.some((line) => line.startsWith('grandchild=')));
|
|
90
|
+
const grandchild = Number(out.lines.find((line) => line.startsWith('grandchild='))!.split('=')[1]);
|
|
91
|
+
|
|
92
|
+
const code = await s.stop('SIGTERM');
|
|
93
|
+
expect(typeof code).toBe('number');
|
|
94
|
+
await sleep(150);
|
|
95
|
+
expect(out.lines.filter((line) => line.startsWith('grandchild='))).toHaveLength(1); // not restarted
|
|
96
|
+
expect(() => process.kill(grandchild, 0)).toThrow(); // the grandchild went with it
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
test('gives up on a child that keeps dying', async () => {
|
|
100
|
+
const s = supervise({ name: 't', cmd: ['sh', '-c', 'exit 3'], log: () => {}, restartDelayMs: 10, maxRestarts: 2 });
|
|
101
|
+
expect(await s.done).toBe(3);
|
|
102
|
+
});
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
describe('elapsedSeconds', () => {
|
|
106
|
+
test('reads the ps elapsed-time formats', () => {
|
|
107
|
+
expect(elapsedSeconds('00:05')).toBe(5);
|
|
108
|
+
expect(elapsedSeconds('01:02:03')).toBe(3723);
|
|
109
|
+
expect(elapsedSeconds('2-00:00:01')).toBe(172_801);
|
|
110
|
+
expect(elapsedSeconds('garbage')).toBe(Number.POSITIVE_INFINITY);
|
|
111
|
+
});
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* The launcher as a whole, in its own process: SIGHUP leaves the server
|
|
116
|
+
* running, a stray SIGTERM to the server's group brings it back, and Ctrl+C
|
|
117
|
+
* to the launcher stops it with a graceful shutdown.
|
|
118
|
+
*/
|
|
119
|
+
describe.if(posix)('a supervising launcher', () => {
|
|
120
|
+
test('survives SIGHUP, recovers from a stray SIGTERM, stops on SIGINT', async () => {
|
|
121
|
+
const server = join(dir, 'fake-server.ts');
|
|
122
|
+
const launcher = join(dir, 'launcher.ts');
|
|
123
|
+
await Bun.write(
|
|
124
|
+
server,
|
|
125
|
+
`console.log('up pid=' + process.pid);
|
|
126
|
+
process.on('SIGHUP', () => console.log('ignored SIGHUP'));
|
|
127
|
+
const shutdown = (sig) => { console.log('graceful ' + sig); process.exit(0); };
|
|
128
|
+
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
|
129
|
+
process.on('SIGINT', () => shutdown('SIGINT'));
|
|
130
|
+
setInterval(() => {}, 1000);
|
|
131
|
+
`
|
|
132
|
+
);
|
|
133
|
+
await Bun.write(
|
|
134
|
+
launcher,
|
|
135
|
+
`import { supervise, stopOnSignals } from ${JSON.stringify(join(import.meta.dir, 'process-supervisor.ts'))};
|
|
136
|
+
const s = supervise({ name: 'server', cmd: ['bun', ${JSON.stringify(server)}], restartDelayMs: 50, log: (l) => console.log(l.split('\\n')[0]) });
|
|
137
|
+
stopOnSignals([s]);
|
|
138
|
+
process.exit(await s.done);
|
|
139
|
+
`
|
|
140
|
+
);
|
|
141
|
+
|
|
142
|
+
const proc = Bun.spawn(['bun', launcher], { stdout: 'pipe', stderr: 'pipe' });
|
|
143
|
+
const out = collect();
|
|
144
|
+
void (async () => {
|
|
145
|
+
const reader = proc.stdout.getReader();
|
|
146
|
+
for (;;) {
|
|
147
|
+
const { done, value } = await reader.read();
|
|
148
|
+
if (done) break;
|
|
149
|
+
out.sink(value);
|
|
150
|
+
}
|
|
151
|
+
})();
|
|
152
|
+
|
|
153
|
+
const ups = () => out.lines.filter((line) => line.startsWith('up pid='));
|
|
154
|
+
await waitFor(() => ups().length === 1, 10_000);
|
|
155
|
+
const firstPid = Number(ups()[0].split('=')[1]);
|
|
156
|
+
|
|
157
|
+
process.kill(proc.pid, 'SIGHUP');
|
|
158
|
+
await sleep(300);
|
|
159
|
+
expect(proc.exitCode).toBeNull();
|
|
160
|
+
expect(() => process.kill(firstPid, 0)).not.toThrow(); // server still running
|
|
161
|
+
|
|
162
|
+
process.kill(-firstPid, 'SIGTERM'); // stray signal to the server's group
|
|
163
|
+
await waitFor(() => ups().length === 2, 10_000);
|
|
164
|
+
expect(proc.exitCode).toBeNull();
|
|
165
|
+
|
|
166
|
+
process.kill(proc.pid, 'SIGINT');
|
|
167
|
+
const code = await proc.exited;
|
|
168
|
+
expect(code).toBe(0);
|
|
169
|
+
expect(out.lines.some((line) => line === 'graceful SIGINT')).toBe(true);
|
|
170
|
+
expect(ups()).toHaveLength(2); // not restarted after the requested stop
|
|
171
|
+
}, 30_000);
|
|
172
|
+
});
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Keep a long-running child process (the Clopen server, the dev frontend) up.
|
|
3
|
+
*
|
|
4
|
+
* Shared by the production launcher (bin/clopen.ts) and the dev runner
|
|
5
|
+
* (scripts/dev.ts) so both stop and recover the same way:
|
|
6
|
+
*
|
|
7
|
+
* - **Its own process group** (POSIX). A signal aimed at one process group —
|
|
8
|
+
* by an agent's tooling, a terminal, anything — no longer reaches the
|
|
9
|
+
* others. Windows has no process groups to speak of and `detached` there
|
|
10
|
+
* means a new console, so it is left as is.
|
|
11
|
+
* - **Restarted when it exits without being asked to.** Exit codes cannot tell
|
|
12
|
+
* the difference: a server that received a stray SIGTERM shuts down cleanly
|
|
13
|
+
* and exits 0. What can is whether this supervisor asked it to stop. A child
|
|
14
|
+
* that keeps dying (5 times in 60 s) is given up on instead of looping.
|
|
15
|
+
* - **Stopped on request.** SIGINT/SIGTERM to the supervisor are forwarded to
|
|
16
|
+
* the child's whole group — what a terminal did before the child had a group
|
|
17
|
+
* of its own — then it gets 15 s to finish before SIGKILL. A second signal
|
|
18
|
+
* forces it; a second programmatic `stop()` does not. SIGHUP is ignored,
|
|
19
|
+
* matching the server, which deliberately keeps running when its terminal or
|
|
20
|
+
* SSH session closes; the supervisor stays with it, and writes to a terminal
|
|
21
|
+
* that is gone are dropped instead of crashing.
|
|
22
|
+
* - **Diagnosed.** Each unrequested exit is logged with its code or signal and
|
|
23
|
+
* the processes started shortly before it (pid, ppid, pgid, command), to the
|
|
24
|
+
* console and to `reportFile`, so the next occurrence leaves a trail. The OS
|
|
25
|
+
* never says who sent a signal; what was running when it arrived is the
|
|
26
|
+
* best available evidence.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
import { appendFileSync, mkdirSync } from 'node:fs';
|
|
30
|
+
import { dirname } from 'node:path';
|
|
31
|
+
|
|
32
|
+
type Subprocess = ReturnType<typeof Bun.spawn>;
|
|
33
|
+
|
|
34
|
+
export interface SupervisedProcessOptions {
|
|
35
|
+
/** Short label for log lines, e.g. `server`. */
|
|
36
|
+
name: string;
|
|
37
|
+
cmd: string[];
|
|
38
|
+
cwd?: string;
|
|
39
|
+
env?: Record<string, string | undefined>;
|
|
40
|
+
/** Where each chunk of the child's output goes. Defaults to inheriting. */
|
|
41
|
+
onStdout?: (chunk: Uint8Array) => void;
|
|
42
|
+
onStderr?: (chunk: Uint8Array) => void;
|
|
43
|
+
/** Lines the supervisor itself prints (restarts, diagnostics). */
|
|
44
|
+
log?: (line: string) => void;
|
|
45
|
+
/** Append-only file for unrequested-exit diagnostics. */
|
|
46
|
+
reportFile?: string;
|
|
47
|
+
/** Defaults: 5 restarts per 60 s, 15 s to stop, 1 s first restart delay. */
|
|
48
|
+
maxRestarts?: number;
|
|
49
|
+
restartWindowMs?: number;
|
|
50
|
+
stopTimeoutMs?: number;
|
|
51
|
+
restartDelayMs?: number;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface Supervisor {
|
|
55
|
+
/** Resolves with the child's final exit code once it is stopped or given up on. */
|
|
56
|
+
readonly done: Promise<number>;
|
|
57
|
+
/** Ask the child to stop (forwarding `signal` to its group). Idempotent. */
|
|
58
|
+
stop(signal?: NodeJS.Signals): Promise<number>;
|
|
59
|
+
/** Stop now: SIGKILL the child's group. */
|
|
60
|
+
kill(): Promise<number>;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const IS_WINDOWS = process.platform === 'win32';
|
|
64
|
+
|
|
65
|
+
/** Run `options.cmd` under supervision until it is stopped. */
|
|
66
|
+
export function supervise(options: SupervisedProcessOptions): Supervisor {
|
|
67
|
+
const log = options.log ?? ((line: string) => console.error(line));
|
|
68
|
+
const maxRestarts = options.maxRestarts ?? 5;
|
|
69
|
+
const restartWindowMs = options.restartWindowMs ?? 60_000;
|
|
70
|
+
const stopTimeoutMs = options.stopTimeoutMs ?? 15_000;
|
|
71
|
+
const baseDelayMs = options.restartDelayMs ?? 1000;
|
|
72
|
+
|
|
73
|
+
let child: Subprocess | null = null;
|
|
74
|
+
let stopping = false;
|
|
75
|
+
const restarts: number[] = [];
|
|
76
|
+
let resolveDone!: (code: number) => void;
|
|
77
|
+
const done = new Promise<number>((resolve) => (resolveDone = resolve));
|
|
78
|
+
|
|
79
|
+
const spawnChild = () => {
|
|
80
|
+
child = Bun.spawn(options.cmd, {
|
|
81
|
+
cwd: options.cwd,
|
|
82
|
+
env: options.env as Record<string, string>,
|
|
83
|
+
stdin: 'ignore',
|
|
84
|
+
stdout: options.onStdout ? 'pipe' : 'inherit',
|
|
85
|
+
stderr: options.onStderr ? 'pipe' : 'inherit',
|
|
86
|
+
// Own process group on POSIX — see the module comment.
|
|
87
|
+
...(IS_WINDOWS ? {} : { detached: true })
|
|
88
|
+
} as Parameters<typeof Bun.spawn>[1]) as Subprocess;
|
|
89
|
+
|
|
90
|
+
const current = child;
|
|
91
|
+
if (options.onStdout) void pump(current.stdout as ReadableStream<Uint8Array>, options.onStdout);
|
|
92
|
+
if (options.onStderr) void pump(current.stderr as ReadableStream<Uint8Array>, options.onStderr);
|
|
93
|
+
|
|
94
|
+
void current.exited.then(async (code) => {
|
|
95
|
+
if (child !== current) return;
|
|
96
|
+
const signal = current.signalCode ?? null;
|
|
97
|
+
if (stopping) {
|
|
98
|
+
resolveDone(code ?? 0);
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const now = Date.now();
|
|
103
|
+
while (restarts.length > 0 && now - restarts[0] > restartWindowMs) restarts.shift();
|
|
104
|
+
const description = signal ? `signal ${signal}` : `code ${code}`;
|
|
105
|
+
const report = await diagnose(options.name, description, current.pid);
|
|
106
|
+
log(report);
|
|
107
|
+
if (options.reportFile) writeReport(options.reportFile, report);
|
|
108
|
+
|
|
109
|
+
if (restarts.length >= maxRestarts) {
|
|
110
|
+
log(`[${options.name}] exited ${restarts.length + 1} times within ${restartWindowMs / 1000}s — not restarting.`);
|
|
111
|
+
resolveDone(code ?? 1);
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
restarts.push(now);
|
|
115
|
+
const delay = Math.min(baseDelayMs * 2 ** (restarts.length - 1), 10_000);
|
|
116
|
+
log(`[${options.name}] stopped unexpectedly (${description}); restarting in ${delay / 1000}s…`);
|
|
117
|
+
setTimeout(() => {
|
|
118
|
+
if (!stopping) spawnChild();
|
|
119
|
+
}, delay);
|
|
120
|
+
});
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
const signalGroup = (signal: NodeJS.Signals) => {
|
|
124
|
+
const pid = child?.pid;
|
|
125
|
+
if (!pid || child?.exitCode !== null) return;
|
|
126
|
+
try {
|
|
127
|
+
// The whole group — the child and whatever it started — like a terminal would.
|
|
128
|
+
if (IS_WINDOWS) process.kill(pid, signal);
|
|
129
|
+
else process.kill(-pid, signal);
|
|
130
|
+
} catch {
|
|
131
|
+
try {
|
|
132
|
+
process.kill(pid, signal);
|
|
133
|
+
} catch {
|
|
134
|
+
// Already gone.
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
const stop = (signal: NodeJS.Signals = 'SIGTERM'): Promise<number> => {
|
|
140
|
+
if (stopping) return done;
|
|
141
|
+
stopping = true;
|
|
142
|
+
if (!child || child.exitCode !== null) {
|
|
143
|
+
resolveDone(child?.exitCode ?? 0);
|
|
144
|
+
} else {
|
|
145
|
+
// On Windows the child shares the console, so Ctrl+C already reached it;
|
|
146
|
+
// forwarding would terminate it outright instead of letting it shut down.
|
|
147
|
+
if (!(IS_WINDOWS && signal === 'SIGINT')) signalGroup(signal);
|
|
148
|
+
const timer = setTimeout(() => signalGroup('SIGKILL'), stopTimeoutMs);
|
|
149
|
+
timer.unref?.();
|
|
150
|
+
void done.then(() => clearTimeout(timer));
|
|
151
|
+
}
|
|
152
|
+
return done;
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
const kill = (): Promise<number> => {
|
|
156
|
+
void stop('SIGKILL');
|
|
157
|
+
signalGroup('SIGKILL');
|
|
158
|
+
return done;
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
spawnChild();
|
|
162
|
+
return { done, stop, kill };
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Forward termination signals to a set of supervisors and exit once they are
|
|
167
|
+
* all down, with the first non-zero code. Returns a function that stops them
|
|
168
|
+
* the same way (for callers that end on their own terms).
|
|
169
|
+
*/
|
|
170
|
+
export function stopOnSignals(supervisors: Supervisor[]): (signal?: NodeJS.Signals) => Promise<number> {
|
|
171
|
+
const stopAll = async (signal: NodeJS.Signals = 'SIGTERM') => {
|
|
172
|
+
const codes = await Promise.all(supervisors.map((s) => s.stop(signal)));
|
|
173
|
+
return codes.find((code) => code !== 0) ?? 0;
|
|
174
|
+
};
|
|
175
|
+
let received = 0;
|
|
176
|
+
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
|
|
177
|
+
process.on(signal, () => {
|
|
178
|
+
received++;
|
|
179
|
+
// A second Ctrl+C means "stop waiting".
|
|
180
|
+
if (received > 1) {
|
|
181
|
+
for (const supervisor of supervisors) void supervisor.kill();
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
void stopAll(signal).then((code) => process.exit(code));
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
// The terminal closed: keep supervising (the server keeps running too).
|
|
188
|
+
process.on('SIGHUP', () => {});
|
|
189
|
+
for (const stream of [process.stdout, process.stderr]) {
|
|
190
|
+
stream.on('error', () => {
|
|
191
|
+
// EIO/EPIPE once the terminal is gone — nothing left to write to.
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
return stopAll;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
async function pump(stream: ReadableStream<Uint8Array>, sink: (chunk: Uint8Array) => void): Promise<void> {
|
|
198
|
+
const reader = stream.getReader();
|
|
199
|
+
try {
|
|
200
|
+
for (;;) {
|
|
201
|
+
const { done, value } = await reader.read();
|
|
202
|
+
if (done) return;
|
|
203
|
+
if (value) sink(value);
|
|
204
|
+
}
|
|
205
|
+
} catch {
|
|
206
|
+
// The stream closes with the process.
|
|
207
|
+
} finally {
|
|
208
|
+
reader.releaseLock();
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** What was running when a child died — processes started in the last 10 minutes. */
|
|
213
|
+
async function diagnose(name: string, description: string, pid: number): Promise<string> {
|
|
214
|
+
const lines = [`[${name}] pid ${pid} exited without being asked to (${description}) at ${new Date().toISOString()}.`];
|
|
215
|
+
if (IS_WINDOWS) return lines.join('\n');
|
|
216
|
+
try {
|
|
217
|
+
const ps = Bun.spawn(['ps', '-A', '-o', 'pid=,ppid=,pgid=,etime=,command='], { stdout: 'pipe', stderr: 'ignore' });
|
|
218
|
+
const output = await new Response(ps.stdout).text();
|
|
219
|
+
const recent = output
|
|
220
|
+
.split('\n')
|
|
221
|
+
.map((line) => line.trim())
|
|
222
|
+
.filter(Boolean)
|
|
223
|
+
.filter((line) => {
|
|
224
|
+
const etime = line.split(/\s+/)[3] ?? '';
|
|
225
|
+
return elapsedSeconds(etime) <= 600;
|
|
226
|
+
})
|
|
227
|
+
.map((line) => (line.length > 220 ? `${line.slice(0, 220)}…` : line));
|
|
228
|
+
lines.push('Processes started in the last 10 minutes (pid ppid pgid elapsed command):', ...recent.map((line) => ` ${line}`));
|
|
229
|
+
} catch {
|
|
230
|
+
lines.push('(process list unavailable)');
|
|
231
|
+
}
|
|
232
|
+
return lines.join('\n');
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** `ps` elapsed time ([[dd-]hh:]mm:ss) in seconds. */
|
|
236
|
+
export function elapsedSeconds(etime: string): number {
|
|
237
|
+
const [daysPart, clock] = etime.includes('-') ? etime.split('-') : ['0', etime];
|
|
238
|
+
const parts = clock.split(':').map(Number);
|
|
239
|
+
if (parts.some((part) => !Number.isFinite(part))) return Number.POSITIVE_INFINITY;
|
|
240
|
+
const [h, m, s] = parts.length === 3 ? parts : [0, parts[0] ?? 0, parts[1] ?? 0];
|
|
241
|
+
return Number(daysPart) * 86_400 + h * 3600 + m * 60 + s;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function writeReport(file: string, report: string): void {
|
|
245
|
+
try {
|
|
246
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
247
|
+
appendFileSync(file, `${report}\n\n`);
|
|
248
|
+
} catch {
|
|
249
|
+
// A report that cannot be written must not take the supervisor down.
|
|
250
|
+
}
|
|
251
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
|
|
3
|
+
import { decodeChunk, encodeChunk, sliceText } from './ws-chunk';
|
|
4
|
+
|
|
5
|
+
describe('ws chunk format', () => {
|
|
6
|
+
test('round-trips header and slice, including separators-like text in the slice', () => {
|
|
7
|
+
const frame = encodeChunk('7', 'messages:list-1-abc', 2, 5, '{"a":"x:y-z"}');
|
|
8
|
+
expect(decodeChunk(frame)).toEqual({
|
|
9
|
+
streamId: '7',
|
|
10
|
+
requestId: 'messages:list-1-abc',
|
|
11
|
+
index: 2,
|
|
12
|
+
count: 5,
|
|
13
|
+
slice: '{"a":"x:y-z"}'
|
|
14
|
+
});
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
test('rejects frames that are not chunks or are out of range', () => {
|
|
18
|
+
expect(decodeChunk('{"action":"x"}')).toBeNull();
|
|
19
|
+
expect(decodeChunk(encodeChunk('1', 'r', 5, 5, 'x'))).toBeNull();
|
|
20
|
+
expect(decodeChunk('\u0001broken')).toBeNull();
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
test('never splits a surrogate pair and reassembles to the original', () => {
|
|
24
|
+
const text = 'ab😀'.repeat(1000);
|
|
25
|
+
const slices = sliceText(text, 7);
|
|
26
|
+
for (const slice of slices) {
|
|
27
|
+
const last = slice.charCodeAt(slice.length - 1);
|
|
28
|
+
expect(last >= 0xd800 && last <= 0xdbff).toBe(false);
|
|
29
|
+
expect(slice.length).toBeLessThanOrEqual(7);
|
|
30
|
+
}
|
|
31
|
+
expect(slices.join('')).toBe(text);
|
|
32
|
+
});
|
|
33
|
+
});
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wire format of a chunked request-response reply — shared by the server that
|
|
3
|
+
* cuts it (backend/utils/ws-wire.ts) and the client that reassembles it
|
|
4
|
+
* (shared/utils/ws-client.ts), so the two cannot drift.
|
|
5
|
+
*
|
|
6
|
+
* `\u0001<streamId>\u0002<requestId>\u0002<index>\u0002<count>\u0002<text slice>`
|
|
7
|
+
*
|
|
8
|
+
* `streamId` is unique per reply. A read that was re-sent can be answered
|
|
9
|
+
* twice under one requestId, and the two replies must not be stitched into
|
|
10
|
+
* each other; the second one to complete is ignored like any duplicate reply.
|
|
11
|
+
*
|
|
12
|
+
* JSON frames always start with `{`, so a leading control character cannot be
|
|
13
|
+
* mistaken for one, and the slice is raw text — not re-escaped inside another
|
|
14
|
+
* JSON string, which would grow every quote and backslash.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
export const CHUNK_MARKER = '\u0001';
|
|
18
|
+
export const CHUNK_MARKER_CODE = 1;
|
|
19
|
+
export const CHUNK_SEPARATOR = '\u0002';
|
|
20
|
+
|
|
21
|
+
export interface Chunk {
|
|
22
|
+
streamId: string;
|
|
23
|
+
requestId: string;
|
|
24
|
+
index: number;
|
|
25
|
+
count: number;
|
|
26
|
+
slice: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function encodeChunk(streamId: string, requestId: string, index: number, count: number, slice: string): string {
|
|
30
|
+
return [CHUNK_MARKER + streamId, requestId, index, count, slice].join(CHUNK_SEPARATOR);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function decodeChunk(frame: string): Chunk | null {
|
|
34
|
+
if (frame.charCodeAt(0) !== CHUNK_MARKER_CODE) return null;
|
|
35
|
+
const cuts: number[] = [];
|
|
36
|
+
let from = 0;
|
|
37
|
+
for (let i = 0; i < 4; i++) {
|
|
38
|
+
const at = frame.indexOf(CHUNK_SEPARATOR, from);
|
|
39
|
+
if (at < 0) return null;
|
|
40
|
+
cuts.push(at);
|
|
41
|
+
from = at + 1;
|
|
42
|
+
}
|
|
43
|
+
const index = Number(frame.slice(cuts[1] + 1, cuts[2]));
|
|
44
|
+
const count = Number(frame.slice(cuts[2] + 1, cuts[3]));
|
|
45
|
+
if (!Number.isInteger(index) || !Number.isInteger(count) || index < 0 || index >= count) return null;
|
|
46
|
+
return {
|
|
47
|
+
streamId: frame.slice(1, cuts[0]),
|
|
48
|
+
requestId: frame.slice(cuts[0] + 1, cuts[1]),
|
|
49
|
+
index,
|
|
50
|
+
count,
|
|
51
|
+
slice: frame.slice(cuts[3] + 1)
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Cut text into pieces of at most `size` UTF-16 units without splitting a
|
|
57
|
+
* surrogate pair — half of one would be replaced on the wire and corrupt the
|
|
58
|
+
* reassembled JSON.
|
|
59
|
+
*/
|
|
60
|
+
export function sliceText(text: string, size: number): string[] {
|
|
61
|
+
const slices: string[] = [];
|
|
62
|
+
let start = 0;
|
|
63
|
+
while (start < text.length) {
|
|
64
|
+
let end = Math.min(start + size, text.length);
|
|
65
|
+
if (end < text.length) {
|
|
66
|
+
const code = text.charCodeAt(end - 1);
|
|
67
|
+
if (code >= 0xd800 && code <= 0xdbff) end--;
|
|
68
|
+
}
|
|
69
|
+
slices.push(text.slice(start, end));
|
|
70
|
+
start = end;
|
|
71
|
+
}
|
|
72
|
+
return slices;
|
|
73
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* End to end: a large request-response reply leaves the server in chunks
|
|
3
|
+
* (backend/utils/ws-wire.ts) and the real client reassembles it into exactly
|
|
4
|
+
* the reply it would have received whole.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { afterEach, expect, test } from 'bun:test';
|
|
8
|
+
|
|
9
|
+
import { WSClient } from './ws-client';
|
|
10
|
+
import { CHUNK_BYTES, sendReply } from '$backend/utils/ws-wire';
|
|
11
|
+
|
|
12
|
+
const servers: Array<{ stop: (force?: boolean) => void }> = [];
|
|
13
|
+
afterEach(() => {
|
|
14
|
+
for (const server of servers.splice(0)) server.stop(true);
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
test('a chunked reply resolves ws.http() with the whole value', async () => {
|
|
18
|
+
const big = { rows: Array.from({ length: 12000 }, (_, i) => ({ id: i, text: `row ${i} — ✓ 😀 "quoted"` })) };
|
|
19
|
+
const server = Bun.serve({
|
|
20
|
+
port: 0,
|
|
21
|
+
fetch(req, srv) {
|
|
22
|
+
return srv.upgrade(req) ? undefined : new Response('no', { status: 400 });
|
|
23
|
+
},
|
|
24
|
+
websocket: {
|
|
25
|
+
async message(ws, raw) {
|
|
26
|
+
const { action, payload } = JSON.parse(String(raw));
|
|
27
|
+
if (action !== 'messages:list') return;
|
|
28
|
+
const reply = JSON.stringify({
|
|
29
|
+
action: 'messages:list:response',
|
|
30
|
+
payload: { success: true, data: big, requestId: payload.requestId }
|
|
31
|
+
});
|
|
32
|
+
expect(reply.length).toBeGreaterThan(CHUNK_BYTES);
|
|
33
|
+
await sendReply(ws, 'messages:list:response', payload.requestId, reply);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
servers.push(server);
|
|
38
|
+
|
|
39
|
+
const client = new WSClient<{ client: any; server: any }>(`ws://localhost:${server.port}`, { autoReconnect: false });
|
|
40
|
+
await client.waitUntilConnected(5000);
|
|
41
|
+
|
|
42
|
+
const data = await client.http('messages:list' as never, {} as never, 10_000);
|
|
43
|
+
expect(data).toEqual(big);
|
|
44
|
+
client.disconnect();
|
|
45
|
+
});
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
12
|
import { debug } from './logger';
|
|
13
|
+
import { CHUNK_MARKER_CODE, decodeChunk } from './ws-chunk';
|
|
13
14
|
|
|
14
15
|
// ============================================================================
|
|
15
16
|
// Singleton Encoders (Performance Optimization)
|
|
@@ -275,6 +276,8 @@ export class WSClient<TAPI extends { client: any; server: any }> {
|
|
|
275
276
|
|
|
276
277
|
/** In-flight HTTP requests, keyed by requestId, for resend-on-reconnect. */
|
|
277
278
|
private pendingHttpRequests = new Map<string, PendingHttpRequest>();
|
|
279
|
+
/** Large replies being reassembled, by reply stream. Dropped with the socket. */
|
|
280
|
+
private chunkAssemblies = new Map<string, { parts: string[]; received: number }>();
|
|
278
281
|
/** Prevents a heal-reconnect stampede when many requests time out at once. */
|
|
279
282
|
private healingReconnect = false;
|
|
280
283
|
|
|
@@ -461,6 +464,9 @@ export class WSClient<TAPI extends { client: any; server: any }> {
|
|
|
461
464
|
debug.log('websocket', 'Disconnected');
|
|
462
465
|
this.isConnected = false;
|
|
463
466
|
this.ws = null;
|
|
467
|
+
// Pieces of a reply cannot be completed on another socket; the request
|
|
468
|
+
// itself is re-sent on reconnect and its reply starts over.
|
|
469
|
+
this.chunkAssemblies.clear();
|
|
464
470
|
|
|
465
471
|
// Auto-reconnect
|
|
466
472
|
if (this.shouldReconnect && this.options.autoReconnect) {
|
|
@@ -482,6 +488,11 @@ export class WSClient<TAPI extends { client: any; server: any }> {
|
|
|
482
488
|
* Handle text/JSON message from server
|
|
483
489
|
*/
|
|
484
490
|
private handleTextMessage(data: string): void {
|
|
491
|
+
if (data.charCodeAt(0) === CHUNK_MARKER_CODE) {
|
|
492
|
+
this.handleChunk(data);
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
|
|
485
496
|
// Check if data looks like binary (not valid JSON start)
|
|
486
497
|
if (data && data.length > 0 && data[0] !== '{' && data[0] !== '[') {
|
|
487
498
|
debug.warn('websocket', `Received non-JSON text data (length: ${data.length}), first char code: ${data.charCodeAt(0)}`);
|
|
@@ -499,6 +510,38 @@ export class WSClient<TAPI extends { client: any; server: any }> {
|
|
|
499
510
|
this.dispatchToListeners(action, payload);
|
|
500
511
|
}
|
|
501
512
|
|
|
513
|
+
/**
|
|
514
|
+
* One piece of a large request-response reply (format: shared/utils/ws-chunk.ts).
|
|
515
|
+
*
|
|
516
|
+
* Each piece is proof the reply is still arriving, so it re-arms that
|
|
517
|
+
* request's timeout — without this a slow link timed a big reply out halfway
|
|
518
|
+
* and re-requested it, downloading it again. The last piece completes the
|
|
519
|
+
* frame, which is then handled exactly like one sent whole.
|
|
520
|
+
*/
|
|
521
|
+
private handleChunk(data: string): void {
|
|
522
|
+
const chunk = decodeChunk(data);
|
|
523
|
+
if (!chunk) {
|
|
524
|
+
debug.warn('websocket', 'Dropping malformed chunk frame');
|
|
525
|
+
return;
|
|
526
|
+
}
|
|
527
|
+
const { streamId, requestId, index, count } = chunk;
|
|
528
|
+
|
|
529
|
+
let assembly = this.chunkAssemblies.get(streamId);
|
|
530
|
+
if (!assembly) {
|
|
531
|
+
assembly = { parts: new Array<string>(count), received: 0 };
|
|
532
|
+
this.chunkAssemblies.set(streamId, assembly);
|
|
533
|
+
}
|
|
534
|
+
if (assembly.parts[index] === undefined) {
|
|
535
|
+
assembly.parts[index] = chunk.slice;
|
|
536
|
+
assembly.received++;
|
|
537
|
+
}
|
|
538
|
+
this.pendingHttpRequests.get(requestId)?.arm();
|
|
539
|
+
|
|
540
|
+
if (assembly.received < count) return;
|
|
541
|
+
this.chunkAssemblies.delete(streamId);
|
|
542
|
+
this.handleTextMessage(assembly.parts.join(''));
|
|
543
|
+
}
|
|
544
|
+
|
|
502
545
|
/**
|
|
503
546
|
* Handle binary message from server
|
|
504
547
|
*/
|