diff --git a/.agents/notes.md b/.agents/notes.md index 249d058..502272c 100644 --- a/.agents/notes.md +++ b/.agents/notes.md @@ -51,3 +51,4 @@ [0] Drizzle SQLite migrator runs migrations in a transaction; `PRAGMA foreign_keys=OFF` inside migration SQL may not disable FK checks. Table-copy migrations should filter/clean orphan rows explicitly (e.g., `INNER JOIN` parents) instead of relying on that pragma. [0] CI `validate` workflow currently runs `format:check`, `lint`, `test`, and `apps/web` build. Before pushing, run all four locally to avoid fast-follow CI fix commits. [0] `stash db doctor` does not create parent directories for a missing DB path; if `STASH_DB_PATH` points to a non-existent directory, command can fail with `unable to open database file`. +[0] Prefer explicit named types over `ReturnType` in production code/tests for readability and easier review comments. diff --git a/AGENTS.md b/AGENTS.md index c6b698b..145384c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -302,6 +302,15 @@ node apps/cli/dist/cli.js --help node apps/cli/dist/cli.js list --help ``` +## Pre-PR Handoff Gate + +Before opening a PR/MR, run local quality gates and keep them green. + +- Code changes: must run `pnpm run check` and fix all failures before PR/MR creation. +- Docs-only changes: must run `pnpm run format:check` before PR/MR creation. +- PR flow: use existing `gh` tooling (`gh pr create`), then watch checks with `gh pr checks --watch`. +- If CI fails, fix locally, re-run the local gate, push, and re-check until all required checks are green. + ## Documentation Maintenance Rule ⚠️ **When adding new features or modifying existing CLI behavior, update ALL THREE documentation files in the same change:** @@ -370,5 +379,6 @@ Updates should include: - Prefer Drizzle ORM for database access in application/runtime code. - Use raw SQL string queries only when Drizzle does not support the required functionality clearly or safely (for example, specialized migration-runner behavior). - Prefer explicit return types on functions and methods (especially exported/public APIs and non-trivial helpers). +- Prefer explicit named types over inferred meta-types like `ReturnType` in app/core code and tests. - Dependency injection pattern: prefer `createXService`/`createCoreServices` factory objects over classes, and inject least-privilege service slices into API route plugins and command handlers. - In this sandbox, local listener startup (for example Vite/dev servers on `127.0.0.1`) may fail with `listen EPERM`; validate listener-bound flows in a less restricted environment when needed. diff --git a/README.md b/README.md index d3741d1..64ba90a 100644 --- a/README.md +++ b/README.md @@ -103,14 +103,17 @@ pnpm run setup ## Code Quality ```bash +pnpm run check pnpm run lint pnpm run format:check -pnpm run check ``` +For code changes, use `pnpm run check` as the local pre-PR gate. +For docs-only changes, run `pnpm run format:check`. + ## CI -GitHub Actions runs on pull requests and pushes to `main` with strict checks: +GitHub Actions runs on pull requests and pushes to `main` with strict staged checks: ```bash pnpm run format:check && pnpm run lint && pnpm run test && pnpm --dir apps/web build diff --git a/apps/api/src/app/create-api-app.ts b/apps/api/src/app/create-api-app.ts index 97a1daa..e317cec 100644 --- a/apps/api/src/app/create-api-app.ts +++ b/apps/api/src/app/create-api-app.ts @@ -1,25 +1,24 @@ import Fastify, { type FastifyInstance } from "fastify" -import { createCoreServices } from "@stash/core" +import type { CoreServices } from "@stash/core" import { extractRoutes } from "../features/extract/routes.js" import { inboxRoutes } from "../features/inbox/routes.js" import { itemRoutes } from "../features/item/routes.js" -import type { ApiRouteOptions } from "../features/options.js" import { saveRoutes } from "../features/save/routes.js" import { statusRoutes } from "../features/status/routes.js" import { tagsRoutes } from "../features/tags/routes.js" import { ttsRoutes } from "../features/tts/routes.js" import { registerApiErrorHandlers } from "./error-handler.js" -export type CreateApiAppOptions = ApiRouteOptions +export type CreateApiAppOptions = { + services: CoreServices + audioDir: string +} export function createApiApp(options: CreateApiAppOptions): FastifyInstance { const server = Fastify({ logger: false, }) - const services = createCoreServices({ - dbPath: options.dbPath, - migrationsDir: options.migrationsDir, - }) + const { services } = options // Fastify's default JSON parser rejects empty bodies (e.g. DELETE with Content-Type: application/json). // Override it to treat empty bodies as undefined instead of an error. diff --git a/apps/api/src/app/server.ts b/apps/api/src/app/server.ts index 2453d67..8a496b2 100644 --- a/apps/api/src/app/server.ts +++ b/apps/api/src/app/server.ts @@ -1,6 +1,7 @@ import http from "node:http" -import { resolveAudioDir, startTtsWorker } from "@stash/core" +import type { FastifyInstance } from "fastify" +import { createCoreRuntime, resolveAudioDir, type TtsWorkerHandle } from "@stash/core" import { createApiApp } from "./create-api-app.js" import { serveStatic } from "./static.js" @@ -102,7 +103,7 @@ async function listenServer( } async function listenApiServer( - server: ReturnType, + server: FastifyInstance, host: string, port: number, ): Promise { @@ -202,6 +203,26 @@ function sendJson(res: http.ServerResponse, statusCode: number, value: unknown): res.end(body) } +async function shutdownApiResources( + server: FastifyInstance, + ttsWorker: TtsWorkerHandle, + closeRuntime: () => void, +): Promise { + const results = await Promise.allSettled([ttsWorker.stop(), server.close()]) + closeRuntime() + + const errors = results + .filter((result): result is PromiseRejectedResult => result.status === "rejected") + .map((result) => result.reason) + + if (errors.length === 1) { + throw errors[0] + } + if (errors.length > 1) { + throw new AggregateError(errors, "Failed to shutdown API server resources.") + } +} + export async function startApiServer(options: StartApiServerOptions): Promise { const audioDir = resolveAudioDir(options.audioDir) const workerOptions = { audioDir } as { audioDir: string; pollMs?: number } @@ -209,25 +230,31 @@ export async function startApiServer(options: StartApiServerOptions): Promise { - await ttsWorker.stop() - await server.close() + await shutdownApiResources(server, ttsWorker, runtime.close) }, } } diff --git a/apps/api/src/features/options.ts b/apps/api/src/features/options.ts deleted file mode 100644 index 45bcceb..0000000 --- a/apps/api/src/features/options.ts +++ /dev/null @@ -1,5 +0,0 @@ -export type ApiRouteOptions = { - dbPath: string - migrationsDir: string - audioDir: string -} diff --git a/apps/api/test/integration.test.ts b/apps/api/test/integration.test.ts index be45490..8e1e1e1 100644 --- a/apps/api/test/integration.test.ts +++ b/apps/api/test/integration.test.ts @@ -5,6 +5,7 @@ import path from "node:path" import { fileURLToPath } from "node:url" import { describe, expect, it } from "vitest" +import { createCoreRuntime } from "@stash/core" import { createApiApp } from "../src/app/create-api-app.js" @@ -169,9 +170,12 @@ const integrationTitle = sqliteBindingsMissing integrationSuite(integrationTitle, () => { it("keeps endpoint response contracts stable across save/list/item/status/extract/tags/tts flows", async () => { const { dbPath, audioDir, cleanup } = createTempPaths() - const app = createApiApp({ + const runtime = createCoreRuntime({ dbPath, migrationsDir, + }) + const app = createApiApp({ + services: runtime.services, audioDir, }) @@ -322,6 +326,7 @@ integrationSuite(integrationTitle, () => { expect(itemJobsBody.jobs[0]?.id).toBe(enqueueTtsBody.job.id) } finally { await app.close() + runtime.close() cleanup() } }) diff --git a/apps/cli/src/cli.ts b/apps/cli/src/cli.ts index 387c2dc..267a31f 100644 --- a/apps/cli/src/cli.ts +++ b/apps/cli/src/cli.ts @@ -6,14 +6,15 @@ import { fileURLToPath } from "node:url" import { Command, InvalidArgumentError } from "commander" import { + createCoreRuntime, DEFAULT_AUDIO_DIR, DEFAULT_DB_PATH, StashError, - createCoreServices, getMigrationStatus, resolveAudioDir, resolveDbPath, runMigrations, + type CoreServices, type StashItem as CoreStashItem, } from "@stash/core" @@ -262,6 +263,43 @@ function resolveMigrationsDir(value?: string): string { return path.resolve(value) } +function withCoreRuntime(action: (services: CoreServices) => T | Promise): T | Promise { + const runtime = createCoreRuntime({ + dbPath: resolveDbPath(program.opts().dbPath as string), + migrationsDir: resolveMigrationsDir(), + }) + let closed = false + const closeRuntime = (): void => { + if (closed) { + return + } + closed = true + runtime.close() + } + + try { + const result = action(runtime.services) + if (isPromiseLike(result)) { + return Promise.resolve(result).finally(() => { + closeRuntime() + }) + } + closeRuntime() + return result + } catch (error) { + closeRuntime() + throw error + } +} + +function isPromiseLike(value: unknown): value is PromiseLike { + return ( + value !== null && + (typeof value === "object" || typeof value === "function") && + typeof (value as { then?: unknown }).then === "function" + ) +} + function ensureMigrationsDirExists(migrationsDir: string): void { if (!fs.existsSync(migrationsDir)) { throw new CliError( @@ -441,40 +479,36 @@ program }, ) => { const jsonMode = Boolean(options.json) - const context = { - dbPath: resolveDbPath(program.opts().dbPath as string), - migrationsDir: resolveMigrationsDir(), - } - const services = createCoreServices(context) - - return runDbAction(jsonMode, async () => { - const saveInput = { - url, - tags: options.tag ?? [], - ...(options.title !== undefined ? { title: options.title } : {}), - ...(options.extract !== undefined ? { extract: options.extract } : {}), - ...(options.autoTags !== undefined ? { autoTags: options.autoTags } : {}), - } - const result = await services.items.saveItem(saveInput) + return runDbAction(jsonMode, () => + withCoreRuntime(async (services) => { + const saveInput = { + url, + tags: options.tag ?? [], + ...(options.title !== undefined ? { title: options.title } : {}), + ...(options.extract !== undefined ? { extract: options.extract } : {}), + ...(options.autoTags !== undefined ? { autoTags: options.autoTags } : {}), + } + const result = await services.items.saveItem(saveInput) - if (jsonMode) { - printJson({ - ok: true, - ...result, - }) - return - } + if (jsonMode) { + printJson({ + ok: true, + ...result, + }) + return + } - process.stdout.write( - `${result.created ? "saved" : "exists"} #${result.item.id} ${result.item.url}\n`, - ) - if (result.auto_tags && result.auto_tags.length > 0) { - process.stdout.write(`auto-tags: ${result.auto_tags.join(", ")}\n`) - } - if (result.auto_tag_warning) { - process.stdout.write(`auto-tags warning: ${result.auto_tag_warning}\n`) - } - }) + process.stdout.write( + `${result.created ? "saved" : "exists"} #${result.item.id} ${result.item.url}\n`, + ) + if (result.auto_tags && result.auto_tags.length > 0) { + process.stdout.write(`auto-tags: ${result.auto_tags.join(", ")}\n`) + } + if (result.auto_tag_warning) { + process.stdout.write(`auto-tags warning: ${result.auto_tag_warning}\n`) + } + }), + ) }, ) @@ -501,158 +535,152 @@ program }, ) => { const jsonMode = Boolean(options.json) - const dbPath = resolveDbPath(program.opts().dbPath as string) - const context = { - dbPath, - migrationsDir: resolveMigrationsDir(), - } - const services = createCoreServices(context) - - return runDbAction(jsonMode, async () => { - if (id === "doctor") { - if (jobId !== undefined) { - throw new CliError( - "Unexpected extra argument for `stash tts doctor`.", - "VALIDATION_ERROR", - 2, - ) - } + return runDbAction(jsonMode, () => + withCoreRuntime(async (services) => { + if (id === "doctor") { + if (jobId !== undefined) { + throw new CliError( + "Unexpected extra argument for `stash tts doctor`.", + "VALIDATION_ERROR", + 2, + ) + } - const report = services.doctor.inspectCoquiTtsHealth() - if (jsonMode) { - printJson({ - ok: true, - ...report, - }) - } else { - process.stdout.write(`tts doctor: ${report.healthy ? "healthy" : "unhealthy"}\n`) - for (const check of report.checks) { - const requirement = check.required ? "required" : "optional" - const status = check.ok ? "ok" : "failed" - const resolvedPath = check.path ?? "-" - process.stdout.write(`${check.id} (${requirement}): ${status} [${resolvedPath}]\n`) - if (check.message) { - process.stdout.write(` ${check.message}\n`) + const report = services.doctor.inspectCoquiTtsHealth() + if (jsonMode) { + printJson({ + ok: true, + ...report, + }) + } else { + process.stdout.write(`tts doctor: ${report.healthy ? "healthy" : "unhealthy"}\n`) + for (const check of report.checks) { + const requirement = check.required ? "required" : "optional" + const status = check.ok ? "ok" : "failed" + const resolvedPath = check.path ?? "-" + process.stdout.write(`${check.id} (${requirement}): ${status} [${resolvedPath}]\n`) + if (check.message) { + process.stdout.write(` ${check.message}\n`) + } } + process.stdout.write( + `coqui flags: --text_file=${report.coqui_cli_features.supports_text_file ? "yes" : "no"} --progress_bar=${report.coqui_cli_features.supports_progress_bar ? "yes" : "no"}\n`, + ) + process.stdout.write( + `invocation strategy: ${report.invocation_strategy.replaceAll("_", " ")}\n`, + ) } - process.stdout.write( - `coqui flags: --text_file=${report.coqui_cli_features.supports_text_file ? "yes" : "no"} --progress_bar=${report.coqui_cli_features.supports_progress_bar ? "yes" : "no"}\n`, - ) - process.stdout.write( - `invocation strategy: ${report.invocation_strategy.replaceAll("_", " ")}\n`, - ) + + if (!report.healthy) { + process.exitCode = 2 + } + return } - if (!report.healthy) { - process.exitCode = 2 + if (id === "status") { + if (!jobId) { + throw new CliError( + "Job id is required: stash tts status ", + "VALIDATION_ERROR", + 2, + ) + } + const parsedJobId = parseItemId(jobId) + const job = services.ttsJobs.getTtsJob(parsedJobId) + + if (jsonMode) { + printJson({ + ok: true, + job, + }) + return + } + + const suffix = job.error_message ? ` (${job.error_message})` : "" + process.stdout.write(`tts job #${job.id} ${job.status}${suffix}\n`) + return } - return - } - if (id === "status") { - if (!jobId) { + if (jobId !== undefined) { throw new CliError( - "Job id is required: stash tts status ", + "Unexpected extra argument for `stash tts `.", "VALIDATION_ERROR", 2, ) } - const parsedJobId = parseItemId(jobId) - const job = services.ttsJobs.getTtsJob(parsedJobId) - - if (jsonMode) { - printJson({ - ok: true, - job, - }) - return - } - - const suffix = job.error_message ? ` (${job.error_message})` : "" - process.stdout.write(`tts job #${job.id} ${job.status}${suffix}\n`) - return - } - if (jobId !== undefined) { - throw new CliError( - "Unexpected extra argument for `stash tts `.", - "VALIDATION_ERROR", - 2, - ) - } + const itemId = parseItemId(id) + const enqueue = services.ttsJobs.enqueueTtsJob({ + itemId, + voice: options.voice, + format: options.format, + }) - const itemId = parseItemId(id) - const enqueue = services.ttsJobs.enqueueTtsJob({ - itemId, - voice: options.voice, - format: options.format, - }) + if (!options.wait) { + if (jsonMode) { + printJson({ + ok: true, + created: enqueue.created, + job_id: enqueue.job.id, + status: enqueue.job.status, + poll_interval_ms: enqueue.poll_interval_ms, + }) + return + } - if (!options.wait) { - if (jsonMode) { - printJson({ - ok: true, - created: enqueue.created, - job_id: enqueue.job.id, - status: enqueue.job.status, - poll_interval_ms: enqueue.poll_interval_ms, - }) + process.stdout.write( + `${enqueue.created ? "queued" : "existing"} tts job #${enqueue.job.id} for item #${itemId}\n`, + ) return } - process.stdout.write( - `${enqueue.created ? "queued" : "existing"} tts job #${enqueue.job.id} for item #${itemId}\n`, - ) - return - } - - const audioDir = resolveAudioDir(process.env.STASH_AUDIO_DIR ?? DEFAULT_AUDIO_DIR) - const worker = services.ttsJobs.startTtsWorker({ - pollMs: options.pollMs, - audioDir, - }) - - try { - const completed = await services.ttsJobs.waitForTtsJob(enqueue.job.id, { + const audioDir = resolveAudioDir(process.env.STASH_AUDIO_DIR ?? DEFAULT_AUDIO_DIR) + const worker = services.ttsJobs.startTtsWorker({ pollMs: options.pollMs, + audioDir, }) - if (completed.status === "failed") { - const code = completed.error_code ?? "INTERNAL_ERROR" - const exitCode = code === "NO_CONTENT" ? 2 : code === "NOT_FOUND" ? 3 : 1 - throw new CliError(completed.error_message ?? "TTS job failed.", code, exitCode) - } + try { + const completed = await services.ttsJobs.waitForTtsJob(enqueue.job.id, { + pollMs: options.pollMs, + }) - const fileName = completed.output_file_name - if (!fileName) { - throw new CliError( - `TTS job ${completed.id} completed without output file.`, - "INTERNAL_ERROR", - 1, - ) - } - const outputPath = path.join(audioDir, fileName) + if (completed.status === "failed") { + const code = completed.error_code ?? "INTERNAL_ERROR" + const exitCode = code === "NO_CONTENT" ? 2 : code === "NOT_FOUND" ? 3 : 1 + throw new CliError(completed.error_message ?? "TTS job failed.", code, exitCode) + } - if (jsonMode) { - printJson({ - ok: true, - job_id: completed.id, - item_id: completed.item_id, - status: completed.status, - output_file_name: fileName, - output_path: outputPath, - }) - return - } + const fileName = completed.output_file_name + if (!fileName) { + throw new CliError( + `TTS job ${completed.id} completed without output file.`, + "INTERNAL_ERROR", + 1, + ) + } + const outputPath = path.join(audioDir, fileName) + + if (jsonMode) { + printJson({ + ok: true, + job_id: completed.id, + item_id: completed.item_id, + status: completed.status, + output_file_name: fileName, + output_path: outputPath, + }) + return + } - process.stdout.write(`generated #${completed.item_id} ${outputPath}\n`) - } finally { - await worker.stop() - } - }) + process.stdout.write(`generated #${completed.item_id} ${outputPath}\n`) + } finally { + await worker.stop() + } + }), + ) }, ) - program .command("extract ") .description("Extract or re-extract content for an item") @@ -662,36 +690,33 @@ program .option("--json", "Print machine-readable JSON output") .action(async (id: string, options: { force?: boolean; autoTags?: boolean; json?: boolean }) => { const jsonMode = Boolean(options.json) - const context = { - dbPath: resolveDbPath(program.opts().dbPath as string), - migrationsDir: resolveMigrationsDir(), - } - const services = createCoreServices(context) const itemId = parseItemId(id) - return runDbAction(jsonMode, async () => { - const extractOptions = { - ...(options.force !== undefined ? { force: options.force } : {}), - ...(options.autoTags !== undefined ? { autoTags: options.autoTags } : {}), - } - const result = await services.extract.extractItem(itemId, extractOptions) + return runDbAction(jsonMode, () => + withCoreRuntime(async (services) => { + const extractOptions = { + ...(options.force !== undefined ? { force: options.force } : {}), + ...(options.autoTags !== undefined ? { autoTags: options.autoTags } : {}), + } + const result = await services.extract.extractItem(itemId, extractOptions) - if (jsonMode) { - printJson({ - ok: true, - ...result, - }) - return - } + if (jsonMode) { + printJson({ + ok: true, + ...result, + }) + return + } - process.stdout.write(`extracted #${itemId} (${result.content_length} chars)\n`) - if (result.auto_tags && result.auto_tags.length > 0) { - process.stdout.write(`auto-tags: ${result.auto_tags.join(", ")}\n`) - } - if (result.auto_tag_warning) { - process.stdout.write(`auto-tags warning: ${result.auto_tag_warning}\n`) - } - }) + process.stdout.write(`extracted #${itemId} (${result.content_length} chars)\n`) + if (result.auto_tags && result.auto_tags.length > 0) { + process.stdout.write(`auto-tags: ${result.auto_tags.join(", ")}\n`) + } + if (result.auto_tag_warning) { + process.stdout.write(`auto-tags warning: ${result.auto_tag_warning}\n`) + } + }), + ) }) program @@ -728,48 +753,44 @@ program printError("Invalid tag mode. Use any or all.", jsonMode, "VALIDATION_ERROR", 2) } - const context = { - dbPath: resolveDbPath(program.opts().dbPath as string), - migrationsDir: resolveMigrationsDir(), - } - const services = createCoreServices(context) - - runDbAction(jsonMode, () => { - const tags = normalizeTags(options.tag ?? []) - const listInput = { - tags, - tagMode, - limit: options.limit, - offset: options.offset, - ...(status ? { status } : {}), - } - const result = services.items.listItems(listInput) - const items = result.items.map(toCliListItem) + runDbAction(jsonMode, () => + withCoreRuntime((services) => { + const tags = normalizeTags(options.tag ?? []) + const listInput = { + tags, + tagMode, + limit: options.limit, + offset: options.offset, + ...(status ? { status } : {}), + } + const result = services.items.listItems(listInput) + const items = result.items.map(toCliListItem) - if (jsonMode) { - printJson({ - ok: true, - items, - paging: { - limit: options.limit, - offset: options.offset, - returned: items.length, - }, - }) - return - } + if (jsonMode) { + printJson({ + ok: true, + items, + paging: { + limit: options.limit, + offset: options.offset, + returned: items.length, + }, + }) + return + } - if (items.length === 0) { - process.stdout.write("No items found.\n") - return - } + if (items.length === 0) { + process.stdout.write("No items found.\n") + return + } - for (const item of items) { - const displayTitle = item.title ?? item.url - const displayTags = item.tags.length > 0 ? ` [${item.tags.join(", ")}]` : "" - process.stdout.write(`#${item.id} ${item.status} ${displayTitle}${displayTags}\n`) - } - }) + for (const item of items) { + const displayTitle = item.title ?? item.url + const displayTags = item.tags.length > 0 ? ` [${item.tags.join(", ")}]` : "" + process.stdout.write(`#${item.id} ${item.status} ${displayTitle}${displayTags}\n`) + } + }), + ) }, ) @@ -793,35 +814,31 @@ tagsCommand .option("--json", "Print machine-readable JSON output") .action((options: { limit: number; offset: number; json?: boolean }) => { const jsonMode = Boolean(options.json) - const context = { - dbPath: resolveDbPath(program.opts().dbPath as string), - migrationsDir: resolveMigrationsDir(), - } - const services = createCoreServices(context) - - runDbAction(jsonMode, () => { - const result = services.tags.listTags({ - limit: options.limit, - offset: options.offset, - }) - - if (jsonMode) { - printJson({ - ok: true, - ...result, + runDbAction(jsonMode, () => + withCoreRuntime((services) => { + const result = services.tags.listTags({ + limit: options.limit, + offset: options.offset, }) - return - } - if (result.tags.length === 0) { - process.stdout.write("No tags found.\n") - return - } + if (jsonMode) { + printJson({ + ok: true, + ...result, + }) + return + } - for (const tag of result.tags) { - process.stdout.write(`${tag.name}\t${tag.item_count}\n`) - } - }) + if (result.tags.length === 0) { + process.stdout.write("No tags found.\n") + return + } + + for (const tag of result.tags) { + process.stdout.write(`${tag.name}\t${tag.item_count}\n`) + } + }), + ) }) tagsCommand @@ -830,40 +847,36 @@ tagsCommand .option("--json", "Print machine-readable JSON output") .action((options: { json?: boolean }) => { const jsonMode = Boolean(options.json) - const context = { - dbPath: resolveDbPath(program.opts().dbPath as string), - migrationsDir: resolveMigrationsDir(), - } - const services = createCoreServices(context) + runDbAction(jsonMode, () => + withCoreRuntime((services) => { + const report = services.doctor.inspectAutoTagsHealth() - runDbAction(jsonMode, () => { - const report = services.doctor.inspectAutoTagsHealth() - - if (jsonMode) { - printJson({ - ok: true, - ...report, - }) - } else { - process.stdout.write(`tags doctor: ${report.healthy ? "healthy" : "unhealthy"}\n`) - process.stdout.write(`backend: ${report.backend}\n`) - process.stdout.write(`model: ${report.model}\n`) - process.stdout.write(`helper: ${report.helper_path}\n`) - process.stdout.write(`python: ${report.python_path ?? "-"}\n`) - for (const check of report.checks) { - const requirement = check.required ? "required" : "optional" - const status = check.ok ? "ok" : "failed" - process.stdout.write(`${check.id} (${requirement}): ${status} [${check.path ?? "-"}]\n`) - if (check.message) { - process.stdout.write(` ${check.message}\n`) + if (jsonMode) { + printJson({ + ok: true, + ...report, + }) + } else { + process.stdout.write(`tags doctor: ${report.healthy ? "healthy" : "unhealthy"}\n`) + process.stdout.write(`backend: ${report.backend}\n`) + process.stdout.write(`model: ${report.model}\n`) + process.stdout.write(`helper: ${report.helper_path}\n`) + process.stdout.write(`python: ${report.python_path ?? "-"}\n`) + for (const check of report.checks) { + const requirement = check.required ? "required" : "optional" + const status = check.ok ? "ok" : "failed" + process.stdout.write(`${check.id} (${requirement}): ${status} [${check.path ?? "-"}]\n`) + if (check.message) { + process.stdout.write(` ${check.message}\n`) + } } } - } - if (!report.healthy) { - process.exitCode = 2 - } - }) + if (!report.healthy) { + process.exitCode = 2 + } + }), + ) }) const tagCommand = program.command("tag").description("Manage item tags") @@ -883,26 +896,22 @@ tagCommand .option("--json", "Print machine-readable JSON output") .action((id: string, tag: string, options: { json?: boolean }) => { const jsonMode = Boolean(options.json) - const context = { - dbPath: resolveDbPath(program.opts().dbPath as string), - migrationsDir: resolveMigrationsDir(), - } - const services = createCoreServices(context) - - runDbAction(jsonMode, () => { - const result = services.tags.addTag(parseItemId(id), tag) - if (jsonMode) { - printJson({ - ok: true, - ...result, - }) - return - } + runDbAction(jsonMode, () => + withCoreRuntime((services) => { + const result = services.tags.addTag(parseItemId(id), tag) + if (jsonMode) { + printJson({ + ok: true, + ...result, + }) + return + } - process.stdout.write( - `${result.added ? "added" : "exists"} tag '${result.tag}' on #${result.item_id}\n`, - ) - }) + process.stdout.write( + `${result.added ? "added" : "exists"} tag '${result.tag}' on #${result.item_id}\n`, + ) + }), + ) }) tagCommand @@ -911,26 +920,22 @@ tagCommand .option("--json", "Print machine-readable JSON output") .action((id: string, tag: string, options: { json?: boolean }) => { const jsonMode = Boolean(options.json) - const context = { - dbPath: resolveDbPath(program.opts().dbPath as string), - migrationsDir: resolveMigrationsDir(), - } - const services = createCoreServices(context) - - runDbAction(jsonMode, () => { - const result = services.tags.removeTag(parseItemId(id), tag) - if (jsonMode) { - printJson({ - ok: true, - ...result, - }) - return - } + runDbAction(jsonMode, () => + withCoreRuntime((services) => { + const result = services.tags.removeTag(parseItemId(id), tag) + if (jsonMode) { + printJson({ + ok: true, + ...result, + }) + return + } - process.stdout.write( - `${result.removed ? "removed" : "missing"} tag '${result.tag}' on #${result.item_id}\n`, - ) - }) + process.stdout.write( + `${result.removed ? "removed" : "missing"} tag '${result.tag}' on #${result.item_id}\n`, + ) + }), + ) }) const markCommand = program.command("mark").description("Mark item states") @@ -950,24 +955,20 @@ markCommand .option("--json", "Print machine-readable JSON output") .action((id: string, options: { json?: boolean }) => { const jsonMode = Boolean(options.json) - const context = { - dbPath: resolveDbPath(program.opts().dbPath as string), - migrationsDir: resolveMigrationsDir(), - } - const services = createCoreServices(context) - - runDbAction(jsonMode, () => { - const itemId = parseItemId(id) - const result = services.status.markRead(itemId) - if (jsonMode) { - printJson({ - ok: true, - ...result, - }) - return - } - process.stdout.write(`marked #${result.item_id} as read\n`) - }) + runDbAction(jsonMode, () => + withCoreRuntime((services) => { + const itemId = parseItemId(id) + const result = services.status.markRead(itemId) + if (jsonMode) { + printJson({ + ok: true, + ...result, + }) + return + } + process.stdout.write(`marked #${result.item_id} as read\n`) + }), + ) }) markCommand @@ -976,24 +977,20 @@ markCommand .option("--json", "Print machine-readable JSON output") .action((id: string, options: { json?: boolean }) => { const jsonMode = Boolean(options.json) - const context = { - dbPath: resolveDbPath(program.opts().dbPath as string), - migrationsDir: resolveMigrationsDir(), - } - const services = createCoreServices(context) - - runDbAction(jsonMode, () => { - const itemId = parseItemId(id) - const result = services.status.markUnread(itemId) - if (jsonMode) { - printJson({ - ok: true, - ...result, - }) - return - } - process.stdout.write(`marked #${result.item_id} as unread\n`) - }) + runDbAction(jsonMode, () => + withCoreRuntime((services) => { + const itemId = parseItemId(id) + const result = services.status.markUnread(itemId) + if (jsonMode) { + printJson({ + ok: true, + ...result, + }) + return + } + process.stdout.write(`marked #${result.item_id} as unread\n`) + }), + ) }) const jobsCommand = program.command("jobs").description("Background job workers") @@ -1007,61 +1004,58 @@ jobsCommand .action(async (options: { pollMs: number; once?: boolean; json?: boolean }) => { const jsonMode = Boolean(options.json) - return runDbAction(jsonMode, async () => { - const context = { - dbPath: resolveDbPath(program.opts().dbPath as string), - migrationsDir: resolveMigrationsDir(), - } - const services = createCoreServices(context) - const audioDir = resolveAudioDir(process.env.STASH_AUDIO_DIR ?? DEFAULT_AUDIO_DIR) + return runDbAction(jsonMode, () => + withCoreRuntime(async (services) => { + const audioDir = resolveAudioDir(process.env.STASH_AUDIO_DIR ?? DEFAULT_AUDIO_DIR) - if (options.once) { - const processed = await services.ttsJobs.runTtsWorkerOnce({ audioDir }) - if (jsonMode) { - printJson({ - ok: true, - processed: Boolean(processed), - job: processed, - }) - return - } + if (options.once) { + const processed = await services.ttsJobs.runTtsWorkerOnce({ audioDir }) + if (jsonMode) { + printJson({ + ok: true, + processed: Boolean(processed), + job: processed, + }) + return + } + + if (!processed) { + process.stdout.write("No queued TTS jobs.\n") + return + } - if (!processed) { - process.stdout.write("No queued TTS jobs.\n") + process.stdout.write(`Processed tts job #${processed.id} (${processed.status}).\n`) return } - process.stdout.write(`Processed tts job #${processed.id} (${processed.status}).\n`) - return - } - - const worker = services.ttsJobs.startTtsWorker({ - pollMs: options.pollMs, - audioDir, - }) - - if (jsonMode) { - printJson({ - ok: true, - status: "running", - poll_ms: options.pollMs, + const worker = services.ttsJobs.startTtsWorker({ + pollMs: options.pollMs, + audioDir, }) - } else { - process.stdout.write(`tts worker running (poll ${options.pollMs}ms)\n`) - } - await new Promise((resolve) => { - const stop = (): void => { - void worker.stop().finally(() => { - process.off("SIGINT", stop) - process.off("SIGTERM", stop) - resolve() + if (jsonMode) { + printJson({ + ok: true, + status: "running", + poll_ms: options.pollMs, }) + } else { + process.stdout.write(`tts worker running (poll ${options.pollMs}ms)\n`) } - process.on("SIGINT", stop) - process.on("SIGTERM", stop) - }) - }) + + await new Promise((resolve) => { + const stop = (): void => { + void worker.stop().finally(() => { + process.off("SIGINT", stop) + process.off("SIGTERM", stop) + resolve() + }) + } + process.on("SIGINT", stop) + process.on("SIGTERM", stop) + }) + }), + ) }) program @@ -1119,23 +1113,20 @@ program .option("--json", "Print machine-readable JSON output") .action((id: string, options: { json?: boolean }) => { const jsonMode = Boolean(options.json) - const context = { - dbPath: resolveDbPath(program.opts().dbPath as string), - migrationsDir: resolveMigrationsDir(), - } - const services = createCoreServices(context) - runDbAction(jsonMode, () => { - const itemId = parseItemId(id) - const result = services.status.markRead(itemId) - if (jsonMode) { - printJson({ - ok: true, - ...result, - }) - return - } - process.stdout.write(`marked #${result.item_id} as read\n`) - }) + runDbAction(jsonMode, () => + withCoreRuntime((services) => { + const itemId = parseItemId(id) + const result = services.status.markRead(itemId) + if (jsonMode) { + printJson({ + ok: true, + ...result, + }) + return + } + process.stdout.write(`marked #${result.item_id} as read\n`) + }), + ) }) program @@ -1144,23 +1135,20 @@ program .option("--json", "Print machine-readable JSON output") .action((id: string, options: { json?: boolean }) => { const jsonMode = Boolean(options.json) - const context = { - dbPath: resolveDbPath(program.opts().dbPath as string), - migrationsDir: resolveMigrationsDir(), - } - const services = createCoreServices(context) - runDbAction(jsonMode, () => { - const itemId = parseItemId(id) - const result = services.status.markUnread(itemId) - if (jsonMode) { - printJson({ - ok: true, - ...result, - }) - return - } - process.stdout.write(`marked #${result.item_id} as unread\n`) - }) + runDbAction(jsonMode, () => + withCoreRuntime((services) => { + const itemId = parseItemId(id) + const result = services.status.markUnread(itemId) + if (jsonMode) { + printJson({ + ok: true, + ...result, + }) + return + } + process.stdout.write(`marked #${result.item_id} as unread\n`) + }), + ) }) program.configureOutput({ diff --git a/package.json b/package.json index bf3d516..7ac8083 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "scripts": { "setup": "pnpm run build && pnpm exec playwright install chromium && node scripts/with-env.mjs node apps/cli/dist/cli.js db migrate --json", "build": "pnpm --filter @stash/core build && pnpm --filter stash-api-app build && pnpm --filter stash-cli-app build", - "check": "pnpm run lint && pnpm run format:check && pnpm run build", + "check": "pnpm run format:check && pnpm run lint && pnpm run test && pnpm --dir apps/web build", "dev": "node scripts/with-env.mjs tsx apps/cli/src/cli.ts", "dev:api": "pnpm run dev -- web", "dev:web": "pnpm --dir apps/web dev", diff --git a/packages/core/src/db/migrate.ts b/packages/core/src/db/migrate.ts index f11656c..9e0fe60 100644 --- a/packages/core/src/db/migrate.ts +++ b/packages/core/src/db/migrate.ts @@ -3,7 +3,7 @@ import path from "node:path" import { migrate as drizzleMigrate } from "drizzle-orm/better-sqlite3/migrator" -import { openDb, openSqlite, type SqliteDatabase } from "./client.js" +import { openDb, openSqlite, type SqliteDatabase, type StashDb } from "./client.js" type MigrationStatus = { applied: string[] @@ -120,30 +120,45 @@ function getMigrationStatusFromJournal( } export function getMigrationStatus(dbPath: string, migrationsDir: string): MigrationStatus { - const entries = readJournalEntries(migrationsDir) const sqlite = openSqlite(dbPath) try { - ensureMigrationTableCompatibility(sqlite, migrationsDir) - const lastAppliedMillis = getLastAppliedMillis(sqlite) - return getMigrationStatusFromJournal(entries, lastAppliedMillis) + return getMigrationStatusForSqlite(sqlite, migrationsDir) } finally { sqlite.close() } } +function getMigrationStatusForSqlite( + sqlite: SqliteDatabase, + migrationsDir: string, +): MigrationStatus { + const entries = readJournalEntries(migrationsDir) + ensureMigrationTableCompatibility(sqlite, migrationsDir) + const lastAppliedMillis = getLastAppliedMillis(sqlite) + return getMigrationStatusFromJournal(entries, lastAppliedMillis) +} + +export function runMigrationsWithDatabase( + db: StashDb, + sqlite: SqliteDatabase, + migrationsDir: string, +): { appliedCount: number; applied: string[] } { + const status = getMigrationStatusForSqlite(sqlite, migrationsDir) + drizzleMigrate(db, { + migrationsFolder: migrationsDir, + migrationsTable: MIGRATIONS_TABLE, + }) + + return { appliedCount: status.pending.length, applied: status.pending } +} + export function runMigrations( dbPath: string, migrationsDir: string, ): { appliedCount: number; applied: string[] } { - const status = getMigrationStatus(dbPath, migrationsDir) const { db, sqlite } = openDb(dbPath) try { - drizzleMigrate(db, { - migrationsFolder: migrationsDir, - migrationsTable: MIGRATIONS_TABLE, - }) - - return { appliedCount: status.pending.length, applied: status.pending } + return runMigrationsWithDatabase(db, sqlite, migrationsDir) } finally { sqlite.close() } diff --git a/packages/core/src/features/common/db.ts b/packages/core/src/features/common/db.ts index c97be79..c337c93 100644 --- a/packages/core/src/features/common/db.ts +++ b/packages/core/src/features/common/db.ts @@ -3,8 +3,7 @@ import path from "node:path" import { and, asc, eq, inArray, type SQL } from "drizzle-orm" -import { openDb, type StashDb } from "../../db/client.js" -import { runMigrations } from "../../db/migrate.js" +import type { StashDb } from "../../db/client.js" import * as schema from "../../db/schema.js" import { StashError } from "../../errors.js" import type { ItemStatus, ItemTtsAudio, StashItem } from "../../types.js" @@ -22,45 +21,6 @@ export function ensureDbDirectory(dbPath: string): void { fs.mkdirSync(path.dirname(dbPath), { recursive: true }) } -export function ensureDbReady(dbPath: string, migrationsDir: string): void { - ensureDbDirectory(dbPath) - runMigrations(dbPath, migrationsDir) -} - -export function withDb(dbPath: string, action: (db: Db) => T): T { - ensureDbDirectory(dbPath) - const { db, sqlite } = openDb(dbPath) - try { - return action(db) - } finally { - sqlite.close() - } -} - -export async function withDbAsync(dbPath: string, action: (db: Db) => Promise): Promise { - ensureDbDirectory(dbPath) - const { db, sqlite } = openDb(dbPath) - try { - return await action(db) - } finally { - sqlite.close() - } -} - -export function withReadyDb(dbPath: string, migrationsDir: string, action: (db: Db) => T): T { - ensureDbReady(dbPath, migrationsDir) - return withDb(dbPath, action) -} - -export async function withReadyDbAsync( - dbPath: string, - migrationsDir: string, - action: (db: Db) => Promise, -): Promise { - ensureDbReady(dbPath, migrationsDir) - return withDbAsync(dbPath, action) -} - export function toIso(value: Date | number | null): string | null { if (value === null) { return null diff --git a/packages/core/src/features/extract/service.ts b/packages/core/src/features/extract/service.ts index 9a18309..470aa24 100644 --- a/packages/core/src/features/extract/service.ts +++ b/packages/core/src/features/extract/service.ts @@ -4,109 +4,107 @@ import * as schema from "../../db/schema.js" import { StashError } from "../../errors.js" import { extractContent } from "../../lib/extract.js" import { isContentExtractionError } from "../../lib/extract-x-browser.js" -import type { ExtractItemOptions, ExtractItemResult, OperationContext } from "../../types.js" +import type { ExtractItemOptions, ExtractItemResult } from "../../types.js" import { resolveAutoTagsRequested } from "../auto-tags/config.js" import { applyAutoTags } from "../auto-tags/service.js" -import { getItemRowById, withReadyDbAsync } from "../common/db.js" +import { type Db, getItemRowById } from "../common/db.js" export async function extractItem( - context: OperationContext, + db: Db, itemId: number, options: ExtractItemOptions = {}, ): Promise { - return withReadyDbAsync(context.dbPath, context.migrationsDir, async (db) => { - const item = getItemRowById(db, itemId) - if (!item) { - throw new StashError(`Item ${itemId} not found.`, "NOT_FOUND", 3, 404) - } + const item = getItemRowById(db, itemId) + if (!item) { + throw new StashError(`Item ${itemId} not found.`, "NOT_FOUND", 3, 404) + } - const existing = db.select().from(schema.notes).where(eq(schema.notes.itemId, itemId)).get() - if (existing && !options.force) { - throw new StashError( - `Item ${itemId} already has extracted content. Use --force to re-extract.`, - "CONTENT_EXISTS", - 4, - 409, - ) - } + const existing = db.select().from(schema.notes).where(eq(schema.notes.itemId, itemId)).get() + if (existing && !options.force) { + throw new StashError( + `Item ${itemId} already has extracted content. Use --force to re-extract.`, + "CONTENT_EXISTS", + 4, + 409, + ) + } - let extracted = null - try { - extracted = await extractContent(item.url) - } catch (error) { - if (isContentExtractionError(error)) { - throw new StashError(error.message, "EXTRACTION_FAILED", 1, 500) - } - throw error + let extracted = null + try { + extracted = await extractContent(item.url) + } catch (error) { + if (isContentExtractionError(error)) { + throw new StashError(error.message, "EXTRACTION_FAILED", 1, 500) } + throw error + } - if (!extracted?.textContent) { - throw new StashError("Failed to extract content", "EXTRACTION_FAILED", 1, 500) - } + if (!extracted?.textContent) { + throw new StashError("Failed to extract content", "EXTRACTION_FAILED", 1, 500) + } - const timestamp = new Date() + const timestamp = new Date() - db.insert(schema.notes) - .values({ - itemId, + db.insert(schema.notes) + .values({ + itemId, + content: extracted.textContent, + updatedAt: timestamp, + }) + .onConflictDoUpdate({ + target: schema.notes.itemId, + set: { content: extracted.textContent, updatedAt: timestamp, + }, + }) + .run() + + const titleUpdated = Boolean(extracted.title && !item.title) + if (titleUpdated && extracted.title) { + db.update(schema.items) + .set({ + title: extracted.title, + thumbnailUrl: extracted.thumbnailUrl ?? null, + updatedAt: timestamp, }) - .onConflictDoUpdate({ - target: schema.notes.itemId, - set: { - content: extracted.textContent, - updatedAt: timestamp, - }, + .where(eq(schema.items.id, itemId)) + .run() + } else { + db.update(schema.items) + .set({ + thumbnailUrl: extracted.thumbnailUrl ?? null, + updatedAt: timestamp, }) + .where(eq(schema.items.id, itemId)) .run() + } - const titleUpdated = Boolean(extracted.title && !item.title) - if (titleUpdated && extracted.title) { - db.update(schema.items) - .set({ - title: extracted.title, - thumbnailUrl: extracted.thumbnailUrl ?? null, - updatedAt: timestamp, - }) - .where(eq(schema.items.id, itemId)) - .run() - } else { - db.update(schema.items) - .set({ - thumbnailUrl: extracted.thumbnailUrl ?? null, - updatedAt: timestamp, - }) - .where(eq(schema.items.id, itemId)) - .run() - } - - const runAutoTags = resolveAutoTagsRequested(options.autoTags) - const autoTagResult = runAutoTags - ? await applyAutoTags(db, { - itemId, - url: item.url, - title: extracted.title ?? item.title ?? null, - domain: item.domain, - content: extracted.textContent, - }) - : null + const runAutoTags = resolveAutoTagsRequested(options.autoTags) + const autoTagResult = runAutoTags + ? await applyAutoTags(db, { + itemId, + url: item.url, + title: extracted.title ?? item.title ?? null, + domain: item.domain, + content: extracted.textContent, + }) + : null - const result: ExtractItemResult = { - item_id: itemId, - title_extracted: extracted.title || null, - title_updated: titleUpdated, - content_length: extracted.textContent.length, - updated_at: timestamp.toISOString(), - } - if (autoTagResult) { - result.auto_tags = autoTagResult.applied - result.auto_tag_scores = autoTagResult.scores - if (autoTagResult.warning) { - result.auto_tag_warning = autoTagResult.warning - } + const result: ExtractItemResult = { + item_id: itemId, + title_extracted: extracted.title || null, + title_updated: titleUpdated, + content_length: extracted.textContent.length, + updated_at: timestamp.toISOString(), + } + if (autoTagResult) { + result.auto_tags = autoTagResult.applied + result.auto_tag_scores = autoTagResult.scores + if (autoTagResult.warning) { + result.auto_tag_warning = autoTagResult.warning } + } - return result - }) + return result } diff --git a/packages/core/src/features/items/service.ts b/packages/core/src/features/items/service.ts index 67ff8a7..1cc0b7c 100644 --- a/packages/core/src/features/items/service.ts +++ b/packages/core/src/features/items/service.ts @@ -2,16 +2,11 @@ import { and, desc, eq, exists, inArray, sql, type SQL } from "drizzle-orm" import * as schema from "../../db/schema.js" import { extractContent } from "../../lib/extract.js" -import type { - ListItemsInput, - ListItemsResult, - OperationContext, - SaveItemInput, - SaveItemResult, -} from "../../types.js" +import type { ListItemsInput, ListItemsResult, SaveItemInput, SaveItemResult } from "../../types.js" import { resolveAutoTagsRequested } from "../auto-tags/config.js" import { applyAutoTags } from "../auto-tags/service.js" import { + type Db, ensureTagId, getExtractedContentForItem, getExtractedContentMap, @@ -25,288 +20,274 @@ import { nowMs, serializeItem, whereAnd, - withReadyDb, - withReadyDbAsync, } from "../common/db.js" import { parseListItemsStatusFilter, parseTagMode, parseUrl } from "../common/validation.js" -export async function saveItem( - context: OperationContext, - input: SaveItemInput, -): Promise { +export async function saveItem(db: Db, input: SaveItemInput): Promise { const parsedUrl = parseUrl(input.url) const normalizedTags = normalizeTags(input.tags ?? []) const runAutoTags = resolveAutoTagsRequested(input.autoTags) - return withReadyDbAsync(context.dbPath, context.migrationsDir, async (db) => { - const existing = db - .select() - .from(schema.items) - .where(eq(schema.items.url, parsedUrl.toString())) - .get() - const timestamp = new Date(nowMs()) - let created = false - let itemId: number | undefined + const existing = db + .select() + .from(schema.items) + .where(eq(schema.items.url, parsedUrl.toString())) + .get() + const timestamp = new Date(nowMs()) + let created = false + let itemId: number | undefined - db.transaction((tx) => { - if (existing) { - itemId = existing.id - if (!existing.title && input.title) { - tx.update(schema.items) - .set({ - title: input.title.trim(), - updatedAt: timestamp, - }) - .where(eq(schema.items.id, existing.id)) - .run() - } - } else { - const result = tx - .insert(schema.items) - .values({ - url: parsedUrl.toString(), - title: input.title?.trim() || null, - domain: parsedUrl.hostname, - status: "unread", - isStarred: false, - createdAt: timestamp, + db.transaction((tx) => { + if (existing) { + itemId = existing.id + if (!existing.title && input.title) { + tx.update(schema.items) + .set({ + title: input.title.trim(), updatedAt: timestamp, - readAt: null, - archivedAt: null, }) + .where(eq(schema.items.id, existing.id)) .run() - - itemId = Number(result.lastInsertRowid) - created = true } + } else { + const result = tx + .insert(schema.items) + .values({ + url: parsedUrl.toString(), + title: input.title?.trim() || null, + domain: parsedUrl.hostname, + status: "unread", + isStarred: false, + createdAt: timestamp, + updatedAt: timestamp, + readAt: null, + archivedAt: null, + }) + .run() - if (itemId === undefined) { - throw new Error("Saved item id could not be determined.") - } + itemId = Number(result.lastInsertRowid) + created = true + } + + if (itemId === undefined) { + throw new Error("Saved item id could not be determined.") + } + + for (const tag of normalizedTags) { + const tagId = ensureTagId(tx, tag, timestamp) + tx.insert(schema.itemTags) + .values({ + itemId, + tagId, + createdAt: timestamp, + isManual: true, + isAuto: false, + autoScore: null, + autoSource: null, + autoModel: null, + autoUpdatedAt: null, + }) + .onConflictDoUpdate({ + target: [schema.itemTags.itemId, schema.itemTags.tagId], + set: { + isManual: true, + }, + }) + .run() + } + }) + + if (itemId === undefined) { + throw new Error("Saved item id could not be determined.") + } - for (const tag of normalizedTags) { - const tagId = ensureTagId(tx, tag, timestamp) - tx.insert(schema.itemTags) + const existingNote = db + .select({ + content: schema.notes.content, + }) + .from(schema.notes) + .where(eq(schema.notes.itemId, itemId)) + .get() + const hasNoteContent = (existingNote?.content ?? "").trim().length > 0 + const shouldExtract = input.extract !== false && (created || (runAutoTags && !hasNoteContent)) + + if (shouldExtract) { + try { + const extracted = await extractContent(parsedUrl.toString()) + if (extracted?.textContent) { + db.insert(schema.notes) .values({ itemId, - tagId, - createdAt: timestamp, - isManual: true, - isAuto: false, - autoScore: null, - autoSource: null, - autoModel: null, - autoUpdatedAt: null, + content: extracted.textContent, + updatedAt: timestamp, }) .onConflictDoUpdate({ - target: [schema.itemTags.itemId, schema.itemTags.tagId], + target: schema.notes.itemId, set: { - isManual: true, + content: extracted.textContent, + updatedAt: timestamp, }, }) .run() - } - }) - - if (itemId === undefined) { - throw new Error("Saved item id could not be determined.") - } - const existingNote = db - .select({ - content: schema.notes.content, - }) - .from(schema.notes) - .where(eq(schema.notes.itemId, itemId)) - .get() - const hasNoteContent = (existingNote?.content ?? "").trim().length > 0 - const shouldExtract = input.extract !== false && (created || (runAutoTags && !hasNoteContent)) - - if (shouldExtract) { - try { - const extracted = await extractContent(parsedUrl.toString()) - if (extracted?.textContent) { - db.insert(schema.notes) - .values({ - itemId, - content: extracted.textContent, + if (extracted.title && !input.title) { + db.update(schema.items) + .set({ + title: extracted.title, + thumbnailUrl: extracted.thumbnailUrl ?? null, updatedAt: timestamp, }) - .onConflictDoUpdate({ - target: schema.notes.itemId, - set: { - content: extracted.textContent, - updatedAt: timestamp, - }, + .where(eq(schema.items.id, itemId)) + .run() + } else { + db.update(schema.items) + .set({ + thumbnailUrl: extracted.thumbnailUrl ?? null, + updatedAt: timestamp, }) + .where(eq(schema.items.id, itemId)) .run() - - if (extracted.title && !input.title) { - db.update(schema.items) - .set({ - title: extracted.title, - thumbnailUrl: extracted.thumbnailUrl ?? null, - updatedAt: timestamp, - }) - .where(eq(schema.items.id, itemId)) - .run() - } else { - db.update(schema.items) - .set({ - thumbnailUrl: extracted.thumbnailUrl ?? null, - updatedAt: timestamp, - }) - .where(eq(schema.items.id, itemId)) - .run() - } } - } catch { - // Keep save action successful even when extraction fails. } + } catch { + // Keep save action successful even when extraction fails. } + } - let autoTagResult: Awaited> | null = null - if (runAutoTags) { - const refreshed = getItemRowById(db, itemId) - if (refreshed) { - const note = db - .select({ - content: schema.notes.content, - }) - .from(schema.notes) - .where(eq(schema.notes.itemId, itemId)) - .get() - - autoTagResult = await applyAutoTags(db, { - itemId, - url: refreshed.url, - title: refreshed.title, - domain: refreshed.domain, - content: note?.content ?? null, + let autoTagResult: Awaited> | null = null + if (runAutoTags) { + const refreshed = getItemRowById(db, itemId) + if (refreshed) { + const note = db + .select({ + content: schema.notes.content, }) - } - } + .from(schema.notes) + .where(eq(schema.notes.itemId, itemId)) + .get() - const row = getItemRowById(db, itemId) - if (!row) { - throw new Error("Saved item could not be reloaded.") + autoTagResult = await applyAutoTags(db, { + itemId, + url: refreshed.url, + title: refreshed.title, + domain: refreshed.domain, + content: note?.content ?? null, + }) } + } - const result: SaveItemResult = { - created, - item: serializeItem( - row, - getItemTags(db, row.id), - getExtractedContentForItem(db, row.id), - getItemAudioForItem(db, row.id), - ), - } - if (autoTagResult) { - result.auto_tags = autoTagResult.applied - result.auto_tag_scores = autoTagResult.scores - if (autoTagResult.warning) { - result.auto_tag_warning = autoTagResult.warning - } + const row = getItemRowById(db, itemId) + if (!row) { + throw new Error("Saved item could not be reloaded.") + } + + const result: SaveItemResult = { + created, + item: serializeItem( + row, + getItemTags(db, row.id), + getExtractedContentForItem(db, row.id), + getItemAudioForItem(db, row.id), + ), + } + if (autoTagResult) { + result.auto_tags = autoTagResult.applied + result.auto_tag_scores = autoTagResult.scores + if (autoTagResult.warning) { + result.auto_tag_warning = autoTagResult.warning } + } - return result - }) + return result } -export function listItems(context: OperationContext, input: ListItemsInput): ListItemsResult { +export function listItems(db: Db, input: ListItemsInput): ListItemsResult { const limit = input.limit ?? 20 const offset = input.offset ?? 0 const tagMode = parseTagMode(input.tagMode ?? "any") const tags = normalizeTags(input.tags ?? []) const status = input.status ? parseListItemsStatusFilter(input.status) : undefined - return withReadyDb(context.dbPath, context.migrationsDir, (db) => { - const conditions: SQL[] = [] + const conditions: SQL[] = [] - if (status) { - if (status === "active") { - conditions.push(inArray(schema.items.status, ["unread", "read"])) - } else { - conditions.push(eq(schema.items.status, status)) - } + if (status) { + if (status === "active") { + conditions.push(inArray(schema.items.status, ["unread", "read"])) + } else { + conditions.push(eq(schema.items.status, status)) } + } - if (tags.length > 0) { - if (tagMode === "any") { + if (tags.length > 0) { + if (tagMode === "any") { + const subquery = db + .select({ one: sql`1` }) + .from(schema.itemTags) + .innerJoin(schema.tags, eq(schema.tags.id, schema.itemTags.tagId)) + .where(and(eq(schema.itemTags.itemId, schema.items.id), inArray(schema.tags.name, tags))) + conditions.push(exists(subquery)) + } else { + for (const tag of tags) { const subquery = db .select({ one: sql`1` }) .from(schema.itemTags) .innerJoin(schema.tags, eq(schema.tags.id, schema.itemTags.tagId)) - .where(and(eq(schema.itemTags.itemId, schema.items.id), inArray(schema.tags.name, tags))) + .where(and(eq(schema.itemTags.itemId, schema.items.id), eq(schema.tags.name, tag))) conditions.push(exists(subquery)) - } else { - for (const tag of tags) { - const subquery = db - .select({ one: sql`1` }) - .from(schema.itemTags) - .innerJoin(schema.tags, eq(schema.tags.id, schema.itemTags.tagId)) - .where(and(eq(schema.itemTags.itemId, schema.items.id), eq(schema.tags.name, tag))) - conditions.push(exists(subquery)) - } } } + } - const rows = db - .select() - .from(schema.items) - .where(whereAnd(conditions)) - .orderBy(desc(schema.items.createdAt), desc(schema.items.id)) - .limit(limit) - .offset(offset) - .all() as ItemRow[] + const rows = db + .select() + .from(schema.items) + .where(whereAnd(conditions)) + .orderBy(desc(schema.items.createdAt), desc(schema.items.id)) + .limit(limit) + .offset(offset) + .all() as ItemRow[] - const tagsMap = getTagsMap( - db, - rows.map((row) => row.id), - ) - const extractedContentMap = getExtractedContentMap( - db, - rows.map((row) => row.id), - ) - const itemAudioMap = getItemAudioMap( - db, - rows.map((row) => row.id), - ) + const tagsMap = getTagsMap( + db, + rows.map((row) => row.id), + ) + const extractedContentMap = getExtractedContentMap( + db, + rows.map((row) => row.id), + ) + const itemAudioMap = getItemAudioMap( + db, + rows.map((row) => row.id), + ) - const items = rows.map((row) => - serializeItem( - row, - tagsMap.get(row.id) ?? [], - extractedContentMap.get(row.id) ?? false, - itemAudioMap.get(row.id) ?? null, - ), - ) + const items = rows.map((row) => + serializeItem( + row, + tagsMap.get(row.id) ?? [], + extractedContentMap.get(row.id) ?? false, + itemAudioMap.get(row.id) ?? null, + ), + ) - return { - items, - paging: { - limit, - offset, - returned: items.length, - }, - } - }) + return { + items, + paging: { + limit, + offset, + returned: items.length, + }, + } } -export function getItem( - context: OperationContext, - itemId: number, -): SaveItemResult["item"] | undefined { - return withReadyDb(context.dbPath, context.migrationsDir, (db) => { - const row = getItemRowById(db, itemId) - if (!row) { - return undefined - } - return serializeItem( - row, - getItemTags(db, row.id), - getExtractedContentForItem(db, row.id), - getItemAudioForItem(db, row.id), - ) - }) +export function getItem(db: Db, itemId: number): SaveItemResult["item"] | undefined { + const row = getItemRowById(db, itemId) + if (!row) { + return undefined + } + return serializeItem( + row, + getItemTags(db, row.id), + getExtractedContentForItem(db, row.id), + getItemAudioForItem(db, row.id), + ) } diff --git a/packages/core/src/features/status/service.ts b/packages/core/src/features/status/service.ts index 0a33acd..bb3a788 100644 --- a/packages/core/src/features/status/service.ts +++ b/packages/core/src/features/status/service.ts @@ -2,61 +2,58 @@ import { eq } from "drizzle-orm" import * as schema from "../../db/schema.js" import { StashError } from "../../errors.js" -import type { OperationContext } from "../../types.js" -import { nowMs, withReadyDb } from "../common/db.js" +import { type Db, nowMs } from "../common/db.js" function markItemStatus( - context: OperationContext, + db: Db, itemId: number, status: "read" | "unread", ): { item_id: number; action: "mark_read" | "mark_unread"; status: "read" | "unread" } { - return withReadyDb(context.dbPath, context.migrationsDir, (db) => { - const timestamp = new Date(nowMs()) + const timestamp = new Date(nowMs()) - const result = - status === "read" - ? db - .update(schema.items) - .set({ - status: "read", - readAt: timestamp, - archivedAt: null, - updatedAt: timestamp, - }) - .where(eq(schema.items.id, itemId)) - .run() - : db - .update(schema.items) - .set({ - status: "unread", - readAt: null, - archivedAt: null, - updatedAt: timestamp, - }) - .where(eq(schema.items.id, itemId)) - .run() + const result = + status === "read" + ? db + .update(schema.items) + .set({ + status: "read", + readAt: timestamp, + archivedAt: null, + updatedAt: timestamp, + }) + .where(eq(schema.items.id, itemId)) + .run() + : db + .update(schema.items) + .set({ + status: "unread", + readAt: null, + archivedAt: null, + updatedAt: timestamp, + }) + .where(eq(schema.items.id, itemId)) + .run() - if (Number(result.changes) === 0) { - throw new StashError(`Item ${itemId} not found.`, "NOT_FOUND", 3, 404) - } + if (Number(result.changes) === 0) { + throw new StashError(`Item ${itemId} not found.`, "NOT_FOUND", 3, 404) + } - return { - item_id: itemId, - action: status === "read" ? "mark_read" : "mark_unread", - status, - } - }) + return { + item_id: itemId, + action: status === "read" ? "mark_read" : "mark_unread", + status, + } } export function markRead( - context: OperationContext, + db: Db, itemId: number, ): { item_id: number action: "mark_read" status: "read" } { - return markItemStatus(context, itemId, "read") as { + return markItemStatus(db, itemId, "read") as { item_id: number action: "mark_read" status: "read" @@ -64,14 +61,14 @@ export function markRead( } export function markUnread( - context: OperationContext, + db: Db, itemId: number, ): { item_id: number action: "mark_unread" status: "unread" } { - return markItemStatus(context, itemId, "unread") as { + return markItemStatus(db, itemId, "unread") as { item_id: number action: "mark_unread" status: "unread" diff --git a/packages/core/src/features/tags/service.ts b/packages/core/src/features/tags/service.ts index 7b110e8..71cceee 100644 --- a/packages/core/src/features/tags/service.ts +++ b/packages/core/src/features/tags/service.ts @@ -1,42 +1,40 @@ import { and, asc, eq, sql } from "drizzle-orm" import * as schema from "../../db/schema.js" -import type { OperationContext, TagsListInput, TagsListResult } from "../../types.js" -import { ensureItemExists, ensureTagId, normalizeTag, nowMs, withReadyDb } from "../common/db.js" +import type { TagsListInput, TagsListResult } from "../../types.js" +import { type Db, ensureItemExists, ensureTagId, normalizeTag, nowMs } from "../common/db.js" -export function listTags(context: OperationContext, input: TagsListInput): TagsListResult { +export function listTags(db: Db, input: TagsListInput): TagsListResult { const limit = input.limit ?? 50 const offset = input.offset ?? 0 - return withReadyDb(context.dbPath, context.migrationsDir, (db) => { - const rows = db - .select({ - name: schema.tags.name, - itemCount: sql`count(${schema.itemTags.itemId})`, - }) - .from(schema.tags) - .leftJoin(schema.itemTags, eq(schema.itemTags.tagId, schema.tags.id)) - .groupBy(schema.tags.id) - .orderBy(asc(schema.tags.name)) - .limit(limit) - .offset(offset) - .all() + const rows = db + .select({ + name: schema.tags.name, + itemCount: sql`count(${schema.itemTags.itemId})`, + }) + .from(schema.tags) + .leftJoin(schema.itemTags, eq(schema.itemTags.tagId, schema.tags.id)) + .groupBy(schema.tags.id) + .orderBy(asc(schema.tags.name)) + .limit(limit) + .offset(offset) + .all() - const tags = rows.map((row) => ({ name: row.name, item_count: Number(row.itemCount) })) + const tags = rows.map((row) => ({ name: row.name, item_count: Number(row.itemCount) })) - return { - tags, - paging: { - limit, - offset, - returned: tags.length, - }, - } - }) + return { + tags, + paging: { + limit, + offset, + returned: tags.length, + }, + } } export function addTag( - context: OperationContext, + db: Db, itemId: number, tag: string, ): { @@ -46,51 +44,49 @@ export function addTag( } { const normalizedTag = normalizeTag(tag) - return withReadyDb(context.dbPath, context.migrationsDir, (db) => { - ensureItemExists(db, itemId) - const timestamp = new Date(nowMs()) - const existing = db - .select({ - isManual: schema.itemTags.isManual, - }) - .from(schema.itemTags) - .innerJoin(schema.tags, eq(schema.tags.id, schema.itemTags.tagId)) - .where(and(eq(schema.itemTags.itemId, itemId), eq(schema.tags.name, normalizedTag))) - .get() - - db.transaction((tx) => { - const tagId = ensureTagId(tx, normalizedTag, timestamp) - tx.insert(schema.itemTags) - .values({ - itemId, - tagId, - createdAt: timestamp, - isManual: true, - isAuto: false, - autoScore: null, - autoSource: null, - autoModel: null, - autoUpdatedAt: null, - }) - .onConflictDoUpdate({ - target: [schema.itemTags.itemId, schema.itemTags.tagId], - set: { - isManual: true, - }, - }) - .run() + ensureItemExists(db, itemId) + const timestamp = new Date(nowMs()) + const existing = db + .select({ + isManual: schema.itemTags.isManual, }) + .from(schema.itemTags) + .innerJoin(schema.tags, eq(schema.tags.id, schema.itemTags.tagId)) + .where(and(eq(schema.itemTags.itemId, itemId), eq(schema.tags.name, normalizedTag))) + .get() - return { - item_id: itemId, - tag: normalizedTag, - added: !existing || !existing.isManual, - } + db.transaction((tx) => { + const tagId = ensureTagId(tx, normalizedTag, timestamp) + tx.insert(schema.itemTags) + .values({ + itemId, + tagId, + createdAt: timestamp, + isManual: true, + isAuto: false, + autoScore: null, + autoSource: null, + autoModel: null, + autoUpdatedAt: null, + }) + .onConflictDoUpdate({ + target: [schema.itemTags.itemId, schema.itemTags.tagId], + set: { + isManual: true, + }, + }) + .run() }) + + return { + item_id: itemId, + tag: normalizedTag, + added: !existing || !existing.isManual, + } } export function removeTag( - context: OperationContext, + db: Db, itemId: number, tag: string, ): { @@ -100,28 +96,26 @@ export function removeTag( } { const normalizedTag = normalizeTag(tag) - return withReadyDb(context.dbPath, context.migrationsDir, (db) => { - ensureItemExists(db, itemId) + ensureItemExists(db, itemId) - const row = db - .select({ id: schema.tags.id }) - .from(schema.tags) - .where(eq(schema.tags.name, normalizedTag)) - .get() + const row = db + .select({ id: schema.tags.id }) + .from(schema.tags) + .where(eq(schema.tags.name, normalizedTag)) + .get() - let removed = false - if (row) { - const result = db - .delete(schema.itemTags) - .where(and(eq(schema.itemTags.itemId, itemId), eq(schema.itemTags.tagId, row.id))) - .run() - removed = Number(result.changes) > 0 - } + let removed = false + if (row) { + const result = db + .delete(schema.itemTags) + .where(and(eq(schema.itemTags.itemId, itemId), eq(schema.itemTags.tagId, row.id))) + .run() + removed = Number(result.changes) > 0 + } - return { - item_id: itemId, - tag: normalizedTag, - removed, - } - }) + return { + item_id: itemId, + tag: normalizedTag, + removed, + } } diff --git a/packages/core/src/features/tts/jobs.ts b/packages/core/src/features/tts/jobs.ts index 71bd952..3e28fb5 100644 --- a/packages/core/src/features/tts/jobs.ts +++ b/packages/core/src/features/tts/jobs.ts @@ -2,8 +2,8 @@ import { and, asc, desc, eq, inArray, lt } from "drizzle-orm" import * as schema from "../../db/schema.js" import { asStashError, StashError } from "../../errors.js" -import type { OperationContext, TtsJob } from "../../types.js" -import { nowMs, toIso, withReadyDb } from "../common/db.js" +import type { TtsJob } from "../../types.js" +import { type Db, nowMs, toIso } from "../common/db.js" import { parseTtsFormat } from "../common/validation.js" import { executeTtsForItem } from "./service.js" @@ -54,71 +54,56 @@ function serializeTtsJob(row: TtsJobRow): TtsJob { } } -function getActiveJobForItem( - dbPath: string, - migrationsDir: string, - itemId: number, -): TtsJobRow | undefined { - return withReadyDb(dbPath, migrationsDir, (db) => - db - .select() - .from(schema.ttsJobs) - .where( - and( - eq(schema.ttsJobs.itemId, itemId), - inArray(schema.ttsJobs.status, [...ACTIVE_JOB_STATUSES]), - ), - ) - .orderBy(asc(schema.ttsJobs.createdAt), asc(schema.ttsJobs.id)) - .get(), - ) +function getActiveJobForItem(db: Db, itemId: number): TtsJobRow | undefined { + return db + .select() + .from(schema.ttsJobs) + .where( + and( + eq(schema.ttsJobs.itemId, itemId), + inArray(schema.ttsJobs.status, [...ACTIVE_JOB_STATUSES]), + ), + ) + .orderBy(asc(schema.ttsJobs.createdAt), asc(schema.ttsJobs.id)) + .get() } -function ensureItemHasExtractedContent( - dbPath: string, - migrationsDir: string, - itemId: number, -): void { - withReadyDb(dbPath, migrationsDir, (db) => { - const row = db - .select({ - id: schema.items.id, - content: schema.notes.content, - }) - .from(schema.items) - .leftJoin(schema.notes, eq(schema.notes.itemId, schema.items.id)) - .where(eq(schema.items.id, itemId)) - .get() +function ensureItemHasExtractedContent(db: Db, itemId: number): void { + const row = db + .select({ + id: schema.items.id, + content: schema.notes.content, + }) + .from(schema.items) + .leftJoin(schema.notes, eq(schema.notes.itemId, schema.items.id)) + .where(eq(schema.items.id, itemId)) + .get() - if (!row) { - throw new StashError(`Item ${itemId} not found.`, "NOT_FOUND", 3, 404) - } + if (!row) { + throw new StashError(`Item ${itemId} not found.`, "NOT_FOUND", 3, 404) + } - const content = row.content?.trim() ?? "" - if (content.length === 0) { - throw new StashError( - `No extracted content found for item ${itemId}. Save without --no-extract or re-save the URL.`, - "NO_CONTENT", - 2, - 400, - ) - } - }) + const content = row.content?.trim() ?? "" + if (content.length === 0) { + throw new StashError( + `No extracted content found for item ${itemId}. Save without --no-extract or re-save the URL.`, + "NO_CONTENT", + 2, + 400, + ) + } } -export function enqueueTtsJob( - context: OperationContext, - input: EnqueueTtsJobInput, -): EnqueueTtsJobResult { +export function enqueueTtsJob(db: Db, input: EnqueueTtsJobInput): EnqueueTtsJobResult { const voice = input.voice?.trim() || DEFAULT_TTS_VOICE if (voice.length === 0) { throw new StashError("Voice cannot be empty.", "VALIDATION_ERROR", 2, 400) } const format = parseTtsFormat(input.format ?? "mp3") - ensureItemHasExtractedContent(context.dbPath, context.migrationsDir, input.itemId) + ensureItemHasExtractedContent(db, input.itemId) - const existing = getActiveJobForItem(context.dbPath, context.migrationsDir, input.itemId) + const existing = getActiveJobForItem(db, input.itemId) if (existing) { return { job: serializeTtsJob(existing), @@ -130,27 +115,25 @@ export function enqueueTtsJob( const createdAt = new Date(nowMs()) try { - const inserted = withReadyDb(context.dbPath, context.migrationsDir, (db) => - db - .insert(schema.ttsJobs) - .values({ - itemId: input.itemId, - status: "queued", - voice, - format, - errorCode: null, - errorMessage: null, - outputFileName: null, - createdAt, - updatedAt: createdAt, - startedAt: null, - finishedAt: null, - }) - .run(), - ) + const inserted = db + .insert(schema.ttsJobs) + .values({ + itemId: input.itemId, + status: "queued", + voice, + format, + errorCode: null, + errorMessage: null, + outputFileName: null, + createdAt, + updatedAt: createdAt, + startedAt: null, + finishedAt: null, + }) + .run() const jobId = Number(inserted.lastInsertRowid) - const job = getTtsJob(context, jobId) + const job = getTtsJob(db, jobId) return { job, @@ -163,7 +146,7 @@ export function enqueueTtsJob( throw error } - const deduped = getActiveJobForItem(context.dbPath, context.migrationsDir, input.itemId) + const deduped = getActiveJobForItem(db, input.itemId) if (!deduped) { throw error } @@ -176,162 +159,136 @@ export function enqueueTtsJob( } } -export function getTtsJob(context: OperationContext, jobId: number): TtsJob { - return withReadyDb(context.dbPath, context.migrationsDir, (db) => { - const row = db.select().from(schema.ttsJobs).where(eq(schema.ttsJobs.id, jobId)).get() - if (!row) { - throw new StashError(`TTS job ${jobId} not found.`, "NOT_FOUND", 3, 404) - } - return serializeTtsJob(row) - }) +export function getTtsJob(db: Db, jobId: number): TtsJob { + const row = db.select().from(schema.ttsJobs).where(eq(schema.ttsJobs.id, jobId)).get() + if (!row) { + throw new StashError(`TTS job ${jobId} not found.`, "NOT_FOUND", 3, 404) + } + return serializeTtsJob(row) } -export function listTtsJobsForItem( - context: OperationContext, - itemId: number, - limit = 10, - offset = 0, -): TtsJob[] { - return withReadyDb(context.dbPath, context.migrationsDir, (db) => { - const item = db - .select({ id: schema.items.id }) - .from(schema.items) - .where(eq(schema.items.id, itemId)) - .get() - if (!item) { - throw new StashError(`Item ${itemId} not found.`, "NOT_FOUND", 3, 404) - } +export function listTtsJobsForItem(db: Db, itemId: number, limit = 10, offset = 0): TtsJob[] { + const item = db + .select({ id: schema.items.id }) + .from(schema.items) + .where(eq(schema.items.id, itemId)) + .get() + if (!item) { + throw new StashError(`Item ${itemId} not found.`, "NOT_FOUND", 3, 404) + } - return db - .select() - .from(schema.ttsJobs) - .where(eq(schema.ttsJobs.itemId, itemId)) - .orderBy(desc(schema.ttsJobs.createdAt), desc(schema.ttsJobs.id)) - .limit(limit) - .offset(offset) - .all() - .map((row) => serializeTtsJob(row)) - }) + return db + .select() + .from(schema.ttsJobs) + .where(eq(schema.ttsJobs.itemId, itemId)) + .orderBy(desc(schema.ttsJobs.createdAt), desc(schema.ttsJobs.id)) + .limit(limit) + .offset(offset) + .all() + .map((row) => serializeTtsJob(row)) } -export function claimNextQueuedJob(context: OperationContext): TtsJob | null { - return withReadyDb(context.dbPath, context.migrationsDir, (db) => { - const queued = db - .select() - .from(schema.ttsJobs) - .where(eq(schema.ttsJobs.status, "queued")) - .orderBy(asc(schema.ttsJobs.createdAt), asc(schema.ttsJobs.id)) - .get() - - if (!queued) { - return null - } +export function claimNextQueuedJob(db: Db): TtsJob | null { + const queued = db + .select() + .from(schema.ttsJobs) + .where(eq(schema.ttsJobs.status, "queued")) + .orderBy(asc(schema.ttsJobs.createdAt), asc(schema.ttsJobs.id)) + .get() - const startedAt = new Date(nowMs()) - const updated = db - .update(schema.ttsJobs) - .set({ - status: "running", - startedAt, - updatedAt: startedAt, - }) - .where(and(eq(schema.ttsJobs.id, queued.id), eq(schema.ttsJobs.status, "queued"))) - .run() + if (!queued) { + return null + } - if (Number(updated.changes) === 0) { - return null - } + const startedAt = new Date(nowMs()) + const updated = db + .update(schema.ttsJobs) + .set({ + status: "running", + startedAt, + updatedAt: startedAt, + }) + .where(and(eq(schema.ttsJobs.id, queued.id), eq(schema.ttsJobs.status, "queued"))) + .run() + + if (Number(updated.changes) === 0) { + return null + } - const claimed = db.select().from(schema.ttsJobs).where(eq(schema.ttsJobs.id, queued.id)).get() - return claimed ? serializeTtsJob(claimed) : null - }) + const claimed = db.select().from(schema.ttsJobs).where(eq(schema.ttsJobs.id, queued.id)).get() + return claimed ? serializeTtsJob(claimed) : null } -export function completeJobSuccess( - context: OperationContext, - jobId: number, - outputFileName: string, -): void { - withReadyDb(context.dbPath, context.migrationsDir, (db) => { - const finishedAt = new Date(nowMs()) - db.update(schema.ttsJobs) - .set({ - status: "succeeded", - outputFileName, - errorCode: null, - errorMessage: null, - finishedAt, - updatedAt: finishedAt, - }) - .where(eq(schema.ttsJobs.id, jobId)) - .run() - }) +export function completeJobSuccess(db: Db, jobId: number, outputFileName: string): void { + const finishedAt = new Date(nowMs()) + db.update(schema.ttsJobs) + .set({ + status: "succeeded", + outputFileName, + errorCode: null, + errorMessage: null, + finishedAt, + updatedAt: finishedAt, + }) + .where(eq(schema.ttsJobs.id, jobId)) + .run() } export function completeJobFailure( - context: OperationContext, + db: Db, jobId: number, errorCode: string, errorMessage: string, ): void { - withReadyDb(context.dbPath, context.migrationsDir, (db) => { - const finishedAt = new Date(nowMs()) - db.update(schema.ttsJobs) - .set({ - status: "failed", - errorCode, - errorMessage: errorMessage.slice(0, 1024), - finishedAt, - updatedAt: finishedAt, - }) - .where(eq(schema.ttsJobs.id, jobId)) - .run() - }) + const finishedAt = new Date(nowMs()) + db.update(schema.ttsJobs) + .set({ + status: "failed", + errorCode, + errorMessage: errorMessage.slice(0, 1024), + finishedAt, + updatedAt: finishedAt, + }) + .where(eq(schema.ttsJobs.id, jobId)) + .run() } -export function markStaleRunningJobsFailed(context: OperationContext): number { - return withReadyDb(context.dbPath, context.migrationsDir, (db) => { - const updatedAt = new Date(nowMs()) - const result = db - .update(schema.ttsJobs) - .set({ - status: "failed", - errorCode: "WORKER_RESTARTED", - errorMessage: "Worker restarted before job completion.", - finishedAt: updatedAt, - updatedAt, - }) - .where(eq(schema.ttsJobs.status, "running")) - .run() +export function markStaleRunningJobsFailed(db: Db): number { + const updatedAt = new Date(nowMs()) + const result = db + .update(schema.ttsJobs) + .set({ + status: "failed", + errorCode: "WORKER_RESTARTED", + errorMessage: "Worker restarted before job completion.", + finishedAt: updatedAt, + updatedAt, + }) + .where(eq(schema.ttsJobs.status, "running")) + .run() - return Number(result.changes) - }) + return Number(result.changes) } -export function pruneOldTerminalJobs( - context: OperationContext, - retentionMs = DEFAULT_TTS_JOB_RETENTION_MS, -): number { - return withReadyDb(context.dbPath, context.migrationsDir, (db) => { - const threshold = new Date(nowMs() - retentionMs) - const result = db - .delete(schema.ttsJobs) - .where( - and( - inArray(schema.ttsJobs.status, [...TERMINAL_JOB_STATUSES]), - lt(schema.ttsJobs.updatedAt, threshold), - ), - ) - .run() - return Number(result.changes) - }) +export function pruneOldTerminalJobs(db: Db, retentionMs = DEFAULT_TTS_JOB_RETENTION_MS): number { + const threshold = new Date(nowMs() - retentionMs) + const result = db + .delete(schema.ttsJobs) + .where( + and( + inArray(schema.ttsJobs.status, [...TERMINAL_JOB_STATUSES]), + lt(schema.ttsJobs.updatedAt, threshold), + ), + ) + .run() + return Number(result.changes) } export async function processNextTtsJob( - context: OperationContext, + db: Db, options: { audioDir?: string } = {}, ): Promise { - const claimed = claimNextQueuedJob(context) + const claimed = claimNextQueuedJob(db) if (!claimed) { return null } @@ -350,18 +307,18 @@ export async function processNextTtsJob( if (options.audioDir) { executeInput.audioDir = options.audioDir } - const result = await executeTtsForItem(context, executeInput) - completeJobSuccess(context, claimed.id, result.file_name) + const result = await executeTtsForItem(db, executeInput) + completeJobSuccess(db, claimed.id, result.file_name) } catch (error) { const stashError = asStashError(error) - completeJobFailure(context, claimed.id, stashError.code, stashError.message) + completeJobFailure(db, claimed.id, stashError.code, stashError.message) } - return getTtsJob(context, claimed.id) + return getTtsJob(db, claimed.id) } export async function waitForTtsJob( - context: OperationContext, + db: Db, jobId: number, options: { pollMs?: number; timeoutMs?: number } = {}, ): Promise { @@ -370,7 +327,7 @@ export async function waitForTtsJob( const deadline = Date.now() + timeoutMs while (true) { - const job = getTtsJob(context, jobId) + const job = getTtsJob(db, jobId) if (job.status === "succeeded" || job.status === "failed") { return job } @@ -383,18 +340,15 @@ export async function waitForTtsJob( } } -export function startTtsWorker( - context: OperationContext, - options: TtsWorkerOptions = {}, -): TtsWorkerHandle { +export function startTtsWorker(db: Db, options: TtsWorkerOptions = {}): TtsWorkerHandle { const pollMs = options.pollMs ?? DEFAULT_TTS_JOB_POLL_MS let shouldStop = false let timer: NodeJS.Timeout | null = null const loopPromise = (async (): Promise => { try { - markStaleRunningJobsFailed(context) - pruneOldTerminalJobs(context) + markStaleRunningJobsFailed(db) + pruneOldTerminalJobs(db) } catch (error) { if (options.onError) { options.onError(error) @@ -404,7 +358,7 @@ export function startTtsWorker( while (!shouldStop) { try { const processOptions = options.audioDir ? { audioDir: options.audioDir } : {} - const processed = await processNextTtsJob(context, processOptions) + const processed = await processNextTtsJob(db, processOptions) if (processed) { continue } @@ -436,10 +390,10 @@ export function startTtsWorker( } export async function runTtsWorkerOnce( - context: OperationContext, + db: Db, options: { audioDir?: string } = {}, ): Promise { - markStaleRunningJobsFailed(context) - pruneOldTerminalJobs(context) - return await processNextTtsJob(context, options) + markStaleRunningJobsFailed(db) + pruneOldTerminalJobs(db) + return await processNextTtsJob(db, options) } diff --git a/packages/core/src/features/tts/service.ts b/packages/core/src/features/tts/service.ts index 74c7f94..6e43795 100644 --- a/packages/core/src/features/tts/service.ts +++ b/packages/core/src/features/tts/service.ts @@ -9,9 +9,9 @@ import { DEFAULT_AUDIO_DIR, resolveAudioDir } from "../../lib/paths.js" import { buildFriendlyFilename, ensureUniqueFilePath } from "../../lib/tts/files.js" import { coquiTtsProvider } from "../../lib/tts/providers/coqui.js" import { TtsProviderError, type TtsFormat } from "../../lib/tts/types.js" -import type { OperationContext, TtsResult } from "../../types.js" +import type { TtsResult } from "../../types.js" import { parseTtsFormat } from "../common/validation.js" -import { nowMs, withReadyDb } from "../common/db.js" +import { type Db, nowMs } from "../common/db.js" export type GenerateTtsInput = { itemId: number @@ -31,41 +31,36 @@ function resolveCliPath(input: string): string { return path.resolve(input) } -function getItemTextForTts( - context: OperationContext, - itemId: number, -): { title: string | null; text: string } { - return withReadyDb(context.dbPath, context.migrationsDir, (db) => { - const row = db - .select({ - id: schema.items.id, - title: schema.items.title, - content: schema.notes.content, - }) - .from(schema.items) - .leftJoin(schema.notes, eq(schema.notes.itemId, schema.items.id)) - .where(eq(schema.items.id, itemId)) - .get() - - if (!row) { - throw new StashError(`Item ${itemId} not found.`, "NOT_FOUND", 3, 404) - } +function getItemTextForTts(db: Db, itemId: number): { title: string | null; text: string } { + const row = db + .select({ + id: schema.items.id, + title: schema.items.title, + content: schema.notes.content, + }) + .from(schema.items) + .leftJoin(schema.notes, eq(schema.notes.itemId, schema.items.id)) + .where(eq(schema.items.id, itemId)) + .get() - const text = row.content?.trim() ?? "" - if (text.length === 0) { - throw new StashError( - `No extracted content found for item ${itemId}. Save without --no-extract or re-save the URL.`, - "NO_CONTENT", - 2, - 400, - ) - } + if (!row) { + throw new StashError(`Item ${itemId} not found.`, "NOT_FOUND", 3, 404) + } - return { - title: row.title, - text, - } - }) + const text = row.content?.trim() ?? "" + if (text.length === 0) { + throw new StashError( + `No extracted content found for item ${itemId}. Save without --no-extract or re-save the URL.`, + "NO_CONTENT", + 2, + 400, + ) + } + + return { + title: row.title, + text, + } } function resolveTtsOutputPath( @@ -126,17 +121,14 @@ function resolveTtsOutputPath( return ensureUniqueFilePath(path.join(resolvedAudioDir, fileName)) } -export async function executeTtsForItem( - context: OperationContext, - input: GenerateTtsInput, -): Promise { +export async function executeTtsForItem(db: Db, input: GenerateTtsInput): Promise { const format = parseTtsFormat(input.format ?? "mp3") const voice = input.voice?.trim() ?? "tts_models/en/vctk/vits|p241" if (voice.length === 0) { throw new StashError("Voice cannot be empty.", "VALIDATION_ERROR", 2, 400) } - const { title, text } = getItemTextForTts(context, input.itemId) + const { title, text } = getItemTextForTts(db, input.itemId) let audioBuffer: Buffer let provider = "coqui" @@ -179,30 +171,28 @@ export async function executeTtsForItem( const fileName = path.basename(outputPath) const generatedAt = new Date(nowMs()) - withReadyDb(context.dbPath, context.migrationsDir, (db) => { - db.insert(schema.itemAudio) - .values({ - itemId: input.itemId, + db.insert(schema.itemAudio) + .values({ + itemId: input.itemId, + fileName, + provider, + voice, + format, + bytes: audioBuffer.length, + generatedAt, + }) + .onConflictDoUpdate({ + target: schema.itemAudio.itemId, + set: { fileName, provider, voice, format, bytes: audioBuffer.length, generatedAt, - }) - .onConflictDoUpdate({ - target: schema.itemAudio.itemId, - set: { - fileName, - provider, - voice, - format, - bytes: audioBuffer.length, - generatedAt, - }, - }) - .run() - }) + }, + }) + .run() return { item_id: input.itemId, @@ -215,9 +205,6 @@ export async function executeTtsForItem( } } -export async function generateTts( - context: OperationContext, - input: GenerateTtsInput, -): Promise { - return await executeTtsForItem(context, input) +export async function generateTts(db: Db, input: GenerateTtsInput): Promise { + return await executeTtsForItem(db, input) } diff --git a/packages/core/src/services/create-core-runtime.ts b/packages/core/src/services/create-core-runtime.ts new file mode 100644 index 0000000..333ecdf --- /dev/null +++ b/packages/core/src/services/create-core-runtime.ts @@ -0,0 +1,39 @@ +import { openDb } from "../db/client.js" +import { runMigrationsWithDatabase } from "../db/migrate.js" +import { ensureDbDirectory } from "../features/common/db.js" +import { createCoreServices } from "./create-core-services.js" +import type { CoreServices } from "./contracts.js" + +export type CreateCoreRuntimeOptions = { + dbPath: string + migrationsDir: string +} + +export type CoreRuntime = { + services: CoreServices + close: () => void +} + +export function createCoreRuntime(options: CreateCoreRuntimeOptions): CoreRuntime { + ensureDbDirectory(options.dbPath) + const { db, sqlite } = openDb(options.dbPath) + try { + runMigrationsWithDatabase(db, sqlite, options.migrationsDir) + } catch (error) { + sqlite.close() + throw error + } + + let closed = false + + return { + services: createCoreServices({ db }), + close: (): void => { + if (closed) { + return + } + sqlite.close() + closed = true + }, + } +} diff --git a/packages/core/src/services/create-core-services.ts b/packages/core/src/services/create-core-services.ts index ab6c792..5e4d197 100644 --- a/packages/core/src/services/create-core-services.ts +++ b/packages/core/src/services/create-core-services.ts @@ -12,36 +12,41 @@ import { startTtsWorker, waitForTtsJob, } from "../features/tts/jobs.js" -import type { OperationContext } from "../types.js" +import type { StashDb } from "../db/client.js" import type { CoreServices } from "./contracts.js" -export function createCoreServices(context: OperationContext): CoreServices { +export type CreateCoreServicesOptions = { + db: StashDb +} + +export function createCoreServices(options: CreateCoreServicesOptions): CoreServices { + const { db } = options + return { items: { - saveItem: async (input) => await saveItem(context, input), - listItems: (input) => listItems(context, input), - getItem: (itemId) => getItem(context, itemId), + saveItem: async (input) => await saveItem(db, input), + listItems: (input) => listItems(db, input), + getItem: (itemId) => getItem(db, itemId), }, extract: { - extractItem: async (itemId, options = {}) => await extractItem(context, itemId, options), + extractItem: async (itemId, options = {}) => await extractItem(db, itemId, options), }, tags: { - listTags: (input) => listTags(context, input), - addTag: (itemId, tag) => addTag(context, itemId, tag), - removeTag: (itemId, tag) => removeTag(context, itemId, tag), + listTags: (input) => listTags(db, input), + addTag: (itemId, tag) => addTag(db, itemId, tag), + removeTag: (itemId, tag) => removeTag(db, itemId, tag), }, status: { - markRead: (itemId) => markRead(context, itemId), - markUnread: (itemId) => markUnread(context, itemId), + markRead: (itemId) => markRead(db, itemId), + markUnread: (itemId) => markUnread(db, itemId), }, ttsJobs: { - enqueueTtsJob: (input) => enqueueTtsJob(context, input), - getTtsJob: (jobId) => getTtsJob(context, jobId), - listTtsJobsForItem: (itemId, limit, offset) => - listTtsJobsForItem(context, itemId, limit, offset), - waitForTtsJob: async (jobId, options) => await waitForTtsJob(context, jobId, options), - startTtsWorker: (options) => startTtsWorker(context, options), - runTtsWorkerOnce: async (options = {}) => await runTtsWorkerOnce(context, options), + enqueueTtsJob: (input) => enqueueTtsJob(db, input), + getTtsJob: (jobId) => getTtsJob(db, jobId), + listTtsJobsForItem: (itemId, limit, offset) => listTtsJobsForItem(db, itemId, limit, offset), + waitForTtsJob: async (jobId, options) => await waitForTtsJob(db, jobId, options), + startTtsWorker: (options) => startTtsWorker(db, options), + runTtsWorkerOnce: async (options = {}) => await runTtsWorkerOnce(db, options), }, doctor: { inspectCoquiTtsHealth: () => inspectCoquiTtsHealth(), diff --git a/packages/core/src/services/index.ts b/packages/core/src/services/index.ts index f361ec9..ceb2f9a 100644 --- a/packages/core/src/services/index.ts +++ b/packages/core/src/services/index.ts @@ -1,2 +1,3 @@ export * from "./contracts.js" +export * from "./create-core-runtime.js" export * from "./create-core-services.js" diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index ea43627..e707432 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -122,8 +122,3 @@ export type TtsJob = { finished_at: string | null updated_at: string } - -export type OperationContext = { - dbPath: string - migrationsDir: string -} diff --git a/packages/core/test/auto-tags.test.ts b/packages/core/test/auto-tags.test.ts index 8d067ed..15bf49d 100644 --- a/packages/core/test/auto-tags.test.ts +++ b/packages/core/test/auto-tags.test.ts @@ -9,10 +9,12 @@ import { openDb } from "../src/db/client.js" import { runMigrations } from "../src/db/migrate.js" import * as schema from "../src/db/schema.js" import { applyAutoTags } from "../src/features/auto-tags/service.js" -import type { OperationContext } from "../src/types.js" type TempContext = { - context: OperationContext + context: { + dbPath: string + migrationsDir: string + } tempDir: string } @@ -27,7 +29,7 @@ function createTempContext(): TempContext { } } -function createItem(context: OperationContext, slug: string, note: string): number { +function createItem(context: TempContext["context"], slug: string, note: string): number { runMigrations(context.dbPath, context.migrationsDir) const { db, sqlite } = openDb(context.dbPath) try { @@ -60,7 +62,7 @@ function createItem(context: OperationContext, slug: string, note: string): numb } } -function createTag(context: OperationContext, tag: string): number { +function createTag(context: TempContext["context"], tag: string): number { const { db, sqlite } = openDb(context.dbPath) try { const timestamp = new Date() @@ -86,7 +88,7 @@ function createTag(context: OperationContext, tag: string): number { } function attachTag( - context: OperationContext, + context: TempContext["context"], options: { itemId: number tagId: number diff --git a/packages/core/test/core-services.test.ts b/packages/core/test/core-services.test.ts index dfca284..a93c956 100644 --- a/packages/core/test/core-services.test.ts +++ b/packages/core/test/core-services.test.ts @@ -7,6 +7,7 @@ import * as statusModule from "../src/features/status/service.js" import * as tagsModule from "../src/features/tags/service.js" import * as ttsDoctorModule from "../src/features/tts/doctor.js" import * as ttsJobsModule from "../src/features/tts/jobs.js" +import type { StashDb } from "../src/db/client.js" import { createCoreServices } from "../src/services/create-core-services.js" import type { TtsJob } from "../src/types.js" @@ -14,10 +15,7 @@ afterEach(() => { vi.restoreAllMocks() }) -const context = { - dbPath: "/tmp/stash-test.db", - migrationsDir: "/tmp/stash-migrations", -} +const db = {} as StashDb function buildTtsJob(id: number): TtsJob { return { @@ -37,7 +35,7 @@ function buildTtsJob(id: number): TtsJob { } describe("createCoreServices", () => { - it("delegates all service methods to existing feature functions with bound context", async () => { + it("delegates all service methods to existing feature functions with bound db", async () => { const saveSpy = vi.spyOn(itemsModule, "saveItem").mockResolvedValue({ created: true, item: {} as never, @@ -120,7 +118,7 @@ describe("createCoreServices", () => { checks: [], }) - const services = createCoreServices(context) + const services = createCoreServices({ db }) const saveInput = { url: "https://example.com" } const listInput = { limit: 5, offset: 0 } @@ -154,25 +152,25 @@ describe("createCoreServices", () => { services.doctor.inspectCoquiTtsHealth() services.doctor.inspectAutoTagsHealth() - expect(saveSpy).toHaveBeenCalledWith(context, saveInput) - expect(listSpy).toHaveBeenCalledWith(context, listInput) - expect(getItemSpy).toHaveBeenCalledWith(context, 1) + expect(saveSpy).toHaveBeenCalledWith(db, saveInput) + expect(listSpy).toHaveBeenCalledWith(db, listInput) + expect(getItemSpy).toHaveBeenCalledWith(db, 1) - expect(extractSpy).toHaveBeenCalledWith(context, 1, extractOptions) + expect(extractSpy).toHaveBeenCalledWith(db, 1, extractOptions) - expect(listTagsSpy).toHaveBeenCalledWith(context, listTagsInput) - expect(addTagSpy).toHaveBeenCalledWith(context, 1, "ai") - expect(removeTagSpy).toHaveBeenCalledWith(context, 1, "ai") + expect(listTagsSpy).toHaveBeenCalledWith(db, listTagsInput) + expect(addTagSpy).toHaveBeenCalledWith(db, 1, "ai") + expect(removeTagSpy).toHaveBeenCalledWith(db, 1, "ai") - expect(markReadSpy).toHaveBeenCalledWith(context, 1) - expect(markUnreadSpy).toHaveBeenCalledWith(context, 1) + expect(markReadSpy).toHaveBeenCalledWith(db, 1) + expect(markUnreadSpy).toHaveBeenCalledWith(db, 1) - expect(enqueueSpy).toHaveBeenCalledWith(context, enqueueInput) - expect(getJobSpy).toHaveBeenCalledWith(context, 10) - expect(listJobsSpy).toHaveBeenCalledWith(context, 1, 10, 0) - expect(waitSpy).toHaveBeenCalledWith(context, 10, waitOptions) - expect(startWorkerSpy).toHaveBeenCalledWith(context, startWorkerOptions) - expect(runOnceSpy).toHaveBeenCalledWith(context, runOnceOptions) + expect(enqueueSpy).toHaveBeenCalledWith(db, enqueueInput) + expect(getJobSpy).toHaveBeenCalledWith(db, 10) + expect(listJobsSpy).toHaveBeenCalledWith(db, 1, 10, 0) + expect(waitSpy).toHaveBeenCalledWith(db, 10, waitOptions) + expect(startWorkerSpy).toHaveBeenCalledWith(db, startWorkerOptions) + expect(runOnceSpy).toHaveBeenCalledWith(db, runOnceOptions) expect(ttsDoctorSpy).toHaveBeenCalled() expect(autoTagsDoctorSpy).toHaveBeenCalled() diff --git a/packages/core/test/tts-jobs.test.ts b/packages/core/test/tts-jobs.test.ts index 1e5851a..b40e275 100644 --- a/packages/core/test/tts-jobs.test.ts +++ b/packages/core/test/tts-jobs.test.ts @@ -5,7 +5,7 @@ import path from "node:path" import { eq } from "drizzle-orm" import { afterEach, describe, expect, it } from "vitest" -import { openDb } from "../src/db/client.js" +import { openDb, type StashDb } from "../src/db/client.js" import { runMigrations } from "../src/db/migrate.js" import * as schema from "../src/db/schema.js" import { @@ -18,53 +18,49 @@ import { processNextTtsJob, pruneOldTerminalJobs, } from "../src/features/tts/jobs.js" -import type { OperationContext } from "../src/types.js" -function createTempContext(): { context: OperationContext; tempDir: string } { +function createTempDb(): { tempDir: string; dbPath: string; close: () => void; db: StashDb } { const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "stash-core-tts-jobs-")) + const dbPath = path.join(tempDir, "stash.db") + runMigrations(dbPath, path.join(process.cwd(), "drizzle")) + const { db, sqlite } = openDb(dbPath) return { - context: { - dbPath: path.join(tempDir, "stash.db"), - migrationsDir: path.join(process.cwd(), "drizzle"), - }, tempDir, + dbPath, + db, + close: (): void => { + sqlite.close() + }, } } -function seedItemWithContent(context: OperationContext, content = "test content"): number { - fs.mkdirSync(path.dirname(context.dbPath), { recursive: true }) - runMigrations(context.dbPath, context.migrationsDir) - const { db, sqlite } = openDb(context.dbPath) - try { - const timestamp = new Date() - const insert = db - .insert(schema.items) - .values({ - url: `https://example.com/${Math.random().toString(16).slice(2)}`, - title: "Example", - domain: "example.com", - status: "unread", - isStarred: false, - createdAt: timestamp, - updatedAt: timestamp, - readAt: null, - archivedAt: null, - }) - .run() - const itemId = Number(insert.lastInsertRowid) - - db.insert(schema.notes) - .values({ - itemId, - content, - updatedAt: timestamp, - }) - .run() - - return itemId - } finally { - sqlite.close() - } +function seedItemWithContent(db: StashDb, content = "test content"): number { + const timestamp = new Date() + const insert = db + .insert(schema.items) + .values({ + url: `https://example.com/${Math.random().toString(16).slice(2)}`, + title: "Example", + domain: "example.com", + status: "unread", + isStarred: false, + createdAt: timestamp, + updatedAt: timestamp, + readAt: null, + archivedAt: null, + }) + .run() + const itemId = Number(insert.lastInsertRowid) + + db.insert(schema.notes) + .values({ + itemId, + content, + updatedAt: timestamp, + }) + .run() + + return itemId } describe("tts jobs service", () => { @@ -80,63 +76,74 @@ describe("tts jobs service", () => { }) it("enqueue creates queued job and deduplicates active job per item", () => { - const { context, tempDir } = createTempContext() + const { db, close, tempDir } = createTempDb() tempDirs.push(tempDir) - const itemId = seedItemWithContent(context) - const first = enqueueTtsJob(context, { itemId, format: "mp3" }) - const second = enqueueTtsJob(context, { itemId, format: "mp3" }) - - expect(first.created).toBe(true) - expect(first.job.status).toBe("queued") - expect(second.created).toBe(false) - expect(second.job.id).toBe(first.job.id) + try { + const itemId = seedItemWithContent(db) + const first = enqueueTtsJob(db, { itemId, format: "mp3" }) + const second = enqueueTtsJob(db, { itemId, format: "mp3" }) + + expect(first.created).toBe(true) + expect(first.job.status).toBe("queued") + expect(second.created).toBe(false) + expect(second.job.id).toBe(first.job.id) + } finally { + close() + } }) it("claims queued job atomically", () => { - const { context, tempDir } = createTempContext() + const { db, close, tempDir } = createTempDb() tempDirs.push(tempDir) - const itemId = seedItemWithContent(context) - const queued = enqueueTtsJob(context, { itemId }) - const claimed = claimNextQueuedJob(context) - const none = claimNextQueuedJob(context) - - expect(claimed?.id).toBe(queued.job.id) - expect(claimed?.status).toBe("running") - expect(none).toBeNull() + try { + const itemId = seedItemWithContent(db) + const queued = enqueueTtsJob(db, { itemId }) + const claimed = claimNextQueuedJob(db) + const none = claimNextQueuedJob(db) + + expect(claimed?.id).toBe(queued.job.id) + expect(claimed?.status).toBe("running") + expect(none).toBeNull() + } finally { + close() + } }) it("marks stale running jobs as failed", () => { - const { context, tempDir } = createTempContext() + const { db, close, tempDir } = createTempDb() tempDirs.push(tempDir) - const itemId = seedItemWithContent(context) - const queued = enqueueTtsJob(context, { itemId }) - const claimed = claimNextQueuedJob(context) - expect(claimed?.status).toBe("running") + try { + const itemId = seedItemWithContent(db) + const queued = enqueueTtsJob(db, { itemId }) + const claimed = claimNextQueuedJob(db) + expect(claimed?.status).toBe("running") - const changed = markStaleRunningJobsFailed(context) - const updated = getTtsJob(context, queued.job.id) + const changed = markStaleRunningJobsFailed(db) + const updated = getTtsJob(db, queued.job.id) - expect(changed).toBe(1) - expect(updated.status).toBe("failed") - expect(updated.error_code).toBe("WORKER_RESTARTED") + expect(changed).toBe(1) + expect(updated.status).toBe("failed") + expect(updated.error_code).toBe("WORKER_RESTARTED") + } finally { + close() + } }) it("prunes only old terminal jobs", () => { - const { context, tempDir } = createTempContext() + const { db, close, tempDir } = createTempDb() tempDirs.push(tempDir) - const itemId = seedItemWithContent(context) - const queued = enqueueTtsJob(context, { itemId }) - const claimed = claimNextQueuedJob(context) - expect(claimed).not.toBeNull() + try { + const itemId = seedItemWithContent(db) + const queued = enqueueTtsJob(db, { itemId }) + const claimed = claimNextQueuedJob(db) + expect(claimed).not.toBeNull() - completeJobSuccess(context, queued.job.id, "old-file.mp3") + completeJobSuccess(db, queued.job.id, "old-file.mp3") - const { db, sqlite } = openDb(context.dbPath) - try { const oldTimestamp = new Date(Date.now() - 31 * 24 * 60 * 60 * 1000) db.update(schema.ttsJobs) .set({ @@ -144,33 +151,32 @@ describe("tts jobs service", () => { }) .where(eq(schema.ttsJobs.id, queued.job.id)) .run() + + const deleted = pruneOldTerminalJobs(db) + const jobs = listTtsJobsForItem(db, itemId, 10, 0) + expect(deleted).toBe(1) + expect(jobs).toHaveLength(0) } finally { - sqlite.close() + close() } - - const deleted = pruneOldTerminalJobs(context) - const jobs = listTtsJobsForItem(context, itemId, 10, 0) - expect(deleted).toBe(1) - expect(jobs).toHaveLength(0) }) it("processes queued job and persists latest item audio", async () => { - const { context, tempDir } = createTempContext() + const { db, close, tempDir } = createTempDb() tempDirs.push(tempDir) - const itemId = seedItemWithContent(context, "Audio body for synthesis.") - const queued = enqueueTtsJob(context, { itemId, format: "mp3" }) - const audioDir = path.join(tempDir, "audio") + try { + const itemId = seedItemWithContent(db, "Audio body for synthesis.") + const queued = enqueueTtsJob(db, { itemId, format: "mp3" }) + const audioDir = path.join(tempDir, "audio") - const processed = await processNextTtsJob(context, { audioDir }) - const finalJob = getTtsJob(context, queued.job.id) + const processed = await processNextTtsJob(db, { audioDir }) + const finalJob = getTtsJob(db, queued.job.id) - expect(processed).not.toBeNull() - expect(finalJob.status).toBe("succeeded") - expect(finalJob.output_file_name).toBeTruthy() + expect(processed).not.toBeNull() + expect(finalJob.status).toBe("succeeded") + expect(finalJob.output_file_name).toBeTruthy() - const { db, sqlite } = openDb(context.dbPath) - try { const row = db .select() .from(schema.itemAudio) @@ -179,7 +185,7 @@ describe("tts jobs service", () => { expect(row).toBeTruthy() expect(row?.fileName).toBe(finalJob.output_file_name) } finally { - sqlite.close() + close() } }) })