poad 2.76.1 → 2.76.3

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.
@@ -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;
@@ -0,0 +1,48 @@
1
+ // Liens de redirection des moteurs de recherche, réseaux sociaux et messageries (google.com/url?url=…,
2
+ // l.facebook.com/l.php?u=…, safelinks d'Outlook…). Ils rendent une page HTML (200) qui redirige en
3
+ // JavaScript : lus tels quels, ils donnent « page web au lieu d'un fichier ». L'adresse du fichier est dans
4
+ // un paramètre : poad source link la reprend. Même liste que l'engine (services/meta/src/source-redirectors.ts,
5
+ // engine 0.73.2), qui déballe aussi de son côté. Pur, sans réseau.
6
+
7
+ const REDIRECTORS = [
8
+ { name: 'Google', host: /^(www\.)?google\.[a-z.]{2,7}$/i, path: /^\/url\/?$/, params: ['url', 'q'] },
9
+ { name: 'Facebook', host: /^(l|lm|m|www)\.facebook\.com$/i, path: /^\/l\.php$/, params: ['u'] },
10
+ { name: 'Instagram', host: /^l\.instagram\.com$/i, path: /^\/?$/, params: ['u'] },
11
+ { name: 'Messenger', host: /^l\.messenger\.com$/i, path: /^\/l\.php$/, params: ['u'] },
12
+ { name: 'YouTube', host: /^(www\.)?youtube\.com$/i, path: /^\/redirect$/, params: ['q'] },
13
+ { name: 'Outlook', host: /^[a-z0-9-]+\.safelinks\.protection\.outlook\.com$/i, path: /^\/?$/, params: ['url'] },
14
+ { name: 'DuckDuckGo', host: /^(www\.)?duckduckgo\.com$/i, path: /^\/l\/?$/, params: ['uddg'] },
15
+ { name: 'LinkedIn', host: /^(www\.)?linkedin\.com$/i, path: /^\/redir\/redirect\/?$/, params: ['url'] },
16
+ { name: 'Slack', host: /^slack-redir\.net$/i, path: /^\/link$/, params: ['url'] },
17
+ { name: 'Steam', host: /^steamcommunity\.com$/i, path: /^\/linkfilter\/?$/, params: ['url', 'u'] },
18
+ ];
19
+
20
+ /**
21
+ * Adresse directe d'un lien de redirection : { url, via } (via = nom du service, null si l'adresse est déjà
22
+ * directe). Plusieurs couches, 5 au plus ; seule une cible http(s) est reprise ; une adresse illisible est rendue telle quelle.
23
+ */
24
+ const directUrl = (raw) => {
25
+ let url = String(raw == null ? '' : raw).trim();
26
+ let via = null;
27
+ for (let i = 0; i < 5; i++) {
28
+ let u;
29
+ try {
30
+ u = new URL(url);
31
+ } catch {
32
+ break;
33
+ }
34
+ const r = REDIRECTORS.find((x) => x.host.test(u.hostname) && x.path.test(u.pathname));
35
+ const target = r ? r.params.map((p) => u.searchParams.get(p)).find((v) => v && /^https?:\/\//i.test(v.trim())) : null;
36
+ if (!r || !target) break;
37
+ try {
38
+ new URL(target.trim());
39
+ } catch {
40
+ break;
41
+ }
42
+ url = target.trim();
43
+ if (via === null) via = r.name;
44
+ }
45
+ return { url, via };
46
+ };
47
+
48
+ module.exports = { directUrl };
@@ -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 };