poad 2.63.0 → 2.64.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/global/start.js +7 -0
- package/package.json +2 -2
- package/poad.js +2 -2
- package/project/auth/import.js +68 -0
- package/project/auth/index.js +7 -0
- package/project/cli.js +6 -1
- package/project/db/import.js +138 -0
- package/project/db/index.js +1 -0
- package/project/deploy.js +4 -0
- package/project/logs.js +2 -0
- package/project/source.js +199 -41
- package/project/storage/cp.js +4 -2
- package/test/auth-import.test.js +113 -0
- package/test/cloud.test.js +1 -0
- package/test/data.test.js +24 -0
- package/test/deps.test.js +108 -0
- package/test/import.test.js +210 -0
- package/test/logs.test.js +12 -0
- package/test/naming.test.js +18 -0
- package/test/source.test.js +37 -0
- package/test/storage-tus.test.js +169 -0
- package/test/storage.test.js +7 -0
- package/utils/auth-import.js +204 -0
- package/utils/cloud/bundle.js +16 -2
- package/utils/cloud/deps.js +297 -0
- package/utils/data.js +41 -0
- package/utils/help-details.js +53 -4
- package/utils/import-upload.js +112 -0
- package/utils/logline.js +2 -2
- package/utils/logs.js +8 -1
- package/utils/naming.js +41 -0
- package/utils/runner.js +1 -1
- package/utils/storage-copy.js +31 -3
- package/utils/storage-tus.js +201 -0
- package/utils/storage.js +37 -1
package/global/start.js
CHANGED
|
@@ -63,6 +63,11 @@ module.exports = async (args = {}) => {
|
|
|
63
63
|
config.engine = await offerEngineUpgrade(root, config, args);
|
|
64
64
|
const gatewayWarning = gateway.maxBody(config).warning;
|
|
65
65
|
if (gatewayWarning) console.log(chalk.yellowBright(gatewayWarning));
|
|
66
|
+
// [storage] file_size_limit (storage 0.6.0+) : une valeur illisible est dite, et pas transmise
|
|
67
|
+
const storageWarning = require('../utils/storage').fileSizeLimit(config).warning;
|
|
68
|
+
if (storageWarning) console.log(chalk.yellowBright(storageWarning));
|
|
69
|
+
const dataWarning = require('../utils/data').serviceRoleTimeout(config).warning;
|
|
70
|
+
if (dataWarning) console.log(chalk.yellowBright(dataWarning));
|
|
66
71
|
// Réglages [ai] (engine 0.30.0+) : une valeur refusée est dite, et pas transmise
|
|
67
72
|
const aiSettings = require('../utils/ai').engineEnv(config);
|
|
68
73
|
aiSettings.warnings.forEach((w) => console.log(chalk.yellowBright(w)));
|
|
@@ -156,6 +161,8 @@ module.exports = async (args = {}) => {
|
|
|
156
161
|
...runner.engineEnv(config),
|
|
157
162
|
// Taille maximale d'un corps de requête : [gateway] max_body (engine 0.28.2+)
|
|
158
163
|
...gateway.engineEnv(config),
|
|
164
|
+
// Délai des requêtes de service_role : [data] service_role_statement_timeout (data 0.11.0+)
|
|
165
|
+
...require('../utils/data').engineEnv(config),
|
|
159
166
|
// Socle IA : [ai] de poad/config.toml (engine 0.30.0+ ; un engine plus ancien les ignore)
|
|
160
167
|
...aiSettings.env,
|
|
161
168
|
// Fronts : port de chacun, réserve, nom du projet (page « En construction »)
|
package/package.json
CHANGED
package/poad.js
CHANGED
|
@@ -255,7 +255,7 @@ const processCommands = (args) => {
|
|
|
255
255
|
} else {
|
|
256
256
|
if (POAD_COMMANDS[command]) {
|
|
257
257
|
// --json : rien d'autre que le JSON sur la sortie standard
|
|
258
|
-
if (!args.includes('--json')) console.log(' ');
|
|
258
|
+
if (!args.includes('--json') && !args.includes('--stdout')) console.log(' ');
|
|
259
259
|
|
|
260
260
|
const dir = args.join('/');
|
|
261
261
|
const px = parseCommandArgs(require(__dirname + '/project/cli'), args);
|
|
@@ -358,7 +358,7 @@ const main = async () => {
|
|
|
358
358
|
const framedMessage = boxen(styledMessage, boxenOptions);
|
|
359
359
|
|
|
360
360
|
// --json : l'avis de nouvelle version part sur stderr, la sortie reste du JSON
|
|
361
|
-
if (process.argv.includes('--json')) console.error(framedMessage);
|
|
361
|
+
if (process.argv.includes('--json') || process.argv.includes('--stdout')) console.error(framedMessage);
|
|
362
362
|
else console.log(framedMessage);
|
|
363
363
|
|
|
364
364
|
POAD_GLOBAL_COMMANDS = loadPoadCommands(__dirname + '/global/cli.js');
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// poad auth import <fichier> [--dry-run] [--trust-verified] [--send-confirmation] [--env <nom>] [--project <id>] [--yes] [--json]
|
|
2
|
+
// Comptes d'un autre système (e-mail, empreinte bcrypt, métadonnées, date d'origine) vers le
|
|
3
|
+
// service auth du projet : engine local, ou poad.io avec --env/--project.
|
|
4
|
+
module.exports = (args, raw) =>
|
|
5
|
+
require('../../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['dry-run', 'trust-verified', 'send-confirmation'] }, async ({ opts, positionals, out }) => {
|
|
6
|
+
const fs = require('fs');
|
|
7
|
+
const path = require('path');
|
|
8
|
+
const { usageError, EXIT } = require('../../utils/cloud/api');
|
|
9
|
+
const { confirm } = require('../../utils/cloud/cli');
|
|
10
|
+
const imp = require('../../utils/auth-import');
|
|
11
|
+
const { chalk } = out;
|
|
12
|
+
|
|
13
|
+
if (positionals.length !== 1) throw usageError('Usage: poad auth import <file.json|file.jsonl|file.csv> [--dry-run] [--trust-verified] [--send-confirmation] [--env <name>]');
|
|
14
|
+
const file = path.resolve(positionals[0]);
|
|
15
|
+
if (!fs.existsSync(file) || !fs.statSync(file).isFile()) throw usageError(`No such file: ${positionals[0]}`);
|
|
16
|
+
const parsed = imp.parseFile(file, fs.readFileSync(file, 'utf8'));
|
|
17
|
+
if (!parsed.rows.length) throw usageError('The file holds no account.');
|
|
18
|
+
|
|
19
|
+
const dryRun = Boolean(opts['dry-run']);
|
|
20
|
+
const trustVerified = Boolean(opts['trust-verified']);
|
|
21
|
+
const sendConfirmation = Boolean(opts['send-confirmation']);
|
|
22
|
+
const target = await require('../../utils/storage').target(opts);
|
|
23
|
+
const cloud = Boolean(opts.env || opts.project);
|
|
24
|
+
|
|
25
|
+
out.log(chalk.bold(`${dryRun ? 'Checking' : 'Importing'} ${parsed.rows.length} account${parsed.rows.length === 1 ? '' : 's'} from ${path.basename(file)} into ${target.label}${dryRun ? ' (dry run: nothing is written)' : ''}`));
|
|
26
|
+
if (trustVerified) out.log(chalk.yellowBright(' --trust-verified: lines with email_verified: true are imported verified, marked "verified by import"; the others stay unverified.'));
|
|
27
|
+
if (sendConfirmation) out.log(chalk.grey(' --send-confirmation: each account created without a verified address receives a confirmation e-mail.'));
|
|
28
|
+
if (cloud && !dryRun) await confirm(`Create the accounts of ${path.basename(file)} in ${target.label}?`, { yes: opts.yes, json: out.json });
|
|
29
|
+
|
|
30
|
+
const send = imp.authClient(target);
|
|
31
|
+
const { results, summary } = await imp.run(parsed, {
|
|
32
|
+
send,
|
|
33
|
+
dryRun,
|
|
34
|
+
trustVerified,
|
|
35
|
+
sendConfirmation,
|
|
36
|
+
onBatch: (done, total) => total > imp.BATCH && out.log(chalk.grey(` ${done}/${total} lines`)),
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
const n0 = (v) => Number(v) || 0;
|
|
40
|
+
const problems = results.filter((r) => r.status === 'invalid' || r.status === 'failed');
|
|
41
|
+
const existing = results.filter((r) => r.status === 'exists');
|
|
42
|
+
out.result({ file: path.basename(file), target: target.label, dry_run: dryRun, trust_verified: trustVerified, send_confirmation: sendConfirmation, summary, results });
|
|
43
|
+
if (!out.json) {
|
|
44
|
+
const n = (k) => summary[k];
|
|
45
|
+
out.log('');
|
|
46
|
+
if (dryRun) out.log(` ${chalk.greenBright(`${n('would_create')} to create`)} (${n('verified')} verified), ${n('exists')} already there, ${n('invalid')} invalid`);
|
|
47
|
+
else out.log(` ${chalk.greenBright(`${n('created')} created`)} (${n('verified')} verified), ${n('exists')} already there (left unchanged), ${n('invalid')} invalid, ${n('failed')} failed`);
|
|
48
|
+
if (sendConfirmation) {
|
|
49
|
+
if (dryRun) out.log(` ${n('confirmations_to_send')} confirmation e-mail${n('confirmations_to_send') === 1 ? '' : 's'} to send`);
|
|
50
|
+
else out.log(` ${n('confirmations_sent')} confirmation e-mail${n('confirmations_sent') === 1 ? '' : 's'} sent${n('confirmations_failed') ? chalk.redBright(`, ${n('confirmations_failed')} not sent (SMTP: poad logs auth)`) : ''}`);
|
|
51
|
+
}
|
|
52
|
+
if (n('verified_ignored')) out.log(chalk.yellowBright(` ${n('verified_ignored')} line${n('verified_ignored') === 1 ? '' : 's'} marked email_verified: true ${dryRun ? 'would be' : 'were'} imported unverified: add --trust-verified to keep the verified state of the file.`));
|
|
53
|
+
if (existing.length) {
|
|
54
|
+
out.log(chalk.grey(`\n Already there, skipped (never overwritten):`));
|
|
55
|
+
for (const r of existing.slice(0, 50)) out.log(chalk.grey(` line ${r.line} ${r.email}`));
|
|
56
|
+
if (existing.length > 50) out.log(chalk.grey(` … and ${existing.length - 50} more (--json for all)`));
|
|
57
|
+
}
|
|
58
|
+
if (problems.length) {
|
|
59
|
+
out.log(chalk.redBright(`\n ${dryRun ? 'Invalid lines' : 'Not imported'}:`));
|
|
60
|
+
for (const r of problems) out.log(` line ${r.line} ${r.email || '(no email)'} ${chalk.redBright(r.reason || r.status)}`);
|
|
61
|
+
}
|
|
62
|
+
const unverified = results.filter((r) => (r.status === 'created' || r.status === 'would_create') && !r.email_verified).length;
|
|
63
|
+
if (unverified && !sendConfirmation) out.log(chalk.grey(`\n ${unverified} account${unverified === 1 ? '' : 's'} without a verified address: if email confirmation is required, they confirm it (link received; --send-confirmation sends it) before their first password sign-in, and an external provider (Keycloak…) is linked only after that.`));
|
|
64
|
+
if (dryRun && !problems.length && n('would_create')) out.log(chalk.grey(`\n Run again without --dry-run to import.`));
|
|
65
|
+
if (!dryRun && problems.length) out.log(chalk.grey(`\n Fix these lines and run the same command again: accounts already imported are skipped.`));
|
|
66
|
+
}
|
|
67
|
+
return problems.length || n0(summary.confirmations_failed) ? EXIT.failed : 0;
|
|
68
|
+
});
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// poad auth : comptes du service auth du projet ; seule sous-commande pour l'instant : import
|
|
2
|
+
module.exports = (args, raw) => {
|
|
3
|
+
const words = (raw || []).map(String);
|
|
4
|
+
if (words[0] === 'import') return require('./import')(args, words.slice(1));
|
|
5
|
+
console.log('Usage: poad auth import <file.json|file.jsonl|file.csv> [--dry-run] [--trust-verified] [--send-confirmation] [--env <name>] [--project <id>] [--yes] [--json]');
|
|
6
|
+
if (words.length) process.exitCode = 2;
|
|
7
|
+
};
|
package/project/cli.js
CHANGED
|
@@ -22,6 +22,7 @@ module.exports = {
|
|
|
22
22
|
diff: 'Structure changes made outside the migrations (console SQL, psql…): diff to list them, diff <name> to write them as a migration, diff --discard to forget them',
|
|
23
23
|
url: 'Connection string of the poad.io database (password masked, copied to the clipboard; --show-password to print it)',
|
|
24
24
|
pull: 'Schema of the poad.io database into a new local migration (pg_dump --schema-only, never overwrites)',
|
|
25
|
+
import: 'Run an SQL file (plain pg_dump accepted, .sql.gz too) in one transaction, after a preview; dangerous statements refused before anything runs: import <file.sql> [--yes] [--env <name>]',
|
|
25
26
|
},
|
|
26
27
|
ref: {
|
|
27
28
|
description: 'Heavy reference tables (municipalities, code lists…) stored on poad.io, outside git and the project volume (S3, encrypted by poad), loaded everywhere; no local folder needed with --project',
|
|
@@ -47,6 +48,10 @@ module.exports = {
|
|
|
47
48
|
rm: 'Delete files, or a whole folder with -r (asks first, --yes outside a terminal): rm <bucket/path…> [-r] [--yes]',
|
|
48
49
|
sync: 'Align the storage of a poad.io environment on the local one (--pull: the other way): sync --env <name> [--pull] [--bucket <name>] [--prune] [--dry-run] [--copy-bytes] [--concurrency <n>]',
|
|
49
50
|
},
|
|
51
|
+
auth: {
|
|
52
|
+
description: 'Accounts of the project auth service, local engine or poad.io (--env <name>)',
|
|
53
|
+
import: 'Import accounts from another system (JSON, JSON Lines or CSV: email, bcrypt password_hash, metadata, original date): import <file> [--dry-run] [--trust-verified] [--send-confirmation] [--env <name>]',
|
|
54
|
+
},
|
|
50
55
|
link: 'Link this project to a poad.io project: [cloud] project = "<id>" in poad/config.toml (no secret): link [<id>]',
|
|
51
56
|
unlink: 'Remove the link to poad.io from poad/config.toml (nothing changes on poad.io)',
|
|
52
57
|
env: {
|
|
@@ -71,7 +76,7 @@ module.exports = {
|
|
|
71
76
|
function: 'Alias of poad functions',
|
|
72
77
|
flows: 'Flows of the project (automations in poad/flows/<name>.json, engine 0.18.0+, needs Valkey): new, list, run, runs, show, cancel; --env <name> for poad.io',
|
|
73
78
|
flow: 'Alias of poad flows',
|
|
74
|
-
source: 'Sources of the project (tables kept up to date from a URL, poad/sources/<name>.yaml, engine 0.64.0+): ls, refresh <name> [--force]
|
|
79
|
+
source: 'Sources of the project (tables kept up to date from a URL or an uploaded file, poad/sources/<name>.yaml, engine 0.64.0+): ls, refresh <name> [--force], import <file> [--table <t>], pull <name>; --env <name> for poad.io',
|
|
75
80
|
sources: 'Alias of poad source',
|
|
76
81
|
/* status: `[AI] Vérification du statut de l'environnement`,
|
|
77
82
|
gen: {
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// poad db import <fichier.sql> [--yes] [--json] [--env <nom> | --project <id>]
|
|
2
|
+
//
|
|
3
|
+
// Exécute un fichier SQL (pg_dump en texte accepté, .sql.gz aussi) dans la base du projet, local ou poad.io
|
|
4
|
+
// (engine 0.65.0+, meta 1.42.0) : le fichier est envoyé dans le bucket système poad-sources (envoi reprenable si le stockage le
|
|
5
|
+
// propose), l'engine le lit en flux et en donne l'aperçu (instructions, tables touchées, lignes de COPY,
|
|
6
|
+
// structure) en refusant AVANT toute exécution ce qui change des rôles, touche aux schémas du système ou aux
|
|
7
|
+
// fichiers du serveur ; puis, après confirmation (--yes hors d'un terminal), tout s'exécute en UNE transaction.
|
|
8
|
+
// Une erreur annule tout. La structure créée arrive au journal des changements : « poad db diff <nom> » l'écrit
|
|
9
|
+
// en migration.
|
|
10
|
+
const POLL_MS = 1000;
|
|
11
|
+
const TIMEOUT_MS = 120000;
|
|
12
|
+
|
|
13
|
+
/** Résumé d'un aperçu, en lignes. Pure. */
|
|
14
|
+
const previewLines = (p) => {
|
|
15
|
+
const chalk = require('chalk-v2');
|
|
16
|
+
const mb = (n) => `${(n / 1048576).toFixed(1)} MB`;
|
|
17
|
+
const out = [` ${p.statements} statement(s): ${p.by_kind.data} data, ${p.by_kind.structure} structure${p.by_kind.ignored ? `, ${p.by_kind.ignored} ignored (transaction of the import)` : ''}${p.copy_rows ? ` · ${p.copy_rows.toLocaleString('en-US')} row(s) by COPY` : ''} · ${mb(p.bytes)}`];
|
|
18
|
+
const tables = (p.tables || []).map((t) => `${t.name}${t.rows ? ` (${t.rows.toLocaleString('en-US')} rows)` : ''}`);
|
|
19
|
+
if (tables.length) out.push(chalk.grey(` tables: ${tables.slice(0, 15).join(', ')}${tables.length > 15 || p.tables_more ? `, +${tables.length - 15 + (p.tables_more || 0)} more` : ''}`));
|
|
20
|
+
for (const r of (p.refused || []).slice(0, 10)) out.push(chalk.redBright(` ✖ line ${r.line}: ${r.message}`));
|
|
21
|
+
if (p.refused_total > 10) out.push(chalk.redBright(` … ${p.refused_total - 10} more refused`));
|
|
22
|
+
return out;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
const main = async (args = {}, raw, deps = {}) => {
|
|
26
|
+
const chalk = require('chalk-v2');
|
|
27
|
+
const fs = require('fs');
|
|
28
|
+
const path = require('path');
|
|
29
|
+
const { findPoadDir } = require('../../utils/findpoad');
|
|
30
|
+
const { readConfig } = require('../../utils/config');
|
|
31
|
+
const flows = require('../flows');
|
|
32
|
+
const cwd = deps.cwd || process.cwd();
|
|
33
|
+
const doFetch = deps.fetch || fetch;
|
|
34
|
+
const sleep = deps.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
35
|
+
const started = deps.started || ((config) => require('../../utils/docker').isDockerExist(config.project_uuid));
|
|
36
|
+
const cloudTarget = deps.cloudTarget || ((opts) => require('../../utils/storage').cloudTarget(opts));
|
|
37
|
+
const confirm = deps.confirm || ((q) => require('@inquirer/prompts').confirm({ message: q, default: false }));
|
|
38
|
+
const fail = (message, code = 1) => {
|
|
39
|
+
process.exitCode = code;
|
|
40
|
+
console.log(chalk.redBright(message));
|
|
41
|
+
};
|
|
42
|
+
const typed = flows.cloudOptions(Array.isArray(raw) ? raw.map(String) : Object.keys(args));
|
|
43
|
+
if (typed.error) return fail(typed.error, 2);
|
|
44
|
+
const yes = typed.words.includes('--yes') || typed.words.includes('-y');
|
|
45
|
+
const json = typed.words.includes('--json');
|
|
46
|
+
const files = typed.words.filter((w) => !w.startsWith('-'));
|
|
47
|
+
const unknown = typed.words.find((w) => w.startsWith('-') && !['--yes', '-y', '--json'].includes(w));
|
|
48
|
+
if (unknown) return fail(`poad db import: unknown option ${unknown}.`, 2);
|
|
49
|
+
if (files.length !== 1) return fail('Usage: poad db import <file.sql> [--yes] [--json] [--env <name> | --project <id>]', 2);
|
|
50
|
+
const file = path.resolve(cwd, files[0]);
|
|
51
|
+
if (!fs.existsSync(file) || !fs.statSync(file).isFile()) return fail(`${files[0]}: no such file.`);
|
|
52
|
+
const cloud = Boolean(typed.env || typed.project);
|
|
53
|
+
const root = findPoadDir(cwd);
|
|
54
|
+
if (!root && !(cloud && typed.project)) return fail(cloud ? 'Not in a poad project folder: cd into one, or pass --project <id>.' : 'You are not in a poad project directory.');
|
|
55
|
+
|
|
56
|
+
let t;
|
|
57
|
+
if (cloud) {
|
|
58
|
+
try {
|
|
59
|
+
const c = await cloudTarget({ env: typed.env, project: typed.project });
|
|
60
|
+
t = { base: c.base, key: c.key, apikey: c.apikey || c.key, label: c.label, renew: c.renew, expires: c.renew && c.renew.first ? Date.parse(c.renew.first) : null };
|
|
61
|
+
} catch (err) {
|
|
62
|
+
return fail((err && err.message) || String(err), (err && err.exit) || 1);
|
|
63
|
+
}
|
|
64
|
+
} else {
|
|
65
|
+
const config = readConfig(root);
|
|
66
|
+
if (!(await started(config))) return fail('The project is not started: run "poad start".');
|
|
67
|
+
t = { base: `http://localhost:${config.web.port}`, key: config.auth.service, apikey: config.auth.service, label: 'local engine' };
|
|
68
|
+
}
|
|
69
|
+
const fresh = async () => {
|
|
70
|
+
if (!t.renew || !t.expires || t.expires - Date.now() > 60000) return;
|
|
71
|
+
const n = await t.renew.next();
|
|
72
|
+
Object.assign(t, { key: n.token, apikey: n.anon_key || t.apikey, expires: Date.parse(n.expires_at) });
|
|
73
|
+
};
|
|
74
|
+
const auth = async () => (await fresh(), { apikey: t.apikey, authorization: `Bearer ${t.key}` });
|
|
75
|
+
const call = async (method, route, body) => {
|
|
76
|
+
let res;
|
|
77
|
+
try {
|
|
78
|
+
res = await doFetch(`${t.base}${route}`, { method, headers: { ...(await auth()), ...(body === undefined ? {} : { 'content-type': 'application/json' }) }, ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(TIMEOUT_MS) });
|
|
79
|
+
} catch (err) {
|
|
80
|
+
throw new Error(`${t.label} does not answer on ${t.base}: ${(err && err.cause && err.cause.message) || (err && err.message) || err}`);
|
|
81
|
+
}
|
|
82
|
+
const data = await res.json().catch(() => null);
|
|
83
|
+
if (res.ok) return data || {};
|
|
84
|
+
const e = data && data.error && typeof data.error === 'object' ? data.error : null;
|
|
85
|
+
if (res.status === 404 && !e) throw new Error(`${t.label} has no SQL import (HTTP 404): engine 0.65.0 or later is needed.`);
|
|
86
|
+
throw new Error(e && e.message ? `${e.message}${e.hint ? ` (${e.hint})` : ''}` : `HTTP ${res.status}`);
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
try {
|
|
90
|
+
const size = fs.statSync(file).size;
|
|
91
|
+
const target = await call('POST', '/meta/v1/sources/uploads', { file_name: path.basename(file), size, kind: 'sql' });
|
|
92
|
+
const { uploadImportFile, progressLine } = deps.upload || require('../../utils/import-upload');
|
|
93
|
+
const bar = progressLine(path.basename(file));
|
|
94
|
+
const t0 = Date.now();
|
|
95
|
+
let sent;
|
|
96
|
+
try {
|
|
97
|
+
sent = await uploadImportFile({ base: t.base, file, target, onProgress: bar.update, fetch: doFetch, auth });
|
|
98
|
+
} finally {
|
|
99
|
+
bar.done();
|
|
100
|
+
}
|
|
101
|
+
if (!json) console.log(`${chalk.greenBright('✔')} ${path.basename(file)} ${chalk.grey(`${(size / 1048576).toFixed(1)} MB sent in ${((Date.now() - t0) / 1000).toFixed(1)} s (${sent.method === 'tus' ? 'resumable' : 'simple'} upload)${cloud ? ` ${t.label}` : ''}`)}`);
|
|
102
|
+
const preview = await call('POST', '/meta/v1/sql/import/preview', { path: target.path });
|
|
103
|
+
if (!json) {
|
|
104
|
+
console.log(`${chalk.bold('Preview')} ${chalk.grey('nothing has run yet')}`);
|
|
105
|
+
for (const line of previewLines(preview)) console.log(line);
|
|
106
|
+
}
|
|
107
|
+
if (preview.refused_total) {
|
|
108
|
+
if (json) console.log(JSON.stringify({ preview, imported: false }, null, 2));
|
|
109
|
+
return fail(`Refused before running anything: ${preview.refused_total} statement(s). Fix the file, then run poad db import again.`);
|
|
110
|
+
}
|
|
111
|
+
if (!yes) {
|
|
112
|
+
if (!process.stdin.isTTY) return fail('Outside a terminal, confirm with --yes.', 2);
|
|
113
|
+
if (!(await confirm(`Run these ${preview.statements} statement(s) in one transaction on ${t.label}?`))) return console.log(chalk.grey(' Nothing was run.'));
|
|
114
|
+
}
|
|
115
|
+
let job = await call('POST', '/meta/v1/sql/import', { path: target.path, confirm: true });
|
|
116
|
+
const tty = process.stderr.isTTY && !json;
|
|
117
|
+
while (job.status === 'analyzing' || job.status === 'running') {
|
|
118
|
+
await sleep(POLL_MS);
|
|
119
|
+
job = await call('GET', `/meta/v1/sql/import/${encodeURIComponent(job.id)}`);
|
|
120
|
+
if (tty) process.stderr.write(`\r ${job.status === 'analyzing' ? 'checking' : 'running'}: ${job.statements_done} / ${job.statements_total ?? '?'} statement(s)${job.rows_copied ? `, ${job.rows_copied.toLocaleString('en-US')} row(s) by COPY` : ''} `);
|
|
121
|
+
}
|
|
122
|
+
if (tty) process.stderr.write('\r\x1b[2K');
|
|
123
|
+
if (json) {
|
|
124
|
+
console.log(JSON.stringify({ preview, job }, null, 2));
|
|
125
|
+
if (job.status !== 'completed') process.exitCode = 1;
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
if (job.status !== 'completed') return fail(`Import cancelled, nothing was imported: ${job.error ? job.error.message : job.status}`);
|
|
129
|
+
console.log(`${chalk.greenBright('completed')} ${chalk.grey(`${job.statements_done} statement(s), ${job.rows_copied.toLocaleString('en-US')} row(s) by COPY, in ${((job.duration_ms || 0) / 1000).toFixed(1)} s, one transaction`)}`);
|
|
130
|
+
if (job.structure) console.log(chalk.grey(` Structure was created or changed: ${cloud ? 'keep it as a migration of the project' : '"poad db diff <name>" writes it as a migration'} so that it replays elsewhere.`));
|
|
131
|
+
console.log(chalk.grey(' Logs: poad logs meta event=sql_import'));
|
|
132
|
+
} catch (err) {
|
|
133
|
+
return fail((err && err.message) || String(err));
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
module.exports = (args, raw) => main(args, raw);
|
|
138
|
+
Object.assign(module.exports, { main, previewLines });
|
package/project/db/index.js
CHANGED
|
@@ -7,6 +7,7 @@ module.exports = async () => {
|
|
|
7
7
|
console.log(` ${chalk.cyanBright('poad db seed')} Apply poad/seed.sql (development data)`);
|
|
8
8
|
console.log(` ${chalk.cyanBright('poad db diff')} Structure changes made outside the migrations; "db diff <name>" writes them as a migration`);
|
|
9
9
|
console.log(` ${chalk.cyanBright('poad db url')} Connection string of the poad.io database (password masked unless --show-password)`);
|
|
10
|
+
console.log(` ${chalk.cyanBright('poad db import')} Run an SQL file in one transaction, after a preview (dangerous statements refused first)`);
|
|
10
11
|
console.log(` ${chalk.cyanBright('poad db pull')} Schema of the poad.io database into a new local migration`);
|
|
11
12
|
console.log(` ${chalk.cyanBright('poad migrate')} Apply pending migrations`);
|
|
12
13
|
console.log(' ');
|
package/project/deploy.js
CHANGED
|
@@ -97,6 +97,10 @@ module.exports = (args, raw) =>
|
|
|
97
97
|
else if (git.empty) out.log(chalk.grey(' git repository without any commit yet: no commit id'));
|
|
98
98
|
else out.log(chalk.grey(' not in a git repository: no commit id'));
|
|
99
99
|
for (const s of b.skipped) if (!large.some((f) => f.rel === s.path)) out.log(chalk.grey(` skipped ${s.path}: ${s.reason}`));
|
|
100
|
+
// Paquets npm des fonctions : seuls les fichiers que leurs imports atteignent partent
|
|
101
|
+
if (b.deps && b.deps.packages.length) out.log(chalk.grey(` npm packages of the functions: ${b.deps.packages.join(', ')} (${b.deps.files} file(s) of poad/functions/node_modules)`));
|
|
102
|
+
for (const m of (b.deps && b.deps.missing) || []) out.log(chalk.yellowBright(` ⚠ ${m.from} imports "${m.spec}", not installed in poad/functions/node_modules: run "npm install ${m.spec}" in poad/functions, or this function will not build on poad.io.`));
|
|
103
|
+
if (b.deps && b.deps.outside.length) out.log(chalk.yellowBright(` ⚠ ${b.deps.outside.join(', ')}: installed above poad/functions, not sent. Install in poad/functions (npm install there).`));
|
|
100
104
|
for (const f of large) out.log(chalk.grey(` ${f.rel} (${kb(f.size)}): too large for git: reference store, sent and loaded only if it changed (sha256)`));
|
|
101
105
|
for (const f of ignored.tracked) out.log(chalk.yellowBright(` ⚠ poad/${f.rel} is tracked by git although it is too large: git rm --cached poad/${f.rel}`));
|
|
102
106
|
|
package/project/logs.js
CHANGED
|
@@ -29,6 +29,8 @@
|
|
|
29
29
|
// realtime_closed, realtime_error, realtime_change_summary)
|
|
30
30
|
// poad logs app front=<id> un front dessiné dans poad (engine 0.46+) : le serveur du moteur
|
|
31
31
|
// et le navigateur (source=server|browser) ; page=<id> pour une page
|
|
32
|
+
// poad logs storage upload=<id> un envoi en morceaux (storage 0.6+) : début, interruption,
|
|
33
|
+
// reprise, fin, annulation, abandon ; bucket=<id> pour un bucket
|
|
32
34
|
// poad logs limit=500 nombre de lignes (100 par défaut)
|
|
33
35
|
// poad logs -f | --follow suivi en direct
|
|
34
36
|
// poad logs --json une ligne JSON par entrée (pour jq)
|
package/project/source.js
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
// poad source ls sources du projet (poad/sources/<nom>.yaml) et leur état
|
|
2
2
|
// poad source refresh <nom> [--force] synchronise une source maintenant et suit son exécution
|
|
3
|
+
// poad source import <fichier> [--table t] charge un fichier (CSV, JSON, GeoJSON, JSONL, gzip) dans une table :
|
|
4
|
+
// source « Fichier envoyé » (nouvelle, ou nouvelle version d'une source envoyée)
|
|
5
|
+
// poad source pull <nom> [--force] rapatrie la déclaration d'une source (créée dans la console
|
|
6
|
+
// de poad.io avec --env) dans poad/sources/<nom>.yaml
|
|
3
7
|
//
|
|
4
8
|
// Une source est une table du projet tenue à jour depuis une adresse (JSON,
|
|
5
9
|
// GeoJSON, CSV, JSONL) : l'engine (0.64.0+, meta /meta/v1/sources) crée la
|
|
@@ -15,11 +19,11 @@
|
|
|
15
19
|
// clé anon : jamais affichés. En local : la clé service_role du projet.
|
|
16
20
|
const flows = require('./flows');
|
|
17
21
|
|
|
18
|
-
const NAME_RE = /^[a-z][a-z0-9-]{0,55}$/; // meta, sources.ts : SOURCE_NAME_RE
|
|
22
|
+
const NAME_RE = /^(?:[a-z][a-z0-9-]{0,55}|[a-z_][a-z0-9_]{0,62})$/; // meta, sources.ts : SOURCE_NAME_RE (nom de table, ou d'avant 0.65.0)
|
|
19
23
|
const POLL_MS = 1000;
|
|
20
|
-
const TIMEOUT_MS =
|
|
24
|
+
const TIMEOUT_MS = 30000;
|
|
21
25
|
const FINAL = ['completed', 'failed', 'cancelled'];
|
|
22
|
-
const USAGE = 'Usage: poad source ls | refresh <name> [--force] [--detach], and --env <name> | --project <id> for poad.io';
|
|
26
|
+
const USAGE = 'Usage: poad source ls | refresh <name> [--force] [--detach] | import <file> [--table <table>] [--name <source>] | pull <name> [--force] [--stdout], and --env <name> | --project <id> for poad.io';
|
|
23
27
|
|
|
24
28
|
// Engine 0.64.0 et plus : sources (/meta/v1/sources), déclarées dans poad/sources
|
|
25
29
|
const supportsSources = (config) => {
|
|
@@ -99,6 +103,7 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
99
103
|
const path = require('path');
|
|
100
104
|
const { findPoadDir } = require('../utils/findpoad');
|
|
101
105
|
const { readConfig } = require('../utils/config');
|
|
106
|
+
const fs = require('fs');
|
|
102
107
|
const cwd = deps.cwd || process.cwd();
|
|
103
108
|
const doFetch = deps.fetch || fetch;
|
|
104
109
|
const sleep = deps.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
@@ -170,7 +175,9 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
170
175
|
if (res.status >= 200 && res.status < 300) return data || {};
|
|
171
176
|
const error = data && typeof data === 'object' && data.error && typeof data.error === 'object' ? data.error : null;
|
|
172
177
|
if (error && error.message) throw new SourceError(`${error.message}${error.hint ? ` (${error.hint})` : ''}`);
|
|
173
|
-
|
|
178
|
+
// Fichier envoyé, échantillon, rapprochement : engine 0.65.0 ; le reste : 0.64.0
|
|
179
|
+
const needs = /\/sources\/(uploads|sample|propose|preview|tables)\b/.test(route) ? '0.65.0' : '0.64.0';
|
|
180
|
+
if (res.status === 404) throw new SourceError(`${t.cloud ? t.label : 'The engine'} has no ${needs === '0.65.0' ? 'such sources API' : 'sources API'} (HTTP 404): engine ${needs} or later is needed.`);
|
|
174
181
|
if (res.status === 401 || res.status === 403) throw new SourceError(t.cloud ? `${t.label} refused the access (HTTP ${res.status}): "poad login" again, or check that you own the project.` : `the engine refused the service_role key (HTTP ${res.status})`);
|
|
175
182
|
throw new SourceError(`HTTP ${res.status}`);
|
|
176
183
|
};
|
|
@@ -185,43 +192,8 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
185
192
|
}
|
|
186
193
|
};
|
|
187
194
|
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
if (words.length > 1) return fail(USAGE, 2);
|
|
191
|
-
const t = await ready();
|
|
192
|
-
if (!t) return;
|
|
193
|
-
const list = await guard(() => call(t, 'GET', '/meta/v1/sources'));
|
|
194
|
-
if (!list) return;
|
|
195
|
-
if (json) return console.log(JSON.stringify(list.sources || [], null, 2));
|
|
196
|
-
const all = list.sources || [];
|
|
197
|
-
console.log(`${chalk.bold('Sources')} ${chalk.grey(cloud ? t.label : 'poad/sources')}`);
|
|
198
|
-
console.log(' ');
|
|
199
|
-
if (!all.length) return console.log(chalk.grey(` None yet: declare one in poad/sources/<name>.yaml${cloud ? ', then "poad deploy"' : ''}.`));
|
|
200
|
-
const width = Math.max(...all.map((s) => String(s.name).length));
|
|
201
|
-
for (const s of all) for (const line of sourceLines(s, width)) console.log(line);
|
|
202
|
-
if (all.some((s) => !s.valid)) process.exitCode = 1;
|
|
203
|
-
return;
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
// ------------------------------------------------------------------ refresh
|
|
207
|
-
if (command === 'refresh' || command === 'sync') {
|
|
208
|
-
let name = null;
|
|
209
|
-
let force = false;
|
|
210
|
-
let wait = true;
|
|
211
|
-
for (const w of words.slice(1)) {
|
|
212
|
-
if (w === '--force') force = true;
|
|
213
|
-
else if (w === '--detach' || w === '--no-wait' || w === '-d') wait = false;
|
|
214
|
-
else if (w === '--wait') wait = true;
|
|
215
|
-
else if (w.startsWith('-')) return fail(`poad source refresh: unknown option ${w}.`, 2);
|
|
216
|
-
else if (name === null) name = w;
|
|
217
|
-
else return fail(`poad source refresh: one source at a time ("${w}").`, 2);
|
|
218
|
-
}
|
|
219
|
-
if (!name) return fail('Usage: poad source refresh <name> [--force] [--detach] [--env <name>] ("poad source ls" lists them).', 2);
|
|
220
|
-
if (!NAME_RE.test(name)) return fail(`"${name}" is not a source name (poad/sources/<name>.yaml: a-z, 0-9 and "-", a letter first, 56 characters at most).`, 2);
|
|
221
|
-
const t = await ready();
|
|
222
|
-
if (!t) return;
|
|
223
|
-
const started = await guard(() => call(t, 'POST', `/meta/v1/sources/${encodeURIComponent(name)}/refresh`, { force }));
|
|
224
|
-
if (!started) return;
|
|
195
|
+
/** Suit l'exécution d'une synchronisation lancée (started : réponse de /refresh ou de la création) jusqu'au bilan */
|
|
196
|
+
const followRun = async (t, name, started, force, wait) => {
|
|
225
197
|
const runId = started.run_id;
|
|
226
198
|
if (!runId) return fail('Source not refreshed: the engine gave no run id.');
|
|
227
199
|
if (!wait) {
|
|
@@ -277,6 +249,192 @@ const main = async (args = {}, raw, deps = {}) => {
|
|
|
277
249
|
if (guardRefused(error) && !force) console.log(chalk.grey(` Nothing was changed. If the source is right: poad source refresh ${name} --force${where}`));
|
|
278
250
|
console.log(chalk.grey(` Details: poad flows show ${runId}${where} · poad logs source=${name}`));
|
|
279
251
|
return;
|
|
252
|
+
};
|
|
253
|
+
|
|
254
|
+
// ------------------------------------------------------------------ ls
|
|
255
|
+
if (command === 'ls' || command === 'list') {
|
|
256
|
+
if (words.length > 1) return fail(USAGE, 2);
|
|
257
|
+
const t = await ready();
|
|
258
|
+
if (!t) return;
|
|
259
|
+
const list = await guard(() => call(t, 'GET', '/meta/v1/sources'));
|
|
260
|
+
if (!list) return;
|
|
261
|
+
if (json) return console.log(JSON.stringify(list.sources || [], null, 2));
|
|
262
|
+
const all = list.sources || [];
|
|
263
|
+
console.log(`${chalk.bold('Sources')} ${chalk.grey(cloud ? t.label : 'poad/sources')}`);
|
|
264
|
+
console.log(' ');
|
|
265
|
+
if (!all.length) return console.log(chalk.grey(` None yet: declare one in poad/sources/<name>.yaml${cloud ? ', then "poad deploy"' : ''}.`));
|
|
266
|
+
const width = Math.max(...all.map((s) => String(s.name).length));
|
|
267
|
+
for (const s of all) for (const line of sourceLines(s, width)) console.log(line);
|
|
268
|
+
if (all.some((s) => !s.valid)) process.exitCode = 1;
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// ------------------------------------------------------------------ refresh
|
|
273
|
+
if (command === 'refresh' || command === 'sync') {
|
|
274
|
+
let name = null;
|
|
275
|
+
let force = false;
|
|
276
|
+
let wait = true;
|
|
277
|
+
for (const w of words.slice(1)) {
|
|
278
|
+
if (w === '--force') force = true;
|
|
279
|
+
else if (w === '--detach' || w === '--no-wait' || w === '-d') wait = false;
|
|
280
|
+
else if (w === '--wait') wait = true;
|
|
281
|
+
else if (w.startsWith('-')) return fail(`poad source refresh: unknown option ${w}.`, 2);
|
|
282
|
+
else if (name === null) name = w;
|
|
283
|
+
else return fail(`poad source refresh: one source at a time ("${w}").`, 2);
|
|
284
|
+
}
|
|
285
|
+
if (!name) return fail('Usage: poad source refresh <name> [--force] [--detach] [--env <name>] ("poad source ls" lists them).', 2);
|
|
286
|
+
if (!NAME_RE.test(name)) return fail(`"${name}" is not a source name (poad/sources/<name>.yaml: a-z, 0-9 and "-", a letter first, 56 characters at most).`, 2);
|
|
287
|
+
const t = await ready();
|
|
288
|
+
if (!t) return;
|
|
289
|
+
const started = await guard(() => call(t, 'POST', `/meta/v1/sources/${encodeURIComponent(name)}/refresh`, { force }));
|
|
290
|
+
if (!started) return;
|
|
291
|
+
return followRun(t, name, started, force, wait);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// ------------------------------------------------------------------ import
|
|
295
|
+
// Un fichier (CSV, JSON, GeoJSON, JSONL, gzip accepté) chargé dans une table, par une source « Fichier envoyé » :
|
|
296
|
+
// envoyé dans le bucket système poad-sources, lu en flux par le flow de la source (aucune limite de taille).
|
|
297
|
+
// Nouvelle source : échantillon lu par l'engine, nouvelle table (ou --existing), déclaration écrite, chargement.
|
|
298
|
+
// Source déjà envoyée (--name, ou le nom tiré du fichier) : nouvelle version au même chemin, puis chargement.
|
|
299
|
+
if (command === 'import') {
|
|
300
|
+
const opts = { file: null, name: null, table: null, key: null, format: null, root: null, existing: false, wait: true };
|
|
301
|
+
const rest = words.slice(1);
|
|
302
|
+
for (let i = 0; i < rest.length; i++) {
|
|
303
|
+
const w = rest[i];
|
|
304
|
+
const value = () => {
|
|
305
|
+
const v = rest[++i];
|
|
306
|
+
if (v === undefined || v.startsWith('--')) throw new SourceError(`poad source import: ${w} needs a value.`);
|
|
307
|
+
return v;
|
|
308
|
+
};
|
|
309
|
+
try {
|
|
310
|
+
if (w === '--name') opts.name = value();
|
|
311
|
+
else if (w === '--table') opts.table = value().replace(/^public\./, '');
|
|
312
|
+
else if (w === '--key') opts.key = value().split(',').map((x) => x.trim()).filter(Boolean);
|
|
313
|
+
else if (w === '--format') opts.format = value();
|
|
314
|
+
else if (w === '--root') opts.root = value();
|
|
315
|
+
else if (w === '--existing') opts.existing = true;
|
|
316
|
+
else if (w === '--detach' || w === '-d') opts.wait = false;
|
|
317
|
+
else if (w.startsWith('-')) return fail(`poad source import: unknown option ${w}.`, 2);
|
|
318
|
+
else if (opts.file === null) opts.file = w;
|
|
319
|
+
else return fail(`poad source import: one file at a time ("${w}").`, 2);
|
|
320
|
+
} catch (err) {
|
|
321
|
+
return fail(err.message, 2);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
const usage = 'Usage: poad source import <file> [--table <table>] [--name <source>] [--key <col,…>] [--existing] [--format csv|json|geojson|jsonl] [--root <path>] [--detach] [--env <name>]';
|
|
325
|
+
if (!opts.file) return fail(usage, 2);
|
|
326
|
+
const file = path.resolve(cwd, opts.file);
|
|
327
|
+
if (!fs.existsSync(file) || !fs.statSync(file).isFile()) return fail(`${opts.file}: no such file.`);
|
|
328
|
+
if (opts.format && !['csv', 'json', 'geojson', 'jsonl'].includes(opts.format)) return fail(`--format: csv, json, geojson or jsonl (got "${opts.format}").`, 2);
|
|
329
|
+
if (opts.existing && !opts.table) return fail('--existing needs --table <table> (the table of the project to load).', 2);
|
|
330
|
+
const base = path.basename(file).replace(/\.gz$/i, '').replace(/\.[a-z0-9]+$/i, '');
|
|
331
|
+
const { cleanIdent } = require('../utils/naming');
|
|
332
|
+
// Nouvelle table : nom nettoyé (accents, espaces, chiffre en tête…) ; table existante : telle quelle
|
|
333
|
+
const table = opts.existing ? String(opts.table).replace(/^public\./, '') : cleanIdent(String(opts.table || base).replace(/^public\./, ''), 'table');
|
|
334
|
+
if (opts.table && !opts.existing && table !== String(opts.table).replace(/^public\./, '')) console.log(chalk.grey(` table name cleaned: "${opts.table}" → ${table}`));
|
|
335
|
+
const t = await ready();
|
|
336
|
+
if (!t) return;
|
|
337
|
+
const size = fs.statSync(file).size;
|
|
338
|
+
const list = await guard(() => call(t, 'GET', '/meta/v1/sources'));
|
|
339
|
+
if (!list) return;
|
|
340
|
+
// Le nom d'une source est celui de sa table (engine 0.65.0). --name reste accepté : une source existante de ce
|
|
341
|
+
// nom (même d'avant 0.65.0) reçoit une nouvelle version ; sinon il est ignoré s'il diffère de la table.
|
|
342
|
+
const byName = (n) => (list.sources || []).find((x) => x.name === n);
|
|
343
|
+
let name = table;
|
|
344
|
+
if (opts.name && byName(opts.name)) name = opts.name;
|
|
345
|
+
else if (opts.name && opts.name !== table) console.log(chalk.yellowBright(` --name ${opts.name} ignored: a source is named after its table (${table}).`));
|
|
346
|
+
if (!NAME_RE.test(name)) return fail(`"${name}" is not a source name: --table <table> (a-z, 0-9 and "_").`, 2);
|
|
347
|
+
const known = byName(name);
|
|
348
|
+
if (known && !(known.origin && known.origin.kind === 'upload')) return fail(`The source "${name}" reads an address: "poad source refresh ${name}" reloads it (or --table <another table>).`);
|
|
349
|
+
const target = await guard(() => call(t, 'POST', '/meta/v1/sources/uploads', known ? { source: name, size, file_name: path.basename(file) } : { file_name: path.basename(file), size, kind: 'source' }));
|
|
350
|
+
if (!target) return;
|
|
351
|
+
const { uploadImportFile, progressLine } = deps.upload || require('../utils/import-upload');
|
|
352
|
+
const bar = progressLine(path.basename(file));
|
|
353
|
+
const startedAt = Date.now();
|
|
354
|
+
let sent;
|
|
355
|
+
try {
|
|
356
|
+
sent = await uploadImportFile({ base: t.base, file, target, onProgress: bar.update, fetch: doFetch, auth: async () => (await fresh(t), { apikey: t.apikey, authorization: `Bearer ${t.key}` }) });
|
|
357
|
+
} catch (err) {
|
|
358
|
+
bar.done();
|
|
359
|
+
return fail(`Upload failed: ${(err && err.message) || err}`);
|
|
360
|
+
} finally {
|
|
361
|
+
bar.done();
|
|
362
|
+
}
|
|
363
|
+
console.log(`${chalk.greenBright('✔')} ${path.basename(file)} ${chalk.grey(`${(size / 1048576).toFixed(1)} MB sent in ${((Date.now() - startedAt) / 1000).toFixed(1)} s (${sent.method === 'tus' ? 'resumable' : 'simple'} upload) → ${target.path}`)}`);
|
|
364
|
+
let started;
|
|
365
|
+
if (known) {
|
|
366
|
+
// Nouvelle version : même chemin, la déclaration ne change pas
|
|
367
|
+
started = await guard(() => call(t, 'POST', `/meta/v1/sources/${encodeURIComponent(name)}/refresh`, { force: false }));
|
|
368
|
+
} else {
|
|
369
|
+
const sample = await guard(() => call(t, 'POST', '/meta/v1/sources/sample', { path: target.path, ...(opts.format ? { format: opts.format } : {}), ...(opts.root ? { root: opts.root } : {}) }));
|
|
370
|
+
if (!sample) return;
|
|
371
|
+
console.log(chalk.grey(` ${sample.format}${sample.gzip ? ' (gzip)' : ''}, ${(sample.fields || []).length} field(s): ${(sample.fields || []).map((f) => `${f.path} ${f.type}`).slice(0, 12).join(', ')}${(sample.fields || []).length > 12 ? '…' : ''}`));
|
|
372
|
+
const proposal = await guard(() => call(t, 'POST', '/meta/v1/sources/propose', { fields: sample.fields, format: sample.format, path: target.path, table, ...(opts.existing ? { existing: true, name } : {}) }));
|
|
373
|
+
if (!proposal) return;
|
|
374
|
+
let columns;
|
|
375
|
+
let key;
|
|
376
|
+
if (opts.existing) {
|
|
377
|
+
const blocking = (proposal.problems || []).filter((p) => p.level === 'error');
|
|
378
|
+
if (blocking.length) return fail(`public.${table} cannot take this file: ${blocking.map((p) => p.message).join(' ; ')}`);
|
|
379
|
+
columns = (proposal.matches || []).filter((m) => m.field).map((m) => ({ name: m.column, from: m.field, ...(m.transform ? { transform: m.transform } : {}) }));
|
|
380
|
+
key = opts.key || proposal.key || [];
|
|
381
|
+
} else {
|
|
382
|
+
if (proposal.table_exists) return fail(`public.${table} already exists: --table <another name>, or --existing to load into it.`);
|
|
383
|
+
columns = (proposal.columns || []).filter((c) => c.include !== false).map((c) => ({ name: c.name, from: c.from, type: c.type, ...(c.transform ? { transform: c.transform } : {}) }));
|
|
384
|
+
key = opts.key || proposal.key || [];
|
|
385
|
+
}
|
|
386
|
+
if (!key.length) return fail(`No key found for public.${table}: --key <column> (a column whose values are unique).`, 2);
|
|
387
|
+
const draft = {
|
|
388
|
+
mode: 'imported',
|
|
389
|
+
origin: { kind: 'upload', path: target.path, format: sample.format, ...(sample.root ? { root: sample.root } : {}), ...(sample.format === 'csv' && sample.csv ? { csv: { delimiter: sample.csv.delimiter, ...(sample.csv.encoding ? { encoding: sample.csv.encoding } : {}) } } : {}) },
|
|
390
|
+
table: `public.${table}`,
|
|
391
|
+
existing: opts.existing,
|
|
392
|
+
key,
|
|
393
|
+
columns,
|
|
394
|
+
};
|
|
395
|
+
const created = await guard(() => call(t, 'POST', '/meta/v1/sources', { draft, run: true, ...(opts.existing ? { confirm: { existing: true } } : {}) }));
|
|
396
|
+
if (!created) return;
|
|
397
|
+
if (created.name) name = created.name;
|
|
398
|
+
for (const w of created.warnings || []) console.log(chalk.yellowBright(` ${w}`));
|
|
399
|
+
console.log(`${chalk.greenBright('✔')} source ${chalk.bold(name)} ${chalk.grey(`${created.file || 'created in the console'} → public.${table}, key ${key.join(', ')}`)}`);
|
|
400
|
+
started = created.run_id ? { run_id: created.run_id, flow: `source-${name.replace(/_/g, '-')}` } : null;
|
|
401
|
+
if (!started) return fail('The source was declared but no load was started: poad source refresh ' + name + where);
|
|
402
|
+
}
|
|
403
|
+
if (!started) return;
|
|
404
|
+
return followRun(t, name, started, false, opts.wait);
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
// ------------------------------------------------------------------ pull
|
|
408
|
+
// La déclaration d'une source (créée dans la console hébergée, gardée en base) écrite dans poad/sources :
|
|
409
|
+
// le fichier fait foi ensuite (poad deploy l'envoie ; sur poad.io, un fichier déployé l'emporte).
|
|
410
|
+
if (command === 'pull') {
|
|
411
|
+
let name = null;
|
|
412
|
+
let force = false;
|
|
413
|
+
let toStdout = false;
|
|
414
|
+
for (const w of words.slice(1)) {
|
|
415
|
+
if (w === '--force' || w === '-f') force = true;
|
|
416
|
+
else if (w === '--stdout') toStdout = true;
|
|
417
|
+
else if (w.startsWith('-')) return fail(`poad source pull: unknown option ${w}.`, 2);
|
|
418
|
+
else if (name === null) name = w;
|
|
419
|
+
else return fail(`poad source pull: one source at a time ("${w}").`, 2);
|
|
420
|
+
}
|
|
421
|
+
if (!name) return fail('Usage: poad source pull <name> [--force] [--stdout] --env <name> ("poad source ls --env <name>" lists them).', 2);
|
|
422
|
+
if (!NAME_RE.test(name)) return fail(`"${name}" is not a source name (the name of its table: a-z, 0-9 and "_"; or, before engine 0.65.0, a-z, 0-9 and "-").`, 2);
|
|
423
|
+
if (!root && !toStdout) return fail('Not in a poad project folder: cd into one, or pass --stdout.');
|
|
424
|
+
const target = root ? path.join(path.dirname(root), 'sources', `${name}.yaml`) : null;
|
|
425
|
+
if (target && !toStdout && !force && (fs.existsSync(target) || fs.existsSync(target.replace(/\.yaml$/, '.yml'))))
|
|
426
|
+
return fail(`poad/sources/${name}.yaml already exists: --force replaces it (check "git diff" afterwards), or --stdout prints the declaration.`);
|
|
427
|
+
const t = await ready();
|
|
428
|
+
if (!t) return;
|
|
429
|
+
const got = await guard(() => call(t, 'GET', `/meta/v1/sources/${encodeURIComponent(name)}/yaml`));
|
|
430
|
+
if (!got) return;
|
|
431
|
+
if (typeof got.yaml !== 'string' || !got.yaml.trim()) return fail('The engine gave no declaration.');
|
|
432
|
+
if (toStdout) return process.stdout.write(got.yaml.endsWith('\n') ? got.yaml : `${got.yaml}\n`);
|
|
433
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
434
|
+
fs.writeFileSync(target, got.yaml.endsWith('\n') ? got.yaml : `${got.yaml}\n`);
|
|
435
|
+
console.log(`${chalk.greenBright('✔')} poad/sources/${name}.yaml ${chalk.grey(`from ${cloud ? t.label : 'the local engine'}${got.stored === 'console' ? ', created in the console' : ''}`)}`);
|
|
436
|
+
if (got.stored === 'console' && cloud) console.log(chalk.grey(` Commit it, then "poad deploy${where}": the deployed file then wins over the console copy.`));
|
|
437
|
+
return;
|
|
280
438
|
}
|
|
281
439
|
|
|
282
440
|
fail(USAGE, 2);
|