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