@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/index.js
CHANGED
|
@@ -1799,6 +1799,49 @@ var Params = class _Params {
|
|
|
1799
1799
|
module: moduleName ?? this._currentModule
|
|
1800
1800
|
});
|
|
1801
1801
|
}
|
|
1802
|
+
/**
|
|
1803
|
+
* Report a param value that a component RESOLVED ON ITS OWN — outside
|
|
1804
|
+
* Params.get() — e.g. discovered by combining its config files (the way
|
|
1805
|
+
* blueprints merge defaults/aggregator/feed data). Without this, every
|
|
1806
|
+
* key such a component probed for an override shows up in the
|
|
1807
|
+
* --showUsedParams dump as "undefined (default)"; reporting upgrades the
|
|
1808
|
+
* entry to the value the component actually works with.
|
|
1809
|
+
*
|
|
1810
|
+
* Attribution rules:
|
|
1811
|
+
* - entries figured from an explicit input (cli/env/options/…) are left
|
|
1812
|
+
* untouched — the component merely confirmed them, the origin stands;
|
|
1813
|
+
* - "default" entries (Params had nothing) and earlier reports are
|
|
1814
|
+
* replaced by the report;
|
|
1815
|
+
* - keys never seen by Params are appended as new entries.
|
|
1816
|
+
* The LATEST report wins — a component may resolve the same key several
|
|
1817
|
+
* times with increasing specificity (e.g. a blueprint re-merged for a
|
|
1818
|
+
* concrete resource) and the dump should show what it settled on.
|
|
1819
|
+
* Later params.get() probes that find nothing ("default") never shadow a
|
|
1820
|
+
* reported value — see {@link getFiguredByModule}.
|
|
1821
|
+
*
|
|
1822
|
+
* @param {string} key
|
|
1823
|
+
* @param {*} value - the value the component actually uses
|
|
1824
|
+
* @param {string} [source="discovered"] - short origin label, e.g. "blueprint"
|
|
1825
|
+
* @param {string} [moduleName] - dump section; defaults to the current module
|
|
1826
|
+
*/
|
|
1827
|
+
reportResolved(key, value, source = "discovered", moduleName) {
|
|
1828
|
+
const mod = moduleName ?? this._currentModule;
|
|
1829
|
+
const mine = this.trackedParams.filter((e) => e.key === key && e.module === mod);
|
|
1830
|
+
if (mine.some((e) => e.source !== "default" && !e.reported)) {
|
|
1831
|
+
return;
|
|
1832
|
+
}
|
|
1833
|
+
this.trackedParams = this.trackedParams.filter(
|
|
1834
|
+
(e) => !(e.key === key && e.module === mod)
|
|
1835
|
+
);
|
|
1836
|
+
this.trackedParams.push({
|
|
1837
|
+
key,
|
|
1838
|
+
definition: "reported",
|
|
1839
|
+
value,
|
|
1840
|
+
source,
|
|
1841
|
+
module: mod,
|
|
1842
|
+
reported: true
|
|
1843
|
+
});
|
|
1844
|
+
}
|
|
1802
1845
|
/**
|
|
1803
1846
|
* Get all tracked parameters (for --stopAfter=init)
|
|
1804
1847
|
*/
|
|
@@ -1823,12 +1866,24 @@ var Params = class _Params {
|
|
|
1823
1866
|
/**
|
|
1824
1867
|
* Get figured parameters grouped by module name.
|
|
1825
1868
|
* Same param can appear in multiple modules (e.g. source, resource).
|
|
1869
|
+
* Last occurrence per key wins, EXCEPT that an empty probe — a
|
|
1870
|
+
* params.get() that found nothing ("default", undefined) — never shadows
|
|
1871
|
+
* a value reported via {@link reportResolved}: components probe for
|
|
1872
|
+
* overrides on every resolution cycle, and those misses say nothing about
|
|
1873
|
+
* the value the component actually uses.
|
|
1826
1874
|
*/
|
|
1827
1875
|
getFiguredByModule() {
|
|
1876
|
+
const reported = /* @__PURE__ */ new Set();
|
|
1877
|
+
for (const param of this.trackedParams) {
|
|
1878
|
+
if (param.reported) reported.add(`${param.module}\0${param.key}`);
|
|
1879
|
+
}
|
|
1828
1880
|
const byModule = {};
|
|
1829
1881
|
for (const param of this.trackedParams) {
|
|
1830
1882
|
const mod = param.module;
|
|
1831
1883
|
if (!byModule[mod]) byModule[mod] = {};
|
|
1884
|
+
if (!param.reported && param.source === "default" && reported.has(`${mod}\0${param.key}`)) {
|
|
1885
|
+
continue;
|
|
1886
|
+
}
|
|
1832
1887
|
byModule[mod][param.key] = { value: param.value, source: param.source };
|
|
1833
1888
|
}
|
|
1834
1889
|
return byModule;
|
|
@@ -3304,13 +3359,113 @@ function listSources(basePath) {
|
|
|
3304
3359
|
|
|
3305
3360
|
// src/db/index.js
|
|
3306
3361
|
import knex from "knex";
|
|
3362
|
+
|
|
3363
|
+
// src/db/ensure.js
|
|
3364
|
+
var dbLabel = (db) => db?.config?.name ?? "db";
|
|
3365
|
+
async function ensureExtension(db, name, options = {}) {
|
|
3366
|
+
const action = `CREATE EXTENSION IF NOT EXISTS "${name}"`;
|
|
3367
|
+
if (!options.dryRun) {
|
|
3368
|
+
await db.raw(action);
|
|
3369
|
+
}
|
|
3370
|
+
options.logger?.silly?.(`[ensure] ${dbLabel(db)}: ${action}${options.dryRun ? " (dryRun)" : ""}`);
|
|
3371
|
+
return { action };
|
|
3372
|
+
}
|
|
3373
|
+
async function ensureTable(db, tableName, spec, options = {}) {
|
|
3374
|
+
const { dryRun = false, logger } = options;
|
|
3375
|
+
const actions = [];
|
|
3376
|
+
const exists = await db.tableExists(tableName);
|
|
3377
|
+
if (!exists) {
|
|
3378
|
+
actions.push(`CREATE TABLE ${tableName} (${Object.keys(spec.columns).length} columns)`);
|
|
3379
|
+
if (!dryRun) {
|
|
3380
|
+
await db.schema.createTable(tableName, (t) => {
|
|
3381
|
+
for (const define of Object.values(spec.columns)) {
|
|
3382
|
+
define(t, db);
|
|
3383
|
+
}
|
|
3384
|
+
});
|
|
3385
|
+
}
|
|
3386
|
+
} else {
|
|
3387
|
+
const missing = [];
|
|
3388
|
+
for (const column of Object.keys(spec.columns)) {
|
|
3389
|
+
if (!await db.schema.hasColumn(tableName, column)) {
|
|
3390
|
+
missing.push(column);
|
|
3391
|
+
}
|
|
3392
|
+
}
|
|
3393
|
+
if (missing.length > 0) {
|
|
3394
|
+
actions.push(`ALTER TABLE ${tableName} ADD COLUMN ${missing.join(", ")}`);
|
|
3395
|
+
if (!dryRun) {
|
|
3396
|
+
await db.schema.alterTable(tableName, (t) => {
|
|
3397
|
+
for (const column of missing) {
|
|
3398
|
+
spec.columns[column](t, db);
|
|
3399
|
+
}
|
|
3400
|
+
});
|
|
3401
|
+
}
|
|
3402
|
+
}
|
|
3403
|
+
}
|
|
3404
|
+
for (const index of spec.indexes ?? []) {
|
|
3405
|
+
const indexActions = await ensureIndex(db, tableName, index, options);
|
|
3406
|
+
actions.push(...indexActions);
|
|
3407
|
+
}
|
|
3408
|
+
for (const action of actions) {
|
|
3409
|
+
logger?.silly?.(`[ensure] ${dbLabel(db)}: ${action}${dryRun ? " (dryRun)" : ""}`);
|
|
3410
|
+
}
|
|
3411
|
+
return actions;
|
|
3412
|
+
}
|
|
3413
|
+
async function ensureIndex(db, tableName, index, options = {}) {
|
|
3414
|
+
const { dryRun = false } = options;
|
|
3415
|
+
const kind = index.unique ? "UNIQUE INDEX" : "INDEX";
|
|
3416
|
+
const cols = index.columns.map((c) => `"${c}"`).join(", ");
|
|
3417
|
+
const isPg = String(db?.config?.connectionString ?? "").startsWith("postgresql");
|
|
3418
|
+
if (isPg) {
|
|
3419
|
+
const sql2 = `CREATE ${kind} IF NOT EXISTS "${index.name}" ON "${tableName}" (${cols})`;
|
|
3420
|
+
const { rows } = await db.raw(`SELECT 1 FROM pg_indexes WHERE indexname = ?`, [index.name]);
|
|
3421
|
+
if (rows.length > 0) return [];
|
|
3422
|
+
if (!dryRun) await db.raw(sql2);
|
|
3423
|
+
return [sql2];
|
|
3424
|
+
}
|
|
3425
|
+
const sql = `CREATE ${kind} ${index.name} ON ${tableName} (${cols})`;
|
|
3426
|
+
if (!dryRun) {
|
|
3427
|
+
try {
|
|
3428
|
+
await db.raw(sql);
|
|
3429
|
+
} catch (error) {
|
|
3430
|
+
if (!/already exists|duplicate/i.test(error?.message ?? "")) throw error;
|
|
3431
|
+
return [];
|
|
3432
|
+
}
|
|
3433
|
+
}
|
|
3434
|
+
return [sql];
|
|
3435
|
+
}
|
|
3436
|
+
async function ensureSchema(db, spec, options = {}) {
|
|
3437
|
+
const actions = [];
|
|
3438
|
+
for (const extension of spec.extensions ?? []) {
|
|
3439
|
+
const { action } = await ensureExtension(db, extension, options);
|
|
3440
|
+
if (options.dryRun) actions.push(action);
|
|
3441
|
+
}
|
|
3442
|
+
for (const [tableName, tableSpec] of Object.entries(spec.tables ?? {})) {
|
|
3443
|
+
actions.push(...await ensureTable(db, tableName, tableSpec, options));
|
|
3444
|
+
}
|
|
3445
|
+
return { database: dbLabel(db), actions };
|
|
3446
|
+
}
|
|
3447
|
+
async function ensureSchemaEverywhere(dbs, spec, options = {}) {
|
|
3448
|
+
const reports = [];
|
|
3449
|
+
for (const db of dbs) {
|
|
3450
|
+
const report = await ensureSchema(db, spec, options);
|
|
3451
|
+
if (report.actions.length > 0) {
|
|
3452
|
+
options.logger?.info?.(
|
|
3453
|
+
`[ensure] ${report.database}: ${options.dryRun ? "would apply" : "applied"} ${report.actions.length} DDL statement(s)`
|
|
3454
|
+
);
|
|
3455
|
+
}
|
|
3456
|
+
reports.push(report);
|
|
3457
|
+
}
|
|
3458
|
+
return reports;
|
|
3459
|
+
}
|
|
3460
|
+
|
|
3461
|
+
// src/db/index.js
|
|
3307
3462
|
var KNEX_DEFAULTS = {
|
|
3308
3463
|
testConnection: true,
|
|
3309
3464
|
pool: { min: 2, max: 10 },
|
|
3310
3465
|
acquireConnectionTimeout: 1e4,
|
|
3311
3466
|
ssl: { rejectUnauthorized: false }
|
|
3312
3467
|
};
|
|
3313
|
-
var Db = class {
|
|
3468
|
+
var Db = class _Db {
|
|
3314
3469
|
static async init(context, options = {}) {
|
|
3315
3470
|
const buildConfig = async () => {
|
|
3316
3471
|
const defs = {
|
|
@@ -3379,6 +3534,177 @@ var Db = class {
|
|
|
3379
3534
|
const config2 = context?.params?.runWithModuleAsync ? await context.params.runWithModuleAsync("db", buildConfig) : await buildConfig();
|
|
3380
3535
|
return dbConnect(context, config2);
|
|
3381
3536
|
}
|
|
3537
|
+
/**
|
|
3538
|
+
* Initialize a SIBLING database handler: a database that lives on the same
|
|
3539
|
+
* server with the same credentials/options as an existing ("base") one, and
|
|
3540
|
+
* differs only by its database name. Typical use: a per-tenant / per-subject
|
|
3541
|
+
* database alongside a main database that keeps the shared tables.
|
|
3542
|
+
*
|
|
3543
|
+
* context.db = await Db.init(context); // main
|
|
3544
|
+
* const sub = await Db.initSibling(context, "src_bright"); // sibling
|
|
3545
|
+
*
|
|
3546
|
+
* LOCATION-AGNOSTIC BY DESIGN — the call gracefully falls back to the main
|
|
3547
|
+
* database, so callers can use it for all subject data without knowing what
|
|
3548
|
+
* has been migrated where:
|
|
3549
|
+
* - empty `siblingName` → the main handler (same as Db.init)
|
|
3550
|
+
* - sibling DB does not exist yet → the main handler (data not migrated;
|
|
3551
|
+
* it still lives in the main database)
|
|
3552
|
+
* Callers that must not fall back can check `handler === context.db`.
|
|
3553
|
+
*
|
|
3554
|
+
* Connection string resolution for an actual sibling, in order:
|
|
3555
|
+
* 1. Explicit override — param `dbConnectionStringSib<SiblingName>` (env
|
|
3556
|
+
* `DB_CONNECTION_STRING_SIB_<SIBLING_NAME>`, e.g. `src_bright` →
|
|
3557
|
+
* `DB_CONNECTION_STRING_SIB_SRC_BRIGHT`). Nobody needs this on day
|
|
3558
|
+
* one; it is the escape hatch for when a sibling later moves to its
|
|
3559
|
+
* own server — one env var, no code changes (the `SIB_` namespace
|
|
3560
|
+
* both overrides the connection and declares that the sibling
|
|
3561
|
+
* exists, so it never falls back to main).
|
|
3562
|
+
* 2. Derived — take the base connection string and swap the database
|
|
3563
|
+
* name (after confirming the database exists on that server). The
|
|
3564
|
+
* base is `options.baseDb` (a Db handler), then
|
|
3565
|
+
* `options.baseConnectionString`, then `context.db`.
|
|
3566
|
+
*
|
|
3567
|
+
* Handlers are cached per name on the context (`context.siblingDbs`), so
|
|
3568
|
+
* any number of components asking for the same sibling share one pool —
|
|
3569
|
+
* including the "falls back to main" answer, which is remembered for the
|
|
3570
|
+
* lifetime of the process (a mid-run migration is picked up on restart).
|
|
3571
|
+
* Disconnect is registered via `context.registerCleanup`, same as the
|
|
3572
|
+
* main handler.
|
|
3573
|
+
*
|
|
3574
|
+
* @param {object} context - context with params/logger (and usually .db)
|
|
3575
|
+
* @param {string} [siblingName] - the sibling's database name (e.g. "src_bright")
|
|
3576
|
+
* @param {object} [options] - { baseDb, baseConnectionString, dbProfile }
|
|
3577
|
+
* @returns {Promise<Db>} connected handler (same proxy shape as Db.init)
|
|
3578
|
+
*/
|
|
3579
|
+
static async initSibling(context, siblingName, options = {}) {
|
|
3580
|
+
if (!siblingName) {
|
|
3581
|
+
return resolveMainHandler(context, options);
|
|
3582
|
+
}
|
|
3583
|
+
if (!/^[a-zA-Z0-9_]+$/.test(siblingName)) {
|
|
3584
|
+
throw new ParamError(
|
|
3585
|
+
`Db.initSibling: invalid sibling database name "${siblingName}" (letters, digits and _ only)`
|
|
3586
|
+
);
|
|
3587
|
+
}
|
|
3588
|
+
if (!context.siblingDbs) {
|
|
3589
|
+
context.siblingDbs = /* @__PURE__ */ new Map();
|
|
3590
|
+
}
|
|
3591
|
+
const cached = context.siblingDbs.get(siblingName);
|
|
3592
|
+
if (cached) {
|
|
3593
|
+
return cached;
|
|
3594
|
+
}
|
|
3595
|
+
const overrideParam = `dbConnectionStringSib${camelizeDbName(siblingName)}`;
|
|
3596
|
+
let connectionString = await context?.params?.get?.(overrideParam, "string");
|
|
3597
|
+
if (connectionString) {
|
|
3598
|
+
context.logger?.debug?.(
|
|
3599
|
+
`[Db] sibling "${siblingName}": using override param "${overrideParam}"`
|
|
3600
|
+
);
|
|
3601
|
+
} else {
|
|
3602
|
+
const baseHandle = options.baseDb ?? context.db;
|
|
3603
|
+
const base = baseHandle?.config?.connectionString ?? options.baseConnectionString;
|
|
3604
|
+
if (!base) {
|
|
3605
|
+
throw new ParamError(
|
|
3606
|
+
`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)})`
|
|
3607
|
+
);
|
|
3608
|
+
}
|
|
3609
|
+
const exists = await databaseExistsOnServer(baseHandle, base, siblingName);
|
|
3610
|
+
if (!exists) {
|
|
3611
|
+
context.logger?.debug?.(
|
|
3612
|
+
`[Db] sibling "${siblingName}" does not exist \u2014 falling back to the main database`
|
|
3613
|
+
);
|
|
3614
|
+
const main = await resolveMainHandler(context, options);
|
|
3615
|
+
context.siblingDbs.set(siblingName, main);
|
|
3616
|
+
return main;
|
|
3617
|
+
}
|
|
3618
|
+
connectionString = replaceDatabaseName(base, siblingName);
|
|
3619
|
+
context.logger?.debug?.(
|
|
3620
|
+
`[Db] sibling "${siblingName}": derived from base (${formatConnectionEndpoint(base) ?? "?"})`
|
|
3621
|
+
);
|
|
3622
|
+
}
|
|
3623
|
+
const config2 = {
|
|
3624
|
+
...KNEX_DEFAULTS,
|
|
3625
|
+
connectionString,
|
|
3626
|
+
name: siblingName,
|
|
3627
|
+
profile: !!options.dbProfile,
|
|
3628
|
+
logger: context.logger
|
|
3629
|
+
};
|
|
3630
|
+
const handler = await dbConnect(context, config2);
|
|
3631
|
+
context.siblingDbs.set(siblingName, handler);
|
|
3632
|
+
return handler;
|
|
3633
|
+
}
|
|
3634
|
+
/**
|
|
3635
|
+
* Discover the sibling databases that are "currently in use", by name.
|
|
3636
|
+
* Two sources, merged (env wins on duplicates):
|
|
3637
|
+
*
|
|
3638
|
+
* 1. ENV-DECLARED — every `DB_CONNECTION_STRING_SIB_<NAME>` env var
|
|
3639
|
+
* (the dedicated `SIB_` namespace) whose decoded name matches. This
|
|
3640
|
+
* covers siblings that moved to their own server: the same var that
|
|
3641
|
+
* overrides the connection also *registers* the database, so `.env`
|
|
3642
|
+
* stays the single convenient list.
|
|
3643
|
+
* 2. SAME-SERVER SCAN — `SELECT datname FROM pg_database` on the base
|
|
3644
|
+
* server (PostgreSQL only), filtered the same way.
|
|
3645
|
+
*
|
|
3646
|
+
* The caller says what "matches": `{ prefix: "src_" }` or
|
|
3647
|
+
* `{ match: /^src_/ }` — the toolkit does not guess a naming convention.
|
|
3648
|
+
*
|
|
3649
|
+
* @param {object} context - needs context.db (or options.baseDb) for the server scan
|
|
3650
|
+
* @param {{ prefix?: string, match?: RegExp, baseDb?: object, env?: object }} options
|
|
3651
|
+
* @returns {Promise<Array<{ name: string, origin: "env"|"server" }>>} sorted by name
|
|
3652
|
+
*/
|
|
3653
|
+
static async discoverSiblings(context, options = {}) {
|
|
3654
|
+
const { prefix, match, env = process.env } = options;
|
|
3655
|
+
if (!prefix && !match) {
|
|
3656
|
+
throw new ParamError(`Db.discoverSiblings: pass { prefix: "..." } or { match: /.../ }`);
|
|
3657
|
+
}
|
|
3658
|
+
const matches = match instanceof RegExp ? (n) => match.test(n) : (n) => n.startsWith(prefix);
|
|
3659
|
+
const found = /* @__PURE__ */ new Map();
|
|
3660
|
+
for (const key of Object.keys(env)) {
|
|
3661
|
+
const m = /^DB_CONNECTION_STRING_SIB_(.+)$/.exec(key);
|
|
3662
|
+
if (!m || !env[key]) continue;
|
|
3663
|
+
const name = m[1].toLowerCase();
|
|
3664
|
+
if (matches(name)) {
|
|
3665
|
+
found.set(name, "env");
|
|
3666
|
+
}
|
|
3667
|
+
}
|
|
3668
|
+
const base = options.baseDb ?? context?.db;
|
|
3669
|
+
if (base) {
|
|
3670
|
+
const connectionString = String(base.config?.connectionString ?? "");
|
|
3671
|
+
if (connectionString.startsWith("postgresql")) {
|
|
3672
|
+
const { rows } = await base.raw(
|
|
3673
|
+
"SELECT datname FROM pg_database WHERE datistemplate = false"
|
|
3674
|
+
);
|
|
3675
|
+
for (const { datname } of rows) {
|
|
3676
|
+
if (matches(datname) && !found.has(datname)) {
|
|
3677
|
+
found.set(datname, "server");
|
|
3678
|
+
}
|
|
3679
|
+
}
|
|
3680
|
+
} else {
|
|
3681
|
+
context?.logger?.warn?.(
|
|
3682
|
+
"[Db] discoverSiblings: server scan supported for PostgreSQL only; using env-declared siblings"
|
|
3683
|
+
);
|
|
3684
|
+
}
|
|
3685
|
+
}
|
|
3686
|
+
return [...found].map(([name, origin]) => ({ name, origin })).sort((a, b) => a.name.localeCompare(b.name));
|
|
3687
|
+
}
|
|
3688
|
+
/**
|
|
3689
|
+
* Discover + connect: one handler per active sibling (cached, pooled —
|
|
3690
|
+
* see initSibling). Pass `includeMain: true` to get `[context.db, ...]`,
|
|
3691
|
+
* which is the usual shape for "apply this DDL everywhere" loops:
|
|
3692
|
+
*
|
|
3693
|
+
* const dbs = await Db.initAllSiblings(context, { prefix: "src_", includeMain: true });
|
|
3694
|
+
* await ensureSchemaEverywhere(dbs, spec, { logger: context.logger });
|
|
3695
|
+
*
|
|
3696
|
+
* @param {object} context
|
|
3697
|
+
* @param {{ prefix?: string, match?: RegExp, includeMain?: boolean, baseDb?: object, env?: object }} options
|
|
3698
|
+
* @returns {Promise<Function[]>} connected handlers
|
|
3699
|
+
*/
|
|
3700
|
+
static async initAllSiblings(context, options = {}) {
|
|
3701
|
+
const discovered = await _Db.discoverSiblings(context, options);
|
|
3702
|
+
const handlers = [];
|
|
3703
|
+
for (const { name } of discovered) {
|
|
3704
|
+
handlers.push(await _Db.initSibling(context, name, options));
|
|
3705
|
+
}
|
|
3706
|
+
return options.includeMain && context.db ? [context.db, ...handlers] : handlers;
|
|
3707
|
+
}
|
|
3382
3708
|
constructor(config2) {
|
|
3383
3709
|
if (!config2 || !config2.connectionString) {
|
|
3384
3710
|
throw new ParamError("Db: connectionString is required");
|
|
@@ -3639,6 +3965,54 @@ var Db = class {
|
|
|
3639
3965
|
function capitalizeFirstLetter(str) {
|
|
3640
3966
|
return str.charAt(0).toUpperCase() + str.slice(1);
|
|
3641
3967
|
}
|
|
3968
|
+
async function resolveMainHandler(context, options = {}) {
|
|
3969
|
+
if (options.baseDb) {
|
|
3970
|
+
return options.baseDb;
|
|
3971
|
+
}
|
|
3972
|
+
if (!context.db) {
|
|
3973
|
+
context.db = await Db.init(context);
|
|
3974
|
+
}
|
|
3975
|
+
return context.db;
|
|
3976
|
+
}
|
|
3977
|
+
async function databaseExistsOnServer(baseHandle, baseConnectionString, databaseName) {
|
|
3978
|
+
if (!String(baseConnectionString).startsWith("postgresql")) {
|
|
3979
|
+
return true;
|
|
3980
|
+
}
|
|
3981
|
+
const query = "SELECT 1 FROM pg_database WHERE datname = ?";
|
|
3982
|
+
if (baseHandle) {
|
|
3983
|
+
const { rows } = await baseHandle.raw(query, [databaseName]);
|
|
3984
|
+
return rows.length > 0;
|
|
3985
|
+
}
|
|
3986
|
+
const shortLived = knex({
|
|
3987
|
+
client: "pg",
|
|
3988
|
+
connection: { connectionString: baseConnectionString },
|
|
3989
|
+
pool: { min: 0, max: 1 }
|
|
3990
|
+
});
|
|
3991
|
+
try {
|
|
3992
|
+
const { rows } = await shortLived.raw(query, [databaseName]);
|
|
3993
|
+
return rows.length > 0;
|
|
3994
|
+
} finally {
|
|
3995
|
+
await shortLived.destroy();
|
|
3996
|
+
}
|
|
3997
|
+
}
|
|
3998
|
+
function camelizeDbName(name) {
|
|
3999
|
+
return name.split(/[_-]+/).filter(Boolean).map(capitalizeFirstLetter).join("");
|
|
4000
|
+
}
|
|
4001
|
+
function toEnvKey(key) {
|
|
4002
|
+
return key.replace(/([A-Z])/g, "_$1").toUpperCase();
|
|
4003
|
+
}
|
|
4004
|
+
function replaceDatabaseName(connectionString, databaseName) {
|
|
4005
|
+
let url;
|
|
4006
|
+
try {
|
|
4007
|
+
url = new URL(connectionString);
|
|
4008
|
+
} catch {
|
|
4009
|
+
throw new ParamError(
|
|
4010
|
+
`Db: cannot parse connection string to derive a sibling database from it`
|
|
4011
|
+
);
|
|
4012
|
+
}
|
|
4013
|
+
url.pathname = `/${databaseName}`;
|
|
4014
|
+
return url.toString();
|
|
4015
|
+
}
|
|
3642
4016
|
function resolveDbDisplayName(dbName, connectionParam, argsEnv, mergedName) {
|
|
3643
4017
|
if (dbName) {
|
|
3644
4018
|
return dbName;
|
|
@@ -5754,29 +6128,90 @@ function queueToTableNames(queueName) {
|
|
|
5754
6128
|
registryTable: `${queueName}_services_registry`
|
|
5755
6129
|
};
|
|
5756
6130
|
}
|
|
5757
|
-
function
|
|
5758
|
-
|
|
5759
|
-
|
|
5760
|
-
|
|
5761
|
-
|
|
5762
|
-
|
|
5763
|
-
|
|
5764
|
-
|
|
5765
|
-
|
|
5766
|
-
|
|
5767
|
-
|
|
5768
|
-
|
|
5769
|
-
|
|
5770
|
-
|
|
5771
|
-
|
|
5772
|
-
|
|
5773
|
-
|
|
5774
|
-
|
|
5775
|
-
|
|
5776
|
-
|
|
5777
|
-
|
|
5778
|
-
|
|
5779
|
-
|
|
6131
|
+
function tasksTableSpec(tableNameForIndex) {
|
|
6132
|
+
return {
|
|
6133
|
+
columns: {
|
|
6134
|
+
id: (t, db) => t.uuid("id").primary().defaultTo(db.raw("uuid_generate_v4()")),
|
|
6135
|
+
created_at: (t, db) => t.timestamp("created_at").notNullable().defaultTo(db.fn.now()),
|
|
6136
|
+
started_at: (t) => t.timestamp("started_at"),
|
|
6137
|
+
completed_at: (t) => t.timestamp("completed_at"),
|
|
6138
|
+
/*
|
|
6139
|
+
* Priority: lower number = claimed first (see claimNextRunnableTask: ORDER BY priority ASC).
|
|
6140
|
+
* Suggested range 0–100: 0 = most urgent, 100 = least; default 50 for normal work.
|
|
6141
|
+
*/
|
|
6142
|
+
priority: (t) => t.integer("priority").notNullable().defaultTo(50),
|
|
6143
|
+
schedule: (t) => t.text("schedule"),
|
|
6144
|
+
next_run_at: (t) => t.timestamp("next_run_at").defaultTo(null),
|
|
6145
|
+
past_due: (t) => t.timestamp("past_due").defaultTo(null),
|
|
6146
|
+
name: (t) => t.text("name").notNullable(),
|
|
6147
|
+
opid: (t) => t.text("opid"),
|
|
6148
|
+
params: (t) => t.jsonb("params"),
|
|
6149
|
+
// those are target identifiers, kind of who is going to run a task.
|
|
6150
|
+
service_group: (t) => t.text("service_group"),
|
|
6151
|
+
// harvester, loader, photos, ...
|
|
6152
|
+
instance_number: (t) => t.integer("instance_number"),
|
|
6153
|
+
service_name: (t) => t.text("service_name"),
|
|
6154
|
+
// that's a "<server_name>_<service_group>_<instance_number>"
|
|
6155
|
+
server_name: (t) => t.text("server_name"),
|
|
6156
|
+
// filled by runner when registering, auto.
|
|
6157
|
+
status: (t) => t.text("status").notNullable().defaultTo("idle"),
|
|
6158
|
+
// idle, running, completed, failed, paused
|
|
6159
|
+
status_changed_at: (t) => t.timestamp("status_changed_at").defaultTo(null),
|
|
6160
|
+
progress: (t) => t.text("progress"),
|
|
6161
|
+
success: (t) => t.boolean("success"),
|
|
6162
|
+
results: (t) => t.jsonb("results")
|
|
6163
|
+
},
|
|
6164
|
+
indexes: [
|
|
6165
|
+
{
|
|
6166
|
+
columns: ["service_group", "status", "priority", "created_at"],
|
|
6167
|
+
name: `${tableNameForIndex}_claim_idx`
|
|
6168
|
+
},
|
|
6169
|
+
{ columns: ["service_group", "name"], name: `${tableNameForIndex}_group_name_idx` }
|
|
6170
|
+
]
|
|
6171
|
+
};
|
|
6172
|
+
}
|
|
6173
|
+
function registryTableSpec(registryTable) {
|
|
6174
|
+
return {
|
|
6175
|
+
columns: {
|
|
6176
|
+
id: (t, db) => t.uuid("id").primary().defaultTo(db.raw("uuid_generate_v4()")),
|
|
6177
|
+
queue_name: (t) => t.text("queue_name").notNullable(),
|
|
6178
|
+
service_group: (t) => t.text("service_group").notNullable(),
|
|
6179
|
+
// harvester, loader, photos, ...
|
|
6180
|
+
instance_number: (t) => t.integer("instance_number").notNullable().defaultTo(1),
|
|
6181
|
+
service_name: (t) => t.text("service_name").notNullable(),
|
|
6182
|
+
// that's a "<server_name>_<service_group>_<instance_number>"
|
|
6183
|
+
server_name: (t) => t.text("server_name").notNullable(),
|
|
6184
|
+
// filled by runner when registering, auto.
|
|
6185
|
+
pid: (t) => t.integer("pid"),
|
|
6186
|
+
metadata: (t) => t.json("metadata"),
|
|
6187
|
+
created_at: (t, db) => t.timestamp("created_at").notNullable().defaultTo(db.fn.now()),
|
|
6188
|
+
last_seen_at: (t, db) => t.timestamp("last_seen_at").notNullable().defaultTo(db.fn.now())
|
|
6189
|
+
},
|
|
6190
|
+
indexes: [
|
|
6191
|
+
{
|
|
6192
|
+
columns: ["queue_name", "service_name"],
|
|
6193
|
+
name: `${registryTable}_queue_name_service_name_uniq`,
|
|
6194
|
+
unique: true
|
|
6195
|
+
},
|
|
6196
|
+
{
|
|
6197
|
+
columns: ["queue_name", "service_group", "last_seen_at"],
|
|
6198
|
+
name: `${registryTable}_queue_group_seen_idx`
|
|
6199
|
+
},
|
|
6200
|
+
{ columns: ["queue_name", "last_seen_at"], name: `${registryTable}_queue_seen_idx` }
|
|
6201
|
+
]
|
|
6202
|
+
// 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.
|
|
6203
|
+
};
|
|
6204
|
+
}
|
|
6205
|
+
function tasksSchemaSpec(queueName = "tasks") {
|
|
6206
|
+
const { tasksTable, historyTable, registryTable } = queueToTableNames(queueName);
|
|
6207
|
+
return {
|
|
6208
|
+
extensions: ["uuid-ossp"],
|
|
6209
|
+
tables: {
|
|
6210
|
+
[tasksTable]: tasksTableSpec(tasksTable),
|
|
6211
|
+
[historyTable]: tasksTableSpec(historyTable),
|
|
6212
|
+
[registryTable]: registryTableSpec(registryTable)
|
|
6213
|
+
}
|
|
6214
|
+
};
|
|
5780
6215
|
}
|
|
5781
6216
|
function taskHistoryInsertFromQueueRow(row, overrides) {
|
|
5782
6217
|
const { id, ...snapshot } = row;
|
|
@@ -5790,60 +6225,38 @@ async function ensureTaskTables(context, options = {}) {
|
|
|
5790
6225
|
const queueName = options.queueName ?? "tasks";
|
|
5791
6226
|
const recreate = options.recreate ?? false;
|
|
5792
6227
|
const dryRun = options.dryRun ?? false;
|
|
5793
|
-
const
|
|
6228
|
+
const databases = options.databases ?? [getDb(context)];
|
|
5794
6229
|
const log = context.logger ?? console;
|
|
5795
6230
|
const { tasksTable, historyTable, registryTable } = queueToTableNames(queueName);
|
|
5796
|
-
const
|
|
5797
|
-
const
|
|
5798
|
-
|
|
5799
|
-
if (dryRun) {
|
|
5800
|
-
const plan = [];
|
|
6231
|
+
const spec = tasksSchemaSpec(queueName);
|
|
6232
|
+
for (const db of databases) {
|
|
6233
|
+
const label = db?.config?.name ?? "db";
|
|
5801
6234
|
if (recreate) {
|
|
5802
|
-
|
|
6235
|
+
if (dryRun) {
|
|
6236
|
+
log.info?.(
|
|
6237
|
+
`[tasks-schema] dryRun \u2014 ${label}: DROP TABLE IF EXISTS ${historyTable}, ${tasksTable}, ${registryTable}`
|
|
6238
|
+
);
|
|
6239
|
+
} else {
|
|
6240
|
+
await db.schema.dropTableIfExists(historyTable);
|
|
6241
|
+
await db.schema.dropTableIfExists(tasksTable);
|
|
6242
|
+
await db.schema.dropTableIfExists(registryTable);
|
|
6243
|
+
}
|
|
5803
6244
|
}
|
|
5804
|
-
|
|
5805
|
-
if (
|
|
5806
|
-
|
|
5807
|
-
|
|
5808
|
-
|
|
5809
|
-
|
|
5810
|
-
|
|
5811
|
-
|
|
6245
|
+
const { actions } = await ensureSchema(db, spec, { dryRun, logger: context.logger });
|
|
6246
|
+
if (dryRun) {
|
|
6247
|
+
if (actions.length === 0) {
|
|
6248
|
+
log.info?.(`[tasks-schema] dryRun \u2014 ${label}: queue "${queueName}" already up to date; no DDL`);
|
|
6249
|
+
} else {
|
|
6250
|
+
log.info?.(
|
|
6251
|
+
`[tasks-schema] dryRun \u2014 ${label}: would run ${actions.length} statement(s) for queue "${queueName}":`
|
|
6252
|
+
);
|
|
6253
|
+
for (const s of actions) log.info?.(` - ${s}`);
|
|
6254
|
+
}
|
|
6255
|
+
} else if (actions.length > 0) {
|
|
6256
|
+
log.info?.(
|
|
6257
|
+
`[tasks-schema] ${label}: applied ${actions.length} DDL statement(s) for queue "${queueName}"`
|
|
6258
|
+
);
|
|
5812
6259
|
}
|
|
5813
|
-
return;
|
|
5814
|
-
}
|
|
5815
|
-
if (recreate) {
|
|
5816
|
-
await db.schema.dropTableIfExists(historyTable);
|
|
5817
|
-
await db.schema.dropTableIfExists(tasksTable);
|
|
5818
|
-
await db.schema.dropTableIfExists(registryTable);
|
|
5819
|
-
}
|
|
5820
|
-
if (needsTasks) {
|
|
5821
|
-
await db.raw(`CREATE EXTENSION IF NOT EXISTS "uuid-ossp"`);
|
|
5822
|
-
await db.schema.createTable(tasksTable, (t) => {
|
|
5823
|
-
defineTasksTable(t, db, tasksTable);
|
|
5824
|
-
});
|
|
5825
|
-
}
|
|
5826
|
-
if (needsHistory) {
|
|
5827
|
-
await db.schema.createTable(historyTable, (t) => {
|
|
5828
|
-
defineTasksTable(t, db, historyTable);
|
|
5829
|
-
});
|
|
5830
|
-
}
|
|
5831
|
-
if (needsRegistry) {
|
|
5832
|
-
await db.schema.createTable(registryTable, (t) => {
|
|
5833
|
-
t.uuid("id").primary().defaultTo(db.raw("uuid_generate_v4()"));
|
|
5834
|
-
t.text("queue_name").notNullable();
|
|
5835
|
-
t.text("service_group").notNullable();
|
|
5836
|
-
t.integer("instance_number").notNullable().defaultTo(1);
|
|
5837
|
-
t.text("service_name").notNullable();
|
|
5838
|
-
t.text("server_name").notNullable();
|
|
5839
|
-
t.integer("pid");
|
|
5840
|
-
t.json("metadata");
|
|
5841
|
-
t.timestamp("created_at").notNullable().defaultTo(db.fn.now());
|
|
5842
|
-
t.timestamp("last_seen_at").notNullable().defaultTo(db.fn.now());
|
|
5843
|
-
t.unique(["queue_name", "service_name"], `${registryTable}_queue_name_service_name_uniq`);
|
|
5844
|
-
t.index(["queue_name", "service_group", "last_seen_at"], `${registryTable}_queue_group_seen_idx`);
|
|
5845
|
-
t.index(["queue_name", "last_seen_at"], `${registryTable}_queue_seen_idx`);
|
|
5846
|
-
});
|
|
5847
6260
|
}
|
|
5848
6261
|
}
|
|
5849
6262
|
async function enqueueTask(context, options) {
|
|
@@ -8002,8 +8415,13 @@ export {
|
|
|
8002
8415
|
enqueueTask,
|
|
8003
8416
|
ensureDeployKeyOnRemote,
|
|
8004
8417
|
ensureEnvOnRemote,
|
|
8418
|
+
ensureExtension,
|
|
8419
|
+
ensureIndex,
|
|
8005
8420
|
ensureRemoteRepo,
|
|
8006
8421
|
ensureRepoDependencies,
|
|
8422
|
+
ensureSchema,
|
|
8423
|
+
ensureSchemaEverywhere,
|
|
8424
|
+
ensureTable,
|
|
8007
8425
|
ensureTaskTables,
|
|
8008
8426
|
flushTaskIpcLogs,
|
|
8009
8427
|
getArgsInstance,
|
|
@@ -8042,6 +8460,7 @@ export {
|
|
|
8042
8460
|
releaseDir,
|
|
8043
8461
|
releaseStamp,
|
|
8044
8462
|
reloadPm2,
|
|
8463
|
+
replaceDatabaseName,
|
|
8045
8464
|
resolveAsterisks,
|
|
8046
8465
|
resolveIpcFileLogsDir,
|
|
8047
8466
|
resolveNextVersion,
|