poad 2.63.0 → 2.65.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 +4 -3
- package/project/auth/import.js +68 -0
- package/project/auth/index.js +7 -0
- package/project/cli.js +7 -2
- package/project/db/import.js +138 -0
- package/project/db/index.js +1 -0
- package/project/deploy.js +22 -0
- package/project/gen/types.js +10 -2
- package/project/logs.js +2 -0
- package/project/source.js +341 -42
- package/project/storage/cp.js +4 -2
- package/project/upgrade.js +10 -0
- package/test/api-exposure.test.js +60 -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 +226 -0
- package/test/logs.test.js +12 -0
- package/test/naming.test.js +18 -0
- package/test/source.test.js +116 -0
- package/test/storage-tus.test.js +169 -0
- package/test/storage.test.js +7 -0
- package/utils/api-exposure/api-exposure.sql +42 -0
- package/utils/api-exposure/index.js +97 -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 +57 -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
|
@@ -224,7 +224,8 @@ const parseCommandArgs = (commands, args) => {
|
|
|
224
224
|
|
|
225
225
|
for (let i = 0; i < args.length; i++) {
|
|
226
226
|
const currentPath = args[i];
|
|
227
|
-
|
|
227
|
+
// Propre à l'objet seulement : sinon « poad source link » trouverait String.prototype.link
|
|
228
|
+
if (currentCommands && typeof currentCommands === 'object' && Object.prototype.hasOwnProperty.call(currentCommands, currentPath) && currentCommands[currentPath]) {
|
|
228
229
|
// Si le chemin est valide, ajoute à dir et descend dans la structure
|
|
229
230
|
dir.push(currentPath);
|
|
230
231
|
currentCommands = currentCommands[currentPath];
|
|
@@ -255,7 +256,7 @@ const processCommands = (args) => {
|
|
|
255
256
|
} else {
|
|
256
257
|
if (POAD_COMMANDS[command]) {
|
|
257
258
|
// --json : rien d'autre que le JSON sur la sortie standard
|
|
258
|
-
if (!args.includes('--json')) console.log(' ');
|
|
259
|
+
if (!args.includes('--json') && !args.includes('--stdout')) console.log(' ');
|
|
259
260
|
|
|
260
261
|
const dir = args.join('/');
|
|
261
262
|
const px = parseCommandArgs(require(__dirname + '/project/cli'), args);
|
|
@@ -358,7 +359,7 @@ const main = async () => {
|
|
|
358
359
|
const framedMessage = boxen(styledMessage, boxenOptions);
|
|
359
360
|
|
|
360
361
|
// --json : l'avis de nouvelle version part sur stderr, la sortie reste du JSON
|
|
361
|
-
if (process.argv.includes('--json')) console.error(framedMessage);
|
|
362
|
+
if (process.argv.includes('--json') || process.argv.includes('--stdout')) console.error(framedMessage);
|
|
362
363
|
else console.log(framedMessage);
|
|
363
364
|
|
|
364
365
|
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: {
|
|
@@ -62,7 +67,7 @@ module.exports = {
|
|
|
62
67
|
logs: 'Unified logs of the project, every service, with filters (level, since, request, flow, function, AI…) and -f',
|
|
63
68
|
gen: {
|
|
64
69
|
description: 'Generators of TypeScript types: the database, the public variables',
|
|
65
|
-
types: 'TypeScript types of the database for createClient<Database>() (out=src/types/database.ts)',
|
|
70
|
+
types: 'TypeScript types of the database for createClient<Database>() (out=src/types/database.ts, role=authenticated|anon|service_role)',
|
|
66
71
|
env: 'TypeScript types of the public variables (PUBLIC_*) for poad.env (out=src/types/poad-env.ts)',
|
|
67
72
|
},
|
|
68
73
|
migrate: 'Apply pending migrations of poad/migrations and named queries of poad/queries (poad start does it too)',
|
|
@@ -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>], link <table> (linked table of another PostgreSQL database), test <name>, 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
|
@@ -7,6 +7,9 @@
|
|
|
7
7
|
// x-poad-dry-run 1 avec --dry-run : le serveur dit ce qu'il ferait, rien ne change
|
|
8
8
|
// réponse : { deploy_id?, status?, migrations: { applied, pending, errors }, warnings }
|
|
9
9
|
// warnings : migrations qui perdent des données (drop table, truncate…), signalées, jamais refusées
|
|
10
|
+
// api_exposure : fonctions et vues que l'API ne sert pas à anon ni à authenticated (SECURITY DEFINER, vues
|
|
11
|
+
// sans security_invoker, vues matérialisées), dans la base et dans les migrations en attente, avec ce que
|
|
12
|
+
// l'engine de l'environnement en fait et le correctif de chacune (poad.io 0.66.0+), jamais bloquant
|
|
10
13
|
// asynchrone (deploy_id et état non terminé) : GET …/deploys/:deploy_id jusqu'à la fin
|
|
11
14
|
//
|
|
12
15
|
// Production (main) : résumé puis confirmation, sauf --yes (obligatoire hors
|
|
@@ -36,9 +39,22 @@ function summarize(d = {}) {
|
|
|
36
39
|
// Signalé, jamais bloquant : migrations qui perdent des données (drop table, truncate…)
|
|
37
40
|
warnings: (Array.isArray(d.warnings) ? d.warnings : []).map((w) => ({ message: String((w && w.message) || ''), files: Array.isArray(w && w.files) ? w.files.map(String) : [] })),
|
|
38
41
|
failed: errors.length > 0 || FAILED.includes(status),
|
|
42
|
+
api_exposure: exposureOf(d.api_exposure),
|
|
39
43
|
};
|
|
40
44
|
}
|
|
41
45
|
|
|
46
|
+
/** Avertissement de l'API (poad.io) ramené à la règle du CLI (utils/api-exposure) : textes en anglais */
|
|
47
|
+
function exposureOf(x) {
|
|
48
|
+
if (!x || typeof x !== 'object' || !Array.isArray(x.items)) return null;
|
|
49
|
+
const items = x.items
|
|
50
|
+
.filter((i) => i && typeof i.schema === 'string' && typeof i.name === 'string')
|
|
51
|
+
.map((i) => ({ kind: String(i.kind || ''), schema: i.schema, name: i.name, signature: typeof i.signature === 'string' ? i.signature : undefined, reason: String(i.reason || ''), anon: Array.isArray(i.roles) ? i.roles.includes('anon') : true, authenticated: Array.isArray(i.roles) ? i.roles.includes('authenticated') : true, source: i.source, file: i.file }));
|
|
52
|
+
const out = require('../utils/api-exposure').impact({ current: x.current || null, target: x.target || x.current || null, items });
|
|
53
|
+
// La décision du serveur prime (il connaît la version de l'environnement)
|
|
54
|
+
if (typeof x.change === 'string') out.change = x.change;
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
|
|
42
58
|
function gitState(dir) {
|
|
43
59
|
const { spawnSync } = require('child_process');
|
|
44
60
|
const git = (a) => spawnSync('git', a, { cwd: dir, encoding: 'utf8', timeout: 10000 });
|
|
@@ -97,6 +113,10 @@ module.exports = (args, raw) =>
|
|
|
97
113
|
else if (git.empty) out.log(chalk.grey(' git repository without any commit yet: no commit id'));
|
|
98
114
|
else out.log(chalk.grey(' not in a git repository: no commit id'));
|
|
99
115
|
for (const s of b.skipped) if (!large.some((f) => f.rel === s.path)) out.log(chalk.grey(` skipped ${s.path}: ${s.reason}`));
|
|
116
|
+
// Paquets npm des fonctions : seuls les fichiers que leurs imports atteignent partent
|
|
117
|
+
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)`));
|
|
118
|
+
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.`));
|
|
119
|
+
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
120
|
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
121
|
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
122
|
|
|
@@ -138,6 +158,8 @@ module.exports = (args, raw) =>
|
|
|
138
158
|
for (const f of w.files) out.log(` ${chalk.yellow(f)}`);
|
|
139
159
|
}
|
|
140
160
|
if (!m.applied.length && !m.pending.length && !m.errors.length) out.log(chalk.grey(' No migration to apply.'));
|
|
161
|
+
// Ce que l'API ne sert pas à anon ni à authenticated : jamais bloquant, toujours dit (avec le correctif)
|
|
162
|
+
for (const l of require('../utils/api-exposure').lines(result.api_exposure, chalk)) out.log(l);
|
|
141
163
|
// Grosses références : après les migrations (les tables existent), envoi puis chargement
|
|
142
164
|
let references = null;
|
|
143
165
|
if (large.length && !dryRun && !result.failed) {
|
package/project/gen/types.js
CHANGED
|
@@ -3,6 +3,9 @@
|
|
|
3
3
|
// à partir de ce qu'il lit dans Postgres (/rest/v1/types.ts) ; le CLI les
|
|
4
4
|
// écrit dans src/types/database.ts (ou out=<chemin>).
|
|
5
5
|
// À relancer après une migration qui change les tables ou les fonctions.
|
|
6
|
+
// role=anon|authenticated (défaut : authenticated, ce que voit un front) ; role=service_role : aussi les fonctions
|
|
7
|
+
// SECURITY DEFINER, vues sans security_invoker et vues matérialisées, que l'API ne sert qu'à service_role (marquées
|
|
8
|
+
// « Réservé à service_role »), pour le code serveur (engine 0.66.0+).
|
|
6
9
|
module.exports = async (args = {}) => {
|
|
7
10
|
const chalk = require('chalk-v2');
|
|
8
11
|
const fs = require('fs');
|
|
@@ -24,7 +27,12 @@ module.exports = async (args = {}) => {
|
|
|
24
27
|
return console.log(chalk.redBright('The project is not started: run "poad start".'));
|
|
25
28
|
}
|
|
26
29
|
const out = path.resolve(path.dirname(path.dirname(root)), String(args.out || path.join('src', 'types', 'database.ts')));
|
|
27
|
-
const
|
|
30
|
+
const role = String(args.role || 'authenticated');
|
|
31
|
+
if (!['anon', 'authenticated', 'service_role'].includes(role)) {
|
|
32
|
+
process.exitCode = 2;
|
|
33
|
+
return console.log(chalk.redBright('role: anon, authenticated or service_role.'));
|
|
34
|
+
}
|
|
35
|
+
const url = `http://localhost:${config.web.port}/rest/v1/types.ts?role=${role}`;
|
|
28
36
|
let text;
|
|
29
37
|
try {
|
|
30
38
|
const res = await fetch(url, { headers: { apikey: config.auth.service, authorization: `Bearer ${config.auth.service}` } });
|
|
@@ -40,5 +48,5 @@ module.exports = async (args = {}) => {
|
|
|
40
48
|
const tables = (text.match(/^ {6}\w+: \{$/gm) || []).length;
|
|
41
49
|
const shown = path.relative(process.cwd(), out).startsWith('..') ? out : path.relative(process.cwd(), out);
|
|
42
50
|
console.log(`${chalk.greenBright('✔')} ${chalk.bold(shown)}${before === text ? chalk.grey(' (unchanged)') : ''}`);
|
|
43
|
-
console.log(chalk.grey(` ${tables} table(s). Use it with: createClient<Database>(url, anonKey)`));
|
|
51
|
+
console.log(chalk.grey(` ${tables} table(s), as seen by ${role}. Use it with: createClient<Database>(url, ${role === 'service_role' ? 'serviceKey' : 'anonKey'})`));
|
|
44
52
|
};
|
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)
|