|
| 1 | +/* oxlint-disable executor/no-try-catch-or-throw, executor/no-json-parse -- boundary: one-shot data migration drives a raw SQL client (JSON text columns, transaction + rollback) */ |
| 2 | +// --------------------------------------------------------------------------- |
| 3 | +// One-off boot migration: unwrap the retired {status, headers, data} |
| 4 | +// transport envelope from persisted OpenAPI tool output schemas. The runtime |
| 5 | +// returns the upstream payload as `data` (status/headers live in the |
| 6 | +// ToolResult `http` side channel), so persisted schemas must describe the |
| 7 | +// payload only — otherwise describe previews show an envelope invocations no |
| 8 | +// longer return. Mirrors the cloud drizzle migration |
| 9 | +// (apps/cloud/drizzle/0002_unwrap_openapi_output_envelope.sql) for the |
| 10 | +// libSQL-backed apps, which have no SQL migration chain at boot. |
| 11 | +// |
| 12 | +// Idempotent by construction: payload-shaped rows don't match the envelope |
| 13 | +// signature, so re-running plans zero updates. |
| 14 | +// --------------------------------------------------------------------------- |
| 15 | + |
| 16 | +const isRecord = (value: unknown): value is Record<string, unknown> => |
| 17 | + typeof value === "object" && value !== null && !Array.isArray(value); |
| 18 | + |
| 19 | +// `{"type": "integer"}` — the envelope's `status` property schema, exactly. |
| 20 | +const isEnvelopeStatusSchema = (value: unknown): boolean => |
| 21 | + isRecord(value) && Object.keys(value).length === 1 && value.type === "integer"; |
| 22 | + |
| 23 | +// `{"type": "object", "additionalProperties": {"type": "string"}}` — the |
| 24 | +// envelope's `headers` property schema, exactly. |
| 25 | +const isEnvelopeHeadersSchema = (value: unknown): boolean => |
| 26 | + isRecord(value) && |
| 27 | + Object.keys(value).length === 2 && |
| 28 | + value.type === "object" && |
| 29 | + isRecord(value.additionalProperties) && |
| 30 | + Object.keys(value.additionalProperties).length === 1 && |
| 31 | + value.additionalProperties.type === "string"; |
| 32 | + |
| 33 | +/** |
| 34 | + * If `schema` is the retired transport envelope, return the payload schema |
| 35 | + * to persist instead (`null` when the envelope carried an empty `{}` data |
| 36 | + * schema — the new producer persists no output schema for those). Returns |
| 37 | + * undefined when the schema is not an envelope and the row must be left |
| 38 | + * untouched. |
| 39 | + */ |
| 40 | +export const unwrapOpenApiTransportEnvelope = ( |
| 41 | + schema: unknown, |
| 42 | +): { readonly outputSchema: unknown | null } | undefined => { |
| 43 | + if (!isRecord(schema)) return undefined; |
| 44 | + if (schema.type !== "object" || schema.additionalProperties !== false) return undefined; |
| 45 | + const required = schema.required; |
| 46 | + if (!Array.isArray(required) || required.length !== 3) return undefined; |
| 47 | + if (!["status", "headers", "data"].every((key) => required.includes(key))) return undefined; |
| 48 | + const properties = schema.properties; |
| 49 | + if (!isRecord(properties) || !("data" in properties)) return undefined; |
| 50 | + if (!isEnvelopeStatusSchema(properties.status)) return undefined; |
| 51 | + if (!isEnvelopeHeadersSchema(properties.headers)) return undefined; |
| 52 | + const data = properties.data; |
| 53 | + const outputSchema = isRecord(data) && Object.keys(data).length === 0 ? null : data; |
| 54 | + return { outputSchema }; |
| 55 | +}; |
| 56 | + |
| 57 | +// --------------------------------------------------------------------------- |
| 58 | +// SQLite runner — shared by the libSQL-backed apps (local boot, selfhost |
| 59 | +// boot). Structural client interface so the plugin doesn't take a driver |
| 60 | +// dependency; `@libsql/client` satisfies it. |
| 61 | +// --------------------------------------------------------------------------- |
| 62 | + |
| 63 | +export interface SqliteToolSchemaClient { |
| 64 | + execute( |
| 65 | + stmt: string | { readonly sql: string; readonly args: readonly unknown[] }, |
| 66 | + ): Promise<{ readonly rows: readonly Record<string, unknown>[] }>; |
| 67 | +} |
| 68 | + |
| 69 | +/** Unwrap envelope-shaped openapi tool output schemas in a SQLite database. |
| 70 | + * Idempotent; returns the number of rows rewritten. The `tool` table may |
| 71 | + * not exist yet on a fresh database — that counts as nothing to migrate. */ |
| 72 | +export const runSqliteOpenApiOutputSchemaMigration = async ( |
| 73 | + client: SqliteToolSchemaClient, |
| 74 | +): Promise<number> => { |
| 75 | + const exists = await client.execute( |
| 76 | + "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'tool'", |
| 77 | + ); |
| 78 | + if (exists.rows.length === 0) return 0; |
| 79 | + |
| 80 | + const result = await client.execute( |
| 81 | + "SELECT row_id, output_schema FROM tool WHERE plugin_id = 'openapi' AND output_schema IS NOT NULL", |
| 82 | + ); |
| 83 | + const updates: { readonly rowId: string; readonly outputSchema: unknown | null }[] = []; |
| 84 | + for (const row of result.rows) { |
| 85 | + if (typeof row.row_id !== "string" || typeof row.output_schema !== "string") continue; |
| 86 | + let schema: unknown; |
| 87 | + try { |
| 88 | + schema = JSON.parse(row.output_schema); |
| 89 | + } catch { |
| 90 | + continue; |
| 91 | + } |
| 92 | + const unwrapped = unwrapOpenApiTransportEnvelope(schema); |
| 93 | + if (unwrapped !== undefined) updates.push({ rowId: row.row_id, ...unwrapped }); |
| 94 | + } |
| 95 | + if (updates.length === 0) return 0; |
| 96 | + |
| 97 | + await client.execute("BEGIN"); |
| 98 | + try { |
| 99 | + for (const update of updates) { |
| 100 | + await client.execute({ |
| 101 | + sql: "UPDATE tool SET output_schema = ? WHERE row_id = ?", |
| 102 | + args: [ |
| 103 | + update.outputSchema === null ? null : JSON.stringify(update.outputSchema), |
| 104 | + update.rowId, |
| 105 | + ], |
| 106 | + }); |
| 107 | + } |
| 108 | + await client.execute("COMMIT"); |
| 109 | + } catch (cause) { |
| 110 | + await client.execute("ROLLBACK"); |
| 111 | + throw cause; |
| 112 | + } |
| 113 | + return updates.length; |
| 114 | +}; |
0 commit comments