Skip to content

Commit 47e86bc

Browse files
committed
refactor: share task sqlite store helpers
1 parent 7f6579e commit 47e86bc

4 files changed

Lines changed: 95 additions & 115 deletions

File tree

‎src/tasks/task-flow-registry.store.sqlite.ts‎

Lines changed: 19 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,18 @@
1-
import { chmodSync, existsSync, mkdirSync } from "node:fs";
21
import type { DatabaseSync, StatementSync } from "node:sqlite";
32
import { requireNodeSqlite } from "../infra/node-sqlite.js";
43
import { configureSqliteWalMaintenance, type SqliteWalMaintenance } from "../infra/sqlite-wal.js";
5-
import { isRecord } from "../utils.js";
6-
import { normalizeDeliveryContext } from "../utils/delivery-context.shared.js";
7-
import type { DeliveryContext } from "../utils/delivery-context.types.js";
84
import {
95
resolveTaskFlowRegistryDir,
106
resolveTaskFlowRegistrySqlitePath,
117
} from "./task-flow-registry.paths.js";
128
import type { TaskFlowRegistryStoreSnapshot } from "./task-flow-registry.store.types.js";
139
import type { TaskFlowRecord, TaskFlowSyncMode, JsonValue } from "./task-flow-registry.types.js";
10+
import {
11+
ensureSqliteStorePermissions,
12+
normalizeSqliteNumber,
13+
parseDeliveryContextJson,
14+
parseSqliteJsonValue,
15+
} from "./task-registry.sqlite.shared.js";
1416

1517
type FlowRegistryRow = {
1618
flow_id: string;
@@ -51,7 +53,6 @@ type FlowRegistryDatabase = {
5153
let cachedDatabase: FlowRegistryDatabase | null = null;
5254
const FLOW_REGISTRY_DIR_MODE = 0o700;
5355
const FLOW_REGISTRY_FILE_MODE = 0o600;
54-
const FLOW_REGISTRY_SIDECAR_SUFFIXES = ["", "-shm", "-wal"] as const;
5556
const FLOW_RUNS_COLUMNS = `
5657
flow_id TEXT PRIMARY KEY,
5758
shape TEXT,
@@ -74,45 +75,10 @@ const FLOW_RUNS_COLUMNS = `
7475
ended_at INTEGER
7576
`;
7677

77-
function normalizeNumber(value: number | bigint | null): number | undefined {
78-
if (typeof value === "bigint") {
79-
return Number(value);
80-
}
81-
return typeof value === "number" ? value : undefined;
82-
}
83-
8478
function serializeJson(value: unknown): string | null {
8579
return value === undefined ? null : JSON.stringify(value);
8680
}
8781

88-
// oxlint-disable-next-line typescript/no-unnecessary-type-parameters -- Persisted JSON columns are typed by the receiving field.
89-
function parseJsonValue<T>(raw: string | null): T | undefined {
90-
if (!raw?.trim()) {
91-
return undefined;
92-
}
93-
try {
94-
return JSON.parse(raw) as T;
95-
} catch {
96-
return undefined;
97-
}
98-
}
99-
100-
function parseDeliveryContextJson(raw: string | null): DeliveryContext | undefined {
101-
const parsed = parseJsonValue<unknown>(raw);
102-
if (!isRecord(parsed)) {
103-
return undefined;
104-
}
105-
return normalizeDeliveryContext({
106-
channel: typeof parsed.channel === "string" ? parsed.channel : undefined,
107-
to: typeof parsed.to === "string" ? parsed.to : undefined,
108-
accountId: typeof parsed.accountId === "string" ? parsed.accountId : undefined,
109-
threadId:
110-
typeof parsed.threadId === "string" || typeof parsed.threadId === "number"
111-
? parsed.threadId
112-
: undefined,
113-
});
114-
}
115-
11682
function rowToSyncMode(row: FlowRegistryRow): TaskFlowSyncMode {
11783
if (row.sync_mode === "task_mirrored" || row.sync_mode === "managed") {
11884
return row.sync_mode;
@@ -121,18 +87,18 @@ function rowToSyncMode(row: FlowRegistryRow): TaskFlowSyncMode {
12187
}
12288

12389
function rowToFlowRecord(row: FlowRegistryRow): TaskFlowRecord {
124-
const endedAt = normalizeNumber(row.ended_at);
125-
const cancelRequestedAt = normalizeNumber(row.cancel_requested_at);
90+
const endedAt = normalizeSqliteNumber(row.ended_at);
91+
const cancelRequestedAt = normalizeSqliteNumber(row.cancel_requested_at);
12692
const requesterOrigin = parseDeliveryContextJson(row.requester_origin_json);
127-
const stateJson = parseJsonValue<JsonValue>(row.state_json);
128-
const waitJson = parseJsonValue<JsonValue>(row.wait_json);
93+
const stateJson = parseSqliteJsonValue<JsonValue>(row.state_json);
94+
const waitJson = parseSqliteJsonValue<JsonValue>(row.wait_json);
12995
return {
13096
flowId: row.flow_id,
13197
syncMode: rowToSyncMode(row),
13298
ownerKey: row.owner_key,
13399
...(requesterOrigin ? { requesterOrigin } : {}),
134100
...(row.controller_id ? { controllerId: row.controller_id } : {}),
135-
revision: normalizeNumber(row.revision) ?? 0,
101+
revision: normalizeSqliteNumber(row.revision) ?? 0,
136102
status: row.status,
137103
notifyPolicy: row.notify_policy,
138104
goal: row.goal,
@@ -142,8 +108,8 @@ function rowToFlowRecord(row: FlowRegistryRow): TaskFlowRecord {
142108
...(stateJson !== undefined ? { stateJson } : {}),
143109
...(waitJson !== undefined ? { waitJson } : {}),
144110
...(cancelRequestedAt != null ? { cancelRequestedAt } : {}),
145-
createdAt: normalizeNumber(row.created_at) ?? 0,
146-
updatedAt: normalizeNumber(row.updated_at) ?? 0,
111+
createdAt: normalizeSqliteNumber(row.created_at) ?? 0,
112+
updatedAt: normalizeSqliteNumber(row.updated_at) ?? 0,
147113
...(endedAt != null ? { endedAt } : {}),
148114
};
149115
}
@@ -429,16 +395,12 @@ function ensureSchema(db: DatabaseSync) {
429395
}
430396

431397
function ensureFlowRegistryPermissions(pathname: string) {
432-
const dir = resolveTaskFlowRegistryDir(process.env);
433-
mkdirSync(dir, { recursive: true, mode: FLOW_REGISTRY_DIR_MODE });
434-
chmodSync(dir, FLOW_REGISTRY_DIR_MODE);
435-
for (const suffix of FLOW_REGISTRY_SIDECAR_SUFFIXES) {
436-
const candidate = `${pathname}${suffix}`;
437-
if (!existsSync(candidate)) {
438-
continue;
439-
}
440-
chmodSync(candidate, FLOW_REGISTRY_FILE_MODE);
441-
}
398+
ensureSqliteStorePermissions({
399+
dir: resolveTaskFlowRegistryDir(process.env),
400+
pathname,
401+
dirMode: FLOW_REGISTRY_DIR_MODE,
402+
fileMode: FLOW_REGISTRY_FILE_MODE,
403+
});
442404
}
443405

444406
function openFlowRegistryDatabase(): FlowRegistryDatabase {
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import { chmodSync, existsSync, mkdirSync } from "node:fs";
2+
import { isRecord } from "../utils.js";
3+
import { normalizeDeliveryContext } from "../utils/delivery-context.shared.js";
4+
import type { DeliveryContext } from "../utils/delivery-context.types.js";
5+
6+
export const SQLITE_SIDECAR_SUFFIXES = ["", "-shm", "-wal"] as const;
7+
8+
export function normalizeSqliteNumber(value: number | bigint | null): number | undefined {
9+
if (typeof value === "bigint") {
10+
return Number(value);
11+
}
12+
return typeof value === "number" ? value : undefined;
13+
}
14+
15+
// oxlint-disable-next-line typescript/no-unnecessary-type-parameters -- Persisted JSON columns are typed by the receiving field.
16+
export function parseSqliteJsonValue<T>(raw: string | null): T | undefined {
17+
if (!raw?.trim()) {
18+
return undefined;
19+
}
20+
try {
21+
return JSON.parse(raw) as T;
22+
} catch {
23+
return undefined;
24+
}
25+
}
26+
27+
export function parseDeliveryContextJson(raw: string | null): DeliveryContext | undefined {
28+
const parsed = parseSqliteJsonValue<unknown>(raw);
29+
if (!isRecord(parsed)) {
30+
return undefined;
31+
}
32+
return normalizeDeliveryContext({
33+
channel: typeof parsed.channel === "string" ? parsed.channel : undefined,
34+
to: typeof parsed.to === "string" ? parsed.to : undefined,
35+
accountId: typeof parsed.accountId === "string" ? parsed.accountId : undefined,
36+
threadId:
37+
typeof parsed.threadId === "string" || typeof parsed.threadId === "number"
38+
? parsed.threadId
39+
: undefined,
40+
});
41+
}
42+
43+
export function ensureSqliteStorePermissions(params: {
44+
dir: string;
45+
pathname: string;
46+
dirMode: number;
47+
fileMode: number;
48+
}) {
49+
mkdirSync(params.dir, { recursive: true, mode: params.dirMode });
50+
chmodSync(params.dir, params.dirMode);
51+
for (const suffix of SQLITE_SIDECAR_SUFFIXES) {
52+
const candidate = `${params.pathname}${suffix}`;
53+
if (!existsSync(candidate)) {
54+
continue;
55+
}
56+
chmodSync(candidate, params.fileMode);
57+
}
58+
}

‎src/tasks/task-registry.store.sqlite.ts‎

Lines changed: 17 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1-
import { chmodSync, existsSync, mkdirSync } from "node:fs";
21
import type { DatabaseSync, StatementSync } from "node:sqlite";
32
import { requireNodeSqlite } from "../infra/node-sqlite.js";
43
import { configureSqliteWalMaintenance, type SqliteWalMaintenance } from "../infra/sqlite-wal.js";
5-
import { isRecord } from "../utils.js";
6-
import { normalizeDeliveryContext } from "../utils/delivery-context.shared.js";
7-
import type { DeliveryContext } from "../utils/delivery-context.types.js";
84
import { resolveTaskRegistryDir, resolveTaskRegistrySqlitePath } from "./task-registry.paths.js";
5+
import {
6+
ensureSqliteStorePermissions,
7+
normalizeSqliteNumber,
8+
parseDeliveryContextJson,
9+
} from "./task-registry.sqlite.shared.js";
910
import type { TaskRegistryStoreSnapshot } from "./task-registry.store.types.js";
1011
import type { TaskDeliveryState, TaskRecord } from "./task-registry.types.js";
1112

@@ -70,7 +71,6 @@ type TaskRegistryDatabase = {
7071
let cachedDatabase: TaskRegistryDatabase | null = null;
7172
const TASK_REGISTRY_DIR_MODE = 0o700;
7273
const TASK_REGISTRY_FILE_MODE = 0o600;
73-
const TASK_REGISTRY_SIDECAR_SUFFIXES = ["", "-shm", "-wal"] as const;
7474
const TASK_RUN_SELECT_COLUMNS = `
7575
task_id,
7676
runtime,
@@ -100,50 +100,15 @@ const TASK_RUN_SELECT_COLUMNS = `
100100
terminal_outcome
101101
`;
102102

103-
function normalizeNumber(value: number | bigint | null): number | undefined {
104-
if (typeof value === "bigint") {
105-
return Number(value);
106-
}
107-
return typeof value === "number" ? value : undefined;
108-
}
109-
110103
function serializeJson(value: unknown): string | null {
111104
return value == null ? null : JSON.stringify(value);
112105
}
113106

114-
// oxlint-disable-next-line typescript/no-unnecessary-type-parameters -- Persisted JSON columns are typed by the receiving field.
115-
function parseJsonValue<T>(raw: string | null): T | undefined {
116-
if (!raw?.trim()) {
117-
return undefined;
118-
}
119-
try {
120-
return JSON.parse(raw) as T;
121-
} catch {
122-
return undefined;
123-
}
124-
}
125-
126-
function parseDeliveryContextJson(raw: string | null): DeliveryContext | undefined {
127-
const parsed = parseJsonValue<unknown>(raw);
128-
if (!isRecord(parsed)) {
129-
return undefined;
130-
}
131-
return normalizeDeliveryContext({
132-
channel: typeof parsed.channel === "string" ? parsed.channel : undefined,
133-
to: typeof parsed.to === "string" ? parsed.to : undefined,
134-
accountId: typeof parsed.accountId === "string" ? parsed.accountId : undefined,
135-
threadId:
136-
typeof parsed.threadId === "string" || typeof parsed.threadId === "number"
137-
? parsed.threadId
138-
: undefined,
139-
});
140-
}
141-
142107
function rowToTaskRecord(row: TaskRegistryRow): TaskRecord {
143-
const startedAt = normalizeNumber(row.started_at);
144-
const endedAt = normalizeNumber(row.ended_at);
145-
const lastEventAt = normalizeNumber(row.last_event_at);
146-
const cleanupAfter = normalizeNumber(row.cleanup_after);
108+
const startedAt = normalizeSqliteNumber(row.started_at);
109+
const endedAt = normalizeSqliteNumber(row.ended_at);
110+
const lastEventAt = normalizeSqliteNumber(row.last_event_at);
111+
const cleanupAfter = normalizeSqliteNumber(row.cleanup_after);
147112
const requesterSessionKey =
148113
row.scope_kind === "system" ? "" : row.requester_session_key?.trim() || row.owner_key;
149114
return {
@@ -164,7 +129,7 @@ function rowToTaskRecord(row: TaskRegistryRow): TaskRecord {
164129
status: row.status,
165130
deliveryStatus: row.delivery_status,
166131
notifyPolicy: row.notify_policy,
167-
createdAt: normalizeNumber(row.created_at) ?? 0,
132+
createdAt: normalizeSqliteNumber(row.created_at) ?? 0,
168133
...(startedAt != null ? { startedAt } : {}),
169134
...(endedAt != null ? { endedAt } : {}),
170135
...(lastEventAt != null ? { lastEventAt } : {}),
@@ -178,7 +143,7 @@ function rowToTaskRecord(row: TaskRegistryRow): TaskRecord {
178143

179144
function rowToTaskDeliveryState(row: TaskDeliveryStateRow): TaskDeliveryState {
180145
const requesterOrigin = parseDeliveryContextJson(row.requester_origin_json);
181-
const lastNotifiedEventAt = normalizeNumber(row.last_notified_event_at);
146+
const lastNotifiedEventAt = normalizeSqliteNumber(row.last_notified_event_at);
182147
return {
183148
taskId: row.task_id,
184149
...(requesterOrigin ? { requesterOrigin } : {}),
@@ -454,16 +419,12 @@ function ensureSchema(db: DatabaseSync) {
454419
}
455420

456421
function ensureTaskRegistryPermissions(pathname: string) {
457-
const dir = resolveTaskRegistryDir(process.env);
458-
mkdirSync(dir, { recursive: true, mode: TASK_REGISTRY_DIR_MODE });
459-
chmodSync(dir, TASK_REGISTRY_DIR_MODE);
460-
for (const suffix of TASK_REGISTRY_SIDECAR_SUFFIXES) {
461-
const candidate = `${pathname}${suffix}`;
462-
if (!existsSync(candidate)) {
463-
continue;
464-
}
465-
chmodSync(candidate, TASK_REGISTRY_FILE_MODE);
466-
}
422+
ensureSqliteStorePermissions({
423+
dir: resolveTaskRegistryDir(process.env),
424+
pathname,
425+
dirMode: TASK_REGISTRY_DIR_MODE,
426+
fileMode: TASK_REGISTRY_FILE_MODE,
427+
});
467428
}
468429

469430
function openTaskRegistryDatabase(): TaskRegistryDatabase {

‎test/scripts/lint-suppressions.test.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -169,8 +169,7 @@ describe("production lint suppressions", () => {
169169
"src/plugins/runtime/runtime-plugin-boundary.ts|typescript/no-unnecessary-type-parameters|1",
170170
"src/plugins/runtime/types-channel.ts|typescript/no-unnecessary-type-parameters|1",
171171
"src/plugins/trusted-tool-policy.ts|typescript/no-unnecessary-type-parameters|1",
172-
"src/tasks/task-flow-registry.store.sqlite.ts|typescript/no-unnecessary-type-parameters|1",
173-
"src/tasks/task-registry.store.sqlite.ts|typescript/no-unnecessary-type-parameters|1",
172+
"src/tasks/task-registry.sqlite.shared.ts|typescript/no-unnecessary-type-parameters|1",
174173
"src/test-utils/bundled-plugin-public-surface.ts|typescript/no-unnecessary-type-parameters|2",
175174
"src/test-utils/vitest-mock-fn.ts|typescript/no-explicit-any|1",
176175
"src/utils.ts|typescript/no-unnecessary-type-parameters|1",

0 commit comments

Comments
 (0)