rvlib-shipkit 2.26.0 → 2.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/package.json +1 -1
- package/src/agent-time/diet.ts +77 -0
- package/src/agent-time/family.ts +72 -0
- package/src/agent-time/hooks.ts +6 -4
- package/src/agent-time/limits.ts +44 -0
- package/src/agent-time/live.ts +1 -3
- package/src/agent-time/mask.ts +96 -18
- package/src/agent-time/refused.ts +45 -0
- package/src/agent-time/render.ts +122 -21
- package/src/agent-time/report-cache.ts +57 -0
- package/src/agent-time/report.ts +314 -40
- package/src/agent-time/shape.ts +50 -3
- package/src/agent-time/store.ts +320 -99
- package/src/agent-time/timeline.ts +140 -21
- package/src/agent-time/turns.ts +18 -8
- package/src/annex/offload.ts +17 -6
- package/src/annex/tidy.ts +70 -10
- package/src/asks/ask-after.ts +40 -0
- package/src/asks/asks-queue.ts +205 -47
- package/src/assets/kit-config.ts +7 -3
- package/src/assets/kits/identity-kit.ts +289 -10
- package/src/check.ts +3 -1
- package/src/checks/SK004-gitignore-policy.check.ts +12 -5
- package/src/checks/SK013-one-way-in-policy.check.ts +8 -3
- package/src/checks/SK026-asks-autoclose.check.ts +5 -5
- package/src/checks/SK028-readme.check.ts +7 -66
- package/src/checks/SK030-cache-audit.check.ts +6 -1
- package/src/checks/SK031-trace-audit.check.ts +2 -0
- package/src/checks/SK033-global-contribution.check.ts +3 -1
- package/src/checks/SK035-public-clean.check.ts +2 -2
- package/src/checks/SK043-scratch-on-the-mac.check.ts +59 -4
- package/src/checks/SK047-login-in-description.check.ts +36 -0
- package/src/checks/SK048-one-local-file.check.ts +36 -0
- package/src/cli/cmd_Asks.ts +71 -5
- package/src/cli/cmd_Backup.ts +2 -2
- package/src/cli/cmd_Capacity.ts +2 -2
- package/src/cli/cmd_CrossRepoActivity.ts +5 -4
- package/src/cli/cmd_Db.ts +253 -0
- package/src/cli/cmd_History.ts +212 -0
- package/src/cli/cmd_Home.ts +31 -3
- package/src/cli/cmd_Hq.ts +516 -0
- package/src/cli/cmd_Machines.ts +36 -0
- package/src/cli/cmd_Media.ts +38 -6
- package/src/cli/cmd_Reflect.ts +23 -2
- package/src/cli/cmd_Review.ts +548 -116
- package/src/cli/cmd_Secret.ts +62 -12
- package/src/cli/cmd_Social.ts +83 -1
- package/src/cli/cmd_Space.ts +324 -0
- package/src/cli/cmd_Time.ts +76 -5
- package/src/cli/cmd_Tmp.ts +28 -4
- package/src/cli/cmd_Trailer.ts +14 -10
- package/src/cli/cmd_Urls.ts +56 -0
- package/src/cli/cmd_Vault.ts +583 -0
- package/src/cli/family-help.ts +4 -2
- package/src/cli/family-pages.ts +1 -1
- package/src/cli/registry.ts +24 -3
- package/src/collections/actions.ts +63 -13
- package/src/collections/collection-types.ts +23 -1
- package/src/collections/providers.ts +117 -23
- package/src/collections/review.ts +4 -4
- package/src/contracts/contract-manifests.ts +6 -5
- package/src/contracts/contract-types.ts +6 -4
- package/src/contracts/contracts-engine.ts +11 -0
- package/src/contracts/manifests/chrome-web-store.contract.ts +31 -0
- package/src/core/budget.ts +12 -17
- package/src/core/capacity.ts +27 -18
- package/src/core/check-runner.ts +7 -4
- package/src/core/layout.ts +3 -0
- package/src/core/machine-busy.ts +127 -0
- package/src/core/machine-commit.ts +6 -1
- package/src/core/machine-db.ts +368 -20
- package/src/core/machine-layout.ts +137 -0
- package/src/core/machine-read.ts +81 -0
- package/src/core/migrate-layout.ts +1 -1
- package/src/core/one-way-in-policy.ts +64 -7
- package/src/core/polling-policy.ts +27 -0
- package/src/core/retention.ts +16 -2
- package/src/core/scope.ts +107 -14
- package/src/core/slots.ts +5 -4
- package/src/drill/clean.ts +25 -1
- package/src/drill/run.ts +1 -1
- package/src/drill/seal.ts +27 -4
- package/src/home/activity-shape.ts +2 -0
- package/src/home/activity.ts +66 -3
- package/src/home/app-sign.ts +15 -4
- package/src/home/daemon-jobs.ts +149 -7
- package/src/home/database-projects.ts +111 -0
- package/src/home/database-words.ts +203 -0
- package/src/home/databases.ts +460 -0
- package/src/home/global-units.ts +6 -0
- package/src/home/gui-app/ShipkitGui.swift +122 -1
- package/src/home/gui-app.ts +6 -3
- package/src/home/home-move.ts +514 -0
- package/src/home/home-paths.ts +12 -3
- package/src/home/home-routes.ts +68 -0
- package/src/home/inbox-shape.ts +24 -14
- package/src/home/machine-fold.ts +820 -0
- package/src/home/machine-host.ts +20 -5
- package/src/home/machine-repair.ts +503 -0
- package/src/home/machine-stores.ts +66 -15
- package/src/home/machine-temp.ts +547 -86
- package/src/home/resume.ts +79 -0
- package/src/home/run-daemon.ts +25 -4
- package/src/home/run-pm.ts +18 -5
- package/src/home/serve-daemon.ts +18 -3
- package/src/home/serve-web.ts +175 -7
- package/src/home/space-job.ts +115 -0
- package/src/home/space-page.ts +257 -0
- package/src/home/space-route.ts +167 -0
- package/src/home/space-words.ts +103 -0
- package/src/home/time-page-shape.ts +202 -0
- package/src/home/time-page.ts +64 -0
- package/src/home/vault-page.ts +482 -0
- package/src/home/vault-words.ts +132 -0
- package/src/hooks/leak-guard.ts +40 -13
- package/src/hooks/one-way-in-guard.ts +17 -4
- package/src/hq/cards.ts +581 -0
- package/src/hq/door-route.ts +43 -0
- package/src/hq/door.ts +163 -0
- package/src/hq/files-send.ts +348 -0
- package/src/hq/forgotten-log.ts +35 -0
- package/src/hq/history-check.ts +255 -0
- package/src/hq/history-place.ts +146 -0
- package/src/hq/history-send.ts +487 -0
- package/src/hq/hq-db.ts +99 -0
- package/src/hq/hq-local.ts +469 -0
- package/src/hq/hq-routes.ts +196 -0
- package/src/hq/hq-store.ts +599 -0
- package/src/hq/kinds/ask.ts +147 -0
- package/src/hq/kinds/card-gone.ts +83 -0
- package/src/hq/kinds/card-msg.ts +66 -0
- package/src/hq/kinds/card.ts +99 -0
- package/src/hq/kinds/index.ts +21 -0
- package/src/hq/kinds/kind.ts +126 -0
- package/src/hq/kinds/media.ts +125 -0
- package/src/hq/kinds/prompt.ts +219 -0
- package/src/hq/kinds/reflection.ts +128 -0
- package/src/hq/kinds/report.ts +55 -0
- package/src/hq/kinds/time-day.ts +236 -0
- package/src/hq/ledger.ts +473 -0
- package/src/hq/machine-key.ts +44 -0
- package/src/hq/machine-notes.ts +131 -0
- package/src/hq/outbox.ts +372 -0
- package/src/hq/replica.ts +168 -0
- package/src/hq/repo-id.ts +4 -0
- package/src/hq/report-facts.ts +117 -0
- package/src/hq/report.ts +274 -0
- package/src/hq/switch.ts +151 -0
- package/src/hq/vault-grant.ts +92 -0
- package/src/identities/identities.ts +15 -3
- package/src/identities/steps.ts +31 -0
- package/src/ledger/db.ts +73 -26
- package/src/ledger/gate-checks.ts +6 -2
- package/src/ledger/run-log.ts +11 -3
- package/src/ledger/store.ts +26 -4
- package/src/media-store/backup/daemon.ts +25 -17
- package/src/media-store/backup/kept.ts +241 -0
- package/src/media-store/backup/restore.ts +14 -4
- package/src/media-store/backup/run.ts +11 -11
- package/src/media-store/backup/secret.ts +6 -4
- package/src/media-store/backup/snapshot.ts +4 -2
- package/src/media-store/backup/sources.ts +67 -16
- package/src/media-store/copy/config.ts +77 -0
- package/src/media-store/copy/copy.ts +194 -0
- package/src/media-store/copy/lifecycle.ts +43 -0
- package/src/media-store/copy/night.ts +90 -0
- package/src/media-store/copy/proof.ts +151 -0
- package/src/media-store/copy/snapshot.ts +152 -0
- package/src/media-store/copy/store.ts +62 -0
- package/src/media-store/copy/stream.ts +176 -0
- package/src/media-store/daemon.ts +66 -16
- package/src/media-store/db.ts +22 -11
- package/src/media-store/forget.ts +23 -3
- package/src/media-store/hand.ts +4 -3
- package/src/media-store/hq-find.ts +75 -0
- package/src/media-store/hq-send.ts +277 -0
- package/src/media-store/kind.ts +2 -0
- package/src/media-store/purge.ts +18 -15
- package/src/media-store/put.ts +24 -8
- package/src/media-store/remote.ts +16 -7
- package/src/media-store/space-listing.ts +240 -0
- package/src/media-store/space.ts +40 -21
- package/src/media-store/sync.ts +5 -5
- package/src/media-store/tidy.ts +98 -0
- package/src/media-store/upload.ts +3 -3
- package/src/media-store/webp.ts +66 -0
- package/src/messages/model.ts +16 -7
- package/src/messages/routes.ts +14 -4
- package/src/messages/score.ts +2 -2
- package/src/messages/suggest.ts +96 -0
- package/src/pages/frame-client.ts +10 -0
- package/src/plan/planner.ts +28 -17
- package/src/recordings/media-kind.ts +1 -0
- package/src/recordings/model.ts +1 -1
- package/src/recordings/recorder-app/Capture.swift +9 -7
- package/src/reflect/hq-corpus.ts +56 -0
- package/src/reflect/prompt-corpus.ts +3 -1
- package/src/reflect/transcript.ts +129 -37
- package/src/release/machine-words.ts +67 -0
- package/src/release/public-clean.ts +8 -3
- package/src/releases/from-card.ts +1 -1
- package/src/releases/routes.ts +10 -5
- package/src/releases/store.ts +10 -1
- package/src/repo-config.ts +32 -2
- package/src/review/anim.ts +2 -2
- package/src/review/auto.ts +2 -2
- package/src/review/card-db.ts +244 -0
- package/src/review/card-rows.ts +266 -0
- package/src/review/cells.ts +76 -5
- package/src/review/draft-card.ts +41 -0
- package/src/review/draft-model.ts +78 -0
- package/src/review/format.ts +29 -10
- package/src/review/gone.ts +98 -0
- package/src/review/inbox-hook.ts +4 -4
- package/src/review/marks.ts +1 -1
- package/src/review/media-kind.ts +7 -5
- package/src/review/media-read.ts +9 -7
- package/src/review/media.ts +32 -5
- package/src/review/model.ts +202 -39
- package/src/review/move.ts +491 -0
- package/src/review/notes.ts +12 -20
- package/src/review/previews.ts +15 -19
- package/src/review/project.ts +1 -1
- package/src/review/rev.ts +8 -0
- package/src/review/role.ts +1 -1
- package/src/review/routes.ts +64 -13
- package/src/review/stage-card.ts +8 -4
- package/src/review/stage-routes.ts +1 -1
- package/src/review/store.ts +529 -83
- package/src/review/thread-fold.ts +51 -0
- package/src/review/threads.ts +147 -9
- package/src/review/trailer-auto-mock.ts +63 -0
- package/src/review/trailer-card.ts +4 -4
- package/src/review/trailer-desk.ts +41 -7
- package/src/review/trailer-media.ts +1 -0
- package/src/review/trailer-model.ts +8 -0
- package/src/review/trailer-notes.ts +1 -1
- package/src/review/trailer-routes.ts +9 -1
- package/src/review/unit.ts +6 -6
- package/src/review/watchers.ts +1 -1
- package/src/rules/untrack-generated.ts +92 -8
- package/src/secrets/held.ts +16 -0
- package/src/secrets/keychain.ts +113 -0
- package/src/secrets/list.ts +16 -6
- package/src/secrets/manager.ts +24 -10
- package/src/secrets/read.ts +257 -0
- package/src/secrets/who-reads.ts +49 -0
- package/src/serve/door-forward.ts +268 -0
- package/src/serve/door-names.ts +47 -0
- package/src/serve/embed.ts +1 -1
- package/src/serve/hub-app/activity-view.tsx +56 -32
- package/src/serve/hub-app/activity.css +7 -1
- package/src/serve/hub-app/asks-page.tsx +48 -0
- package/src/serve/hub-app/asks-st.ts +25 -0
- package/src/serve/hub-app/clock-svc.ts +1 -2
- package/src/serve/hub-app/col-card.tsx +64 -13
- package/src/serve/hub-app/col-list-page.tsx +122 -0
- package/src/serve/hub-app/col-list-st.ts +103 -0
- package/src/serve/hub-app/col-tables-view.tsx +10 -41
- package/src/serve/hub-app/col-tables.ts +76 -8
- package/src/serve/hub-app/cols-svc.ts +70 -16
- package/src/serve/hub-app/database-st.ts +260 -0
- package/src/serve/hub-app/database-view.tsx +289 -0
- package/src/serve/hub-app/database.css +32 -0
- package/src/serve/hub-app/entry-bar.css +14 -0
- package/src/serve/hub-app/entry-bar.tsx +33 -0
- package/src/serve/hub-app/entry-pick.ts +31 -0
- package/src/serve/hub-app/floating.tsx +1 -0
- package/src/serve/hub-app/hash-route.ts +11 -1
- package/src/serve/hub-app/header-bar.tsx +14 -18
- package/src/serve/hub-app/home-st.ts +89 -9
- package/src/serve/hub-app/home-strip.css +5 -19
- package/src/serve/hub-app/home-strip.tsx +58 -92
- package/src/serve/hub-app/home.html +7 -0
- package/src/serve/hub-app/hub-app.tsx +31 -142
- package/src/serve/hub-app/hub-types.ts +3 -1
- package/src/serve/hub-app/hub.css +109 -23
- package/src/serve/hub-app/icons.tsx +18 -1
- package/src/serve/hub-app/identities-st.ts +56 -6
- package/src/serve/hub-app/identities-view.tsx +100 -58
- package/src/serve/hub-app/identities.css +17 -15
- package/src/serve/hub-app/identity-address.ts +5 -0
- package/src/serve/hub-app/inbox-st.ts +41 -24
- package/src/serve/hub-app/inbox-view.tsx +37 -41
- package/src/serve/hub-app/inbox.css +2 -5
- package/src/serve/hub-app/index.html +7 -0
- package/src/serve/hub-app/kept-cols.tsx +7 -0
- package/src/serve/hub-app/keys.ts +28 -15
- package/src/serve/hub-app/later.tsx +26 -0
- package/src/serve/hub-app/list-filter.tsx +14 -0
- package/src/serve/hub-app/list-walk.ts +72 -3
- package/src/serve/hub-app/machines-st.ts +251 -0
- package/src/serve/hub-app/machines-view.tsx +224 -0
- package/src/serve/hub-app/machines.css +76 -0
- package/src/serve/hub-app/md-copy.tsx +79 -0
- package/src/serve/hub-app/media-view.tsx +2 -0
- package/src/serve/hub-app/messages/messages-page.tsx +79 -7
- package/src/serve/hub-app/messages/messages-st.ts +99 -3
- package/src/serve/hub-app/messages.css +14 -0
- package/src/serve/hub-app/page-keys.ts +175 -0
- package/src/serve/hub-app/pages-frames.tsx +11 -3
- package/src/serve/hub-app/palette-st.ts +58 -11
- package/src/serve/hub-app/palette-view.tsx +3 -1
- package/src/serve/hub-app/project-list.css +54 -8
- package/src/serve/hub-app/project-list.tsx +128 -59
- package/src/serve/hub-app/projects-svc.ts +78 -7
- package/src/serve/hub-app/reader-chips.tsx +13 -0
- package/src/serve/hub-app/readme-view.tsx +2 -3
- package/src/serve/hub-app/readme.css +27 -5
- package/src/serve/hub-app/reflections-page.tsx +42 -0
- package/src/serve/hub-app/reflections-st.ts +17 -0
- package/src/serve/hub-app/releases/releases-page.tsx +25 -2
- package/src/serve/hub-app/releases/releases-st.ts +1 -1
- package/src/serve/hub-app/repo-sections.ts +9 -5
- package/src/serve/hub-app/repo-st.ts +35 -8
- package/src/serve/hub-app/review/draft-card.tsx +163 -0
- package/src/serve/hub-app/review/kit.tsx +50 -7
- package/src/serve/hub-app/review/note-place.ts +1 -1
- package/src/serve/hub-app/review/review-board.tsx +2 -2
- package/src/serve/hub-app/review/review-cells.tsx +145 -65
- package/src/serve/hub-app/review/review-kit.ts +27 -1
- package/src/serve/hub-app/review/review-list.tsx +68 -30
- package/src/serve/hub-app/review/review-page.tsx +7 -8
- package/src/serve/hub-app/review/review-st.ts +111 -24
- package/src/serve/hub-app/review/review-thread.tsx +49 -19
- package/src/serve/hub-app/review/review-views.tsx +475 -144
- package/src/serve/hub-app/review/thread-control-st.ts +115 -0
- package/src/serve/hub-app/review/thread-control.tsx +74 -0
- package/src/serve/hub-app/review/thread-st.ts +73 -26
- package/src/serve/hub-app/review/trailer-card.tsx +1 -1
- package/src/serve/hub-app/review/trailer-page.tsx +37 -16
- package/src/serve/hub-app/review/trailer-st.ts +41 -7
- package/src/serve/hub-app/review.css +267 -61
- package/src/serve/hub-app/side-lists.ts +72 -0
- package/src/serve/hub-app/sidebar.tsx +6 -3
- package/src/serve/hub-app/site/site-part.tsx +2 -8
- package/src/serve/hub-app/site/site-st.ts +4 -4
- package/src/serve/hub-app/social/comms-page.tsx +20 -5
- package/src/serve/hub-app/social/kit.tsx +30 -4
- package/src/serve/hub-app/social/post-card.tsx +139 -49
- package/src/serve/hub-app/social/serial-writes.ts +13 -0
- package/src/serve/hub-app/social/social-model.ts +11 -0
- package/src/serve/hub-app/social/social-page.tsx +94 -35
- package/src/serve/hub-app/social/social-st.ts +120 -36
- package/src/serve/hub-app/social/stage-popup.tsx +1 -1
- package/src/serve/hub-app/social/stage-st.ts +1 -1
- package/src/serve/hub-app/social/step-layout.ts +1 -1
- package/src/serve/hub-app/social.css +3 -0
- package/src/serve/hub-app/space-st.ts +209 -0
- package/src/serve/hub-app/space-view.tsx +196 -0
- package/src/serve/hub-app/space.css +27 -0
- package/src/serve/hub-app/stores/stores-page.tsx +91 -23
- package/src/serve/hub-app/stores/stores-st.ts +44 -19
- package/src/serve/hub-app/stores.css +6 -1
- package/src/serve/hub-app/theme-st.ts +22 -9
- package/src/serve/hub-app/time-charts.tsx +291 -0
- package/src/serve/hub-app/time-pages.tsx +749 -0
- package/src/serve/hub-app/time-st.ts +162 -0
- package/src/serve/hub-app/time-view.tsx +76 -0
- package/src/serve/hub-app/time.css +138 -0
- package/src/serve/hub-app/tree-build.ts +52 -42
- package/src/serve/hub-app/tree-row.tsx +4 -4
- package/src/serve/hub-app/tree-svc.ts +18 -9
- package/src/serve/hub-app/urls-svc.ts +154 -0
- package/src/serve/hub-app/urls-view.tsx +117 -0
- package/src/serve/hub-app/urls.css +30 -0
- package/src/serve/hub-app/vault-st.ts +127 -0
- package/src/serve/hub-app/vault-view.tsx +154 -0
- package/src/serve/hub-app/vault.css +38 -0
- package/src/serve/hub-app/veille/veille-st.ts +12 -10
- package/src/serve/hub-app/waiting-svc.ts +29 -0
- package/src/serve/hub-app/wikis-view.tsx +2 -2
- package/src/serve/hub-runtime.ts +15 -2
- package/src/serve/project-gutter-route.ts +27 -14
- package/src/serve/project-gutter.ts +25 -12
- package/src/serve/same-origin.ts +10 -0
- package/src/serve/serve-hub.ts +13 -4
- package/src/shipkit-files.ts +16 -2
- package/src/shipkit.ts +1 -1
- package/src/shot/shooter.ts +616 -420
- package/src/shot/shot-ask.ts +246 -155
- package/src/site/desk.ts +2 -2
- package/src/smoke/run-smoke.ts +3 -2
- package/src/social/cover.ts +202 -0
- package/src/social/discord-layout.ts +37 -13
- package/src/social/drafts.ts +3 -0
- package/src/social/load.ts +23 -2
- package/src/social/media-kind.ts +2 -1
- package/src/social/publish/discord.ts +5 -2
- package/src/social/publish/secret.ts +2 -2
- package/src/social/release-stage.ts +28 -13
- package/src/social/routes.ts +26 -1
- package/src/social/stage.ts +1 -1
- package/src/social/stats.ts +12 -9
- package/src/social/strip.ts +4 -1
- package/src/social/thumbnail.ts +255 -0
- package/src/stores/collection.ts +15 -11
- package/src/stores/desk.ts +236 -42
- package/src/stores/model.ts +72 -6
- package/src/stores/routes.ts +37 -12
- package/src/stores/unit.ts +14 -8
- package/src/suite/judge-suites.ts +41 -11
- package/src/suite/select.ts +45 -3
- package/src/suite/suite-cli.ts +16 -10
- package/src/trailer/bed.ts +1 -1
- package/src/trailer/build.ts +134 -21
- package/src/trailer/ffmpeg.ts +7 -0
- package/src/trailer/fonts.ts +3 -2
- package/src/trailer/grammar.ts +201 -2
- package/src/trailer/graph.ts +42 -5
- package/src/trailer/look.ts +21 -0
- package/src/trailer/mock.ts +154 -0
- package/src/trailer/passage.ts +65 -26
- package/src/trailer/score/heard.ts +89 -0
- package/src/trailer/score/sound.ts +14 -8
- package/src/trailer/sound/run.ts +16 -6
- package/src/trailer/stitch.ts +26 -5
- package/src/trailer/titles.ts +82 -19
- package/src/trailer/versions.ts +1 -3
- package/src/trailer/vertical.ts +3 -1
- package/src/urls/frame.ts +195 -0
- package/src/urls/routes.ts +43 -0
- package/src/urls/rows.ts +171 -0
- package/src/urls/unit.ts +73 -0
- package/src/vault/house-keys.ts +42 -0
- package/src/vault/layout.ts +50 -0
- package/src/vault/policy.ts +165 -0
- package/src/vault/vault-audit.ts +276 -0
- package/src/vault/vault-client.ts +40 -0
- package/src/vault/vault-config.ts +159 -0
- package/src/vault/vault-destroy.ts +78 -0
- package/src/vault/vault-handover.ts +305 -0
- package/src/vault/vault-http.ts +352 -0
- package/src/vault/vault-import.ts +208 -0
- package/src/vault/vault-init.ts +328 -0
- package/src/vault/vault-minter.ts +271 -0
- package/src/vault/vault-restore.ts +333 -0
- package/src/vault/vault-serve.ts +342 -0
- package/src/vault/vault-snapshot.ts +281 -0
- package/src/veille/asks.ts +1 -1
- package/src/veille/desk.ts +2 -2
|
@@ -0,0 +1,820 @@
|
|
|
1
|
+
// the fold (`sk db fold`): the media index, the agent time index and the daemon's file, each a file of its own, become
|
|
2
|
+
// tables of the machine db (`media_*`, `time_*`, the daemon's under their own names), the machine's one local file
|
|
3
|
+
// beside the hq. Per store, a mark first (every open
|
|
4
|
+
// of the store refuses while it is there, foldRefusal), a whole copy kept beside it (`<file>.before-fold`), then its
|
|
5
|
+
// file replaced by a text tombstone, so code that predates the fold is refused before a row is copied; the rows come
|
|
6
|
+
// from the file as it was at that moment, in steps of a few ms, every table counted on both sides; the mark goes last.
|
|
7
|
+
// `--back` is the same walk the other way: the rows of the tables, those added since the fold too, into a file of the
|
|
8
|
+
// old shape, which replaces the tombstone, then the tables are dropped.
|
|
9
|
+
// The one constraint a reader breaks first: the mark, the tombstone and a link to the old file (`<file>.fold-src`) say
|
|
10
|
+
// together where a walk stopped, so a fold or a way back killed at any step is finished or cleaned by the next run of
|
|
11
|
+
// either, and the store has one truth at every moment
|
|
12
|
+
import { Database } from 'bun:sqlite'
|
|
13
|
+
import { chmodSync, existsSync, linkSync, lstatSync, renameSync, rmSync, statSync, statfsSync, writeFileSync } from 'fs'
|
|
14
|
+
import { createIndexTables } from '../agent-time/store.ts'
|
|
15
|
+
import { waitRefused, FOLD_AUTO, FOLD_LOCK, foldAutoOn, FOLD_MARK, FOLDED_STORES, forgetStoreHomes, machineFileCreate, ownShape, type FoldedStore, type FoldMark, foldMarkOf, isTombstone, machineDb, machineDbPath, machineRead, oldStorePath, tombstoneText, vacuumSteps, WALK_TOOK, walkBytes } from '../core/machine-db.ts'
|
|
16
|
+
import { createMediaTables } from '../media-store/db.ts'
|
|
17
|
+
import { createDaemonTables, DAEMON_TABLES } from '../hq/outbox.ts'
|
|
18
|
+
|
|
19
|
+
/** where a store's whole copy is kept before its fold */
|
|
20
|
+
export const foldCopy = (old: string): string => `${old}.before-fold`
|
|
21
|
+
/** a second name of the old file while its rows are copied: the file as it was when its tombstone went down */
|
|
22
|
+
export const foldSource = (old: string): string => `${old}.fold-src`
|
|
23
|
+
/** the old file the way back builds, before it replaces the tombstone */
|
|
24
|
+
const backFile = (old: string): string => `${old}.back-tmp`
|
|
25
|
+
|
|
26
|
+
/** each store's tables: its old name, and its prefix in the machine db */
|
|
27
|
+
export const STORES: Record<FoldedStore, { prefix: string; tables: readonly string[]; create: (db: Database) => void }> = {
|
|
28
|
+
'media index': { prefix: 'media_', tables: ['codes', 'items', 'files', 'objects', 'fetched'], create: createMediaTables },
|
|
29
|
+
'agent time index': { prefix: 'time_', tables: ['files', 'calls', 'marks', 'prompts', 'meta', 'hooks', 'bg_ends'], create: createIndexTables },
|
|
30
|
+
'daemon file': { prefix: '', tables: DAEMON_TABLES, create: createDaemonTables },
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** rows one copy step writes: a few ms of the machine db's write lock */
|
|
34
|
+
export const COPY_STEP = 500
|
|
35
|
+
/** a machine db smaller than this turns to incremental auto vacuum by one VACUUM (100 ms on 8 MB) */
|
|
36
|
+
const SWITCH_MAX_BYTES = 64 * 1024 * 1024
|
|
37
|
+
/** the lock of a fold or a way back, a row of the machine db: one at a time on a machine */
|
|
38
|
+
const LOCK = FOLD_LOCK
|
|
39
|
+
|
|
40
|
+
export type FoldStep = 'marked' | 'copy' | 'tombstone' | 'tables' | 'counted'
|
|
41
|
+
export type BackStep = 'marked' | 'built' | 'passed' | 'locked' | 'swapped' | 'renamed' | 'dropped'
|
|
42
|
+
/** `half`: a fold or a way back stopped on the way, its mark still there: the next run of either ends it */
|
|
43
|
+
export type StoreState = { store: FoldedStore; old: string; state: 'own file' | 'folded' | 'half' | 'none'; bytes: number; copy: { path: string; bytes: number } | null; mark: FoldMark | null }
|
|
44
|
+
export type Counted = { table: string; from: number; to: number }
|
|
45
|
+
export type Folded = { store: FoldedStore; done: boolean; why: string; counted: Counted[]; ms: number; heldMs: number; carried: number }
|
|
46
|
+
export type Print = (l: string) => void
|
|
47
|
+
|
|
48
|
+
export const q = (name: string): string => `"${name.replace(/"/g, '""')}"`
|
|
49
|
+
const sizeOf = (p: string): number => {
|
|
50
|
+
try {
|
|
51
|
+
return statSync(p).size
|
|
52
|
+
} catch {
|
|
53
|
+
return 0
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
const there = (p: string): boolean => lstatSync(p, { throwIfNoEntry: false }) != null
|
|
57
|
+
/** a database file gone with its log and shared memory */
|
|
58
|
+
const rmDb = (p: string): void => {
|
|
59
|
+
for (const f of [p, `${p}-wal`, `${p}-shm`]) rmSync(f, { force: true })
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const markOf = foldMarkOf
|
|
63
|
+
const setMark = (store: FoldedStore, way: FoldMark['way']): void => void machineDb((db) => db.query('insert or replace into state (name, value, at) values (?, ?, ?)').run(`${FOLD_MARK}${store}`, JSON.stringify({ way, pid: process.pid, at: Date.now() } satisfies FoldMark), Date.now()))
|
|
64
|
+
const clearMark = (store: FoldedStore): void => void machineDb((db) => db.query('delete from state where name = ?').run(`${FOLD_MARK}${store}`))
|
|
65
|
+
/** a whole walk ended: the mark goes, and the time since it was set is kept for the next refusal's estimate */
|
|
66
|
+
const walkEnded = (store: FoldedStore, bytes: number): void => {
|
|
67
|
+
const mark = markOf(store)
|
|
68
|
+
if (mark != null) machineDb((db) => db.query('insert or replace into state (name, value, at) values (?, ?, ?)').run(`${WALK_TOOK}${store}:${mark.way}`, JSON.stringify({ ms: Date.now() - mark.at, bytes }), Date.now()))
|
|
69
|
+
clearMark(store)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** where each store is now: in its own file, folded (its tombstone, or no file at all), half way, or nowhere */
|
|
73
|
+
export function foldState(): StoreState[] {
|
|
74
|
+
return FOLDED_STORES.map((store) => {
|
|
75
|
+
const old = oldStorePath(store)
|
|
76
|
+
const copy = existsSync(foldCopy(old)) ? { path: foldCopy(old), bytes: sizeOf(foldCopy(old)) } : null
|
|
77
|
+
const mark = markOf(store)
|
|
78
|
+
const state: StoreState['state'] = mark != null ? 'half' : !there(old) ? (copy == null ? 'none' : 'folded') : isTombstone(old) ? 'folded' : 'own file'
|
|
79
|
+
return { store, old, state, bytes: there(old) && !isTombstone(old) ? sizeOf(old) + sizeOf(`${old}-wal`) : 0, copy, mark }
|
|
80
|
+
})
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const alive = (pid: number): boolean => {
|
|
84
|
+
try {
|
|
85
|
+
process.kill(pid, 0)
|
|
86
|
+
return true
|
|
87
|
+
} catch (e) {
|
|
88
|
+
return (e as { code?: string }).code === 'EPERM'
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** the lock taken, or the pid that holds it: a dead holder's lock is taken over */
|
|
93
|
+
export function takeLock(): { ok: true; release: () => void } | { ok: false; pid: number } {
|
|
94
|
+
const held = machineDb((db) =>
|
|
95
|
+
db.transaction(() => {
|
|
96
|
+
const row = db.query('select value from state where name = ?').get(LOCK) as { value: string } | null
|
|
97
|
+
const pid = row == null ? null : (JSON.parse(row.value) as { pid: number }).pid
|
|
98
|
+
if (pid != null && pid !== process.pid && alive(pid)) return pid
|
|
99
|
+
db.query('insert or replace into state (name, value, at) values (?, ?, ?)').run(LOCK, JSON.stringify({ pid: process.pid }), Date.now())
|
|
100
|
+
return null
|
|
101
|
+
}).immediate(),
|
|
102
|
+
)
|
|
103
|
+
if (held != null) return { ok: false, pid: held }
|
|
104
|
+
return { ok: true, release: () => void machineDb((db) => db.query('delete from state where name = ?').run(LOCK)) }
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** the machine db opened for a walk, with the timeout every machine write has */
|
|
108
|
+
export function openHost(): Database {
|
|
109
|
+
const path = machineDbPath()
|
|
110
|
+
// its own tables first, through its own open: a fold on a machine that never opened it makes it as it should be
|
|
111
|
+
machineDb(() => null)
|
|
112
|
+
// it holds prompts and commands now: the owner's only, its log and shared memory too
|
|
113
|
+
for (const f of [path, `${path}-wal`, `${path}-shm`]) try { chmodSync(f, 0o600) } catch { /* not made yet */ }
|
|
114
|
+
const db = new Database(path, { readwrite: true })
|
|
115
|
+
db.exec('pragma busy_timeout = 5000')
|
|
116
|
+
db.exec('pragma synchronous = NORMAL')
|
|
117
|
+
// the unique index of a call's id takes its rows in no order: with sqlite's small default cache a copy step of
|
|
118
|
+
// 2,000 rows held the lock 838 ms on a real sized index; the pages of the indexes stay in memory instead
|
|
119
|
+
db.exec('pragma cache_size = -262144')
|
|
120
|
+
return db
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** the host's free pages given back in steps from now on: one VACUUM, while it is small, turns it to incremental */
|
|
124
|
+
function incrementalHost(db: Database, print: Print): void {
|
|
125
|
+
const mode = Number((db.query('pragma auto_vacuum').get() as { auto_vacuum: number }).auto_vacuum)
|
|
126
|
+
if (mode === 2) return
|
|
127
|
+
const bytes = sizeOf(machineDbPath())
|
|
128
|
+
if (bytes > SWITCH_MAX_BYTES) return void print(`WARN the machine db is ${Math.round(bytes / 1e6)} MB: it keeps its auto vacuum mode, and its free pages are reused, never given back`)
|
|
129
|
+
const t = performance.now()
|
|
130
|
+
db.exec('pragma auto_vacuum = incremental')
|
|
131
|
+
db.exec('vacuum')
|
|
132
|
+
print(`ok: the machine db turned to incremental auto vacuum (${Math.round(performance.now() - t)} ms, ${Math.round(bytes / 1e6)} MB)`)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export type Shape = { rowid: boolean; pk: string[]; cols: string[] }
|
|
136
|
+
export function shapeOf(db: Database, schema: string, table: string): Shape | null {
|
|
137
|
+
const info = db.query(`select name, pk from ${schema}.pragma_table_info(?)`).all(table) as { name: string; pk: number }[]
|
|
138
|
+
if (info.length === 0) return null
|
|
139
|
+
const wr = (db.query(`select wr from ${schema}.pragma_table_list where name = ?`).get(table) as { wr: number } | null)?.wr === 1
|
|
140
|
+
return { rowid: !wr, pk: info.filter((c) => c.pk > 0).sort((a, b) => a.pk - b.pk).map((c) => c.name), cols: info.map((c) => c.name) }
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** one table copied from schema `from` to schema `to` of one connection in steps of `step` rows, each its own
|
|
144
|
+
* transaction: by rowid, kept as it was (an id another table or a cursor names), else by the primary key. The longest
|
|
145
|
+
* step's ms */
|
|
146
|
+
function copyTable(db: Database, src: { schema: string; table: string }, dst: { schema: string; table: string }, step: number): number {
|
|
147
|
+
const s = shapeOf(db, src.schema, src.table)
|
|
148
|
+
const t = shapeOf(db, dst.schema, dst.table)
|
|
149
|
+
if (s == null || t == null) return 0
|
|
150
|
+
const cols = t.cols.filter((c) => s.cols.includes(c))
|
|
151
|
+
const list = cols.map(q).join(', ')
|
|
152
|
+
const keys = s.rowid ? ['rowid'] : s.pk
|
|
153
|
+
const tuple = `(${keys.map(q).join(', ')})`
|
|
154
|
+
const marks = `(${keys.map(() => '?').join(', ')})`
|
|
155
|
+
const into = `${dst.schema}.${q(dst.table)}`
|
|
156
|
+
const head = s.rowid ? `insert into ${into} (rowid, ${list}) select rowid, ${list}` : `insert into ${into} (${list}) select ${list}`
|
|
157
|
+
const from = `${src.schema}.${q(src.table)}`
|
|
158
|
+
let lo: unknown[] | null = null
|
|
159
|
+
let held = 0
|
|
160
|
+
for (;;) {
|
|
161
|
+
const after = lo == null ? '' : `where ${tuple} > ${marks}`
|
|
162
|
+
const hiRow = db.query(`select ${keys.map(q).join(', ')} from ${from} ${after} order by ${keys.map(q).join(', ')} limit 1 offset ${step - 1}`).values(...((lo ?? []) as never[]))[0] as unknown[] | undefined
|
|
163
|
+
const upto = hiRow == null ? '' : `${lo == null ? 'where' : 'and'} ${tuple} <= ${marks}`
|
|
164
|
+
const tt = performance.now()
|
|
165
|
+
const write = db.transaction(() => db.query(`${head} from ${from} ${after} ${upto}`).run(...([...(lo ?? []), ...(hiRow ?? [])] as never[])))
|
|
166
|
+
// into the machine db: its write lock, taken at once; into an attached file (the way back): a deferred one, so the
|
|
167
|
+
// machine db is only read and its writers never wait on the step
|
|
168
|
+
if (dst.schema === 'main') write.immediate()
|
|
169
|
+
else write()
|
|
170
|
+
held = Math.max(held, performance.now() - tt)
|
|
171
|
+
if (hiRow == null) break
|
|
172
|
+
lo = hiRow
|
|
173
|
+
}
|
|
174
|
+
return held
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export const count = (db: Database, schema: string, table: string): number => (db.query(`select count(*) as n from ${schema}.${q(table)}`).get() as { n: number }).n
|
|
178
|
+
|
|
179
|
+
/** a store's tables out of the machine db: emptied in steps (by rowid, or by primary key for a table of none), then
|
|
180
|
+
* dropped, their pages given back in steps */
|
|
181
|
+
export async function dropTables(db: Database, store: FoldedStore): Promise<{ deleteMs: number; dropMs: number; vacuumMs: number }> {
|
|
182
|
+
const { prefix, tables } = STORES[store]
|
|
183
|
+
const held = { deleteMs: 0, dropMs: 0, vacuumMs: 0 }
|
|
184
|
+
const timed = (k: keyof typeof held, f: () => number | void): number | void => {
|
|
185
|
+
const t = performance.now()
|
|
186
|
+
const r = f()
|
|
187
|
+
held[k] = Math.max(held[k], Math.round(performance.now() - t))
|
|
188
|
+
return r
|
|
189
|
+
}
|
|
190
|
+
for (const name of tables.flatMap((t) => [`${prefix}${t}`, `${prefix}${t}${GONE}`])) {
|
|
191
|
+
const s = shapeOf(db, 'main', name)
|
|
192
|
+
if (s == null) continue
|
|
193
|
+
const keys = (s.rowid ? ['rowid'] : s.pk).map(q).join(', ')
|
|
194
|
+
for (;;) if (timed('deleteMs', () => db.transaction(() => db.query(`delete from ${q(name)} where (${keys}) in (select ${keys} from ${q(name)} limit ${DROP_STEP})`).run().changes).immediate()) === 0) break
|
|
195
|
+
timed('dropMs', () => void db.transaction(() => db.exec(`drop table ${q(name)}`)).immediate())
|
|
196
|
+
}
|
|
197
|
+
const v = await vacuumSteps(db)
|
|
198
|
+
if (v !== false) held.vacuumMs = Math.round(v.ms)
|
|
199
|
+
return held
|
|
200
|
+
}
|
|
201
|
+
/** a store's table the way back took away from its writers, still to drop in steps */
|
|
202
|
+
const GONE = '__back'
|
|
203
|
+
/** the keys of the rows written in a store's tables while a way back copies them, logged by triggers on every table
|
|
204
|
+
* whichever connection writes: under the write lock at its end, the way back carries them into its file */
|
|
205
|
+
const LOG = 'db_fold_writes'
|
|
206
|
+
const trigger = (name: string, op: string): string => q(`db_fold_${op}_${name}`)
|
|
207
|
+
const OPS = ['insert', 'update', 'delete'] as const
|
|
208
|
+
/** rows the way back carries under the machine db's write lock at most: about 100 ms of it */
|
|
209
|
+
const CARRY_MAX = 2_000
|
|
210
|
+
|
|
211
|
+
/** a row's key as the log keeps it: its rowid, else its primary key as a json array */
|
|
212
|
+
const keyOf = (s: Shape, row: 'new' | 'old'): string => (s.rowid ? `${row}.rowid` : `json_array(${s.pk.map((c) => `${row}.${q(c)}`).join(', ')})`)
|
|
213
|
+
|
|
214
|
+
/** every write to the store's tables from now on logs the key it wrote, whichever connection makes it */
|
|
215
|
+
function watchWrites(db: Database, store: FoldedStore): void {
|
|
216
|
+
const { prefix, tables } = STORES[store]
|
|
217
|
+
db.transaction(() => {
|
|
218
|
+
db.exec(`create table if not exists ${LOG} (store text not null, tbl text not null, k not null)`)
|
|
219
|
+
db.query(`delete from ${LOG} where store = ?`).run(store)
|
|
220
|
+
for (const t of tables) {
|
|
221
|
+
const name = `${prefix}${t}`
|
|
222
|
+
const sh = shapeOf(db, 'main', name)
|
|
223
|
+
if (sh == null) continue
|
|
224
|
+
const log = (row: 'new' | 'old'): string => `insert into ${LOG} values ('${store.replace(/'/g, "''")}', '${name}', ${keyOf(sh, row)});`
|
|
225
|
+
for (const op of OPS) db.exec(`create trigger if not exists ${trigger(name, op)} after ${op} on ${q(name)} begin ${op === 'insert' ? log('new') : op === 'delete' ? log('old') : log('old') + ' ' + log('new')} end`)
|
|
226
|
+
}
|
|
227
|
+
}).immediate()
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** the logging triggers gone, and the store's log */
|
|
231
|
+
function unwatchWrites(db: Database, store: FoldedStore): void {
|
|
232
|
+
const { prefix, tables } = STORES[store]
|
|
233
|
+
for (const t of tables) for (const op of OPS) db.exec(`drop trigger if exists ${trigger(`${prefix}${t}`, op)}`)
|
|
234
|
+
if (shapeOf(db, 'main', LOG) == null) return
|
|
235
|
+
db.query(`delete from ${LOG} where store = ?`).run(store)
|
|
236
|
+
if (db.query(`select 1 from ${LOG} limit 1`).get() == null) db.exec(`drop table ${LOG}`)
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** the rows the log names, carried from the machine db into the way back's file through its own connection: each key's
|
|
240
|
+
* row as the tables hold it now, or gone. How many; `final`, under the write lock, refuses (a negative count) past
|
|
241
|
+
* CARRY_MAX */
|
|
242
|
+
function carryWrites(db: Database, file: Database, store: FoldedStore, final: boolean): number {
|
|
243
|
+
if (shapeOf(db, 'main', LOG) == null) return 0
|
|
244
|
+
const top = Number((db.query(`select max(rowid) as m from ${LOG} where store = ?`).get(store) as { m: number | null }).m ?? 0)
|
|
245
|
+
const logged = db.query(`select distinct tbl, k from ${LOG} where store = ? and rowid <= ?`).all(store, top) as { tbl: string; k: string | number }[]
|
|
246
|
+
if (final && logged.length > CARRY_MAX) return -logged.length
|
|
247
|
+
const shapes = new Map<string, Shape>()
|
|
248
|
+
file.transaction(() => {
|
|
249
|
+
for (const { tbl, k } of logged) {
|
|
250
|
+
let sh = shapes.get(tbl)
|
|
251
|
+
if (sh == null) {
|
|
252
|
+
sh = shapeOf(db, 'main', tbl)!
|
|
253
|
+
shapes.set(tbl, sh)
|
|
254
|
+
}
|
|
255
|
+
const cols = sh.cols.map(q).join(', ')
|
|
256
|
+
const where = sh.rowid ? 'rowid = ?' : `(${sh.pk.map(q).join(', ')}) = (${sh.pk.map((_, i) => `json_extract(?, '$[${i}]')`).join(', ')})`
|
|
257
|
+
const args = (sh.rowid ? [k] : sh.pk.map(() => k)) as never[]
|
|
258
|
+
const row = db.query(`select ${sh.rowid ? 'rowid, ' : ''}${cols} from main.${q(tbl)} where ${where}`).values(...args)[0]
|
|
259
|
+
file.query(`delete from ${q(tbl)} where ${where}`).run(...args)
|
|
260
|
+
if (row != null) file.query(`insert into ${q(tbl)} (${sh.rowid ? 'rowid, ' : ''}${cols}) values (${row.map(() => '?').join(', ')})`).run(...(row as never[]))
|
|
261
|
+
}
|
|
262
|
+
})()
|
|
263
|
+
// before the lock, a pass reads rows a writer may change again: that write is logged after `top`, the next pass
|
|
264
|
+
// carries it
|
|
265
|
+
if (!final) db.transaction(() => db.query(`delete from ${LOG} where store = ? and rowid <= ?`).run(store, top)).immediate()
|
|
266
|
+
return logged.length
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** whether a way back took the store's tables away under its lock: they wait to drop under other names */
|
|
270
|
+
const tablesGone = (db: Database, store: FoldedStore): boolean => STORES[store].tables.some((t) => shapeOf(db, 'main', `${STORES[store].prefix}${t}${GONE}`) != null)
|
|
271
|
+
|
|
272
|
+
/** the processes that hold a file open, as the system says (lsof): pid and command */
|
|
273
|
+
function holders(path: string): string {
|
|
274
|
+
const r = Bun.spawnSync(['lsof', '-nP', '-Fpc', '--', path], { stdout: 'pipe', stderr: 'ignore' })
|
|
275
|
+
const out: string[] = []
|
|
276
|
+
let pid = ''
|
|
277
|
+
for (const l of r.stdout.toString().split('\n')) {
|
|
278
|
+
if (l.startsWith('p')) pid = l.slice(1)
|
|
279
|
+
else if (l.startsWith('c') && Number(pid) !== process.pid) out.push(`${pid} (${l.slice(1)})`)
|
|
280
|
+
}
|
|
281
|
+
return out.length === 0 ? 'no other process the system names' : out.join(', ')
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** rows one step of a drop deletes: each row leaves every index of its table, so fewer than a copy step */
|
|
285
|
+
const DROP_STEP = 200
|
|
286
|
+
|
|
287
|
+
/** a table's name in a store's own file: the machine db's (a file a way back wrote, its old names only views), else the
|
|
288
|
+
* name of before the fold; null when it has neither */
|
|
289
|
+
function ownName(db: Database, schema: string, prefix: string, t: string): string | null {
|
|
290
|
+
const isTable = (n: string): boolean => db.query(`select 1 from ${schema}.sqlite_master where type = 'table' and name = ?`).get(n) != null
|
|
291
|
+
return isTable(`${prefix}${t}`) ? `${prefix}${t}` : isTable(t) ? t : null
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** a database read write and never made: a read only open of a WAL file with no shared memory beside it fails, and
|
|
295
|
+
* VACUUM INTO opens its target with its source's flags */
|
|
296
|
+
const openOld = (path: string): Database => {
|
|
297
|
+
const db = new Database(path, { readwrite: true, create: false })
|
|
298
|
+
db.exec('pragma busy_timeout = 5000')
|
|
299
|
+
return db
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** the old file of a store replaced by its tombstone, and kept under a second name for its rows: checkpointed first,
|
|
303
|
+
* so its main file holds every row written until now. Its log and shared memory go: a log left beside the tombstone
|
|
304
|
+
* would make a database of it again at its next open */
|
|
305
|
+
function tombstone(store: FoldedStore, old: string, locked?: () => void): void {
|
|
306
|
+
const live = openOld(old)
|
|
307
|
+
try {
|
|
308
|
+
// the log into the file, then its write lock held to the rename: a process that holds its own connection to
|
|
309
|
+
// the old file commits before (into the file the copy reads) or waits, then fails on the moved file; never
|
|
310
|
+
// into a log nobody reads
|
|
311
|
+
for (let tries = 0; ; tries++) {
|
|
312
|
+
live.query('pragma wal_checkpoint(truncate)').all()
|
|
313
|
+
live.exec('begin immediate')
|
|
314
|
+
if (sizeOf(`${old}-wal`) === 0) break
|
|
315
|
+
live.exec('rollback')
|
|
316
|
+
if (tries >= 50) throw new Error(`${old} is written without a pause: its log never empties, nothing moved; stop what writes it, then run sk db fold --go again`)
|
|
317
|
+
}
|
|
318
|
+
try {
|
|
319
|
+
locked?.()
|
|
320
|
+
rmSync(foldSource(old), { force: true })
|
|
321
|
+
linkSync(old, foldSource(old))
|
|
322
|
+
const tmp = `${old}.fold-tmp`
|
|
323
|
+
writeFileSync(tmp, tombstoneText(store, machineDbPath()), { mode: 0o600 })
|
|
324
|
+
renameSync(tmp, old)
|
|
325
|
+
for (const f of [`${old}-wal`, `${old}-shm`]) rmSync(f, { force: true })
|
|
326
|
+
} finally {
|
|
327
|
+
live.exec('rollback')
|
|
328
|
+
}
|
|
329
|
+
} finally {
|
|
330
|
+
live.close()
|
|
331
|
+
}
|
|
332
|
+
if (!isTombstone(old)) throw new Error(`${old} is not the tombstone just written: a process wrote it again, run sk db fold --go again`)
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** what a walk would do, said before it does it: each store, its size, where its copy goes, the room it needs */
|
|
336
|
+
export function foldPlan(): { states: StoreState[]; need: number; free: number } {
|
|
337
|
+
const states = foldState()
|
|
338
|
+
const own = states.filter((s) => s.state === 'own file' || s.state === 'half')
|
|
339
|
+
// its copy, and its rows again in the machine db
|
|
340
|
+
const need = own.reduce((n, s) => n + 2 * s.bytes, 0)
|
|
341
|
+
let free = Number.MAX_SAFE_INTEGER
|
|
342
|
+
try {
|
|
343
|
+
const f = statfsSync(machineDbPath().replace(/\/[^/]+$/, ''))
|
|
344
|
+
free = Number(f.bavail) * Number(f.bsize)
|
|
345
|
+
} catch {
|
|
346
|
+
// a disk that does not say: the copy says it when it fails
|
|
347
|
+
}
|
|
348
|
+
return { states, need, free }
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** the switch of the daemon's fold (hq/switch.ts declares it): on, its default, the daemon folds a store left in its
|
|
352
|
+
* own file; a way back turns it off, so a store sent back stays back, and a fold by hand turns it on again. A machine
|
|
353
|
+
* db that does not read THROWS: read as on or off, it would fold or strand a machine behind its owner */
|
|
354
|
+
export { FOLD_AUTO, foldAutoOn } from '../core/machine-db.ts'
|
|
355
|
+
const FOLD_AUTO_AT = 'db-fold-auto-at'
|
|
356
|
+
export function setFoldAuto(on: boolean): void {
|
|
357
|
+
forgetStoreHomes()
|
|
358
|
+
machineDb((db) =>
|
|
359
|
+
db.transaction(() => {
|
|
360
|
+
const put = db.query('insert or replace into state (name, value, at) values (?, ?, ?)')
|
|
361
|
+
put.run(FOLD_AUTO, JSON.stringify(on), Date.now())
|
|
362
|
+
put.run(FOLD_AUTO_AT, JSON.stringify(Date.now()), Date.now())
|
|
363
|
+
})(),
|
|
364
|
+
)
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** a time as the owner reads it: his machine's own clock */
|
|
368
|
+
export const localTime = (at: number): string => new Date(at).toLocaleString('sv-SE').slice(0, 16)
|
|
369
|
+
|
|
370
|
+
/** where the fold of this machine stands, in words: the switch, each store, the copies */
|
|
371
|
+
export function foldWords(): string[] {
|
|
372
|
+
const on = foldAutoOn()
|
|
373
|
+
const at = machineRead<number>(FOLD_AUTO_AT)
|
|
374
|
+
const states = foldState()
|
|
375
|
+
const out = [on ? 'the automatic fold is on: the daemon folds a store left in its own file' : `the automatic fold is off since ${at == null ? 'a way back' : localTime(at)} (a way back turns it off): a store not folded is read and written in its own file, for as long as you want; sk db fold --go folds them and turns it on`]
|
|
376
|
+
for (const s of states) {
|
|
377
|
+
if (s.state === 'half') out.push(`${s.store}: a ${s.mark?.way === 'back' ? 'way back' : 'fold'} stopped half way: sk db fold ${s.mark?.way === 'back' ? '--back ' : ''}--go ends it`)
|
|
378
|
+
else if (s.state === 'folded') {
|
|
379
|
+
const d = machineRead<{ at: number; rows: number }>(`${DONE}${s.store}`)
|
|
380
|
+
out.push(`${s.store}: folded${d == null ? '' : ` on ${localTime(d.at).slice(0, 10)}, ${d.rows.toLocaleString('en-US')} rows`}${s.copy == null ? '' : `; its copy ${s.copy.path} (${Math.round(s.copy.bytes / 1e6)} MB) keeps the way back (sk db fold --back --go): once sure, sk db fold --rm-copies says what goes, --go deletes, and the way back ends`}`)
|
|
381
|
+
} else if (s.state === 'own file') {
|
|
382
|
+
const hurt = damagedOld(s.store)
|
|
383
|
+
const shape = ownShape(s.store, s.old)
|
|
384
|
+
out.push(hurt != null ? `${s.store}: its own file ${s.old} is damaged (${hurt.what}), not folded; ${damagedHow(s.store, s.old)}` : `${s.store}: its own file ${s.old}${on ? ', the daemon folds it at its next look' : shape === 'old' ? ', in the shape of before the fold, so it is not read: sk db fold --back --go gives it the tables this code reads' : ', read and written there'}${s.copy != null && shape === 'tables' ? `; its copy ${s.copy.path} (${Math.round(s.copy.bytes / 1e6)} MB) is needed no more: sk db fold --rm-copies` : ''}`)
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
return out
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** a store folded: when, and its rows */
|
|
391
|
+
const DONE = 'db-fold-done:'
|
|
392
|
+
/** a store that went back to its file: its fold's record goes with it */
|
|
393
|
+
const forgetDone = (store: FoldedStore): void => void machineDb((d) => d.query('delete from state where name = ?').run(`${DONE}${store}`))
|
|
394
|
+
/** the notice of a fold, written once a machine */
|
|
395
|
+
const NOTICE = 'db-fold-notice'
|
|
396
|
+
|
|
397
|
+
/** the copies the fold kept for the way back, deleted with `go`: the way back ends with them */
|
|
398
|
+
export function rmCopies(o: { go: boolean; print: Print }): { path: string; bytes: number }[] {
|
|
399
|
+
// a folded store's copy keeps the way back; a store back in its own file, whole and in the tables this code reads,
|
|
400
|
+
// needs its copy no more. A store half way, damaged or of the old shape keeps it
|
|
401
|
+
const spare = (s: StoreState): boolean => s.copy != null && (s.state === 'folded' || (s.state === 'own file' && ownShape(s.store, s.old) === 'tables' && oldDamage(s.old) == null))
|
|
402
|
+
const states = foldState().filter(spare)
|
|
403
|
+
for (const s of states) {
|
|
404
|
+
if (o.go) rmSync(s.copy!.path, { force: true })
|
|
405
|
+
o.print(`${o.go ? 'ok: deleted' : 'would delete'} ${s.copy!.path} (${Math.round(s.copy!.bytes / 1e6)} MB)${s.state === 'folded' ? '' : `: the ${s.store} is back in its own file, whole`}`)
|
|
406
|
+
}
|
|
407
|
+
const kept = foldState().filter((s) => s.copy != null && !spare(s))
|
|
408
|
+
for (const s of kept) o.print(`kept ${s.copy!.path}: the ${s.store} is ${s.state === 'half' ? 'half way' : 'not whole in its own file'}`)
|
|
409
|
+
if (states.length === 0 && kept.length === 0) o.print('no copy of a store is left')
|
|
410
|
+
else if (!o.go && states.some((s) => s.state === 'folded')) o.print('dry run: --go deletes them, and sk db fold --back then writes its files from the tables alone')
|
|
411
|
+
else if (!o.go && states.length > 0) o.print('dry run: --go deletes them')
|
|
412
|
+
return states.map((s) => s.copy!)
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/** the notice of the fold for the owner, once a machine: an ask in the house repo, which closes itself once the copies
|
|
416
|
+
* are gone. Null when none is owed */
|
|
417
|
+
export async function foldNotice(root: string): Promise<string | null> {
|
|
418
|
+
const folded = foldState().filter((s) => s.state === 'folded' && s.copy != null)
|
|
419
|
+
if (folded.length === 0 || machineRead(NOTICE) != null) return null
|
|
420
|
+
const { createAsk } = await import('../asks/asks-queue.ts')
|
|
421
|
+
const { afterValue } = await import('../asks/ask-after.ts')
|
|
422
|
+
const { LAYOUT } = await import('../core/layout.ts')
|
|
423
|
+
const { join } = await import('path')
|
|
424
|
+
const { readFileSync } = await import('fs')
|
|
425
|
+
const dir = join(root, LAYOUT.asks)
|
|
426
|
+
const mb = folded.reduce((n, s) => n + s.copy!.bytes, 0) / 1e6
|
|
427
|
+
const key = shortKey()
|
|
428
|
+
// the machine's key in its name and its check: two machines share the house repo, and each closes only its own
|
|
429
|
+
const file = createAsk(dir, `the machine db of machine ${key} folded: delete its ${Math.round(mb)} MB of copies once sure`, {
|
|
430
|
+
why: `${folded.map((s) => s.store).join(', ')} ${folded.length === 1 ? 'is' : 'are'} tables of the machine db now; the copies of their old files keep the way back`,
|
|
431
|
+
blocks: 'tools/shipkit (its page home.md, One local file)',
|
|
432
|
+
check: `sk db fold --notice-done ${key}`,
|
|
433
|
+
// two days to trust the fold before the copies go: out of the owner's way until then
|
|
434
|
+
after: afterValue('2d', new Date()),
|
|
435
|
+
})
|
|
436
|
+
const p = join(dir, file)
|
|
437
|
+
const text = readFileSync(p, 'utf8')
|
|
438
|
+
// the ask contract: one line a paragraph or a bullet (RV029)
|
|
439
|
+
const body = [foldWords().filter((l) => !l.startsWith('the automatic fold')).map((l) => `- ${l}`).join('\n'), `## 1. Look`, 'On the machine whose key is ' + key + ' (`sk db fold` prints it), run `sk time --since 1d` and `sk db`: the agent time index answers, the machine db has three parts.', '## 2. Delete the copies', 'Run `sk db fold --rm-copies` (it says what goes), then `sk db fold --rm-copies --go`. The way back (`sk db fold --back --go`) ends with them.', ''].join('\n\n')
|
|
440
|
+
writeFileSync(p, text.replace(/<!-- one "## N\." section per step[\s\S]*?(?=\*\*Answer\*\*)/, body))
|
|
441
|
+
machineDb((db) => db.query('insert or replace into state (name, value, at) values (?, ?, ?)').run(NOTICE, JSON.stringify({ at: Date.now(), file }), Date.now()))
|
|
442
|
+
return file
|
|
443
|
+
}
|
|
444
|
+
/** this machine's key, short: what names it in its notice */
|
|
445
|
+
export const shortKey = (): string => {
|
|
446
|
+
const { machineKey } = require('../hq/machine-key.ts') as typeof import('../hq/machine-key.ts')
|
|
447
|
+
return machineKey().slice(0, 8)
|
|
448
|
+
}
|
|
449
|
+
/** the notice's check: true on the machine of that key once no copy of an old file is left; never on another machine */
|
|
450
|
+
export const noticeDone = (key: string): boolean => key === shortKey() && FOLDED_STORES.every((s) => !existsSync(foldCopy(oldStorePath(s))))
|
|
451
|
+
|
|
452
|
+
export const noticeOwed = (): boolean => machineRead(NOTICE) == null && foldState().some((s) => s.state === 'folded' && s.copy != null)
|
|
453
|
+
|
|
454
|
+
/** a store whose old file the fold found damaged: its file's stamp then, so the daemon checks it again only once it moved */
|
|
455
|
+
const DAMAGED = 'db-fold-damaged:'
|
|
456
|
+
const stampOf = (p: string): string => {
|
|
457
|
+
try {
|
|
458
|
+
const st = statSync(p)
|
|
459
|
+
const w = lstatSync(`${p}-wal`, { throwIfNoEntry: false })
|
|
460
|
+
return `${st.size}:${st.mtimeMs}:${w?.size ?? 0}:${w?.mtimeMs ?? 0}`
|
|
461
|
+
} catch {
|
|
462
|
+
return ''
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
/** what sqlite's check finds in an old file, null when it reads whole */
|
|
466
|
+
export function oldDamage(old: string): string | null {
|
|
467
|
+
let db: Database | null = null
|
|
468
|
+
try {
|
|
469
|
+
db = openOld(old)
|
|
470
|
+
const lines = (db.query('pragma quick_check(5)').all() as { quick_check: string }[]).flatMap((r) => r.quick_check.split('\n')).filter((l) => l !== 'ok' && !l.startsWith('*** in database'))
|
|
471
|
+
return lines.length === 0 ? null : lines.slice(0, 2).join('; ').slice(0, 200)
|
|
472
|
+
} catch (e) {
|
|
473
|
+
return (e as Error).message
|
|
474
|
+
} finally {
|
|
475
|
+
db?.close()
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
/** what the owner does with a damaged old file */
|
|
479
|
+
const damagedHow = (store: FoldedStore, old: string): string =>
|
|
480
|
+
store === 'media index'
|
|
481
|
+
? `the media index builds again from the files and the Space: mv ${old} ${old}.damaged, then sk db fold --go makes its tables anew`
|
|
482
|
+
: `sk db repair time says what a repair keeps, --go writes every row that reads into a new file in its place, then the fold takes it`
|
|
483
|
+
/** the damage a fold found in a store's old file, forgotten once the file was written again */
|
|
484
|
+
export const forgetDamage = (store: FoldedStore): void => void machineDb((db) => db.query('delete from state where name = ?').run(`${DAMAGED}${store}`))
|
|
485
|
+
/** the damaged old file a fold found, while that file has not moved since */
|
|
486
|
+
export function damagedOld(store: FoldedStore): { what: string; at: number } | null {
|
|
487
|
+
const row = machineDb((db) => db.query('select value from state where name = ?').get(`${DAMAGED}${store}`) as { value: string } | null)
|
|
488
|
+
if (row == null) return null
|
|
489
|
+
const v = JSON.parse(row.value) as { stamp: string; what: string; at: number }
|
|
490
|
+
return v.stamp === stampOf(oldStorePath(store)) ? { what: v.what, at: v.at } : null
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/** a store left to fold: in its own file, or a walk stopped half way, and the switch on. The disk too small says it,
|
|
494
|
+
* and waits */
|
|
495
|
+
export function foldDue(): boolean {
|
|
496
|
+
if (noticeOwed()) return true
|
|
497
|
+
if (!foldAutoOn()) return false
|
|
498
|
+
const plan = foldPlan()
|
|
499
|
+
if (!plan.states.some((s) => (s.state === 'own file' && damagedOld(s.store) == null) || (s.state === 'half' && s.mark?.way === 'go'))) return false
|
|
500
|
+
if (plan.need > plan.free) {
|
|
501
|
+
process.stderr.write(`WARN db fold: it needs ${Math.round(plan.need / 1e6)} MB and the disk has ${Math.round(plan.free / 1e6)} MB free: the media store sends nothing to the Space until sk db fold --go runs\n`)
|
|
502
|
+
return false
|
|
503
|
+
}
|
|
504
|
+
return true
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
type FoldOpts = { print: Print; step?: number; byHand?: boolean; stopAfter?: (store: FoldedStore, step: FoldStep) => boolean; locked?: (store: FoldedStore) => void }
|
|
508
|
+
|
|
509
|
+
/** every store not folded yet folded into the machine db, one after the other; a store a walk left half way is ended
|
|
510
|
+
* first. `stopAfter`: a test's kill at a step */
|
|
511
|
+
export async function fold(o: FoldOpts = { print: () => {} }): Promise<Folded[]> {
|
|
512
|
+
const plan = foldPlan()
|
|
513
|
+
if (plan.need > plan.free) throw new Error(`the fold needs ${Math.round(plan.need / 1e6)} MB and the disk has ${Math.round(plan.free / 1e6)} MB free`)
|
|
514
|
+
const lock = takeLock()
|
|
515
|
+
if (!lock.ok) throw new Error(`a fold runs (pid ${lock.pid}): one at a time`)
|
|
516
|
+
const host = openHost()
|
|
517
|
+
const out: Folded[] = []
|
|
518
|
+
try {
|
|
519
|
+
// a fold the owner typed is his word again for the daemon's
|
|
520
|
+
if (o.byHand === true) setFoldAuto(true)
|
|
521
|
+
incrementalHost(host, o.print)
|
|
522
|
+
for (const s of plan.states) out.push(await foldOne(host, s, o))
|
|
523
|
+
} finally {
|
|
524
|
+
host.close()
|
|
525
|
+
lock.release()
|
|
526
|
+
forgetStoreHomes()
|
|
527
|
+
}
|
|
528
|
+
return out
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
async function foldOne(db: Database, s: StoreState, o: FoldOpts): Promise<Folded> {
|
|
532
|
+
const t0 = performance.now()
|
|
533
|
+
const { store, old } = s
|
|
534
|
+
const { prefix, tables, create } = STORES[store]
|
|
535
|
+
const bytes = walkBytes(old)
|
|
536
|
+
const stop = (step: FoldStep): void => {
|
|
537
|
+
if (o.stopAfter?.(store, step) === true) throw new Error(`stopped after ${step} of the ${store}`)
|
|
538
|
+
}
|
|
539
|
+
const done = (why: string, more: Partial<Folded> = {}): Folded => ({ store, done: false, why, counted: [], ms: Math.round(performance.now() - t0), heldMs: 0, carried: 0, ...more })
|
|
540
|
+
const tomb = there(old) && isTombstone(old)
|
|
541
|
+
// a fold stopped once its rows were copied and its mark gone: only the second name of the old file is left
|
|
542
|
+
if (s.state === 'folded') {
|
|
543
|
+
rmDb(foldSource(old))
|
|
544
|
+
return done('folded already')
|
|
545
|
+
}
|
|
546
|
+
if (s.state === 'none') return done('no file to fold')
|
|
547
|
+
// half way, tombstone down, no second name: a way back stopped before its rename, the tables are the whole store
|
|
548
|
+
if (s.state === 'half' && tomb && !there(foldSource(old))) {
|
|
549
|
+
// a way back stopped after its swap: the tables under their names again, the file it made dropped
|
|
550
|
+
if (tablesGone(db, store))
|
|
551
|
+
db.transaction(() => {
|
|
552
|
+
for (const t of tables) if (shapeOf(db, 'main', `${prefix}${t}${GONE}`) != null) db.exec(`alter table ${q(`${prefix}${t}${GONE}`)} rename to ${q(`${prefix}${t}`)}`)
|
|
553
|
+
}).immediate()
|
|
554
|
+
rmDb(backFile(old))
|
|
555
|
+
unwatchWrites(db, store)
|
|
556
|
+
clearMark(store)
|
|
557
|
+
o.print(`ok: the ${store}: a way back stopped before its rename; the store stays in its tables`)
|
|
558
|
+
return done('folded, a way back undone')
|
|
559
|
+
}
|
|
560
|
+
// a store of rows in the machine db that no walk of its own wrote is another store's: never dropped
|
|
561
|
+
const held = tables.map((t) => `${prefix}${t}`).filter((t) => shapeOf(db, 'main', t) != null && count(db, 'main', t) > 0)
|
|
562
|
+
if (s.state === 'own file' && held.length > 0) throw new Error(`the machine db holds rows of the ${store} already (${held.join(', ')}), and ${old} is a store of its own again: an older process made it after a fold. Nothing is dropped; look at both before a fold`)
|
|
563
|
+
let before: Record<string, number> = {}
|
|
564
|
+
if (!tomb) {
|
|
565
|
+
// a damaged old file is never folded: refused before any mark, left exactly as it was, the other store goes on
|
|
566
|
+
const hurt = oldDamage(old)
|
|
567
|
+
if (hurt != null) {
|
|
568
|
+
if (s.mark != null) clearMark(store)
|
|
569
|
+
for (const f of [`${foldCopy(old)}.tmp`, `${foldCopy(old)}.tmp-journal`]) rmSync(f, { force: true })
|
|
570
|
+
machineDb((db) => db.query('insert or replace into state (name, value, at) values (?, ?, ?)').run(`${DAMAGED}${store}`, JSON.stringify({ stamp: stampOf(old), what: hurt, at: Date.now() }), Date.now()))
|
|
571
|
+
o.print(`FAIL: the ${store}: ${old} is damaged (${hurt}): not folded, the file left as it was; ${damagedHow(store, old)}`)
|
|
572
|
+
return done(`damaged: ${hurt}`)
|
|
573
|
+
}
|
|
574
|
+
// the old file is the store's one truth: the mark, its copy, then its tombstone, before any row is copied
|
|
575
|
+
setMark(store, 'go')
|
|
576
|
+
stop('marked')
|
|
577
|
+
const copy = foldCopy(old)
|
|
578
|
+
const tmp = `${copy}.tmp`
|
|
579
|
+
for (const f of [tmp, `${tmp}-journal`, `${tmp}-wal`]) rmSync(f, { force: true })
|
|
580
|
+
const live = openOld(old)
|
|
581
|
+
try {
|
|
582
|
+
live.exec(`vacuum into '${tmp.replace(/'/g, "''")}'`)
|
|
583
|
+
} finally {
|
|
584
|
+
live.close()
|
|
585
|
+
}
|
|
586
|
+
chmodSync(tmp, 0o600)
|
|
587
|
+
renameSync(tmp, copy)
|
|
588
|
+
const c = openOld(copy)
|
|
589
|
+
before = Object.fromEntries(tables.map((t) => [t, ownName(c, 'main', prefix, t)]).filter(([, n]) => n != null).map(([t, n]) => [t, count(c, 'main', n!)]))
|
|
590
|
+
c.close()
|
|
591
|
+
o.print(`ok: the ${store}: its copy ${copy} (${Math.round(sizeOf(copy) / 1e6)} MB)`)
|
|
592
|
+
stop('copy')
|
|
593
|
+
tombstone(store, old, () => o.locked?.(store))
|
|
594
|
+
o.print(`ok: the ${store}: ${old} is a tombstone now; its rows come from it as it was then`)
|
|
595
|
+
stop('tombstone')
|
|
596
|
+
}
|
|
597
|
+
// the rows of the old file as its tombstone found it, into tables made again from nothing
|
|
598
|
+
const src = foldSource(old)
|
|
599
|
+
await dropTables(db, store)
|
|
600
|
+
create(db)
|
|
601
|
+
db.query('attach database ? as src').run(`file:${encodeURI(src)}?mode=rw`)
|
|
602
|
+
let heldMs = 0
|
|
603
|
+
const counted: Counted[] = []
|
|
604
|
+
try {
|
|
605
|
+
for (const t of tables) {
|
|
606
|
+
const n = ownName(db, 'src', prefix, t)
|
|
607
|
+
if (n != null) heldMs = Math.max(heldMs, copyTable(db, { schema: 'src', table: n }, { schema: 'main', table: `${prefix}${t}` }, o.step ?? COPY_STEP))
|
|
608
|
+
}
|
|
609
|
+
stop('tables')
|
|
610
|
+
for (const t of tables) {
|
|
611
|
+
const n = ownName(db, 'src', prefix, t)
|
|
612
|
+
if (n != null) counted.push({ table: `${prefix}${t}`, from: count(db, 'src', n), to: count(db, 'main', `${prefix}${t}`) })
|
|
613
|
+
}
|
|
614
|
+
} finally {
|
|
615
|
+
db.exec('detach database src')
|
|
616
|
+
}
|
|
617
|
+
const off = counted.filter((c) => c.from !== c.to)
|
|
618
|
+
if (off.length > 0) throw new Error(`the ${store}'s rows do not match its old file (${off.map((c) => `${c.table} ${c.from} → ${c.to}`).join(', ')}): its mark stays, so nothing reads the tables; run sk db fold --go again`)
|
|
619
|
+
stop('counted')
|
|
620
|
+
// the rows an older process wrote between the copy and the tombstone: carried, since they come from the old file
|
|
621
|
+
const carried = counted.reduce((n, c) => n + Math.max(0, c.from - (before[c.table.slice(prefix.length)] ?? c.from)), 0)
|
|
622
|
+
walkEnded(store, bytes)
|
|
623
|
+
rmDb(src)
|
|
624
|
+
o.print(`ok: the ${store}: ${counted.map((c) => `${c.table} ${c.to.toLocaleString('en-US')}`).join(', ')} rows, as in its old file (the longest step ${Math.round(heldMs)} ms)${carried > 0 ? `; ${carried} of them written while its copy was made` : ''}`)
|
|
625
|
+
machineDb((db) => db.query('insert or replace into state (name, value, at) values (?, ?, ?)').run(`${DONE}${store}`, JSON.stringify({ at: Date.now(), rows: counted.reduce((n, c) => n + c.to, 0) }), Date.now()))
|
|
626
|
+
return { store, done: true, why: 'folded', counted, ms: Math.round(performance.now() - t0), heldMs: Math.round(heldMs), carried }
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
type BackOpts = { print: Print; step?: number; stopAfter?: (store: FoldedStore, step: BackStep) => boolean }
|
|
630
|
+
|
|
631
|
+
/** the way back: each folded store's rows, those added since the fold too, into a file of its old shape that replaces
|
|
632
|
+
* its tombstone, then its tables dropped. Its old shape is its copy's (`<file>.before-fold`). A store a walk left half
|
|
633
|
+
* way is ended first */
|
|
634
|
+
export async function unfold(o: BackOpts = { print: () => {} }): Promise<{ store: FoldedStore; back: boolean; why: string; rows: number }[]> {
|
|
635
|
+
const lock = takeLock()
|
|
636
|
+
if (!lock.ok) throw new Error(`a fold runs (pid ${lock.pid}): one at a time`)
|
|
637
|
+
const db = openHost()
|
|
638
|
+
const out: { store: FoldedStore; back: boolean; why: string; rows: number }[] = []
|
|
639
|
+
try {
|
|
640
|
+
// first: a way back stays back, the daemon never folds again behind it
|
|
641
|
+
setFoldAuto(false)
|
|
642
|
+
for (const s of foldState()) out.push(await unfoldOne(db, s, o))
|
|
643
|
+
} finally {
|
|
644
|
+
db.close()
|
|
645
|
+
lock.release()
|
|
646
|
+
forgetStoreHomes()
|
|
647
|
+
}
|
|
648
|
+
for (const r of out) if (!r.back) o.print(`${r.store}: nothing to put back: ${r.why}`)
|
|
649
|
+
return out
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
async function unfoldOne(db: Database, s: StoreState, o: BackOpts): Promise<{ store: FoldedStore; back: boolean; why: string; rows: number }> {
|
|
653
|
+
const { store, old } = s
|
|
654
|
+
const { prefix, tables } = STORES[store]
|
|
655
|
+
const stop = (step: BackStep): void => {
|
|
656
|
+
if (o.stopAfter?.(store, step) === true) throw new Error(`stopped after ${step} of the ${store}`)
|
|
657
|
+
}
|
|
658
|
+
const tomb = there(old) && isTombstone(old)
|
|
659
|
+
if (s.state === 'none') return { store, back: false, why: 'no file and no tables: nothing to put back', rows: 0 }
|
|
660
|
+
if (s.state === 'own file') {
|
|
661
|
+
// a way back stopped after its drop leaves free pages: they go back now
|
|
662
|
+
await vacuumSteps(db)
|
|
663
|
+
if (ownShape(store, old) === 'tables') return { store, back: false, why: `its own file ${old} already, with the tables this code reads`, rows: 0 }
|
|
664
|
+
const hurt = oldDamage(old)
|
|
665
|
+
if (hurt != null) return { store, back: false, why: `its own file ${old} is damaged (${hurt}): ${damagedHow(store, old)}`, rows: 0 }
|
|
666
|
+
}
|
|
667
|
+
// half way, its old file whole again (a way back stopped after its rename, or a fold before its tombstone): the
|
|
668
|
+
// old file is the truth, the tables go
|
|
669
|
+
if (s.state === 'half' && !tomb) {
|
|
670
|
+
await dropTables(db, store)
|
|
671
|
+
rmDb(foldSource(old))
|
|
672
|
+
clearMark(store)
|
|
673
|
+
forgetDone(store)
|
|
674
|
+
o.print(`ok: the ${store}: its own file again, its tables out of ${machineDbPath()}`)
|
|
675
|
+
return { store, back: true, why: 'back in its own file', rows: 0 }
|
|
676
|
+
}
|
|
677
|
+
// half way, tombstone down, the second name there: a fold stopped while it copied, the old file under that name is
|
|
678
|
+
// the truth
|
|
679
|
+
if (s.state === 'half' && there(foldSource(old))) {
|
|
680
|
+
renameSync(foldSource(old), old)
|
|
681
|
+
await dropTables(db, store)
|
|
682
|
+
clearMark(store)
|
|
683
|
+
o.print(`ok: the ${store}: a fold stopped half way, its old file is back as it was`)
|
|
684
|
+
return { store, back: true, why: 'back in its own file', rows: 0 }
|
|
685
|
+
}
|
|
686
|
+
// a way back stopped after its swap under the lock: its file is whole and the tables are gone, so it ends
|
|
687
|
+
if (s.state === 'half' && tomb && tablesGone(db, store) && there(backFile(old))) {
|
|
688
|
+
const w = new Database(backFile(old), { readwrite: true })
|
|
689
|
+
w.exec('pragma journal_mode = WAL')
|
|
690
|
+
w.close()
|
|
691
|
+
renameSync(backFile(old), old)
|
|
692
|
+
for (const f of [`${old}-wal`, `${old}-shm`]) rmSync(f, { force: true })
|
|
693
|
+
forgetStoreHomes()
|
|
694
|
+
await dropTables(db, store)
|
|
695
|
+
clearMark(store)
|
|
696
|
+
forgetDone(store)
|
|
697
|
+
o.print(`ok: the ${store}: a way back stopped after its swap, ended: ${old} is its own file again`)
|
|
698
|
+
return { store, back: true, why: 'back in its own file', rows: 0 }
|
|
699
|
+
}
|
|
700
|
+
// the rows come from the machine db's tables, or, for a file of before the fold, from that file by its old names
|
|
701
|
+
const reshape = s.state === 'own file'
|
|
702
|
+
setMark(store, 'back')
|
|
703
|
+
const bytes = walkBytes(old)
|
|
704
|
+
// a writer that holds its connection open writes past the mark: each of its writes is counted from here
|
|
705
|
+
if (!reshape) watchWrites(db, store)
|
|
706
|
+
// the way back gives up: its tables were only read, so the store is whole where it was; the mark goes, so it is
|
|
707
|
+
// read and written there meanwhile. If even that cannot be written, the store stays refused until the rerun
|
|
708
|
+
const refuse = (why: string): never => {
|
|
709
|
+
let left = ''
|
|
710
|
+
try {
|
|
711
|
+
unwatchWrites(db, store)
|
|
712
|
+
clearMark(store)
|
|
713
|
+
} catch {
|
|
714
|
+
left = `; the ${store} stays refused until that rerun`
|
|
715
|
+
}
|
|
716
|
+
rmDb(backFile(old))
|
|
717
|
+
throw waitRefused(`${why}: nothing moved, the ${store} is whole in ${machineDbPath()}${left}. Processes that hold it: ${holders(machineDbPath())}; stop what writes it, or let it end, then run sk db fold --back --go again`)
|
|
718
|
+
}
|
|
719
|
+
stop('marked')
|
|
720
|
+
// a file of the store's own tables (the machine db's, so this code reads it as it is) and, for code of before the
|
|
721
|
+
// fold, a view of each under its old name: it reads, and a write there fails loud instead of making a second store
|
|
722
|
+
const tmp = backFile(old)
|
|
723
|
+
for (const f of [tmp, `${tmp}-journal`, `${tmp}-wal`, `${tmp}-shm`]) rmSync(f, { force: true })
|
|
724
|
+
const made = new Database(tmp, { create: true, readwrite: true })
|
|
725
|
+
machineFileCreate(tmp, made)
|
|
726
|
+
STORES[store].create(made)
|
|
727
|
+
if (prefix !== '') for (const t of tables) made.exec(`create view if not exists ${q(t)} as select * from ${q(`${prefix}${t}`)}`)
|
|
728
|
+
made.close()
|
|
729
|
+
chmodSync(tmp, 0o600)
|
|
730
|
+
if (reshape) db.query('attach database ? as src').run(`file:${encodeURI(old)}?mode=rw`)
|
|
731
|
+
db.query('attach database ? as back').run(tmp)
|
|
732
|
+
const from = (t: string): { schema: string; table: string } => (reshape ? { schema: 'src', table: t } : { schema: 'main', table: `${prefix}${t}` })
|
|
733
|
+
let rows = 0
|
|
734
|
+
try {
|
|
735
|
+
for (const t of tables) copyTable(db, from(t), { schema: 'back', table: `${prefix}${t}` }, o.step ?? COPY_STEP)
|
|
736
|
+
const off: string[] = []
|
|
737
|
+
// a file of before the fold is refused to every writer: its counts are final. The tables are counted again
|
|
738
|
+
// under the write lock, once the rows written meanwhile are carried
|
|
739
|
+
if (reshape)
|
|
740
|
+
for (const t of tables) {
|
|
741
|
+
const f = from(t)
|
|
742
|
+
if (shapeOf(db, f.schema, f.table) == null) continue
|
|
743
|
+
const [a, b] = [count(db, f.schema, f.table), count(db, 'back', `${prefix}${t}`)]
|
|
744
|
+
rows += b
|
|
745
|
+
if (a !== b) off.push(`${t} ${a} → ${b}`)
|
|
746
|
+
}
|
|
747
|
+
if (off.length > 0) throw new Error(`the ${store}'s rows do not match the file the way back made (${off.join(', ')}): ${reshape ? 'its file stays as it was' : 'its tables stay'}, run sk db fold --back --go again`)
|
|
748
|
+
} finally {
|
|
749
|
+
db.exec('detach database back')
|
|
750
|
+
if (reshape) db.exec('detach database src')
|
|
751
|
+
}
|
|
752
|
+
stop('built')
|
|
753
|
+
// a file of before the fold is kept as the fold's copy is: the way back of the way back
|
|
754
|
+
if (reshape && !existsSync(foldCopy(old))) linkSync(old, foldCopy(old))
|
|
755
|
+
if (!reshape) {
|
|
756
|
+
// under the machine db's write lock: the rows written since the copy began carried into the file, its counts
|
|
757
|
+
// checked, then the tables under other names, so a writer still on them fails loud; the file moves after
|
|
758
|
+
const file = new Database(tmp, { readwrite: true })
|
|
759
|
+
try {
|
|
760
|
+
file.exec('pragma busy_timeout = 5000')
|
|
761
|
+
// the rows written while it copied, carried in passes without the lock until few are left for under it
|
|
762
|
+
let carried = 0
|
|
763
|
+
try {
|
|
764
|
+
for (let pass = 0; pass < 50; pass++) if (carryWrites(db, file, store, false) <= CARRY_MAX / 4) break
|
|
765
|
+
stop('passed')
|
|
766
|
+
carried = db
|
|
767
|
+
.transaction(() => {
|
|
768
|
+
const n = carryWrites(db, file, store, true)
|
|
769
|
+
if (n < 0) return n
|
|
770
|
+
const off: string[] = []
|
|
771
|
+
rows = 0
|
|
772
|
+
for (const t of tables) {
|
|
773
|
+
const name = `${prefix}${t}`
|
|
774
|
+
if (shapeOf(db, 'main', name) == null) continue
|
|
775
|
+
const [a, b] = [count(db, 'main', name), (file.query(`select count(*) as n from ${q(name)}`).get() as { n: number }).n]
|
|
776
|
+
rows += b
|
|
777
|
+
if (a !== b) off.push(`${t} ${a} → ${b}`)
|
|
778
|
+
}
|
|
779
|
+
if (off.length > 0) throw new Error(`the ${store}'s rows do not match the file the way back made (${off.join(', ')}): its tables stay, run sk db fold --back --go again`)
|
|
780
|
+
stop('locked')
|
|
781
|
+
unwatchWrites(db, store)
|
|
782
|
+
for (const t of tables) if (shapeOf(db, 'main', `${prefix}${t}`) != null) db.exec(`alter table ${q(`${prefix}${t}`)} rename to ${q(`${prefix}${t}${GONE}`)}`)
|
|
783
|
+
return n
|
|
784
|
+
})
|
|
785
|
+
.immediate()
|
|
786
|
+
} catch (e) {
|
|
787
|
+
if (!/database is locked|busy/i.test((e as Error).message)) throw e
|
|
788
|
+
file.close()
|
|
789
|
+
refuse(`a write of another process held ${machineDbPath()} past the way back's wait (${(e as Error).message})`)
|
|
790
|
+
}
|
|
791
|
+
if (carried < 0) {
|
|
792
|
+
file.close()
|
|
793
|
+
refuse(`the ${store} was written ${-carried} times while the way back copied it, more than it carries under the write lock`)
|
|
794
|
+
}
|
|
795
|
+
if (carried > 0) o.print(`ok: the ${store}: ${carried} rows written while it copied, carried into its file`)
|
|
796
|
+
file.exec('pragma journal_mode = WAL')
|
|
797
|
+
} finally {
|
|
798
|
+
file.close()
|
|
799
|
+
}
|
|
800
|
+
stop('swapped')
|
|
801
|
+
} else {
|
|
802
|
+
const w = new Database(tmp, { readwrite: true })
|
|
803
|
+
w.exec('pragma journal_mode = WAL')
|
|
804
|
+
w.close()
|
|
805
|
+
}
|
|
806
|
+
renameSync(tmp, old)
|
|
807
|
+
for (const f of [`${old}-wal`, `${old}-shm`]) rmSync(f, { force: true })
|
|
808
|
+
forgetStoreHomes()
|
|
809
|
+
o.print(`ok: the ${store}: ${old} is its own file${reshape ? ', in the tables this code reads' : ' again'}, ${rows.toLocaleString('en-US')} rows${reshape ? '' : ', those added since the fold too'}`)
|
|
810
|
+
stop('renamed')
|
|
811
|
+
if (!reshape) {
|
|
812
|
+
const held = await dropTables(db, store)
|
|
813
|
+
o.print(`ok: the ${store}: its tables dropped in steps, the longest a delete ${held.deleteMs} ms, a drop ${held.dropMs} ms, a page give back ${held.vacuumMs} ms`)
|
|
814
|
+
}
|
|
815
|
+
stop('dropped')
|
|
816
|
+
walkEnded(store, bytes)
|
|
817
|
+
forgetDone(store)
|
|
818
|
+
if (!reshape) o.print(`ok: the ${store}: its tables are out of ${machineDbPath()}`)
|
|
819
|
+
return { store, back: true, why: 'back in its own file', rows }
|
|
820
|
+
}
|