@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.
- package/dist/cli-runner.cjs +455 -73
- package/dist/cli-runner.cjs.map +1 -1
- package/dist/cli-runner.js +455 -73
- package/dist/cli-runner.js.map +1 -1
- package/dist/db.cjs +332 -3
- package/dist/db.cjs.map +1 -1
- package/dist/db.js +325 -2
- package/dist/db.js.map +1 -1
- package/dist/index.cjs +480 -73
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +474 -73
- package/dist/index.js.map +1 -1
- package/dist/init.cjs +37 -0
- package/dist/init.cjs.map +1 -1
- package/dist/init.js +37 -0
- package/dist/init.js.map +1 -1
- package/dist/params.cjs +37 -0
- package/dist/params.cjs.map +1 -1
- package/dist/params.js +37 -0
- package/dist/params.js.map +1 -1
- package/dist/tasks.cjs +196 -72
- package/dist/tasks.cjs.map +1 -1
- package/dist/tasks.js +196 -72
- package/dist/tasks.js.map +1 -1
- package/package.json +1 -1
package/dist/cli-runner.js
CHANGED
|
@@ -1852,6 +1852,43 @@ var Params = class _Params {
|
|
|
1852
1852
|
module: moduleName ?? this._currentModule
|
|
1853
1853
|
});
|
|
1854
1854
|
}
|
|
1855
|
+
/**
|
|
1856
|
+
* Report a param value that a component RESOLVED ON ITS OWN — outside
|
|
1857
|
+
* Params.get() — e.g. discovered by combining its config files (the way
|
|
1858
|
+
* blueprints merge defaults/aggregator/feed data). Without this, every
|
|
1859
|
+
* key such a component probed for an override shows up in the
|
|
1860
|
+
* --showUsedParams dump as "undefined (default)"; reporting upgrades the
|
|
1861
|
+
* entry to the value the component actually works with.
|
|
1862
|
+
*
|
|
1863
|
+
* Attribution rules:
|
|
1864
|
+
* - entries figured from an explicit input (cli/env/options/…) are left
|
|
1865
|
+
* untouched — the component merely confirmed them, the origin stands;
|
|
1866
|
+
* - entries whose source is "default" (Params had nothing) are upgraded
|
|
1867
|
+
* in place to the reported value and source;
|
|
1868
|
+
* - keys never seen by Params are appended as new entries.
|
|
1869
|
+
* First report wins: once upgraded, later reports for the same key/module
|
|
1870
|
+
* are ignored (the source is no longer "default").
|
|
1871
|
+
*
|
|
1872
|
+
* @param {string} key
|
|
1873
|
+
* @param {*} value - the value the component actually uses
|
|
1874
|
+
* @param {string} [source="discovered"] - short origin label, e.g. "blueprint"
|
|
1875
|
+
* @param {string} [moduleName] - dump section; defaults to the current module
|
|
1876
|
+
*/
|
|
1877
|
+
reportResolved(key, value, source = "discovered", moduleName) {
|
|
1878
|
+
const mod = moduleName ?? this._currentModule;
|
|
1879
|
+
const mine = this.trackedParams.filter((e) => e.key === key && e.module === mod);
|
|
1880
|
+
if (mine.some((e) => e.source !== "default")) {
|
|
1881
|
+
return;
|
|
1882
|
+
}
|
|
1883
|
+
if (mine.length === 0) {
|
|
1884
|
+
this.trackParam(key, "reported", value, source, mod);
|
|
1885
|
+
return;
|
|
1886
|
+
}
|
|
1887
|
+
for (const entry of mine) {
|
|
1888
|
+
entry.value = value;
|
|
1889
|
+
entry.source = source;
|
|
1890
|
+
}
|
|
1891
|
+
}
|
|
1855
1892
|
/**
|
|
1856
1893
|
* Get all tracked parameters (for --stopAfter=init)
|
|
1857
1894
|
*/
|
|
@@ -2644,13 +2681,100 @@ async function init(flow2, opts = {}) {
|
|
|
2644
2681
|
|
|
2645
2682
|
// src/db/index.js
|
|
2646
2683
|
import knex from "knex";
|
|
2684
|
+
|
|
2685
|
+
// src/db/ensure.js
|
|
2686
|
+
var dbLabel = (db) => db?.config?.name ?? "db";
|
|
2687
|
+
async function ensureExtension(db, name, options = {}) {
|
|
2688
|
+
const action = `CREATE EXTENSION IF NOT EXISTS "${name}"`;
|
|
2689
|
+
if (!options.dryRun) {
|
|
2690
|
+
await db.raw(action);
|
|
2691
|
+
}
|
|
2692
|
+
options.logger?.silly?.(`[ensure] ${dbLabel(db)}: ${action}${options.dryRun ? " (dryRun)" : ""}`);
|
|
2693
|
+
return { action };
|
|
2694
|
+
}
|
|
2695
|
+
async function ensureTable(db, tableName, spec, options = {}) {
|
|
2696
|
+
const { dryRun = false, logger } = options;
|
|
2697
|
+
const actions = [];
|
|
2698
|
+
const exists = await db.tableExists(tableName);
|
|
2699
|
+
if (!exists) {
|
|
2700
|
+
actions.push(`CREATE TABLE ${tableName} (${Object.keys(spec.columns).length} columns)`);
|
|
2701
|
+
if (!dryRun) {
|
|
2702
|
+
await db.schema.createTable(tableName, (t) => {
|
|
2703
|
+
for (const define of Object.values(spec.columns)) {
|
|
2704
|
+
define(t, db);
|
|
2705
|
+
}
|
|
2706
|
+
});
|
|
2707
|
+
}
|
|
2708
|
+
} else {
|
|
2709
|
+
const missing = [];
|
|
2710
|
+
for (const column of Object.keys(spec.columns)) {
|
|
2711
|
+
if (!await db.schema.hasColumn(tableName, column)) {
|
|
2712
|
+
missing.push(column);
|
|
2713
|
+
}
|
|
2714
|
+
}
|
|
2715
|
+
if (missing.length > 0) {
|
|
2716
|
+
actions.push(`ALTER TABLE ${tableName} ADD COLUMN ${missing.join(", ")}`);
|
|
2717
|
+
if (!dryRun) {
|
|
2718
|
+
await db.schema.alterTable(tableName, (t) => {
|
|
2719
|
+
for (const column of missing) {
|
|
2720
|
+
spec.columns[column](t, db);
|
|
2721
|
+
}
|
|
2722
|
+
});
|
|
2723
|
+
}
|
|
2724
|
+
}
|
|
2725
|
+
}
|
|
2726
|
+
for (const index of spec.indexes ?? []) {
|
|
2727
|
+
const indexActions = await ensureIndex(db, tableName, index, options);
|
|
2728
|
+
actions.push(...indexActions);
|
|
2729
|
+
}
|
|
2730
|
+
for (const action of actions) {
|
|
2731
|
+
logger?.silly?.(`[ensure] ${dbLabel(db)}: ${action}${dryRun ? " (dryRun)" : ""}`);
|
|
2732
|
+
}
|
|
2733
|
+
return actions;
|
|
2734
|
+
}
|
|
2735
|
+
async function ensureIndex(db, tableName, index, options = {}) {
|
|
2736
|
+
const { dryRun = false } = options;
|
|
2737
|
+
const kind = index.unique ? "UNIQUE INDEX" : "INDEX";
|
|
2738
|
+
const cols = index.columns.map((c) => `"${c}"`).join(", ");
|
|
2739
|
+
const isPg = String(db?.config?.connectionString ?? "").startsWith("postgresql");
|
|
2740
|
+
if (isPg) {
|
|
2741
|
+
const sql2 = `CREATE ${kind} IF NOT EXISTS "${index.name}" ON "${tableName}" (${cols})`;
|
|
2742
|
+
const { rows } = await db.raw(`SELECT 1 FROM pg_indexes WHERE indexname = ?`, [index.name]);
|
|
2743
|
+
if (rows.length > 0) return [];
|
|
2744
|
+
if (!dryRun) await db.raw(sql2);
|
|
2745
|
+
return [sql2];
|
|
2746
|
+
}
|
|
2747
|
+
const sql = `CREATE ${kind} ${index.name} ON ${tableName} (${cols})`;
|
|
2748
|
+
if (!dryRun) {
|
|
2749
|
+
try {
|
|
2750
|
+
await db.raw(sql);
|
|
2751
|
+
} catch (error) {
|
|
2752
|
+
if (!/already exists|duplicate/i.test(error?.message ?? "")) throw error;
|
|
2753
|
+
return [];
|
|
2754
|
+
}
|
|
2755
|
+
}
|
|
2756
|
+
return [sql];
|
|
2757
|
+
}
|
|
2758
|
+
async function ensureSchema(db, spec, options = {}) {
|
|
2759
|
+
const actions = [];
|
|
2760
|
+
for (const extension of spec.extensions ?? []) {
|
|
2761
|
+
const { action } = await ensureExtension(db, extension, options);
|
|
2762
|
+
if (options.dryRun) actions.push(action);
|
|
2763
|
+
}
|
|
2764
|
+
for (const [tableName, tableSpec] of Object.entries(spec.tables ?? {})) {
|
|
2765
|
+
actions.push(...await ensureTable(db, tableName, tableSpec, options));
|
|
2766
|
+
}
|
|
2767
|
+
return { database: dbLabel(db), actions };
|
|
2768
|
+
}
|
|
2769
|
+
|
|
2770
|
+
// src/db/index.js
|
|
2647
2771
|
var KNEX_DEFAULTS = {
|
|
2648
2772
|
testConnection: true,
|
|
2649
2773
|
pool: { min: 2, max: 10 },
|
|
2650
2774
|
acquireConnectionTimeout: 1e4,
|
|
2651
2775
|
ssl: { rejectUnauthorized: false }
|
|
2652
2776
|
};
|
|
2653
|
-
var Db = class {
|
|
2777
|
+
var Db = class _Db {
|
|
2654
2778
|
static async init(context, options = {}) {
|
|
2655
2779
|
const buildConfig = async () => {
|
|
2656
2780
|
const defs2 = {
|
|
@@ -2719,6 +2843,177 @@ var Db = class {
|
|
|
2719
2843
|
const config2 = context?.params?.runWithModuleAsync ? await context.params.runWithModuleAsync("db", buildConfig) : await buildConfig();
|
|
2720
2844
|
return dbConnect(context, config2);
|
|
2721
2845
|
}
|
|
2846
|
+
/**
|
|
2847
|
+
* Initialize a SIBLING database handler: a database that lives on the same
|
|
2848
|
+
* server with the same credentials/options as an existing ("base") one, and
|
|
2849
|
+
* differs only by its database name. Typical use: a per-tenant / per-subject
|
|
2850
|
+
* database alongside a main database that keeps the shared tables.
|
|
2851
|
+
*
|
|
2852
|
+
* context.db = await Db.init(context); // main
|
|
2853
|
+
* const sub = await Db.initSibling(context, "src_bright"); // sibling
|
|
2854
|
+
*
|
|
2855
|
+
* LOCATION-AGNOSTIC BY DESIGN — the call gracefully falls back to the main
|
|
2856
|
+
* database, so callers can use it for all subject data without knowing what
|
|
2857
|
+
* has been migrated where:
|
|
2858
|
+
* - empty `siblingName` → the main handler (same as Db.init)
|
|
2859
|
+
* - sibling DB does not exist yet → the main handler (data not migrated;
|
|
2860
|
+
* it still lives in the main database)
|
|
2861
|
+
* Callers that must not fall back can check `handler === context.db`.
|
|
2862
|
+
*
|
|
2863
|
+
* Connection string resolution for an actual sibling, in order:
|
|
2864
|
+
* 1. Explicit override — param `dbConnectionStringSib<SiblingName>` (env
|
|
2865
|
+
* `DB_CONNECTION_STRING_SIB_<SIBLING_NAME>`, e.g. `src_bright` →
|
|
2866
|
+
* `DB_CONNECTION_STRING_SIB_SRC_BRIGHT`). Nobody needs this on day
|
|
2867
|
+
* one; it is the escape hatch for when a sibling later moves to its
|
|
2868
|
+
* own server — one env var, no code changes (the `SIB_` namespace
|
|
2869
|
+
* both overrides the connection and declares that the sibling
|
|
2870
|
+
* exists, so it never falls back to main).
|
|
2871
|
+
* 2. Derived — take the base connection string and swap the database
|
|
2872
|
+
* name (after confirming the database exists on that server). The
|
|
2873
|
+
* base is `options.baseDb` (a Db handler), then
|
|
2874
|
+
* `options.baseConnectionString`, then `context.db`.
|
|
2875
|
+
*
|
|
2876
|
+
* Handlers are cached per name on the context (`context.siblingDbs`), so
|
|
2877
|
+
* any number of components asking for the same sibling share one pool —
|
|
2878
|
+
* including the "falls back to main" answer, which is remembered for the
|
|
2879
|
+
* lifetime of the process (a mid-run migration is picked up on restart).
|
|
2880
|
+
* Disconnect is registered via `context.registerCleanup`, same as the
|
|
2881
|
+
* main handler.
|
|
2882
|
+
*
|
|
2883
|
+
* @param {object} context - context with params/logger (and usually .db)
|
|
2884
|
+
* @param {string} [siblingName] - the sibling's database name (e.g. "src_bright")
|
|
2885
|
+
* @param {object} [options] - { baseDb, baseConnectionString, dbProfile }
|
|
2886
|
+
* @returns {Promise<Db>} connected handler (same proxy shape as Db.init)
|
|
2887
|
+
*/
|
|
2888
|
+
static async initSibling(context, siblingName, options = {}) {
|
|
2889
|
+
if (!siblingName) {
|
|
2890
|
+
return resolveMainHandler(context, options);
|
|
2891
|
+
}
|
|
2892
|
+
if (!/^[a-zA-Z0-9_]+$/.test(siblingName)) {
|
|
2893
|
+
throw new ParamError(
|
|
2894
|
+
`Db.initSibling: invalid sibling database name "${siblingName}" (letters, digits and _ only)`
|
|
2895
|
+
);
|
|
2896
|
+
}
|
|
2897
|
+
if (!context.siblingDbs) {
|
|
2898
|
+
context.siblingDbs = /* @__PURE__ */ new Map();
|
|
2899
|
+
}
|
|
2900
|
+
const cached = context.siblingDbs.get(siblingName);
|
|
2901
|
+
if (cached) {
|
|
2902
|
+
return cached;
|
|
2903
|
+
}
|
|
2904
|
+
const overrideParam = `dbConnectionStringSib${camelizeDbName(siblingName)}`;
|
|
2905
|
+
let connectionString = await context?.params?.get?.(overrideParam, "string");
|
|
2906
|
+
if (connectionString) {
|
|
2907
|
+
context.logger?.debug?.(
|
|
2908
|
+
`[Db] sibling "${siblingName}": using override param "${overrideParam}"`
|
|
2909
|
+
);
|
|
2910
|
+
} else {
|
|
2911
|
+
const baseHandle = options.baseDb ?? context.db;
|
|
2912
|
+
const base = baseHandle?.config?.connectionString ?? options.baseConnectionString;
|
|
2913
|
+
if (!base) {
|
|
2914
|
+
throw new ParamError(
|
|
2915
|
+
`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)})`
|
|
2916
|
+
);
|
|
2917
|
+
}
|
|
2918
|
+
const exists = await databaseExistsOnServer(baseHandle, base, siblingName);
|
|
2919
|
+
if (!exists) {
|
|
2920
|
+
context.logger?.debug?.(
|
|
2921
|
+
`[Db] sibling "${siblingName}" does not exist \u2014 falling back to the main database`
|
|
2922
|
+
);
|
|
2923
|
+
const main = await resolveMainHandler(context, options);
|
|
2924
|
+
context.siblingDbs.set(siblingName, main);
|
|
2925
|
+
return main;
|
|
2926
|
+
}
|
|
2927
|
+
connectionString = replaceDatabaseName(base, siblingName);
|
|
2928
|
+
context.logger?.debug?.(
|
|
2929
|
+
`[Db] sibling "${siblingName}": derived from base (${formatConnectionEndpoint(base) ?? "?"})`
|
|
2930
|
+
);
|
|
2931
|
+
}
|
|
2932
|
+
const config2 = {
|
|
2933
|
+
...KNEX_DEFAULTS,
|
|
2934
|
+
connectionString,
|
|
2935
|
+
name: siblingName,
|
|
2936
|
+
profile: !!options.dbProfile,
|
|
2937
|
+
logger: context.logger
|
|
2938
|
+
};
|
|
2939
|
+
const handler = await dbConnect(context, config2);
|
|
2940
|
+
context.siblingDbs.set(siblingName, handler);
|
|
2941
|
+
return handler;
|
|
2942
|
+
}
|
|
2943
|
+
/**
|
|
2944
|
+
* Discover the sibling databases that are "currently in use", by name.
|
|
2945
|
+
* Two sources, merged (env wins on duplicates):
|
|
2946
|
+
*
|
|
2947
|
+
* 1. ENV-DECLARED — every `DB_CONNECTION_STRING_SIB_<NAME>` env var
|
|
2948
|
+
* (the dedicated `SIB_` namespace) whose decoded name matches. This
|
|
2949
|
+
* covers siblings that moved to their own server: the same var that
|
|
2950
|
+
* overrides the connection also *registers* the database, so `.env`
|
|
2951
|
+
* stays the single convenient list.
|
|
2952
|
+
* 2. SAME-SERVER SCAN — `SELECT datname FROM pg_database` on the base
|
|
2953
|
+
* server (PostgreSQL only), filtered the same way.
|
|
2954
|
+
*
|
|
2955
|
+
* The caller says what "matches": `{ prefix: "src_" }` or
|
|
2956
|
+
* `{ match: /^src_/ }` — the toolkit does not guess a naming convention.
|
|
2957
|
+
*
|
|
2958
|
+
* @param {object} context - needs context.db (or options.baseDb) for the server scan
|
|
2959
|
+
* @param {{ prefix?: string, match?: RegExp, baseDb?: object, env?: object }} options
|
|
2960
|
+
* @returns {Promise<Array<{ name: string, origin: "env"|"server" }>>} sorted by name
|
|
2961
|
+
*/
|
|
2962
|
+
static async discoverSiblings(context, options = {}) {
|
|
2963
|
+
const { prefix, match, env = process.env } = options;
|
|
2964
|
+
if (!prefix && !match) {
|
|
2965
|
+
throw new ParamError(`Db.discoverSiblings: pass { prefix: "..." } or { match: /.../ }`);
|
|
2966
|
+
}
|
|
2967
|
+
const matches = match instanceof RegExp ? (n) => match.test(n) : (n) => n.startsWith(prefix);
|
|
2968
|
+
const found = /* @__PURE__ */ new Map();
|
|
2969
|
+
for (const key of Object.keys(env)) {
|
|
2970
|
+
const m = /^DB_CONNECTION_STRING_SIB_(.+)$/.exec(key);
|
|
2971
|
+
if (!m || !env[key]) continue;
|
|
2972
|
+
const name = m[1].toLowerCase();
|
|
2973
|
+
if (matches(name)) {
|
|
2974
|
+
found.set(name, "env");
|
|
2975
|
+
}
|
|
2976
|
+
}
|
|
2977
|
+
const base = options.baseDb ?? context?.db;
|
|
2978
|
+
if (base) {
|
|
2979
|
+
const connectionString = String(base.config?.connectionString ?? "");
|
|
2980
|
+
if (connectionString.startsWith("postgresql")) {
|
|
2981
|
+
const { rows } = await base.raw(
|
|
2982
|
+
"SELECT datname FROM pg_database WHERE datistemplate = false"
|
|
2983
|
+
);
|
|
2984
|
+
for (const { datname } of rows) {
|
|
2985
|
+
if (matches(datname) && !found.has(datname)) {
|
|
2986
|
+
found.set(datname, "server");
|
|
2987
|
+
}
|
|
2988
|
+
}
|
|
2989
|
+
} else {
|
|
2990
|
+
context?.logger?.warn?.(
|
|
2991
|
+
"[Db] discoverSiblings: server scan supported for PostgreSQL only; using env-declared siblings"
|
|
2992
|
+
);
|
|
2993
|
+
}
|
|
2994
|
+
}
|
|
2995
|
+
return [...found].map(([name, origin]) => ({ name, origin })).sort((a, b) => a.name.localeCompare(b.name));
|
|
2996
|
+
}
|
|
2997
|
+
/**
|
|
2998
|
+
* Discover + connect: one handler per active sibling (cached, pooled —
|
|
2999
|
+
* see initSibling). Pass `includeMain: true` to get `[context.db, ...]`,
|
|
3000
|
+
* which is the usual shape for "apply this DDL everywhere" loops:
|
|
3001
|
+
*
|
|
3002
|
+
* const dbs = await Db.initAllSiblings(context, { prefix: "src_", includeMain: true });
|
|
3003
|
+
* await ensureSchemaEverywhere(dbs, spec, { logger: context.logger });
|
|
3004
|
+
*
|
|
3005
|
+
* @param {object} context
|
|
3006
|
+
* @param {{ prefix?: string, match?: RegExp, includeMain?: boolean, baseDb?: object, env?: object }} options
|
|
3007
|
+
* @returns {Promise<Function[]>} connected handlers
|
|
3008
|
+
*/
|
|
3009
|
+
static async initAllSiblings(context, options = {}) {
|
|
3010
|
+
const discovered = await _Db.discoverSiblings(context, options);
|
|
3011
|
+
const handlers = [];
|
|
3012
|
+
for (const { name } of discovered) {
|
|
3013
|
+
handlers.push(await _Db.initSibling(context, name, options));
|
|
3014
|
+
}
|
|
3015
|
+
return options.includeMain && context.db ? [context.db, ...handlers] : handlers;
|
|
3016
|
+
}
|
|
2722
3017
|
constructor(config2) {
|
|
2723
3018
|
if (!config2 || !config2.connectionString) {
|
|
2724
3019
|
throw new ParamError("Db: connectionString is required");
|
|
@@ -2979,6 +3274,54 @@ var Db = class {
|
|
|
2979
3274
|
function capitalizeFirstLetter(str) {
|
|
2980
3275
|
return str.charAt(0).toUpperCase() + str.slice(1);
|
|
2981
3276
|
}
|
|
3277
|
+
async function resolveMainHandler(context, options = {}) {
|
|
3278
|
+
if (options.baseDb) {
|
|
3279
|
+
return options.baseDb;
|
|
3280
|
+
}
|
|
3281
|
+
if (!context.db) {
|
|
3282
|
+
context.db = await Db.init(context);
|
|
3283
|
+
}
|
|
3284
|
+
return context.db;
|
|
3285
|
+
}
|
|
3286
|
+
async function databaseExistsOnServer(baseHandle, baseConnectionString, databaseName) {
|
|
3287
|
+
if (!String(baseConnectionString).startsWith("postgresql")) {
|
|
3288
|
+
return true;
|
|
3289
|
+
}
|
|
3290
|
+
const query = "SELECT 1 FROM pg_database WHERE datname = ?";
|
|
3291
|
+
if (baseHandle) {
|
|
3292
|
+
const { rows } = await baseHandle.raw(query, [databaseName]);
|
|
3293
|
+
return rows.length > 0;
|
|
3294
|
+
}
|
|
3295
|
+
const shortLived = knex({
|
|
3296
|
+
client: "pg",
|
|
3297
|
+
connection: { connectionString: baseConnectionString },
|
|
3298
|
+
pool: { min: 0, max: 1 }
|
|
3299
|
+
});
|
|
3300
|
+
try {
|
|
3301
|
+
const { rows } = await shortLived.raw(query, [databaseName]);
|
|
3302
|
+
return rows.length > 0;
|
|
3303
|
+
} finally {
|
|
3304
|
+
await shortLived.destroy();
|
|
3305
|
+
}
|
|
3306
|
+
}
|
|
3307
|
+
function camelizeDbName(name) {
|
|
3308
|
+
return name.split(/[_-]+/).filter(Boolean).map(capitalizeFirstLetter).join("");
|
|
3309
|
+
}
|
|
3310
|
+
function toEnvKey(key) {
|
|
3311
|
+
return key.replace(/([A-Z])/g, "_$1").toUpperCase();
|
|
3312
|
+
}
|
|
3313
|
+
function replaceDatabaseName(connectionString, databaseName) {
|
|
3314
|
+
let url;
|
|
3315
|
+
try {
|
|
3316
|
+
url = new URL(connectionString);
|
|
3317
|
+
} catch {
|
|
3318
|
+
throw new ParamError(
|
|
3319
|
+
`Db: cannot parse connection string to derive a sibling database from it`
|
|
3320
|
+
);
|
|
3321
|
+
}
|
|
3322
|
+
url.pathname = `/${databaseName}`;
|
|
3323
|
+
return url.toString();
|
|
3324
|
+
}
|
|
2982
3325
|
function resolveDbDisplayName(dbName, connectionParam, argsEnv, mergedName) {
|
|
2983
3326
|
if (dbName) {
|
|
2984
3327
|
return dbName;
|
|
@@ -3231,29 +3574,90 @@ function queueToTableNames(queueName) {
|
|
|
3231
3574
|
registryTable: `${queueName}_services_registry`
|
|
3232
3575
|
};
|
|
3233
3576
|
}
|
|
3234
|
-
function
|
|
3235
|
-
|
|
3236
|
-
|
|
3237
|
-
|
|
3238
|
-
|
|
3239
|
-
|
|
3240
|
-
|
|
3241
|
-
|
|
3242
|
-
|
|
3243
|
-
|
|
3244
|
-
|
|
3245
|
-
|
|
3246
|
-
|
|
3247
|
-
|
|
3248
|
-
|
|
3249
|
-
|
|
3250
|
-
|
|
3251
|
-
|
|
3252
|
-
|
|
3253
|
-
|
|
3254
|
-
|
|
3255
|
-
|
|
3256
|
-
|
|
3577
|
+
function tasksTableSpec(tableNameForIndex) {
|
|
3578
|
+
return {
|
|
3579
|
+
columns: {
|
|
3580
|
+
id: (t, db) => t.uuid("id").primary().defaultTo(db.raw("uuid_generate_v4()")),
|
|
3581
|
+
created_at: (t, db) => t.timestamp("created_at").notNullable().defaultTo(db.fn.now()),
|
|
3582
|
+
started_at: (t) => t.timestamp("started_at"),
|
|
3583
|
+
completed_at: (t) => t.timestamp("completed_at"),
|
|
3584
|
+
/*
|
|
3585
|
+
* Priority: lower number = claimed first (see claimNextRunnableTask: ORDER BY priority ASC).
|
|
3586
|
+
* Suggested range 0–100: 0 = most urgent, 100 = least; default 50 for normal work.
|
|
3587
|
+
*/
|
|
3588
|
+
priority: (t) => t.integer("priority").notNullable().defaultTo(50),
|
|
3589
|
+
schedule: (t) => t.text("schedule"),
|
|
3590
|
+
next_run_at: (t) => t.timestamp("next_run_at").defaultTo(null),
|
|
3591
|
+
past_due: (t) => t.timestamp("past_due").defaultTo(null),
|
|
3592
|
+
name: (t) => t.text("name").notNullable(),
|
|
3593
|
+
opid: (t) => t.text("opid"),
|
|
3594
|
+
params: (t) => t.jsonb("params"),
|
|
3595
|
+
// those are target identifiers, kind of who is going to run a task.
|
|
3596
|
+
service_group: (t) => t.text("service_group"),
|
|
3597
|
+
// harvester, loader, photos, ...
|
|
3598
|
+
instance_number: (t) => t.integer("instance_number"),
|
|
3599
|
+
service_name: (t) => t.text("service_name"),
|
|
3600
|
+
// that's a "<server_name>_<service_group>_<instance_number>"
|
|
3601
|
+
server_name: (t) => t.text("server_name"),
|
|
3602
|
+
// filled by runner when registering, auto.
|
|
3603
|
+
status: (t) => t.text("status").notNullable().defaultTo("idle"),
|
|
3604
|
+
// idle, running, completed, failed, paused
|
|
3605
|
+
status_changed_at: (t) => t.timestamp("status_changed_at").defaultTo(null),
|
|
3606
|
+
progress: (t) => t.text("progress"),
|
|
3607
|
+
success: (t) => t.boolean("success"),
|
|
3608
|
+
results: (t) => t.jsonb("results")
|
|
3609
|
+
},
|
|
3610
|
+
indexes: [
|
|
3611
|
+
{
|
|
3612
|
+
columns: ["service_group", "status", "priority", "created_at"],
|
|
3613
|
+
name: `${tableNameForIndex}_claim_idx`
|
|
3614
|
+
},
|
|
3615
|
+
{ columns: ["service_group", "name"], name: `${tableNameForIndex}_group_name_idx` }
|
|
3616
|
+
]
|
|
3617
|
+
};
|
|
3618
|
+
}
|
|
3619
|
+
function registryTableSpec(registryTable) {
|
|
3620
|
+
return {
|
|
3621
|
+
columns: {
|
|
3622
|
+
id: (t, db) => t.uuid("id").primary().defaultTo(db.raw("uuid_generate_v4()")),
|
|
3623
|
+
queue_name: (t) => t.text("queue_name").notNullable(),
|
|
3624
|
+
service_group: (t) => t.text("service_group").notNullable(),
|
|
3625
|
+
// harvester, loader, photos, ...
|
|
3626
|
+
instance_number: (t) => t.integer("instance_number").notNullable().defaultTo(1),
|
|
3627
|
+
service_name: (t) => t.text("service_name").notNullable(),
|
|
3628
|
+
// that's a "<server_name>_<service_group>_<instance_number>"
|
|
3629
|
+
server_name: (t) => t.text("server_name").notNullable(),
|
|
3630
|
+
// filled by runner when registering, auto.
|
|
3631
|
+
pid: (t) => t.integer("pid"),
|
|
3632
|
+
metadata: (t) => t.json("metadata"),
|
|
3633
|
+
created_at: (t, db) => t.timestamp("created_at").notNullable().defaultTo(db.fn.now()),
|
|
3634
|
+
last_seen_at: (t, db) => t.timestamp("last_seen_at").notNullable().defaultTo(db.fn.now())
|
|
3635
|
+
},
|
|
3636
|
+
indexes: [
|
|
3637
|
+
{
|
|
3638
|
+
columns: ["queue_name", "service_name"],
|
|
3639
|
+
name: `${registryTable}_queue_name_service_name_uniq`,
|
|
3640
|
+
unique: true
|
|
3641
|
+
},
|
|
3642
|
+
{
|
|
3643
|
+
columns: ["queue_name", "service_group", "last_seen_at"],
|
|
3644
|
+
name: `${registryTable}_queue_group_seen_idx`
|
|
3645
|
+
},
|
|
3646
|
+
{ columns: ["queue_name", "last_seen_at"], name: `${registryTable}_queue_seen_idx` }
|
|
3647
|
+
]
|
|
3648
|
+
// 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.
|
|
3649
|
+
};
|
|
3650
|
+
}
|
|
3651
|
+
function tasksSchemaSpec(queueName = "tasks") {
|
|
3652
|
+
const { tasksTable, historyTable, registryTable } = queueToTableNames(queueName);
|
|
3653
|
+
return {
|
|
3654
|
+
extensions: ["uuid-ossp"],
|
|
3655
|
+
tables: {
|
|
3656
|
+
[tasksTable]: tasksTableSpec(tasksTable),
|
|
3657
|
+
[historyTable]: tasksTableSpec(historyTable),
|
|
3658
|
+
[registryTable]: registryTableSpec(registryTable)
|
|
3659
|
+
}
|
|
3660
|
+
};
|
|
3257
3661
|
}
|
|
3258
3662
|
function taskHistoryInsertFromQueueRow(row, overrides) {
|
|
3259
3663
|
const { id, ...snapshot } = row;
|
|
@@ -3267,60 +3671,38 @@ async function ensureTaskTables(context, options = {}) {
|
|
|
3267
3671
|
const queueName = options.queueName ?? "tasks";
|
|
3268
3672
|
const recreate = options.recreate ?? false;
|
|
3269
3673
|
const dryRun = options.dryRun ?? false;
|
|
3270
|
-
const
|
|
3674
|
+
const databases = options.databases ?? [getDb(context)];
|
|
3271
3675
|
const log = context.logger ?? console;
|
|
3272
3676
|
const { tasksTable, historyTable, registryTable } = queueToTableNames(queueName);
|
|
3273
|
-
const
|
|
3274
|
-
const
|
|
3275
|
-
|
|
3276
|
-
if (dryRun) {
|
|
3277
|
-
const plan = [];
|
|
3677
|
+
const spec = tasksSchemaSpec(queueName);
|
|
3678
|
+
for (const db of databases) {
|
|
3679
|
+
const label = db?.config?.name ?? "db";
|
|
3278
3680
|
if (recreate) {
|
|
3279
|
-
|
|
3681
|
+
if (dryRun) {
|
|
3682
|
+
log.info?.(
|
|
3683
|
+
`[tasks-schema] dryRun \u2014 ${label}: DROP TABLE IF EXISTS ${historyTable}, ${tasksTable}, ${registryTable}`
|
|
3684
|
+
);
|
|
3685
|
+
} else {
|
|
3686
|
+
await db.schema.dropTableIfExists(historyTable);
|
|
3687
|
+
await db.schema.dropTableIfExists(tasksTable);
|
|
3688
|
+
await db.schema.dropTableIfExists(registryTable);
|
|
3689
|
+
}
|
|
3280
3690
|
}
|
|
3281
|
-
|
|
3282
|
-
if (
|
|
3283
|
-
|
|
3284
|
-
|
|
3285
|
-
|
|
3286
|
-
|
|
3287
|
-
|
|
3288
|
-
|
|
3691
|
+
const { actions } = await ensureSchema(db, spec, { dryRun, logger: context.logger });
|
|
3692
|
+
if (dryRun) {
|
|
3693
|
+
if (actions.length === 0) {
|
|
3694
|
+
log.info?.(`[tasks-schema] dryRun \u2014 ${label}: queue "${queueName}" already up to date; no DDL`);
|
|
3695
|
+
} else {
|
|
3696
|
+
log.info?.(
|
|
3697
|
+
`[tasks-schema] dryRun \u2014 ${label}: would run ${actions.length} statement(s) for queue "${queueName}":`
|
|
3698
|
+
);
|
|
3699
|
+
for (const s of actions) log.info?.(` - ${s}`);
|
|
3700
|
+
}
|
|
3701
|
+
} else if (actions.length > 0) {
|
|
3702
|
+
log.info?.(
|
|
3703
|
+
`[tasks-schema] ${label}: applied ${actions.length} DDL statement(s) for queue "${queueName}"`
|
|
3704
|
+
);
|
|
3289
3705
|
}
|
|
3290
|
-
return;
|
|
3291
|
-
}
|
|
3292
|
-
if (recreate) {
|
|
3293
|
-
await db.schema.dropTableIfExists(historyTable);
|
|
3294
|
-
await db.schema.dropTableIfExists(tasksTable);
|
|
3295
|
-
await db.schema.dropTableIfExists(registryTable);
|
|
3296
|
-
}
|
|
3297
|
-
if (needsTasks) {
|
|
3298
|
-
await db.raw(`CREATE EXTENSION IF NOT EXISTS "uuid-ossp"`);
|
|
3299
|
-
await db.schema.createTable(tasksTable, (t) => {
|
|
3300
|
-
defineTasksTable(t, db, tasksTable);
|
|
3301
|
-
});
|
|
3302
|
-
}
|
|
3303
|
-
if (needsHistory) {
|
|
3304
|
-
await db.schema.createTable(historyTable, (t) => {
|
|
3305
|
-
defineTasksTable(t, db, historyTable);
|
|
3306
|
-
});
|
|
3307
|
-
}
|
|
3308
|
-
if (needsRegistry) {
|
|
3309
|
-
await db.schema.createTable(registryTable, (t) => {
|
|
3310
|
-
t.uuid("id").primary().defaultTo(db.raw("uuid_generate_v4()"));
|
|
3311
|
-
t.text("queue_name").notNullable();
|
|
3312
|
-
t.text("service_group").notNullable();
|
|
3313
|
-
t.integer("instance_number").notNullable().defaultTo(1);
|
|
3314
|
-
t.text("service_name").notNullable();
|
|
3315
|
-
t.text("server_name").notNullable();
|
|
3316
|
-
t.integer("pid");
|
|
3317
|
-
t.json("metadata");
|
|
3318
|
-
t.timestamp("created_at").notNullable().defaultTo(db.fn.now());
|
|
3319
|
-
t.timestamp("last_seen_at").notNullable().defaultTo(db.fn.now());
|
|
3320
|
-
t.unique(["queue_name", "service_name"], `${registryTable}_queue_name_service_name_uniq`);
|
|
3321
|
-
t.index(["queue_name", "service_group", "last_seen_at"], `${registryTable}_queue_group_seen_idx`);
|
|
3322
|
-
t.index(["queue_name", "last_seen_at"], `${registryTable}_queue_seen_idx`);
|
|
3323
|
-
});
|
|
3324
3706
|
}
|
|
3325
3707
|
}
|
|
3326
3708
|
async function updateTaskProgress(context, tasksTable, taskId, progress) {
|