poad 2.76.1 → 2.76.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "poad",
3
- "version": "2.76.1",
3
+ "version": "2.76.2",
4
4
  "engine": "0.28.0",
5
5
  "runner": "0.5.0",
6
6
  "main": "index.js",
package/project/deploy.js CHANGED
@@ -98,7 +98,13 @@ function exposureOf(x) {
98
98
  const items = x.items
99
99
  .filter((i) => i && typeof i.schema === 'string' && typeof i.name === 'string')
100
100
  .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 }));
101
- const out = require('../utils/api-exposure').impact({ current: x.current || null, target: x.target || x.current || null, items });
101
+ // Fonctions DEFINER des politiques RLS : à part, sans correctif (poad.io 0.70+ les sépare ; sinon policies/policies_indirect)
102
+ const policy_functions = (Array.isArray(x.policy_functions) ? x.policy_functions : []).filter((i) => i && typeof i.schema === 'string' && typeof i.name === 'string');
103
+ for (const i of items) {
104
+ const raw = x.items.find((r) => r && r.schema === i.schema && r.name === i.name && String(r.kind || '') === i.kind);
105
+ if (raw && (raw.policies || raw.policies_indirect || raw.policy)) Object.assign(i, { policies: raw.policies, policies_indirect: raw.policies_indirect, policy: raw.policy });
106
+ }
107
+ const out = require('../utils/api-exposure').impact({ current: x.current || null, target: x.target || x.current || null, items, policy_functions });
102
108
  // La décision du serveur prime (il connaît la version de l'environnement)
103
109
  if (typeof x.change === 'string') out.change = x.change;
104
110
  return out;
@@ -119,7 +125,7 @@ function gitState(dir) {
119
125
  }
120
126
 
121
127
  module.exports = (args, raw) =>
122
- require('../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['dry-run', 'allow-destructive', 'accept-data-loss'] }, async ({ opts, out }) => {
128
+ require('../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['dry-run', 'allow-destructive', 'accept-data-loss', 'verbose'] }, async ({ opts, out }) => {
123
129
  const path = require('path');
124
130
  const api = require('../utils/cloud/api');
125
131
  const cli = require('../utils/cloud/cli');
@@ -168,7 +174,8 @@ module.exports = (args, raw) =>
168
174
  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)`));
169
175
  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.`));
170
176
  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).`));
171
- for (const f of large) out.log(chalk.grey(` ${f.rel} (${kb(f.size)}): too large for git: reference store, sent only if it changed (sha256), loaded if not yet loaded in ${env.branch}`));
177
+ // Grosses références : une ligne chacune ; ce qui les attend (déjà chargée, à charger…) est dit après les migrations
178
+ if (large.length) out.log(chalk.grey(` ${large.length} reference file(s) too large for git, through the reference store: ${large.map((f) => `${f.rel} (${kb(f.size)})`).join(', ')}`));
172
179
  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}`));
173
180
 
174
181
  if (env.production && !dryRun) {
@@ -251,18 +258,26 @@ module.exports = (args, raw) =>
251
258
  }
252
259
  if (!m.applied.length && !m.pending.length && !m.errors.length) out.log(chalk.grey(' No migration to apply.'));
253
260
  // Ce que l'API ne sert pas à anon ni à authenticated : jamais bloquant, toujours dit (avec le correctif)
254
- for (const l of require('../utils/api-exposure').lines(result.api_exposure, chalk)) out.log(l);
261
+ // Fonctions DEFINER appelées par des politiques RLS : normales, hors sortie par défaut (--verbose, --json)
262
+ for (const l of require('../utils/api-exposure').lines(result.api_exposure, chalk, { verbose: Boolean(opts.verbose) })) out.log(l);
255
263
  // Grosses références : après les migrations (les tables existent), envoi puis chargement
264
+ // État lu dans la base de l'environnement (marque posée au chargement, lignes) : un volume recréé vide recharge
256
265
  let references = null;
257
- if (large.length && !dryRun && !result.failed) {
258
- references = await refStore.sendAndLoad(id, env.branch, poadDir, large, opts, out);
259
- if (references.failed) result.failed = true;
266
+ if (large.length && !result.failed && !lossRefused) {
267
+ out.log(' ');
268
+ try {
269
+ references = await refStore.sendAndLoad(id, env.branch, poadDir, large, opts, out, { dryRun });
270
+ } catch (e) {
271
+ if (!dryRun) throw e;
272
+ out.log(chalk.yellowBright(` ⚠ reference tables: state not readable (${e.message})`));
273
+ }
274
+ if (references && references.failed) result.failed = true;
260
275
  }
261
276
 
262
277
  out.log(' ');
263
278
  if (lossRefused) out.log(chalk.redBright(' Deploy refused: pending migrations lose data on production.'));
264
279
  else if (result.failed) out.log(chalk.redBright(` Deploy failed${references && references.failed ? ': a reference table could not be loaded' : result.message ? `: ${result.message}` : ''}.`));
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.`);
280
+ else if (dryRun && references && references.tables.some((t) => t.action !== 'unchanged')) out.log(`${chalk.greenBright('✔')} Dry run: nothing changed on ${env.branch}. ${references.tables.filter((t) => t.action !== 'unchanged').map((t) => t.target).join(', ')} would be ${references.tables.some((t) => t.action === 'send') ? 'sent and ' : ''}loaded.`);
266
281
  else if (dryRun) out.log(`${chalk.greenBright('✔')} Dry run: nothing changed on ${env.branch}.`);
267
282
  else out.log(`${chalk.greenBright('✔')} Deployed to ${env.branch}${result.deploy_id ? chalk.grey(` (${result.deploy_id})`) : ''}.`);
268
283
  out.log(' ');
@@ -37,7 +37,7 @@ module.exports = async (args, raw = []) => {
37
37
  if (dryRun) report.dry_run = true;
38
38
  // Tables de référence : après les migrations, quand leur structure est à jour
39
39
  // --force-reference : le fichier fait foi même s'il retire beaucoup de lignes (garde-fou de l'engine passé)
40
- if (ok && !dryRun) 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'), via: 'poad migrate' });
41
41
  } finally {
42
42
  console.log = log;
43
43
  }
@@ -6,8 +6,8 @@ module.exports = async () => {
6
6
  console.log(' ');
7
7
  console.log(` ${c('poad ref inspect <file>')} What the file holds, column by column, and its weight: nothing is sent`);
8
8
  console.log(` ${c('poad ref push <file>')} Send each table of a .sql (INSERT, COPY) or .csv file as a reference table`);
9
- console.log(` ${c('poad ref ls')} Reference tables stored on poad.io, and what each environment has loaded`);
10
- console.log(` ${c('poad ref load [table…]')} Load them into an environment (--env), or into the local engine (--local)`);
9
+ console.log(` ${c('poad ref ls')} Reference tables stored on poad.io, and their state in each environment (read in its database)`);
10
+ console.log(` ${c('poad ref load [table…]')} Load them into an environment (--env), or into the local engine (--local); already loaded: skipped (--force)`);
11
11
  console.log(` ${c('poad ref rm <table>')} Remove a reference from poad.io (the table keeps its rows)`);
12
12
  console.log(' ');
13
13
  console.log(chalk.grey(' Reference tables (municipalities, code lists…) are part of the project and are loaded everywhere,'));
@@ -1,25 +1,50 @@
1
- // poad ref load [table…] [--env <branche>] [--project <id>] [--json]
1
+ // poad ref load [table…] [--env <branche>] [--project <id>] [--force] [--json]
2
2
  // poad ref load [table…] --local : dans l'engine Docker du projet de ce dossier
3
- // Sans table : toutes celles du registre (--reference : seulement les références).
3
+ // Sans table : toutes celles du registre. Une table déjà chargée (marque posée au chargement, à l'empreinte du
4
+ // registre, autant de lignes qu'à la pose : lu dans la base visée) n'est pas rechargée, sauf --force.
4
5
  module.exports = (args, raw) =>
5
- require('../../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['local'] }, async ({ opts, positionals, out }) => {
6
+ require('../../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['local', 'force'] }, async ({ opts, positionals, out }) => {
6
7
  const api = require('../../utils/cloud/api');
7
8
  const cli = require('../../utils/cloud/cli');
9
+ const refStore = require('../../utils/reference-store');
8
10
  const { parseTarget } = require('../../utils/seed/convert');
9
11
  const S = require('../../utils/seed/run');
12
+ const A = require('../../utils/seed/apply');
10
13
  const { chalk } = out;
14
+ const force = Boolean(opts.force);
11
15
  const targets = positionals.map((t) => {
12
16
  const v = parseTarget(t);
13
17
  if (!v) throw api.usageError(`"${t}" is not schema.table`);
14
18
  return v;
15
19
  });
20
+ const pick = (items) => {
21
+ if (!targets.length) return items;
22
+ const missing = targets.filter((t) => !items.some((s) => s.target === t));
23
+ if (missing.length) throw api.usageError(`unknown reference: ${missing.join(', ')} ("poad ref ls")`);
24
+ return items.filter((s) => targets.includes(s.target));
25
+ };
16
26
  const { id, root } = cli.targetProject(opts);
17
27
  if (!opts.local) {
18
28
  const branches = require('../../utils/cloud/branches');
19
29
  const env = await branches.resolve(id, { wanted: opts.env, root });
30
+ const registry = await api.call('GET', `v1/projects/${api.enc(id)}/seeds?verify=${encodeURIComponent(env.branch)}`, { what: 'references' });
31
+ const items = pick(registry.items || []);
32
+ if (!items.length) throw api.usageError('No reference to load ("poad ref ls").');
33
+ const todo = [];
34
+ for (const s of items) {
35
+ const st = refStore.cloudState(registry, env.branch, s.target, s.sha256);
36
+ const loaded = st.state === 'loaded';
37
+ const line = { target: s.target, action: loaded && !force ? 'loaded' : 'load', state: loaded ? 'forced' : st.state, rows: st.rows, mark_rows: st.mark_rows, sha256: st.sha256 || s.sha256, expected_rows: s.rows, checked: st.checked };
38
+ out.log(refStore.planLine(line, env.branch, chalk));
39
+ if (!loaded || force) todo.push(s.target);
40
+ }
41
+ if (!todo.length) {
42
+ out.result({ project: id, branch: env.branch, load: null, unchanged: items.map((s) => s.target) });
43
+ return 0;
44
+ }
20
45
  const { startAndWait } = require('./push');
21
- const l = await startAndWait(id, env.branch, targets.length ? targets : undefined, opts, out);
22
- out.result({ project: id, load: l });
46
+ const l = await startAndWait(id, env.branch, todo, opts, out);
47
+ out.result({ project: id, branch: env.branch, load: l, unchanged: items.map((s) => s.target).filter((t) => !todo.includes(t)) });
23
48
  return l.status === 'failed' ? api.EXIT.failed : 0;
24
49
  }
25
50
  // Engine local : le projet de ce dossier, démarré
@@ -27,25 +52,40 @@ module.exports = (args, raw) =>
27
52
  const { readConfig } = require('../../utils/config');
28
53
  const { isDockerExist } = require('../../utils/docker');
29
54
  const config = readConfig(root);
30
- if (!(await isDockerExist(config.project_uuid))) throw api.usageError('The local project is not started: "poad start".');
31
- const list = await api.call('GET', `v1/projects/${api.enc(id)}/seeds`, { what: 'references' });
32
- let items = list.items;
33
- if (targets.length) {
34
- const missing = targets.filter((t) => !items.some((s) => s.target === t));
35
- if (missing.length) throw api.usageError(`unknown reference: ${missing.join(', ')} ("poad ref ls")`);
36
- items = items.filter((s) => targets.includes(s.target));
37
- }
55
+ const container = config.project_uuid;
56
+ if (!(await isDockerExist(container))) throw api.usageError('The local project is not started: "poad start".');
57
+ const list = await api.call('GET', `v1/projects/${api.enc(id)}/seeds?verify=0`, { what: 'references' });
58
+ const items = pick(list.items || []);
38
59
  if (!items.length) throw api.usageError('No reference to load ("poad ref ls").');
39
- const A = require('../../utils/seed/apply');
40
- const order = A.loadOrder(items.map((s) => s.target), await S.localEdges(config.project_uuid));
60
+ const order = A.loadOrder(items.map((s) => s.target), await S.localEdges(container));
61
+ // État réel dans la base locale : une base remise à zéro ou une table vidée redeviennent « à charger »
62
+ const state = await S.localState(container, order);
63
+ if (!state) throw new api.CloudError('The local database cannot be read.', { code: 'local_db' });
41
64
  const results = [];
42
65
  for (const target of order) {
66
+ const s = items.find((x) => x.target === target);
67
+ const raw = state[target];
68
+ const st = A.referenceState(s.sha256, raw);
69
+ await S.localLog(container, [{ msg: `reference ${target}: ${st}`, attrs: { event: 'reference_state', table: target, state: st, rows: raw ? raw.rows : null, mark_rows: raw ? raw.mark_rows : null, sha256: s.sha256.slice(0, 12), env: 'local', via: 'poad ref load' } }]);
70
+ const line = { target, action: st === 'loaded' && !force ? 'loaded' : 'load', state: st === 'loaded' ? 'forced' : st, rows: raw ? raw.rows : null, mark_rows: raw ? raw.mark_rows : null, sha256: s.sha256, expected_rows: s.rows };
71
+ out.log(refStore.stateLine(line, 'locally', chalk));
72
+ if (st === 'no_table') {
73
+ results.push({ target, state: st, action: 'none' });
74
+ continue;
75
+ }
76
+ if (line.action === 'loaded') {
77
+ results.push({ target, state: st, action: 'unchanged', rows: raw.rows });
78
+ continue;
79
+ }
43
80
  const t0 = Date.now();
44
81
  const d = await api.call('POST', `v1/projects/${api.enc(id)}/seeds/download`, { body: { target }, what: `reference ${target}` });
45
- const r = await S.loadLocal(config.project_uuid, d);
46
- out.log(`${chalk.greenBright('✔')} ${target} loaded locally: ${r.written} rows written, ${r.deleted} removed (${((Date.now() - t0) / 1000).toFixed(1)} s)`);
82
+ const r = await S.loadLocal(container, d);
83
+ const ms = Date.now() - t0;
84
+ out.log(`${chalk.greenBright('✔')} ${target} loaded locally: ${r.written} rows written, ${r.deleted} removed (${(ms / 1000).toFixed(1)} s)`);
47
85
  for (const w of r.warnings || []) out.log(chalk.yellowBright(` ⚠ ${w}`));
48
- results.push({ target, ...r });
86
+ await S.localLog(container, [{ msg: `reference ${target} loaded locally: ${r.written} rows`, attrs: { event: 'reference_load', table: target, outcome: 'loaded', reason: st, rows: r.written, deleted: r.deleted, duration_ms: ms, sha256: s.sha256.slice(0, 12), env: 'local', via: 'poad ref load' } }]);
87
+ results.push({ target, state: st, action: 'loaded', ...r });
49
88
  }
50
89
  out.result({ project: id, local: true, tables: results });
90
+ return results.some((r) => r.state === 'no_table') ? api.EXIT.failed : 0;
51
91
  });
package/project/ref/ls.js CHANGED
@@ -1,4 +1,5 @@
1
1
  // poad ref ls [--project <id>] [--json] : registre des références, quota, ce que chaque environnement a chargé
2
+ // (lu dans sa base par poad.io : déjà chargée, lignes et empreinte, ou à charger et pourquoi)
2
3
  module.exports = (args, raw) =>
3
4
  require('../../utils/cloud/cli').run(raw, { values: ['project'] }, async ({ opts, out }) => {
4
5
  const api = require('../../utils/cloud/api');
@@ -12,15 +13,24 @@ module.exports = (args, raw) =>
12
13
  if (!r.store) out.log(chalk.yellowBright(' The reference store is not configured on this poad.io instance.'));
13
14
  out.log(` Store: ${fmt(r.quota.used)} used of ${fmt(r.quota.limit)} (account quota, outside the project volume)`);
14
15
  if (!r.items.length) return out.log(chalk.grey(' No reference stored yet: poad ref inspect <file>, then poad ref push <file>'));
15
- const envs = Object.keys(r.applied);
16
+ // État lu dans la base de chaque environnement (poad.io : marque posée au chargement, lignes) ; sinon son registre
17
+ const { WHY } = require('../../utils/reference-store');
18
+ const envs = [...new Set([...Object.keys(r.state || {}), ...Object.keys(r.applied)])];
19
+ const n = (x) => Number(x || 0).toLocaleString('en-US');
16
20
  out.log('');
17
21
  for (const s of r.items) {
18
22
  const state = envs.map((e) => {
19
- const a = r.applied[e][s.target];
20
- return a ? (a.sha256 === s.sha256 ? chalk.greenBright(`${e} ✔`) : chalk.yellowBright(`${e} outdated`)) : null;
23
+ const v = r.state && r.state[e] && r.state[e][s.target];
24
+ if (v && v.state === 'loaded') return chalk.greenBright(`${e}: already loaded (${n(v.rows)} rows, sha256 ${String(v.sha256).slice(0, 12)})`);
25
+ if (v && v.state === 'incomplete') return chalk.yellowBright(`${e}: to load (${n(v.rows)} of ${n(v.mark_rows)} rows)`);
26
+ if (v && WHY[v.state]) return chalk.yellowBright(`${e}: to load (${WHY[v.state]})`);
27
+ const a = r.applied[e] && r.applied[e][s.target];
28
+ const note = v && v.state === 'not_running' ? ', engine stopped: not checked' : v ? ', not checked' : '';
29
+ if (a) return a.sha256 === s.sha256 ? chalk.green(`${e}: loaded as recorded${note}`) : chalk.yellowBright(`${e}: to load (another version is loaded${note})`);
30
+ return v ? chalk.grey(`${e}: not loaded${note}`) : null;
21
31
  }).filter(Boolean);
22
32
  out.log(` ${chalk.bold(s.target)} ${s.rows} rows ${fmt(s.stored_bytes)} stored${s.db_bytes ? `, ≈ ${fmt(s.db_bytes)} in the database` : ''} ${chalk.grey(s.source || '')}${s.dropped && s.dropped.length ? chalk.grey(` without ${s.dropped.join(', ')}`) : ''}`);
23
- out.log(` ${state.length ? state.join(' ') : chalk.grey('not loaded anywhere yet')}`);
33
+ for (const l of state.length ? state : [chalk.grey('not loaded anywhere yet')]) out.log(` ${l}`);
24
34
  }
25
35
  const last = r.loads[0];
26
36
  if (last) out.log(chalk.grey(`\n Last load: ${last.branch}, ${last.status}${last.error ? ` (${last.error})` : ''}, ${new Date(last.started_at).toLocaleString()}`));
@@ -148,7 +148,7 @@ module.exports = async (args = {}) => {
148
148
  const exposure = require('../utils/api-exposure');
149
149
  const found = exposure.readLocal(config.project_uuid);
150
150
  if (found) {
151
- const lines = exposure.lines(exposure.impact({ current, target, items: found.items }), chalk);
151
+ const lines = exposure.lines(exposure.impact({ current, target, items: found.items }), chalk, { verbose: process.argv.includes('--verbose') });
152
152
  for (const l of lines) console.log(l);
153
153
  if (lines.length) console.log(' ');
154
154
  }
@@ -95,3 +95,43 @@ test('query : même requête que api-exposure.sql, sans les lignes psql, schéma
95
95
  assert.deepEqual(seen.params, ['public,api']);
96
96
  assert.equal(await exposure.query({ query: async () => { throw new Error('role "anon" does not exist'); } }, ['public']), null);
97
97
  });
98
+
99
+ // --- Fonctions DEFINER appelées par des politiques RLS (motif contre la récursion) : pas de correctif ---------
100
+
101
+ test('fonction d’une politique RLS : à part, sans correctif ; mention courte seulement en --verbose', () => {
102
+ const helper = { kind: 'function', schema: 'public', name: 'mes_equipes', signature: 'mes_equipes()', reason: 'security_definer', anon: true, authenticated: true, policies: 2, policies_indirect: 0 };
103
+ const indirect = { ...helper, name: 'est_admin_brut', signature: 'est_admin_brut()', policies: 0, policies_indirect: 1 };
104
+ const x = exposure.afterMigrate({ engine: '0.73.1', before: [], after: [helper, indirect, definer] });
105
+ assert.equal(x.count, 1, 'seule la DEFINER isolée est avertie');
106
+ assert.deepEqual(x.items.map((i) => i.name), ['est_admin']);
107
+ assert.deepEqual(x.policy_functions.map((i) => i.name), ['mes_equipes', 'est_admin_brut']);
108
+ const quiet = exposure.migrateLines(x, chalk).join('\n');
109
+ assert.match(quiet, /alter function public\.est_admin\(uuid\) security invoker;/);
110
+ assert.ok(!/mes_equipes|est_admin_brut|RLS policies/.test(quiet), quiet);
111
+ const verbose = exposure.migrateLines(x, chalk, { verbose: true }).join('\n');
112
+ assert.match(verbose, /2 SECURITY DEFINER function\(s\) used by RLS policies: normal, not callable directly by the API \(rpc\) — public\.mes_equipes, public\.est_admin_brut/);
113
+ assert.ok(!/mes_equipes\(\) security invoker/.test(verbose), 'jamais le correctif pour elles');
114
+ // Seulement des fonctions de politiques : rien par défaut
115
+ const only = exposure.afterMigrate({ engine: '0.73.1', before: [], after: [helper] });
116
+ assert.equal(only.count, 0);
117
+ assert.deepEqual(exposure.migrateLines(only, chalk), []);
118
+ assert.equal(exposure.migrateLines(only, chalk, { verbose: true }).length, 1);
119
+ });
120
+
121
+ test('poad deploy : poad.io sépare policy_functions (sans correctif), --json les garde', () => {
122
+ const r = summarize({
123
+ outcome: 'success',
124
+ api_exposure: { current: '0.73.1', target: '0.73.1', change: 'unchanged', items: [], policy_functions: [{ schema: 'public', name: 'mes_equipes', signature: 'mes_equipes()', policies: 2, policies_indirect: 0 }] },
125
+ });
126
+ assert.equal(r.api_exposure.count, 0);
127
+ assert.equal(r.api_exposure.policy_count, 1);
128
+ assert.deepEqual(exposure.lines(r.api_exposure, chalk), []);
129
+ assert.match(exposure.lines(r.api_exposure, chalk, { verbose: true }).join('\n'), /1 SECURITY DEFINER function\(s\) used by RLS policies/);
130
+ });
131
+
132
+ test('api-exposure.sql compte les politiques qui appellent la fonction (pg_depend), directement ou par une fonction', () => {
133
+ const sql = fs.readFileSync(path.join(__dirname, '../utils/api-exposure/api-exposure.sql'), 'utf8');
134
+ assert.match(sql, /classid = 'pg_policy'::regclass/);
135
+ assert.match(sql, /as policies,/);
136
+ assert.match(sql, /as policies_indirect/);
137
+ });
@@ -162,7 +162,7 @@ function fakeCloud(t, seen, { space = { limit: 1024 ** 3, used: 1024 ** 2 }, eve
162
162
  seen.push({ method: req.method, url: req.url, body });
163
163
  const send = (s, o) => (res.writeHead(s, { 'content-type': 'application/json' }), res.end(JSON.stringify(o)));
164
164
  if (/\/branches$/.test(req.url)) return send(200, [{ name: 'main', kind: 'production' }, { name: 'dev' }]);
165
- if (/\/seeds$/.test(req.url)) return send(200, { store: true, items: [{ target: 'ref.communes', sha256: 'aa', rows: 5 }], applied: { dev: { 'ref.communes': { sha256: 'aa' } } }, quota: {}, loads: [] });
165
+ if (/\/seeds(\?.*)?$/.test(req.url)) return send(200, { store: true, items: [{ target: 'ref.communes', sha256: 'aa', rows: 5 }], applied: { dev: { 'ref.communes': { sha256: 'aa' } } }, quota: {}, loads: [] });
166
166
  if (/\/sync-plan$/.test(req.url)) return send(200, { space });
167
167
  if (/\/backup$/.test(req.url)) return send(200, { file: 'pre-deploy-20261205-000000.dump', bytes: 1234 });
168
168
  if (/\/sync-events$/.test(req.url)) {
@@ -44,7 +44,7 @@ test('envoyée, jamais chargée dans cet environnement → chargée au deploy su
44
44
  t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
45
45
  let polls = 0;
46
46
  const calls = fakeApi(t, [
47
- [/^GET .*\/seeds$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA }], applied: { dev: { 'public.commune': { sha256: SHA } } } })],
47
+ [/^GET .*\/seeds(\?.*)?$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA }], applied: { dev: { 'public.commune': { sha256: SHA } } } })],
48
48
  [/^POST .*\/seeds\/load$/, () => ({ load_id: 'l1', targets: ['public.commune'], plan: { mode: 'together', order: ['public.commune'] } })],
49
49
  [/^GET .*\/seeds\/loads\/l1$/, () => (++polls < 2 ? { status: 'running', steps: [{ target: 'public.commune', status: 'running' }] } : { status: 'done', steps: [{ target: 'public.commune', status: 'done', written: 4, deleted: 0, duration_ms: 1200 }] })],
50
50
  ]);
@@ -61,7 +61,7 @@ test('envoyée, jamais chargée dans cet environnement → chargée au deploy su
61
61
  test('déjà chargée dans cet environnement : ni envoi ni chargement', async (t) => {
62
62
  const { dir, files } = project();
63
63
  t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
64
- const calls = fakeApi(t, [[/^GET .*\/seeds$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA }], applied: { main: { 'public.commune': { sha256: SHA } } } })]]);
64
+ const calls = fakeApi(t, [[/^GET .*\/seeds(\?.*)?$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA }], applied: { main: { 'public.commune': { sha256: SHA } } } })]]);
65
65
  const { out } = output();
66
66
  const r = await store.sendAndLoad('abcdefghijkl', 'main', dir, files, {}, out);
67
67
  assert.deepStrictEqual(r.tables.map((x) => [x.action, x.state]), [['unchanged', 'loaded']]);
@@ -73,7 +73,7 @@ test('poad.io refuse faute de place (aucun ordre ne tient) : chaque table dite,
73
73
  t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
74
74
  const message = 'place insuffisante, même table par table : public.commune demande à elle seule environ 700.0 Mio, + 10 % de marge = 770.0 Mio, plus 256.0 Mio pour le journal (il manquerait 76.3 Mio). Pour passer : poad ref inspect public.commune, --exclude, ou une offre plus grande.';
75
75
  fakeApi(t, [
76
- [/^GET .*\/seeds$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA }], applied: {} })],
76
+ [/^GET .*\/seeds(\?.*)?$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA }], applied: {} })],
77
77
  [/^POST .*\/seeds\/load$/, () => {
78
78
  throw new api.CloudError(`reference load: ${message} (seed_no_space)`, { status: 413, code: 'seed_no_space', details: { code: 'seed_no_space', message, margin: 1.1, required: 1100, free: 1000, limit: 1024, tables: [{ target: 'public.commune', need: 734003200, status: 'refused' }, { target: 'public.region', need: 1, status: 'pending' }] } });
79
79
  }],
@@ -93,7 +93,7 @@ test('chargement table par table : annoncé, puis une table refusée en cours et
93
93
  const { dir, files } = project();
94
94
  t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
95
95
  fakeApi(t, [
96
- [/^GET .*\/seeds$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA }], applied: {} })],
96
+ [/^GET .*\/seeds(\?.*)?$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA }], applied: {} })],
97
97
  [/^POST .*\/seeds\/load$/, () => ({ load_id: 'l2', targets: ['public.commune'], plan: { mode: 'stepwise', order: ['public.a', 'public.commune', 'public.c'] } })],
98
98
  [/^GET .*\/seeds\/loads\/l2$/, () => ({ status: 'failed', steps: [
99
99
  { target: 'public.a', status: 'done', written: 1, deleted: 0, duration_ms: 10, warnings: ['place restante faible sur l’engine main : 200.0 Mio libres sur 1.00 Gio (20 %)'] },
@@ -111,3 +111,93 @@ test('chargement table par table : annoncé, puis une table refusée en cours et
111
111
  assert.match(text, /public\.commune: refusée : place insuffisante/);
112
112
  assert.match(text, /public\.c: pending, not loaded into main; the next "poad deploy" loads it/);
113
113
  });
114
+
115
+ // --- État réel lu dans la base de l'environnement (poad.io : GET seeds?verify) : seed_applied n'est qu'un cache ---
116
+
117
+ const doneLoad = (written) => [
118
+ [/^POST .*\/seeds\/load$/, () => ({ load_id: 'l2', targets: ['public.commune'], plan: { mode: 'together', order: ['public.commune'] } })],
119
+ [/^GET .*\/seeds\/loads\/l2$/, () => ({ status: 'done', steps: [{ target: 'public.commune', status: 'done', written, deleted: 0, duration_ms: 900 }] })],
120
+ ];
121
+
122
+ test('volume recréé vide : le registre dit « chargée », la base dit vide → rechargée, ligne « to load (table empty) »', async (t) => {
123
+ const { dir, files } = project();
124
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
125
+ const calls = fakeApi(t, [
126
+ [/^GET .*\/seeds\?verify=main$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA, rows: 4 }], applied: { main: { 'public.commune': { sha256: SHA, rows: 4 } } }, state: { main: { 'public.commune': { state: 'empty', rows: null, mark_rows: null, sha256: null } } } })],
127
+ ...doneLoad(4),
128
+ ]);
129
+ const { lines, out } = output();
130
+ const r = await store.sendAndLoad('abcdefghijkl', 'main', dir, files, {}, out);
131
+ assert.deepStrictEqual(r.tables.map((x) => [x.target, x.action, x.state, x.reason]), [['public.commune', 'load', 'loaded', 'empty']]);
132
+ assert.ok(calls.some(([m, route]) => m === 'POST' && /seeds\/load$/.test(route)), 'rechargée');
133
+ assert.ok(!calls.some(([, route]) => /seeds\/upload/.test(route)), 'pas renvoyée');
134
+ assert.match(lines.join('\n'), /○ public\.commune to load in main \(table empty; 4 rows to load\)/);
135
+ });
136
+
137
+ test('déjà chargée, lu dans la base : ni envoi ni chargement, ligne avec lignes et empreinte', async (t) => {
138
+ const { dir, files } = project();
139
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
140
+ const calls = fakeApi(t, [[/^GET .*\/seeds\?verify=main$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA, rows: 4 }], applied: {}, state: { main: { 'public.commune': { state: 'loaded', rows: 4, mark_rows: 4, sha256: SHA } } } })]]);
141
+ const { lines, out } = output();
142
+ const r = await store.sendAndLoad('abcdefghijkl', 'main', dir, files, {}, out);
143
+ assert.deepStrictEqual(r.tables.map((x) => [x.action, x.state]), [['unchanged', 'loaded']]);
144
+ assert.strictEqual(calls.length, 1);
145
+ assert.match(lines.join('\n'), /✔ public\.commune already loaded in main \(4 rows, sha256 aaaaaaaaaaaa\)/);
146
+ assert.ok(!/not checked/.test(lines.join('\n')));
147
+ });
148
+
149
+ test('table vidée à la main : moins de lignes qu’à la pose de la marque → rechargée', async (t) => {
150
+ const { dir, files } = project();
151
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
152
+ fakeApi(t, [[/^GET .*\/seeds\?verify=main$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA, rows: 4 }], applied: { main: { 'public.commune': { sha256: SHA } } }, state: { main: { 'public.commune': { state: 'incomplete', rows: 0, mark_rows: 4, sha256: SHA } } } })], ...doneLoad(4)]);
153
+ const { lines, out } = output();
154
+ const r = await store.sendAndLoad('abcdefghijkl', 'main', dir, files, {}, out);
155
+ assert.deepStrictEqual(r.tables.map((x) => [x.action, x.state]), [['load', 'loaded']]);
156
+ assert.match(lines.join('\n'), /to load in main \(0 of 4 rows/);
157
+ });
158
+
159
+ test('--dry-run : une ligne par table (déjà chargée / à charger / à envoyer puis charger), rien d’envoyé ni de chargé', async (t) => {
160
+ const { dir } = project();
161
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
162
+ fs.writeFileSync(path.join(dir, 'reference', 'public.region.jsonl'), '{"id":1}\n'.repeat(8));
163
+ fs.writeFileSync(path.join(dir, 'reference', 'public.zone.jsonl'), '{"id":1}\n'.repeat(8));
164
+ const files = store.largeFiles(dir, 5);
165
+ const cache = JSON.parse(fs.readFileSync(path.join(dir, 'data', 'reference-store.json'), 'utf8'));
166
+ const reg = files.find((f) => f.target === 'public.region');
167
+ cache[reg.file] = { size: reg.size, mtimeMs: reg.mtimeMs, sha256: 'b'.repeat(64), target: reg.target };
168
+ fs.writeFileSync(path.join(dir, 'data', 'reference-store.json'), JSON.stringify(cache));
169
+ const calls = fakeApi(t, [[/^GET .*\/seeds\?verify=main$/, () => ({
170
+ store: true,
171
+ items: [{ target: 'public.commune', sha256: SHA, rows: 4 }, { target: 'public.region', sha256: 'b'.repeat(64), rows: 8 }],
172
+ applied: {},
173
+ state: { main: { 'public.commune': { state: 'loaded', rows: 4, mark_rows: 4, sha256: SHA }, 'public.region': { state: 'unmarked', rows: null, sha256: null } } },
174
+ })]]);
175
+ const { lines, out } = output();
176
+ const r = await store.sendAndLoad('abcdefghijkl', 'main', dir, files, {}, out, { dryRun: true });
177
+ assert.strictEqual(calls.length, 1, 'une lecture, rien d’autre');
178
+ assert.deepStrictEqual(r.tables.map((x) => [x.target, x.action]), [['public.commune', 'unchanged'], ['public.region', 'load'], ['public.zone', 'send']]);
179
+ const text = lines.join('\n');
180
+ assert.match(text, /✔ public\.commune already loaded in main \(4 rows, sha256 aaaaaaaaaaaa\)/);
181
+ assert.match(text, /○ public\.region would be loaded in main \(rows without the load mark; 8 rows to load\)/);
182
+ assert.match(text, /○ public\.zone would be sent, then loaded in main \(never sent\)/);
183
+ assert.ok(!/loaded if not yet loaded/.test(text), 'plus de message générique');
184
+ });
185
+
186
+ test('poad.io d’avant la vérification (pas de state) : le registre, dit « not checked »', async (t) => {
187
+ const { dir, files } = project();
188
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
189
+ fakeApi(t, [[/^GET .*\/seeds(\?.*)?$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA, rows: 4 }], applied: { main: { 'public.commune': { sha256: SHA, rows: 4 } } } })]]);
190
+ const { lines, out } = output();
191
+ await store.sendAndLoad('abcdefghijkl', 'main', dir, files, {}, out, { dryRun: true });
192
+ assert.match(lines.join('\n'), /already loaded in main \(4 rows, sha256 aaaaaaaaaaaa, as recorded by poad\.io: not checked in the database\)/);
193
+ });
194
+
195
+ test('verdict partagé avec poad.io (seed-format.mjs) : marque, empreinte, lignes', () => {
196
+ const A = require('../utils/seed/apply');
197
+ assert.strictEqual(A.referenceState(SHA, { exists: true, empty: true }), 'empty');
198
+ assert.strictEqual(A.referenceState(SHA, { exists: true, sha256: SHA, rows: 3, mark_rows: 4 }), 'incomplete');
199
+ assert.strictEqual(A.referenceState(SHA, { exists: true, sha256: 'b'.repeat(64), rows: 4, mark_rows: 4 }), 'outdated');
200
+ assert.strictEqual(A.referenceState(SHA, { exists: true, sha256: SHA, rows: 4, mark_rows: 4 }), 'loaded');
201
+ assert.ok(A.tail('public.commune', ['id'], SHA).includes("insert into _poad.reference_loads (target, sha256, rows) select 'public.commune'"));
202
+ assert.ok(!A.tail('public.commune', ['id']).includes('reference_loads'));
203
+ });
@@ -16,7 +16,15 @@ select json_build_object(
16
16
  select 'function' as kind, n.nspname as schema, p.proname as name, p.oid::regprocedure::text as signature,
17
17
  'security_definer' as reason,
18
18
  has_function_privilege('anon', p.oid, 'execute') as anon,
19
- has_function_privilege('authenticated', p.oid, 'execute') as authenticated
19
+ has_function_privilege('authenticated', p.oid, 'execute') as authenticated,
20
+ -- Appelée par des politiques RLS (motif classique contre leur récursion) : normal, pas de correctif
21
+ -- « security invoker » (il casserait les politiques). Directement (pg_depend de pg_policy : USING,
22
+ -- WITH CHECK), ou par une fonction qu'une politique appelle et dont le corps la nomme (un niveau).
23
+ (select count(distinct d.objid) from pg_depend d
24
+ where d.classid = 'pg_policy'::regclass and d.refclassid = 'pg_proc'::regclass and d.refobjid = p.oid) as policies,
25
+ (select count(distinct d.objid) from pg_depend d join pg_proc f on f.oid = d.refobjid
26
+ where d.classid = 'pg_policy'::regclass and d.refclassid = 'pg_proc'::regclass and f.oid <> p.oid
27
+ and f.prosrc ~* ('\m' || regexp_replace(p.proname, '([^A-Za-z0-9_])', '\\\1', 'g') || '\M')) as policies_indirect
20
28
  from pg_proc p join pg_namespace n on n.oid = p.pronamespace
21
29
  where n.nspname = any (s.names) and p.prokind = 'f' and p.prosecdef
22
30
  and p.prorettype not in ('trigger'::regtype, 'event_trigger'::regtype)
@@ -29,7 +37,8 @@ select json_build_object(
29
37
  select case c.relkind when 'm' then 'materialized_view' else 'view' end, n.nspname, c.relname, null,
30
38
  case c.relkind when 'm' then 'materialized_view' else 'view_owner_rights' end,
31
39
  has_table_privilege('anon', c.oid, 'select') or has_table_privilege('anon', c.oid, 'insert'),
32
- has_table_privilege('authenticated', c.oid, 'select') or has_table_privilege('authenticated', c.oid, 'insert')
40
+ has_table_privilege('authenticated', c.oid, 'select') or has_table_privilege('authenticated', c.oid, 'insert'),
41
+ 0, 0
33
42
  from pg_class c join pg_namespace n on n.oid = c.relnamespace
34
43
  where n.nspname = any (s.names)
35
44
  and (c.relkind = 'm' or (c.relkind = 'v' and not coalesce((select bool_or(lower(o) in ('security_invoker=true', 'security_invoker=on', 'security_invoker=yes', 'security_invoker=1')) from unnest(c.reloptions) o), false)))
@@ -45,10 +45,24 @@ function fixFor(i) {
45
45
  return 'read it through a SECURITY INVOKER function that returns only allowed rows, or replace it with a table and policies';
46
46
  }
47
47
 
48
- /** Ce que la version visée change ; { change: lost | regained_service_role | unchanged | none, items } */
49
- function impact({ current = null, target = null, items = [] } = {}) {
48
+ /**
49
+ * Fonction SECURITY DEFINER appelée par des politiques RLS (directement, ou par une fonction qu'une politique appelle) :
50
+ * le motif classique contre la récursion des politiques. Normal : l'API ne la sert pas en rpc, mais aucun correctif
51
+ * « security invoker » (il casserait les politiques). policies / policies_indirect : api-exposure.sql ; policy : scan
52
+ * des migrations en attente (poad.io).
53
+ */
54
+ const usedByPolicies = (i) => i.kind === 'function' && (Number(i.policies) > 0 || Number(i.policies_indirect) > 0 || i.policy === true);
55
+ const helperOf = (i) => ({ schema: i.schema, name: i.name, ...(i.signature ? { signature: i.signature } : {}), policies: Number(i.policies) || 0, policies_indirect: Number(i.policies_indirect) || 0, ...(i.source ? { source: i.source } : {}), ...(i.file ? { file: i.file } : {}) });
56
+
57
+ /**
58
+ * Ce que la version visée change ; { change: lost | regained_service_role | unchanged | none, items, policy_functions }.
59
+ * items : avec leur correctif ; policy_functions (appelées par des politiques RLS) : à part, sans correctif.
60
+ */
61
+ function impact({ current = null, target = null, items = [], policy_functions = [] } = {}) {
50
62
  const from = phaseOf(current);
51
63
  const to = phaseOf(target || current);
64
+ const helpers = [...policy_functions.map(helperOf), ...items.filter(usedByPolicies).map(helperOf)];
65
+ items = items.filter((i) => !usedByPolicies(i));
52
66
  const all = items.map((i) => ({ kind: i.kind, schema: i.schema, name: i.name, ...(i.signature ? { signature: i.signature } : {}), reason: i.reason, why: WHY[i.reason] || i.reason, roles: ['anon', 'authenticated'].filter((r) => i[r] !== false), fix: fixFor(i), ...(i.source ? { source: i.source } : {}), ...(i.file ? { file: i.file } : {}) }));
53
67
  let change = 'none';
54
68
  if (all.length && to !== 'served') {
@@ -56,7 +70,15 @@ function impact({ current = null, target = null, items = [] } = {}) {
56
70
  else if (from === 'refused_all' && to === 'service_role_only') change = 'regained_service_role';
57
71
  else change = 'unchanged';
58
72
  }
59
- return { current, target: target || current, phase: to, change, count: all.length, items: all };
73
+ return { current, target: target || current, phase: to, change, count: all.length, items: all, policy_count: helpers.length, policy_functions: helpers };
74
+ }
75
+
76
+ /** Mention courte, regroupée, des fonctions DEFINER des politiques RLS (--verbose) ; [] sinon */
77
+ function policyLines(x, chalk, { verbose = false } = {}) {
78
+ const h = (x && x.policy_functions) || [];
79
+ if (!verbose || !h.length || x.phase === 'served') return [];
80
+ const names = h.slice(0, 8).map((i) => `${i.schema}.${i.name}`).join(', ') + (h.length > 8 ? `, … (+${h.length - 8})` : '');
81
+ return [chalk.grey(` ℹ ${h.length} SECURITY DEFINER function(s) used by RLS policies: normal, not callable directly by the API (rpc) — ${names}`)];
60
82
  }
61
83
 
62
84
  /** La liste lue dans la base de l'engine local (lecture seule) ; null si illisible */
@@ -109,12 +131,12 @@ function afterMigrate({ engine = null, before = null, after = null } = {}) {
109
131
  const had = new Set((before || []).map(keyOf));
110
132
  const x = impact({ current: engine, target: engine, items: after });
111
133
  const items = x.items.map((i) => ({ ...i, created: Array.isArray(before) && !had.has(keyOf(i)) }));
112
- return { engine, phase: x.phase, count: items.length, created: items.filter((i) => i.created).map((i) => `${i.schema}.${i.name}`), items };
134
+ return { engine, phase: x.phase, count: items.length, created: items.filter((i) => i.created).map((i) => `${i.schema}.${i.name}`), items, policy_count: x.policy_count, policy_functions: x.policy_functions };
113
135
  }
114
136
 
115
137
  /** Lignes de poad migrate ; full : la liste (des migrations viennent d'être appliquées), sinon un rappel d'une ligne */
116
- function migrateLines(x, chalk, { full = true, max = 20 } = {}) {
117
- if (!x || !x.count) return [];
138
+ function migrateLines(x, chalk, { full = true, max = 20, verbose = false } = {}) {
139
+ if (!x || !x.count) return policyLines(x, chalk, { verbose });
118
140
  const n = `${x.count} function(s) or view(s)`;
119
141
  if (!full) return [chalk.yellowBright(` ⚠ ${n} granted to anon or authenticated are not served to them by the API (403 not_exposed): "poad migrate --json" or the Migrations screen of the console list them with their fix.`)];
120
142
  const out = [chalk.yellowBright(` ⚠ ${n} granted to anon or authenticated are not served to them by the API: they would bypass RLS, so a front end gets 403 not_exposed (service_role and SQL still work).`)];
@@ -123,12 +145,12 @@ function migrateLines(x, chalk, { full = true, max = 20 } = {}) {
123
145
  out.push(chalk.grey(` fix: ${i.fix}`));
124
146
  }
125
147
  if (x.items.length > max) out.push(chalk.grey(` … and ${x.items.length - max} more (poad migrate --json lists them all)`));
126
- return out;
148
+ return [...out, ...policyLines(x, chalk, { verbose })];
127
149
  }
128
150
 
129
151
  /** Lignes à montrer (poad deploy, poad upgrade) ; [] si rien à dire */
130
- function lines(x, chalk, { max = 20 } = {}) {
131
- if (!x || !x.count || !x.change || x.change === 'none') return [];
152
+ function lines(x, chalk, { max = 20, verbose = false } = {}) {
153
+ if (!x || !x.count || !x.change || x.change === 'none') return policyLines(x, chalk, { verbose });
132
154
  const n = `${x.count} function(s) or view(s)`;
133
155
  const head =
134
156
  x.change === 'lost'
@@ -142,7 +164,7 @@ function lines(x, chalk, { max = 20 } = {}) {
142
164
  out.push(chalk.grey(` fix: ${i.fix}`));
143
165
  }
144
166
  if (x.items.length > max) out.push(chalk.grey(` … and ${x.items.length - max} more (--json lists them all)`));
145
- return out;
167
+ return [...out, ...policyLines(x, chalk, { verbose })];
146
168
  }
147
169
 
148
- module.exports = { HIDDEN_SINCE, SERVICE_ROLE_SINCE, phaseOf, fixFor, impact, readLocal, lines, query, afterMigrate, migrateLines };
170
+ module.exports = { HIDDEN_SINCE, SERVICE_ROLE_SINCE, phaseOf, fixFor, impact, readLocal, lines, query, afterMigrate, migrateLines, policyLines, usedByPolicies };
@@ -484,21 +484,23 @@ Object.assign(sheets, {
484
484
  notes: [EXIT_NOTE],
485
485
  },
486
486
  deploy: {
487
- usage: ['poad deploy [--env <name>] [--dry-run] [--yes] [--allow-destructive] [--json]'],
487
+ usage: ['poad deploy [--env <name>] [--dry-run] [--yes] [--allow-destructive] [--verbose] [--json]'],
488
488
  text: [
489
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.',
490
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.',
491
491
  ],
492
492
  options: [
493
493
  ['--env <name>', 'the environment (default: the current git branch if it exists on poad.io, else main)'],
494
- ['--dry-run', 'poad.io says what it would do (migrations to apply), nothing changes'],
494
+ ['--dry-run', 'poad.io says what it would do (migrations to apply, and for each large reference table: already loaded, to load or to send then load), nothing changes'],
495
495
  ['--yes', 'no question for production (required outside a terminal); does not accept a data loss'],
496
+ ['--verbose', 'also the SECURITY DEFINER functions used by RLS policies (normal: not callable directly by the API, no fix needed); --json always lists them (api_exposure.policy_functions)'],
496
497
  ['--allow-destructive', 'production: apply migrations that lose data without asking (required outside a terminal when they do); alias --accept-data-loss'],
497
498
  PROJECT_OPT,
498
499
  JSON_OPT,
499
500
  ],
500
501
  notes: [
501
502
  '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.',
503
+ 'Large reference tables (poad/reference files over 20 MB, outside git): their state is read in the database of the environment (a mark set by the load, with the sha256 of the content and its number of rows): one line per table, "already loaded (N rows, sha256 …)", "to load (table empty | rows without the load mark | another version is loaded | N of M rows)" or "to send, then load". A volume recreated empty or a database reset loads them again (logs: poad logs deploy event=reference_state).',
502
504
  '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).',
503
505
  EXIT_NOTE,
504
506
  ],
@@ -78,7 +78,7 @@ module.exports = async (root, config, { quietWhenNone = false, report = null, ex
78
78
  }
79
79
  // Fonctions et vues accordées à anon ou authenticated que l'API ne leur sert pas (SECURITY DEFINER, vues sans
80
80
  // security_invoker, vues matérialisées) : même règle que poad deploy et poad upgrade (utils/api-exposure)
81
- for (const l of require('./api-exposure').migrateLines(result.apiExposure, chalk, { full: exposureList || applied.length > 0 })) console.log(l);
81
+ for (const l of require('./api-exposure').migrateLines(result.apiExposure, chalk, { full: exposureList || applied.length > 0, verbose: process.argv.includes('--verbose') })) console.log(l);
82
82
  return qr.errors.length === 0;
83
83
  };
84
84
 
@@ -132,7 +132,8 @@ function run(direction, raw, deps = {}) {
132
132
  let registry = null;
133
133
  if (has('refs') || has('base')) {
134
134
  try {
135
- registry = await api.call('GET', `v1/projects/${api.enc(id)}/seeds`, { what: 'references' });
135
+ // Poussée : poad.io lit l'état réel dans la base de l'environnement (marque posée au chargement, lignes)
136
+ registry = await api.call('GET', `v1/projects/${api.enc(id)}/seeds?verify=${push ? encodeURIComponent(env.branch) : '0'}`, { what: 'references' });
136
137
  } catch (e) {
137
138
  registry = null;
138
139
  if (has('refs')) out.log(chalk.yellowBright(` ⚠ reference store not readable (${e.message}): refs left out.`));
@@ -148,7 +149,7 @@ function run(direction, raw, deps = {}) {
148
149
  if (has('auth')) preview.auth = await authPreview(pg, P, container, src, dst, inv);
149
150
 
150
151
  // Références
151
- if (has('refs') && registry) preview.refs = refsPreview(registry, env, poadDir, push, has('code'));
152
+ if (has('refs') && registry) preview.refs = await refsPreview(registry, env, poadDir, push, has('code'), push ? null : container);
152
153
 
153
154
  // Fichiers du Stockage
154
155
  let storage = null;
@@ -506,27 +507,37 @@ async function transferData(pg, P, container, src, dst, { base, auth, inv, sel,
506
507
 
507
508
  // --- Références -------------------------------------------------------------------------------------------
508
509
 
509
- const localRefsFile = (poadDir) => path.join(poadDir, 'data', 'reference-local.json');
510
- const readJson = (f) => {
511
- try {
512
- return JSON.parse(fs.readFileSync(f, 'utf8'));
513
- } catch {
514
- return {};
515
- }
516
- };
517
-
518
- function refsPreview(registry, env, poadDir, push, withCode) {
510
+ /**
511
+ * Ce qui attend chaque table de référence de l'autre côté, lu dans SA base (marque posée au chargement, lignes) :
512
+ * tables: [{ target, action: loaded | load | send, state, rows, sha256, … }] ; load : celles à charger hors gros
513
+ * fichiers du dossier (ceux-là passent par l'envoi au magasin, ou par poad deploy avec la partie code).
514
+ */
515
+ async function refsPreview(registry, env, poadDir, push, withCode, container) {
519
516
  const items = Array.isArray(registry.items) ? registry.items : [];
517
+ const refStore = require('../reference-store');
520
518
  if (push) {
521
- const refStore = require('../reference-store');
522
519
  const large = refStore.largeFiles(poadDir);
523
- const applied = (registry.applied && registry.applied[env.branch]) || {};
524
- const outdated = items.filter((s) => !applied[s.target] || applied[s.target].sha256 !== s.sha256).map((s) => s.target);
525
- return { store: Boolean(registry.store), large: large.map((f) => ({ rel: f.rel, target: f.target, bytes: f.size })), large_by_code: withCode, load: outdated, todo: large.length > 0 || outdated.length > 0 };
520
+ const planned = refStore.plan(registry, env.branch, poadDir, large);
521
+ const others = items.filter((s) => !large.some((f) => f.target === s.target)).map((s) => {
522
+ const st = refStore.cloudState(registry, env.branch, s.target, s.sha256);
523
+ return { target: s.target, action: st.state === 'loaded' ? 'loaded' : 'load', state: st.state, rows: st.rows, mark_rows: st.mark_rows, sha256: st.sha256 || s.sha256, expected_rows: s.rows, checked: st.checked };
524
+ });
525
+ const tables = [...planned, ...others];
526
+ const load = others.filter((t) => t.action === 'load').map((t) => t.target);
527
+ return { store: Boolean(registry.store), large: large.map((f) => ({ rel: f.rel, target: f.target, bytes: f.size })), large_by_code: withCode, tables, load, todo: tables.some((t) => t.action !== 'loaded') };
526
528
  }
527
- const loaded = readJson(localRefsFile(poadDir));
528
- const load = items.filter((s) => !loaded[s.target] || loaded[s.target] !== s.sha256).map((s) => ({ target: s.target, sha256: s.sha256, rows: s.rows }));
529
- return { store: Boolean(registry.store), load, todo: load.length > 0 };
529
+ // Tirer : l'état de la base locale ; une base remise à zéro ou une table vidée redeviennent « à charger »
530
+ const S = require('../seed/run');
531
+ const A = require('../seed/apply');
532
+ const st = container ? await S.localState(container, items.map((s) => s.target)) : null;
533
+ const tables = items.map((s) => {
534
+ const raw = st ? st[s.target] : null;
535
+ const state = st ? A.referenceState(s.sha256, raw) : 'unknown';
536
+ return { target: s.target, sha256: s.sha256, rows: raw ? raw.rows : null, mark_rows: raw ? raw.mark_rows : null, expected_rows: s.rows, state, action: state === 'loaded' ? 'loaded' : 'load' };
537
+ });
538
+ if (container && st) await S.localLog(container, tables.map((t) => ({ msg: `reference ${t.target}: ${t.state}`, attrs: { event: 'reference_state', table: t.target, state: t.state, rows: t.rows, mark_rows: t.mark_rows, sha256: t.sha256.slice(0, 12), env: 'local', via: 'poad pull' } })));
539
+ const load = tables.filter((t) => t.action === 'load' && t.state !== 'no_table').map((t) => ({ target: t.target, sha256: t.sha256, rows: t.expected_rows }));
540
+ return { store: Boolean(registry.store), tables, load, todo: load.length > 0 };
530
541
  }
531
542
 
532
543
  async function refsApply(id, env, poadDir, plan, push, opts, out, config, withCode) {
@@ -551,16 +562,12 @@ async function refsApply(id, env, poadDir, plan, push, opts, out, config, withCo
551
562
  const S = require('../seed/run');
552
563
  const A = require('../seed/apply');
553
564
  const order = A.loadOrder(plan.load.map((s) => s.target), await S.localEdges(config.project_uuid));
554
- const loaded = readJson(localRefsFile(poadDir));
555
565
  const tables = [];
556
566
  for (const target of order) {
557
567
  const t0 = Date.now();
558
568
  const d = await api.call('POST', `v1/projects/${api.enc(id)}/seeds/download`, { body: { target }, what: `reference ${target}` });
569
+ // La marque (empreinte, lignes) est posée dans la base locale, dans la transaction du chargement
559
570
  const r = await S.loadLocal(config.project_uuid, d);
560
- const s = plan.load.find((x) => x.target === target);
561
- loaded[target] = s.sha256;
562
- fs.mkdirSync(path.dirname(localRefsFile(poadDir)), { recursive: true });
563
- fs.writeFileSync(localRefsFile(poadDir), JSON.stringify(loaded, null, 2) + '\n');
564
571
  out.log(`${out.chalk.greenBright('✔')} ${target} loaded locally: ${n(r.written)} rows written, ${n(r.deleted)} removed`);
565
572
  tables.push({ target, rows: r.written, outcome: 'done', duration_ms: Date.now() - t0 });
566
573
  }
@@ -847,8 +854,14 @@ function printPreview(out, P, pv, { push, env, sel }) {
847
854
  }
848
855
  if (pv.refs) {
849
856
  const r = pv.refs;
850
- if (push) out.log(` ${pad('refs')}${r.large.length ? `${r.large.length} large file(s) to the store${r.large_by_code ? ' (by poad deploy)' : ''}, ` : ''}${r.load.length} table(s) to load in ${env.branch}${r.load.length ? chalk.grey(` (${r.load.slice(0, 6).join(', ')})`) : ''}`);
851
- else out.log(` ${pad('refs')}${r.load.length} table(s) of the store to load locally${r.load.length ? chalk.grey(` (${r.load.slice(0, 6).map((x) => x.target).join(', ')})`) : ''}`);
857
+ // Une ligne par table, lue dans la base de l'autre côté : déjà chargée (lignes, empreinte) / à charger (pourquoi)
858
+ const refStore = require('../reference-store');
859
+ const tables = r.tables || [];
860
+ const count = (a) => tables.filter((t) => t.action === a).length;
861
+ const where = push ? `in ${env.branch}` : 'locally';
862
+ out.log(` ${pad('refs')}${tables.length ? `${tables.length} table(s): ${count('loaded')} already loaded, ${count('load')} to load${count('send') ? `, ${count('send')} to send then load` : ''}${push && r.large.length && r.large_by_code ? chalk.grey(' (large files: by poad deploy)') : ''}` : 'no reference table'}`);
863
+ for (const t of tables.slice(0, 30)) out.log(` ${refStore.stateLine(t, where, chalk)}`);
864
+ if (tables.length > 30) out.log(chalk.grey(` … and ${tables.length - 30} more (--json lists them all)`));
852
865
  }
853
866
  if (pv.s3) {
854
867
  const t = pv.s3.totals;
@@ -8,6 +8,9 @@
8
8
  // Rien n'est refait pour rien : poad/data/reference-store.json garde, par fichier,
9
9
  // sa taille, sa date et l'empreinte de son contenu converti. Fichier inchangé et
10
10
  // déjà chargé dans l'environnement : ni conversion, ni envoi, ni chargement.
11
+ // « Déjà chargé » se lit dans la base de l'environnement (marque posée au
12
+ // chargement, nombre de lignes : poad.io la lit, GET seeds?verify) : un volume
13
+ // recréé vide ou une base remise à zéro redonnent « à charger » (CLI 2.76.2).
11
14
  'use strict';
12
15
  const fs = require('fs');
13
16
  const path = require('path');
@@ -83,33 +86,97 @@ function writeCache(poadDir, cache) {
83
86
  fs.writeFileSync(cachePath(poadDir), JSON.stringify(cache, null, 2) + '\n');
84
87
  }
85
88
 
89
+ // --- État des tables dans un environnement --------------------------------
90
+
91
+ /** Pourquoi une table est à charger, en clair */
92
+ const WHY = {
93
+ empty: 'table empty',
94
+ unmarked: 'rows without the load mark',
95
+ outdated: 'another version is loaded',
96
+ incomplete: 'fewer rows than loaded',
97
+ no_table: 'table not created yet',
98
+ not_loaded: 'not loaded yet',
99
+ };
100
+ const n = (x) => Number(x || 0).toLocaleString('en-US');
101
+ const short = (sha) => (sha ? String(sha).slice(0, 12) : '?');
102
+
86
103
  /**
87
- * Envoie et charge les grosses références dans un environnement. Renvoie
88
- * { tables: [{ target, action: 'unchanged'|'loaded'|'sent', … }], load, failed }.
104
+ * État d'une table dans un environnement hébergé : celui que poad.io a lu dans la base (registry.state, poad.io
105
+ * avec ?verify) ; sinon son registre (applied), dit « non vérifié ». { state, rows, sha256, checked }
89
106
  */
90
- async function sendAndLoad(id, branch, poadDir, files, opts, out) {
107
+ function cloudState(registry, branch, target, sha256) {
108
+ const st = registry.state && registry.state[branch] && registry.state[branch][target];
109
+ if (st && st.state && st.state !== 'unknown' && st.state !== 'not_running') {
110
+ // Lu dans la base contre l'empreinte du registre ; une autre empreinte attendue (fichier changé) : à charger
111
+ const state = st.state === 'loaded' && sha256 && st.sha256 && st.sha256 !== sha256 ? 'outdated' : st.state;
112
+ return { state, rows: st.rows, mark_rows: st.mark_rows, sha256: st.sha256, checked: true };
113
+ }
114
+ const a = registry.applied && registry.applied[branch] && registry.applied[branch][target];
115
+ if (a && (!sha256 || a.sha256 === sha256)) return { state: 'loaded', rows: a.rows, sha256: a.sha256, checked: false, why: st ? st.state : 'not_verified' };
116
+ return { state: a ? 'outdated' : 'not_loaded', checked: false, why: st ? st.state : 'not_verified' };
117
+ }
118
+
119
+ /**
120
+ * Ce qui attend chaque gros fichier dans l'environnement, sans rien envoyer : loaded (déjà chargée), load (au
121
+ * magasin, à charger), send (fichier changé ou jamais envoyé : à envoyer puis charger). [{ file, target, action, … }]
122
+ */
123
+ function plan(registry, branch, poadDir, files) {
124
+ const stored = new Map((registry.items || []).map((s) => [s.target, s]));
125
+ const cache = readCache(poadDir);
126
+ return files.map((f) => {
127
+ const c = cache[f.file];
128
+ const item = stored.get(f.target);
129
+ const same = c && c.size === f.size && c.mtimeMs === f.mtimeMs && c.sha256 && item && item.sha256 === c.sha256;
130
+ if (!same) return { file: f.file, rel: f.rel, target: f.target, action: 'send', why: item ? 'file changed since it was sent' : 'never sent' };
131
+ const st = cloudState(registry, branch, f.target, c.sha256);
132
+ return { file: f.file, rel: f.rel, target: f.target, action: st.state === 'loaded' ? 'loaded' : 'load', state: st.state, rows: st.rows, mark_rows: st.mark_rows, expected_rows: item.rows, sha256: c.sha256, checked: st.checked };
133
+ });
134
+ }
135
+
136
+ /**
137
+ * Une ligne par table : déjà chargée (lignes, empreinte) / à charger (pourquoi) / à envoyer puis charger.
138
+ * where : « in main », « locally »… ; p : { target, action: loaded|load|send, state, rows, mark_rows, sha256, expected_rows, checked, why }
139
+ */
140
+ function stateLine(p, where, chalk, { dryRun = false } = {}) {
141
+ const t = chalk.bold(p.target);
142
+ const at = where.startsWith('in ') || where === 'locally' ? where : `in ${where}`;
143
+ if (p.action === 'loaded') return `${chalk.greenBright('✔')} ${t} already loaded ${at} ${chalk.grey(`(${n(p.rows)} rows, sha256 ${short(p.sha256)}${p.checked === false ? ', as recorded by poad.io: not checked in the database' : ''})`)}`;
144
+ if (p.action === 'load') {
145
+ const why = p.state === 'incomplete' ? `${n(p.rows)} of ${n(p.mark_rows)} rows` : p.state === 'forced' ? 'already loaded, --force' : WHY[p.state] || p.state;
146
+ return `${chalk.yellow('○')} ${t} ${dryRun ? 'would be loaded' : 'to load'} ${at} ${chalk.grey(`(${why}${p.expected_rows !== undefined && p.expected_rows !== null ? `; ${n(p.expected_rows)} rows to load` : ''})`)}`;
147
+ }
148
+ return `${chalk.yellow('○')} ${t} ${dryRun ? 'would be sent, then loaded' : 'to send, then load'} ${at} ${chalk.grey(`(${p.why})`)}`;
149
+ }
150
+ const planLine = (p, branch, chalk, o) => stateLine(p, `in ${branch}`, chalk, o);
151
+
152
+ /** Registre et état réel dans cet environnement (poad.io lit la base de l'engine) */
153
+ const registryOf = (id, branch) => require('./cloud/api').call('GET', `v1/projects/${require('./cloud/api').enc(id)}/seeds?verify=${encodeURIComponent(branch)}`, { what: 'references' });
154
+
155
+ /**
156
+ * Envoie et charge les grosses références dans un environnement ; dryRun : dit seulement ce qui attend chaque
157
+ * table. Renvoie { tables: [{ target, action: 'unchanged'|'load'|'sent', state, … }], load, failed }.
158
+ */
159
+ async function sendAndLoad(id, branch, poadDir, files, opts, out, { dryRun = false } = {}) {
91
160
  const api = require('./cloud/api');
92
161
  const S = require('./seed/run');
93
162
  const { startAndWait } = require('../project/ref/push');
94
163
  const { chalk } = out;
95
- const registry = await api.call('GET', `v1/projects/${api.enc(id)}/seeds`, { what: 'references' });
96
- if (!registry.store) throw new api.CloudError('The reference store is not configured on this poad.io instance: large reference tables cannot be sent.', { code: 'store_missing' });
97
- const stored = new Map(registry.items.map((s) => [s.target, s.sha256]));
98
- const applied = (registry.applied && registry.applied[branch]) || {};
164
+ const registry = await registryOf(id, branch);
165
+ if (!registry.store && !dryRun) throw new api.CloudError('The reference store is not configured on this poad.io instance: large reference tables cannot be sent.', { code: 'store_missing' });
166
+ const planned = plan(registry, branch, poadDir, files);
167
+ if (dryRun) {
168
+ for (const p of planned) out.log(planLine(p, branch, chalk, { dryRun: true }));
169
+ return { tables: planned.map((p) => ({ target: p.target, action: p.action === 'loaded' ? 'unchanged' : p.action, state: p.action === 'loaded' ? 'loaded' : 'pending', rows: p.rows ?? null, sha256: p.sha256 || null, reason: p.state || p.why, checked: p.checked ?? null })), load: null, failed: false, dry_run: true };
170
+ }
99
171
  const cache = readCache(poadDir);
100
172
  const tables = [];
101
173
  const toLoad = [];
102
- for (const f of files) {
103
- const c = cache[f.file];
104
- const same = c && c.size === f.size && c.mtimeMs === f.mtimeMs && c.sha256 && stored.get(f.target) === c.sha256;
105
- if (same) {
106
- if (applied[f.target] && applied[f.target].sha256 === c.sha256) {
107
- out.log(`${chalk.greenBright('✔')} ${chalk.bold(f.target)} ${chalk.grey('reference unchanged, already loaded in ' + branch)}`);
108
- tables.push({ target: f.target, action: 'unchanged', sha256: c.sha256 });
109
- } else {
110
- tables.push({ target: f.target, action: 'load', sha256: c.sha256 });
111
- toLoad.push(f.target);
112
- }
174
+ for (const p of planned) {
175
+ const f = files.find((x) => x.file === p.file);
176
+ if (p.action !== 'send') {
177
+ out.log(planLine(p, branch, chalk));
178
+ tables.push({ target: p.target, action: p.action === 'loaded' ? 'unchanged' : 'load', sha256: p.sha256, rows: p.rows ?? null, reason: p.state, checked: p.checked });
179
+ if (p.action === 'load') toLoad.push(p.target);
113
180
  continue;
114
181
  }
115
182
  // Conversion puis envoi (contenu déjà au magasin : rien n'est renvoyé)
@@ -141,11 +208,14 @@ async function sendAndLoad(id, branch, poadDir, files, opts, out) {
141
208
  },
142
209
  });
143
210
  if (!out.json && process.stderr.isTTY) process.stderr.write('\r\x1b[K');
144
- out.log(`${chalk.greenBright('✔')} ${chalk.bold(t.target)} ${r.uploaded ? `sent to the reference store (${S.fmt(r.stored)} encrypted)` : 'already in the reference store'}`);
145
211
  cache[f.file] = { size: f.size, mtimeMs: f.mtimeMs, sha256: t.sha256, target: t.target };
146
212
  writeCache(poadDir, cache);
147
- tables.push({ target: t.target, action: 'sent', sha256: t.sha256, rows: t.rows, uploaded: r.uploaded });
148
- if (!(applied[t.target] && applied[t.target].sha256 === t.sha256)) toLoad.push(t.target);
213
+ // Contenu inchangé au magasin : il peut être déjà chargé (l'état lu dans la base le dit)
214
+ const st = cloudState(registry, branch, t.target, t.sha256);
215
+ const loaded = st.state === 'loaded';
216
+ out.log(`${loaded ? chalk.greenBright('✔') : chalk.yellow('○')} ${chalk.bold(t.target)} ${r.uploaded ? `sent to the reference store (${S.fmt(r.stored)} encrypted)` : 'already in the reference store'}${loaded ? `, already loaded in ${branch} ${chalk.grey(`(${n(st.rows)} rows, sha256 ${short(t.sha256)})`)}` : `, to load in ${branch}`}`);
217
+ tables.push({ target: t.target, action: 'sent', sha256: t.sha256, rows: t.rows, uploaded: r.uploaded, reason: st.state });
218
+ if (!loaded) toLoad.push(t.target);
149
219
  } finally {
150
220
  fs.rmSync(dir, { recursive: true, force: true });
151
221
  }
@@ -155,11 +225,11 @@ async function sendAndLoad(id, branch, poadDir, files, opts, out) {
155
225
  // État de chaque table dans cet environnement : loaded, pending (pas encore chargée), refused (place), failed
156
226
  for (const t of tables) {
157
227
  const st = load && (load.steps || []).find((x) => x.target === t.target);
158
- if (t.action === 'unchanged') t.state = 'loaded';
228
+ if (!toLoad.includes(t.target)) t.state = 'loaded';
159
229
  else if (st) t.state = st.status === 'done' ? 'loaded' : st.status === 'failed' ? (st.reason === 'space' ? 'refused' : 'failed') : 'pending';
160
230
  else t.state = 'pending';
161
231
  }
162
232
  return { tables, load, failed: Boolean(load && load.status === 'failed') };
163
233
  }
164
234
 
165
- module.exports = { LARGE, largeFiles, ensureGitignore, ignoreText, sendAndLoad, IGNORE_HEADER };
235
+ module.exports = { LARGE, largeFiles, ensureGitignore, ignoreText, sendAndLoad, IGNORE_HEADER, plan, planLine, stateLine, cloudState, readCache, WHY };
@@ -22,7 +22,7 @@ const files = (root) => {
22
22
  * pu être synchronisée ; true sinon (y compris sans table, ou avec un engine
23
23
  * qui ne connaît pas encore les tables de référence).
24
24
  */
25
- const sync = async (root, config, { force = false } = {}) => {
25
+ const sync = async (root, config, { force = false, via = 'poad start' } = {}) => {
26
26
  const chalk = require('chalk-v2');
27
27
  if (!files(root).length) return true;
28
28
  let res;
@@ -59,8 +59,91 @@ const sync = async (root, config, { force = false } = {}) => {
59
59
  console.log(`${chalk.greenBright('✔')} ${chalk.bold(name)} ${chalk.grey(`: ${t.rows} row(s), ${t.upserted} written, ${t.deleted} removed`)}`);
60
60
  }
61
61
  }
62
- if (ok && !tables.some((t) => t.upserted || t.deleted)) console.log(chalk.grey(` Reference tables up to date (${tables.length}).`));
63
- return ok;
62
+ // Grosses références (plus de 20 Mo, hors git) : le service meta ne les relit pas au démarrage ; leur état se lit
63
+ // dans la base (marque posée au chargement, lignes). Base neuve, remise à zéro ou table vidée : chargées ici.
64
+ const large = await ensureLarge(root, config, { via }).catch((e) => ({ ok: false, error: e.message, tables: [] }));
65
+ if (large.error) console.log(chalk.yellowBright(` ⚠ large reference tables not checked: ${large.error}`));
66
+ const small = tables.filter((t) => !large.tables.some((x) => x.target === `${t.schema}.${t.name}`));
67
+ if (ok && !small.some((t) => t.upserted || t.deleted) && small.length) console.log(chalk.grey(` Reference tables up to date (${small.length}).`));
68
+ return ok && large.ok;
64
69
  };
65
70
 
66
- module.exports = { dir, files, sync };
71
+ /**
72
+ * Grosses références du dossier dans l'engine local : déjà chargée (marque à l'empreinte du fichier converti, autant
73
+ * de lignes qu'à la pose) ou chargée maintenant (COPY, même conversion que poad deploy, marque posée dans la même
74
+ * transaction). Une ligne par table à l'écran et au puits local (service cli, event=reference_state).
75
+ * force : recharge même déjà chargée. Renvoie { ok, tables: [{ target, state, action, rows }] }.
76
+ */
77
+ const ensureLarge = async (root, config, { via = 'poad start', force = false, out = null } = {}) => {
78
+ const chalk = require('chalk-v2');
79
+ const log = out ? (l) => out.log(l) : (l) => console.log(l);
80
+ const refStore = require('./reference-store');
81
+ const poadDir = path.dirname(root);
82
+ const files = refStore.largeFiles(poadDir);
83
+ if (!files.length) return { ok: true, tables: [] };
84
+ const S = require('./seed/run');
85
+ const A = require('./seed/apply');
86
+ const container = config.project_uuid;
87
+ const order = A.loadOrder(files.map((f) => f.target), await S.localEdges(container));
88
+ const st = await S.localState(container, order);
89
+ if (!st) throw new Error('the local database cannot be read');
90
+ const cache = refStore.readCache(poadDir);
91
+ const results = [];
92
+ const logs = [];
93
+ let ok = true;
94
+ for (const target of order) {
95
+ const f = files.find((x) => x.target === target);
96
+ const c = cache[f.file];
97
+ const known = c && c.size === f.size && c.mtimeMs === f.mtimeMs && c.sha256 ? c.sha256 : null;
98
+ const raw = st[target];
99
+ // Empreinte du contenu converti : celle de la mémoire locale si le fichier n'a pas bougé, sinon recalculée
100
+ let state = known ? A.referenceState(known, raw) : raw && raw.sha256 ? null : A.referenceState(null, raw);
101
+ let conv = null;
102
+ let dir = null;
103
+ try {
104
+ if (state === null || (state !== 'loaded' && state !== 'no_table') || force) {
105
+ dir = S.tmpDir();
106
+ conv = (await S.convertFile(f.abs, { format: 'jsonl', dir })).tables[0];
107
+ if (!conv) throw new Error(`${f.rel}: no row`);
108
+ cache[f.file] = { size: f.size, mtimeMs: f.mtimeMs, sha256: conv.sha256, target: conv.target };
109
+ require('fs').mkdirSync(path.join(poadDir, 'data'), { recursive: true });
110
+ require('fs').writeFileSync(path.join(poadDir, 'data', 'reference-store.json'), JSON.stringify(cache, null, 2) + '\n');
111
+ if (state === null) state = A.referenceState(conv.sha256, raw);
112
+ }
113
+ const sha = conv ? conv.sha256 : known;
114
+ const x = { target, state, rows: raw ? raw.rows : null, mark_rows: raw ? raw.mark_rows : null, sha256: raw && raw.sha256 ? raw.sha256 : sha, expected_rows: conv ? conv.rows : raw && raw.mark_rows, checked: true };
115
+ // Au puits tout de suite : l'état d'avant le chargement, à son heure
116
+ await S.localLog(container, [{ msg: `reference ${target}: ${state}`, attrs: { event: 'reference_state', table: target, state, rows: x.rows, mark_rows: x.mark_rows, sha256: sha ? sha.slice(0, 12) : null, env: 'local', via } }]);
117
+ if (state === 'no_table') {
118
+ ok = false;
119
+ log(`${chalk.yellowBright('⚠')} ${chalk.bold(target)} ${chalk.grey('not loaded: the table does not exist (migration not applied?)')}`);
120
+ results.push({ target, state, action: 'none' });
121
+ continue;
122
+ }
123
+ if (state === 'loaded' && !force) {
124
+ log(refStore.stateLine({ ...x, action: 'loaded' }, 'locally', chalk));
125
+ results.push({ target, state, action: 'unchanged', rows: x.rows });
126
+ continue;
127
+ }
128
+ log(refStore.stateLine({ ...x, action: 'load', state: force && state === 'loaded' ? 'forced' : state }, 'locally', chalk));
129
+ const t0 = Date.now();
130
+ const r = await S.loadLocalFile(container, conv);
131
+ const ms = Date.now() - t0;
132
+ log(`${chalk.greenBright('✔')} ${chalk.bold(target)} loaded locally: ${Number(r.written || 0).toLocaleString('en-US')} rows written, ${Number(r.deleted || 0).toLocaleString('en-US')} removed ${chalk.grey(`(${(ms / 1000).toFixed(1)} s, sha256 ${sha.slice(0, 12)})`)}`);
133
+ for (const w of r.warnings || []) log(chalk.yellowBright(` ⚠ ${w}`));
134
+ logs.push({ msg: `reference ${target} loaded locally: ${r.written} rows`, attrs: { event: 'reference_load', table: target, outcome: 'loaded', reason: state, rows: r.written, deleted: r.deleted, duration_ms: ms, sha256: sha.slice(0, 12), env: 'local', via } });
135
+ results.push({ target, state, action: 'loaded', rows: r.written });
136
+ } catch (e) {
137
+ ok = false;
138
+ log(`${chalk.redBright('✖')} ${chalk.bold(target)} not loaded locally: ${e.message}`);
139
+ logs.push({ level: 'warn', msg: `reference ${target} not loaded locally`, attrs: { event: 'reference_load', table: target, outcome: 'failed', reason: state, env: 'local', via } });
140
+ results.push({ target, state, action: 'failed', error: e.message });
141
+ } finally {
142
+ if (dir) require('fs').rmSync(dir, { recursive: true, force: true });
143
+ }
144
+ }
145
+ await S.localLog(container, logs);
146
+ return { ok, tables: results };
147
+ };
148
+
149
+ module.exports = { dir, files, sync, ensureLarge };
@@ -72,7 +72,7 @@ const SEQUENCES = ` for s in select a.attname::text as col, pg_get_serial_seque
72
72
  end loop;`;
73
73
 
74
74
  /** Fin du script (après les lignes de données) */
75
- function tail(target, columns) {
75
+ function tail(target, columns, sha256) {
76
76
  const arr = columns && columns.length ? `array[${columns.map(quoteLiteral).join(', ')}]::text[]` : 'null::text[]';
77
77
  const reg = `${quoteLiteral(sqlName(target))}::regclass`;
78
78
  return `\\.
@@ -113,8 +113,10 @@ begin
113
113
  get diagnostics d = row_count;
114
114
  execute format('insert into %s (%s) overriding system value select %s from _poad_seed', t, collist, collist);
115
115
  else
116
+ -- Clé primaire : jamais nulle, « = » suffit et permet une anti-jointure par hachage (« is not distinct
117
+ -- from » forçait une boucle imbriquée : 132 s pour recharger 260 000 lignes sur 100 000)
116
118
  execute format('delete from %s x where not exists (select 1 from _poad_seed s where %s)', t,
117
- (select string_agg(format('s.%1$I is not distinct from x.%1$I', c), ' and ') from unnest(pk) c));
119
+ (select string_agg(format('s.%1$I = x.%1$I', c), ' and ') from unnest(pk) c));
118
120
  get diagnostics d = row_count;
119
121
  setlist := (select string_agg(format('%1$I = excluded.%1$I', c), ', ') from unnest(cols) c where c <> all (pk));
120
122
  execute format('insert into %s (%s) overriding system value select %s from _poad_seed on conflict (%s) do %s', t, collist, collist,
@@ -127,7 +129,7 @@ ${SEQUENCES}
127
129
  end
128
130
  $poad$;
129
131
  \\endif
130
- commit;
132
+ ${sha256 ? markSql(target, sha256) : ''}commit;
131
133
  `;
132
134
  }
133
135
 
@@ -137,6 +139,68 @@ function parseNotice(text) {
137
139
  return m ? { table: m[1], written: Number(m[2]), deleted: Number(m[3]) } : null;
138
140
  }
139
141
 
142
+ // --- État réel d'une table de référence dans la base (CLI 2.76.2) ---------------------------------
143
+ // La marque est posée dans la base du projet, dans la transaction du chargement : _poad.reference_loads
144
+ // (table, empreinte sha256 du contenu chargé, nombre de lignes après chargement). Un volume recréé vide ou
145
+ // une base remise à zéro la perdent avec les lignes : la table redevient « à charger ». Le registre du
146
+ // plan de contrôle (seed_applied) et poad/data du CLI ne sont qu'un cache de cet état.
147
+
148
+ const SHA_RE = /^[0-9a-f]{64}$/;
149
+
150
+ /** Instructions qui posent la marque (dans une transaction ouverte) ; la table de marques est créée au besoin */
151
+ function markSql(target, sha256) {
152
+ if (!SHA_RE.test(String(sha256))) throw new Error('empreinte sha256 attendue');
153
+ return `create schema if not exists _poad;
154
+ create table if not exists _poad.reference_loads (target text primary key, sha256 text not null, rows bigint not null, loaded_at timestamptz not null default now());
155
+ revoke all on _poad.reference_loads from public;
156
+ insert into _poad.reference_loads (target, sha256, rows) select ${quoteLiteral(target)}, ${quoteLiteral(sha256)}, count(*) from ${sqlName(target)}
157
+ on conflict (target) do update set sha256 = excluded.sha256, rows = excluded.rows, loaded_at = now();
158
+ `;
159
+ }
160
+
161
+ /**
162
+ * Une requête (une ligne JSON) : pour chaque table, existe-t-elle, est-elle vide, sa marque (empreinte, lignes
163
+ * à la pose) et, si elle est marquée, son nombre de lignes. Lecture seule ; marche aussi sans la table de marques
164
+ * (engine jamais chargé) et sans la table elle-même (migration non appliquée).
165
+ */
166
+ function stateSql(targets) {
167
+ const rows = targets.map((t) => `(${quoteLiteral(t)}, ${quoteLiteral(sqlName(t))})`).join(', ');
168
+ const xp = (path, x, type) => `(xpath('${path}/text()', ${x}))[1]::text${type ? `::${type}` : ''}`;
169
+ return `select coalesce(json_agg(json_build_object('target', target, 'exists', rel is not null, 'empty', empty, 'sha256', ${xp('/row/s', 'mark')}, 'mark_rows', ${xp('/row/r', 'mark', 'bigint')}, 'loaded_at', ${xp('/row/l', 'mark')}, ` +
170
+ `'rows', case when rel is not null and ${xp('/row/s', 'mark')} is not null then ${xp('/row/n', "query_to_xml(format('select count(*) as n from %s', rel), false, true, '')", 'bigint')} end) order by target), '[]')::text from (` +
171
+ `select w.target, w.rel, case when w.rel is null then null else ${xp('/row/e', "query_to_xml(format('select not exists (select 1 from %s) as e', w.rel), false, true, '')", 'boolean')} end as empty, ` +
172
+ `case when to_regclass('_poad.reference_loads') is not null then nullif(query_to_xml(format('select sha256 as s, rows as r, loaded_at as l from _poad.reference_loads where target = %L', w.target), false, true, '')::text, '')::xml end as mark ` +
173
+ `from (select v.target, to_regclass(v.name) as rel from (values ${rows}) v(target, name)) w) y`;
174
+ }
175
+
176
+ /**
177
+ * Verdict pour une table : loaded (marque à l'empreinte attendue, autant de lignes qu'à la pose ou plus),
178
+ * sinon à charger : empty (vide, sans marque), unmarked (des lignes, pas de marque), outdated (autre
179
+ * empreinte), incomplete (moins de lignes qu'à la pose), no_table (pas encore créée) ; unknown : base illisible.
180
+ * expected : une empreinte ou une liste d'empreintes acceptées.
181
+ */
182
+ function referenceState(expected, st) {
183
+ if (!st) return 'unknown';
184
+ if (!st.exists) return 'no_table';
185
+ if (!st.sha256) return st.empty ? 'empty' : 'unmarked';
186
+ const ok = (Array.isArray(expected) ? expected : [expected]).filter(Boolean);
187
+ if (ok.length && !ok.includes(st.sha256)) return 'outdated';
188
+ if (st.rows === null || st.rows === undefined || Number(st.rows) < Number(st.mark_rows || 0)) return 'incomplete';
189
+ return 'loaded';
190
+ }
191
+
192
+ /** Sortie de stateSql (dernière ligne non vide) → { target: état brut } ; null si illisible */
193
+ function parseState(text) {
194
+ const line = String(text || '').trim().split('\n').filter(Boolean).pop();
195
+ try {
196
+ const list = JSON.parse(line);
197
+ if (!Array.isArray(list)) return null;
198
+ return Object.fromEntries(list.map((x) => [x.target, { ...x, rows: x.rows === null ? null : Number(x.rows), mark_rows: x.mark_rows === null ? null : Number(x.mark_rows) }]));
199
+ } catch {
200
+ return null;
201
+ }
202
+ }
203
+
140
204
  /** Requête des dépendances (clés étrangères) entre tables, pour l'ordre de chargement */
141
205
  const FK_SQL = "select conrelid::regclass::text || '|' || confrelid::regclass::text from pg_constraint where contype = 'f' and conrelid <> confrelid";
142
206
 
@@ -164,4 +228,4 @@ function loadOrder(targets, edges) {
164
228
  return out;
165
229
  }
166
230
 
167
- module.exports = { head, tail, parseNotice, sqlName, quoteIdent, loadOrder, FK_SQL };
231
+ module.exports = { head, tail, parseNotice, sqlName, quoteIdent, loadOrder, FK_SQL, markSql, stateSql, referenceState, parseState };
package/utils/seed/run.js CHANGED
@@ -188,7 +188,7 @@ async function loadLocal(container, d, { database } = {}) {
188
188
  // psql peut s'arrêter avant la fin (ON_ERROR_STOP) : c'est alors son message qui compte, pas l'écriture coupée
189
189
  let streamErr = null;
190
190
  await pipeline(Readable.fromWeb(res.body), decryptStream(Buffer.from(d.key, 'base64')), zlib.createGunzip(), c.stdin, { end: false })
191
- .then(() => c.stdin.end(A.tail(d.target, d.columns)))
191
+ .then(() => c.stdin.end(A.tail(d.target, d.columns, d.sha256)))
192
192
  .catch((e) => {
193
193
  streamErr = e;
194
194
  c.stdin.destroy();
@@ -206,6 +206,66 @@ async function loadLocal(container, d, { database } = {}) {
206
206
  }
207
207
 
208
208
  /** Dépendances entre tables de l'engine local (ordre de chargement) */
209
+ /**
210
+ * Contenu converti (convertFile : COPY en gzip) chargé dans l'engine local, avec la marque de son empreinte (la
211
+ * même que sur poad.io pour le même fichier) ; { written, deleted, warnings }
212
+ */
213
+ async function loadLocalFile(container, t, { database } = {}) {
214
+ const c = localPsql(container, [], database);
215
+ let out = '';
216
+ c.stdout.on('data', (x) => (out = (out + x).slice(-20000)));
217
+ c.stderr.on('data', (x) => (out = (out + x).slice(-20000)));
218
+ const closed = new Promise((r) => c.on('close', r));
219
+ c.stdin.on('error', () => {});
220
+ c.stdin.write(A.head(t.target, t.columns));
221
+ let streamErr = null;
222
+ await pipeline(fs.createReadStream(t.file), zlib.createGunzip(), c.stdin, { end: false })
223
+ .then(() => c.stdin.end(A.tail(t.target, t.columns, t.sha256)))
224
+ .catch((e) => {
225
+ streamErr = e;
226
+ c.stdin.destroy();
227
+ });
228
+ const code = await closed;
229
+ if (code === 0 && streamErr) throw new api.CloudError(`${t.target}: ${streamErr.message}`, { code: 'seed_load_failed' });
230
+ if (code !== 0) {
231
+ const lines = out.split('\n');
232
+ const e = (lines.find((l) => /ERROR:/.test(l)) || lines.filter(Boolean).pop() || `psql ${code}`).replace(/^psql:[^E]*/, '').replace(/^ERROR:\s+([0-9A-Z]{5}:\s+)?/, '');
233
+ throw new api.CloudError(`${t.target}: ${e}`, { code: 'seed_load_failed' });
234
+ }
235
+ const warnings = out.split('\n').filter((l) => /WARNING:.*poad-seed/.test(l)).map((l) => l.replace(/^.*WARNING:\s+([0-9A-Z]{5}:\s+)?poad-seed\s+/, ''));
236
+ return { ...(A.parseNotice(out) || { written: null, deleted: null }), warnings };
237
+ }
238
+
239
+ /** État réel des tables dans la base locale (marque posée au chargement, lignes) ; null : illisible */
240
+ function localState(container, targets) {
241
+ if (!targets.length) return Promise.resolve({});
242
+ return new Promise((resolve) => {
243
+ const c = localPsql(container, ['-tA', '-c', A.stateSql(targets)]);
244
+ let out = '';
245
+ c.stdout.on('data', (x) => (out += x));
246
+ c.on('error', () => resolve(null));
247
+ c.on('close', (code) => resolve(code === 0 ? A.parseState(out) : null));
248
+ c.stdin.end();
249
+ });
250
+ }
251
+
252
+ /**
253
+ * Lignes du puits de logs local (service cli) : event=reference_state (une par table vérifiée) ou reference_load ;
254
+ * noms, états, nombres de lignes, empreintes courtes ; jamais une valeur des données.
255
+ */
256
+ function localLog(container, entries) {
257
+ if (!entries.length) return Promise.resolve();
258
+ const lit = (v) => `'${String(v).replace(/'/g, "''")}'`;
259
+ const values = entries.map((e) => `(${lit(e.level || 'info')}, ${lit(e.msg)}, ${lit(JSON.stringify(e.attrs))})`).join(', ');
260
+ const sql = `insert into _logs.entries (ts, level, service, msg, attrs) select now(), l, 'cli', m, a::jsonb from (values ${values}) v(l, m, a) where to_regclass('_logs.entries') is not null`;
261
+ return new Promise((resolve) => {
262
+ const c = localPsql(container, ['-tA', '-c', sql]);
263
+ c.on('error', () => resolve());
264
+ c.on('close', () => resolve());
265
+ c.stdin.end();
266
+ });
267
+ }
268
+
209
269
  function localEdges(container) {
210
270
  return new Promise((resolve) => {
211
271
  const c = localPsql(container, ['-tA', '-c', A.FK_SQL]);
@@ -216,4 +276,4 @@ function localEdges(container) {
216
276
  });
217
277
  }
218
278
 
219
- module.exports = { convertFile, pushTable, waitLoad, loadLocal, localEdges, fmt, tmpDir };
279
+ module.exports = { convertFile, pushTable, waitLoad, loadLocal, loadLocalFile, localState, localLog, localEdges, fmt, tmpDir };