@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,460 @@
|
|
|
1
|
+
import { assertLocalMigrationPath, migrateLocalDatabase } from './local-server-migrations.mjs';
|
|
2
|
+
import { watchRuntime } from './local-server-watchdog.mjs';
|
|
3
|
+
import { lockLocalData, recordWorkerd, WORKERD_RECORD, writePrivateJson } from './local-server-lock.mjs';
|
|
4
|
+
import { deploymentFingerprint } from './deployment-fingerprint.mjs';
|
|
5
|
+
import { coordinatorPath, packaged, revocationPath, runtimeVersion, serverAssetPath, workerPath } from './assets.mjs';
|
|
6
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
7
|
+
import { readFile, readdir, unlink } from 'node:fs/promises';
|
|
8
|
+
import { join, resolve } from 'node:path';
|
|
9
|
+
import { pathToFileURL } from 'node:url';
|
|
10
|
+
/** @type {typeof import('miniflare')} */
|
|
11
|
+
const { Miniflare, convertV4MiniflareOptions } = await import(packaged
|
|
12
|
+
? '../vendor/miniflare/dist/src/index.js' : 'miniflare');
|
|
13
|
+
/** @type {typeof import('../../../src/cloudflare/worker/auth/revocation.ts')} */
|
|
14
|
+
const { revokeCredential } = await import(pathToFileURL(revocationPath).href);
|
|
15
|
+
/** @type {typeof import('../../../src/cloudflare/worker/coordinator/coordinator.ts')} */
|
|
16
|
+
const { armReminderDispatcher, revokeCoordinatedCredential, sendHostAlert } = await import(pathToFileURL(coordinatorPath).href);
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The D1 subset the server uses. Miniflare types its bindings with workers types this
|
|
20
|
+
* repository does not install. Rows stay untyped because JavaScript callers cannot pass
|
|
21
|
+
* a row type; declare the columns where a row is read.
|
|
22
|
+
* @typedef {any} D1Row
|
|
23
|
+
* @typedef {{
|
|
24
|
+
* bind(...values: unknown[]): LocalD1Statement,
|
|
25
|
+
* first(): Promise<D1Row | null>,
|
|
26
|
+
* run(): Promise<{ meta: { changes: number } }>,
|
|
27
|
+
* all(): Promise<{ results: D1Row[] }>,
|
|
28
|
+
* }} LocalD1Statement
|
|
29
|
+
* @typedef {{
|
|
30
|
+
* prepare(query: string): LocalD1Statement,
|
|
31
|
+
* batch<T = unknown>(statements: LocalD1Statement[]): Promise<T[]>,
|
|
32
|
+
* exec(query: string): Promise<unknown>,
|
|
33
|
+
* }} LocalD1Database
|
|
34
|
+
* @typedef {{ get(key: string): Promise<{ body: AsyncIterable<Uint8Array> } | null> }} LocalR2Bucket
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The Worker's binding names and runtime settings (`src/cloudflare/worker-runtime.json`).
|
|
39
|
+
* @typedef {object} WorkerRuntimeConfig
|
|
40
|
+
* @property {string} compatibilityDate
|
|
41
|
+
* @property {string[]} compatibilityFlags
|
|
42
|
+
* @property {{ database: string, bucket: string, reminderAlarms: string, notificationRateLimiter: string }} bindings
|
|
43
|
+
* @property {string} durableObjectClass
|
|
44
|
+
* @property {{ limit: number, period: 10 | 60 }} notificationRateLimit
|
|
45
|
+
*/
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The release manifest (`src/cloudflare/server-release.json`).
|
|
49
|
+
* @typedef {import('../../../src/cloudflare/deployment/database-upgrade-rules.ts').DatabaseRelease} ServerRelease
|
|
50
|
+
*/
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* What a data directory was last opened with (`server.json`).
|
|
54
|
+
* @typedef {object} ServerMetadata
|
|
55
|
+
* @property {number} format
|
|
56
|
+
* @property {string} instanceId
|
|
57
|
+
* @property {string} schemaHash
|
|
58
|
+
* @property {number} schemaVersion
|
|
59
|
+
* @property {string} runtimeVersion
|
|
60
|
+
* @property {number} serverRevision
|
|
61
|
+
*/
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* An open data directory. `close` disposes Miniflare, then releases the lock.
|
|
65
|
+
* @typedef {object} LocalRuntime
|
|
66
|
+
* @property {import('miniflare').Miniflare} mf
|
|
67
|
+
* @property {LocalD1Database} db
|
|
68
|
+
* @property {string} dataDir
|
|
69
|
+
* @property {string} origin
|
|
70
|
+
* @property {(id: string) => Promise<boolean>} revoke
|
|
71
|
+
* @property {(kind: string) => Promise<number>} alert Pushes a host alert; returns how many devices received it.
|
|
72
|
+
* @property {Promise<never>} failed Rejects when a serving runtime stops responding; never settles for administrative runtimes.
|
|
73
|
+
* @property {number} crashes Unexpected workerd exits Miniflare recovered from.
|
|
74
|
+
* @property {RequestGate['request']} request Hold the result while using `mf` or `db`; a pause waits for it.
|
|
75
|
+
* @property {() => Promise<() => Promise<void>>} pause Stops workerd once running requests finish, so its files
|
|
76
|
+
* can be copied. The returned resume starts it again; a failed resume rejects `failed`.
|
|
77
|
+
* @property {() => Promise<void>} close
|
|
78
|
+
*/
|
|
79
|
+
|
|
80
|
+
/** @typedef {ReturnType<typeof createRequestGate>} RequestGate */
|
|
81
|
+
|
|
82
|
+
/** Admits requests to the runtime. Closing waits for admitted ones and holds new ones
|
|
83
|
+
* until it opens again.
|
|
84
|
+
* @param {{ hold?: number, drain?: number }} [options] Milliseconds a new request waits
|
|
85
|
+
* for a closed gate, and a closing gate waits for running requests. */
|
|
86
|
+
export function createRequestGate({ hold = 30_000, drain = 15_000 } = {}) {
|
|
87
|
+
let running = 0;
|
|
88
|
+
/** @type {Promise<void> | null} */
|
|
89
|
+
let closed = null;
|
|
90
|
+
let reopen = () => {};
|
|
91
|
+
let idle = () => {};
|
|
92
|
+
/** @param {Promise<unknown>} promise @param {number} ms */
|
|
93
|
+
const within = async (promise, ms) => {
|
|
94
|
+
/** @type {NodeJS.Timeout | undefined} */
|
|
95
|
+
let timer;
|
|
96
|
+
try { return await Promise.race([promise.then(() => true), new Promise(resolve => { timer = setTimeout(resolve, ms, false); })]); }
|
|
97
|
+
finally { clearTimeout(timer); }
|
|
98
|
+
};
|
|
99
|
+
return {
|
|
100
|
+
/** @returns {Promise<(() => void) | null>} A release, or null when the gate stayed closed too long. */
|
|
101
|
+
async request() {
|
|
102
|
+
while (closed) if (!await within(closed, hold)) return null;
|
|
103
|
+
running++;
|
|
104
|
+
let released = false;
|
|
105
|
+
return () => {
|
|
106
|
+
if (released) return;
|
|
107
|
+
released = true;
|
|
108
|
+
if (--running === 0) idle();
|
|
109
|
+
};
|
|
110
|
+
},
|
|
111
|
+
async close() {
|
|
112
|
+
if (closed) throw new Error('The runtime is already paused.');
|
|
113
|
+
closed = new Promise(resolve => { reopen = resolve; });
|
|
114
|
+
if (running) await within(new Promise(resolve => { idle = () => resolve(undefined); }), drain);
|
|
115
|
+
idle = () => {};
|
|
116
|
+
},
|
|
117
|
+
open() { closed = null; reopen(); },
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** @param {string} value */
|
|
122
|
+
const digest = value => createHash('sha256').update(value).digest('hex');
|
|
123
|
+
|
|
124
|
+
// Miniflare's default outbound service permits private networks even when the
|
|
125
|
+
// Worker uses global_fetch_strictly_public. Enforce the boundary natively for
|
|
126
|
+
// both explicit article/title fetches and any other Worker fetch (such as push).
|
|
127
|
+
/** @returns {Pick<import('miniflare').V4WorkerOptionsShape, 'outboundService' | 'serviceBindings'>} */
|
|
128
|
+
export function localNetworkOptions() {
|
|
129
|
+
const publicNetwork = { network: { allow: ['public'], deny: ['private', 'local', '100.64.0.0/10', '198.18.0.0/15', '192.0.0.0/24', '240.0.0.0/4'], tlsOptions: { trustBrowserCas: true } } };
|
|
130
|
+
return {
|
|
131
|
+
// The v5 adapter does not accept a network as outboundService. Forward
|
|
132
|
+
// through its supported hook to the same native network binding instead.
|
|
133
|
+
outboundService: async (request, runtime) => (/** @type {{ READING_FETCH: { fetch(request: import('miniflare').Request): Promise<import('miniflare').Response> } }} */ (await runtime.getBindings())).READING_FETCH.fetch(request),
|
|
134
|
+
serviceBindings: { READING_FETCH: publicNetwork },
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export async function localBuildInfo() {
|
|
139
|
+
const [schema, releaseText] = await Promise.all([
|
|
140
|
+
readFile(serverAssetPath('schema.sql'), 'utf8'),
|
|
141
|
+
readFile(serverAssetPath('server-release.json'), 'utf8'),
|
|
142
|
+
]);
|
|
143
|
+
/** @type {ServerRelease} */
|
|
144
|
+
const release = JSON.parse(releaseText);
|
|
145
|
+
return { runtimeVersion,
|
|
146
|
+
schemaHash: digest(schema), serverRevision: release.revision, release };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* @param {ServerMetadata | null | undefined} previous
|
|
151
|
+
* @param {Pick<ServerMetadata, 'schemaHash' | 'runtimeVersion' | 'serverRevision'>} expected
|
|
152
|
+
* @param {string} [dataDir] The data directory being opened; omitted when checking a backup.
|
|
153
|
+
*/
|
|
154
|
+
export function assertCompatibleLocalMetadata(previous, expected, dataDir) {
|
|
155
|
+
const compatible = previous && previous.format === 1 && Number.isSafeInteger(previous.serverRevision)
|
|
156
|
+
&& previous.serverRevision >= 1 && typeof previous.instanceId === 'string' && previous.schemaHash === expected.schemaHash
|
|
157
|
+
&& previous.serverRevision <= expected.serverRevision;
|
|
158
|
+
if (compatible && dataDir && runtimeAdvances(previous.runtimeVersion, expected.runtimeVersion)) {
|
|
159
|
+
throw new Error(`The server data in ${dataDir} was written by an older storage runtime. Stop the server and run upgrade with a new --output backup directory before starting. The update command and the Docker image do this for you.`);
|
|
160
|
+
}
|
|
161
|
+
if (!compatible || previous.runtimeVersion !== expected.runtimeVersion) {
|
|
162
|
+
throw new Error(dataDir
|
|
163
|
+
? `The server data in ${dataDir} is damaged or comes from a different Crate server version, so this version can't open it. To start fresh, choose another folder with --data-dir or move this one aside. To keep the data, run the version that created it. Don't edit server.json.`
|
|
164
|
+
: "This backup is damaged or comes from a different Crate server version, so this version can't restore it. Restore it with the version that created it.");
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Whether `recorded` is an older Miniflare version than `current`, in semver order.
|
|
169
|
+
* Anything that is not a plain semver version never advances.
|
|
170
|
+
* @param {unknown} recorded @param {string} current */
|
|
171
|
+
export function runtimeAdvances(recorded, current) {
|
|
172
|
+
const pattern = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/;
|
|
173
|
+
const [a, b] = [pattern.exec(String(recorded)), pattern.exec(current)];
|
|
174
|
+
if (!a || !b) return false;
|
|
175
|
+
for (const i of [1, 2, 3]) if (Number(a[i]) !== Number(b[i])) return Number(a[i]) < Number(b[i]);
|
|
176
|
+
// A release follows its prereleases; prerelease identifiers compare as semver specifies.
|
|
177
|
+
if (!a[4] || !b[4]) return Boolean(a[4]) && !b[4];
|
|
178
|
+
const [x, y] = [a[4].split('.'), b[4].split('.')];
|
|
179
|
+
for (let i = 0; i < Math.min(x.length, y.length); i++) {
|
|
180
|
+
const [p, q] = [String(x[i]), String(y[i])];
|
|
181
|
+
if (p === q) continue;
|
|
182
|
+
const [numericP, numericQ] = [/^\d+$/.test(p), /^\d+$/.test(q)];
|
|
183
|
+
if (numericP && numericQ) return Number(p) < Number(q);
|
|
184
|
+
return numericP === numericQ ? p < q : numericP;
|
|
185
|
+
}
|
|
186
|
+
return x.length < y.length;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Reads every current and retained file back through a new storage runtime and checks its
|
|
190
|
+
* size and SHA-256, so a runtime that cannot read the old layout fails before it owns the data.
|
|
191
|
+
* @param {LocalD1Database} db @param {LocalR2Bucket} bucket @param {string} backup */
|
|
192
|
+
async function assertReadableFiles(db, bucket, backup) {
|
|
193
|
+
const page = 64;
|
|
194
|
+
for (const [table, order] of [['files', 'portable_path'], ['file_versions', 'id']]) {
|
|
195
|
+
/** @type {unknown} */
|
|
196
|
+
let after = null;
|
|
197
|
+
for (;;) {
|
|
198
|
+
/** @type {{ results: { position: unknown, storage_key: string, hash: string, size: number }[] }} */
|
|
199
|
+
const { results } = await db.prepare(`SELECT ${order} AS position, storage_key, hash, size FROM ${table}${after === null ? '' : ` WHERE ${order} > ?1`} ORDER BY ${order} LIMIT ${page}`)
|
|
200
|
+
.bind(...(after === null ? [] : [after])).all();
|
|
201
|
+
const unreadable = await Promise.all(results.map(async row => {
|
|
202
|
+
const object = await bucket.get(row.storage_key);
|
|
203
|
+
if (!object) return true;
|
|
204
|
+
const hash = createHash('sha256');
|
|
205
|
+
let size = 0;
|
|
206
|
+
for await (const chunk of object.body) { hash.update(chunk); size += chunk.byteLength; }
|
|
207
|
+
return size !== row.size || hash.digest('hex') !== row.hash;
|
|
208
|
+
}));
|
|
209
|
+
if (unreadable.includes(true)) {
|
|
210
|
+
throw new Error(`After the storage runtime update, a stored file is missing or does not match its checksum, so the data was not upgraded and the previous release still opens it. The backup made before this check is at ${backup}.`);
|
|
211
|
+
}
|
|
212
|
+
if (results.length < page) break;
|
|
213
|
+
after = results.at(-1)?.position;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** @param {string} value */
|
|
219
|
+
export function normalizeLocalOrigin(value) {
|
|
220
|
+
const url = new URL(value);
|
|
221
|
+
const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
|
|
222
|
+
if ((url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback))
|
|
223
|
+
|| url.username || url.password || url.search || url.hash || url.pathname !== '/') {
|
|
224
|
+
throw new Error('Origin must be an HTTPS origin, or HTTP on localhost, without a path or credentials.');
|
|
225
|
+
}
|
|
226
|
+
return url.origin;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* @param {object} options
|
|
231
|
+
* @param {string} options.dataDir
|
|
232
|
+
* @param {string} [options.origin]
|
|
233
|
+
* @param {boolean} [options.administrative] Registers no Durable Objects, so no alarm runs.
|
|
234
|
+
* @param {boolean} [options.handleSignals] Keeps Miniflare's own signal handlers.
|
|
235
|
+
* @param {string} [options.upgradeBackup] Migrates the database after backing up here.
|
|
236
|
+
* @param {boolean} [options.reuseUpgradeBackup] Keeps a complete backup already at `upgradeBackup`.
|
|
237
|
+
* @param {number} [options.maxFileBytes] Largest synced file; the Worker's default when unset.
|
|
238
|
+
* @returns {Promise<LocalRuntime>}
|
|
239
|
+
*/
|
|
240
|
+
export async function openLocalRuntime({ dataDir, origin = 'http://localhost:8787', administrative = false, handleSignals = true, upgradeBackup, reuseUpgradeBackup = false, maxFileBytes }) {
|
|
241
|
+
dataDir = resolve(dataDir);
|
|
242
|
+
origin = normalizeLocalOrigin(origin);
|
|
243
|
+
const [schema, releaseText, runtimeText, worker] = await Promise.all([
|
|
244
|
+
readFile(serverAssetPath('schema.sql'), 'utf8'),
|
|
245
|
+
readFile(serverAssetPath('server-release.json'), 'utf8'),
|
|
246
|
+
readFile(serverAssetPath('worker-runtime.json'), 'utf8'),
|
|
247
|
+
readFile(workerPath, 'utf8').catch(() => {
|
|
248
|
+
throw new Error('Build the server first with npm run build:worker.');
|
|
249
|
+
}),
|
|
250
|
+
]);
|
|
251
|
+
/** @type {ServerRelease} */
|
|
252
|
+
const release = JSON.parse(releaseText);
|
|
253
|
+
/** @type {WorkerRuntimeConfig} */
|
|
254
|
+
const { compatibilityDate, compatibilityFlags, bindings, durableObjectClass, notificationRateLimit } = JSON.parse(runtimeText);
|
|
255
|
+
const unlock = await lockLocalData(dataDir);
|
|
256
|
+
// Best effort: without a record, a force-quit still leaves the manual kill.
|
|
257
|
+
const record = () => recordWorkerd(dataDir).catch(() => {});
|
|
258
|
+
/** @type {import('miniflare').Miniflare | undefined} */
|
|
259
|
+
let mf;
|
|
260
|
+
/** @param {import('miniflare').V4MiniflareOptions} options */
|
|
261
|
+
const createRuntime = options => {
|
|
262
|
+
// The CLI drains HTTP and storage even when interrupted during startup.
|
|
263
|
+
// Miniflare's synchronous exit handlers would bypass that cleanup.
|
|
264
|
+
const signals = ['SIGINT', 'SIGTERM', 'SIGHUP'];
|
|
265
|
+
const previous = new Map(signals.map(signal => [signal, process.listeners(signal)]));
|
|
266
|
+
const instance = new Miniflare(convertV4MiniflareOptions(options));
|
|
267
|
+
if (!handleSignals) for (const signal of signals) {
|
|
268
|
+
for (const listener of process.listeners(signal)) {
|
|
269
|
+
if (!/** @type {Function[]} */ (previous.get(signal)).includes(listener)) process.removeListener(signal, listener);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
return instance;
|
|
273
|
+
};
|
|
274
|
+
try {
|
|
275
|
+
const metadataPath = join(dataDir, 'server.json');
|
|
276
|
+
const previousText = await readFile(metadataPath, 'utf8').catch(error => {
|
|
277
|
+
if (error.code === 'ENOENT') return null;
|
|
278
|
+
throw error;
|
|
279
|
+
});
|
|
280
|
+
/** @type {ServerMetadata | null} */
|
|
281
|
+
const previous = previousText === null ? null : JSON.parse(previousText);
|
|
282
|
+
|
|
283
|
+
const expected = { schemaHash: digest(schema), runtimeVersion, serverRevision: release.revision };
|
|
284
|
+
// Set when upgrade opens data written by an older Miniflare, which this start verifies before recording.
|
|
285
|
+
let runtimeUpgrade = false;
|
|
286
|
+
let usedBackup = '';
|
|
287
|
+
if (previousText !== null) {
|
|
288
|
+
// Damaged metadata (`null` included) fails the same way with or without an upgrade.
|
|
289
|
+
if (!upgradeBackup || !previous) assertCompatibleLocalMetadata(previous, expected, dataDir);
|
|
290
|
+
else {
|
|
291
|
+
const current = /** @type {ServerMetadata} */ (previous);
|
|
292
|
+
if (current.schemaHash !== expected.schemaHash) assertLocalMigrationPath(current.schemaVersion, release);
|
|
293
|
+
runtimeUpgrade = runtimeAdvances(current.runtimeVersion, runtimeVersion);
|
|
294
|
+
assertCompatibleLocalMetadata({ ...current, schemaHash: expected.schemaHash, ...(runtimeUpgrade ? { runtimeVersion } : {}) }, expected, dataDir);
|
|
295
|
+
const { backupLocalServer, prepareMigrationBackup } = await import('./local-server-backup.mjs');
|
|
296
|
+
// A retried migration keeps the backup taken before its first attempt while it still holds this data.
|
|
297
|
+
usedBackup = reuseUpgradeBackup ? await prepareMigrationBackup(dataDir, upgradeBackup)
|
|
298
|
+
: await backupLocalServer(dataDir, upgradeBackup, { alreadyLocked: true });
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
if (previousText === null && (await readdir(dataDir)).some(name => !['server.lock', '.DS_Store'].includes(name))) {
|
|
303
|
+
throw new Error('This directory contains data without server.json. Restore a complete backup or choose a new empty directory.');
|
|
304
|
+
}
|
|
305
|
+
const metadata = { format: 1, instanceId: previous?.instanceId ?? randomUUID(),
|
|
306
|
+
schemaHash: digest(schema), schemaVersion: release.schemaVersion, runtimeVersion, serverRevision: release.revision };
|
|
307
|
+
const options = {
|
|
308
|
+
name: 'crate-local', modules: true, script: worker,
|
|
309
|
+
compatibilityDate, compatibilityFlags,
|
|
310
|
+
...localNetworkOptions(),
|
|
311
|
+
host: '127.0.0.1', port: 0, cf: false, telemetry: { enabled: false },
|
|
312
|
+
resourcePersistencePath: join(dataDir, 'resources'),
|
|
313
|
+
isolatedResourcePersistencePath: join(dataDir, 'isolated'),
|
|
314
|
+
bindings: { CRATE_PUBLIC_ORIGIN: origin, CRATE_DEPLOYMENT_FINGERPRINT: deploymentFingerprint({ worker, schema, release }),
|
|
315
|
+
...(maxFileBytes ? { CRATE_MAX_FILE_BYTES: String(maxFileBytes) } : {}) },
|
|
316
|
+
d1Databases: { [bindings.database]: 'crate-local-db' },
|
|
317
|
+
...(runtimeUpgrade ? { r2Buckets: { [bindings.bucket]: 'crate-local-files' } } : {}),
|
|
318
|
+
};
|
|
319
|
+
// Validate and initialize with no Durable Objects registered: overdue
|
|
320
|
+
// alarms must not execute against an unverified database or during admin.
|
|
321
|
+
mf = createRuntime(options);
|
|
322
|
+
await mf.ready;
|
|
323
|
+
await record();
|
|
324
|
+
const info = /** @type {{ serverRevision?: unknown, schemaVersion?: unknown }} */ (await (await mf.dispatchFetch(`${origin}/.well-known/crate`)).json());
|
|
325
|
+
if (info.serverRevision !== release.revision || info.schemaVersion !== release.schemaVersion) {
|
|
326
|
+
throw new Error('The Worker build is out of date. Run npm run build:worker before starting the server.');
|
|
327
|
+
}
|
|
328
|
+
/** @type {LocalD1Database} */
|
|
329
|
+
let db = await mf.getD1Database(bindings.database);
|
|
330
|
+
await assertIntactDatabase(db);
|
|
331
|
+
const { results: tables } = await db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '_cf_%'").all();
|
|
332
|
+
if (tables.length === 0) {
|
|
333
|
+
if (previous) throw new Error('The existing server database is missing. Restore a complete backup; refusing to create an empty replacement.');
|
|
334
|
+
// Our versioned schema contains no triggers or semicolons in literals.
|
|
335
|
+
// D1 batch initializes it atomically, including the schema marker.
|
|
336
|
+
await db.batch(schema.split(';').map(sql => sql.trim()).filter(Boolean).map(sql => db.prepare(sql)));
|
|
337
|
+
} else {
|
|
338
|
+
if (!tables.some(table => table.name === 'crate_schema')) throw new Error('Refusing to initialize a non-empty, unrecognized database.');
|
|
339
|
+
const marker = await db.prepare('SELECT version FROM crate_schema WHERE id = 1').first();
|
|
340
|
+
// Before any migration and before server.json records the new runtime, so a failed check
|
|
341
|
+
// leaves the data as the previous release wrote it.
|
|
342
|
+
if (runtimeUpgrade) await assertReadableFiles(db, /** @type {LocalR2Bucket} */ (/** @type {unknown} */ (await mf.getR2Bucket(bindings.bucket))), usedBackup);
|
|
343
|
+
if (upgradeBackup) await migrateLocalDatabase(db, release);
|
|
344
|
+
else if (marker?.version !== release.schemaVersion) throw new Error('Unsupported local database schema. Run the stopped-server upgrade command with a new backup directory.');
|
|
345
|
+
}
|
|
346
|
+
await writePrivateJson(metadataPath, metadata);
|
|
347
|
+
let crashes = 0;
|
|
348
|
+
/** @type {() => Promise<void>} */
|
|
349
|
+
let wakeReminders = async () => {};
|
|
350
|
+
const serving = { ...options,
|
|
351
|
+
r2Buckets: { [bindings.bucket]: 'crate-local-files' },
|
|
352
|
+
durableObjects: { [bindings.reminderAlarms]: { className: durableObjectClass, useSQLite: true } },
|
|
353
|
+
ratelimits: { [bindings.notificationRateLimiter]: { namespace_id: '1001', simple: notificationRateLimit } },
|
|
354
|
+
// Miniflare restarted a crashed workerd; reminders may have come due meanwhile.
|
|
355
|
+
unsafeHandleRuntimeRestart: async () => { crashes++; await record(); await wakeReminders(); },
|
|
356
|
+
};
|
|
357
|
+
if (!administrative) {
|
|
358
|
+
await mf.dispose();
|
|
359
|
+
mf = createRuntime(serving);
|
|
360
|
+
await mf.ready;
|
|
361
|
+
await record();
|
|
362
|
+
db = await mf.getD1Database(bindings.database);
|
|
363
|
+
}
|
|
364
|
+
let live = /** @type {import('miniflare').Miniflare} */ (mf);
|
|
365
|
+
// Miniflare types the namespace with workers types this repository does not install.
|
|
366
|
+
const alarms = async () => ({ REMINDER_ALARMS: /** @type {DurableObjectNamespace} */ (/** @type {unknown} */ (
|
|
367
|
+
await live.getDurableObjectNamespace(bindings.reminderAlarms))) });
|
|
368
|
+
let closed = false;
|
|
369
|
+
let disposed = false;
|
|
370
|
+
// Administrative runtimes register no Durable Objects, so they revoke directly.
|
|
371
|
+
/** @type {(id: string) => Promise<boolean>} */
|
|
372
|
+
const revoke = administrative ? id => revokeCredential(db, id) : async id => revokeCoordinatedCredential(await alarms(), id);
|
|
373
|
+
/** @type {(error: unknown) => void} */
|
|
374
|
+
let fail = () => {};
|
|
375
|
+
/** @type {Promise<never>} */
|
|
376
|
+
const failed = new Promise((_, reject) => { fail = reject; });
|
|
377
|
+
failed.catch(() => {});
|
|
378
|
+
/** @type {ReturnType<typeof watchRuntime> | undefined} */
|
|
379
|
+
let watchdog;
|
|
380
|
+
const watch = () => {
|
|
381
|
+
watchdog = watchRuntime({ async probe(signal) {
|
|
382
|
+
const response = await live.dispatchFetch(`${origin}/.well-known/crate`, { signal });
|
|
383
|
+
await response.arrayBuffer();
|
|
384
|
+
if (!response.ok) throw new Error(`health check returned ${response.status}`);
|
|
385
|
+
} });
|
|
386
|
+
watchdog.failed.catch(fail);
|
|
387
|
+
};
|
|
388
|
+
if (!administrative) {
|
|
389
|
+
// Otherwise only a commit or enabling Reminders arms delivery, so a reminder that
|
|
390
|
+
// came due while the server was down would wait for the next sync.
|
|
391
|
+
wakeReminders = async () => {
|
|
392
|
+
if (!await armReminderDispatcher(await alarms())) console.warn('Could not wake reminder delivery. It resumes with the next sync.');
|
|
393
|
+
};
|
|
394
|
+
await wakeReminders();
|
|
395
|
+
watch();
|
|
396
|
+
}
|
|
397
|
+
const gate = createRequestGate();
|
|
398
|
+
/** @type {(kind: string) => Promise<number>} */
|
|
399
|
+
const alert = async kind => {
|
|
400
|
+
if (administrative) throw new Error('Alerts need the serving runtime.');
|
|
401
|
+
return sendHostAlert(await alarms(), kind);
|
|
402
|
+
};
|
|
403
|
+
return { get mf() { return live; }, get db() { return db; }, dataDir, origin, revoke, alert, failed,
|
|
404
|
+
get crashes() { return crashes; },
|
|
405
|
+
request: gate.request,
|
|
406
|
+
async pause() {
|
|
407
|
+
if (administrative) return async () => {};
|
|
408
|
+
await gate.close();
|
|
409
|
+
watchdog?.close();
|
|
410
|
+
disposed = true;
|
|
411
|
+
await live.dispose();
|
|
412
|
+
return async () => {
|
|
413
|
+
try {
|
|
414
|
+
if (closed) return;
|
|
415
|
+
const next = createRuntime(serving);
|
|
416
|
+
await next.ready;
|
|
417
|
+
await record();
|
|
418
|
+
if (closed) { await next.dispose(); return; }
|
|
419
|
+
live = next;
|
|
420
|
+
db = await next.getD1Database(bindings.database);
|
|
421
|
+
disposed = false;
|
|
422
|
+
await wakeReminders();
|
|
423
|
+
watch();
|
|
424
|
+
} catch (error) {
|
|
425
|
+
fail(new Error(`The Workers runtime could not restart after a backup (${error instanceof Error ? error.message : String(error)}). Crate is stopping so its service manager can restart it.`, { cause: error }));
|
|
426
|
+
throw error;
|
|
427
|
+
} finally { gate.open(); }
|
|
428
|
+
};
|
|
429
|
+
},
|
|
430
|
+
async close() {
|
|
431
|
+
if (closed) return;
|
|
432
|
+
closed = true;
|
|
433
|
+
watchdog?.close();
|
|
434
|
+
if (!disposed) await live.dispose();
|
|
435
|
+
await unlink(join(dataDir, WORKERD_RECORD)).catch(() => {});
|
|
436
|
+
await unlock();
|
|
437
|
+
} };
|
|
438
|
+
} catch (error) {
|
|
439
|
+
await mf?.dispose();
|
|
440
|
+
await unlink(join(dataDir, WORKERD_RECORD)).catch(() => {});
|
|
441
|
+
await unlock();
|
|
442
|
+
throw error;
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/** Refuses to serve, migrate or administer a damaged database. Recovery is a complete
|
|
447
|
+
* backup or a rebuild from devices, never an automatic repair or reset.
|
|
448
|
+
* @param {LocalD1Database} db */
|
|
449
|
+
async function assertIntactDatabase(db) {
|
|
450
|
+
/** @type {unknown} */
|
|
451
|
+
let problem;
|
|
452
|
+
try {
|
|
453
|
+
// D1 permits quick_check but not integrity_check.
|
|
454
|
+
const { results } = await db.prepare('PRAGMA quick_check').all();
|
|
455
|
+
if (results.length !== 1 || Object.values(results[0])[0] !== 'ok') problem = results.map(row => String(Object.values(row)[0]).replace(/\s+/g, ' ')).slice(0, 3).join('; ');
|
|
456
|
+
} catch (error) { problem = error instanceof Error ? error.message : String(error); }
|
|
457
|
+
if (problem !== undefined) {
|
|
458
|
+
throw new Error(`The server database failed its integrity check (${problem}). Keep this data directory unchanged, then restore a complete backup into a new directory or rebuild from your devices; see "If the server is lost" in the self-hosting guide.`);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
// Starts Crate at login and restarts it after a failure: a launchd agent on macOS, a
|
|
2
|
+
// systemd user service on Linux. The file names exact Node and Crate paths, since
|
|
3
|
+
// version-manager shims on PATH do not work for background services.
|
|
4
|
+
import { execFile, spawn } from 'node:child_process';
|
|
5
|
+
import { mkdir, readFile, realpath, unlink, writeFile } from 'node:fs/promises';
|
|
6
|
+
import { homedir } from 'node:os';
|
|
7
|
+
import { dirname, join, relative, isAbsolute } from 'node:path';
|
|
8
|
+
import { promisify } from 'node:util';
|
|
9
|
+
|
|
10
|
+
const SERVICE_LABEL = 'local.crate.server';
|
|
11
|
+
const SYSTEMD_UNIT = 'crate';
|
|
12
|
+
const execFileAsync = promisify(execFile);
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* @typedef {object} ServiceEnvironment
|
|
16
|
+
* @property {NodeJS.Platform} [platform]
|
|
17
|
+
* @property {string} [home]
|
|
18
|
+
* @property {number} [uid]
|
|
19
|
+
* @property {(command: string, args: string[]) => Promise<{ stdout: string }>} [run]
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/** @param {ServiceEnvironment} [environment] */
|
|
23
|
+
function resolveEnvironment({ platform = process.platform, home = homedir(), uid = process.getuid?.() ?? 0, run = execFileAsync } = {}) {
|
|
24
|
+
return { platform, home, uid, run };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Where the service definition and its log live, or null where Crate cannot install one.
|
|
28
|
+
* @param {ServiceEnvironment} [environment] */
|
|
29
|
+
export function servicePaths(environment) {
|
|
30
|
+
const { platform, home } = resolveEnvironment(environment);
|
|
31
|
+
if (platform === 'darwin') return { file: join(home, 'Library/LaunchAgents', `${SERVICE_LABEL}.plist`), log: join(home, 'Library/Logs/crate-server.log') };
|
|
32
|
+
if (platform === 'linux') return { file: join(home, '.config/systemd/user', `${SYSTEMD_UNIT}.service`), log: join(home, '.local/state/crate/server.log') };
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** @param {string} value */
|
|
37
|
+
const xml = value => value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
38
|
+
/** systemd splits ExecStart on spaces; quote each argument. @param {string} value */
|
|
39
|
+
const quoted = value => `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* @typedef {object} ServiceCommand
|
|
43
|
+
* @property {string} node Absolute Node executable.
|
|
44
|
+
* @property {string} script Absolute Crate CLI script.
|
|
45
|
+
* @property {string} dataDir
|
|
46
|
+
* @property {boolean} keepAwake
|
|
47
|
+
* @property {string} [maxFileSize] --max-file-size in MB, forwarded to start.
|
|
48
|
+
* @property {string} log
|
|
49
|
+
*/
|
|
50
|
+
|
|
51
|
+
/** @param {ServiceCommand} command */
|
|
52
|
+
function serviceArguments({ node, script, dataDir, keepAwake, maxFileSize }) {
|
|
53
|
+
return [node, script, 'start', '--data-dir', dataDir, ...(keepAwake ? ['--keep-awake'] : []), ...(maxFileSize ? ['--max-file-size', maxFileSize] : [])];
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** PATH lets Crate find cloudflared or tailscale from a service. @param {string} node */
|
|
57
|
+
const servicePath = node => [...new Set([dirname(node), '/opt/homebrew/bin', '/usr/local/bin', '/usr/bin', '/bin'])].join(':');
|
|
58
|
+
|
|
59
|
+
/** @param {ServiceCommand} command */
|
|
60
|
+
export function launchdPlist(command) {
|
|
61
|
+
const args = serviceArguments(command).map(arg => `\t\t<string>${xml(arg)}</string>`).join('\n');
|
|
62
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
63
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
64
|
+
<plist version="1.0">
|
|
65
|
+
<dict>
|
|
66
|
+
<key>Label</key>
|
|
67
|
+
<string>${SERVICE_LABEL}</string>
|
|
68
|
+
<key>ProgramArguments</key>
|
|
69
|
+
<array>
|
|
70
|
+
${args}
|
|
71
|
+
</array>
|
|
72
|
+
<key>EnvironmentVariables</key>
|
|
73
|
+
<dict>
|
|
74
|
+
<key>PATH</key>
|
|
75
|
+
<string>${xml(servicePath(command.node))}</string>
|
|
76
|
+
</dict>
|
|
77
|
+
<key>RunAtLoad</key>
|
|
78
|
+
<true/>
|
|
79
|
+
<key>KeepAlive</key>
|
|
80
|
+
<dict>
|
|
81
|
+
<key>SuccessfulExit</key>
|
|
82
|
+
<false/>
|
|
83
|
+
</dict>
|
|
84
|
+
<key>ThrottleInterval</key>
|
|
85
|
+
<integer>30</integer>
|
|
86
|
+
<key>StandardOutPath</key>
|
|
87
|
+
<string>${xml(command.log)}</string>
|
|
88
|
+
<key>StandardErrorPath</key>
|
|
89
|
+
<string>${xml(command.log)}</string>
|
|
90
|
+
</dict>
|
|
91
|
+
</plist>
|
|
92
|
+
`;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** @param {ServiceCommand} command */
|
|
96
|
+
export function systemdUnit(command) {
|
|
97
|
+
return `[Unit]
|
|
98
|
+
Description=Crate server
|
|
99
|
+
|
|
100
|
+
[Service]
|
|
101
|
+
ExecStart=${serviceArguments(command).map(quoted).join(' ')}
|
|
102
|
+
Environment=${quoted(`PATH=${servicePath(command.node)}`)}
|
|
103
|
+
StandardOutput=append:${command.log}
|
|
104
|
+
StandardError=append:${command.log}
|
|
105
|
+
Restart=on-failure
|
|
106
|
+
RestartSec=30
|
|
107
|
+
TimeoutStopSec=30
|
|
108
|
+
|
|
109
|
+
[Install]
|
|
110
|
+
WantedBy=default.target
|
|
111
|
+
`;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** macOS asks before a background service reads these folders, so a service there fails.
|
|
115
|
+
* @param {string} path @param {ServiceEnvironment} [environment] */
|
|
116
|
+
export function protectedMacFolder(path, environment) {
|
|
117
|
+
const { platform, home } = resolveEnvironment(environment);
|
|
118
|
+
if (platform !== 'darwin') return null;
|
|
119
|
+
for (const folder of ['Documents', 'Desktop', 'Downloads']) {
|
|
120
|
+
const inside = relative(join(home, folder), path);
|
|
121
|
+
if (!inside.startsWith('..') && !isAbsolute(inside)) return folder;
|
|
122
|
+
}
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Whether a service is installed, and for which data directory, and whether it runs.
|
|
127
|
+
* @param {ServiceEnvironment} [environment]
|
|
128
|
+
* @returns {Promise<{ supported: boolean, installed: boolean, running: boolean, keepAwake: boolean, dataDir: string | null, file: string | null, log: string | null }>} */
|
|
129
|
+
export async function serviceState(environment) {
|
|
130
|
+
const env = resolveEnvironment(environment);
|
|
131
|
+
const paths = servicePaths(env);
|
|
132
|
+
if (!paths) return { supported: false, installed: false, running: false, keepAwake: false, dataDir: null, file: null, log: null };
|
|
133
|
+
let text;
|
|
134
|
+
try { text = await readFile(paths.file, 'utf8'); }
|
|
135
|
+
catch (error) { if (error.code === 'ENOENT') return { supported: true, installed: false, running: false, keepAwake: false, dataDir: null, ...paths }; throw error; }
|
|
136
|
+
const dataDir = env.platform === 'darwin'
|
|
137
|
+
? text.match(/<string>--data-dir<\/string>\s*<string>([^<]*)<\/string>/)?.[1]?.replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&') ?? null
|
|
138
|
+
: text.match(/"--data-dir" "((?:[^"\\]|\\.)*)"/)?.[1]?.replace(/\\(.)/g, '$1') ?? null;
|
|
139
|
+
let running = false;
|
|
140
|
+
try {
|
|
141
|
+
if (env.platform === 'darwin') running = /\bstate = running\b/.test((await env.run('launchctl', ['print', `gui/${env.uid}/${SERVICE_LABEL}`])).stdout);
|
|
142
|
+
else running = (await env.run('systemctl', ['--user', 'is-active', SYSTEMD_UNIT])).stdout.trim() === 'active';
|
|
143
|
+
} catch { /* Not loaded, or not active: both exit non-zero. */ }
|
|
144
|
+
return { supported: true, installed: true, running, keepAwake: text.includes('--keep-awake'), dataDir, ...paths };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Loads the installed service, which starts Crate. @param {ServiceEnvironment} [environment] */
|
|
148
|
+
export async function startService(environment) {
|
|
149
|
+
const env = resolveEnvironment(environment);
|
|
150
|
+
const paths = /** @type {{ file: string }} */ (servicePaths(env));
|
|
151
|
+
if (env.platform === 'darwin') await env.run('launchctl', ['bootstrap', `gui/${env.uid}`, paths.file]);
|
|
152
|
+
else await env.run('systemctl', ['--user', 'start', SYSTEMD_UNIT]);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Stops Crate cleanly; launchd and systemd send SIGTERM and wait. @param {ServiceEnvironment} [environment] */
|
|
156
|
+
export async function stopService(environment) {
|
|
157
|
+
const env = resolveEnvironment(environment);
|
|
158
|
+
try {
|
|
159
|
+
if (env.platform === 'darwin') await env.run('launchctl', ['bootout', `gui/${env.uid}/${SERVICE_LABEL}`]);
|
|
160
|
+
else await env.run('systemctl', ['--user', 'stop', SYSTEMD_UNIT]);
|
|
161
|
+
} catch { /* Already stopped. */ }
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Writes the service for this data directory, replacing an earlier one, and starts it.
|
|
165
|
+
* @param {{ dataDir: string, keepAwake: boolean, maxFileSize?: string, node?: string, script?: string }} options
|
|
166
|
+
* @param {ServiceEnvironment} [environment]
|
|
167
|
+
* @returns {Promise<{ file: string, log: string }>} */
|
|
168
|
+
export async function installService({ dataDir, keepAwake, maxFileSize, node = process.execPath, script = process.argv[1] }, environment) {
|
|
169
|
+
const env = resolveEnvironment(environment);
|
|
170
|
+
const paths = servicePaths(env);
|
|
171
|
+
if (!paths) throw new Error('Starting Crate automatically is supported on macOS and Linux. On Windows, use Docker Desktop.');
|
|
172
|
+
const resolvedScript = await realpath(script);
|
|
173
|
+
const folder = protectedMacFolder(resolvedScript, env) ?? protectedMacFolder(dataDir, env);
|
|
174
|
+
if (folder) throw new Error(`macOS blocks background services from reading ${folder}. Install Crate with npm install -g @kaanbiryol/crate-server, or move the checkout and data out of ${folder}.`);
|
|
175
|
+
const command = { node, script: resolvedScript, dataDir, keepAwake, maxFileSize, log: paths.log };
|
|
176
|
+
await mkdir(dirname(paths.file), { recursive: true });
|
|
177
|
+
await mkdir(dirname(paths.log), { recursive: true, mode: 0o700 });
|
|
178
|
+
await stopService(env);
|
|
179
|
+
await writeFile(paths.file, env.platform === 'darwin' ? launchdPlist(command) : systemdUnit(command), { mode: 0o644 });
|
|
180
|
+
if (env.platform === 'darwin') await startService(env);
|
|
181
|
+
else {
|
|
182
|
+
await env.run('systemctl', ['--user', 'daemon-reload']);
|
|
183
|
+
await env.run('systemctl', ['--user', 'enable', '--now', SYSTEMD_UNIT]);
|
|
184
|
+
}
|
|
185
|
+
return paths;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** @param {ServiceEnvironment} [environment] @returns {Promise<boolean>} Whether one was installed. */
|
|
189
|
+
export async function uninstallService(environment) {
|
|
190
|
+
const env = resolveEnvironment(environment);
|
|
191
|
+
const paths = servicePaths(env);
|
|
192
|
+
if (!paths) return false;
|
|
193
|
+
await stopService(env);
|
|
194
|
+
if (env.platform === 'linux') await env.run('systemctl', ['--user', 'disable', SYSTEMD_UNIT]).catch(() => {});
|
|
195
|
+
try { await unlink(paths.file); }
|
|
196
|
+
catch (error) { if (error.code === 'ENOENT') return false; throw error; }
|
|
197
|
+
if (env.platform === 'linux') await env.run('systemctl', ['--user', 'daemon-reload']).catch(() => {});
|
|
198
|
+
return true;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Keeps a Mac from idle sleep while this process serves. `-w` ends caffeinate with it.
|
|
202
|
+
* @param {{ platform?: NodeJS.Platform, start?: typeof spawn }} [options] @returns {boolean} */
|
|
203
|
+
export function keepAwake({ platform = process.platform, start = spawn } = {}) {
|
|
204
|
+
if (platform !== 'darwin') return false;
|
|
205
|
+
const child = start('caffeinate', ['-i', '-w', String(process.pid)], { stdio: 'ignore' });
|
|
206
|
+
child.on('error', () => console.warn('Could not keep this Mac awake: caffeinate did not start.'));
|
|
207
|
+
child.unref();
|
|
208
|
+
return true;
|
|
209
|
+
}
|