poad 2.75.2 → 2.76.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 +1 -1
- package/package.json +1 -1
- package/project/cli.js +2 -0
- package/project/deploy.js +85 -26
- package/project/migrate.js +7 -3
- package/project/pull.js +4 -0
- package/project/push.js +4 -0
- package/test/cloud.test.js +55 -2
- package/test/data-loss.test.js +112 -0
- package/test/project-sync.test.js +297 -0
- package/utils/banner.js +2 -0
- package/utils/cloud/db.js +6 -7
- package/utils/data-loss.js +600 -0
- package/utils/help-details.js +61 -7
- package/utils/migrate-run.js +32 -1
- package/utils/migrations.js +29 -3
- package/utils/project-sync/code.js +122 -0
- package/utils/project-sync/pg.js +130 -0
- package/utils/project-sync/plan.js +436 -0
- package/utils/project-sync/run.js +769 -0
package/utils/help-details.js
CHANGED
|
@@ -328,14 +328,16 @@ const sheets = {
|
|
|
328
328
|
],
|
|
329
329
|
},
|
|
330
330
|
migrate: {
|
|
331
|
-
usage: ['poad migrate', 'poad migrate --force-reference', 'poad migrate --json', 'poad migrate list [--env <name>] [--json]', 'poad migrate pull [--env <name>] [--yes] [--dry-run] [--json]', 'poad migrate renumber <version|file> [--env <name>] [--yes] [--json]', 'poad migrate renumber --pending [--env <name>] [--yes] [--json]'],
|
|
331
|
+
usage: ['poad migrate', 'poad migrate --dry-run', 'poad migrate --force-reference', 'poad migrate --json', 'poad migrate list [--env <name>] [--json]', 'poad migrate pull [--env <name>] [--yes] [--dry-run] [--json]', 'poad migrate renumber <version|file> [--env <name>] [--yes] [--json]', 'poad migrate renumber --pending [--env <name>] [--yes] [--json]'],
|
|
332
332
|
text: [
|
|
333
333
|
'Apply pending migrations of poad/migrations and named queries of poad/queries, then the reference tables of poad/reference (the file is the source of truth).',
|
|
334
|
+
'Before applying, reads the pending migrations (never run for this) and counts on the database what they would lose: DROP TABLE, DROP COLUMN (non-null values), ALTER COLUMN … TYPE, TRUNCATE, DELETE, DROP SCHEMA, and what breaks API clients (RENAME TABLE / COLUMN, DROP VIEW / FUNCTION served to anon or authenticated). Silent when the target does not exist yet (created by the same batch) or is empty; otherwise a warning with file, statement and number of rows. Locally a warning only (poad deploy asks to confirm on production). Logs: poad logs cli event=migration_data_loss_check.',
|
|
334
335
|
'Then warns (never blocks) about functions and views granted to anon or authenticated that the API does not serve them (403 not_exposed: SECURITY DEFINER functions, views without security_invoker, materialized views), each with its fix; the ones a migration just created also go to the log sink (poad logs cli event=api_exposure).',
|
|
335
336
|
],
|
|
336
337
|
options: [
|
|
338
|
+
['--dry-run', 'the pending migrations and the data they would lose (counted on the database), nothing applied'],
|
|
337
339
|
['--force-reference', 'also apply a reference file that would remove many rows: an empty file for a table that has rows, or more than 20% of its rows (refused otherwise, nothing removed)'],
|
|
338
|
-
['--json', 'one JSON object: applied, failed, pending, api_exposure (items with reason, roles, fix, created), unprotected tables'],
|
|
340
|
+
['--json', 'one JSON object: applied, failed, pending, data_loss ([{ file, line, statement, target, rows, kind, decision }]), api_exposure (items with reason, roles, fix, created), unprotected tables'],
|
|
339
341
|
['list', 'poad/migrations against an environment of poad.io (--env, else the git branch, else main; the local engine when the project is not linked): applied on both sides, pending here, missing here, written on poad.io without being applied, same version under another name, changed since applied, older than the last one applied (poad deploy refuses it); with version, name and date'],
|
|
340
342
|
['pull', 'same as poad migration pull'],
|
|
341
343
|
['renumber <version>', 'give a pending migration a version after the last one of the environment and of the folder (the file is renamed, its SQL is unchanged) when poad deploy refuses it as out of order. Refused when it is applied on any environment of poad.io; applied on the local engine only: the local history follows. Logs: poad logs cli event=migration_renumbered'],
|
|
@@ -482,7 +484,7 @@ Object.assign(sheets, {
|
|
|
482
484
|
notes: [EXIT_NOTE],
|
|
483
485
|
},
|
|
484
486
|
deploy: {
|
|
485
|
-
usage: ['poad deploy [--env <name>] [--dry-run] [--yes] [--json]'],
|
|
487
|
+
usage: ['poad deploy [--env <name>] [--dry-run] [--yes] [--allow-destructive] [--json]'],
|
|
486
488
|
text: [
|
|
487
489
|
'Send the poad/ folder to an environment of the linked poad.io project, which applies its pending migrations and loads its functions, flows, API, auth and storage settings.',
|
|
488
490
|
'Sent: migrations, auth, storage, functions, flows, api, reference, variables (defaults, no secret), types, credentials/manifest.json (names and types only, never values), seed.sql, config.toml (without any secret key). Never sent: poad/secrets.toml, .env files, data/, backups/, node_modules, symbolic links. If a value of poad/secrets.toml appears in a file to send, nothing is sent.',
|
|
@@ -490,26 +492,78 @@ Object.assign(sheets, {
|
|
|
490
492
|
options: [
|
|
491
493
|
['--env <name>', 'the environment (default: the current git branch if it exists on poad.io, else main)'],
|
|
492
494
|
['--dry-run', 'poad.io says what it would do (migrations to apply), nothing changes'],
|
|
493
|
-
['--yes', 'no question for production (required outside a terminal)'],
|
|
495
|
+
['--yes', 'no question for production (required outside a terminal); does not accept a data loss'],
|
|
496
|
+
['--allow-destructive', 'production: apply migrations that lose data without asking (required outside a terminal when they do); alias --accept-data-loss'],
|
|
494
497
|
PROJECT_OPT,
|
|
495
498
|
JSON_OPT,
|
|
496
499
|
],
|
|
497
500
|
notes: [
|
|
501
|
+
'Before applying, poad.io counts on the database of the environment what the pending migrations would lose (DROP TABLE, DROP COLUMN, ALTER COLUMN … TYPE, TRUNCATE, DELETE, DROP SCHEMA; RENAME and DROP VIEW / FUNCTION served by the API break clients): nothing is said when the target is created by the same deploy or is empty; otherwise file, statement and number of rows (data_loss in --json, --dry-run included). Production: a loss of data needs a confirmation in a terminal, or --allow-destructive; refused otherwise (exit code 4), nothing changed. Other environments: a warning.',
|
|
498
502
|
'Production (main): a summary, then a confirmation (none for --dry-run, which changes nothing). Uncommitted changes in poad/: a warning, and no commit id is sent (the commit id is sent when poad/ is clean).',
|
|
499
503
|
EXIT_NOTE,
|
|
500
504
|
],
|
|
501
505
|
},
|
|
506
|
+
push: {
|
|
507
|
+
usage: [
|
|
508
|
+
'poad push [--env <name>] [--dry-run] [--only code,base,auth,s3,refs | --skip …] [--tables a,b] [--with-secrets] [--yes] [--json]',
|
|
509
|
+
'poad push --env main --yes --confirm <project id> (production, outside a terminal)',
|
|
510
|
+
],
|
|
511
|
+
text: [
|
|
512
|
+
'Make an environment of the linked poad.io project the mirror of the local project, part by part, in this order: code (what poad deploy sends: migrations, functions, flows, API…), base (rows of the tables of the project schemas), auth (accounts with their password hashes, identities and metadata, as they are), refs (reference tables of the store), s3 (files of the storage). The target becomes the mirror of the source for the chosen parts: what it has of its own there is replaced; nothing is merged both ways. Tables that exist only on the target are left alone.',
|
|
513
|
+
'A preview always comes first, part by part and table by table: rows added (+), replaced (~), deleted (-) and identical, compared row by row with fingerprints of the primary key and of each row (never a value; above 200,000 rows a table is compared by counts only), sizes, room left on the target. An identical table is not rewritten.',
|
|
514
|
+
'Base and auth go in ONE transaction, through the direct database access of poad.io (db.poad.io), run by the PostgreSQL tools of the local engine: the source is read in one consistent snapshot, the target is written with triggers and foreign keys paused during the load (nothing cascades), sequences are set as on the source; any error and nothing changes. Sessions and refresh tokens of the target are closed (accounts sign in again there), confirmation and recovery tokens are emptied. The structure must match first: a table missing or different on the target stops the base part before anything is written, and the code part (when chosen) runs first and is checked again after it.',
|
|
515
|
+
'Secrets only with --with-secrets, after a confirmation of their own: the values of the variables of the engine and the credentials (fields, uses, vault values), except those of the storage, which each environment keeps. Values are never shown, written to a file or logged; keys of the engine, auth provider secrets and MCP tokens are never copied.',
|
|
516
|
+
],
|
|
517
|
+
options: [
|
|
518
|
+
['--env <name>', 'the environment (default: the current git branch if it exists on poad.io, else main)'],
|
|
519
|
+
['--dry-run, -n', 'the preview only, nothing changes (also: poad push status)'],
|
|
520
|
+
['--only <parts>', 'only these parts: code, base, auth, s3, refs (comma separated)'],
|
|
521
|
+
['--skip <parts>', 'all parts but these'],
|
|
522
|
+
['--tables <a,b>', 'only these tables of the base part (table or schema.table)'],
|
|
523
|
+
['--with-secrets', 'also the values of variables and credentials (asks separately)'],
|
|
524
|
+
['--allow-destructive', 'passed to poad deploy (alias --accept-data-loss): migrations that lose data are applied on production without asking'],
|
|
525
|
+
['--yes', 'no question (required outside a terminal)'],
|
|
526
|
+
['--confirm <id>', 'production: the project id, typed in the command (outside a terminal: with --yes)'],
|
|
527
|
+
PROJECT_OPT,
|
|
528
|
+
JSON_OPT,
|
|
529
|
+
],
|
|
530
|
+
notes: [
|
|
531
|
+
'Production (main): a backup of its database first (kept in its volume, 3 kept), a check of the room left (rows to write + 10 % + the journal of the database), and a strong confirmation: type the project id; outside a terminal, --yes --confirm <id>, else nothing changes.',
|
|
532
|
+
'The local project must be started (poad start). Logs, one line per part and per table (part, table, rows, bytes, duration_ms, outcome; never a value): poad logs cli event=project_push here, and in the logs of the environment on poad.io (poad logs --project … event=project_push).',
|
|
533
|
+
EXIT_NOTE.replace('5 deploy failed', '5 a part failed (the base part is all or nothing)'),
|
|
534
|
+
],
|
|
535
|
+
},
|
|
536
|
+
pull: {
|
|
537
|
+
usage: ['poad pull [--env <name>] [--dry-run] [--only code,base,auth,s3,refs | --skip …] [--tables a,b] [--with-secrets] [--yes] [--json]'],
|
|
538
|
+
text: [
|
|
539
|
+
'The other way of poad push: make the local project the mirror of an environment of poad.io, part by part: code (the migrations written there, by poad migration pull, then the deployed files of queries, auth, storage, functions, flows, api, reference, sources, transforms, connections, variables and seed.sql, then poad migrate), base, auth, refs (the reference tables of the store, loaded into the local engine), s3 (files of the storage).',
|
|
540
|
+
'A local file is replaced or removed only when git tracks it without uncommitted change; otherwise it is kept and named (commit or stash it, then pull again). Migrations are never overwritten (a version used here under another name is a conflict, said and left alone).',
|
|
541
|
+
'Same preview, same single transaction for base and auth, same structure check and same --with-secrets as poad push. Before writing a local database that holds rows, a backup: poad/backups/<timestamp>-pre-pull.dump (pg_dump custom format, outside git; pg_restore brings it back).',
|
|
542
|
+
],
|
|
543
|
+
options: [
|
|
544
|
+
['--env <name>', 'the environment to read (default: the current git branch if it exists on poad.io, else main); never written'],
|
|
545
|
+
['--dry-run, -n', 'the preview only, nothing changes (also: poad pull status)'],
|
|
546
|
+
['--only <parts>', 'only these parts: code, base, auth, s3, refs'],
|
|
547
|
+
['--skip <parts>', 'all parts but these'],
|
|
548
|
+
['--tables <a,b>', 'only these tables of the base part'],
|
|
549
|
+
['--with-secrets', 'also the values of variables and credentials (asks separately)'],
|
|
550
|
+
['--yes', 'no question (required outside a terminal)'],
|
|
551
|
+
PROJECT_OPT,
|
|
552
|
+
JSON_OPT,
|
|
553
|
+
],
|
|
554
|
+
notes: ['Logs: poad logs cli event=project_pull (and in the logs of the environment on poad.io). ' + EXIT_NOTE.replace('5 deploy failed', '5 a part failed')],
|
|
555
|
+
},
|
|
502
556
|
'db url': {
|
|
503
557
|
usage: ['poad db url [--env <name>] [--mode session|transaction] [--show-password] [--copy | --no-copy] [--json]'],
|
|
504
558
|
text: [
|
|
505
|
-
'Connection string of the database of the linked poad.io project: postgresql://postgres.<id>:<password>@db.poad.io:<port>/postgres?sslmode=require. The password is never printed unless --show-password: in a terminal, the full string goes to the clipboard and the screen shows it masked.',
|
|
559
|
+
'Connection string of the database of the linked poad.io project (or of one of its environments: user postgres.<id>--<env>): postgresql://postgres.<id>:<password>@db.poad.io:<port>/postgres?sslmode=require. The password is never printed unless --show-password: in a terminal, the full string goes to the clipboard and the screen shows it masked.',
|
|
506
560
|
],
|
|
507
561
|
options: [
|
|
508
562
|
['--mode session', 'port 5432, long connections (psql, pg_dump, migrations); the default'],
|
|
509
563
|
['--mode transaction', 'port 6543, pooled short connections (serverless functions)'],
|
|
510
564
|
['--show-password', 'print the full string (it stays in your terminal history)'],
|
|
511
565
|
['--copy, --no-copy', 'copy to the clipboard even outside a terminal, or never'],
|
|
512
|
-
['--env <name>', 'the environment (
|
|
566
|
+
['--env <name>', 'the environment (default: as poad deploy); an environment has its own database, user postgres.<id>--<env>'],
|
|
513
567
|
PROJECT_OPT,
|
|
514
568
|
JSON_OPT,
|
|
515
569
|
],
|
|
@@ -521,7 +575,7 @@ Object.assign(sheets, {
|
|
|
521
575
|
'Write the schema of the poad.io database into a new local migration (poad/migrations/<timestamp>_cloud_main_schema.sql), with pg_dump --schema-only through db.poad.io. Engine schemas (auth, storage, _poad…) are left out. An existing migration is never overwritten.',
|
|
522
576
|
'pg_dump: the one of this machine, else the one of the local engine (project started), else the command tells what to install.',
|
|
523
577
|
],
|
|
524
|
-
options: [['--name <name>', 'name of the migration'], ['--env <name>', 'the environment (
|
|
578
|
+
options: [['--name <name>', 'name of the migration'], ['--env <name>', 'the environment (default: as poad deploy); an environment has its own database, user postgres.<id>--<env>'], PROJECT_OPT, JSON_OPT],
|
|
525
579
|
notes: [EXIT_NOTE],
|
|
526
580
|
},
|
|
527
581
|
});
|
package/utils/migrate-run.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
const path = require('path');
|
|
3
3
|
|
|
4
4
|
// report : objet rempli pour --json (applied, failed, api_exposure, unprotected, queries)
|
|
5
|
-
module.exports = async (root, config, { quietWhenNone = false, report = null, exposureList = false } = {}) => {
|
|
5
|
+
module.exports = async (root, config, { quietWhenNone = false, report = null, exposureList = false, dryRun = false, via = 'poad migrate' } = {}) => {
|
|
6
6
|
const chalk = require('chalk-v2');
|
|
7
7
|
const migrations = require('./migrations');
|
|
8
8
|
const rel = (p) => path.relative(process.cwd(), p);
|
|
@@ -10,6 +10,12 @@ module.exports = async (root, config, { quietWhenNone = false, report = null, ex
|
|
|
10
10
|
let result;
|
|
11
11
|
try {
|
|
12
12
|
result = await migrations.migrate(root, config, {
|
|
13
|
+
dryRun,
|
|
14
|
+
via,
|
|
15
|
+
// Avant la première migration appliquée : ce qui sera perdu (silence si la cible est absente ou vide)
|
|
16
|
+
onDataLoss: (list) => {
|
|
17
|
+
for (const l of dataLossLines(list, chalk, { local: true })) console.log(l);
|
|
18
|
+
},
|
|
13
19
|
onApply: (m) => console.log(`${chalk.greenBright('✔')} ${chalk.bold(m.file)}`),
|
|
14
20
|
});
|
|
15
21
|
} catch (err) {
|
|
@@ -19,6 +25,7 @@ module.exports = async (root, config, { quietWhenNone = false, report = null, ex
|
|
|
19
25
|
const { applied, failed, state } = result;
|
|
20
26
|
if (report) {
|
|
21
27
|
Object.assign(report, {
|
|
28
|
+
data_loss: require('./data-loss').jsonOf(result.dataLoss || []),
|
|
22
29
|
applied: applied.map((m) => m.file),
|
|
23
30
|
failed: failed ? { file: failed.migration.file, message: failed.message } : null,
|
|
24
31
|
pending: state.pending.filter((m) => !applied.includes(m)).map((m) => m.file),
|
|
@@ -28,6 +35,11 @@ module.exports = async (root, config, { quietWhenNone = false, report = null, ex
|
|
|
28
35
|
});
|
|
29
36
|
}
|
|
30
37
|
|
|
38
|
+
if (dryRun) {
|
|
39
|
+
for (const m of state.pending) console.log(` ${chalk.yellow('○')} ${m.file} ${chalk.grey('(would be applied)')}`);
|
|
40
|
+
console.log(state.pending.length ? chalk.bold(` Dry run: ${state.pending.length} pending migration(s), nothing applied.`) : chalk.grey(` Database up to date (${state.list.length} migration(s)).`));
|
|
41
|
+
return true;
|
|
42
|
+
}
|
|
31
43
|
for (const m of state.changed) {
|
|
32
44
|
console.log(chalk.yellowBright(` ${m.file} changed after it was applied: it is not replayed. Write a new migration instead.`));
|
|
33
45
|
}
|
|
@@ -69,3 +81,22 @@ module.exports = async (root, config, { quietWhenNone = false, report = null, ex
|
|
|
69
81
|
for (const l of require('./api-exposure').migrateLines(result.apiExposure, chalk, { full: exposureList || applied.length > 0 })) console.log(l);
|
|
70
82
|
return qr.errors.length === 0;
|
|
71
83
|
};
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Lignes d'avertissement des pertes de données (utils/data-loss.js), partagées avec poad deploy :
|
|
87
|
+
* « ⚠ fichier:ligne DROP COLUMN public.t.c — 1,240 non-null value(s) will be lost », puis l'instruction.
|
|
88
|
+
* local : la base du poste (avertissement seul) ; sinon le mot de la décision de poad.io.
|
|
89
|
+
*/
|
|
90
|
+
function dataLossLines(list, chalk, { local = false, production = false } = {}) {
|
|
91
|
+
const shown = (list || []).filter((d) => d && d.decision !== 'silent' && d.message);
|
|
92
|
+
if (!shown.length) return [];
|
|
93
|
+
const out = [`${chalk.yellowBright('⚠')} ${chalk.bold('Pending migrations lose data or break API clients:')}`];
|
|
94
|
+
for (const d of shown) {
|
|
95
|
+
out.push(` ${chalk.yellow(`${d.file}${d.line ? `:${d.line}` : ''}`)} ${d.loss ? chalk.yellowBright(d.message) : d.message}`);
|
|
96
|
+
if (d.statement) out.push(chalk.grey(` ${d.statement}`));
|
|
97
|
+
}
|
|
98
|
+
if (local) out.push(chalk.grey(' Local database: applied anyway. On the production of poad.io, poad deploy asks to confirm (or --allow-destructive).'));
|
|
99
|
+
else if (production && shown.some((d) => d.decision === 'confirm')) out.push(chalk.grey(' Production: data is lost only after a confirmation (terminal) or with --allow-destructive.'));
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
module.exports.dataLossLines = dataLossLines;
|
package/utils/migrations.js
CHANGED
|
@@ -137,12 +137,17 @@ function lineOf(sql, position) {
|
|
|
137
137
|
* transaction est annulée, les suivantes ne sont pas tentées).
|
|
138
138
|
* Renvoie { applied: [...], failed: { migration, message } | null, state }.
|
|
139
139
|
*/
|
|
140
|
-
async function migrate(root, config, { onApply } = {}) {
|
|
140
|
+
async function migrate(root, config, { onApply, onDataLoss, dryRun = false, via = 'poad migrate' } = {}) {
|
|
141
141
|
const client = await connect(config);
|
|
142
142
|
const applied = [];
|
|
143
143
|
try {
|
|
144
144
|
await client.query('select pg_advisory_lock($1)', [LOCK_ID]);
|
|
145
145
|
const state = await status(root, client);
|
|
146
|
+
// Avant d'appliquer : ce que les migrations en attente perdent vraiment sur cette base (utils/data-loss.js).
|
|
147
|
+
// En local, un avertissement seulement (la confirmation est pour la production de poad.io, poad deploy).
|
|
148
|
+
const dataLoss = state.pending.length ? await dataLossCheck(client, state.pending, config, dryRun ? `${via} --dry-run` : via) : [];
|
|
149
|
+
if (onDataLoss) onDataLoss(dataLoss);
|
|
150
|
+
if (dryRun) return { applied, failed: null, state, dataLoss, dryRun: true };
|
|
146
151
|
// Ce que l'API ne sert pas à anon ni à authenticated alors qu'ils en ont le droit, avant les migrations : ce
|
|
147
152
|
// qu'elles font apparaître est signalé et va au puits de logs (event=api_exposure)
|
|
148
153
|
const exposure = require('./api-exposure');
|
|
@@ -159,7 +164,7 @@ async function migrate(root, config, { onApply } = {}) {
|
|
|
159
164
|
} catch (err) {
|
|
160
165
|
await client.query('rollback').catch(() => {});
|
|
161
166
|
const where = err.position ? ` (line ${lineOf(m.sql, err.position)})` : '';
|
|
162
|
-
return { applied, failed: { migration: m, message: `${err.message}${where}` }, state };
|
|
167
|
+
return { applied, failed: { migration: m, message: `${err.message}${where}` }, state, dataLoss };
|
|
163
168
|
}
|
|
164
169
|
}
|
|
165
170
|
// Empreinte de la structure après les migrations (journal des changements)
|
|
@@ -170,13 +175,34 @@ async function migrate(root, config, { onApply } = {}) {
|
|
|
170
175
|
const unprotected = await unprotectedTables(client, exposedSchemas(config));
|
|
171
176
|
const apiExposure = exposure.afterMigrate({ engine: config.engine, before, after: await exposure.query(client, exposedSchemas(config)) });
|
|
172
177
|
if (apiExposure.created.length) await logApiExposure(client, apiExposure, applied);
|
|
173
|
-
return { applied, failed: null, state, queries, unprotected, apiExposure };
|
|
178
|
+
return { applied, failed: null, state, queries, unprotected, apiExposure, dataLoss };
|
|
174
179
|
} finally {
|
|
175
180
|
await client.query('select pg_advisory_unlock($1)', [LOCK_ID]).catch(() => {});
|
|
176
181
|
await client.end().catch(() => {});
|
|
177
182
|
}
|
|
178
183
|
}
|
|
179
184
|
|
|
185
|
+
/**
|
|
186
|
+
* Pertes de données des migrations en attente, comptées sur la base locale (lecture seule, délai court). Une ligne
|
|
187
|
+
* par constat dans le puits (service cli, event=migration_data_loss_check ; debug quand rien n'est perdu) : fichier,
|
|
188
|
+
* genre, cible, nombre de lignes, décision ; jamais d'instruction ni de valeur. Une erreur ici ne bloque jamais.
|
|
189
|
+
*/
|
|
190
|
+
async function dataLossCheck(client, pending, config, via) {
|
|
191
|
+
const dl = require('./data-loss');
|
|
192
|
+
try {
|
|
193
|
+
const findings = dl.analyze(pending.map((m) => ({ file: m.file, sql: m.sql })));
|
|
194
|
+
if (!findings.length) return [];
|
|
195
|
+
const results = await dl.runChecks(client, dl.checks(findings));
|
|
196
|
+
const decided = dl.decide(findings, results, { production: false, exposedSchemas: exposedSchemas(config) });
|
|
197
|
+
const rows = decided.map((d) => [dl.levelOf(d), dl.logMsg(d), JSON.stringify(dl.logAttrs(d, { via, env: 'local' }))]);
|
|
198
|
+
for (const r of rows) await client.query("insert into _logs.entries (ts, level, service, msg, attrs) values (now(), $1, 'cli', $2, $3::jsonb)", r).catch(() => {});
|
|
199
|
+
return decided;
|
|
200
|
+
} catch {
|
|
201
|
+
await client.query('rollback').catch(() => {});
|
|
202
|
+
return [];
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
180
206
|
/**
|
|
181
207
|
* Puits de logs (service cli, event=api_exposure) : une migration vient de créer des fonctions ou vues accordées à
|
|
182
208
|
* anon ou authenticated que l'API ne leur sert pas. Noms et raisons seulement, jamais de SQL ni de secret.
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// poad pull, partie code : les fichiers déployés d'un environnement de poad.io (export de /project) face au
|
|
2
|
+
// dossier poad/ local, pour les dossiers que poad deploy envoie. Les migrations ont leur commande (poad
|
|
3
|
+
// migration pull) ; types/ est régénéré ; config.toml et credentials/ restent ceux de chaque côté.
|
|
4
|
+
//
|
|
5
|
+
// Rien n'est perdu : un fichier local n'est remplacé ou retiré que s'il est suivi par git et sans
|
|
6
|
+
// modification en cours ; sinon il est gardé et nommé (« commit ou stash, puis relancez »).
|
|
7
|
+
'use strict';
|
|
8
|
+
const fs = require('fs');
|
|
9
|
+
const path = require('path');
|
|
10
|
+
|
|
11
|
+
const MIRRORED = ['queries', 'auth', 'storage', 'functions', 'flows', 'api', 'reference', 'sources', 'transforms', 'connections', 'variables'];
|
|
12
|
+
const FILES = ['seed.sql'];
|
|
13
|
+
|
|
14
|
+
/** Le chemin (relatif à poad/) fait-il partie du miroir ? Pure. */
|
|
15
|
+
function mirrored(rel) {
|
|
16
|
+
if (FILES.includes(rel)) return true;
|
|
17
|
+
const parts = rel.split('/');
|
|
18
|
+
if (parts.length < 2 || !MIRRORED.includes(parts[0])) return false;
|
|
19
|
+
if (parts.includes('node_modules') || parts.some((p) => p.startsWith('.'))) return false;
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Fichiers locaux du miroir : { rel: Buffer } (au-delà de la limite des références lourdes : laissés de côté) */
|
|
24
|
+
function localFiles(poadDir, { maxFile = 20 * 1024 * 1024 } = {}) {
|
|
25
|
+
const out = new Map();
|
|
26
|
+
const walk = (dir, rel) => {
|
|
27
|
+
let names = [];
|
|
28
|
+
try {
|
|
29
|
+
names = fs.readdirSync(dir, { withFileTypes: true });
|
|
30
|
+
} catch {
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
for (const d of names) {
|
|
34
|
+
const r = rel ? `${rel}/${d.name}` : d.name;
|
|
35
|
+
if (d.isDirectory()) {
|
|
36
|
+
if (d.name === 'node_modules' || d.name.startsWith('.')) continue;
|
|
37
|
+
walk(path.join(dir, d.name), r);
|
|
38
|
+
} else if (d.isFile() && mirrored(r)) {
|
|
39
|
+
const abs = path.join(dir, d.name);
|
|
40
|
+
if (fs.statSync(abs).size <= maxFile) out.set(r, fs.readFileSync(abs));
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
for (const d of MIRRORED) walk(path.join(poadDir, d), d);
|
|
45
|
+
for (const f of FILES) {
|
|
46
|
+
try {
|
|
47
|
+
out.set(f, fs.readFileSync(path.join(poadDir, f)));
|
|
48
|
+
} catch {}
|
|
49
|
+
}
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** État git des fichiers de poad/ : { repo, tracked: Set, dirty: Set } (chemins relatifs à poad/) */
|
|
54
|
+
function gitFiles(poadDir) {
|
|
55
|
+
const { spawnSync } = require('child_process');
|
|
56
|
+
const git = (a) => spawnSync('git', a, { cwd: poadDir, encoding: 'utf8', timeout: 15000, maxBuffer: 64 * 1024 * 1024 });
|
|
57
|
+
const prefix = git(['rev-parse', '--show-prefix']);
|
|
58
|
+
if (prefix.status !== 0) return { repo: false, tracked: new Set(), dirty: new Set() };
|
|
59
|
+
const pre = prefix.stdout.trim();
|
|
60
|
+
const ls = git(['ls-files', '-z', '--', '.']);
|
|
61
|
+
const tracked = new Set(ls.status === 0 ? ls.stdout.split('\0').filter(Boolean) : []);
|
|
62
|
+
const st = git(['status', '--porcelain=v1', '-z', '--untracked-files=all', '--', '.']);
|
|
63
|
+
const dirty = new Set();
|
|
64
|
+
if (st.status === 0) {
|
|
65
|
+
const items = st.stdout.split('\0');
|
|
66
|
+
for (let i = 0; i < items.length; i++) {
|
|
67
|
+
const it = items[i];
|
|
68
|
+
if (!it) continue;
|
|
69
|
+
const p = it.slice(3);
|
|
70
|
+
if (it[0] === 'R' || it[0] === 'C') i++; // renommage : le chemin d'origine suit
|
|
71
|
+
dirty.add(pre && p.startsWith(pre) ? p.slice(pre.length) : p);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return { repo: true, tracked, dirty };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Plan : remote (Map rel → Buffer, de l'export) face à local (Map), avec l'état git. Pure.
|
|
79
|
+
* Rend { add: [rel], update: [rel], remove: [rel], unchanged: n, kept: [{ rel, reason }] }
|
|
80
|
+
*/
|
|
81
|
+
function planFiles(remote, local, git) {
|
|
82
|
+
const plan = { add: [], update: [], remove: [], unchanged: 0, kept: [] };
|
|
83
|
+
const safe = (rel) => git.repo && git.tracked.has(rel) && !git.dirty.has(rel);
|
|
84
|
+
const why = (rel) => (!git.repo ? 'not in a git repository' : !git.tracked.has(rel) ? 'not tracked by git' : 'uncommitted changes');
|
|
85
|
+
for (const [rel, data] of remote) {
|
|
86
|
+
if (!mirrored(rel)) continue;
|
|
87
|
+
const here = local.get(rel);
|
|
88
|
+
if (!here) plan.add.push(rel);
|
|
89
|
+
else if (Buffer.compare(here, data) === 0) plan.unchanged++;
|
|
90
|
+
else if (safe(rel)) plan.update.push(rel);
|
|
91
|
+
else plan.kept.push({ rel, reason: why(rel), change: 'update' });
|
|
92
|
+
}
|
|
93
|
+
for (const rel of local.keys()) {
|
|
94
|
+
if (remote.has(rel)) continue;
|
|
95
|
+
if (safe(rel)) plan.remove.push(rel);
|
|
96
|
+
else plan.kept.push({ rel, reason: why(rel), change: 'remove' });
|
|
97
|
+
}
|
|
98
|
+
for (const k of ['add', 'update', 'remove']) plan[k].sort();
|
|
99
|
+
plan.kept.sort((a, b) => a.rel.localeCompare(b.rel));
|
|
100
|
+
return plan;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Fichiers de l'export (tar.gz en base64) → Map rel → Buffer */
|
|
104
|
+
function exportFiles(b64) {
|
|
105
|
+
const tar = require('../tar');
|
|
106
|
+
const entries = tar.readTar(tar.gunzip(Buffer.from(String(b64 || ''), 'base64')), { strip: 0 });
|
|
107
|
+
const out = new Map();
|
|
108
|
+
for (const e of entries) if (e.type === 'file' && mirrored(e.path)) out.set(e.path, Buffer.from(e.data));
|
|
109
|
+
return out;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Applique le plan dans poad/ */
|
|
113
|
+
function applyFiles(poadDir, plan, remote) {
|
|
114
|
+
for (const rel of [...plan.add, ...plan.update]) {
|
|
115
|
+
const abs = path.join(poadDir, rel);
|
|
116
|
+
fs.mkdirSync(path.dirname(abs), { recursive: true });
|
|
117
|
+
fs.writeFileSync(abs, remote.get(rel));
|
|
118
|
+
}
|
|
119
|
+
for (const rel of plan.remove) fs.rmSync(path.join(poadDir, rel), { force: true });
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
module.exports = { MIRRORED, mirrored, localFiles, gitFiles, planFiles, exportFiles, applyFiles };
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// poad push / poad pull : psql dans le conteneur de l'engine local, vers sa base (socket) ou vers celle de
|
|
2
|
+
// poad.io (db.poad.io, mot de passe de l'accès direct). Les outils Postgres sont ceux de l'engine (même version).
|
|
3
|
+
//
|
|
4
|
+
// Le mot de passe de poad.io ne passe jamais en argument : variable d'environnement de docker exec
|
|
5
|
+
// (« -e POAD_R_PW » : la valeur vient de l'environnement de docker, pas de la ligne de commande), lue par
|
|
6
|
+
// psql dans PGPASSWORD. Les scripts (des noms de tables, jamais une valeur) arrivent par l'entrée de bash.
|
|
7
|
+
'use strict';
|
|
8
|
+
const { spawn } = require('child_process');
|
|
9
|
+
|
|
10
|
+
const LOCAL_PSQL = 'psql -X -q -h /var/run/postgresql -U postgres -d postgres';
|
|
11
|
+
const REMOTE_PSQL = 'PGPASSWORD="$POAD_R_PW" PGSSLMODE="$POAD_R_SSL" PGCONNECT_TIMEOUT=15 PGAPPNAME=poad-cli psql -X -q -h "$POAD_R_HOST" -p "$POAD_R_PORT" -U "$POAD_R_USER" -d postgres';
|
|
12
|
+
|
|
13
|
+
/** Côté local : l'engine du projet (conteneur project_uuid) */
|
|
14
|
+
const localSide = (container) => ({ kind: 'local', label: 'local engine', container, psql: LOCAL_PSQL });
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Côté poad.io : { host, port, user, password } de utils/cloud/db.credentials.
|
|
18
|
+
* sslmode=require, sauf POAD_CLOUD_DB_SSLMODE=disable avec un poad.io sur cette machine (essais, faux poad.io).
|
|
19
|
+
*/
|
|
20
|
+
function cloudSide(c, { label, env = process.env } = {}) {
|
|
21
|
+
let ssl = 'require';
|
|
22
|
+
if (env.POAD_CLOUD_DB_SSLMODE === 'disable') {
|
|
23
|
+
const api = require('../cloud/api');
|
|
24
|
+
const host = new URL(api.apiBase(env)).hostname;
|
|
25
|
+
if (!['127.0.0.1', 'localhost', '[::1]', '::1'].includes(host)) throw new api.CloudError('POAD_CLOUD_DB_SSLMODE=disable is accepted only with a poad.io on this machine (POAD_CLOUD_API on 127.0.0.1).', { code: 'bad_api', exit: api.EXIT.usage });
|
|
26
|
+
ssl = 'disable';
|
|
27
|
+
}
|
|
28
|
+
return { kind: 'cloud', label, psql: REMOTE_PSQL, vars: { POAD_R_PW: c.password, POAD_R_HOST: c.host, POAD_R_PORT: String(c.port('session')), POAD_R_USER: c.user, POAD_R_SSL: ssl } };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Lance un script bash dans le conteneur. vars : variables passées par nom (valeurs hors ligne de commande).
|
|
33
|
+
* Rend { code, stdout (Buffer), stderr (texte) } ; onStderr(ligne) pour suivre l'avancement.
|
|
34
|
+
*/
|
|
35
|
+
function bash(container, script, { vars = {}, onStderr, timeoutMs = 0, docker = 'docker' } = {}) {
|
|
36
|
+
return new Promise((resolve) => {
|
|
37
|
+
const env = { ...process.env, ...vars };
|
|
38
|
+
const args = ['exec', '-i', ...Object.keys(vars).flatMap((k) => ['-e', k]), container, 'bash', '-s'];
|
|
39
|
+
const child = spawn(docker, args, { env, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
40
|
+
const out = [];
|
|
41
|
+
let err = '';
|
|
42
|
+
let partial = '';
|
|
43
|
+
let timer = null;
|
|
44
|
+
if (timeoutMs) timer = setTimeout(() => child.kill('SIGTERM'), timeoutMs);
|
|
45
|
+
child.stdout.on('data', (d) => out.push(d));
|
|
46
|
+
child.stderr.on('data', (d) => {
|
|
47
|
+
const s = d.toString('utf8');
|
|
48
|
+
if (err.length < 1e6) err += s;
|
|
49
|
+
if (onStderr) {
|
|
50
|
+
partial += s;
|
|
51
|
+
const lines = partial.split('\n');
|
|
52
|
+
partial = lines.pop();
|
|
53
|
+
for (const l of lines) onStderr(l);
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
child.on('error', (e) => resolve({ code: -1, stdout: Buffer.alloc(0), stderr: String(e.message) }));
|
|
57
|
+
child.on('close', (code) => {
|
|
58
|
+
if (timer) clearTimeout(timer);
|
|
59
|
+
if (onStderr && partial) onStderr(partial);
|
|
60
|
+
resolve({ code, stdout: Buffer.concat(out), stderr: err });
|
|
61
|
+
});
|
|
62
|
+
child.stdin.on('error', () => {});
|
|
63
|
+
child.stdin.end(script);
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Les variables d'un côté et de l'autre (un seul côté distant à la fois) */
|
|
68
|
+
const varsOf = (...sides) => Object.assign({}, ...sides.map((s) => s.vars || {}));
|
|
69
|
+
|
|
70
|
+
/** Masque le mot de passe d'un texte d'erreur (au cas où psql le citerait) */
|
|
71
|
+
const mask = (text, sides) => {
|
|
72
|
+
let t = String(text || '');
|
|
73
|
+
for (const s of sides) if (s.vars && s.vars.POAD_R_PW) t = t.split(s.vars.POAD_R_PW).join('••••••••');
|
|
74
|
+
return t;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
/** Requête : sortie de psql -tA (texte). Erreur : Error avec la ligne de psql (sans valeur ni mot de passe). */
|
|
78
|
+
async function query(container, side, sql, { timeoutMs = 300000 } = {}) {
|
|
79
|
+
const script = `${side.psql} -v ON_ERROR_STOP=1 -tA -f - <<'POAD_SQL_EOF'\n${sql}\nPOAD_SQL_EOF\n`;
|
|
80
|
+
const r = await bash(container, script, { vars: varsOf(side), timeoutMs });
|
|
81
|
+
if (r.code !== 0) {
|
|
82
|
+
const plan = require('./plan');
|
|
83
|
+
const lines = mask(r.stderr, [side]).split('\n').filter(Boolean);
|
|
84
|
+
throw Object.assign(new Error(`${side.label}: ${plan.errorLine(lines) || `psql exit ${r.code}`}`), { code: 'psql_failed', side: side.kind });
|
|
85
|
+
}
|
|
86
|
+
return r.stdout.toString('utf8');
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Requête qui rend un seul JSON */
|
|
90
|
+
async function json(container, side, sql, opts) {
|
|
91
|
+
const text = (await query(container, side, sql, opts)).trim();
|
|
92
|
+
try {
|
|
93
|
+
return JSON.parse(text);
|
|
94
|
+
} catch {
|
|
95
|
+
throw Object.assign(new Error(`${side.label}: unreadable answer of the database`), { code: 'bad_answer' });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Script de transfert (plan.transferScript) entre deux côtés ; suit les repères de la sortie d'erreur */
|
|
100
|
+
function transfer(container, src, dst, script, { onMarker } = {}) {
|
|
101
|
+
return bash(container, script, {
|
|
102
|
+
vars: varsOf(src, dst),
|
|
103
|
+
onStderr: (l) => {
|
|
104
|
+
if (onMarker && l.startsWith('@@poad ')) onMarker(l);
|
|
105
|
+
},
|
|
106
|
+
}).then((r) => ({ ...r, stderr: mask(r.stderr, [src, dst]) }));
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Sauvegarde de la base locale (pg_dump -Fc) dans un fichier de la machine ; rend sa taille */
|
|
110
|
+
function dumpLocal(container, file, { docker = 'docker' } = {}) {
|
|
111
|
+
const fs = require('fs');
|
|
112
|
+
return new Promise((resolve, reject) => {
|
|
113
|
+
const outFd = fs.openSync(file + '.part', 'w', 0o600);
|
|
114
|
+
const child = spawn(docker, ['exec', container, 'pg_dump', '-Fc', '-h', '/var/run/postgresql', '-U', 'postgres', '-d', 'postgres'], { stdio: ['ignore', outFd, 'pipe'] });
|
|
115
|
+
let err = '';
|
|
116
|
+
child.stderr.on('data', (d) => (err = (err + d).slice(-400)));
|
|
117
|
+
child.on('error', (e) => (fs.closeSync(outFd), reject(e)));
|
|
118
|
+
child.on('close', (code) => {
|
|
119
|
+
fs.closeSync(outFd);
|
|
120
|
+
if (code !== 0) {
|
|
121
|
+
fs.rmSync(file + '.part', { force: true });
|
|
122
|
+
return reject(new Error(`pg_dump: ${err.trim().split('\n').pop() || `exit ${code}`}`));
|
|
123
|
+
}
|
|
124
|
+
fs.renameSync(file + '.part', file);
|
|
125
|
+
resolve(fs.statSync(file).size);
|
|
126
|
+
});
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
module.exports = { LOCAL_PSQL, REMOTE_PSQL, localSide, cloudSide, bash, query, json, transfer, dumpLocal, mask };
|