Spaces:
Sleeping
Sleeping
Deploy GitHub commit f81680443de94cdbd778f9e30e47e2d2392c100b
Browse filesFiles changed (42)
- .env.example+10-2
- .github/workflows/deploy-hf.yml+23-3
- .github/workflows/validation.yml+21-48
- Dockerfile+32-4
- README.md+14-8
- apps/server/src/app.ts+24-2
- apps/server/src/config/environment.ts+95-31
- apps/server/src/config/environment.unit.test.ts+78-2
- apps/server/src/database/create-database.ts+16-12
- apps/server/src/database/migration-runner.integration.test.ts+4-8
- apps/server/src/database/sqlite-system-database.ts+46-4
- apps/server/src/database/transaction-runner.integration.test.ts+5-1
- apps/server/src/http/routes.integration.test.ts+5-3
- apps/server/src/index.ts+24-1
- apps/server/src/observability/operational-metrics.tsAdded+84
- apps/server/src/observability/operational-metrics.unit.test.tsAdded+35
- apps/server/src/startup/bootstrap-database.tsAdded+44
- apps/server/src/startup/database-bootstrap.tsAdded+72
- apps/server/src/startup/database-bootstrap.unit.test.tsAdded+144
- apps/server/src/startup/database-path.tsAdded+91
- apps/server/src/startup/database-path.unit.test.tsAdded+109
- apps/server/src/startup/legacy-database.integration.test.tsAdded+42
- apps/server/src/startup/litestream-restorer.tsAdded+50
- apps/server/src/startup/litestream-restorer.unit.test.tsAdded+42
- apps/server/src/system/runtime-witness-service.tsAdded+56
- apps/server/src/system/runtime-witness.integration.test.tsAdded+84
- docker/entrypoint.shAdded+14
- docker/litestream.ymlAdded+14
- docs/architecture/BACKUP_AND_RECOVERY.md+7-3
- docs/architecture/DATABASE_MIGRATION_STRATEGY.md+9-2
- docs/architecture/DEPLOYMENT.md+14-7
- docs/architecture/FOUNDATION.md+1-1
- docs/architecture/IMPLEMENTATION_SEQUENCE.md+2-1
- docs/architecture/LOCAL_DEVELOPMENT.md+2-1
- docs/architecture/OBJECT_STORAGE_V1.md+2-2
- docs/architecture/PHASE3A_PERSISTENCE_KERNEL.md+23-11
- docs/architecture/TECHNICAL_ARCHITECTURE_V1.md+19-14
- docs/decisions/0017-sqlite-single-space-mvp.md+2-2
- docs/decisions/0026-backup-recovery-and-scaling-exit.md+4
- docs/decisions/0027-local-sqlite-with-hf-s3-replication.mdAdded+81
- playwright.config.ts+3-4
- scripts/run-docker-litestream-recovery.shAdded+227
12345671 unmodified line91011NODE_ENV=developmentPORT=7860DATA_DIR=/dataDATABASE_URL=file:/data/database/oloka-dev.dbAPP_VERSION=0.1.0GIT_COMMIT_SHA=localBUILD_TIMESTAMP=development1 unmodified line# Required before upgrading any existing database. Generate 32 random bytes and# encode them as canonical unpadded base64url; store the value only as a secret.# OLOKA_APP_KEY=1234567891011121 unmodified line141516171819NODE_ENV=developmentPORT=7860DATABASE_PATH=/absolute/local/path/oloka.dbOBJECT_STORAGE_ROOT=/absolute/persistent/object-storageHF_S3_ENDPOINT=https://s3.hf.co/phucsdHF_S3_REGION=us-east-1HF_S3_BUCKET=oloka-video-dev-dataHF_S3_SQLITE_PREFIX=sqlite-replica/devOLOKA_DATABASE_BOOTSTRAP_MODE=fresh-if-replica-missingAPP_VERSION=0.1.0GIT_COMMIT_SHA=localBUILD_TIMESTAMP=development1 unmodified line# Required before upgrading any existing database. Generate 32 random bytes and# encode them as canonical unpadded base64url; store the value only as a secret.# OLOKA_APP_KEY=# Required only for the production Litestream process. Store values as secrets.# HF_S3_ACCESS_KEY_ID=# HF_S3_SECRET_ACCESS_KEY=
35 unmodified lines3637383940414243444535 unmodified linesapi = HfApi(token=os.environ["HF_TOKEN"])repo_id = "phucsd/Oloka-Video-Dev"secret_names = set(api.get_space_secrets(repo_id))if "OLOKA_APP_KEY" not in secret_names:raise RuntimeError("Required Space secret OLOKA_APP_KEY is not configured")variables = {"NODE_ENV": "development","GIT_COMMIT_SHA": os.environ["GITHUB_SHA"],"BUILD_TIMESTAMP": datetime.now(UTC).isoformat().replace("+00:00", "Z"),}35 unmodified lines36373839404142434445464748495051525354555657585960616263646535 unmodified linesapi = HfApi(token=os.environ["HF_TOKEN"])repo_id = "phucsd/Oloka-Video-Dev"secret_names = set(api.get_space_secrets(repo_id))required_secret_names = {"OLOKA_APP_KEY","HF_S3_ACCESS_KEY_ID","HF_S3_SECRET_ACCESS_KEY",}missing_secret_names = required_secret_names - secret_namesif missing_secret_names:raise RuntimeError("Required Space secret names are not configured: "+ ", ".join(sorted(missing_secret_names)))space_variable_names = set(api.get_space_variables(repo_id))if "OLOKA_DATABASE_BOOTSTRAP_MODE" not in space_variable_names:raise RuntimeError("Required Space variable OLOKA_DATABASE_BOOTSTRAP_MODE is not configured")variables = {"NODE_ENV": "production","DATABASE_PATH": "/var/lib/oloka/database/oloka.db","OBJECT_STORAGE_ROOT": "/data","HF_S3_ENDPOINT": "https://s3.hf.co/phucsd","HF_S3_REGION": "us-east-1","HF_S3_BUCKET": "oloka-video-dev-data","HF_S3_SQLITE_PREFIX": "sqlite-replica/dev","GIT_COMMIT_SHA": os.environ["GITHUB_SHA"],"BUILD_TIMESTAMP": datetime.now(UTC).isoformat().replace("+00:00", "Z"),}
36 unmodified lines3738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878836 unmodified lines--build-arg GIT_COMMIT_SHA=${GITHUB_SHA} \--build-arg BUILD_TIMESTAMP=$(date -u +%Y-%m-%dT%H:%M:%SZ) \-t oloka-video:${GITHUB_SHA} .- name: Verify production image restart persistenceenv:OLOKA_APP_KEY: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAArun: |volume="oloka-video-smoke-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"first="oloka-video-first-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"second="oloka-video-second-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"cleanup() {docker rm -f "$first" "$second" >/dev/null 2>&1 || truedocker volume rm "$volume" >/dev/null 2>&1 || true}trap cleanup EXITdocker volume create "$volume" >/dev/nulldocker run -d --name "$first" -p 17860:7860 \-e OLOKA_APP_KEY="$OLOKA_APP_KEY" \-v "$volume:/data" oloka-video:${GITHUB_SHA} >/dev/nullfor attempt in $(seq 1 30); docurl --fail --silent http://127.0.0.1:17860/api/ready && breaksleep 1donecurl --fail http://127.0.0.1:17860/api/healthcurl --fail http://127.0.0.1:17860/api/readytest "$(curl --fail --silent http://127.0.0.1:17860/api/version | jq -r .gitCommitSha)" = "$GITHUB_SHA"docker stop "$first" >/dev/nulldocker rm "$first" >/dev/nulldocker run -d --name "$second" -p 17860:7860 \-e OLOKA_APP_KEY="$OLOKA_APP_KEY" \-v "$volume:/data" oloka-video:${GITHUB_SHA} >/dev/nullfor attempt in $(seq 1 30); docurl --fail --silent http://127.0.0.1:17860/api/ready && breaksleep 1donecurl --fail http://127.0.0.1:17860/api/healthcurl --fail http://127.0.0.1:17860/api/readytest "$(curl --fail --silent http://127.0.0.1:17860/api/version | jq -r .gitCommitSha)" = "$GITHUB_SHA"docker exec "$second" node --input-type=module -e "import { access, mkdir, rm, writeFile } from 'node:fs/promises';import { DatabaseSync } from 'node:sqlite';const db = new DatabaseSync('/data/database/oloka-dev.db', { readOnly: true });const ledger = db.prepare('SELECT version, COUNT(*) AS count FROM schema_migrations GROUP BY version ORDER BY version').all();db.close();if (JSON.stringify(ledger) !== JSON.stringify([{ version: 1, count: 1 }, { version: 2, count: 1 }])) throw new Error('migration ledger replayed');await access('/data/database/oloka-dev.db-wal');await access('/data/database/oloka-dev.db-shm');const probe = '/data/backups/ci-write-test';await mkdir(probe, { recursive: true });await writeFile(probe + '/probe', 'ok', 'utf8');await rm(probe, { recursive: true });"36 unmodified lines3738394041424344454647484950515253545556575859606136 unmodified lines--build-arg GIT_COMMIT_SHA=${GITHUB_SHA} \--build-arg BUILD_TIMESTAMP=$(date -u +%Y-%m-%dT%H:%M:%SZ) \-t oloka-video:${GITHUB_SHA} .- name: Verify production image durability contractrun: |test "$(docker run --rm --entrypoint node oloka-video:${GITHUB_SHA} --version)" = "v22.16.0"test "$(docker run --rm --entrypoint litestream oloka-video:${GITHUB_SHA} version)" = "0.5.11"test "$(docker image inspect oloka-video:${GITHUB_SHA} --format '{{.Config.User}}')" = "1000:1000"test "$(docker image inspect oloka-video:${GITHUB_SHA} --format '{{index .Config.Labels "org.oloka.litestream.version"}}')" = "0.5.11"test "$(docker image inspect oloka-video:${GITHUB_SHA} --format '{{index .Config.Labels "org.oloka.litestream.archive.sha256"}}')" = "2f80fdb6b0a0ff7a116ee37adf02d3de8e977ef76e052b28a6690218f0f7ab55"docker run --rm --entrypoint sh oloka-video:${GITHUB_SHA} -c \"test ! -e /usr/bin/curl && test ! -e /usr/bin/wget && test -r /usr/share/licenses/litestream/LICENSE && ! grep -E 'access-key|secret-access-key|HF_S3_ACCESS_KEY_ID|HF_S3_SECRET_ACCESS_KEY' /etc/litestream.yml"set +emissing_output="$(docker run --rm oloka-video:${GITHUB_SHA} 2>&1)"missing_exit=$?set -etest "$missing_exit" -ne 0grep -q 'HF_S3_ACCESS_KEY_ID is required' <<<"$missing_output"! grep -q 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' <<<"$missing_output"- name: Verify MinIO replication and ephemeral local recoveryenv:RECOVERY_RUN_ID: ${{ github.run_id }}-${{ github.run_attempt }}run: bash scripts/run-docker-litestream-recovery.sh oloka-video:${GITHUB_SHA}- name: Record production image digestrun: docker image inspect oloka-video:${GITHUB_SHA} --format 'image_id={{.Id}} repo_digests={{json .RepoDigests}}'
123412 unmodified lines171819202122232425262728293031325 unmodified lines38394041# syntax=docker/dockerfile:1.7FROM node:22.16.0-bookworm-slim AS dependenciesWORKDIR /appCOPY package.json package-lock.json ./12 unmodified linesARG APP_VERSION=0.1.0ARG GIT_COMMIT_SHA=unknownARG BUILD_TIMESTAMP=unknownENV NODE_ENV=production \PORT=7860 \DATA_DIR=/data \DATABASE_URL=file:/data/database/oloka-dev.db \APP_VERSION=${APP_VERSION} \GIT_COMMIT_SHA=${GIT_COMMIT_SHA} \BUILD_TIMESTAMP=${BUILD_TIMESTAMP} \LOG_LEVEL=infoWORKDIR /appRUN mkdir -p /data/database && chown -R 1000:1000 /data /appCOPY --from=build --chown=1000:1000 /app/package.json /app/package-lock.json ./COPY --from=build --chown=1000:1000 /app/node_modules ./node_modulesCOPY --from=build --chown=1000:1000 /app/apps/server/dist ./apps/server/dist5 unmodified linesEXPOSE 7860HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \CMD ["node", "-e", "fetch('http://127.0.0.1:7860/api/health').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))"]CMD ["node", "apps/server/dist/index.js"]1234567891011121314151617181912 unmodified lines32333435363738394041424344454647484950515253545556575859605 unmodified lines66676869# syntax=docker/dockerfile:1.7FROM debian:bookworm-slim AS litestreamARG TARGETARCHARG LITESTREAM_VERSION=0.5.11ARG LITESTREAM_SHA256=2f80fdb6b0a0ff7a116ee37adf02d3de8e977ef76e052b28a6690218f0f7ab55RUN test "$TARGETARCH" = "amd64" && \apt-get update && apt-get install -y --no-install-recommends ca-certificates curl && \rm -rf /var/lib/apt/lists/* && \archive="litestream-${LITESTREAM_VERSION}-linux-x86_64.tar.gz" && \curl --fail --location --silent --show-error \--output "/tmp/${archive}" \"https://github.com/benbjohnson/litestream/releases/download/v${LITESTREAM_VERSION}/${archive}" && \echo "${LITESTREAM_SHA256} /tmp/${archive}" | sha256sum --check --strict && \mkdir -p /opt/litestream && \tar -xzf "/tmp/${archive}" -C /opt/litestream litestream LICENSEFROM node:22.16.0-bookworm-slim AS dependenciesWORKDIR /appCOPY package.json package-lock.json ./12 unmodified linesARG APP_VERSION=0.1.0ARG GIT_COMMIT_SHA=unknownARG BUILD_TIMESTAMP=unknownLABEL org.oloka.litestream.version="0.5.11" \org.oloka.litestream.archive.sha256="2f80fdb6b0a0ff7a116ee37adf02d3de8e977ef76e052b28a6690218f0f7ab55"ENV NODE_ENV=production \PORT=7860 \DATABASE_PATH=/var/lib/oloka/database/oloka.db \OBJECT_STORAGE_ROOT=/data \HF_S3_ENDPOINT=https://s3.hf.co/phucsd \HF_S3_REGION=us-east-1 \HF_S3_BUCKET=oloka-video-dev-data \HF_S3_SQLITE_PREFIX=sqlite-replica/dev \APP_VERSION=${APP_VERSION} \GIT_COMMIT_SHA=${GIT_COMMIT_SHA} \BUILD_TIMESTAMP=${BUILD_TIMESTAMP} \LOG_LEVEL=infoWORKDIR /appRUN mkdir -p /var/lib/oloka/database /data /etc /usr/share/licenses/litestream && \chown -R 1000:1000 /var/lib/oloka /data /appCOPY --from=litestream /opt/litestream/litestream /usr/local/bin/litestreamCOPY --from=litestream /opt/litestream/LICENSE /usr/share/licenses/litestream/LICENSECOPY docker/litestream.yml /etc/litestream.ymlCOPY docker/entrypoint.sh /usr/local/bin/oloka-entrypointRUN chmod 0555 /usr/local/bin/litestream /usr/local/bin/oloka-entrypoint && \chmod 0444 /etc/litestream.yml /usr/share/licenses/litestream/LICENSECOPY --from=build --chown=1000:1000 /app/package.json /app/package-lock.json ./COPY --from=build --chown=1000:1000 /app/node_modules ./node_modulesCOPY --from=build --chown=1000:1000 /app/apps/server/dist ./apps/server/dist5 unmodified linesEXPOSE 7860HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \CMD ["node", "-e", "fetch('http://127.0.0.1:7860/api/health').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))"]ENTRYPOINT ["/usr/local/bin/oloka-entrypoint"]
32 unmodified lines333435363738394022 unmodified lines63646566676869707172737410 unmodified lines858687888990919232 unmodified linesThe API listens on `http://localhost:7860`; Vite serves the local frontend on `http://localhost:5173` and proxies `/api` to the backend. On Windows, override the Linux online defaults:```powershell$env:DATA_DIR = "$PWD\.data"$env:DATABASE_URL = "file:$($PWD.Path.Replace('\','/'))/.data/database/oloka-dev.db"npm run dev```22 unmodified lines--build-arg BUILD_TIMESTAMP=$(date -u +%Y-%m-%dT%H:%M:%SZ) \-t oloka-video:dev .docker run --rm -p 7860:7860 \-e OLOKA_APP_KEY="$OLOKA_APP_KEY" \-v oloka-video-data:/data oloka-video:dev```The named volume is mounted at `/data`; the development SQLite database is created at `/data/database/oloka-dev.db`. The process runs as UID `1000`.## Verify the service10 unmodified lines1. Create the Docker Space `phucsd/Oloka-Video-Dev` and select Docker SDK.2. Configure persistent storage so Hugging Face mounts it at `/data`.3. In the GitHub repository, open **Settings → Secrets and variables → Actions** and add a repository secret named `HF_TOKEN`. Use a Hugging Face token with write access to the target Space.4. Push a validated change to `develop`. `.github/workflows/deploy-hf.yml` runs the full validation workflow and only pushes to the Space after it succeeds.5. Open the Space **Logs** tab to view Docker build logs and structured runtime logs. The public application is available at `https://phucsd-oloka-video-dev.hf.space` after the Space reaches `RUNNING`.No token belongs in `.env`, Git history, Docker build arguments, or the Space repository.32 unmodified lines33343536373839404122 unmodified lines6465666768697071727374757677787910 unmodified lines90919293949596979832 unmodified linesThe API listens on `http://localhost:7860`; Vite serves the local frontend on `http://localhost:5173` and proxies `/api` to the backend. On Windows, override the Linux online defaults:```powershell$env:OBJECT_STORAGE_ROOT = "$PWD\.data\objects"$env:DATABASE_PATH = "$PWD\.data\local\oloka-dev.db"$env:OLOKA_DATABASE_BOOTSTRAP_MODE = "fresh-if-replica-missing"npm run dev```22 unmodified lines--build-arg BUILD_TIMESTAMP=$(date -u +%Y-%m-%dT%H:%M:%SZ) \-t oloka-video:dev .bash scripts/run-docker-litestream-recovery.sh oloka-video:dev```The recovery harness uses pinned MinIO fixtures, replaces the local databasevolume three times, and preserves only its test replica/object volumes betweenboots. The production image runs as UID `1000`, keeps the live database at`/var/lib/oloka/database/oloka.db`, and reserves `/data` for persistent objectsand backup artifacts. A manual container run must supply explicit bootstrapmode plus S3 credentials through environment variables; never place them in theimage or YAML.## Verify the service10 unmodified lines1. Create the Docker Space `phucsd/Oloka-Video-Dev` and select Docker SDK.2. Configure persistent storage so Hugging Face mounts it at `/data`.3. In the GitHub repository, open **Settings → Secrets and variables → Actions** and add a repository secret named `HF_TOKEN`. Use a Hugging Face token with write access to the target Space.4. Configure Space secrets `OLOKA_APP_KEY`, `HF_S3_ACCESS_KEY_ID`, and `HF_S3_SECRET_ACCESS_KEY`. Configure the non-secret Space variable `OLOKA_DATABASE_BOOTSTRAP_MODE` only during the separately approved cutover gate.5. Push a validated change to `develop`. `.github/workflows/deploy-hf.yml` runs the full validation workflow and only uploads after all required secret names and the explicit bootstrap variable exist.6. Open the Space **Logs** tab to view Docker build logs and structured runtime logs. The public application is available at `https://phucsd-oloka-video-dev.hf.space` after the Space reaches `RUNNING`.No token belongs in `.env`, Git history, Docker build arguments, or the Space repository.
5 unmodified lines6789101112131415161718192021222324252627282930313233343536373839404130 unmodified lines72737475765 unmodified lines} from "@oloka/contracts";import Fastify, { type FastifyInstance } from "fastify";import { resolve } from "node:path";import type { AppEnvironment } from "./config/environment.js";import { createDatabase } from "./database/create-database.js";import { FilesystemObjectStorage } from "./storage/filesystem-object-storage.js";import { HealthService } from "./system/health-service.js";import { ReadinessService } from "./system/readiness-service.js";import { VersionService } from "./system/version-service.js";export interface BuildApplicationOptions {environment: AppEnvironment;serveFrontend?: boolean;}export async function buildApplication(options: BuildApplicationOptions,): Promise<FastifyInstance> {const { environment } = options;const app = Fastify({logger:environment.logLevel === "silent"? false: { level: environment.logLevel },});const database = await createDatabase(environment);try {await database.migrate();} catch (error) {await database.close();throw error;}const storage = new FilesystemObjectStorage(environment.dataDir);const initialStorageState = await storage.checkReadiness();if (initialStorageState.status !== "ready") {await database.close();30 unmodified linesawait Promise.all([storage.close(), database.close()]);});return app;}5 unmodified lines67891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606130 unmodified lines929394959697985 unmodified lines} from "@oloka/contracts";import Fastify, { type FastifyInstance } from "fastify";import { resolve } from "node:path";import { performance } from "node:perf_hooks";import type { AppEnvironment } from "./config/environment.js";import { createDatabase } from "./database/create-database.js";import { FilesystemObjectStorage } from "./storage/filesystem-object-storage.js";import { HealthService } from "./system/health-service.js";import { ReadinessService } from "./system/readiness-service.js";import { VersionService } from "./system/version-service.js";import { RuntimeWitnessService } from "./system/runtime-witness-service.js";import { SystemClock } from "./kernel/clock.js";import { OperationalMetrics } from "./observability/operational-metrics.js";export interface BuildApplicationOptions {environment: AppEnvironment;serveFrontend?: boolean;metrics?: OperationalMetrics;}export async function buildApplication(options: BuildApplicationOptions,): Promise<FastifyInstance> {const { environment } = options;const startupStartedAt = performance.now();const metrics = options.metrics ?? new OperationalMetrics();const app = Fastify({logger:environment.logLevel === "silent"? false: { level: environment.logLevel },});const database = await createDatabase(environment, metrics);try {await database.migrate();const runtimeWitnessUpdate = new RuntimeWitnessService(database.transactions,new SystemClock(),).record(environment.gitCommitSha);app.log.info({event: "deployment.runtime.updated",startupCount: runtimeWitnessUpdate.witness.startupCount,metadataVersion: runtimeWitnessUpdate.metadataVersion,buildSha: runtimeWitnessUpdate.witness.lastBuildSha,},"database runtime witness recorded",);} catch (error) {await database.close();throw error;}const storage = new FilesystemObjectStorage(environment.objectStorageRoot);const initialStorageState = await storage.checkReadiness();if (initialStorageState.status !== "ready") {await database.close();30 unmodified linesawait Promise.all([storage.close(), database.close()]);});metrics.observe("startup", performance.now() - startupStartedAt);return app;}
1234567891011121314151617181920212223242526272829303 unmodified lines343536373839404142434445464748495051525354import { z } from "zod";import { decodeApplicationKey } from "../kernel/app-key.js";const environmentSchema = z.object({NODE_ENV: z.enum(["development", "test", "production"]).default("development"),PORT: z.coerce.number().int().min(1).max(65_535).default(7860),DATA_DIR: z.string().min(1).default("/data"),DATABASE_URL: z.string().min(1).optional(),APP_VERSION: z.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/).default("0.1.0"),GIT_COMMIT_SHA: z.string().min(1).default("local"),BUILD_TIMESTAMP: z.string().min(1).default("development"),LOG_LEVEL: z.enum(["fatal", "error", "warn", "info", "debug", "trace", "silent"]).default("info"),OLOKA_APP_KEY: z.string().optional(),});export interface AppEnvironment {nodeEnv: "development" | "test" | "production";port: number;dataDir: string;databaseUrl: string;appVersion: string;gitCommitSha: string;buildTimestamp: string;3 unmodified linesexport function parseEnvironment(input: NodeJS.ProcessEnv): AppEnvironment {const parsed = environmentSchema.parse(input);const databaseUrl =parsed.DATABASE_URL ?? `file:${parsed.DATA_DIR}/database/oloka-dev.db`;if (!databaseUrl.startsWith("file:") &&!databaseUrl.startsWith("postgresql://")) {throw new Error("DATABASE_URL must use file: or postgresql://");}return {nodeEnv: parsed.NODE_ENV,port: parsed.PORT,dataDir: parsed.DATA_DIR,databaseUrl,appVersion: parsed.APP_VERSION,gitCommitSha: parsed.GIT_COMMIT_SHA,buildTimestamp: parsed.BUILD_TIMESTAMP,12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394953 unmodified lines99100101102103104105106107108109110111112113114115116117118import { z } from "zod";import { decodeApplicationKey } from "../kernel/app-key.js";const bootstrapModeSchema = z.enum(["fresh-if-replica-missing","restore-required",]);const environmentSchema = z.object({NODE_ENV: z.enum(["development", "test", "production"]).default("development"),PORT: z.coerce.number().int().min(1).max(65_535).default(7860),DATABASE_PATH: z.string().min(1).default("/var/lib/oloka/database/oloka.db"),OBJECT_STORAGE_ROOT: z.string().min(1).default("/data"),HF_S3_ENDPOINT: z.url().default("https://s3.hf.co/phucsd"),HF_S3_REGION: z.string().min(1).default("us-east-1"),HF_S3_BUCKET: z.string().min(1).default("oloka-video-dev-data"),HF_S3_SQLITE_PREFIX: z.string().min(1).default("sqlite-replica/dev"),HF_S3_ACCESS_KEY_ID: z.string().min(1).optional(),HF_S3_SECRET_ACCESS_KEY: z.string().min(1).optional(),OLOKA_DATABASE_BOOTSTRAP_MODE: bootstrapModeSchema.optional(),APP_VERSION: z.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/).default("0.1.0"),GIT_COMMIT_SHA: z.string().min(1).default("local"),BUILD_TIMESTAMP: z.string().min(1).default("development"),LOG_LEVEL: z.enum(["fatal", "error", "warn", "info", "debug", "trace", "silent"]).default("info"),OLOKA_APP_KEY: z.string().optional(),}).superRefine((environment, context) => {if (environment.NODE_ENV !== "production") return;if (environment.DATABASE_PATH !== "/var/lib/oloka/database/oloka.db") {context.addIssue({code: "custom",path: ["DATABASE_PATH"],message:"DATABASE_PATH must use the canonical production-local SQLite path",});}if (environment.OBJECT_STORAGE_ROOT !== "/data") {context.addIssue({code: "custom",path: ["OBJECT_STORAGE_ROOT"],message: "OBJECT_STORAGE_ROOT must use the persistent /data mount",});}if (environment.HF_S3_SQLITE_PREFIX !== "sqlite-replica/dev") {context.addIssue({code: "custom",path: ["HF_S3_SQLITE_PREFIX"],message:"HF_S3_SQLITE_PREFIX must use the isolated production replica prefix",});}for (const key of ["OLOKA_DATABASE_BOOTSTRAP_MODE","HF_S3_ACCESS_KEY_ID","HF_S3_SECRET_ACCESS_KEY","OLOKA_APP_KEY",] as const) {if (environment[key] === undefined) {context.addIssue({code: "custom",path: [key],message: `${key} is required in production`,});}}});export type DatabaseBootstrapMode = z.infer<typeof bootstrapModeSchema>;export interface AppEnvironment {nodeEnv: "development" | "test" | "production";port: number;databasePath: string;objectStorageRoot: string;databaseBootstrapMode: DatabaseBootstrapMode;hfS3: {endpoint: string;region: string;bucket: string;sqlitePrefix: string;};appVersion: string;gitCommitSha: string;buildTimestamp: string;3 unmodified linesexport function parseEnvironment(input: NodeJS.ProcessEnv): AppEnvironment {const parsed = environmentSchema.parse(input);return {nodeEnv: parsed.NODE_ENV,port: parsed.PORT,databasePath: parsed.DATABASE_PATH,objectStorageRoot: parsed.OBJECT_STORAGE_ROOT,databaseBootstrapMode:parsed.OLOKA_DATABASE_BOOTSTRAP_MODE ?? "fresh-if-replica-missing",hfS3: {endpoint: parsed.HF_S3_ENDPOINT,region: parsed.HF_S3_REGION,bucket: parsed.HF_S3_BUCKET,sqlitePrefix: parsed.HF_S3_SQLITE_PREFIX,},appVersion: parsed.APP_VERSION,gitCommitSha: parsed.GIT_COMMIT_SHA,buildTimestamp: parsed.BUILD_TIMESTAMP,
6 unmodified lines78910111213146 unmodified lines});it("rejects an invalid application key without revealing it", () => {expect(() => parseEnvironment({ OLOKA_APP_KEY: "not+a+key" })).toThrow(/base64url/i,);});});6 unmodified lines7891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889906 unmodified lines});it("rejects an invalid application key without revealing it", () => {const secret = "not+a+key";let failure: unknown;try {parseEnvironment({ OLOKA_APP_KEY: secret });} catch (error) {failure = error;}expect(failure).toBeInstanceOf(Error);expect(String(failure)).toMatch(/base64url/i);expect(String(failure)).not.toContain(secret);});it("keeps the local SQLite database separate from persistent object storage", () => {const environment = parseEnvironment({NODE_ENV: "test",DATABASE_PATH: "/var/lib/oloka/database/oloka.db",OBJECT_STORAGE_ROOT: "/data",OLOKA_DATABASE_BOOTSTRAP_MODE: "fresh-if-replica-missing",});expect(environment).toMatchObject({databasePath: "/var/lib/oloka/database/oloka.db",objectStorageRoot: "/data",databaseBootstrapMode: "fresh-if-replica-missing",hfS3: {endpoint: "https://s3.hf.co/phucsd",region: "us-east-1",bucket: "oloka-video-dev-data",sqlitePrefix: "sqlite-replica/dev",},});});it("requires an explicit bootstrap mode and HF S3 credentials in production", () => {expect(() => parseEnvironment({ NODE_ENV: "production" })).toThrow(/OLOKA_DATABASE_BOOTSTRAP_MODE/,);expect(() =>parseEnvironment({NODE_ENV: "production",OLOKA_DATABASE_BOOTSTRAP_MODE: "restore-required",}),).toThrow(/HF_S3_ACCESS_KEY_ID/);});it("locks production SQLite to the local canonical database path", () => {expect(() =>parseEnvironment({NODE_ENV: "production",DATABASE_PATH: "/data/database/oloka.db",OLOKA_DATABASE_BOOTSTRAP_MODE: "restore-required",HF_S3_ACCESS_KEY_ID: "access-key-name",HF_S3_SECRET_ACCESS_KEY: "secret-key-value",OLOKA_APP_KEY: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",}),).toThrow(/DATABASE_PATH/);});it("rejects bootstrap booleans and unknown modes", () => {expect(() =>parseEnvironment({ OLOKA_DATABASE_BOOTSTRAP_MODE: "true" }),).toThrow(/OLOKA_DATABASE_BOOTSTRAP_MODE/);expect(() =>parseEnvironment({ OLOKA_DATABASE_BOOTSTRAP_MODE: "automatic" }),).toThrow(/OLOKA_DATABASE_BOOTSTRAP_MODE/);});it("locks production replication to the isolated production prefix", () => {expect(() =>parseEnvironment({NODE_ENV: "production",OLOKA_DATABASE_BOOTSTRAP_MODE: "restore-required",HF_S3_SQLITE_PREFIX: "qualification/sqlite-litestream/run",HF_S3_ACCESS_KEY_ID: "access-key-name",HF_S3_SECRET_ACCESS_KEY: "secret-key-value",OLOKA_APP_KEY: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",}),).toThrow(/HF_S3_SQLITE_PREFIX/);});});
12345678910111213141516171819202122import type { SystemDatabase } from "./database.js";import { SqliteSystemDatabase } from "./sqlite-system-database.js";import type { AppEnvironment } from "../config/environment.js";export async function createDatabase(environment: AppEnvironment,): Promise<SystemDatabase> {const { databaseUrl } = environment;if (databaseUrl.startsWith("file:")) {return SqliteSystemDatabase.connect(databaseUrl, {appBuildSha: environment.gitCommitSha,appKey: environment.appKey,backupRoot: `${environment.dataDir}/backups`,});}if (databaseUrl.startsWith("postgresql://")) {throw new Error("PostgreSQL adapter is not enabled in the online development foundation",);}throw new Error("Unsupported DATABASE_URL");}1234567891011121314151617181920212223242526import type { SystemDatabase } from "./database.js";import { SqliteSystemDatabase } from "./sqlite-system-database.js";import type { AppEnvironment } from "../config/environment.js";import { join } from "node:path";import { pathToFileURL } from "node:url";import type { OperationalMetrics } from "../observability/operational-metrics.js";import { prepareLocalDatabasePath } from "../startup/database-path.js";export async function createDatabase(environment: AppEnvironment,metrics?: OperationalMetrics,): Promise<SystemDatabase> {await prepareLocalDatabasePath({databasePath: environment.databasePath,objectStorageRoot: environment.objectStorageRoot,});return SqliteSystemDatabase.connect(pathToFileURL(environment.databasePath).href,{appBuildSha: environment.gitCommitSha,appKey: environment.appKey,backupRoot: join(environment.objectStorageRoot, "backups"),metrics,},);}
93 unmodified lines94959697989910010110210310410510610710810911011193 unmodified linesawait database.close();});it("treats a pre-created zero-byte database as fresh and requires no key", async () => {const directory = await mkdtemp(join(tmpdir(), "oloka-migration-"));temporaryDirectories.push(directory);const databasePath = join(directory, "database.sqlite");await writeFile(databasePath, new Uint8Array());const database = await SqliteSystemDatabase.connect(pathToFileURL(databasePath).href,);await expect(database.migrate()).resolves.toBeUndefined();expect(database.listApplicationTables()).toContain("users");await database.close();});it("creates and verifies an authenticated online backup before upgrading v1", async () => {93 unmodified lines94959697989910010110210310410510610793 unmodified linesawait database.close();});it("rejects a pre-created zero-byte database instead of treating it as fresh", async () => {const directory = await mkdtemp(join(tmpdir(), "oloka-migration-"));temporaryDirectories.push(directory);const databasePath = join(directory, "database.sqlite");await writeFile(databasePath, new Uint8Array());await expect(SqliteSystemDatabase.connect(pathToFileURL(databasePath).href),).rejects.toThrow(/zero bytes/i);});it("creates and verifies an authenticated online backup before upgrading v1", async () => {
1234569 unmodified lines1617181920218 unmodified lines303132333435363738394041424344454610 unmodified lines5758596061626364656613 unmodified lines8081828384858 unmodified lines9495969798991001 unmodified line1021031041051061071081091105 unmodified lines11611711811912012119 unmodified lines1411421431441451468 unmodified lines1551561571581591609 unmodified lines170171172173174175176177178179180181228 unmodified lines410411412import { access, mkdir, readFile, stat } from "node:fs/promises";import { dirname, join } from "node:path";import { DatabaseSync } from "node:sqlite";import { fileURLToPath } from "node:url";import type { Clock } from "../kernel/clock.js";import { SystemClock } from "../kernel/clock.js";9 unmodified linestype TransactionRunner,} from "./database.js";import { createPreMigrationBackup } from "./pre-migration-backup.js";interface MigrationAsset {version: number;8 unmodified linesbackupRoot?: string;clock?: Clock;idGenerator?: IdGenerator;}class SqliteTransactionRunner implements TransactionRunner {private activeMode: TransactionMode | undefined;constructor(private readonly database: DatabaseSync) {}run<T>(mode: TransactionMode,operation: (context: TransactionContext) => T,): T {if (this.activeMode !== undefined) {if (mode !== "read") {throw new Error("Nested write transactions are not allowed");10 unmodified linesreturn result;} catch (error) {if (this.database.isTransaction) this.database.exec("ROLLBACK");if (isSqliteBusy(error)) throw new PersistenceBusyError({ cause: error });throw error;} finally {this.activeMode = undefined;}}13 unmodified linesprivate readonly appKey: Uint8Array | undefined;private readonly backupRoot: string;private readonly idGenerator: IdGenerator;private migrationFailure: string | undefined;private expectedMigrationChecksums = new Map<number, string>();8 unmodified linesthis.backupRoot =options.backupRoot ?? join(dirname(databasePath), "..", "backups");this.idGenerator = options.idGenerator ?? new UuidIdGenerator();this.transactions = new SqliteTransactionRunner(database);}static async connect(1 unmodified lineoptions: SqliteConnectionOptions = {},): Promise<SqliteSystemDatabase> {if (!databaseUrl.startsWith("file:")) {throw new Error("The SQLite adapter requires a file: DATABASE_URL");}const databasePath = fileURLToPath(databaseUrl);await mkdir(dirname(databasePath), { recursive: true });const instance = new SqliteSystemDatabase(new DatabaseSync(databasePath),5 unmodified lines}async migrate(): Promise<void> {try {const migrations = await loadMigrationAssets();this.expectedMigrationChecksums = new Map(19 unmodified lines} catch (error) {this.migrationFailure = "Database migration verification failed";throw error;}}8 unmodified lines}checkReadiness(): Promise<DatabaseReadiness> {try {if (this.migrationFailure !== undefined) {return Promise.resolve({9 unmodified linesif (foreignKeyFailures.length > 0) {throw new Error("Foreign key verification failed");}return Promise.resolve({ status: "ready" });} catch {return Promise.resolve({status: "not_ready",message: "Database integrity verification failed",});}}228 unmodified lines/busy|locked/i.test(error.message));}12345679 unmodified lines171819202122238 unmodified lines3233343536373839404142434445464748495051525310 unmodified lines6465666768697071727374757677787913 unmodified lines939495969798998 unmodified lines1081091101111121131141151 unmodified line1171181191201211221231241251261271281291301311325 unmodified lines13813914014114214314419 unmodified lines1641651661671681691701718 unmodified lines1801811821831841851869 unmodified lines196197198199200201202203204205206207208209210211212213214215228 unmodified lines444445446447448449450451452453454import { access, mkdir, readFile, stat } from "node:fs/promises";import { dirname, join } from "node:path";import { DatabaseSync } from "node:sqlite";import { performance } from "node:perf_hooks";import { fileURLToPath } from "node:url";import type { Clock } from "../kernel/clock.js";import { SystemClock } from "../kernel/clock.js";9 unmodified linestype TransactionRunner,} from "./database.js";import { createPreMigrationBackup } from "./pre-migration-backup.js";import type { OperationalMetrics } from "../observability/operational-metrics.js";interface MigrationAsset {version: number;8 unmodified linesbackupRoot?: string;clock?: Clock;idGenerator?: IdGenerator;metrics?: OperationalMetrics;}class SqliteTransactionRunner implements TransactionRunner {private activeMode: TransactionMode | undefined;constructor(private readonly database: DatabaseSync,private readonly metrics?: OperationalMetrics,) {}run<T>(mode: TransactionMode,operation: (context: TransactionContext) => T,): T {const startedAt = performance.now();if (this.activeMode !== undefined) {if (mode !== "read") {throw new Error("Nested write transactions are not allowed");10 unmodified linesreturn result;} catch (error) {if (this.database.isTransaction) this.database.exec("ROLLBACK");if (isSqliteBusy(error)) {this.metrics?.recordSqliteBusy();throw new PersistenceBusyError({ cause: error });}throw error;} finally {this.activeMode = undefined;const durationMs = performance.now() - startedAt;this.metrics?.observe("transaction", durationMs);this.metrics?.observe("databaseOperation", durationMs);}}13 unmodified linesprivate readonly appKey: Uint8Array | undefined;private readonly backupRoot: string;private readonly idGenerator: IdGenerator;private readonly metrics: OperationalMetrics | undefined;private migrationFailure: string | undefined;private expectedMigrationChecksums = new Map<number, string>();8 unmodified linesthis.backupRoot =options.backupRoot ?? join(dirname(databasePath), "..", "backups");this.idGenerator = options.idGenerator ?? new UuidIdGenerator();this.metrics = options.metrics;this.transactions = new SqliteTransactionRunner(database, options.metrics);}static async connect(1 unmodified lineoptions: SqliteConnectionOptions = {},): Promise<SqliteSystemDatabase> {if (!databaseUrl.startsWith("file:")) {throw new Error("The SQLite adapter requires a file URL");}const databasePath = fileURLToPath(databaseUrl);try {const existing = await stat(databasePath);if (!existing.isFile()) throw new Error("Database path is not a file");if (existing.size === 0) throw new Error("Database file is zero bytes");} catch (error) {if (!isFileNotFound(error)) throw error;}await mkdir(dirname(databasePath), { recursive: true });const instance = new SqliteSystemDatabase(new DatabaseSync(databasePath),5 unmodified lines}async migrate(): Promise<void> {const startedAt = performance.now();try {const migrations = await loadMigrationAssets();this.expectedMigrationChecksums = new Map(19 unmodified lines} catch (error) {this.migrationFailure = "Database migration verification failed";throw error;} finally {this.metrics?.observe("migration", performance.now() - startedAt);}}8 unmodified lines}checkReadiness(): Promise<DatabaseReadiness> {const startedAt = performance.now();try {if (this.migrationFailure !== undefined) {return Promise.resolve({9 unmodified linesif (foreignKeyFailures.length > 0) {throw new Error("Foreign key verification failed");}const quickCheck = this.database.prepare("PRAGMA quick_check").get() as| Record<string, string>| undefined;if (quickCheck === undefined || Object.values(quickCheck)[0] !== "ok") {throw new Error("SQLite quick integrity check failed");}return Promise.resolve({ status: "ready" });} catch {return Promise.resolve({status: "not_ready",message: "Database integrity verification failed",});} finally {this.metrics?.observe("databaseOperation", performance.now() - startedAt);}}228 unmodified lines/busy|locked/i.test(error.message));}function isFileNotFound(error: unknown): boolean {return (error instanceof Error &&"code" in error &&(error as NodeJS.ErrnoException).code === "ENOENT");}
4 unmodified lines567891076 unmodified lines878889909192933 unmodified lines9798991001011024 unmodified linesimport { afterEach, describe, expect, it } from "vitest";import { SqliteSystemDatabase } from "./sqlite-system-database.js";import { PersistenceBusyError } from "./database.js";const temporaryDirectories: string[] = [];76 unmodified linesconst databaseUrl = pathToFileURL(join(directory, "database.sqlite")).href;const first = await SqliteSystemDatabase.connect(databaseUrl);await first.migrate();const second = await SqliteSystemDatabase.connect(databaseUrl);second.transactions.run("read", ({ database }) =>database.exec("PRAGMA busy_timeout=1"),);3 unmodified linessecond.transactions.run("immediate", () => undefined),),).toThrow(PersistenceBusyError);await Promise.all([first.close(), second.close()]);});});4 unmodified lines56789101176 unmodified lines88899091929394953 unmodified lines991001011021031041051064 unmodified linesimport { afterEach, describe, expect, it } from "vitest";import { SqliteSystemDatabase } from "./sqlite-system-database.js";import { PersistenceBusyError } from "./database.js";import { OperationalMetrics } from "../observability/operational-metrics.js";const temporaryDirectories: string[] = [];76 unmodified linesconst databaseUrl = pathToFileURL(join(directory, "database.sqlite")).href;const first = await SqliteSystemDatabase.connect(databaseUrl);await first.migrate();const metrics = new OperationalMetrics();const second = await SqliteSystemDatabase.connect(databaseUrl, { metrics });second.transactions.run("read", ({ database }) =>database.exec("PRAGMA busy_timeout=1"),);3 unmodified linessecond.transactions.run("immediate", () => undefined),),).toThrow(PersistenceBusyError);expect(metrics.snapshot().sqliteBusyCount).toBe(1);expect(metrics.snapshot().timings.transaction?.count).toBeGreaterThan(0);await Promise.all([first.close(), second.close()]);});});
123456714 unmodified lines222324252627282927 unmodified lines575859606162import { mkdtemp, rm } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import { pathToFileURL } from "node:url";import { afterEach, describe, expect, it } from "vitest";import { buildApplication } from "../app.js";import { parseEnvironment } from "../config/environment.js";14 unmodified linesreturn buildApplication({environment: parseEnvironment({NODE_ENV: "test",DATA_DIR: dataDir,DATABASE_URL: pathToFileURL(join(dataDir, "database", "test.db")).href,APP_VERSION: "1.2.3",GIT_COMMIT_SHA: "abc123",BUILD_TIMESTAMP: "2026-08-05T01:00:00.000Z",27 unmodified linesconfiguration: { status: "ready" },},});await app.close();});12345614 unmodified lines21222324252627282927 unmodified lines5758596061626364import { mkdtemp, rm } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, it } from "vitest";import { buildApplication } from "../app.js";import { parseEnvironment } from "../config/environment.js";14 unmodified linesreturn buildApplication({environment: parseEnvironment({NODE_ENV: "test",OBJECT_STORAGE_ROOT: join(dataDir, "objects"),DATABASE_PATH: join(dataDir, "database", "test.db"),OLOKA_DATABASE_BOOTSTRAP_MODE: "fresh-if-replica-missing",APP_VERSION: "1.2.3",GIT_COMMIT_SHA: "abc123",BUILD_TIMESTAMP: "2026-08-05T01:00:00.000Z",27 unmodified linesconfiguration: { status: "ready" },},});expect(response.body).not.toContain("test.db");expect(response.body).not.toContain("/var/lib/oloka");await app.close();});
123456789101112131414 unmodified lines293031323334import { buildApplication } from "./app.js";import { parseEnvironment } from "./config/environment.js";async function start(): Promise<void> {const environment = parseEnvironment(process.env);const app = await buildApplication({ environment });let shuttingDown = false;const shutdown = async (signal: NodeJS.Signals) => {if (shuttingDown) return;shuttingDown = true;app.log.info({ signal }, "graceful shutdown started");await app.close();process.exitCode = 0;14 unmodified linesschemaVersion: 2,migrationsVerified: true,},},"Oloka Video is listening",);12345678910111213141516171819202122232425262728293031323334353614 unmodified lines51525354555657import { buildApplication } from "./app.js";import { parseEnvironment } from "./config/environment.js";import { monitorEventLoopDelay } from "node:perf_hooks";import { OperationalMetrics } from "./observability/operational-metrics.js";async function start(): Promise<void> {const environment = parseEnvironment(process.env);const metrics = new OperationalMetrics();const eventLoopDelay = monitorEventLoopDelay({ resolution: 20 });eventLoopDelay.enable();const app = await buildApplication({ environment, metrics });let shuttingDown = false;const metricsInterval = setInterval(() => {metrics.observe("eventLoopDelay", eventLoopDelay.percentile(99) / 1e6);eventLoopDelay.reset();const snapshot = metrics.snapshot();const warning =(snapshot.timings.databaseOperation?.p99Ms ?? 0) > 25 ||(snapshot.timings.transaction?.p99Ms ?? 0) > 20 ||(snapshot.timings.eventLoopDelay?.p99Ms ?? 0) > 50 ||snapshot.sqliteBusyCount > 0;app.log[warning ? "warn" : "info"]({ metrics: snapshot },"persistence operational metrics",);}, 60_000);metricsInterval.unref();const shutdown = async (signal: NodeJS.Signals) => {if (shuttingDown) return;shuttingDown = true;clearInterval(metricsInterval);eventLoopDelay.disable();app.log.info({ signal }, "graceful shutdown started");await app.close();process.exitCode = 0;14 unmodified linesschemaVersion: 2,migrationsVerified: true,},metrics: metrics.snapshot(),},"Oloka Video is listening",);
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384export type TimingMetric = | "startup" | "restore" | "migration" | "databaseOperation" | "transaction" | "eventLoopDelay";
interface TimingAccumulator { count: number; maxMs: number; samples: number[]; nextSample: number;}
export interface OperationalMetricsSnapshot { schemaVersion: 1; timings: Partial< Record<TimingMetric, { count: number; p99Ms: number; maxMs: number }> >; sqliteBusyCount: number;}
const metricOrder: TimingMetric[] = [ "startup", "restore", "migration", "databaseOperation", "transaction", "eventLoopDelay",];
export class OperationalMetrics { private readonly accumulators = new Map<TimingMetric, TimingAccumulator>(); private sqliteBusyCount = 0;
constructor(private readonly sampleLimit = 512) { if (!Number.isInteger(sampleLimit) || sampleLimit < 1) { throw new Error("Metric sample limit must be a positive integer"); } }
observe(metric: TimingMetric, durationMs: number): void { if (!Number.isFinite(durationMs) || durationMs < 0) return; const rounded = Math.round(durationMs * 1000) / 1000; const accumulator = this.accumulators.get(metric) ?? { count: 0, maxMs: 0, samples: [], nextSample: 0, }; accumulator.count += 1; accumulator.maxMs = Math.max(accumulator.maxMs, rounded); if (accumulator.samples.length < this.sampleLimit) { accumulator.samples.push(rounded); } else { accumulator.samples[accumulator.nextSample] = rounded; accumulator.nextSample = (accumulator.nextSample + 1) % this.sampleLimit; } this.accumulators.set(metric, accumulator); }
recordSqliteBusy(): void { this.sqliteBusyCount += 1; }
snapshot(): OperationalMetricsSnapshot { const timings: OperationalMetricsSnapshot["timings"] = {}; for (const metric of metricOrder) { const accumulator = this.accumulators.get(metric); if (accumulator === undefined) continue; const samples = [...accumulator.samples].sort( (left, right) => left - right, ); const percentileIndex = Math.max(0, Math.ceil(samples.length * 0.99) - 1); timings[metric] = { count: accumulator.count, p99Ms: samples[percentileIndex] ?? 0, maxMs: accumulator.maxMs, }; } return { schemaVersion: 1, timings, sqliteBusyCount: this.sqliteBusyCount }; }}1234567891011121314151617181920212223242526272829303132333435import { describe, expect, it } from "vitest";import { OperationalMetrics } from "./operational-metrics.js";
describe("OperationalMetrics", () => { it("reports bounded aggregate percentiles and SQLite busy counts", () => { const metrics = new OperationalMetrics(); for (let duration = 1; duration <= 100; duration += 1) { metrics.observe("transaction", duration); } metrics.observe("migration", 12); metrics.recordSqliteBusy();
expect(metrics.snapshot()).toEqual({ schemaVersion: 1, timings: { migration: { count: 1, p99Ms: 12, maxMs: 12 }, transaction: { count: 100, p99Ms: 99, maxMs: 100 }, }, sqliteBusyCount: 1, }); });
it("retains only a bounded number of duration samples", () => { const metrics = new OperationalMetrics(4); for (let duration = 1; duration <= 10; duration += 1) { metrics.observe("databaseOperation", duration); }
expect(metrics.snapshot().timings.databaseOperation).toEqual({ count: 10, p99Ms: 10, maxMs: 10, }); });});1234567891011121314151617181920212223242526272829303132333435363738394041424344import { performance } from "node:perf_hooks";import { pathToFileURL } from "node:url";import { parseEnvironment } from "../config/environment.js";import { OperationalMetrics } from "../observability/operational-metrics.js";import { bootstrapLocalDatabase } from "./database-bootstrap.js";import { restoreWithLitestream } from "./litestream-restorer.js";
export async function runDatabaseBootstrap( input: NodeJS.ProcessEnv = process.env,): Promise<void> { const startedAt = performance.now(); const environment = parseEnvironment(input); const metrics = new OperationalMetrics(); const result = await bootstrapLocalDatabase({ databasePath: environment.databasePath, objectStorageRoot: environment.objectStorageRoot, mode: environment.databaseBootstrapMode, restore: async () => { const restoreStartedAt = performance.now(); try { await restoreWithLitestream(environment.databasePath); } finally { metrics.observe("restore", performance.now() - restoreStartedAt); } }, }); metrics.observe("startup", performance.now() - startedAt); process.stdout.write( `${JSON.stringify({ level: "info", message: "database bootstrap completed", source: result.source, mode: environment.databaseBootstrapMode, metrics: metrics.snapshot() })}\n`, );}
const entrypoint = process.argv[1];if ( entrypoint !== undefined && import.meta.url === pathToFileURL(entrypoint).href) { runDatabaseBootstrap().catch((error: unknown) => { process.stderr.write( `${JSON.stringify({ level: "fatal", message: "database bootstrap failed", errorCode: "DATABASE_BOOTSTRAP_FAILED", errorType: error instanceof Error ? error.name : "UnknownError" })}\n`, ); process.exitCode = 1; });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172import { DatabaseSync } from "node:sqlite";import { lstat } from "node:fs/promises";import type { DatabaseBootstrapMode } from "../config/environment.js";import { prepareLocalDatabasePath } from "./database-path.js";
export interface DatabaseBootstrapResult { source: "existing" | "restored" | "fresh";}
export async function bootstrapLocalDatabase(input: { databasePath: string; objectStorageRoot: string; mode: DatabaseBootstrapMode; restore: () => Promise<void>;}): Promise<DatabaseBootstrapResult> { const before = await prepareLocalDatabasePath(input); if (before.existed) { await assertNoRollbackJournal(before.databasePath); verifyDatabaseIntegrity(before.databasePath); return { source: "existing" }; }
await input.restore(); const after = await prepareLocalDatabasePath(input); if (after.existed) { await assertNoRollbackJournal(after.databasePath); verifyDatabaseIntegrity(after.databasePath); return { source: "restored" }; } if (input.mode === "fresh-if-replica-missing") { return { source: "fresh" }; } throw new Error("A database replica is required but none was restored");}
async function assertNoRollbackJournal(databasePath: string): Promise<void> { try { await lstat(`${databasePath}-journal`); throw new Error("Unexpected SQLite rollback journal is present"); } catch (error) { if ( error instanceof Error && "code" in error && (error as NodeJS.ErrnoException).code === "ENOENT" ) { return; } throw error; }}
function verifyDatabaseIntegrity(databasePath: string): void { let database: DatabaseSync | undefined; try { database = new DatabaseSync(databasePath, { readOnly: true }); const quickCheck = database.prepare("PRAGMA quick_check").get() as | Record<string, string> | undefined; if (quickCheck === undefined || Object.values(quickCheck)[0] !== "ok") { throw new Error("SQLite quick integrity check failed"); } if (database.prepare("PRAGMA foreign_key_check").all().length !== 0) { throw new Error("SQLite foreign key integrity check failed"); } } catch (error) { throw new Error("Local SQLite database integrity validation failed", { cause: error, }); } finally { database?.close(); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import { DatabaseSync } from "node:sqlite";import { afterEach, describe, expect, it, vi } from "vitest";import { bootstrapLocalDatabase } from "./database-bootstrap.js";
const temporaryDirectories: string[] = [];
afterEach(async () => { await Promise.all( temporaryDirectories .splice(0) .map((directory) => rm(directory, { recursive: true, force: true })), );});
describe("bootstrapLocalDatabase", () => { it("preserves a valid existing database without attempting restore", async () => { const root = await mkdtemp(join(tmpdir(), "oloka-bootstrap-")); temporaryDirectories.push(root); const databasePath = join(root, "local", "oloka.db"); await mkdir(join(root, "local")); const database = new DatabaseSync(databasePath); database.exec("CREATE TABLE marker (value TEXT NOT NULL)"); database.close(); const restore = vi.fn();
await expect( bootstrapLocalDatabase({ databasePath, objectStorageRoot: join(root, "objects"), mode: "restore-required", restore, }), ).resolves.toEqual({ source: "existing" }); expect(restore).not.toHaveBeenCalled(); });
it("allows a fresh database only when missing replicas are explicitly allowed", async () => { const root = await mkdtemp(join(tmpdir(), "oloka-bootstrap-")); temporaryDirectories.push(root); const restore = vi.fn().mockResolvedValue(undefined);
await expect( bootstrapLocalDatabase({ databasePath: join(root, "fresh", "oloka.db"), objectStorageRoot: join(root, "objects"), mode: "fresh-if-replica-missing", restore, }), ).resolves.toEqual({ source: "fresh" }); expect(restore).toHaveBeenCalledOnce(); });
it("fails closed when restore-required finds no replica", async () => { const root = await mkdtemp(join(tmpdir(), "oloka-bootstrap-")); temporaryDirectories.push(root);
await expect( bootstrapLocalDatabase({ databasePath: join(root, "required", "oloka.db"), objectStorageRoot: join(root, "objects"), mode: "restore-required", restore: vi.fn().mockResolvedValue(undefined), }), ).rejects.toThrow(/required/i); });
it.each([ "network restore failed", "authentication restore failed", "corrupt replica restore failed", ])("fails closed on %s", async (message) => { const root = await mkdtemp(join(tmpdir(), "oloka-bootstrap-")); temporaryDirectories.push(root); const restore = vi.fn().mockRejectedValue(new Error(message));
await expect( bootstrapLocalDatabase({ databasePath: join(root, "failed", "oloka.db"), objectStorageRoot: join(root, "objects"), mode: "fresh-if-replica-missing", restore, }), ).rejects.toThrow(message); });
it("accepts only an integrity-checked restored database", async () => { const root = await mkdtemp(join(tmpdir(), "oloka-bootstrap-")); temporaryDirectories.push(root); const databasePath = join(root, "restored", "oloka.db"); const restore = vi.fn(() => { const database = new DatabaseSync(databasePath); database.exec("CREATE TABLE marker (value TEXT NOT NULL)"); database.close(); return Promise.resolve(); });
await expect( bootstrapLocalDatabase({ databasePath, objectStorageRoot: join(root, "objects"), mode: "restore-required", restore, }), ).resolves.toEqual({ source: "restored" }); });
it("rejects a corrupt or zero-byte restore result", async () => { const root = await mkdtemp(join(tmpdir(), "oloka-bootstrap-")); temporaryDirectories.push(root); const databasePath = join(root, "corrupt", "oloka.db");
await expect( bootstrapLocalDatabase({ databasePath, objectStorageRoot: join(root, "objects"), mode: "restore-required", restore: () => writeFile(databasePath, new Uint8Array()), }), ).rejects.toThrow(/zero bytes/i); });
it("rejects an unexpected rollback journal left by restore", async () => { const root = await mkdtemp(join(tmpdir(), "oloka-bootstrap-")); temporaryDirectories.push(root); const databasePath = join(root, "journal", "oloka.db");
await expect( bootstrapLocalDatabase({ databasePath, objectStorageRoot: join(root, "objects"), mode: "restore-required", restore: async () => { const database = new DatabaseSync(databasePath); database.exec("CREATE TABLE marker (value TEXT NOT NULL)"); database.close(); await writeFile(`${databasePath}-journal`, "unexpected"); }, }), ).rejects.toThrow(/journal/i); });});12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091import { lstat, mkdir, realpath, stat } from "node:fs/promises";import { dirname, isAbsolute, parse, relative, resolve, sep } from "node:path";
export interface PreparedDatabasePath { databasePath: string; existed: boolean;}
export async function prepareLocalDatabasePath(input: { databasePath: string; objectStorageRoot: string;}): Promise<PreparedDatabasePath> { if (hasTraversalSegment(input.databasePath)) { throw new Error("Database path must not contain traversal segments"); } if (!isAbsolute(input.databasePath) || !isAbsolute(input.objectStorageRoot)) { throw new Error("Database and object storage paths must be absolute"); }
const databasePath = resolve(input.databasePath); const objectStorageRoot = resolve(input.objectStorageRoot); if (isSameOrInside(databasePath, objectStorageRoot)) { throw new Error("The live database must be outside object storage"); }
await assertNoSymbolicLinkComponent(databasePath); await mkdir(dirname(databasePath), { recursive: true }); await assertNoSymbolicLinkComponent(databasePath);
const realObjectStorageRoot = await realpathIfPresent(objectStorageRoot); const realDatabaseParent = await realpath(dirname(databasePath)); if ( realObjectStorageRoot !== undefined && isSameOrInside(realDatabaseParent, realObjectStorageRoot) ) { throw new Error("The live database resolves inside object storage"); }
try { const details = await stat(databasePath); if (!details.isFile()) throw new Error("Database path is not a file"); if (details.size === 0) throw new Error("Database file is zero bytes"); return { databasePath, existed: true }; } catch (error) { if (hasCode(error, "ENOENT")) return { databasePath, existed: false }; throw error; }}
function hasTraversalSegment(path: string): boolean { return path.split(/[\\/]/u).includes("..");}
async function assertNoSymbolicLinkComponent(path: string): Promise<void> { const root = parse(path).root; const parts = path.slice(root.length).split(sep).filter(Boolean); let current = root; for (const part of parts) { current = resolve(current, part); try { if ((await lstat(current)).isSymbolicLink()) { throw new Error("Database path contains a symbolic link"); } } catch (error) { if (hasCode(error, "ENOENT")) return; throw error; } }}
async function realpathIfPresent(path: string): Promise<string | undefined> { try { return await realpath(path); } catch (error) { if (hasCode(error, "ENOENT")) return undefined; throw error; }}
function isSameOrInside(candidate: string, root: string): boolean { const child = relative(root, candidate); return child === "" || (!child.startsWith(`..${sep}`) && child !== "..");}
function hasCode(error: unknown, code: string): boolean { return ( error instanceof Error && "code" in error && (error as NodeJS.ErrnoException).code === code );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join, sep } from "node:path";import { afterEach, describe, expect, it } from "vitest";import { prepareLocalDatabasePath } from "./database-path.js";
const temporaryDirectories: string[] = [];
afterEach(async () => { await Promise.all( temporaryDirectories .splice(0) .map((directory) => rm(directory, { recursive: true, force: true })), );});
describe("prepareLocalDatabasePath", () => { it("rejects a live database nested beneath persistent object storage", async () => { const root = await mkdtemp(join(tmpdir(), "oloka-path-")); temporaryDirectories.push(root);
await expect( prepareLocalDatabasePath({ databasePath: join(root, "data", "database", "oloka.db"), objectStorageRoot: join(root, "data"), }), ).rejects.toThrow(/object storage/i); });
it("rejects traversal segments instead of normalizing them silently", async () => { const root = await mkdtemp(join(tmpdir(), "oloka-path-")); temporaryDirectories.push(root);
await expect( prepareLocalDatabasePath({ databasePath: `${root}${sep}local${sep}..${sep}database${sep}oloka.db`, objectStorageRoot: join(root, "objects"), }), ).rejects.toThrow(/traversal/i); });
it("rejects relative and empty database paths", async () => { await expect( prepareLocalDatabasePath({ databasePath: "database/oloka.db", objectStorageRoot: "/data", }), ).rejects.toThrow(/absolute/i); await expect( prepareLocalDatabasePath({ databasePath: "", objectStorageRoot: "/data", }), ).rejects.toThrow(/absolute/i); });
it("rejects directories and zero-byte database files", async () => { const root = await mkdtemp(join(tmpdir(), "oloka-path-")); temporaryDirectories.push(root); const directoryPath = join(root, "directory.db"); await mkdir(directoryPath); await expect( prepareLocalDatabasePath({ databasePath: directoryPath, objectStorageRoot: join(root, "objects"), }), ).rejects.toThrow(/not a file/i);
const zeroBytePath = join(root, "empty.db"); await writeFile(zeroBytePath, new Uint8Array()); await expect( prepareLocalDatabasePath({ databasePath: zeroBytePath, objectStorageRoot: join(root, "objects"), }), ).rejects.toThrow(/zero bytes/i); });
it("rejects a symbolic-link component in the database path", async () => { const root = await mkdtemp(join(tmpdir(), "oloka-path-")); temporaryDirectories.push(root); const target = join(root, "target"); const alias = join(root, "alias"); await mkdir(target); await symlink(target, alias, "junction");
await expect( prepareLocalDatabasePath({ databasePath: join(alias, "oloka.db"), objectStorageRoot: join(root, "objects"), }), ).rejects.toThrow(/symbolic link/i); });
it("creates only the safe local parent and preserves a valid existing file", async () => { const root = await mkdtemp(join(tmpdir(), "oloka-path-")); temporaryDirectories.push(root); const databasePath = join(root, "local", "database", "oloka.db"); const objectStorageRoot = join(root, "objects");
await expect( prepareLocalDatabasePath({ databasePath, objectStorageRoot }), ).resolves.toEqual({ databasePath, existed: false }); await writeFile(databasePath, "sqlite-placeholder"); await expect( prepareLocalDatabasePath({ databasePath, objectStorageRoot }), ).resolves.toEqual({ databasePath, existed: true }); });});123456789101112131415161718192021222324252627282930313233343536373839404142import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, it } from "vitest";import { buildApplication } from "../app.js";import { parseEnvironment } from "../config/environment.js";
const temporaryDirectories: string[] = [];
afterEach(async () => { await Promise.all( temporaryDirectories .splice(0) .map((directory) => rm(directory, { recursive: true, force: true })), );});
describe("legacy bucket database isolation", () => { it("never opens or mutates the legacy database under object storage", async () => { const root = await mkdtemp(join(tmpdir(), "oloka-legacy-")); temporaryDirectories.push(root); const objectStorageRoot = join(root, "objects"); const legacyPath = join(objectStorageRoot, "database", "oloka-dev.db"); const legacyEvidence = Buffer.from("legacy-evidence-must-remain-untouched"); await mkdir(join(objectStorageRoot, "database"), { recursive: true }); await writeFile(legacyPath, legacyEvidence);
const app = await buildApplication({ environment: parseEnvironment({ NODE_ENV: "test", DATABASE_PATH: join(root, "local", "oloka.db"), OBJECT_STORAGE_ROOT: objectStorageRoot, OLOKA_DATABASE_BOOTSTRAP_MODE: "fresh-if-replica-missing", LOG_LEVEL: "silent", }), serveFrontend: false, }); await app.close();
await expect(readFile(legacyPath)).resolves.toEqual(legacyEvidence); });});1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950import { execFile } from "node:child_process";import { promisify } from "node:util";
const execFileAsync = promisify(execFile);
export interface RestoreProcessOptions { timeout: number;}
export type RestoreProcessRunner = ( executable: string, arguments_: string[], options: RestoreProcessOptions,) => Promise<void>;
export async function restoreWithLitestream( databasePath: string, options: { run?: RestoreProcessRunner } = {},): Promise<void> { const run = options.run ?? runProcess; try { await run( "litestream", [ "restore", "-config", "/etc/litestream.yml", "-integrity-check", "quick", "-if-replica-exists", databasePath, ], { timeout: 30_000 }, ); } catch { throw new Error("Litestream database restore failed"); }}
async function runProcess( executable: string, arguments_: string[], options: RestoreProcessOptions,): Promise<void> { await execFileAsync(executable, arguments_, { timeout: options.timeout, windowsHide: true, maxBuffer: 64 * 1024, });}123456789101112131415161718192021222324252627282930313233343536373839404142import { describe, expect, it, vi } from "vitest";import { restoreWithLitestream } from "./litestream-restorer.js";
describe("restoreWithLitestream", () => { it("uses a bounded, shell-free, integrity-checked conditional restore", async () => { const run = vi.fn().mockResolvedValue(undefined);
await restoreWithLitestream("/var/lib/oloka/database/oloka.db", { run, });
expect(run).toHaveBeenCalledWith( "litestream", [ "restore", "-config", "/etc/litestream.yml", "-integrity-check", "quick", "-if-replica-exists", "/var/lib/oloka/database/oloka.db", ], { timeout: 30_000 }, ); });
it("fails closed without exposing process output that could contain secrets", async () => { const sensitiveValue = "credential-from-process-output"; const run = vi.fn().mockRejectedValue(new Error(sensitiveValue));
let failure: unknown; try { await restoreWithLitestream("/var/lib/oloka/database/oloka.db", { run }); } catch (error) { failure = error; }
expect(failure).toBeInstanceOf(Error); expect(String(failure)).toMatch(/Litestream database restore failed/); expect(String(failure)).not.toContain(sensitiveValue); });});1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556import { z } from "zod";import type { TransactionRunner } from "../database/database.js";import { SystemMetadataRepository } from "../database/repositories/system-metadata-repository.js";import type { Clock } from "../kernel/clock.js";
const runtimeWitnessSchema = z .object({ schemaVersion: z.literal(1), firstStartedAt: z.number().int().nonnegative(), lastStartedAt: z.number().int().nonnegative(), startupCount: z.number().int().positive(), lastBuildSha: z.string().min(1), runtimeMode: z.literal("sqlite-local-hf-s3-replication"), }) .strict();
export type RuntimeWitness = z.infer<typeof runtimeWitnessSchema>;export interface RuntimeWitnessUpdate { witness: RuntimeWitness; metadataVersion: number;}
export class RuntimeWitnessService { private readonly repository = new SystemMetadataRepository();
constructor( private readonly transactions: TransactionRunner, private readonly clock: Clock, ) {}
record(buildSha: string): RuntimeWitnessUpdate { const now = this.clock.now(); return this.transactions.run("immediate", (context) => { const existing = this.repository.get(context, "deployment.runtime"); const previous = existing === undefined ? undefined : runtimeWitnessSchema.parse(existing.value); const witness: RuntimeWitness = { schemaVersion: 1, firstStartedAt: previous?.firstStartedAt ?? now, lastStartedAt: now, startupCount: (previous?.startupCount ?? 0) + 1, lastBuildSha: buildSha, runtimeMode: "sqlite-local-hf-s3-replication", }; const stored = this.repository.put(context, { key: "deployment.runtime", value: witness, updatedAt: now, expectedVersion: existing?.version ?? null, }); return { witness, metadataVersion: stored.version }; }); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384import { mkdtemp, rm } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import { pathToFileURL } from "node:url";import { afterEach, describe, expect, it } from "vitest";import { SqliteSystemDatabase } from "../database/sqlite-system-database.js";import type { Clock } from "../kernel/clock.js";import { RuntimeWitnessService } from "./runtime-witness-service.js";
const temporaryDirectories: string[] = [];
afterEach(async () => { await Promise.all( temporaryDirectories .splice(0) .map((directory) => rm(directory, { recursive: true, force: true })), );});
describe("RuntimeWitnessService", () => { it("preserves first start and increments exactly once for each startup", async () => { const directory = await mkdtemp(join(tmpdir(), "oloka-witness-")); temporaryDirectories.push(directory); const database = await SqliteSystemDatabase.connect( pathToFileURL(join(directory, "database.sqlite")).href, ); await database.migrate(); const clock = new SequenceClock([100, 200, 300]);
const first = new RuntimeWitnessService( database.transactions, clock, ).record("build-one"); const second = new RuntimeWitnessService( database.transactions, clock, ).record("build-two"); const third = new RuntimeWitnessService( database.transactions, clock, ).record("build-three");
expect(first).toEqual({ metadataVersion: 1, witness: { schemaVersion: 1, firstStartedAt: 100, lastStartedAt: 100, startupCount: 1, lastBuildSha: "build-one", runtimeMode: "sqlite-local-hf-s3-replication", }, }); expect(second).toMatchObject({ metadataVersion: 2, witness: { firstStartedAt: 100, lastStartedAt: 200, startupCount: 2, lastBuildSha: "build-two", }, }); expect(third).toMatchObject({ metadataVersion: 3, witness: { firstStartedAt: 100, lastStartedAt: 300, startupCount: 3, lastBuildSha: "build-three", }, }); await database.close(); });});
class SequenceClock implements Clock { constructor(private readonly values: number[]) {}
now(): number { const value = this.values.shift(); if (value === undefined) throw new Error("Clock sequence exhausted"); return value; }}1234567891011121314#!/bin/shset -eu
: "${HF_S3_ACCESS_KEY_ID:?HF_S3_ACCESS_KEY_ID is required}": "${HF_S3_SECRET_ACCESS_KEY:?HF_S3_SECRET_ACCESS_KEY is required}"
export LITESTREAM_ACCESS_KEY_ID="$HF_S3_ACCESS_KEY_ID"export LITESTREAM_SECRET_ACCESS_KEY="$HF_S3_SECRET_ACCESS_KEY"
node apps/server/dist/startup/bootstrap-database.js
exec litestream replicate \ -config /etc/litestream.yml \ -exec "node apps/server/dist/index.js"1234567891011121314logging: level: info
dbs: - path: ${DATABASE_PATH} replica: type: s3 bucket: ${HF_S3_BUCKET} path: ${HF_S3_SQLITE_PREFIX} endpoint: ${HF_S3_ENDPOINT} region: ${HF_S3_REGION} force-path-style: true sign-payload: true require-content-md5: false1 unmodified line23456789101134 unmodified lines4647484950515211 unmodified lines646566671 unmodified line## Objectives and limitationMVP protects recoverability from application/migration error on one HF persistent volume. A backup stored only under the same `/data` volume is not full disaster recovery; loss of the Space storage can lose both live data and local backups. External encrypted, independently retained backup is a required post-MVP control before stronger DR claims.Initial targets for Phase 3 validation: RPO at most 24 hours for periodic snapshots plus a pre-migration snapshot; RTO four hours for a documented operator restore. Product owner must confirm these targets.## Consistent SQLite snapshotNever copy a live database file or separately copy `.db`, `-wal`, and `-shm`.34 unmodified lines## Restore runbook1. Stop traffic/app and preserve the failed DB/WAL/SHM/object state under an incident directory without overwriting it.2. Choose a compatible backup; derive the declared manifest key version,canonicalize the manifest, verify its HMAC in constant time, then verify allrecorded checksums before reading it as restore authority.11 unmodified lines## Corruption/startup behaviorStartup refuses readiness on migration checksum mismatch, unsupported newer schema, failed quick/foreign-key check, or unavailable database path. It never silently creates a new empty production DB when the expected `/data` DB is corrupt/unavailable. Operators choose restore or explicit incident-mode recovery. Object reconciliation can degrade individual resources without erasing their evidence.1 unmodified line2345678910111213141534 unmodified lines5051525354555611 unmodified lines686970711 unmodified line## Objectives and limitationMVP uses two complementary mechanisms: Litestream continuously replicates the local SQLite primary to the HF S3 API for ephemeral-disk/rebuild recovery, while authenticated immutable backup sets under `/data` protect migration rollback. Both remain within the same HF provider/account failure domain and are not full disaster recovery. External encrypted, independently retained backup is required before stronger DR claims.Initial targets for Phase 3 validation: RPO at most 24 hours for periodic snapshots plus a pre-migration snapshot; RTO four hours for a documented operator restore. Product owner must confirm these targets.The qualification crash observation lost one sparse-write generation andrestored state 8,018 ms old after a commit 60 ms before termination. This is onemeasurement, not a maximum RPO and not evidence of zero data loss.## Consistent SQLite snapshotNever copy a live database file or separately copy `.db`, `-wal`, and `-shm`.34 unmodified lines## Restore runbook1. Stop traffic/app and preserve the failed DB/WAL/SHM/object state under an incident directory without overwriting it. Litestream must be the only supervisor/replicator.2. Choose a compatible backup; derive the declared manifest key version,canonicalize the manifest, verify its HMAC in constant time, then verify allrecorded checksums before reading it as restore authority.11 unmodified lines## Corruption/startup behaviorProduction keeps the live DB at `/var/lib/oloka/database/oloka.db`. Startup validates containment/symlinks, then restores an absent DB with `litestream restore -config /etc/litestream.yml -integrity-check quick -if-replica-exists`. Any network, authentication, permission, corruption, timeout, or command error fails closed. `restore-required` also fails when no replica exists; only explicit `fresh-if-replica-missing` permits a fresh DB. Readiness then re-verifies migrations, PRAGMAs, quick integrity, foreign keys, startup initialization, and object storage without making a fresh S3 request on every probe.
12345678910111241 unmodified lines54555657585919 unmodified lines798081# Database Migration StrategyStatus: normative Phase 2 design; no migration is created here.## ContractMigrations are numbered, named, immutable, forward-only SQL assets executed before the HTTP listener starts. The runner records version, name, SHA-256 checksum, applied time, execution duration, and application build SHA in `schema_migrations`. It refuses startup on a checksum/name mismatch, gap, duplicate version, failed migration, or database schema newer than the application.The current foundation database is schema version 1. Phase 2 only designs version 2 and later. Services must never infer schema, execute opportunistic `ALTER TABLE`, or edit an applied migration.## Ledger compatibility41 unmodified lines## Execution algorithm- Open the database with the required PRAGMAs and acquire an application-wide migration lock.- Run integrity and ledger checks, discover migration assets, hash their exact UTF-8 bytes, and compare applied rows.- Create a pre-migration consistent backup before the first pending migration.19 unmodified lines- injected failure proves transaction rollback;- foreign-key and integrity checks;- backup restore into the prior application build.12345678910111241 unmodified lines5455565758596019 unmodified lines808182838485868788# Database Migration StrategyStatus: normative; migrations v1/v2 are implemented and immutable.## ContractMigrations are numbered, named, immutable, forward-only SQL assets executed before the HTTP listener starts. The runner records version, name, SHA-256 checksum, applied time, execution duration, and application build SHA in `schema_migrations`. It refuses startup on a checksum/name mismatch, gap, duplicate version, failed migration, or database schema newer than the application.The current Persistence Kernel database is schema version 2. Phase 3A.1 changes startup durability only: it creates no migration v3 and does not alter a byte of v1/v2. Services must never infer schema, execute opportunistic `ALTER TABLE`, or edit an applied migration.## Ledger compatibility41 unmodified lines## Execution algorithm- Restore an absent local primary from the configured Litestream replica before the application opens SQLite. A non-zero restore exit always fails closed; missing replica permits fresh creation only under explicit `fresh-if-replica-missing`.- Open the database with the required PRAGMAs and acquire an application-wide migration lock.- Run integrity and ledger checks, discover migration assets, hash their exact UTF-8 bytes, and compare applied rows.- Create a pre-migration consistent backup before the first pending migration.19 unmodified lines- injected failure proves transaction rollback;- foreign-key and integrity checks;- backup restore into the prior application build.- three fresh local volumes restored successively from one pinned MinIO replica, proving witness counts 1/2/3 and a byte-stable v1/v2 ledger.Litestream 0.5.11 may create `_litestream_lock` and `_litestream_seq` for its owncoordination. They are provider-internal runtime tables and never ledgerentries, application migrations, or authorization/product entities. Theapplication schema allowlist remains the six Slice 3A tables.
1 unmodified line234567891011121314151617181920212223242526271 unmodified line## Build artifactBoth Docker stages use exactly Node `22.16.0`. The multi-stage build installs the locked dependency graph, compiles contracts, design system, web, and server, then prunes development dependencies. The runtime stage contains production dependencies, compiled artifacts, and immutable SQL migration assets. It runs as UID/GID `1000`, exposes `7860`, and includes an application health check.Build identity enters the image through `APP_VERSION`, `GIT_COMMIT_SHA`, and `BUILD_TIMESTAMP` build arguments. Runtime configuration can override ordinary environment values, but production operators should keep build identity immutable.## GitHub to Hugging FaceThe `develop` deployment workflow invokes the reusable validation workflow first on Node `22.16.0`. Formatting, lint, typecheck, unit, integration, frontend, aggregate test, production, browser, Docker build, and two-start named-volume persistence checks must pass. The deployment job then synchronizes the exact validated Git commit to `phucsd/Oloka-Video-Dev` using the masked `HF_TOKEN` secret. It also sets the Space runtime variables, including the validated Git SHA and deployment timestamp, so `/api/version` identifies the hosted source exactly.The Space reads Docker metadata from the YAML header in `README.md`. Persistent Hugging Face storage must be attached at `/data`; replacing that path with ephemeral storage loses SQLite state after rebuilds.Configure `OLOKA_APP_KEY` as a Hugging Face Space secret before deploying abuild that can upgrade an existing database. It must be unpadded base64url forexactly 32 random bytes. Never configure it as a public variable or build arg.Pre-migration recovery sets are written under`/data/backups/pre-migration/<opaque-set>` and share the same volume failuredomain.## ObservabilityFastify emits JSON logs to standard output. Use the Space Logs tab for build and container logs. Diagnose deployment layers separately: GitHub validation, repository sync, Docker build, container start, `/api/health`, then `/api/ready`.## Rollback1 unmodified line23456789101112131415161718192021222324252627282930313233341 unmodified line## Build artifactAll Node stages use exactly Node `22.16.0`. A separate build stage downloads Litestream `0.5.11`, verifies archive SHA-256 `2f80fdb6b0a0ff7a116ee37adf02d3de8e977ef76e052b28a6690218f0f7ab55`, and copies only its binary/license. The runtime contains production dependencies, compiled artifacts, immutable SQL migrations, and credential-free `/etc/litestream.yml`. It runs as UID/GID `1000`, exposes `7860`, and includes an application health check.Build identity enters the image through `APP_VERSION`, `GIT_COMMIT_SHA`, and `BUILD_TIMESTAMP` build arguments. Runtime configuration can override ordinary environment values, but production operators should keep build identity immutable.## GitHub to Hugging FaceThe `develop` deployment workflow invokes validation first on Node `22.16.0`. Formatting, lint, typecheck, unit, integration, frontend, aggregate, build, browser, production-image, and pinned-MinIO three-boot recovery checks must pass. Validation destroys three successive local DB volumes while preserving the replica, proves startup counts 1/2/3 and signal shutdown, and never uses the production HF bucket.The Space reads Docker metadata from the YAML header in `README.md`. `/data` remains the persistent object/backup mount. The live SQLite primary is local ephemeral storage at `/var/lib/oloka/database/oloka.db`; Litestream restores it before Fastify starts and continuously replicates it to the isolated production prefix `sqlite-replica/dev`.Configure `OLOKA_APP_KEY`, `HF_S3_ACCESS_KEY_ID`, and`HF_S3_SECRET_ACCESS_KEY` as Hugging Face Space secrets. The deploy preflightchecks names only. Set `OLOKA_DATABASE_BOOTSTRAP_MODE` explicitly as a Spacevariable; a missing mode blocks upload. Use `fresh-if-replica-missing` only forthe separately approved first cutover, then change to `restore-required` afterreplica verification. Never configure secret values as variables or build args.Pre-migration recovery sets are written under`/data/backups/pre-migration/<opaque-set>` and share the same volume failuredomain.## ObservabilityFastify and Litestream emit structured operational logs. Aggregates cover startup, restore, migration, database operation, transaction, event-loop delay, and SQLite busy counts without per-SQL logs. Diagnose deployment layers separately: GitHub validation, repository sync, Docker build, restore/bootstrap, Litestream supervision, container start, `/api/health`, then `/api/ready`.This implementation PR does not set the live bootstrap variable, upload theSpace, touch `sqlite-replica/dev`, restart the Space, or migrate/delete thelegacy `/data/database/oloka-dev.db`. Those are a separate cutover gate.## Rollback
9 unmodified lines101112131415169 unmodified linesThe database boundary is `SystemDatabase`. `SqliteSystemDatabase` is the MVP adapter and owns verified PRAGMAs, immutable migration assets, readiness, and a synchronous transaction runner. Repositories own SQL; routes do not. A PostgreSQL adapter is a documented scaling exit, not an implemented alternative.The persistent-data boundary is `ObjectStorage`. `FilesystemObjectStorage` owns all filesystem readiness work beneath `DATA_DIR`; future object-store implementations can replace it without changing HTTP handlers.## Request flow9 unmodified lines101112131415169 unmodified linesThe database boundary is `SystemDatabase`. `SqliteSystemDatabase` is the MVP adapter and owns verified PRAGMAs, immutable migration assets, readiness, and a synchronous transaction runner. Repositories own SQL; routes do not. A PostgreSQL adapter is a documented scaling exit, not an implemented alternative.The persistent-byte boundary is `ObjectStorage`. `FilesystemObjectStorage` owns filesystem readiness beneath `OBJECT_STORAGE_ROOT`; future object-store implementations can replace it without changing HTTP handlers. The local SQLite primary is configured separately by `DATABASE_PATH` and must remain outside that root.## Request flow
12345611 unmodified lines181920212223# Phase 3 Implementation SequenceStatus: Slice 3A implemented; later slices remain proposed and require explicit authorization.## 3A — Persistence kernel11 unmodified linesaudit redaction, RFC 8785/HMAC-SHA256 backup manifest verification andconsistent backup/restore on the pinned runtime.- Deployment smoke: exact validated HF SHA, schema/readiness metadata, DB/storage restart persistence, no product route added.- Rollback: stop app, restore verified pre-v2 snapshot, deploy Phase 2 foundation build; no down migration.- Explicitly excluded: Google/auth, Project, Asset/upload, dispatcher Jobs, providers, composition, preview, render, UI.- Exit criteria: repository/application boundaries are enforced; no route SQL; v1->v2 and restore drill pass; outbox/audit primitives have deterministic tests. Only this slice may start after Phase 2 approval.12345611 unmodified lines18192021222324# Phase 3 Implementation SequenceStatus: Slice 3A implemented; Slice 3A.1 durability implementation is under review and production cutover is pending. Later slices require explicit authorization.## 3A — Persistence kernel11 unmodified linesaudit redaction, RFC 8785/HMAC-SHA256 backup manifest verification andconsistent backup/restore on the pinned runtime.- Deployment smoke: exact validated HF SHA, schema/readiness metadata, DB/storage restart persistence, no product route added.- Durability correction: local primary outside `/data`, Litestream 0.5.11 to HF S3, explicit restore policy, startup witness, and pinned-MinIO three-boot recovery. This does not authorize production cutover or Slice 3B.- Rollback: stop app, restore verified pre-v2 snapshot, deploy Phase 2 foundation build; no down migration.- Explicitly excluded: Google/auth, Project, Asset/upload, dispatcher Jobs, providers, composition, preview, render, UI.- Exit criteria: repository/application boundaries are enforced; no route SQL; v1->v2 and restore drill pass; outbox/audit primitives have deterministic tests. Only this slice may start after Phase 2 approval.
1 unmodified line23456787 unmodified lines1617181920211 unmodified line## SetupInstall exactly Node.js `22.16.0` using `.nvmrc`/`.node-version` and run `npm ci`. Copy `.env.example` only when a local environment file is useful; never add `.env` to Git. Windows developers should set `DATA_DIR` and `DATABASE_URL` to a writable repository-local path because `/data` is the online Linux default.`npm run dev` starts Fastify on `7860` and Vite on `5173`. Vite proxies API requests to Fastify. Production and browser checks use the single-port compiled build.7 unmodified lines- `npm run test:frontend` exercises connected and error states.- `npm run build` produces all production artifacts.- `npm run test:e2e` starts the compiled server and checks the page in Chromium.## Data cleanup1 unmodified line23456787 unmodified lines161718192021221 unmodified line## SetupInstall exactly Node.js `22.16.0` using `.nvmrc`/`.node-version` and run `npm ci`. Copy `.env.example` only when a local environment file is useful; never add `.env` to Git. Set `DATABASE_PATH` and `OBJECT_STORAGE_ROOT` to separate absolute writable paths. Local/test may explicitly use `OLOKA_DATABASE_BOOTSTRAP_MODE=fresh-if-replica-missing`; production never receives that mode by default.`npm run dev` starts Fastify on `7860` and Vite on `5173`. Vite proxies API requests to Fastify. Production and browser checks use the single-port compiled build.7 unmodified lines- `npm run test:frontend` exercises connected and error states.- `npm run build` produces all production artifacts.- `npm run test:e2e` starts the compiled server and checks the page in Chromium.- `bash scripts/run-docker-litestream-recovery.sh <image>` uses pinned MinIO fixtures to destroy three successive local DB volumes while retaining the replica; it verifies startup counts 1/2/3, unchanged v1/v2 ledger, integrity, signal shutdown, and secret redaction.## Data cleanup
1 unmodified line234567841 unmodified lines505152531 unmodified line## ScopeThe MVP object adapter stores durable bytes beneath `/data/objects` and temporary upload bytes beneath `/data/tmp`. Runtime bytes are never written to Git and are not served by a public static mount. The interface is intentionally portable to S3-compatible storage later.## Key and path contract41 unmodified lines## LimitsThe filesystem shares the Space availability zone and `/data` failure domain. It is persistence, not full disaster recovery. External replicated object storage is post-MVP and enters through this interface when scale/DR exit criteria in `TECHNICAL_ARCHITECTURE_V1.md` are met.1 unmodified line234567841 unmodified lines505152531 unmodified line## ScopeThe MVP object adapter stores durable bytes beneath `OBJECT_STORAGE_ROOT` (production `/data`) and temporary upload bytes beneath its staging area. Runtime bytes are never written to Git and are not served by a public static mount. The live SQLite primary is explicitly outside this root at `/var/lib/oloka/database/oloka.db`; `/data/database/oloka-dev.db` is legacy evidence only.## Key and path contract41 unmodified lines## LimitsThe filesystem, same-bucket backup sets, and Litestream's HF S3 replica share provider/account failure domains. They improve persistence and rebuild recovery but are not independent disaster recovery. Litestream's database replica is durability transport and does not bypass this object-storage interface for product bytes.
39 unmodified lines40414243444525 unmodified lines7172737475767735 unmodified lines11311411511611711811912012112212312412512612712839 unmodified linesOAuth, sessions, projects, assets, composition, preview, render, provider,quota, and durable Job tables are intentionally absent.## SQLite connection and transaction contractEvery opened connection applies and verifies `foreign_keys=ON`, WAL journal25 unmodified lineskey. The default layout is:```text<DATA_DIR>/backups/pre-migration/<opaque-set>/database.sqlitemanifest.jsonmanifest.hmac35 unmodified lines## Startup and operationsConfiguration is validated, SQLite is opened, PRAGMAs are verified, allmigrations and required backup complete, and storage is probed before thelistener opens. Failure closes SQLite and emits only a safe startup error codeand error type. The success summary contains adapter/schema/checksum status butno key or filesystem path.The validation workflow uses the exact Node patch, runs all existing qualitygates, builds the production image, then starts it twice against one namedvolume with a test-only application key and requires `/api/ready` after bothstarts.## Explicit exclusions39 unmodified lines404142434445464748495025 unmodified lines7677787980818235 unmodified lines11811912012112212312412512612712812913013113213313413513613713813914039 unmodified linesOAuth, sessions, projects, assets, composition, preview, render, provider,quota, and durable Job tables are intentionally absent.Litestream 0.5.11 owns two transport-internal runtime tables,`_litestream_lock` and `_litestream_seq`, while supervising the primary. Theyare not created by application migration v1/v2 and are excluded from theapplication table allowlist above.## SQLite connection and transaction contractEvery opened connection applies and verifies `foreign_keys=ON`, WAL journal25 unmodified lineskey. The default layout is:```text<OBJECT_STORAGE_ROOT>/backups/pre-migration/<opaque-set>/database.sqlitemanifest.jsonmanifest.hmac35 unmodified lines## Startup and operationsPhase 3A.1 moves the live primary to`/var/lib/oloka/database/oloka.db`. Before the application opens it, theentrypoint validates configuration/path containment and performs a boundedLitestream restore when absent. Litestream then becomes PID 1 and supervisesFastify. Migrations/readiness run, `deployment.runtime` is updated through anoptimistic short transaction, and storage is probed before listening. Failureemits safe error code/type only; no secret or public filesystem path is added.The validation workflow uses exact Node/Litestream versions, runs all existingquality gates, and proves three starts against pinned MinIO while replacing thelocal DB volume after each stop. It requires counts 1/2/3, preserved first start,unchanged v1/v2 ledger, quick/FK integrity, bounded graceful signal handling,replica objects, and no credential in logs/config.Operational metrics are bounded aggregates, not per-SQL telemetry. Warningthresholds are database-operation p99 over 25 ms, transaction p99 over 20 ms,event-loop-delay p99 over 50 ms, or any observed `SQLITE_BUSY`.## Explicit exclusions
12345678910111213141516171819202122233 unmodified lines2728293031323336 unmodified lines7071727374759 unmodified lines85868788899091# Technical Architecture V1Status: Phase 2 blueprint; implementation is deferred to Phase 3.## Decision summaryOloka Video MVP is one TypeScript modular monolith deployed as one Node.js 22 process in one Hugging Face Docker Space. Fastify owns HTTP, authentication, authorization, orchestration, delivery, and background dispatch. React/Vite is the browser client. SQLite and the Hugging Face persistent `/data` filesystem are the only durable stores. Modal is the only remote render provider.This document resolves the choices left open in `MVP_SYSTEM_BOUNDARY.md`; the Phase 1 product and domain contracts remain authoritative where this blueprint is silent.| Concern | Locked choice | Explicitly excluded from MVP || -------- | ------------------------------------------------------------------------------- | ----------------------------------------------------- || Runtime | Node.js 22.16.0 exact reviewed patch, TypeScript ESM, npm workspaces | floating Node major, second backend, serverless split || HTTP/UI | Fastify 5, React, Vite, Zod contracts | full-stack framework, duplicated API types || Database | `node:sqlite`, one database under `/data/database` | ORM, external database, replicas || Bytes | filesystem object adapter rooted at `/data/objects` | Git-tracked runtime bytes, S3/R2 || Jobs | in-process dispatcher with durable SQLite leases/outbox | RAM-only queue, message broker || Preview | immutable authorized artifact using the trusted HyperFrames materializer/player | arbitrary HTML, per-project permanent preview servers || Render | Modal adapter behind typed provider boundary | local production rendering, provider fan-out || Deploy | one HF Docker Space, one app instance | Cloudflare runtime, horizontal scale |## Component map3 unmodified linesG["Google OIDC"] <--> FF --> C["Zod contracts and domain services"]C --> R["Repositories and transaction runner"]R --> D[("SQLite /data/database")]C --> S["Filesystem object storage"]S --> O[("/data/objects")]U[("/data/tmp upload staging")] --> S36 unmodified lines- IDs are UUIDv4 generated with `crypto.randomUUID()`.- Database timestamps are UTC Unix epoch milliseconds stored as SQLite `INTEGER`.- Connections enable `foreign_keys=ON`, `journal_mode=WAL`, `synchronous=FULL`, and `busy_timeout=5000`.- `node:sqlite` is synchronous. Statements and transactions must be short; provider calls, filesystem streaming, checksums, and media analysis never run while a transaction is open.- Routes never contain SQL. All writes use a transaction runner and repository interfaces.- JSON is Zod-validated, schema-versioned, RFC 8785 canonicalized UTF-8 text. Search/filter/join fields remain normal columns.9 unmodified lines## Availability and scale envelopeMVP intentionally supports one Space replica and one application process. WAL improves read/write overlap but does not make shared-filesystem multi-writer SQLite safe. Move to PostgreSQL when any of these become true: more than one application instance is required; sustained lock wait or write latency breaches the NFR; job throughput requires independent workers; backup/recovery objectives require managed point-in-time recovery; or the dataset/storage growth makes maintenance windows unacceptable. Object storage then moves behind the existing adapter to S3-compatible storage and dispatcher leases move to a multi-worker-capable database/queue. No part of that exit is implemented in Phase 2.## Source evidence1234567891011121314151617181920212223243 unmodified lines2829303132333435363736 unmodified lines747576777879809 unmodified lines90919293949596# Technical Architecture V1Status: Phase 2 blueprint with the accepted Phase 3A.1 durability correction.## Decision summaryOloka Video MVP is one TypeScript modular monolith deployed in one Hugging Face Docker Space. Litestream supervises one Node.js 22/Fastify application process. React/Vite is the browser client. SQLite is a local single-writer primary; Litestream transports recovery state to the HF S3 API. The `/data` mount stores object bytes and immutable backups, never the live SQLite database. Modal remains the only planned remote render provider.This document resolves the choices left open in `MVP_SYSTEM_BOUNDARY.md`; the Phase 1 product and domain contracts remain authoritative where this blueprint is silent.| Concern | Locked choice | Explicitly excluded from MVP || ---------- | ------------------------------------------------------------------------------- | ----------------------------------------------------- || Runtime | Node.js 22.16.0 exact reviewed patch, TypeScript ESM, npm workspaces | floating Node major, second backend, serverless split || HTTP/UI | Fastify 5, React, Vite, Zod contracts | full-stack framework, duplicated API types || Database | `node:sqlite` at `/var/lib/oloka/database/oloka.db`, one writer | ORM, external SQL database, app replicas || Durability | Litestream 0.5.11 to HF S3 `sqlite-replica/dev` | zero-data-loss claim, second app reader/writer || Bytes | filesystem object adapter rooted beneath `/data` | Git-tracked runtime bytes, live SQLite under `/data` || Jobs | in-process dispatcher with durable SQLite leases/outbox | RAM-only queue, message broker || Preview | immutable authorized artifact using the trusted HyperFrames materializer/player | arbitrary HTML, per-project permanent preview servers || Render | Modal adapter behind typed provider boundary | local production rendering, provider fan-out || Deploy | one HF Docker Space, one app instance | Cloudflare runtime, horizontal scale |## Component map3 unmodified linesG["Google OIDC"] <--> FF --> C["Zod contracts and domain services"]C --> R["Repositories and transaction runner"]R --> D[("Local SQLite /var/lib/oloka")]L["Litestream PID 1"] -->|"supervises"| FD -->|"continuous replication"| LL --> Q[("HF S3 sqlite-replica/dev")]C --> S["Filesystem object storage"]S --> O[("/data/objects")]U[("/data/tmp upload staging")] --> S36 unmodified lines- IDs are UUIDv4 generated with `crypto.randomUUID()`.- Database timestamps are UTC Unix epoch milliseconds stored as SQLite `INTEGER`.- Connections enable `foreign_keys=ON`, `journal_mode=WAL`, `synchronous=FULL`, and `busy_timeout=5000`.- Startup restores the absent local primary before application start. Production requires an explicit `fresh-if-replica-missing` or `restore-required` policy and fails closed on every restore error.- `node:sqlite` is synchronous. Statements and transactions must be short; provider calls, filesystem streaming, checksums, and media analysis never run while a transaction is open.- Routes never contain SQL. All writes use a transaction runner and repository interfaces.- JSON is Zod-validated, schema-versioned, RFC 8785 canonicalized UTF-8 text. Search/filter/join fields remain normal columns.9 unmodified lines## Availability and scale envelopeMVP intentionally supports one Space and one application writer. WAL improves read/write overlap; Litestream adds recovery transport, not multi-writer safety. Move to PostgreSQL when any of these become true: more than one application instance is required; sustained lock wait or write latency breaches the NFR; job throughput requires independent workers; backup/recovery objectives require managed point-in-time recovery or an independent failure domain; or dataset/storage growth makes maintenance windows unacceptable. No part of that exit is implemented in Phase 3A.1.## Source evidence
1234562 unmodified lines9101112131415# ADR 0017: SQLite in one Space instance for MVP- Status: Accepted- Date: 2026-08-05## Context2 unmodified lines## DecisionUse built-in `node:sqlite` with one database under `/data/database` and one application instance. Enable foreign keys, WAL, FULL synchronous writes, and 5000 ms busy timeout. SQL is contained in repositories; routes never execute it. Because the API is synchronous, transactions are short and never contain provider calls, media analysis, hashing, or filesystem streaming.## Consequences1234562 unmodified lines9101112131415# ADR 0017: SQLite in one Space instance for MVP- Status: Superseded in part by ADR 0027- Date: 2026-08-05## Context2 unmodified lines## DecisionUse built-in `node:sqlite` with one database and one application instance. ADR 0027 corrects the physical location from `/data/database` to the local primary `/var/lib/oloka/database/oloka.db` with Litestream durability. Enable foreign keys, WAL, FULL synchronous writes, and 5000 ms busy timeout. SQL is contained in repositories; routes never execute it. Because the API is synchronous, transactions are short and never contain provider calls, media analysis, hashing, or filesystem streaming.## Consequences
13 unmodified lines14151613 unmodified lines## ConsequencesExternal encrypted backup is post-MVP before stronger DR claims. Numeric RPO/RTO require owner confirmation. Multiple instances, write/lock pressure, independent workers, managed PITR, or storage/maintenance limits trigger planned SQLite->PostgreSQL, filesystem->S3, dispatcher->multi-worker architecture under new ADRs—not Phase 2 implementation.13 unmodified lines1415161718192013 unmodified lines## ConsequencesExternal encrypted backup is post-MVP before stronger DR claims. Numeric RPO/RTO require owner confirmation. Multiple instances, write/lock pressure, independent workers, managed PITR, or storage/maintenance limits trigger planned SQLite->PostgreSQL, filesystem->S3, dispatcher->multi-worker architecture under new ADRs—not Phase 2 implementation.ADR 0027 adds Litestream recovery transport for the local primary. It does notreplace this authenticated backup contract or make same-provider HF S3 anindependent disaster-recovery domain.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081# ADR 0027: Local SQLite with Hugging Face S3 replication
- Status: Accepted for implementation; production cutover pending- Date: 2026-08-06
## Context
SQLite WAL requires ordinary local filesystem locking and write semantics. TheHugging Face `/data` bucket mount is durable object storage presented through afilesystem interface; it is not a safe live SQLite primary. Keeping the livedatabase there risks lock, WAL, latency, and partial-filesystem failures.
The MVP still benefits from SQLite's small operational surface, built-in`node:sqlite` support, the existing custom migration/repository contracts, and asingle application writer. Moving to an ORM or PostgreSQL in Slice 3A.1 wouldexpand scope without evidence that the current scale envelope requires it.
The separate qualification PR proved Litestream 0.5.11 against the HF S3 API onNode 22.16.0. Qualification A-E covered direct object operations, continuousreplication/restore, multiple generations, abrupt termination, repeatedrestart, cross-UID process control, bounded outage/recovery, and secretredaction. The observed crash restored generation 3 after generation 4 hadcommitted: one sparse-write generation was lost, with a 60 ms commit-to-crashinterval and restored-state age of 8,018 ms. This observation is not a maximumRPO and does not support a zero-data-loss claim.
## Decision
Use one local SQLite primary at`/var/lib/oloka/database/oloka.db`. Keep `/data` exclusively for object/mediabytes, immutable backup sets, and legacy evidence. Litestream 0.5.11 runs ascontainer PID 1, supervises the single Fastify process, and continuouslyreplicates to HF S3 bucket `oloka-video-dev-data` under`sqlite-replica/dev`.
The image downloads `litestream-0.5.11-linux-x86_64.tar.gz`, verifies SHA-256`2f80fdb6b0a0ff7a116ee37adf02d3de8e977ef76e052b28a6690218f0f7ab55`,and carries only the binary and license into the non-root runtime. Credentialsare environment-only; `/etc/litestream.yml` contains no secret.
Startup validates absolute/real paths and symlinks before opening SQLite. Whenthe local DB is absent, it runs a bounded, integrity-checked conditionalrestore. `fresh-if-replica-missing` permits creation only for local/test or acontrolled first cutover. `restore-required` fails closed when no replica isavailable. Production has no bootstrap-mode default and therefore requires anexplicit operator choice.
Migrations remain immutable v1/v2; there is no v3 in this slice. The`deployment.runtime` witness records first/last start, exact startup count,build SHA, and runtime mode through the existing optimistic metadatarepository. Litestream 0.5.11 also owns `_litestream_lock` and`_litestream_seq`; these are transport-internal tables, not applicationmigrations or product schema.
## Consequences
- Exactly one Space/application writer is supported. A second replica or process opening the same primary is forbidden.- A local-disk loss is recovered from HF S3 before Fastify starts. Litestream failure terminates the supervised application instead of leaving false-ready HTTP service.- HF bucket replication and `/data` backups share provider/account failure domains. They improve restart durability but are not independent disaster recovery.- Recovery has a non-zero, workload-dependent RPO. Operational evidence must report measured loss/age rather than promise zero loss.- Existing authenticated pre-migration backups remain unchanged under `/data/backups/pre-migration`; Litestream does not replace that contract.- The legacy `/data/database/oloka-dev.db` remains untouched evidence. Its read-only bucket snapshot passed `quick_check`/foreign keys and contained only the six Slice 3A tables: `schema_migrations` had exactly two rows while `users`, `system_metadata`, `audit_events`, `outbox_events`, and `idempotency_records` each had zero rows. No product table/data was present, so no data migration or deletion is authorized.
PostgreSQL becomes the required exit when more than one application instanceor writer is needed, sustained database-operation/transaction/busy metricsbreach the NFR, independent workers are required, managed PITR or an independentfailure domain is required, or database size/maintenance makes the single-nodeenvelope unacceptable. That exit needs a separate ADR, migration, rollback,and product approval.12345614 unmodified lines212223242526272829import { defineConfig, devices } from "@playwright/test";import { join } from "node:path";import { pathToFileURL } from "node:url";const dataDir = join(process.cwd(), ".tmp", "playwright-data");14 unmodified linesenv: {NODE_ENV: "test",PORT: "7860",DATA_DIR: dataDir,DATABASE_URL: pathToFileURL(join(dataDir, "database", "playwright.db")).href,APP_VERSION: "0.1.0",GIT_COMMIT_SHA: "playwright",BUILD_TIMESTAMP: "playwright",1234514 unmodified lines202122232425262728import { defineConfig, devices } from "@playwright/test";import { join } from "node:path";const dataDir = join(process.cwd(), ".tmp", "playwright-data");14 unmodified linesenv: {NODE_ENV: "test",PORT: "7860",OBJECT_STORAGE_ROOT: join(dataDir, "objects"),DATABASE_PATH: join(dataDir, "local", "playwright.db"),OLOKA_DATABASE_BOOTSTRAP_MODE: "fresh-if-replica-missing",APP_VERSION: "0.1.0",GIT_COMMIT_SHA: "playwright",BUILD_TIMESTAMP: "playwright",
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227#!/usr/bin/env bashset -euo pipefail
export MSYS_NO_PATHCONV=1
image="${1:?production image tag is required}"run_id="${RECOVERY_RUN_ID:-local-$$}"run_id="${run_id//[^a-zA-Z0-9_.-]/-}"network="oloka-recovery-network-$run_id"minio_container="oloka-recovery-minio-$run_id"minio_volume="oloka-recovery-minio-data-$run_id"object_volume="oloka-recovery-objects-$run_id"bucket="oloka-recovery"prefix="sqlite-replica/dev"minio_image="quay.io/minio/minio@sha256:a1ea29fa28355559ef137d71fc570e508a214ec84ff8083e39bc5428980b015e"mc_image="quay.io/minio/mc@sha256:aead63c77f9db9107f1696fb08ecb0faeda23729cde94b0f663edf4fe09728e3"access_key="minio-ci-access"secret_key="minio-ci-secret-value"application_key="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"containers=()volumes=("$minio_volume" "$object_volume")
cleanup() { for boot in 1 2 3; do docker rm -f "oloka-recovery-boot-$boot-$run_id" >/dev/null 2>&1 || true done for container in "${containers[@]}"; do docker rm -f "$container" >/dev/null 2>&1 || true done docker rm -f "$minio_container" >/dev/null 2>&1 || true docker network rm "$network" >/dev/null 2>&1 || true for volume in "${volumes[@]}"; do docker volume rm "$volume" >/dev/null 2>&1 || true done}trap cleanup EXIT
mc() { docker run --rm --network "$network" --entrypoint /bin/sh "$mc_image" -c \ "mc alias set ci http://$minio_container:9000 '$access_key' '$secret_key' >/dev/null 2>&1 && mc $*"}
wait_for_minio() { for _ in $(seq 1 60); do if mc "ready ci >/dev/null 2>&1"; then return 0; fi sleep 1 done echo "MinIO did not become ready" >&2 return 1}
wait_for_application() { local container="$1" for _ in $(seq 1 60); do if docker exec "$container" node -e \ "fetch('http://127.0.0.1:7860/api/ready').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))"; then return 0 fi if [ "$(docker inspect -f '{{.State.Running}}' "$container")" != "true" ]; then docker logs "$container" >&2 return 1 fi sleep 1 done docker logs "$container" >&2 echo "Application did not become ready" >&2 return 1}
wait_for_replica() { for _ in $(seq 1 60); do if [ "$(mc "ls --recursive ci/$bucket/$prefix 2>/dev/null | wc -l" | tr -d '[:space:]')" -gt 0 ]; then return 0 fi sleep 1 done echo "Litestream replica did not appear" >&2 return 1}
start_boot() { local boot="$1" local mode="$2" local local_volume="$3" local container="oloka-recovery-boot-$boot-$run_id" containers+=("$container") docker run -d --name "$container" --network "$network" \ -e OLOKA_DATABASE_BOOTSTRAP_MODE="$mode" \ -e HF_S3_ACCESS_KEY_ID="$access_key" \ -e HF_S3_SECRET_ACCESS_KEY="$secret_key" \ -e OLOKA_APP_KEY="$application_key" \ -e HF_S3_ENDPOINT="http://$minio_container:9000" \ -e HF_S3_REGION=us-east-1 \ -e HF_S3_BUCKET="$bucket" \ -e HF_S3_SQLITE_PREFIX="$prefix" \ -v "$local_volume:/var/lib/oloka" \ -v "$object_volume:/data" \ "$image" >/dev/null wait_for_application "$container" docker exec "$container" node --input-type=module -e ' const urls=["/api/health","/api/ready","/api/version"]; const responses=await Promise.all(urls.map(path=>fetch(`http://127.0.0.1:7860${path}`))); if (responses.some(response=>response.status !== 200)) process.exit(1); const payloads=await Promise.all(responses.map(response=>response.json())); if (payloads[0].status !== "ok" || payloads[1].status !== "ready") process.exit(1); if (JSON.stringify(payloads).includes("/var/lib/oloka")) process.exit(1); ' printf '%s' "$container"}
stop_boot() { local container="$1" local started_at finished_at elapsed logs started_at="$(date +%s)" docker stop --time 20 "$container" >/dev/null finished_at="$(date +%s)" elapsed=$((finished_at - started_at)) if [ "$elapsed" -gt 20 ]; then echo "Container shutdown exceeded the bounded grace period" >&2 return 1 fi logs="$(docker logs "$container" 2>&1)" grep -q 'graceful shutdown started' <<<"$logs" if grep -Fq "$access_key" <<<"$logs" || \ grep -Fq "$secret_key" <<<"$logs" || \ grep -Fq "$application_key" <<<"$logs"; then echo "A test credential leaked into container logs" >&2 return 1 fi echo "boot_container=$container shutdown_seconds=$elapsed secret_scan=pass"}
inspect_database() { local local_volume="$1" docker run --rm --entrypoint node \ -v "$local_volume:/var/lib/oloka" "$image" --input-type=module -e ' import { DatabaseSync } from "node:sqlite"; const db = new DatabaseSync("/var/lib/oloka/database/oloka.db", { readOnly: true }); const quickCheck = Object.values(db.prepare("PRAGMA quick_check").get())[0]; const foreignKeyFailures = db.prepare("PRAGMA foreign_key_check").all().length; const ledger = db.prepare("SELECT version, name, checksum_sha256, applied_at FROM schema_migrations ORDER BY version").all(); const tables = db.prepare("SELECT name FROM sqlite_schema WHERE type = ? AND name NOT LIKE ? ORDER BY name").all("table", "sqlite_%").map(row => row.name); const coreTables = tables.filter(name => !name.startsWith("_litestream_")); const litestreamTables = tables.filter(name => name.startsWith("_litestream_")); const metadata = db.prepare("SELECT value_json, version FROM system_metadata WHERE key = ?").get("deployment.runtime"); db.close(); process.stdout.write(JSON.stringify({ quickCheck, foreignKeyFailures, ledger, coreTables, litestreamTables, metadataVersion: metadata.version, witness: JSON.parse(metadata.value_json) })); '}
docker network create "$network" >/dev/nulldocker volume create "$minio_volume" >/dev/nulldocker volume create "$object_volume" >/dev/nulldocker run -d --name "$minio_container" --network "$network" \ -e MINIO_ROOT_USER="$access_key" \ -e MINIO_ROOT_PASSWORD="$secret_key" \ -v "$minio_volume:/data" \ "$minio_image" server /data --console-address :9001 >/dev/nullwait_for_miniomc "mb --ignore-existing ci/$bucket >/dev/null"
missing_volume="oloka-recovery-missing-$run_id"volumes+=("$missing_volume")docker volume create "$missing_volume" >/dev/nullset +emissing_output="$(docker run --rm --network "$network" \ -e OLOKA_DATABASE_BOOTSTRAP_MODE=restore-required \ -e HF_S3_ACCESS_KEY_ID="$access_key" \ -e HF_S3_SECRET_ACCESS_KEY="$secret_key" \ -e OLOKA_APP_KEY="$application_key" \ -e HF_S3_ENDPOINT="http://$minio_container:9000" \ -e HF_S3_BUCKET="$bucket" \ -e HF_S3_SQLITE_PREFIX="$prefix" \ -v "$missing_volume:/var/lib/oloka" \ -v "$object_volume:/data" "$image" 2>&1)"missing_exit=$?set -eif [ "$missing_exit" -eq 0 ] || ! grep -q 'DATABASE_BOOTSTRAP_FAILED' <<<"$missing_output"; then echo "restore-required did not fail closed for a missing replica" >&2 exit 1fiecho "missing_replica_restore_required=fail_closed"
first_started_at=""ledger_json=""for boot in 1 2 3; do local_volume="oloka-recovery-local-$boot-$run_id" volumes+=("$local_volume") docker volume create "$local_volume" >/dev/null mode="restore-required" if [ "$boot" -eq 1 ]; then mode="fresh-if-replica-missing"; fi container="$(start_boot "$boot" "$mode" "$local_volume")" wait_for_replica stop_boot "$container" evidence="$(inspect_database "$local_volume")" echo "boot_evidence=$evidence" startup_count="$(docker run --rm -i --entrypoint node "$image" --input-type=commonjs -e 'const d=JSON.parse(require("fs").readFileSync(0,"utf8")); process.stdout.write(String(d.witness.startupCount))' <<<"$evidence")" current_first_started_at="$(docker run --rm -i --entrypoint node "$image" --input-type=commonjs -e 'const d=JSON.parse(require("fs").readFileSync(0,"utf8")); process.stdout.write(String(d.witness.firstStartedAt))' <<<"$evidence")" current_ledger="$(docker run --rm -i --entrypoint node "$image" --input-type=commonjs -e 'const d=JSON.parse(require("fs").readFileSync(0,"utf8")); process.stdout.write(JSON.stringify(d.ledger))' <<<"$evidence")" test "$startup_count" = "$boot" docker run --rm -i --entrypoint node "$image" --input-type=commonjs -e ' const d=JSON.parse(require("fs").readFileSync(0,"utf8")); const expectedTables=["audit_events","idempotency_records","outbox_events","schema_migrations","system_metadata","users"]; const valid=d.metadataVersion === d.witness.startupCount && d.quickCheck === "ok" && d.foreignKeyFailures === 0 && JSON.stringify(d.ledger.map(row=>row.version)) === JSON.stringify([1,2]) && JSON.stringify(d.ledger.map(row=>row.name)) === JSON.stringify(["foundation_system_tables","persistence-kernel"]) && JSON.stringify(d.coreTables) === JSON.stringify(expectedTables) && JSON.stringify(d.litestreamTables) === JSON.stringify(["_litestream_lock","_litestream_seq"]); if (!valid) process.exit(1); ' <<<"$evidence" if [ "$boot" -eq 1 ]; then first_started_at="$current_first_started_at" ledger_json="$current_ledger" else test "$current_first_started_at" = "$first_started_at" test "$current_ledger" = "$ledger_json" fi echo "boot=$boot startup_count=$startup_count first_started_at=$current_first_started_at ledger_versions=1,2 quick_check=ok foreign_keys=0" docker rm "$container" >/dev/null docker volume rm "$local_volume" >/dev/nulldone
docker run --rm --entrypoint sh -v "$object_volume:/data" "$image" -c \ 'test ! -d /data/backups/pre-migration'remaining_replica_objects="$(mc "ls --recursive ci/$bucket/$prefix | wc -l" | tr -d '[:space:]')"test "$remaining_replica_objects" -gt 0echo "replica_objects=$remaining_replica_objects no_pending_migration_backup=pass recovery_test=pass".env.example+10-2
.github/workflows/deploy-hf.yml+23-3
.github/workflows/validation.yml+21-48
Dockerfile+32-4
README.md+14-8
apps/server/src/app.ts+24-2
apps/server/src/config/environment.ts+95-31
apps/server/src/config/environment.unit.test.ts+78-2
apps/server/src/database/create-database.ts+16-12
apps/server/src/database/migration-runner.integration.test.ts+4-8
apps/server/src/database/sqlite-system-database.ts+46-4
apps/server/src/database/transaction-runner.integration.test.ts+5-1
apps/server/src/http/routes.integration.test.ts+5-3
apps/server/src/index.ts+24-1
apps/server/src/observability/operational-metrics.tsAdded+84
apps/server/src/observability/operational-metrics.unit.test.tsAdded+35
apps/server/src/startup/bootstrap-database.tsAdded+44
apps/server/src/startup/database-bootstrap.tsAdded+72
apps/server/src/startup/database-bootstrap.unit.test.tsAdded+144
apps/server/src/startup/database-path.tsAdded+91
apps/server/src/startup/database-path.unit.test.tsAdded+109
apps/server/src/startup/legacy-database.integration.test.tsAdded+42
apps/server/src/startup/litestream-restorer.tsAdded+50
apps/server/src/startup/litestream-restorer.unit.test.tsAdded+42
apps/server/src/system/runtime-witness-service.tsAdded+56
apps/server/src/system/runtime-witness.integration.test.tsAdded+84
docker/entrypoint.shAdded+14
docker/litestream.ymlAdded+14
docs/architecture/BACKUP_AND_RECOVERY.md+7-3
docs/architecture/DATABASE_MIGRATION_STRATEGY.md+9-2
docs/architecture/DEPLOYMENT.md+14-7
docs/architecture/FOUNDATION.md+1-1
docs/architecture/IMPLEMENTATION_SEQUENCE.md+2-1
docs/architecture/LOCAL_DEVELOPMENT.md+2-1
docs/architecture/OBJECT_STORAGE_V1.md+2-2
docs/architecture/PHASE3A_PERSISTENCE_KERNEL.md+23-11
docs/architecture/TECHNICAL_ARCHITECTURE_V1.md+19-14
docs/decisions/0017-sqlite-single-space-mvp.md+2-2
docs/decisions/0026-backup-recovery-and-scaling-exit.md+4
docs/decisions/0027-local-sqlite-with-hf-s3-replication.mdAdded+81
playwright.config.ts+3-4
scripts/run-docker-litestream-recovery.shAdded+227