@nmakarov/cli-toolkit 0.33.0 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1868,6 +1868,43 @@ var Params = class _Params {
1868
1868
  module: moduleName ?? this._currentModule
1869
1869
  });
1870
1870
  }
1871
+ /**
1872
+ * Report a param value that a component RESOLVED ON ITS OWN — outside
1873
+ * Params.get() — e.g. discovered by combining its config files (the way
1874
+ * blueprints merge defaults/aggregator/feed data). Without this, every
1875
+ * key such a component probed for an override shows up in the
1876
+ * --showUsedParams dump as "undefined (default)"; reporting upgrades the
1877
+ * entry to the value the component actually works with.
1878
+ *
1879
+ * Attribution rules:
1880
+ * - entries figured from an explicit input (cli/env/options/…) are left
1881
+ * untouched — the component merely confirmed them, the origin stands;
1882
+ * - entries whose source is "default" (Params had nothing) are upgraded
1883
+ * in place to the reported value and source;
1884
+ * - keys never seen by Params are appended as new entries.
1885
+ * First report wins: once upgraded, later reports for the same key/module
1886
+ * are ignored (the source is no longer "default").
1887
+ *
1888
+ * @param {string} key
1889
+ * @param {*} value - the value the component actually uses
1890
+ * @param {string} [source="discovered"] - short origin label, e.g. "blueprint"
1891
+ * @param {string} [moduleName] - dump section; defaults to the current module
1892
+ */
1893
+ reportResolved(key, value, source = "discovered", moduleName) {
1894
+ const mod = moduleName ?? this._currentModule;
1895
+ const mine = this.trackedParams.filter((e) => e.key === key && e.module === mod);
1896
+ if (mine.some((e) => e.source !== "default")) {
1897
+ return;
1898
+ }
1899
+ if (mine.length === 0) {
1900
+ this.trackParam(key, "reported", value, source, mod);
1901
+ return;
1902
+ }
1903
+ for (const entry of mine) {
1904
+ entry.value = value;
1905
+ entry.source = source;
1906
+ }
1907
+ }
1871
1908
  /**
1872
1909
  * Get all tracked parameters (for --stopAfter=init)
1873
1910
  */
@@ -2660,13 +2697,100 @@ async function init(flow2, opts = {}) {
2660
2697
 
2661
2698
  // src/db/index.js
2662
2699
  var import_knex = __toESM(require("knex"), 1);
2700
+
2701
+ // src/db/ensure.js
2702
+ var dbLabel = (db) => db?.config?.name ?? "db";
2703
+ async function ensureExtension(db, name, options = {}) {
2704
+ const action = `CREATE EXTENSION IF NOT EXISTS "${name}"`;
2705
+ if (!options.dryRun) {
2706
+ await db.raw(action);
2707
+ }
2708
+ options.logger?.silly?.(`[ensure] ${dbLabel(db)}: ${action}${options.dryRun ? " (dryRun)" : ""}`);
2709
+ return { action };
2710
+ }
2711
+ async function ensureTable(db, tableName, spec, options = {}) {
2712
+ const { dryRun = false, logger } = options;
2713
+ const actions = [];
2714
+ const exists = await db.tableExists(tableName);
2715
+ if (!exists) {
2716
+ actions.push(`CREATE TABLE ${tableName} (${Object.keys(spec.columns).length} columns)`);
2717
+ if (!dryRun) {
2718
+ await db.schema.createTable(tableName, (t) => {
2719
+ for (const define of Object.values(spec.columns)) {
2720
+ define(t, db);
2721
+ }
2722
+ });
2723
+ }
2724
+ } else {
2725
+ const missing = [];
2726
+ for (const column of Object.keys(spec.columns)) {
2727
+ if (!await db.schema.hasColumn(tableName, column)) {
2728
+ missing.push(column);
2729
+ }
2730
+ }
2731
+ if (missing.length > 0) {
2732
+ actions.push(`ALTER TABLE ${tableName} ADD COLUMN ${missing.join(", ")}`);
2733
+ if (!dryRun) {
2734
+ await db.schema.alterTable(tableName, (t) => {
2735
+ for (const column of missing) {
2736
+ spec.columns[column](t, db);
2737
+ }
2738
+ });
2739
+ }
2740
+ }
2741
+ }
2742
+ for (const index of spec.indexes ?? []) {
2743
+ const indexActions = await ensureIndex(db, tableName, index, options);
2744
+ actions.push(...indexActions);
2745
+ }
2746
+ for (const action of actions) {
2747
+ logger?.silly?.(`[ensure] ${dbLabel(db)}: ${action}${dryRun ? " (dryRun)" : ""}`);
2748
+ }
2749
+ return actions;
2750
+ }
2751
+ async function ensureIndex(db, tableName, index, options = {}) {
2752
+ const { dryRun = false } = options;
2753
+ const kind = index.unique ? "UNIQUE INDEX" : "INDEX";
2754
+ const cols = index.columns.map((c) => `"${c}"`).join(", ");
2755
+ const isPg = String(db?.config?.connectionString ?? "").startsWith("postgresql");
2756
+ if (isPg) {
2757
+ const sql2 = `CREATE ${kind} IF NOT EXISTS "${index.name}" ON "${tableName}" (${cols})`;
2758
+ const { rows } = await db.raw(`SELECT 1 FROM pg_indexes WHERE indexname = ?`, [index.name]);
2759
+ if (rows.length > 0) return [];
2760
+ if (!dryRun) await db.raw(sql2);
2761
+ return [sql2];
2762
+ }
2763
+ const sql = `CREATE ${kind} ${index.name} ON ${tableName} (${cols})`;
2764
+ if (!dryRun) {
2765
+ try {
2766
+ await db.raw(sql);
2767
+ } catch (error) {
2768
+ if (!/already exists|duplicate/i.test(error?.message ?? "")) throw error;
2769
+ return [];
2770
+ }
2771
+ }
2772
+ return [sql];
2773
+ }
2774
+ async function ensureSchema(db, spec, options = {}) {
2775
+ const actions = [];
2776
+ for (const extension of spec.extensions ?? []) {
2777
+ const { action } = await ensureExtension(db, extension, options);
2778
+ if (options.dryRun) actions.push(action);
2779
+ }
2780
+ for (const [tableName, tableSpec] of Object.entries(spec.tables ?? {})) {
2781
+ actions.push(...await ensureTable(db, tableName, tableSpec, options));
2782
+ }
2783
+ return { database: dbLabel(db), actions };
2784
+ }
2785
+
2786
+ // src/db/index.js
2663
2787
  var KNEX_DEFAULTS = {
2664
2788
  testConnection: true,
2665
2789
  pool: { min: 2, max: 10 },
2666
2790
  acquireConnectionTimeout: 1e4,
2667
2791
  ssl: { rejectUnauthorized: false }
2668
2792
  };
2669
- var Db = class {
2793
+ var Db = class _Db {
2670
2794
  static async init(context, options = {}) {
2671
2795
  const buildConfig = async () => {
2672
2796
  const defs2 = {
@@ -2735,6 +2859,177 @@ var Db = class {
2735
2859
  const config2 = context?.params?.runWithModuleAsync ? await context.params.runWithModuleAsync("db", buildConfig) : await buildConfig();
2736
2860
  return dbConnect(context, config2);
2737
2861
  }
2862
+ /**
2863
+ * Initialize a SIBLING database handler: a database that lives on the same
2864
+ * server with the same credentials/options as an existing ("base") one, and
2865
+ * differs only by its database name. Typical use: a per-tenant / per-subject
2866
+ * database alongside a main database that keeps the shared tables.
2867
+ *
2868
+ * context.db = await Db.init(context); // main
2869
+ * const sub = await Db.initSibling(context, "src_bright"); // sibling
2870
+ *
2871
+ * LOCATION-AGNOSTIC BY DESIGN — the call gracefully falls back to the main
2872
+ * database, so callers can use it for all subject data without knowing what
2873
+ * has been migrated where:
2874
+ * - empty `siblingName` → the main handler (same as Db.init)
2875
+ * - sibling DB does not exist yet → the main handler (data not migrated;
2876
+ * it still lives in the main database)
2877
+ * Callers that must not fall back can check `handler === context.db`.
2878
+ *
2879
+ * Connection string resolution for an actual sibling, in order:
2880
+ * 1. Explicit override — param `dbConnectionStringSib<SiblingName>` (env
2881
+ * `DB_CONNECTION_STRING_SIB_<SIBLING_NAME>`, e.g. `src_bright` →
2882
+ * `DB_CONNECTION_STRING_SIB_SRC_BRIGHT`). Nobody needs this on day
2883
+ * one; it is the escape hatch for when a sibling later moves to its
2884
+ * own server — one env var, no code changes (the `SIB_` namespace
2885
+ * both overrides the connection and declares that the sibling
2886
+ * exists, so it never falls back to main).
2887
+ * 2. Derived — take the base connection string and swap the database
2888
+ * name (after confirming the database exists on that server). The
2889
+ * base is `options.baseDb` (a Db handler), then
2890
+ * `options.baseConnectionString`, then `context.db`.
2891
+ *
2892
+ * Handlers are cached per name on the context (`context.siblingDbs`), so
2893
+ * any number of components asking for the same sibling share one pool —
2894
+ * including the "falls back to main" answer, which is remembered for the
2895
+ * lifetime of the process (a mid-run migration is picked up on restart).
2896
+ * Disconnect is registered via `context.registerCleanup`, same as the
2897
+ * main handler.
2898
+ *
2899
+ * @param {object} context - context with params/logger (and usually .db)
2900
+ * @param {string} [siblingName] - the sibling's database name (e.g. "src_bright")
2901
+ * @param {object} [options] - { baseDb, baseConnectionString, dbProfile }
2902
+ * @returns {Promise<Db>} connected handler (same proxy shape as Db.init)
2903
+ */
2904
+ static async initSibling(context, siblingName, options = {}) {
2905
+ if (!siblingName) {
2906
+ return resolveMainHandler(context, options);
2907
+ }
2908
+ if (!/^[a-zA-Z0-9_]+$/.test(siblingName)) {
2909
+ throw new ParamError(
2910
+ `Db.initSibling: invalid sibling database name "${siblingName}" (letters, digits and _ only)`
2911
+ );
2912
+ }
2913
+ if (!context.siblingDbs) {
2914
+ context.siblingDbs = /* @__PURE__ */ new Map();
2915
+ }
2916
+ const cached = context.siblingDbs.get(siblingName);
2917
+ if (cached) {
2918
+ return cached;
2919
+ }
2920
+ const overrideParam = `dbConnectionStringSib${camelizeDbName(siblingName)}`;
2921
+ let connectionString = await context?.params?.get?.(overrideParam, "string");
2922
+ if (connectionString) {
2923
+ context.logger?.debug?.(
2924
+ `[Db] sibling "${siblingName}": using override param "${overrideParam}"`
2925
+ );
2926
+ } else {
2927
+ const baseHandle = options.baseDb ?? context.db;
2928
+ const base = baseHandle?.config?.connectionString ?? options.baseConnectionString;
2929
+ if (!base) {
2930
+ throw new ParamError(
2931
+ `Db.initSibling: no base connection to derive "${siblingName}" from \u2014 init the main Db first (context.db = await Db.init(context)), or pass options.baseDb / options.baseConnectionString, or set the ${overrideParam} param (env ${toEnvKey(overrideParam)})`
2932
+ );
2933
+ }
2934
+ const exists = await databaseExistsOnServer(baseHandle, base, siblingName);
2935
+ if (!exists) {
2936
+ context.logger?.debug?.(
2937
+ `[Db] sibling "${siblingName}" does not exist \u2014 falling back to the main database`
2938
+ );
2939
+ const main = await resolveMainHandler(context, options);
2940
+ context.siblingDbs.set(siblingName, main);
2941
+ return main;
2942
+ }
2943
+ connectionString = replaceDatabaseName(base, siblingName);
2944
+ context.logger?.debug?.(
2945
+ `[Db] sibling "${siblingName}": derived from base (${formatConnectionEndpoint(base) ?? "?"})`
2946
+ );
2947
+ }
2948
+ const config2 = {
2949
+ ...KNEX_DEFAULTS,
2950
+ connectionString,
2951
+ name: siblingName,
2952
+ profile: !!options.dbProfile,
2953
+ logger: context.logger
2954
+ };
2955
+ const handler = await dbConnect(context, config2);
2956
+ context.siblingDbs.set(siblingName, handler);
2957
+ return handler;
2958
+ }
2959
+ /**
2960
+ * Discover the sibling databases that are "currently in use", by name.
2961
+ * Two sources, merged (env wins on duplicates):
2962
+ *
2963
+ * 1. ENV-DECLARED — every `DB_CONNECTION_STRING_SIB_<NAME>` env var
2964
+ * (the dedicated `SIB_` namespace) whose decoded name matches. This
2965
+ * covers siblings that moved to their own server: the same var that
2966
+ * overrides the connection also *registers* the database, so `.env`
2967
+ * stays the single convenient list.
2968
+ * 2. SAME-SERVER SCAN — `SELECT datname FROM pg_database` on the base
2969
+ * server (PostgreSQL only), filtered the same way.
2970
+ *
2971
+ * The caller says what "matches": `{ prefix: "src_" }` or
2972
+ * `{ match: /^src_/ }` — the toolkit does not guess a naming convention.
2973
+ *
2974
+ * @param {object} context - needs context.db (or options.baseDb) for the server scan
2975
+ * @param {{ prefix?: string, match?: RegExp, baseDb?: object, env?: object }} options
2976
+ * @returns {Promise<Array<{ name: string, origin: "env"|"server" }>>} sorted by name
2977
+ */
2978
+ static async discoverSiblings(context, options = {}) {
2979
+ const { prefix, match, env = process.env } = options;
2980
+ if (!prefix && !match) {
2981
+ throw new ParamError(`Db.discoverSiblings: pass { prefix: "..." } or { match: /.../ }`);
2982
+ }
2983
+ const matches = match instanceof RegExp ? (n) => match.test(n) : (n) => n.startsWith(prefix);
2984
+ const found = /* @__PURE__ */ new Map();
2985
+ for (const key of Object.keys(env)) {
2986
+ const m = /^DB_CONNECTION_STRING_SIB_(.+)$/.exec(key);
2987
+ if (!m || !env[key]) continue;
2988
+ const name = m[1].toLowerCase();
2989
+ if (matches(name)) {
2990
+ found.set(name, "env");
2991
+ }
2992
+ }
2993
+ const base = options.baseDb ?? context?.db;
2994
+ if (base) {
2995
+ const connectionString = String(base.config?.connectionString ?? "");
2996
+ if (connectionString.startsWith("postgresql")) {
2997
+ const { rows } = await base.raw(
2998
+ "SELECT datname FROM pg_database WHERE datistemplate = false"
2999
+ );
3000
+ for (const { datname } of rows) {
3001
+ if (matches(datname) && !found.has(datname)) {
3002
+ found.set(datname, "server");
3003
+ }
3004
+ }
3005
+ } else {
3006
+ context?.logger?.warn?.(
3007
+ "[Db] discoverSiblings: server scan supported for PostgreSQL only; using env-declared siblings"
3008
+ );
3009
+ }
3010
+ }
3011
+ return [...found].map(([name, origin]) => ({ name, origin })).sort((a, b) => a.name.localeCompare(b.name));
3012
+ }
3013
+ /**
3014
+ * Discover + connect: one handler per active sibling (cached, pooled —
3015
+ * see initSibling). Pass `includeMain: true` to get `[context.db, ...]`,
3016
+ * which is the usual shape for "apply this DDL everywhere" loops:
3017
+ *
3018
+ * const dbs = await Db.initAllSiblings(context, { prefix: "src_", includeMain: true });
3019
+ * await ensureSchemaEverywhere(dbs, spec, { logger: context.logger });
3020
+ *
3021
+ * @param {object} context
3022
+ * @param {{ prefix?: string, match?: RegExp, includeMain?: boolean, baseDb?: object, env?: object }} options
3023
+ * @returns {Promise<Function[]>} connected handlers
3024
+ */
3025
+ static async initAllSiblings(context, options = {}) {
3026
+ const discovered = await _Db.discoverSiblings(context, options);
3027
+ const handlers = [];
3028
+ for (const { name } of discovered) {
3029
+ handlers.push(await _Db.initSibling(context, name, options));
3030
+ }
3031
+ return options.includeMain && context.db ? [context.db, ...handlers] : handlers;
3032
+ }
2738
3033
  constructor(config2) {
2739
3034
  if (!config2 || !config2.connectionString) {
2740
3035
  throw new ParamError("Db: connectionString is required");
@@ -2995,6 +3290,54 @@ var Db = class {
2995
3290
  function capitalizeFirstLetter(str) {
2996
3291
  return str.charAt(0).toUpperCase() + str.slice(1);
2997
3292
  }
3293
+ async function resolveMainHandler(context, options = {}) {
3294
+ if (options.baseDb) {
3295
+ return options.baseDb;
3296
+ }
3297
+ if (!context.db) {
3298
+ context.db = await Db.init(context);
3299
+ }
3300
+ return context.db;
3301
+ }
3302
+ async function databaseExistsOnServer(baseHandle, baseConnectionString, databaseName) {
3303
+ if (!String(baseConnectionString).startsWith("postgresql")) {
3304
+ return true;
3305
+ }
3306
+ const query = "SELECT 1 FROM pg_database WHERE datname = ?";
3307
+ if (baseHandle) {
3308
+ const { rows } = await baseHandle.raw(query, [databaseName]);
3309
+ return rows.length > 0;
3310
+ }
3311
+ const shortLived = (0, import_knex.default)({
3312
+ client: "pg",
3313
+ connection: { connectionString: baseConnectionString },
3314
+ pool: { min: 0, max: 1 }
3315
+ });
3316
+ try {
3317
+ const { rows } = await shortLived.raw(query, [databaseName]);
3318
+ return rows.length > 0;
3319
+ } finally {
3320
+ await shortLived.destroy();
3321
+ }
3322
+ }
3323
+ function camelizeDbName(name) {
3324
+ return name.split(/[_-]+/).filter(Boolean).map(capitalizeFirstLetter).join("");
3325
+ }
3326
+ function toEnvKey(key) {
3327
+ return key.replace(/([A-Z])/g, "_$1").toUpperCase();
3328
+ }
3329
+ function replaceDatabaseName(connectionString, databaseName) {
3330
+ let url;
3331
+ try {
3332
+ url = new URL(connectionString);
3333
+ } catch {
3334
+ throw new ParamError(
3335
+ `Db: cannot parse connection string to derive a sibling database from it`
3336
+ );
3337
+ }
3338
+ url.pathname = `/${databaseName}`;
3339
+ return url.toString();
3340
+ }
2998
3341
  function resolveDbDisplayName(dbName, connectionParam, argsEnv, mergedName) {
2999
3342
  if (dbName) {
3000
3343
  return dbName;
@@ -3247,29 +3590,90 @@ function queueToTableNames(queueName) {
3247
3590
  registryTable: `${queueName}_services_registry`
3248
3591
  };
3249
3592
  }
3250
- function defineTasksTable(t, db, tableNameForIndex) {
3251
- t.uuid("id").primary().defaultTo(db.raw("uuid_generate_v4()"));
3252
- t.timestamp("created_at").notNullable().defaultTo(db.fn.now());
3253
- t.timestamp("started_at");
3254
- t.timestamp("completed_at");
3255
- t.integer("priority").notNullable().defaultTo(50);
3256
- t.text("schedule");
3257
- t.timestamp("next_run_at").defaultTo(null);
3258
- t.timestamp("past_due").defaultTo(null);
3259
- t.text("name").notNullable();
3260
- t.text("opid");
3261
- t.jsonb("params");
3262
- t.text("service_group");
3263
- t.integer("instance_number");
3264
- t.text("service_name");
3265
- t.text("server_name");
3266
- t.text("status").notNullable().defaultTo("idle");
3267
- t.timestamp("status_changed_at").defaultTo(null);
3268
- t.text("progress");
3269
- t.boolean("success");
3270
- t.jsonb("results");
3271
- t.index(["service_group", "status", "priority", "created_at"], `${tableNameForIndex}_claim_idx`);
3272
- t.index(["service_group", "name"], `${tableNameForIndex}_group_name_idx`);
3593
+ function tasksTableSpec(tableNameForIndex) {
3594
+ return {
3595
+ columns: {
3596
+ id: (t, db) => t.uuid("id").primary().defaultTo(db.raw("uuid_generate_v4()")),
3597
+ created_at: (t, db) => t.timestamp("created_at").notNullable().defaultTo(db.fn.now()),
3598
+ started_at: (t) => t.timestamp("started_at"),
3599
+ completed_at: (t) => t.timestamp("completed_at"),
3600
+ /*
3601
+ * Priority: lower number = claimed first (see claimNextRunnableTask: ORDER BY priority ASC).
3602
+ * Suggested range 0–100: 0 = most urgent, 100 = least; default 50 for normal work.
3603
+ */
3604
+ priority: (t) => t.integer("priority").notNullable().defaultTo(50),
3605
+ schedule: (t) => t.text("schedule"),
3606
+ next_run_at: (t) => t.timestamp("next_run_at").defaultTo(null),
3607
+ past_due: (t) => t.timestamp("past_due").defaultTo(null),
3608
+ name: (t) => t.text("name").notNullable(),
3609
+ opid: (t) => t.text("opid"),
3610
+ params: (t) => t.jsonb("params"),
3611
+ // those are target identifiers, kind of who is going to run a task.
3612
+ service_group: (t) => t.text("service_group"),
3613
+ // harvester, loader, photos, ...
3614
+ instance_number: (t) => t.integer("instance_number"),
3615
+ service_name: (t) => t.text("service_name"),
3616
+ // that's a "<server_name>_<service_group>_<instance_number>"
3617
+ server_name: (t) => t.text("server_name"),
3618
+ // filled by runner when registering, auto.
3619
+ status: (t) => t.text("status").notNullable().defaultTo("idle"),
3620
+ // idle, running, completed, failed, paused
3621
+ status_changed_at: (t) => t.timestamp("status_changed_at").defaultTo(null),
3622
+ progress: (t) => t.text("progress"),
3623
+ success: (t) => t.boolean("success"),
3624
+ results: (t) => t.jsonb("results")
3625
+ },
3626
+ indexes: [
3627
+ {
3628
+ columns: ["service_group", "status", "priority", "created_at"],
3629
+ name: `${tableNameForIndex}_claim_idx`
3630
+ },
3631
+ { columns: ["service_group", "name"], name: `${tableNameForIndex}_group_name_idx` }
3632
+ ]
3633
+ };
3634
+ }
3635
+ function registryTableSpec(registryTable) {
3636
+ return {
3637
+ columns: {
3638
+ id: (t, db) => t.uuid("id").primary().defaultTo(db.raw("uuid_generate_v4()")),
3639
+ queue_name: (t) => t.text("queue_name").notNullable(),
3640
+ service_group: (t) => t.text("service_group").notNullable(),
3641
+ // harvester, loader, photos, ...
3642
+ instance_number: (t) => t.integer("instance_number").notNullable().defaultTo(1),
3643
+ service_name: (t) => t.text("service_name").notNullable(),
3644
+ // that's a "<server_name>_<service_group>_<instance_number>"
3645
+ server_name: (t) => t.text("server_name").notNullable(),
3646
+ // filled by runner when registering, auto.
3647
+ pid: (t) => t.integer("pid"),
3648
+ metadata: (t) => t.json("metadata"),
3649
+ created_at: (t, db) => t.timestamp("created_at").notNullable().defaultTo(db.fn.now()),
3650
+ last_seen_at: (t, db) => t.timestamp("last_seen_at").notNullable().defaultTo(db.fn.now())
3651
+ },
3652
+ indexes: [
3653
+ {
3654
+ columns: ["queue_name", "service_name"],
3655
+ name: `${registryTable}_queue_name_service_name_uniq`,
3656
+ unique: true
3657
+ },
3658
+ {
3659
+ columns: ["queue_name", "service_group", "last_seen_at"],
3660
+ name: `${registryTable}_queue_group_seen_idx`
3661
+ },
3662
+ { columns: ["queue_name", "last_seen_at"], name: `${registryTable}_queue_seen_idx` }
3663
+ ]
3664
+ // TODO: a reference is needed - task_history entry should reference the registry entry, so that we can easily find all executed tasks for a given service and calculate the average workload or identify if there's a bottleneck. Also may be used for the load balancing.
3665
+ };
3666
+ }
3667
+ function tasksSchemaSpec(queueName = "tasks") {
3668
+ const { tasksTable, historyTable, registryTable } = queueToTableNames(queueName);
3669
+ return {
3670
+ extensions: ["uuid-ossp"],
3671
+ tables: {
3672
+ [tasksTable]: tasksTableSpec(tasksTable),
3673
+ [historyTable]: tasksTableSpec(historyTable),
3674
+ [registryTable]: registryTableSpec(registryTable)
3675
+ }
3676
+ };
3273
3677
  }
3274
3678
  function taskHistoryInsertFromQueueRow(row, overrides) {
3275
3679
  const { id, ...snapshot } = row;
@@ -3283,60 +3687,38 @@ async function ensureTaskTables(context, options = {}) {
3283
3687
  const queueName = options.queueName ?? "tasks";
3284
3688
  const recreate = options.recreate ?? false;
3285
3689
  const dryRun = options.dryRun ?? false;
3286
- const db = getDb(context);
3690
+ const databases = options.databases ?? [getDb(context)];
3287
3691
  const log = context.logger ?? console;
3288
3692
  const { tasksTable, historyTable, registryTable } = queueToTableNames(queueName);
3289
- const needsTasks = recreate ? true : !await db.tableExists(tasksTable);
3290
- const needsHistory = recreate ? true : !await db.tableExists(historyTable);
3291
- const needsRegistry = recreate ? true : !await db.tableExists(registryTable);
3292
- if (dryRun) {
3293
- const plan = [];
3693
+ const spec = tasksSchemaSpec(queueName);
3694
+ for (const db of databases) {
3695
+ const label = db?.config?.name ?? "db";
3294
3696
  if (recreate) {
3295
- plan.push(`DROP TABLE IF EXISTS ${historyTable}, ${tasksTable}, ${registryTable}`);
3697
+ if (dryRun) {
3698
+ log.info?.(
3699
+ `[tasks-schema] dryRun \u2014 ${label}: DROP TABLE IF EXISTS ${historyTable}, ${tasksTable}, ${registryTable}`
3700
+ );
3701
+ } else {
3702
+ await db.schema.dropTableIfExists(historyTable);
3703
+ await db.schema.dropTableIfExists(tasksTable);
3704
+ await db.schema.dropTableIfExists(registryTable);
3705
+ }
3296
3706
  }
3297
- if (needsTasks) plan.push(`CREATE TABLE ${tasksTable} (tasks queue)`);
3298
- if (needsHistory) plan.push(`CREATE TABLE ${historyTable} (history mirror)`);
3299
- if (needsRegistry) plan.push(`CREATE TABLE ${registryTable} (services registry)`);
3300
- if (plan.length === 0) {
3301
- log.info?.(`[tasks-schema] dryRun \u2014 queue "${queueName}" already up to date; no DDL`);
3302
- } else {
3303
- log.info?.(`[tasks-schema] dryRun \u2014 would run ${plan.length} statement(s) for queue "${queueName}":`);
3304
- for (const s of plan) log.info?.(` - ${s}`);
3707
+ const { actions } = await ensureSchema(db, spec, { dryRun, logger: context.logger });
3708
+ if (dryRun) {
3709
+ if (actions.length === 0) {
3710
+ log.info?.(`[tasks-schema] dryRun \u2014 ${label}: queue "${queueName}" already up to date; no DDL`);
3711
+ } else {
3712
+ log.info?.(
3713
+ `[tasks-schema] dryRun \u2014 ${label}: would run ${actions.length} statement(s) for queue "${queueName}":`
3714
+ );
3715
+ for (const s of actions) log.info?.(` - ${s}`);
3716
+ }
3717
+ } else if (actions.length > 0) {
3718
+ log.info?.(
3719
+ `[tasks-schema] ${label}: applied ${actions.length} DDL statement(s) for queue "${queueName}"`
3720
+ );
3305
3721
  }
3306
- return;
3307
- }
3308
- if (recreate) {
3309
- await db.schema.dropTableIfExists(historyTable);
3310
- await db.schema.dropTableIfExists(tasksTable);
3311
- await db.schema.dropTableIfExists(registryTable);
3312
- }
3313
- if (needsTasks) {
3314
- await db.raw(`CREATE EXTENSION IF NOT EXISTS "uuid-ossp"`);
3315
- await db.schema.createTable(tasksTable, (t) => {
3316
- defineTasksTable(t, db, tasksTable);
3317
- });
3318
- }
3319
- if (needsHistory) {
3320
- await db.schema.createTable(historyTable, (t) => {
3321
- defineTasksTable(t, db, historyTable);
3322
- });
3323
- }
3324
- if (needsRegistry) {
3325
- await db.schema.createTable(registryTable, (t) => {
3326
- t.uuid("id").primary().defaultTo(db.raw("uuid_generate_v4()"));
3327
- t.text("queue_name").notNullable();
3328
- t.text("service_group").notNullable();
3329
- t.integer("instance_number").notNullable().defaultTo(1);
3330
- t.text("service_name").notNullable();
3331
- t.text("server_name").notNullable();
3332
- t.integer("pid");
3333
- t.json("metadata");
3334
- t.timestamp("created_at").notNullable().defaultTo(db.fn.now());
3335
- t.timestamp("last_seen_at").notNullable().defaultTo(db.fn.now());
3336
- t.unique(["queue_name", "service_name"], `${registryTable}_queue_name_service_name_uniq`);
3337
- t.index(["queue_name", "service_group", "last_seen_at"], `${registryTable}_queue_group_seen_idx`);
3338
- t.index(["queue_name", "last_seen_at"], `${registryTable}_queue_seen_idx`);
3339
- });
3340
3722
  }
3341
3723
  }
3342
3724
  async function updateTaskProgress(context, tasksTable, taskId, progress) {