Files
OmniRoute/src/lib/db/adapters/driverFactory.ts
Diego Rodrigues de Sa e Souza 7ee5bbc64d fix(build): v3.8.48 hotfix — npm tarball head-response-guard (#7065), electron win spawn, Sonar gate zeroed (#7055)
* fix(build): spawn npx.cmd through a shell in the electron better-sqlite3 rebuild

Node's CVE-2024-27980 hardening makes spawnSync of .cmd/.bat shims fail with
status null unless shell:true — the v3.8.47 tag build died on the Windows job
with 'better-sqlite3 rebuild against electron 43.1.0 failed (exit null)'.
Extracted the spawn plan into electronRebuildPlan.mjs (pure, import-safe) with
a regression test; args are fixed literals, no untrusted input reaches the shell.

* fix(build): ship head-response-guard.cjs in the npm tarball (#7065)

The prepublish prune allowlist (pack-artifact-policy.ts) lacked
head-response-guard.cjs, so assembleStandalone copied it and the prune
deleted it — every boot of the published 3.8.47 crashed with
ERR_MODULE_NOT_FOUND (3rd occurrence of this class; tls-options/3.8.41).
Also added to PACK_ARTIFACT_REQUIRED_PATHS so check:pack-artifact fails
loudly, plus a closure test that derives every server-ws.mjs sibling
import and asserts both lists cover it.

* fix(ci): zero the Sonar quality-gate findings on new code

- ci.yml sonarqube job: download the coverage artifact into coverage/ so
  lcov.info lands where sonar.javascript.lcov.reportPaths points — the
  upload strips the common coverage/ prefix, so 'path: .' left new-code
  coverage at 0% on every scan
- kiro auto-import: await the async isCloudEnabled() gate (S6544 — a bare
  truthiness check on the Promise made syncToCloud run even with cloud
  sync disabled)
- stream.ts: real JSON fallback in the reasoning-split clone (S3923 — both
  ternary branches called structuredClone, the promised fallback was dead)
- codex executor: handle the async reader.cancel() rejection (S4822)
- deterministic localeCompare sorts (S2871 x2)
- classify-pr-changes.mjs: confine the argv list file to the workspace
  (jssecurity:S8707 path-traversal guard) + behavioral tests
- Dockerfile: rebuild better-sqlite3 with npm's bundled node-gyp instead
  of npx --yes (docker:S6505 — no on-demand registry install)

* chore(ci): make the Sonar quality gate informational (wait=false)

The org's SonarCloud FREE plan cannot associate a custom quality gate — only
the built-in Sonar way (80% new coverage) applies, which no full-cycle release
PR can realistically meet. The scan still uploads (dashboard, PR decoration);
the CI job just no longer fails on the gate. A tuned 'OmniRoute way' gate
(coverage >=60, duplication <=5) is already configured in the org for the day
the plan is upgraded — re-enable wait=true then.

* chore(release): v3.8.48 hotfix bump + changelog (npm 3.8.47 unbootable, #7065)

* test: align pack-artifact + dockerfile guards to the corrected contracts

pack-artifact-policy.test.ts encoded the pre-#7065 REQUIRED list (without
head-response-guard.cjs) and dockerfile-better-sqlite3-node-gyp-6700.test.ts
asserted the npx invocation the Sonar fix replaced with npm's bundled
node-gyp — both now assert the corrected behavior.
2026-07-13 18:18:54 -03:00

139 lines
4.9 KiB
TypeScript

import { createRequire } from "node:module";
import { createBetterSqliteAdapter } from "./betterSqliteAdapter";
import {
createNodeSqliteAdapterFromDatabase,
type NodeSqliteDatabaseLike,
} from "./nodeSqliteShared";
import type { SqliteAdapter } from "./types";
const _require = createRequire(import.meta.url);
declare global {
var __omnirouteSqlJsAdapters: Map<string, SqliteAdapter> | undefined;
var __omnirouteSqlJsInitPromises: Map<string, Promise<SqliteAdapter>> | undefined;
}
function getSqlJsCache(): Map<string, SqliteAdapter> {
if (!globalThis.__omnirouteSqlJsAdapters) {
globalThis.__omnirouteSqlJsAdapters = new Map();
}
return globalThis.__omnirouteSqlJsAdapters;
}
/**
* Cache das Promises de inicialização EM VOO (não resolvidas ainda), por filePath.
* Separado de getSqlJsCache() (que só guarda o adapter já resolvido) para que
* chamadores concorrentes (BATCH/STARTUP/HealthCheck/ProviderLimitsSync no boot)
* compartilhem UMA única leitura+decode do arquivo em vez de cada um chamar
* fs.readFileSync + WASM decode independentemente (#6628 — thundering herd).
*/
function getSqlJsPendingCache(): Map<string, Promise<SqliteAdapter>> {
if (!globalThis.__omnirouteSqlJsInitPromises) {
globalThis.__omnirouteSqlJsInitPromises = new Map();
}
return globalThis.__omnirouteSqlJsInitPromises;
}
/** Tenta abrir com better-sqlite3 e node:sqlite sincronamente. Retorna null se ambos falharem. */
export function tryOpenSync(
filePath: string,
options?: Record<string, unknown>
): SqliteAdapter | null {
// better-sqlite3: rápido, nativo — skip em Bun
if (!process.versions.bun) {
try {
const BetterSqlite = _require("better-sqlite3") as {
new (p: string, o?: object): import("better-sqlite3").Database;
};
const db = new BetterSqlite(filePath, options);
return createBetterSqliteAdapter(db);
} catch {
// continua para próximo driver
}
}
// node:sqlite: built-in desde Node 22.5 — skip em Bun
if (!process.versions.bun) {
const [maj, min] = (process.versions.node ?? "0.0").split(".").map(Number);
if (maj > 22 || (maj === 22 && min >= 5)) {
try {
const { DatabaseSync } = _require("node:sqlite") as {
DatabaseSync: new (p: string) => NodeSqliteDatabaseLike;
};
const db = new DatabaseSync(filePath);
return createNodeSqliteAdapterFromDatabase(db, filePath);
} catch {
// continua
}
}
}
return null;
}
/**
* Pré-inicializa sql.js para um filePath.
* Armazena em globalThis para acesso posterior via getSqlJsAdapter().
* Idempotente — seguro chamar múltiplas vezes.
*/
export async function preInitSqlJs(filePath: string): Promise<SqliteAdapter> {
const cache = getSqlJsCache();
const existing = cache.get(filePath);
if (existing) {
if (existing.open) return existing;
// Stale handle left over by a prior close/reload (e.g. gracefulShutdown or
// resetDbInstance closed the underlying WASM db but this globalThis-backed
// cache — deliberately shared across re-invocations for idempotency — still
// holds the reference). Reusing it would make every subsequent query throw
// the raw string "Database closed" straight from sql.js (#6560). Evict and
// recreate instead of returning a dead connection.
cache.delete(filePath);
}
// Share one in-flight load across concurrent callers for the same filePath
// (#6628): without this, each of BATCH/STARTUP/HealthCheck/ProviderLimitsSync
// independently fs.readFileSync + WASM-decode the same (possibly 300+MB) file
// at boot, multiplying peak memory pressure by the number of racing callers.
const pending = getSqlJsPendingCache();
const inflight = pending.get(filePath);
if (inflight !== undefined) return inflight;
const initPromise = (async () => {
const { createSqlJsAdapter } = await import("./sqljsAdapter");
const adapter = await createSqlJsAdapter(filePath);
cache.set(filePath, adapter);
return adapter;
})();
pending.set(filePath, initPromise);
try {
return await initPromise;
} finally {
pending.delete(filePath);
}
}
/** Retorna adapter sql.js pré-inicializado ou null se ainda não inicializado. */
export function getSqlJsAdapter(filePath: string): SqliteAdapter | null {
return getSqlJsCache().get(filePath) ?? null;
}
/**
* Factory assíncrona completa: tenta todos os drivers em cascata.
* Ordem: better-sqlite3 → node:sqlite → sql.js
*/
export async function openDatabaseAsync(
filePath: string,
options?: Record<string, unknown>
): Promise<SqliteAdapter> {
const sync = tryOpenSync(filePath, options);
if (sync) {
console.log(`[DB] Driver: ${sync.driver} | file: ${filePath}`);
return sync;
}
console.warn("[DB] Synchronous drivers unavailable — falling back to sql.js (WASM)");
const adapter = await preInitSqlJs(filePath);
console.log(`[DB] Driver: sql.js | file: ${filePath}`);
return adapter;
}