@kaanbiryol/crate-server 0.0.0-stage → 0.17.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +73 -2
- package/THIRD_PARTY_NOTICES.md +3664 -0
- package/assets/coordinator.mjs +116 -0
- package/assets/credential-revocation.mjs +18 -0
- package/assets/database-upgrade-rules.mjs +42 -0
- package/assets/migrations/README.md +19 -0
- package/assets/qrcode.mjs +1638 -0
- package/assets/schema.sql +368 -0
- package/assets/server-release.json +6 -0
- package/assets/worker-runtime.json +12 -0
- package/assets/worker.mjs +1458 -0
- package/npm-shrinkwrap.json +939 -0
- package/package.json +38 -4
- package/scripts/assets.mjs +33 -0
- package/scripts/commands/data.mjs +80 -0
- package/scripts/commands/devices.mjs +100 -0
- package/scripts/commands/doctor.mjs +127 -0
- package/scripts/commands/service.mjs +19 -0
- package/scripts/commands/setup.mjs +194 -0
- package/scripts/commands/start.mjs +171 -0
- package/scripts/commands/status.mjs +49 -0
- package/scripts/commands/update.mjs +138 -0
- package/scripts/crate-server.mjs +11 -0
- package/scripts/deployment-fingerprint.mjs +13 -0
- package/scripts/local-server-alerts.mjs +53 -0
- package/scripts/local-server-backup-schedule.mjs +153 -0
- package/scripts/local-server-backup.mjs +275 -0
- package/scripts/local-server-cloudflared.mjs +93 -0
- package/scripts/local-server-control.mjs +150 -0
- package/scripts/local-server-devices.mjs +71 -0
- package/scripts/local-server-host-status.mjs +72 -0
- package/scripts/local-server-http.mjs +120 -0
- package/scripts/local-server-install.mjs +22 -0
- package/scripts/local-server-lifecycle.mjs +54 -0
- package/scripts/local-server-lock.mjs +217 -0
- package/scripts/local-server-migrations.mjs +43 -0
- package/scripts/local-server-options.mjs +134 -0
- package/scripts/local-server-pairing.mjs +47 -0
- package/scripts/local-server-process.mjs +77 -0
- package/scripts/local-server-qr.mjs +34 -0
- package/scripts/local-server-quick.mjs +116 -0
- package/scripts/local-server-readiness.mjs +48 -0
- package/scripts/local-server-runtime.mjs +460 -0
- package/scripts/local-server-service.mjs +209 -0
- package/scripts/local-server-style.mjs +12 -0
- package/scripts/local-server-tailscale.mjs +122 -0
- package/scripts/local-server-tunnel.mjs +212 -0
- package/scripts/local-server-watchdog.mjs +37 -0
- package/scripts/local-server-wizard.mjs +100 -0
- package/scripts/local-server.mjs +100 -0
- package/vendor/miniflare/LICENSE +25 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/ArrowClockwise.es-Cs0EHtoR.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/Breadcrumbs-BlzUUgNz.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/CaretDown.es-r8EMGhHM.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/CaretLeft.es-CCxvlwgr.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/CaretRight.es-CWeeOO8C.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/CaretUpDown.es-Bp73BWZN.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/Check.es-B3dV_aVM.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/Copy.es-DUyM7PbX.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/CopyButton-DdMFsAgv.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/CronTriggersContext-CtoQyHCH.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/CronTriggersPage-BC2FvZf5.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/DotsThree.es-B9u_qIrH.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/Download.es-v8YTKdZh.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/List.es-GlowdvL8.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/ListBullets.es-DrJsrtCL.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/MagnifyingGlass.es-BzOo3pru.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/PaperPlaneTilt.es-DTLdWOnM.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/Paperclip.es-6Ysj3lly.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/Pencil.es-CDpuGAys.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/Plus.es-xOjOjCs5.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/ResourceError-DNadec0F.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/Spinner.es-oqUPe-aY.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/TableSelect-DgjN53ZF.js +25 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/Trash.es-DTqwcb2_.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/Warning.es-CLa-n7LD.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/X.es-BiJFnG31.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_appId-Cow8QNw6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_appId-TnuOHwOA.js +5 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_bucketName-Cow8QNw6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_bucketName-DMGTgdaZ.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_bucketName-Daanvg3W.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_bucketName-DqCj-aYZ.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_bucketName-uYCS7veQ.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_captureId-Cb6ggQGG.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_captureId-Cow8QNw6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_captureId-Daanvg3W.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_className-BW1__nAw.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_className-Cow8QNw6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_className-DCj9M_Uf.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_className-DMGTgdaZ.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_className-Daanvg3W.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_className-uYCS7veQ.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_databaseId-BEh2sOY5.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_databaseId-Cow8QNw6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_instanceId-Cow8QNw6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_instanceId-CxJm9jpK.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_instanceId-Daanvg3W.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_namespaceId-Cow8QNw6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_namespaceId-HT9g0tMq.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_objectId-Cow8QNw6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_objectId-Daanvg3W.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_objectId-DdmD-NV1.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_workflowName-Cow8QNw6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_workflowName-DMGTgdaZ.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_workflowName-Daanvg3W.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_workflowName-WgIBBs_w.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/_workflowName-uYCS7veQ.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/ad-hoc-B9HL0oNk.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/async-t2_zA-v_.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/button-cdxnqcgzwko8ooha-CjoTKpgy.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/checkbox-kt1uojk2f9e0d0h1-D923QL-G.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/clipboard-text-vcbvmtne4zjk4b18-CEoJIuMe.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/configured-BGeRrlYf.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/cron-triggers-ZP5ClwAa.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/dialog-oqh8l3l3zutpibxx-nho54TMC.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/dropdown-ncwhcd912vmone8k-BAT0p_ep.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/email-B-IveBKB.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/events-ClnoiyGH.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/events-Cow8QNw6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/field-krp6z6vfbkrvufz2-DsLUBjzS.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/format-CjQ0gyEW.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/helpers-Bz2sloWm.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/index-BHW_FKpE.js +30 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/index-CiXL10aq.css +2 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/input-area-no30c09udyjxshu5-T786oEMj.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/input-group-lxdd09p60cf27pe1-BqVz8A4J.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/input-h48k3uagzrgb98au-BF-hE08e.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/label-latndvb1ngem7we8-mWoel0Kk.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/link-DadJAPnd.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/link-provider-mn2voeohon7cj9o4-CNosc_Ni.js +13 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/matchContext-C1eKDtty.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/object._-Cow8QNw6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/object._-DDwO6NT7.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/object._-Daanvg3W.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/observability-CC1mP6Xo.js +15 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/observability-CX-6-j6d.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/observability-Cow8QNw6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/react-BZY8YNV6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/redirect-CckYXsV1.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/routes-BlOyav-b.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/routing-CVthjHxr.js +2 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/routing-Cow8QNw6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/routing-DMGTgdaZ.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/routing-uYCS7veQ.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/select-kva5ru5f673kah1m-DQuxH2_G.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/sending-BPjb3S3Y.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/sending-Cow8QNw6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/switch-ihaydbzem62bey4p-C9M-MPNS.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/table-inweecadl3her7pd-UWLv9e8D.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/text-nmyi1rkwdj37f30f-BLzIhmEO.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/types-DTx0hLYz.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/useCursorPaginatedList-BGUINn38.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/assets/useRouterState-BLq6Ai_6.js +1 -0
- package/vendor/miniflare/dist/local-explorer-ui/favicon.svg +3 -0
- package/vendor/miniflare/dist/local-explorer-ui/index.html +27 -0
- package/vendor/miniflare/dist/src/index.d.ts +14183 -0
- package/vendor/miniflare/dist/src/index.js +123738 -0
- package/vendor/miniflare/dist/src/mdream_edge_bg.wasm +0 -0
- package/vendor/miniflare/dist/src/plugins/artifacts/git-sidecar.js +21071 -0
- package/vendor/miniflare/dist/src/workers/access/access-identity.worker.js +10 -0
- package/vendor/miniflare/dist/src/workers/analytics-engine/analytics-engine.worker.js +21 -0
- package/vendor/miniflare/dist/src/workers/analytics-engine/remote.worker.js +2578 -0
- package/vendor/miniflare/dist/src/workers/artifacts/binding.worker.js +903 -0
- package/vendor/miniflare/dist/src/workers/artifacts/wrapped-binding.worker.js +52 -0
- package/vendor/miniflare/dist/src/workers/assets/assets-kv.worker.js +27 -0
- package/vendor/miniflare/dist/src/workers/assets/assets.worker.js +1525 -0
- package/vendor/miniflare/dist/src/workers/assets/router.worker.js +1883 -0
- package/vendor/miniflare/dist/src/workers/assets/rpc-proxy.worker.js +55 -0
- package/vendor/miniflare/dist/src/workers/browser-rendering/binding.worker.js +453 -0
- package/vendor/miniflare/dist/src/workers/cache/cache-entry-noop.worker.js +18 -0
- package/vendor/miniflare/dist/src/workers/cache/cache-entry.worker.js +24 -0
- package/vendor/miniflare/dist/src/workers/cache/cache.worker.js +652 -0
- package/vendor/miniflare/dist/src/workers/core/dev-control.worker.js +52 -0
- package/vendor/miniflare/dist/src/workers/core/dev-registry-proxy.worker.js +371 -0
- package/vendor/miniflare/dist/src/workers/core/do-wrapper.worker.js +67 -0
- package/vendor/miniflare/dist/src/workers/core/entry.worker.js +5516 -0
- package/vendor/miniflare/dist/src/workers/core/outbound.worker.js +147 -0
- package/vendor/miniflare/dist/src/workers/d1/database.worker.js +298 -0
- package/vendor/miniflare/dist/src/workers/d1/entry.worker.js +143 -0
- package/vendor/miniflare/dist/src/workers/dispatch-namespace/dispatch-namespace-proxy.worker.js +2574 -0
- package/vendor/miniflare/dist/src/workers/dispatch-namespace/dispatch-namespace.worker.js +11 -0
- package/vendor/miniflare/dist/src/workers/email/email-store.worker.js +606 -0
- package/vendor/miniflare/dist/src/workers/email/email.worker.js +26 -0
- package/vendor/miniflare/dist/src/workers/email/send_email.worker.js +3703 -0
- package/vendor/miniflare/dist/src/workers/flagship/binding.worker.js +394 -0
- package/vendor/miniflare/dist/src/workers/flagship/object.worker.js +349 -0
- package/vendor/miniflare/dist/src/workers/hello-world/binding.worker.js +18 -0
- package/vendor/miniflare/dist/src/workers/hello-world/object.worker.js +13 -0
- package/vendor/miniflare/dist/src/workers/images/images.worker.js +450 -0
- package/vendor/miniflare/dist/src/workers/k2/binding.worker.js +2583 -0
- package/vendor/miniflare/dist/src/workers/kv/namespace.worker.js +323 -0
- package/vendor/miniflare/dist/src/workers/kv/sites.worker.js +148 -0
- package/vendor/miniflare/dist/src/workers/local-explorer/explorer.worker.js +17275 -0
- package/vendor/miniflare/dist/src/workers/observability/collector.worker.js +725 -0
- package/vendor/miniflare/dist/src/workers/pipelines/pipeline.worker.js +9 -0
- package/vendor/miniflare/dist/src/workers/queues/broker.worker.js +391 -0
- package/vendor/miniflare/dist/src/workers/r2/bucket.worker.js +1171 -0
- package/vendor/miniflare/dist/src/workers/r2/public.worker.js +1319 -0
- package/vendor/miniflare/dist/src/workers/r2/s3/index.worker.js +11128 -0
- package/vendor/miniflare/dist/src/workers/ratelimit/ratelimit-object.worker.js +55 -0
- package/vendor/miniflare/dist/src/workers/ratelimit/ratelimit.worker.js +69 -0
- package/vendor/miniflare/dist/src/workers/secrets-store/secret.worker.js +64 -0
- package/vendor/miniflare/dist/src/workers/shared/index.worker.js +730 -0
- package/vendor/miniflare/dist/src/workers/shared/object-entry.worker.js +33 -0
- package/vendor/miniflare/dist/src/workers/shared/remote-proxy-client.worker.js +2698 -0
- package/vendor/miniflare/dist/src/workers/shared/zod.worker.js +15459 -0
- package/vendor/miniflare/dist/src/workers/stream/binding.worker.js +282 -0
- package/vendor/miniflare/dist/src/workers/stream/object.worker.js +479 -0
- package/vendor/miniflare/dist/src/workers/workflows/binding.worker.js +5137 -0
- package/vendor/miniflare/dist/src/workers/workflows/wrapped-binding.worker.js +111 -0
- package/vendor/miniflare/package.json +135 -0
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// What this computer reports to connected devices about itself: how Crate was installed,
|
|
2
|
+
// when it started and last backed up, and whether its public address works. It is written
|
|
3
|
+
// to `maintenance_state` (key HOST_STATUS_KEY in src/protocol/host-status.ts), where the
|
|
4
|
+
// Worker's /server/host-status route reads it with the device's own authorization.
|
|
5
|
+
// Paths and error text stay on this computer.
|
|
6
|
+
import { statfs } from 'node:fs/promises';
|
|
7
|
+
import { readLastBackup } from './local-server-backup.mjs';
|
|
8
|
+
|
|
9
|
+
const HOST_STATUS_KEY = 'crate_host_status';
|
|
10
|
+
|
|
11
|
+
/** @param {string} path @returns {Promise<number | null>} */
|
|
12
|
+
export async function freeBytes(path) {
|
|
13
|
+
try { const stats = await statfs(path); return Number(stats.bavail) * Number(stats.bsize); }
|
|
14
|
+
catch { return null; }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* @typedef {object} HostStatusRecord
|
|
19
|
+
* @property {import('./local-server-install.mjs').InstallKind} install
|
|
20
|
+
* @property {string} startedAt
|
|
21
|
+
* @property {string | null} lastBackupAt
|
|
22
|
+
* @property {{ on: boolean, lastFailureAt: string | null }} autoBackup
|
|
23
|
+
* @property {'ready' | 'waiting' | null} publicAccess
|
|
24
|
+
* @property {number | null} diskFreeBytes
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* @param {object} options
|
|
29
|
+
* @param {Pick<import('./local-server-runtime.mjs').LocalRuntime, 'request' | 'db'>} options.runtime
|
|
30
|
+
* @param {string} options.dataDir
|
|
31
|
+
* @param {import('./local-server-install.mjs').InstallKind} options.install
|
|
32
|
+
* @param {boolean} options.public Whether an HTTPS address is being checked.
|
|
33
|
+
* @param {() => Promise<{ settings: { dir: string } | null, lastFailure: { at: string } | null }>} options.autoBackup
|
|
34
|
+
* @param {(bytes: number | null) => void} [options.onDisk] Free space on the fuller of the data and backup disks.
|
|
35
|
+
* @param {() => Date} [options.now]
|
|
36
|
+
*/
|
|
37
|
+
export function createHostStatus({ runtime, dataDir, install, public: isPublic, autoBackup, onDisk = () => {}, now = () => new Date() }) {
|
|
38
|
+
/** @type {HostStatusRecord} */
|
|
39
|
+
const record = { install, startedAt: now().toISOString(), lastBackupAt: null, autoBackup: { on: false, lastFailureAt: null },
|
|
40
|
+
publicAccess: isPublic ? 'waiting' : null, diskFreeBytes: null };
|
|
41
|
+
let queue = Promise.resolve();
|
|
42
|
+
|
|
43
|
+
async function write() {
|
|
44
|
+
// A backup pauses the runtime; the write waits for it to resume.
|
|
45
|
+
const release = await runtime.request();
|
|
46
|
+
if (!release) return;
|
|
47
|
+
try {
|
|
48
|
+
await runtime.db.prepare('INSERT INTO maintenance_state(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value')
|
|
49
|
+
.bind(HOST_STATUS_KEY, JSON.stringify(record)).run();
|
|
50
|
+
} finally { release(); }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
return {
|
|
54
|
+
record,
|
|
55
|
+
/** Rereads backups and disk space, applies `patch`, and writes the record in order.
|
|
56
|
+
* @param {Partial<Pick<HostStatusRecord, 'publicAccess'>>} [patch] */
|
|
57
|
+
refresh(patch = {}) {
|
|
58
|
+
queue = queue.then(async () => {
|
|
59
|
+
const [last, auto] = await Promise.all([readLastBackup(dataDir), autoBackup()]);
|
|
60
|
+
const sizes = (await Promise.all([dataDir, ...(auto.settings ? [auto.settings.dir] : [])].map(freeBytes))).filter(size => size !== null);
|
|
61
|
+
const disk = sizes.length ? Math.min(...sizes) : null;
|
|
62
|
+
onDisk(disk);
|
|
63
|
+
Object.assign(record, patch, { lastBackupAt: last?.createdAt ?? null, diskFreeBytes: disk,
|
|
64
|
+
autoBackup: { on: Boolean(auto.settings), lastFailureAt: auto.lastFailure?.at ?? null } });
|
|
65
|
+
await write();
|
|
66
|
+
}).catch(error => { console.warn(`Could not record server status for devices: ${error.message}`); });
|
|
67
|
+
return queue;
|
|
68
|
+
},
|
|
69
|
+
/** Waits for pending writes, before storage closes. */
|
|
70
|
+
settled: () => queue,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { createServer } from 'node:http';
|
|
2
|
+
import { Readable } from 'node:stream';
|
|
3
|
+
import { pipeline } from 'node:stream/promises';
|
|
4
|
+
|
|
5
|
+
/** @param {import('node:http').ServerResponse} response @param {number} status @param {unknown} value */
|
|
6
|
+
export function sendJson(response, status, value) {
|
|
7
|
+
response.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
|
|
8
|
+
response.end(JSON.stringify(value));
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** @param {import('node:http').IncomingMessage} request @param {number} [limit] Maximum characters. */
|
|
12
|
+
export async function readSmallJson(request, limit = 2048) {
|
|
13
|
+
let body = '';
|
|
14
|
+
for await (const chunk of request) {
|
|
15
|
+
body += chunk.toString();
|
|
16
|
+
if (body.length > limit) throw new Error('Request too large');
|
|
17
|
+
}
|
|
18
|
+
return JSON.parse(body);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const LOOPBACK = new Set(['127.0.0.1', '::1', '::ffff:127.0.0.1']);
|
|
22
|
+
|
|
23
|
+
// The header each managed tunnel sets to the client's address, replacing any value
|
|
24
|
+
// the client sent. Each passes the other's header through, so trust only its own.
|
|
25
|
+
// Tailscale serve and Funnel drop inbound X-Forwarded-* and set X-Forwarded-For to
|
|
26
|
+
// the single source address.
|
|
27
|
+
/** @typedef {'cloudflare' | 'tailscale'} ManagedTunnel */
|
|
28
|
+
/** @type {Record<ManagedTunnel, string>} */
|
|
29
|
+
const FORWARDED_ADDRESS = { cloudflare: 'cf-connecting-ip', tailscale: 'x-forwarded-for' };
|
|
30
|
+
|
|
31
|
+
/** A managed tunnel ('cloudflare' or 'tailscale') connects from loopback and forwards
|
|
32
|
+
* each client's address, so per-address admission limits stay per client.
|
|
33
|
+
* @param {import('node:http').IncomingMessage} request
|
|
34
|
+
* @param {ManagedTunnel | null} [tunnel] */
|
|
35
|
+
export function clientAddress(request, tunnel) {
|
|
36
|
+
const peer = request.socket.remoteAddress ?? '127.0.0.1';
|
|
37
|
+
const forwarded = tunnel ? request.headers[FORWARDED_ADDRESS[tunnel]] : undefined;
|
|
38
|
+
return LOOPBACK.has(peer) && typeof forwarded === 'string' && forwarded ? forwarded : peer;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Expose only the application fetch handler. Miniflare's development HTTP
|
|
42
|
+
// endpoints and inspector stay on their own private loopback listener.
|
|
43
|
+
/**
|
|
44
|
+
* @param {import('./local-server-runtime.mjs').LocalRuntime | (() => import('./local-server-runtime.mjs').LocalRuntime | null | undefined)} runtime
|
|
45
|
+
* The runtime, or a getter that returns none while the server starts.
|
|
46
|
+
* @param {object} [options]
|
|
47
|
+
* @param {string} [options.host]
|
|
48
|
+
* @param {number} [options.port]
|
|
49
|
+
* @param {{ exchange(code: unknown): Promise<{ token: string } | null> }} [options.pairing]
|
|
50
|
+
* @param {string} [options.instance] Answers the public readiness probe.
|
|
51
|
+
* @param {ManagedTunnel | null} [options.tunnel]
|
|
52
|
+
* @param {number} [options.maxFileBytes] Lengthens the request timeout for larger uploads.
|
|
53
|
+
*/
|
|
54
|
+
export async function listenLocalServer(runtime, { host = '127.0.0.1', port = 8787, pairing, instance, tunnel = null, maxFileBytes = 0 } = {}) {
|
|
55
|
+
const server = createServer(async (request, response) => {
|
|
56
|
+
try {
|
|
57
|
+
const active = typeof runtime === 'function' ? runtime() : runtime;
|
|
58
|
+
if (!active) {
|
|
59
|
+
response.writeHead(503, { 'Content-Type': 'text/plain', 'Cache-Control': 'no-store' });
|
|
60
|
+
response.end('Crate is starting.');
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
const url = new URL(request.url || '/', active.origin);
|
|
64
|
+
if (url.origin !== active.origin || /^\/(?:cdn-cgi|__cf_local)(?:\/|$)/.test(decodeURIComponent(url.pathname))) {
|
|
65
|
+
response.writeHead(404);
|
|
66
|
+
response.end();
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
if (url.pathname === '/__crate/ready' && request.method === 'GET' && instance) {
|
|
70
|
+
sendJson(response, 200, { instance }); return;
|
|
71
|
+
}
|
|
72
|
+
// A backup pauses the runtime briefly; hold the request until it resumes.
|
|
73
|
+
const release = await active.request();
|
|
74
|
+
if (!release) {
|
|
75
|
+
response.writeHead(503, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', 'Retry-After': '5' });
|
|
76
|
+
response.end(JSON.stringify({ error: 'Crate is finishing a backup. Try again shortly.' }));
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
try {
|
|
80
|
+
if (url.pathname === '/__crate/pair' && pairing) {
|
|
81
|
+
if (request.method !== 'POST') { sendJson(response, 405, { error: 'Use POST' }); return; }
|
|
82
|
+
let credential;
|
|
83
|
+
try { credential = await pairing.exchange((await readSmallJson(request)).code); }
|
|
84
|
+
catch { sendJson(response, 400, { error: 'Could not redeem this pairing code. Generate a new code and try again.' }); return; }
|
|
85
|
+
if (!credential) { sendJson(response, 401, { error: 'Pairing code expired or already used. Generate a new code on your server.' }); return; }
|
|
86
|
+
sendJson(response, 200, { authToken: credential.token }); return;
|
|
87
|
+
}
|
|
88
|
+
const headers = new Headers();
|
|
89
|
+
for (const [name, value] of Object.entries(request.headers)) {
|
|
90
|
+
if (value !== undefined && !['host', 'connection', 'transfer-encoding'].includes(name)
|
|
91
|
+
&& !name.startsWith('mf-') && !name.startsWith('cf-') && !name.startsWith('x-forwarded-') && !name.startsWith('x-crate-internal-')) {
|
|
92
|
+
headers.set(name, Array.isArray(value) ? value.join(', ') : value);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
headers.set('CF-Connecting-IP', clientAddress(request, tunnel));
|
|
96
|
+
const abort = new AbortController();
|
|
97
|
+
response.on('close', () => { if (!response.writableFinished) abort.abort(); });
|
|
98
|
+
const result = await active.mf.dispatchFetch(url.href, {
|
|
99
|
+
method: request.method, headers, redirect: 'manual', signal: abort.signal,
|
|
100
|
+
...(['GET', 'HEAD'].includes(/** @type {string} */ (request.method)) ? {} : { body: Readable.toWeb(request), duplex: 'half' }),
|
|
101
|
+
});
|
|
102
|
+
const responseHeaders = new Headers(result.headers);
|
|
103
|
+
// dispatchFetch transparently decodes upstream compression.
|
|
104
|
+
if (responseHeaders.has('MF-Content-Encoding')) responseHeaders.delete('Content-Length');
|
|
105
|
+
for (const name of ['MF-Content-Encoding', 'Content-Encoding', 'Transfer-Encoding', 'Connection']) responseHeaders.delete(name);
|
|
106
|
+
response.writeHead(result.status, Object.fromEntries(responseHeaders));
|
|
107
|
+
if (result.body) await pipeline(Readable.fromWeb(result.body), response);
|
|
108
|
+
else response.end();
|
|
109
|
+
} finally { release(); }
|
|
110
|
+
} catch {
|
|
111
|
+
if (!response.headersSent) response.writeHead(503, { 'Content-Type': 'application/json' });
|
|
112
|
+
response.end(JSON.stringify({ error: 'Local server unavailable' }));
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
// Two minutes, or long enough to receive the largest single request at 256 KiB/s. Larger
|
|
116
|
+
// files travel in parts; 128 MiB mirrors MAX_BUFFERED_FILE_BYTES in src/protocol/sync-limits.ts.
|
|
117
|
+
server.requestTimeout = Math.max(120_000, Math.ceil(Math.min(maxFileBytes, 128 * 1024 * 1024) / (256 * 1024)) * 1000);
|
|
118
|
+
await /** @type {Promise<void>} */ (new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, host, resolve); }));
|
|
119
|
+
return server;
|
|
120
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// How this server was installed, which decides the commands Crate prints for pairing,
|
|
2
|
+
// updating and running it as a service.
|
|
3
|
+
import { sep } from 'node:path';
|
|
4
|
+
import { packaged } from './assets.mjs';
|
|
5
|
+
|
|
6
|
+
/** @typedef {'docker' | 'source' | 'npx' | 'npm'} InstallKind */
|
|
7
|
+
|
|
8
|
+
export const PACKAGE_NAME = '@kaanbiryol/crate-server';
|
|
9
|
+
|
|
10
|
+
/** @param {{ docker?: boolean, packaged?: boolean, script?: string }} [options] @returns {InstallKind} */
|
|
11
|
+
export function installKind({ docker = process.env.CRATE_DOCKER === '1', packaged: isPackaged = packaged, script = process.argv[1] ?? '' } = {}) {
|
|
12
|
+
if (docker) return 'docker';
|
|
13
|
+
if (!isPackaged) return 'source';
|
|
14
|
+
return script.includes(`${sep}_npx${sep}`) ? 'npx' : 'npm';
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** The command line that runs a Crate command for this install.
|
|
18
|
+
* @param {InstallKind} kind @param {string} args */
|
|
19
|
+
export function crateCommand(kind, args) {
|
|
20
|
+
const prefix = { docker: 'docker compose exec crate crate', source: 'npm run server --', npx: `npx ${PACKAGE_NAME}`, npm: 'crate-server' }[kind];
|
|
21
|
+
return `${prefix} ${args}`;
|
|
22
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What `closeLocalServerResources` stops, in this order. Each one is optional.
|
|
3
|
+
* @typedef {object} LocalServerResources
|
|
4
|
+
* @property {{ close(): Promise<void> }} [readiness]
|
|
5
|
+
* @property {{ close(): Promise<void> }} [control]
|
|
6
|
+
* @property {{ stop(): Promise<void> }} [tunnel]
|
|
7
|
+
* @property {import('node:http').Server} [server]
|
|
8
|
+
* @property {{ close(): Promise<void> } | null} [runtime]
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* The resources a CLI command opens. A Quick Tunnel server closes its own set.
|
|
13
|
+
* @typedef {LocalServerResources & { quickServer?: { close(): Promise<void> } }} CommandResources
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** @param {import('node:http').Server} server */
|
|
17
|
+
async function closeHttpServer(server) {
|
|
18
|
+
const deadline = setTimeout(() => server.closeAllConnections(), 5000);
|
|
19
|
+
try {
|
|
20
|
+
await /** @type {Promise<void>} */ (new Promise((resolve, reject) => server.close((/** @type {NodeJS.ErrnoException | undefined} */ error) => {
|
|
21
|
+
if (error && error.code !== 'ERR_SERVER_NOT_RUNNING') reject(error);
|
|
22
|
+
else resolve();
|
|
23
|
+
})));
|
|
24
|
+
} finally { clearTimeout(deadline); }
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Stop incoming work before disposing storage. One failed cleanup must not skip
|
|
28
|
+
* the remaining resources; the runtime still owns disposal and safe unlocking.
|
|
29
|
+
* @param {LocalServerResources} resources
|
|
30
|
+
* @param {unknown} [startupError] */
|
|
31
|
+
export async function closeLocalServerResources({ readiness, control, tunnel, server, runtime }, startupError) {
|
|
32
|
+
const errors = [];
|
|
33
|
+
const messages = [];
|
|
34
|
+
for (const [name, close] of /** @type {[string, () => unknown][]} */ ([
|
|
35
|
+
['Readiness checks', () => readiness?.close()],
|
|
36
|
+
['Pairing control', () => control?.close()],
|
|
37
|
+
['Tunnel', () => tunnel?.stop()],
|
|
38
|
+
['HTTP server', () => server && closeHttpServer(server)],
|
|
39
|
+
['Storage runtime', () => runtime?.close()],
|
|
40
|
+
])) {
|
|
41
|
+
try { await close(); }
|
|
42
|
+
catch (error) {
|
|
43
|
+
errors.push(error);
|
|
44
|
+
messages.push(`${name}: ${error instanceof Error ? error.message : String(error)}`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (errors.length) {
|
|
48
|
+
if (startupError !== undefined) {
|
|
49
|
+
errors.unshift(startupError);
|
|
50
|
+
messages.unshift(startupError instanceof Error ? startupError.message : String(startupError));
|
|
51
|
+
}
|
|
52
|
+
throw new AggregateError(errors, messages.join('\n'), { cause: startupError });
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { link, mkdir, open, readFile, readdir, readlink, realpath, rename, unlink } from 'node:fs/promises';
|
|
4
|
+
import { uptime as osUptime } from 'node:os';
|
|
5
|
+
import { basename, join, resolve } from 'node:path';
|
|
6
|
+
import { promisify } from 'node:util';
|
|
7
|
+
|
|
8
|
+
/** The owner of a data directory lock (`server.lock`).
|
|
9
|
+
* @typedef {{ pid: number, startedAt: string }} ServerLock */
|
|
10
|
+
|
|
11
|
+
// Every command owns the complete data directory. Never run two workerd
|
|
12
|
+
// processes against the same SQLite files, including administrative commands.
|
|
13
|
+
/** A lock is left over from an earlier boot only when it predates this boot and its
|
|
14
|
+
* process is gone. Both are required: a clock corrected after boot can make a live
|
|
15
|
+
* server's lock look old, and a reused process ID keeps a stale one. Every
|
|
16
|
+
* process from before a restart has exited, so no workerd can still use the data.
|
|
17
|
+
* @param {string} text
|
|
18
|
+
* @param {{ now?: number, uptime?: number, isRunning?: (pid: number) => boolean }} [options] */
|
|
19
|
+
export function isLockFromEarlierBoot(text, { now = Date.now(), uptime = osUptime(), isRunning = pidIsRunning } = {}) {
|
|
20
|
+
/** @type {ServerLock} */
|
|
21
|
+
let lock;
|
|
22
|
+
try { lock = JSON.parse(text); } catch { return false; }
|
|
23
|
+
const startedAt = Date.parse(lock?.startedAt);
|
|
24
|
+
return Number.isSafeInteger(lock?.pid) && Number.isFinite(startedAt)
|
|
25
|
+
&& startedAt < now - uptime * 1000 && !isRunning(lock.pid);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** @param {number} pid */
|
|
29
|
+
function pidIsRunning(pid) {
|
|
30
|
+
try { process.kill(pid, 0); return true; }
|
|
31
|
+
catch (error) { return error.code !== 'ESRCH'; }
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Every running process, or null where processes cannot be listed.
|
|
35
|
+
* @returns {Promise<{ pid: number, ppid: number, name: string }[] | null>} */
|
|
36
|
+
async function listProcesses() {
|
|
37
|
+
/** @type {{ pid: number, ppid: number, name: string }[]} */
|
|
38
|
+
let processes;
|
|
39
|
+
try {
|
|
40
|
+
if (process.platform === 'linux') {
|
|
41
|
+
processes = [];
|
|
42
|
+
for (const entry of await readdir('/proc')) {
|
|
43
|
+
if (!/^\d+$/.test(entry)) continue;
|
|
44
|
+
// `pid (comm) state ppid ...`; comm may contain spaces and parentheses.
|
|
45
|
+
const stat = await readFile(`/proc/${entry}/stat`, 'utf8').catch(() => null);
|
|
46
|
+
const match = stat && /^(\d+) \((.*)\) \S+ (\d+)/s.exec(stat);
|
|
47
|
+
if (match) processes.push({ pid: Number(match[1]), name: match[2], ppid: Number(match[3]) });
|
|
48
|
+
}
|
|
49
|
+
} else if (process.platform === 'darwin') {
|
|
50
|
+
const { stdout } = await promisify(execFile)('ps', ['-A', '-o', 'pid=,ppid=,comm=']);
|
|
51
|
+
processes = stdout.split('\n').flatMap(line => {
|
|
52
|
+
const match = /^\s*(\d+)\s+(\d+)\s+(.+)$/.exec(line);
|
|
53
|
+
return match ? [{ pid: Number(match[1]), ppid: Number(match[2]), name: basename(match[3].trim()) }] : [];
|
|
54
|
+
});
|
|
55
|
+
} else return null;
|
|
56
|
+
} catch { return null; }
|
|
57
|
+
return processes;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Whether a process has files open under `directory`, or null when that cannot be read.
|
|
61
|
+
* @param {number} pid @param {string} directory @returns {Promise<boolean | null>} */
|
|
62
|
+
async function processUsesDirectory(pid, directory) {
|
|
63
|
+
const inside = (/** @type {string} */ path) => path === directory || path.startsWith(`${directory}/`);
|
|
64
|
+
try {
|
|
65
|
+
if (process.platform === 'linux') {
|
|
66
|
+
const fds = await readdir(`/proc/${pid}/fd`);
|
|
67
|
+
const paths = await Promise.all(fds.map(fd => readlink(`/proc/${pid}/fd/${fd}`).catch(() => '')));
|
|
68
|
+
return paths.some(inside);
|
|
69
|
+
}
|
|
70
|
+
if (process.platform === 'darwin') {
|
|
71
|
+
// lsof exits 1 when it lists nothing for a running process.
|
|
72
|
+
/** @type {string} */
|
|
73
|
+
const stdout = await promisify(execFile)('lsof', ['-w', '-Fn', '-p', String(pid)]).then(result => result.stdout, error => {
|
|
74
|
+
if (error.code === 1 && typeof error.stdout === 'string') return error.stdout;
|
|
75
|
+
throw error;
|
|
76
|
+
});
|
|
77
|
+
return stdout.split('\n').some(line => line.startsWith('n') && inside(line.slice(1)));
|
|
78
|
+
}
|
|
79
|
+
} catch { /* Unreadable: the caller assumes it may use the directory. */ }
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Running workerd processes that lost their parent, or null where processes cannot be
|
|
84
|
+
* listed. A force-quit server leaves its workerd running on the same files, adopted by
|
|
85
|
+
* init or a subreaper. Workerd whose parent is a live Node process belongs to another
|
|
86
|
+
* server or tool that still runs, never to the dead lock holder. With `dataDir`, only
|
|
87
|
+
* workerd with files open in its storage counts, so another server's leftover runtime
|
|
88
|
+
* never blocks this one; one whose files cannot be read still counts.
|
|
89
|
+
* @param {string} [dataDir] @returns {Promise<number[] | null>} */
|
|
90
|
+
async function otherWorkerdProcesses(dataDir) {
|
|
91
|
+
const processes = await listProcesses();
|
|
92
|
+
if (!processes) return null;
|
|
93
|
+
const names = new Map(processes.map(entry => [entry.pid, entry.name]));
|
|
94
|
+
const orphans = processes.filter(entry => entry.name === 'workerd' && names.get(entry.ppid) !== 'node').map(entry => entry.pid);
|
|
95
|
+
if (dataDir === undefined || !orphans.length) return orphans;
|
|
96
|
+
const storage = join(await realpath(dataDir).catch(() => resolve(dataDir)), 'resources');
|
|
97
|
+
const uses = await Promise.all(orphans.map(pid => processUsesDirectory(pid, storage)));
|
|
98
|
+
return orphans.filter((_, index) => uses[index] !== false);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** The workerd processes a server started on its data directory (`workerd.json`), so a
|
|
102
|
+
* start after a force-quit can stop the ones it left running there.
|
|
103
|
+
* @typedef {{ serverPid: number, workerd: number[] }} WorkerdRecord */
|
|
104
|
+
export const WORKERD_RECORD = 'workerd.json';
|
|
105
|
+
|
|
106
|
+
/** Records this process's workerd children. Miniflare starts a new one on each restart.
|
|
107
|
+
* @param {string} dataDir */
|
|
108
|
+
export async function recordWorkerd(dataDir) {
|
|
109
|
+
const processes = await listProcesses();
|
|
110
|
+
if (!processes) return;
|
|
111
|
+
const workerd = processes.filter(entry => entry.name === 'workerd' && entry.ppid === process.pid).map(entry => entry.pid);
|
|
112
|
+
await writePrivateJson(join(dataDir, WORKERD_RECORD), { serverPid: process.pid, workerd });
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** @param {string} dataDir @returns {Promise<WorkerdRecord | null>} */
|
|
116
|
+
async function readWorkerdRecord(dataDir) {
|
|
117
|
+
try {
|
|
118
|
+
const record = JSON.parse(await readFile(join(dataDir, WORKERD_RECORD), 'utf8'));
|
|
119
|
+
return Number.isSafeInteger(record?.serverPid) && Array.isArray(record.workerd) ? record : null;
|
|
120
|
+
} catch { return null; }
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Asks processes to stop, then kills those that keep running.
|
|
124
|
+
* @param {number[]} pids @returns {Promise<boolean>} True once all have exited. */
|
|
125
|
+
async function stopProcesses(pids) {
|
|
126
|
+
/** @param {NodeJS.Signals} signal */
|
|
127
|
+
const send = signal => { for (const pid of pids) { try { process.kill(pid, signal); } catch { /* already gone */ } } };
|
|
128
|
+
/** @param {number} ms */
|
|
129
|
+
const exited = async ms => {
|
|
130
|
+
for (const deadline = Date.now() + ms; pids.some(pidIsRunning);) {
|
|
131
|
+
if (Date.now() > deadline) return false;
|
|
132
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
133
|
+
}
|
|
134
|
+
return true;
|
|
135
|
+
};
|
|
136
|
+
send('SIGTERM');
|
|
137
|
+
if (await exited(10_000)) return true;
|
|
138
|
+
send('SIGKILL');
|
|
139
|
+
return exited(5_000);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Without a reboot, a lock is stale once its process is gone and no workerd it may
|
|
143
|
+
* have started is still running. Workerd the dead server recorded as its own is
|
|
144
|
+
* stopped first. Throws while any other may still use the data.
|
|
145
|
+
* @param {string} text
|
|
146
|
+
* @param {{ isRunning?: (pid: number) => boolean, listWorkerd?: () => Promise<number[] | null>,
|
|
147
|
+
* record?: WorkerdRecord | null, stop?: (pids: number[]) => Promise<boolean> }} [options] */
|
|
148
|
+
export async function isAbandonedLock(text, { isRunning = pidIsRunning, listWorkerd = otherWorkerdProcesses, record = null, stop = stopProcesses } = {}) {
|
|
149
|
+
/** @type {ServerLock} */
|
|
150
|
+
let lock;
|
|
151
|
+
try { lock = JSON.parse(text); } catch { return false; }
|
|
152
|
+
if (!Number.isSafeInteger(lock?.pid) || isRunning(lock.pid)) return false;
|
|
153
|
+
let workerd = await listWorkerd();
|
|
154
|
+
if (workerd === null) return false;
|
|
155
|
+
// Only workerd that lost its parent and that the dead lock holder recorded is stopped.
|
|
156
|
+
const owned = record?.serverPid === lock.pid ? workerd.filter(pid => record.workerd.includes(pid)) : [];
|
|
157
|
+
if (owned.length) {
|
|
158
|
+
if (!await stop(owned)) throw new Error(`Data directory is locked by a Crate server that was force-quit, and its workerd did not stop (PID ${owned.join(', ')}). Stop it with: kill -9 ${owned.join(' ')}. Then start Crate again.`);
|
|
159
|
+
console.warn(`Stopped workerd left running by a force-quit Crate server (PID ${owned.join(', ')}).`);
|
|
160
|
+
workerd = workerd.filter(pid => !owned.includes(pid));
|
|
161
|
+
}
|
|
162
|
+
if (workerd.length) {
|
|
163
|
+
throw new Error(`Data directory is locked by a Crate server that was force-quit, and workerd it may have started is still running without it (PID ${workerd.join(', ')}). Stop it with: kill ${workerd.join(' ')}. Then start Crate again.`);
|
|
164
|
+
}
|
|
165
|
+
return true;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** @param {string} dataDir @param {Parameters<typeof isAbandonedLock>[1]} [options]
|
|
169
|
+
* @returns {Promise<() => Promise<void>>} Releases the lock. */
|
|
170
|
+
export async function lockLocalData(dataDir, options) {
|
|
171
|
+
await mkdir(dataDir, { recursive: true, mode: 0o700 });
|
|
172
|
+
const path = join(dataDir, 'server.lock');
|
|
173
|
+
const locked = () => new Error(`Data directory is locked. Stop its Crate server first. After a crash, verify no Crate/workerd process uses this directory before removing ${path}.`);
|
|
174
|
+
/** @type {import('node:fs/promises').FileHandle | undefined} */
|
|
175
|
+
let handle;
|
|
176
|
+
for (let attempt = 0; !handle; attempt++) {
|
|
177
|
+
try { handle = await open(path, 'wx', 0o600); }
|
|
178
|
+
catch (error) {
|
|
179
|
+
if (error.code !== 'EEXIST') throw error;
|
|
180
|
+
const previous = await readFile(path, 'utf8').catch(() => '');
|
|
181
|
+
if (attempt === 0 && (isLockFromEarlierBoot(previous) || await isAbandonedLock(previous, { record: await readWorkerdRecord(dataDir), listWorkerd: () => otherWorkerdProcesses(dataDir), ...options }))) {
|
|
182
|
+
if (!await removeStaleLock(path, previous)) throw locked();
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
throw locked();
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
const lock = `${JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString() })}\n`;
|
|
189
|
+
await handle.writeFile(lock);
|
|
190
|
+
await handle.close();
|
|
191
|
+
// Another start may have taken the lock over after a crash; only our own is removed.
|
|
192
|
+
return async () => { if (await readFile(path, 'utf8').catch(() => null) === lock) await unlink(path); };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Removes the stale lock that was checked, not one another start wrote after removing it first.
|
|
196
|
+
* Moving it aside is atomic, so only one start can take each lock file.
|
|
197
|
+
* @param {string} path @param {string} previous @returns {Promise<boolean>} False when another start owns the lock. */
|
|
198
|
+
async function removeStaleLock(path, previous) {
|
|
199
|
+
const claimed = `${path}.stale-${randomUUID()}`;
|
|
200
|
+
try { await rename(path, claimed); }
|
|
201
|
+
catch (error) { if (error.code === 'ENOENT') return true; throw error; }
|
|
202
|
+
try {
|
|
203
|
+
if (await readFile(claimed, 'utf8') === previous) return true;
|
|
204
|
+
await link(claimed, path).catch(() => {});
|
|
205
|
+
return false;
|
|
206
|
+
} finally { await unlink(claimed).catch(() => {}); }
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Writes JSON readable only by the owner, replacing the file atomically.
|
|
210
|
+
* @param {string} path @param {unknown} value */
|
|
211
|
+
export async function writePrivateJson(path, value) {
|
|
212
|
+
const temporary = `${path}.tmp`;
|
|
213
|
+
const file = await open(temporary, 'w', 0o600);
|
|
214
|
+
try { await file.writeFile(`${JSON.stringify(value, null, 2)}\n`); await file.sync(); }
|
|
215
|
+
finally { await file.close(); }
|
|
216
|
+
await rename(temporary, path);
|
|
217
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
import { pathToFileURL } from 'node:url';
|
|
4
|
+
import { serverAssetPath, upgradeRulesPath } from './assets.mjs';
|
|
5
|
+
|
|
6
|
+
// The Cloudflare provisioner's manifest, history and transaction rules.
|
|
7
|
+
/** @type {typeof import('../../../src/cloudflare/deployment/database-upgrade-rules.ts')} */
|
|
8
|
+
const { migrationTransactionSql, planDatabaseUpgrade, validateMigrationHistory } = await import(pathToFileURL(upgradeRulesPath).href);
|
|
9
|
+
const readMigration = (/** @type {string} */ file) => readFile(serverAssetPath(`migrations/${file}`), 'utf8');
|
|
10
|
+
|
|
11
|
+
// server.json records the schema version beside its hash, like crate_release on
|
|
12
|
+
// Cloudflare. A changed schema needs an older version with a registered path.
|
|
13
|
+
/** @param {number} schemaVersion @param {import('./local-server-runtime.mjs').ServerRelease} release */
|
|
14
|
+
export function assertLocalMigrationPath(schemaVersion, release) {
|
|
15
|
+
if (!Number.isSafeInteger(schemaVersion) || schemaVersion >= release.schemaVersion) throw new Error('No tested migration exists for this data directory.');
|
|
16
|
+
planDatabaseUpgrade(schemaVersion, release);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @param {import('./local-server-runtime.mjs').LocalD1Database} db
|
|
21
|
+
* @param {import('./local-server-runtime.mjs').ServerRelease} release
|
|
22
|
+
* @param {(file: string) => Promise<string>} [readSql]
|
|
23
|
+
*/
|
|
24
|
+
export async function migrateLocalDatabase(db, release, readSql = readMigration) {
|
|
25
|
+
const verify = async () => {
|
|
26
|
+
const marker = await db.prepare('SELECT version, created_version FROM crate_schema WHERE id=1').first();
|
|
27
|
+
if (!Number.isSafeInteger(marker?.version)) throw new Error('Unsupported local schema. Restore using the matching server build.');
|
|
28
|
+
validateMigrationHistory(marker.version, marker.created_version, (await db.prepare('SELECT id, checksum FROM crate_migrations').all()).results, release);
|
|
29
|
+
return marker.version;
|
|
30
|
+
};
|
|
31
|
+
const counts = () => db.prepare('SELECT (SELECT count(*) FROM auth_tokens) AS tokens, (SELECT count(*) FROM files) AS files, (SELECT count(*) FROM file_versions) AS versions').first();
|
|
32
|
+
const version = await verify();
|
|
33
|
+
const before = await counts();
|
|
34
|
+
for (const migration of planDatabaseUpgrade(version, release)) {
|
|
35
|
+
const sql = await readSql(migration.file);
|
|
36
|
+
if (createHash('sha256').update(sql).digest('hex') !== migration.checksum) throw new Error('Database migration failed its integrity check');
|
|
37
|
+
// One prepared query runs the whole script in one D1 transaction, like the
|
|
38
|
+
// Cloudflare query API, so triggers and quoted semicolons stay intact.
|
|
39
|
+
await db.prepare(migrationTransactionSql(migration, sql)).run();
|
|
40
|
+
}
|
|
41
|
+
await verify();
|
|
42
|
+
if (JSON.stringify(before) !== JSON.stringify(await counts())) throw new Error('Upgrade verification failed. Keep the stopped server and its backup.');
|
|
43
|
+
}
|