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/global/start.js
CHANGED
|
@@ -247,7 +247,7 @@ module.exports = async (args = {}) => {
|
|
|
247
247
|
process.exitCode = 1;
|
|
248
248
|
} else {
|
|
249
249
|
waiting.stop();
|
|
250
|
-
const migrated = migrate ? await require('../utils/migrate-run')(root, config, { quietWhenNone: false }) : true;
|
|
250
|
+
const migrated = migrate ? await require('../utils/migrate-run')(root, config, { quietWhenNone: false, via: 'poad start' }) : true;
|
|
251
251
|
// Code de sortie 1 si une migration ou le seed échoue (scripts, CI)
|
|
252
252
|
if (!migrated) process.exitCode = 1;
|
|
253
253
|
if (hasReference && migrated && !(await reference.sync(root, config))) process.exitCode = 1;
|
package/package.json
CHANGED
package/project/cli.js
CHANGED
|
@@ -63,6 +63,8 @@ module.exports = {
|
|
|
63
63
|
sync: 'Old name of env clone',
|
|
64
64
|
rm: 'Remove an environment, its database and files (confirmation, --yes); never main',
|
|
65
65
|
},
|
|
66
|
+
push: 'The whole local project to a poad.io environment, the target becoming its mirror: code (poad deploy), base (rows of the project tables), auth (accounts, password hashes), s3 (storage files), refs; preview first, backup and typed confirmation for production: push [--env <name>] [--dry-run] [--only|--skip code,base,auth,s3,refs] [--tables a,b] [--with-secrets]',
|
|
67
|
+
pull: 'A whole poad.io environment into the local project (the other way of poad push): code (migrations and files), base, auth, s3, refs; preview first, local backup: pull [--env <name>] [--dry-run] [--only|--skip …] [--tables a,b] [--with-secrets]',
|
|
66
68
|
deploy: 'Send poad/ (migrations, functions, flows, api, auth, storage…, never a secret) to poad.io: deploy [--env <name>] [--dry-run] [--yes]',
|
|
67
69
|
upgrade: 'Upgrade the engine of the project (backup first), or roll back to a backup',
|
|
68
70
|
logs: 'Unified logs of the project, every service, with filters (level, since, request, flow, function, AI…) and -f',
|
package/project/deploy.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// poad deploy [--env <branche>] [--dry-run] [--yes] [--json]
|
|
1
|
+
// poad deploy [--env <branche>] [--dry-run] [--yes] [--allow-destructive | --accept-data-loss] [--json]
|
|
2
2
|
//
|
|
3
3
|
// Envoie le dossier poad/ (liste blanche, sans aucun secret : utils/cloud/bundle.js)
|
|
4
4
|
// à l'environnement du projet poad.io lié :
|
|
@@ -6,15 +6,21 @@
|
|
|
6
6
|
// x-poad-sha commit git courant, si poad/ n'a aucun changement non commité
|
|
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
|
+
// x-poad-allow-destructive 1 avec --allow-destructive (ou après confirmation) : la production applique des
|
|
10
|
+
// migrations qui perdent des données
|
|
11
|
+
// warnings : migrations appliquées modifiées depuis… (et, pour les anciens CLI, le résumé des pertes de données)
|
|
12
|
+
// data_loss : [{ file, line, statement, target, rows, kind, decision, message }] (poad.io 0.70+) : ce que les
|
|
13
|
+
// migrations en attente perdent vraiment, compté sur la base de l'environnement (utils/data-loss.js) ; silence
|
|
14
|
+
// quand la cible est créée par le même déploiement ou vide. Production : refus destructive_migrations sans
|
|
15
|
+
// x-poad-allow-destructive, avant toute écriture ; dans un terminal, le CLI demande et relance avec l'en-tête.
|
|
10
16
|
// api_exposure : fonctions et vues que l'API ne sert pas à anon ni à authenticated (SECURITY DEFINER, vues
|
|
11
17
|
// sans security_invoker, vues matérialisées), dans la base et dans les migrations en attente, avec ce que
|
|
12
18
|
// l'engine de l'environnement en fait et le correctif de chacune (poad.io 0.66.0+), jamais bloquant
|
|
13
19
|
// asynchrone (deploy_id et état non terminé) : GET …/deploys/:deploy_id jusqu'à la fin
|
|
14
20
|
//
|
|
15
21
|
// Production (main) : résumé puis confirmation, sauf --yes (obligatoire hors
|
|
16
|
-
// terminal). Codes de sortie : 0 déployé, 5 déploiement en échec
|
|
17
|
-
// migration), 4 confirmation manquante, 3 session, 2 usage, 1 autre erreur.
|
|
22
|
+
// terminal ; --yes n'accepte pas une perte de données). Codes de sortie : 0 déployé, 5 déploiement en échec
|
|
23
|
+
// (erreurs de migration), 4 confirmation manquante (ou perte de données refusée), 3 session, 2 usage, 1 autre erreur.
|
|
18
24
|
const DONE = ['succeeded', 'success', 'refused', 'done', 'deployed', 'completed', 'ok', 'failed', 'error', 'cancelled', 'canceled'];
|
|
19
25
|
const FAILED = ['failed', 'error', 'cancelled', 'canceled', 'refused'];
|
|
20
26
|
|
|
@@ -67,13 +73,25 @@ function summarize(d = {}) {
|
|
|
67
73
|
dry_run: Boolean(d.dry_run),
|
|
68
74
|
migrations: { applied: names(m.applied), pending: names(m.pending), errors },
|
|
69
75
|
message: typeof d.message === 'string' ? d.message : null,
|
|
70
|
-
// Signalé, jamais bloquant : migrations
|
|
71
|
-
warnings: (Array.isArray(d.warnings) ? d.warnings : []).map((w) => ({ message: String((w && w.message) || ''), files: Array.isArray(w && w.files) ? w.files.map(String) : [] })),
|
|
76
|
+
// Signalé, jamais bloquant : migrations appliquées modifiées, résumé des pertes de données (code data_loss)
|
|
77
|
+
warnings: (Array.isArray(d.warnings) ? d.warnings : []).map((w) => ({ message: String((w && w.message) || ''), files: Array.isArray(w && w.files) ? w.files.map(String) : [], ...(w && typeof w.code === 'string' ? { code: w.code } : {}) })),
|
|
78
|
+
data_loss: dataLossOf(d.data_loss),
|
|
79
|
+
refused: errors.some((e) => e.code === 'destructive_migrations') ? 'destructive_migrations' : null,
|
|
72
80
|
failed: errors.length > 0 || FAILED.includes(status),
|
|
73
81
|
api_exposure: exposureOf(d.api_exposure),
|
|
74
82
|
};
|
|
75
83
|
}
|
|
76
84
|
|
|
85
|
+
/** Pertes de données rendues par poad.io, ramenées aux champs connus (textes bornés) */
|
|
86
|
+
function dataLossOf(list) {
|
|
87
|
+
if (!Array.isArray(list)) return [];
|
|
88
|
+
const str = (v, n) => (typeof v === 'string' ? v.slice(0, n) : null);
|
|
89
|
+
return list
|
|
90
|
+
.filter((x) => x && typeof x.file === 'string' && typeof x.kind === 'string')
|
|
91
|
+
.slice(0, 200)
|
|
92
|
+
.map((x) => ({ file: str(x.file, 200), line: Number.isInteger(x.line) ? x.line : null, statement: str(x.statement, 300), target: str(x.target, 200), rows: typeof x.rows === 'number' ? x.rows : null, approx: Boolean(x.approx), kind: str(x.kind, 40), loss: Boolean(x.loss), decision: str(x.decision, 20), message: str(x.message, 400) }));
|
|
93
|
+
}
|
|
94
|
+
|
|
77
95
|
/** Avertissement de l'API (poad.io) ramené à la règle du CLI (utils/api-exposure) : textes en anglais */
|
|
78
96
|
function exposureOf(x) {
|
|
79
97
|
if (!x || typeof x !== 'object' || !Array.isArray(x.items)) return null;
|
|
@@ -101,7 +119,7 @@ function gitState(dir) {
|
|
|
101
119
|
}
|
|
102
120
|
|
|
103
121
|
module.exports = (args, raw) =>
|
|
104
|
-
require('../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['dry-run', 'allow-destructive'] }, async ({ opts, out }) => {
|
|
122
|
+
require('../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['dry-run', 'allow-destructive', 'accept-data-loss'] }, async ({ opts, out }) => {
|
|
105
123
|
const path = require('path');
|
|
106
124
|
const api = require('../utils/cloud/api');
|
|
107
125
|
const cli = require('../utils/cloud/cli');
|
|
@@ -118,7 +136,9 @@ module.exports = (args, raw) =>
|
|
|
118
136
|
// Tables de référence trop lourdes pour git : hors de l'archive, envoyées au magasin de références
|
|
119
137
|
const large = refStore.largeFiles(poadDir);
|
|
120
138
|
const ignored = refStore.ensureGitignore(poadDir, large);
|
|
121
|
-
// --allow-destructive
|
|
139
|
+
// --allow-destructive (alias --accept-data-loss) : la production applique sans demander les migrations qui
|
|
140
|
+
// perdent des données ; sans lui, poad.io refuse (avant toute écriture) et le CLI demande dans un terminal
|
|
141
|
+
let allowLoss = Boolean(opts['allow-destructive'] || opts['accept-data-loss']);
|
|
122
142
|
|
|
123
143
|
const env = await branches.resolve(id, { wanted: opts.env, root });
|
|
124
144
|
let b;
|
|
@@ -158,22 +178,55 @@ module.exports = (args, raw) =>
|
|
|
158
178
|
const route = `v1/projects/${api.enc(id)}/branches/${api.enc(env.branch)}`;
|
|
159
179
|
// --env des commandes proposées : omis quand poad deploy l'aurait aussi omis (production par défaut)
|
|
160
180
|
const where = env.source === 'option' || !env.production ? ` --env ${env.branch}` : '';
|
|
161
|
-
const
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
181
|
+
const send = async () => {
|
|
182
|
+
const headers = {};
|
|
183
|
+
if (sha) headers['x-poad-sha'] = sha;
|
|
184
|
+
if (dryRun) headers['x-poad-dry-run'] = '1';
|
|
185
|
+
if (allowLoss) headers['x-poad-allow-destructive'] = '1';
|
|
186
|
+
let r = summarize(await api.call('POST', `${route}/deploy`, { body: b.tgz, contentType: 'application/gzip', headers, what: 'deploy', timeout: 300000 }));
|
|
187
|
+
// Déploiement asynchrone : suivi jusqu'à son terme
|
|
188
|
+
if (r.deploy_id && r.status && !DONE.includes(r.status)) {
|
|
189
|
+
const started = Date.now();
|
|
190
|
+
let last = r.status;
|
|
191
|
+
out.log(chalk.grey(` deploy ${r.deploy_id}: ${last}…`));
|
|
192
|
+
while (!DONE.includes(r.status)) {
|
|
193
|
+
if (Date.now() - started > 15 * 60 * 1000) throw new api.CloudError(`Deploy ${r.deploy_id} still ${r.status} after 15 min: follow it on poad.io.`, { code: 'timeout' });
|
|
194
|
+
await new Promise((res) => setTimeout(res, Number(process.env.POAD_DEPLOY_POLL_MS) || 2000));
|
|
195
|
+
const next = summarize(await api.call('GET', `${route}/deploys/${api.enc(r.deploy_id)}`, { what: 'deploy status' }));
|
|
196
|
+
r = { ...next, deploy_id: next.deploy_id || r.deploy_id };
|
|
197
|
+
if (r.status !== last) out.log(chalk.grey(` deploy ${r.deploy_id}: ${(last = r.status)}`));
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
return r;
|
|
201
|
+
};
|
|
202
|
+
let result = await send();
|
|
203
|
+
const lossLines = (r) => require('../utils/migrate-run').dataLossLines(r.data_loss, chalk, { production: env.production });
|
|
204
|
+
|
|
205
|
+
// Production : des migrations perdent des données, poad.io a refusé avant toute écriture. Dans un terminal :
|
|
206
|
+
// ce qui serait perdu, puis la question ; oui : même envoi avec x-poad-allow-destructive. Sinon : refus (code 4).
|
|
207
|
+
let lossRefused = false;
|
|
208
|
+
let lossShown = false;
|
|
209
|
+
if (result.refused === 'destructive_migrations' && !allowLoss && !dryRun) {
|
|
210
|
+
out.log(' ');
|
|
211
|
+
for (const l of lossLines(result)) out.log(l);
|
|
212
|
+
lossShown = true;
|
|
213
|
+
const lost = result.data_loss.filter((d) => d.loss && d.decision === 'confirm');
|
|
214
|
+
const total = lost.reduce((n, d) => n + (d.rows || 0), 0);
|
|
215
|
+
if (cli.interactive() && !out.json) {
|
|
216
|
+
const { confirm: ask } = require('@inquirer/prompts');
|
|
217
|
+
out.log(' ');
|
|
218
|
+
const ok = await ask({ message: `Apply anyway on production (${env.branch})? ${lost.length} statement(s), ${total.toLocaleString('en-US')}${lost.some((d) => d.approx || d.rows === null) ? '+' : ''} row(s) or value(s) lost (a backup is taken first).`, default: false }).catch(() => false);
|
|
219
|
+
if (ok) {
|
|
220
|
+
allowLoss = true;
|
|
221
|
+
result = await send();
|
|
222
|
+
} else {
|
|
223
|
+
out.log(chalk.grey(' Cancelled: nothing was changed.'));
|
|
224
|
+
lossRefused = true;
|
|
225
|
+
}
|
|
226
|
+
} else {
|
|
227
|
+
out.log(chalk.redBright(' Refused: these migrations lose data on production. Nothing was changed.'));
|
|
228
|
+
out.log(chalk.grey(' Run poad deploy in a terminal to confirm, or add --allow-destructive.'));
|
|
229
|
+
lossRefused = true;
|
|
177
230
|
}
|
|
178
231
|
}
|
|
179
232
|
|
|
@@ -182,12 +235,17 @@ module.exports = (args, raw) =>
|
|
|
182
235
|
for (const n of m.applied) out.log(` ${chalk.greenBright('✔')} ${n}`);
|
|
183
236
|
for (const n of m.pending) out.log(` ${chalk.yellow('○')} ${n} ${chalk.grey(dryRun ? '(would be applied)' : '(pending)')}`);
|
|
184
237
|
for (const e of m.errors) {
|
|
238
|
+
// Refus pour pertes de données : déjà détaillé (et demandé) plus haut
|
|
239
|
+
if (e.code === 'destructive_migrations' && result.data_loss.length) continue;
|
|
185
240
|
out.log(` ${chalk.redBright('✕')} ${e.migration ? chalk.bold(e.migration) + ': ' : ''}${e.message}`);
|
|
186
241
|
// Refus : lesquelles ; migrations manquantes ou hors d'ordre : la commande qui lève le refus
|
|
187
242
|
for (const f of e.files || []) out.log(` ${chalk.yellow(f)}`);
|
|
188
243
|
for (const l of refusalLines(e, { env: env.branch, where, chalk })) out.log(l);
|
|
189
244
|
}
|
|
245
|
+
// Pertes de données (sauf si déjà montrées avec le refus) : fichier, instruction, nombre de lignes
|
|
246
|
+
if (!result.refused && !lossShown) for (const l of lossLines(result)) out.log(l);
|
|
190
247
|
for (const w of result.warnings || []) {
|
|
248
|
+
if (w.code === 'data_loss' && result.data_loss.length) continue;
|
|
191
249
|
out.log(` ${chalk.yellowBright('⚠')} ${w.message}`);
|
|
192
250
|
for (const f of w.files) out.log(` ${chalk.yellow(f)}`);
|
|
193
251
|
}
|
|
@@ -202,7 +260,8 @@ module.exports = (args, raw) =>
|
|
|
202
260
|
}
|
|
203
261
|
|
|
204
262
|
out.log(' ');
|
|
205
|
-
if (
|
|
263
|
+
if (lossRefused) out.log(chalk.redBright(' Deploy refused: pending migrations lose data on production.'));
|
|
264
|
+
else if (result.failed) out.log(chalk.redBright(` Deploy failed${references && references.failed ? ': a reference table could not be loaded' : result.message ? `: ${result.message}` : ''}.`));
|
|
206
265
|
else if (dryRun && large.length) out.log(`${chalk.greenBright('✔')} Dry run: nothing changed on ${env.branch}. ${large.map((f) => f.target).join(', ')} would go to the reference store, then be loaded.`);
|
|
207
266
|
else if (dryRun) out.log(`${chalk.greenBright('✔')} Dry run: nothing changed on ${env.branch}.`);
|
|
208
267
|
else out.log(`${chalk.greenBright('✔')} Deployed to ${env.branch}${result.deploy_id ? chalk.grey(` (${result.deploy_id})`) : ''}.`);
|
|
@@ -225,7 +284,7 @@ module.exports = (args, raw) =>
|
|
|
225
284
|
large_references: large.map((f) => ({ path: `poad/${f.rel}`, bytes: f.size, target: f.target })),
|
|
226
285
|
references,
|
|
227
286
|
});
|
|
228
|
-
return result.failed ? api.EXIT.failed : 0;
|
|
287
|
+
return lossRefused ? api.EXIT.confirm : result.failed ? api.EXIT.failed : 0;
|
|
229
288
|
});
|
|
230
289
|
|
|
231
290
|
module.exports.summarize = summarize;
|
package/project/migrate.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
// poad migrate : applique les migrations en attente de poad/migrations
|
|
1
|
+
// poad migrate [--dry-run] [--json] : applique les migrations en attente de poad/migrations (avant : ce qu'elles
|
|
2
|
+
// perdent sur la base, utils/data-loss.js, avertissement seulement en local)
|
|
2
3
|
// poad migrate pull | list | renumber : poad/migrations face à poad.io (migration-pull.js, migrate-cloud.js)
|
|
3
4
|
module.exports = async (args, raw = []) => {
|
|
4
5
|
if (raw[0] === 'pull') return require('./migration-pull')(raw.slice(1));
|
|
@@ -30,10 +31,13 @@ module.exports = async (args, raw = []) => {
|
|
|
30
31
|
let ok;
|
|
31
32
|
let refOk = true;
|
|
32
33
|
try {
|
|
33
|
-
|
|
34
|
+
// --dry-run : migrations en attente et ce qu'elles perdraient (comptées sur la base), rien d'appliqué
|
|
35
|
+
const dryRun = process.argv.includes('--dry-run');
|
|
36
|
+
ok = await require('../utils/migrate-run')(root, config, { report, exposureList: true, dryRun });
|
|
37
|
+
if (dryRun) report.dry_run = true;
|
|
34
38
|
// Tables de référence : après les migrations, quand leur structure est à jour
|
|
35
39
|
// --force-reference : le fichier fait foi même s'il retire beaucoup de lignes (garde-fou de l'engine passé)
|
|
36
|
-
if (ok) refOk = await require('../utils/reference').sync(root, config, { force: process.argv.includes('--force-reference') });
|
|
40
|
+
if (ok && !dryRun) refOk = await require('../utils/reference').sync(root, config, { force: process.argv.includes('--force-reference') });
|
|
37
41
|
} finally {
|
|
38
42
|
console.log = log;
|
|
39
43
|
}
|
package/project/pull.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// poad pull [--env <nom>] [--dry-run] [--only code,base,auth,s3,refs | --skip …] [--tables a,b] [--with-secrets]
|
|
2
|
+
// [--yes] [--project <id>] [--json]
|
|
3
|
+
// Tout un environnement de poad.io vers le projet local : utils/project-sync/run.js
|
|
4
|
+
module.exports = (args, raw) => require('../utils/project-sync/run').run('pull', raw);
|
package/project/push.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// poad push [--env <nom>] [--dry-run] [--only code,base,auth,s3,refs | --skip …] [--tables a,b] [--with-secrets]
|
|
2
|
+
// [--allow-destructive] [--yes] [--confirm <id>] [--project <id>] [--json]
|
|
3
|
+
// Tout le projet local vers un environnement de poad.io : utils/project-sync/run.js
|
|
4
|
+
module.exports = (args, raw) => require('../utils/project-sync/run').run('push', raw);
|
package/test/cloud.test.js
CHANGED
|
@@ -81,6 +81,7 @@ function fakeCloud(t, behaviour = {}) {
|
|
|
81
81
|
if (req.method === 'GET' && rest === '/engine') return send(res, 200, { current: '0.38.0', offered: '0.39.0', available: true, reason: null });
|
|
82
82
|
if (req.method === 'POST' && rest === '/upgrade') return send(res, 202, { state: 'running', to: json().to });
|
|
83
83
|
if (req.method === 'GET' && rest === '/db-password') return send(res, 200, { user: `postgres.${id}`, password: DB_PASSWORD, host: 'db.poad.io', session_port: 5432, transaction_port: 6543 });
|
|
84
|
+
if (req.method === 'GET' && rest === '/branches/dev/db-password') return send(res, 200, { user: `postgres.${id}--dev`, password: DB_PASSWORD, host: 'db.poad.io', session_port: 5432, transaction_port: 6543 });
|
|
84
85
|
if (req.method === 'GET' && rest === '/branches') return send(res, 200, { branches: state.branches[id] });
|
|
85
86
|
if (req.method === 'POST' && rest === '/branches') {
|
|
86
87
|
const b = { name: json().name, kind: json().kind, status: 'creating' };
|
|
@@ -107,6 +108,15 @@ function fakeCloud(t, behaviour = {}) {
|
|
|
107
108
|
if (req.method === 'POST' && m[2] === '/deploy') {
|
|
108
109
|
const dry = req.headers['x-poad-dry-run'] === '1';
|
|
109
110
|
if (behaviour.refuse) return send(res, 200, { deploy_id: 'dr', outcome: 'refused', dry_run: dry, migrations_applied: [], migrations_pending: [], errors: [behaviour.refuse] });
|
|
111
|
+
// Pertes de données (push.sh, control/data-loss.cjs) : production refusée sans x-poad-allow-destructive
|
|
112
|
+
if (behaviour.dataLoss) {
|
|
113
|
+
const prod = branch === 'main';
|
|
114
|
+
const allow = req.headers['x-poad-allow-destructive'] === '1';
|
|
115
|
+
const item = (decision) => ({ file: '20261204212826_sans_fichier.sql', line: 2, statement: 'alter table public.documents drop column fichier', target: 'public.documents.fichier', rows: 1240, approx: false, kind: 'drop_column', loss: true, decision, message: 'DROP COLUMN public.documents.fichier — 1,240 non-null value(s) will be lost' });
|
|
116
|
+
const summary = { message: 'pending migrations lose data or break API clients', files: ['20261204212826_sans_fichier.sql'], code: 'data_loss' };
|
|
117
|
+
if (prod && !allow && !dry) return send(res, 200, { deploy_id: 'dl', outcome: 'refused', migrations_applied: [], migrations_pending: ['20261204212826_sans_fichier.sql'], errors: [{ code: 'destructive_migrations', message: 'pending migrations lose data on production', files: ['20261204212826_sans_fichier.sql'] }], warnings: [], data_loss: [item('confirm')] });
|
|
118
|
+
return send(res, 200, { deploy_id: 'dl', outcome: 'success', dry_run: dry, migrations_applied: dry ? [] : ['20261204212826_sans_fichier.sql'], migrations_pending: dry ? ['20261204212826_sans_fichier.sql'] : [], errors: [], warnings: [summary], data_loss: [item(!prod ? 'warn' : allow ? 'accepted' : 'confirm')] });
|
|
119
|
+
}
|
|
110
120
|
if (behaviour.async) {
|
|
111
121
|
state.deploys.d1 = 0;
|
|
112
122
|
// La forme réelle de poad.io (control/server.mjs, deployView) : outcome, migrations_applied…
|
|
@@ -558,9 +568,11 @@ test('db url : mot de passe masqué par défaut, --show-password l’affiche, mo
|
|
|
558
568
|
assert.strictEqual(cloud.requests.at(-1).query.purpose, 'reveal');
|
|
559
569
|
const bad = await poad(box, cloud.api, ['db', 'url', '--mode', 'pool']);
|
|
560
570
|
assert.strictEqual(bad.status, 2);
|
|
571
|
+
// Un environnement : sa propre base (postgres.<id>--<branche>, route par branche de poad.io)
|
|
561
572
|
const dev = await poad(box, cloud.api, ['db', 'url', '--env', 'dev']);
|
|
562
|
-
assert.strictEqual(dev.status,
|
|
563
|
-
assert.match(dev.
|
|
573
|
+
assert.strictEqual(dev.status, 0, dev.all);
|
|
574
|
+
assert.match(dev.stdout, new RegExp(`postgresql://postgres\\.${PID}--dev:•+@db\\.poad\\.io:5432/postgres`));
|
|
575
|
+
assert.ok(!dev.all.includes(DB_PASSWORD));
|
|
564
576
|
});
|
|
565
577
|
|
|
566
578
|
test('db pull : pg_dump --schema-only avec PGPASSWORD (jamais en argument), nouvelle migration à chaque fois', async (t) => {
|
|
@@ -827,3 +839,44 @@ test('pendingToRenumber : pure', () => {
|
|
|
827
839
|
assert.deepStrictEqual(pendingToRenumber([l('20261109000000'), l('20261101000000'), l('20261111000000')], remote).map((m) => m.version), ['20261101000000', '20261109000000', '20261111000000']);
|
|
828
840
|
assert.deepStrictEqual(pendingToRenumber([l('20261101000000')], []), []);
|
|
829
841
|
});
|
|
842
|
+
|
|
843
|
+
test('deploy : pertes de données (à la Prisma) : recette avertie ; production refusée hors terminal (code 4), --allow-destructive passe ; --json data_loss', async (t) => {
|
|
844
|
+
const box = sandbox(t);
|
|
845
|
+
const cloud = await fakeCloud(t, { dataLoss: true });
|
|
846
|
+
await login(box, cloud);
|
|
847
|
+
await poad(box, cloud.api, ['link', PID]);
|
|
848
|
+
git(box.app, 'commit', '-qam', 'link');
|
|
849
|
+
|
|
850
|
+
// Recette : avertissement avec fichier, instruction et nombre ; jamais de question
|
|
851
|
+
const dev = await poad(box, cloud.api, ['deploy', '--env', 'dev']);
|
|
852
|
+
assert.strictEqual(dev.status, 0, dev.all);
|
|
853
|
+
assert.match(dev.stdout, /20261204212826_sans_fichier\.sql:2\s+DROP COLUMN public\.documents\.fichier — 1,240 non-null value\(s\) will be lost/);
|
|
854
|
+
assert.match(dev.stdout, /alter table public\.documents drop column fichier/);
|
|
855
|
+
assert.doesNotMatch(dev.stdout, /pending migrations lose data or break API clients\n/, 'résumé des anciens CLI remplacé par le détail');
|
|
856
|
+
|
|
857
|
+
// Production, hors terminal, --yes : refus (--yes n'accepte pas une perte de données), rien appliqué
|
|
858
|
+
const refused = await poad(box, cloud.api, ['deploy', '--yes']);
|
|
859
|
+
assert.strictEqual(refused.status, 4, refused.all);
|
|
860
|
+
assert.match(refused.stdout, /1,240 non-null value\(s\) will be lost/);
|
|
861
|
+
assert.match(refused.stdout, /--allow-destructive/);
|
|
862
|
+
assert.match(refused.stdout, /Deploy refused/);
|
|
863
|
+
assert.strictEqual(cloud.requests.filter((q) => q.route.endsWith('/main/deploy')).length, 1, 'un seul envoi');
|
|
864
|
+
|
|
865
|
+
const j = jsonOf(await poad(box, cloud.api, ['deploy', '--yes', '--json']));
|
|
866
|
+
assert.strictEqual(j.refused, 'destructive_migrations');
|
|
867
|
+
assert.deepStrictEqual(Object.fromEntries(['file', 'statement', 'target', 'rows', 'kind'].map((k) => [k, j.data_loss[0][k]])), { file: '20261204212826_sans_fichier.sql', statement: 'alter table public.documents drop column fichier', target: 'public.documents.fichier', rows: 1240, kind: 'drop_column' });
|
|
868
|
+
|
|
869
|
+
// --dry-run : la même chose, sans refus ni envoi de l'en-tête
|
|
870
|
+
const dry = await poad(box, cloud.api, ['deploy', '--dry-run']);
|
|
871
|
+
assert.strictEqual(dry.status, 0, dry.all);
|
|
872
|
+
assert.match(dry.stdout, /1,240 non-null value\(s\) will be lost/);
|
|
873
|
+
assert.match(dry.stdout, /data is lost only after a confirmation/);
|
|
874
|
+
|
|
875
|
+
// --allow-destructive (ou --accept-data-loss) : l'en-tête part, déployé
|
|
876
|
+
for (const flag of ['--allow-destructive', '--accept-data-loss']) {
|
|
877
|
+
const ok = await poad(box, cloud.api, ['deploy', '--yes', flag]);
|
|
878
|
+
assert.strictEqual(ok.status, 0, ok.all);
|
|
879
|
+
assert.strictEqual(cloud.requests.filter((q) => q.route.endsWith('/main/deploy')).at(-1).headers['x-poad-allow-destructive'], '1');
|
|
880
|
+
assert.match(ok.stdout, /Deployed to main/);
|
|
881
|
+
}
|
|
882
|
+
});
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// Avertissement à la Prisma (utils/data-loss.js) : lecture des migrations, décision. Sans base : les résultats
|
|
2
|
+
// des requêtes sont donnés à la main (le comptage réel est essayé sur un projet jetable, poad migrate).
|
|
3
|
+
const test = require('node:test');
|
|
4
|
+
const assert = require('node:assert');
|
|
5
|
+
const dl = require('../utils/data-loss');
|
|
6
|
+
|
|
7
|
+
const kinds = (sql) => dl.analyze([{ file: '20261204212826_x.sql', sql }]).map((f) => `${f.kind} ${f.schema}${f.table ? '.' + f.table : ''}${f.column ? '.' + f.column : ''}`);
|
|
8
|
+
|
|
9
|
+
test('commentaires, chaînes et corps de fonctions ($$, BEGIN ATOMIC) ignorés', () => {
|
|
10
|
+
const sql = `-- drop table a;
|
|
11
|
+
/* drop table b; /* imbriqué */ truncate c; */
|
|
12
|
+
create function f() returns void language plpgsql as $$ begin drop table z; delete from w; end $$;
|
|
13
|
+
create function g() returns void language plpgsql as $body$ begin execute 'truncate q'; end $body$;
|
|
14
|
+
do $x$ begin alter table t drop column c; end $x$;
|
|
15
|
+
select 'drop table k', E'it\\'s; drop table j', "drop table";
|
|
16
|
+
create function h() returns int language sql begin atomic select case when true then 1 end; delete from inatomic; end;
|
|
17
|
+
drop table vraie;`;
|
|
18
|
+
assert.deepStrictEqual(kinds(sql), ['drop_table public.vraie']);
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
test('instructions repérées avec leur cible', () => {
|
|
22
|
+
const sql = `ALTER TABLE public.documents DROP COLUMN fichier, ADD COLUMN x int DEFAULT f(1, 2), ALTER COLUMN n TYPE numeric(5,2) USING n::numeric;
|
|
23
|
+
alter table t drop constraint k, alter column c drop default, alter column d set not null;
|
|
24
|
+
truncate table a, only s.b restart identity;
|
|
25
|
+
delete from logs; delete from s.l2 where id in (select id from z);
|
|
26
|
+
with d as (delete from old returning *) select 1;
|
|
27
|
+
drop table if exists t1, "Mixte".T2 cascade; drop schema arch cascade;
|
|
28
|
+
alter table x rename column a to b; alter table x rename to y; alter table x rename constraint k to l;
|
|
29
|
+
drop view if exists v1; drop function g(int, text);`;
|
|
30
|
+
assert.deepStrictEqual(kinds(sql), [
|
|
31
|
+
'drop_column public.documents.fichier',
|
|
32
|
+
'alter_type public.documents.n',
|
|
33
|
+
'truncate public.a',
|
|
34
|
+
'truncate s.b',
|
|
35
|
+
'delete public.logs',
|
|
36
|
+
'delete_where s.l2',
|
|
37
|
+
'delete public.old',
|
|
38
|
+
'drop_table public.t1',
|
|
39
|
+
'drop_table Mixte.t2',
|
|
40
|
+
'drop_schema arch',
|
|
41
|
+
'rename_column public.x.a',
|
|
42
|
+
'rename_table public.x',
|
|
43
|
+
'drop_view public.v1',
|
|
44
|
+
'drop_function public.g',
|
|
45
|
+
]);
|
|
46
|
+
const [f] = dl.analyze([{ file: 'a.sql', sql: '\n\nalter table documents\n drop column fichier; -- fin' }]);
|
|
47
|
+
assert.strictEqual(f.line, 3);
|
|
48
|
+
assert.strictEqual(f.statement, 'alter table documents drop column fichier');
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
test('renommage dans le lot : la cible est cherchée sous son nom sur la base ; vue recréée : silence', () => {
|
|
52
|
+
const f = dl.analyze([
|
|
53
|
+
{ file: '1.sql', sql: 'alter table old_name rename to new_name;' },
|
|
54
|
+
{ file: '2.sql', sql: 'alter table new_name drop column c; drop view if exists v; create or replace view v as select 1;' },
|
|
55
|
+
]);
|
|
56
|
+
assert.deepStrictEqual(f[1].db, { schema: 'public', table: 'old_name', column: 'c' });
|
|
57
|
+
assert.strictEqual(f[2].recreated, true);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
const one = (sql, result, opts) => {
|
|
61
|
+
const findings = dl.analyze([{ file: '20261204212826_x.sql', sql }]);
|
|
62
|
+
return dl.decide(findings, [result], opts)[0];
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
test('décision : base neuve (cible absente) et table vide : silence', () => {
|
|
66
|
+
assert.strictEqual(one('drop table documents;', { exists: false }).decision, 'silent');
|
|
67
|
+
assert.strictEqual(one('drop table documents;', { exists: false }, { production: true }).reason, 'target_absent');
|
|
68
|
+
assert.strictEqual(one('alter table documents drop column fichier;', { exists: true, relkind: 'r', column: true, rows: 0 }, { production: true }).decision, 'silent');
|
|
69
|
+
assert.strictEqual(one('alter table documents drop column fichier;', { exists: true, relkind: 'r', column: false, rows: null }).reason, 'target_absent');
|
|
70
|
+
assert.strictEqual(one('drop table ft;', { exists: true, relkind: 'f', rows: null }).reason, 'foreign_table');
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
test('décision : table pleine + DROP COLUMN : avertissement avec le nombre ; production : confirmation ; acceptée', () => {
|
|
74
|
+
const r = { exists: true, relkind: 'r', column: true, rows: 1240 };
|
|
75
|
+
const w = one('alter table public.documents drop column fichier;', r);
|
|
76
|
+
assert.strictEqual(w.decision, 'warn');
|
|
77
|
+
assert.strictEqual(w.message, 'DROP COLUMN public.documents.fichier — 1,240 non-null value(s) will be lost');
|
|
78
|
+
assert.strictEqual(one('alter table public.documents drop column fichier;', r, { production: true }).decision, 'confirm');
|
|
79
|
+
assert.strictEqual(one('alter table public.documents drop column fichier;', r, { production: true, accepted: true }).decision, 'accepted');
|
|
80
|
+
// Comptage impossible (délai) : prudence, comme une perte
|
|
81
|
+
assert.strictEqual(one('truncate documents;', null, { production: true }).decision, 'confirm');
|
|
82
|
+
// JSON : { file, statement, target, rows, kind }
|
|
83
|
+
const [j] = dl.jsonOf([w]);
|
|
84
|
+
assert.deepStrictEqual([j.file, j.statement, j.target, j.rows, j.kind], ['20261204212826_x.sql', 'alter table public.documents drop column fichier', 'public.documents.fichier', 1240, 'drop_column']);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
test('décision : conversions sans perte, renommages et vues hors API', () => {
|
|
88
|
+
assert.strictEqual(one('alter table t alter column c type text;', { exists: true, relkind: 'r', column: true, rows: 5, type: 'character varying(20)' }).reason, 'lossless_conversion');
|
|
89
|
+
assert.strictEqual(one('alter table t alter column c type bigint;', { exists: true, relkind: 'r', column: true, rows: 5, type: 'integer' }).reason, 'lossless_conversion');
|
|
90
|
+
assert.strictEqual(one('alter table t alter column c type integer;', { exists: true, relkind: 'r', column: true, rows: 5, type: 'text' }, { production: true }).decision, 'confirm');
|
|
91
|
+
const ren = one('alter table t rename column a to b;', { exists: true, relkind: 'r', column: true, rows: 5 }, { production: true });
|
|
92
|
+
assert.deepStrictEqual([ren.decision, ren.loss], ['warn', false]);
|
|
93
|
+
assert.strictEqual(one('drop view v;', { exists: true, relkind: 'v', api: false }).reason, 'not_exposed');
|
|
94
|
+
assert.strictEqual(one('drop view v;', { exists: true, relkind: 'v', api: true }).decision, 'warn');
|
|
95
|
+
assert.strictEqual(one('drop view private.v;', { exists: true, relkind: 'v', api: true }).reason, 'not_exposed');
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
test('script psql et lecture de sa sortie ; ligne de journal sans instruction', () => {
|
|
99
|
+
const findings = dl.analyze([{ file: 'x.sql', sql: "alter table documents drop column fichier; delete from notes where body = 'secret';" }]);
|
|
100
|
+
const s = dl.script(dl.checks(findings));
|
|
101
|
+
assert.match(s, /^begin transaction read only;/);
|
|
102
|
+
assert.match(s, /statement_timeout = '3s'/);
|
|
103
|
+
assert.doesNotMatch(s, /secret/);
|
|
104
|
+
const res = dl.parseOutput('0 e {"exists":true,"relkind":"r","column":true,"rows":3}\n1 f {"exists":true,"relkind":"r","rows":7}\n', 2);
|
|
105
|
+
assert.strictEqual(res[0].rows, 3);
|
|
106
|
+
assert.deepStrictEqual([res[1].rows, res[1].approx], [7, true]);
|
|
107
|
+
const d = dl.decide(findings, res);
|
|
108
|
+
const a = dl.logAttrs(d[1]);
|
|
109
|
+
assert.strictEqual(a.event, 'migration_data_loss_check');
|
|
110
|
+
assert.strictEqual(a.target, 'public.notes');
|
|
111
|
+
assert.doesNotMatch(JSON.stringify(a) + dl.logMsg(d[1]), /secret|body/);
|
|
112
|
+
});
|