poad 2.61.2 → 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 +12 -1
- 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 +11 -3
- 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 +444 -0
- package/project/sources.js +2 -0
- package/project/storage/cp.js +48 -16
- package/project/storage/ls.js +20 -6
- package/project/storage/mv.js +5 -5
- package/project/storage/sync.js +101 -0
- 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 +282 -0
- package/test/storage-sync.test.js +283 -0
- package/test/storage-tus.test.js +169 -0
- package/test/storage.test.js +240 -4
- package/utils/auth-import.js +204 -0
- package/utils/cloud/bundle.js +18 -4
- package/utils/cloud/deps.js +297 -0
- package/utils/data.js +41 -0
- package/utils/help-details.js +113 -5
- 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 +122 -18
- package/utils/storage-sync.js +277 -0
- package/utils/storage-tus.js +201 -0
- package/utils/storage.js +130 -3
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,10 +161,15 @@ 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 »)
|
|
162
169
|
...(withFronts ? fronts.engineEnv(config) : []),
|
|
170
|
+
// Identité du projet (project_uuid, projet poad.io lié) : poad storage sync entre
|
|
171
|
+
// environnements d'un même projet seulement (storage 0.4.0+)
|
|
172
|
+
...require('../utils/storage').engineEnv(config),
|
|
163
173
|
],
|
|
164
174
|
ExposedPorts: { '5432/tcp': {}, '8000/tcp': {}, ...gelf.exposed, ...frontPorts.exposed },
|
|
165
175
|
HostConfig: {
|
|
@@ -174,7 +184,8 @@ module.exports = async (args = {}) => {
|
|
|
174
184
|
// poad/auth et poad/storage : manifestes versionnés des réglages d'auth et des buckets.
|
|
175
185
|
// poad/reference : contenu des tables de référence, un fichier par table
|
|
176
186
|
// poad/api : définitions de l'API publiée du projet, un fichier par version
|
|
177
|
-
|
|
187
|
+
// poad/sources : déclarations des sources (<nom>.yaml), lues par meta (engine 0.64.0+)
|
|
188
|
+
Binds: [path.dirname(root) + '/data:/data', `${ensureDir(path.join(path.dirname(root), 'migrations'))}:/project/migrations`, `${ensureDir(path.join(path.dirname(root), 'credentials'))}:/project/credentials`, `${ensureDir(path.join(path.dirname(root), 'functions'))}:/project/functions`, `${ensureDir(path.join(path.dirname(root), 'variables'))}:/project/variables`, `${ensureDir(path.join(path.dirname(root), 'types'))}:/project/types`, `${ensureDir(path.join(path.dirname(root), 'flows'))}:/project/flows`, `${ensureDir(path.join(path.dirname(root), 'auth'))}:/project/auth`, `${ensureDir(path.join(path.dirname(root), 'storage'))}:/project/storage`, `${ensureDir(path.join(path.dirname(root), 'reference'))}:/project/reference`, `${ensureDir(path.join(path.dirname(root), 'sources'))}:/project/sources`, `${ensureDir(path.join(path.dirname(root), 'api'))}:/project/api`],
|
|
178
189
|
// Services lancés sur la machine : joignables depuis l'engine, y
|
|
179
190
|
// compris sous Linux
|
|
180
191
|
ExtraHosts: ['host.docker.internal:host-gateway'],
|
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',
|
|
@@ -40,11 +41,16 @@ module.exports = {
|
|
|
40
41
|
rm: 'Same as poad ref rm',
|
|
41
42
|
},
|
|
42
43
|
storage: {
|
|
43
|
-
description: 'Files of the project storage, local engine or poad.io (--env <name>): ls, cp (disk ↔ storage, storage → storage), mv, rm; a storage path is bucket/path (poad:bucket/path for cp)',
|
|
44
|
+
description: 'Files of the project storage, local engine or poad.io (--env <name>): ls, cp (disk ↔ storage, storage → storage), mv, rm, sync (local ↔ poad.io); a storage path is bucket/path (poad:bucket/path for cp)',
|
|
44
45
|
ls: 'Buckets, or the files and folders of a folder: ls [bucket[/folder]] [-r] [--json]',
|
|
45
|
-
cp: 'Copy files, -r for a folder: cp ./a.png poad:images/ | cp poad:images/a.png ./ | cp -r poad:images/2024 poad:archives/',
|
|
46
|
-
mv: 'Move or rename inside the storage (copy, then delete the source): mv <bucket/path> <bucket/path> [-r]',
|
|
46
|
+
cp: 'Copy files, -r for a folder: cp ./a.png poad:images/ | cp poad:images/a.png ./ | cp -r poad:images/2024 poad:archives/ [--concurrency <n>]',
|
|
47
|
+
mv: 'Move or rename inside the storage (copy, then delete the source): mv <bucket/path> <bucket/path> [-r] [--concurrency <n>]',
|
|
47
48
|
rm: 'Delete files, or a whole folder with -r (asks first, --yes outside a terminal): rm <bucket/path…> [-r] [--yes]',
|
|
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>]',
|
|
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>]',
|
|
48
54
|
},
|
|
49
55
|
link: 'Link this project to a poad.io project: [cloud] project = "<id>" in poad/config.toml (no secret): link [<id>]',
|
|
50
56
|
unlink: 'Remove the link to poad.io from poad/config.toml (nothing changes on poad.io)',
|
|
@@ -70,6 +76,8 @@ module.exports = {
|
|
|
70
76
|
function: 'Alias of poad functions',
|
|
71
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',
|
|
72
78
|
flow: 'Alias of poad flows',
|
|
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',
|
|
80
|
+
sources: 'Alias of poad source',
|
|
73
81
|
/* status: `[AI] Vérification du statut de l'environnement`,
|
|
74
82
|
gen: {
|
|
75
83
|
description: 'Génération automatique des éléments clés pour votre projet',
|
|
@@ -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)
|