poad 2.73.0 → 2.74.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/global/start.js +9 -1
- package/package.json +1 -1
- package/project/cli.js +4 -2
- package/project/deploy.js +39 -2
- package/project/logs.js +6 -2
- package/project/migrate-cloud.js +184 -0
- package/project/migrate.js +29 -6
- package/project/migration-pull.js +159 -0
- package/project/migration.js +7 -2
- package/project/transform.js +354 -0
- package/project/transforms.js +2 -0
- package/test/api-exposure.test.js +38 -1
- package/test/cloud.test.js +161 -0
- package/test/transform.test.js +177 -0
- package/utils/api-exposure/index.js +53 -2
- package/utils/cloud/bundle.js +2 -2
- package/utils/help-details.js +34 -6
- package/utils/logline.js +4 -2
- package/utils/migrate-run.js +15 -1
- package/utils/migrations.js +31 -1
- package/utils/transforms.js +64 -0
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
// poad transform : ls, check, run (suivi), preview, new, pull ; filtre transform= de poad logs ;
|
|
2
|
+
// poad/transforms dans l'archive de poad deploy.
|
|
3
|
+
const test = require('node:test');
|
|
4
|
+
const assert = require('node:assert');
|
|
5
|
+
const fs = require('fs');
|
|
6
|
+
const path = require('path');
|
|
7
|
+
const zlib = require('zlib');
|
|
8
|
+
const { tmpdir } = require('./helpers');
|
|
9
|
+
|
|
10
|
+
const transform = require('../project/transform');
|
|
11
|
+
const RUN = '7c2e1d90-4b3a-4f1e-8d2c-5a6b7c8d9e0f';
|
|
12
|
+
|
|
13
|
+
const LIST = {
|
|
14
|
+
available: true,
|
|
15
|
+
dir: 'poad/transforms',
|
|
16
|
+
store: 'file',
|
|
17
|
+
hosted: false,
|
|
18
|
+
running: null,
|
|
19
|
+
order: ['commandes_propres', 'ventes_par_mois'],
|
|
20
|
+
models: [
|
|
21
|
+
{ name: 'commandes_propres', file: 'poad/transforms/staging/commandes_propres.sql', stored: 'file', valid: true, problems: [], warnings: [], materialized: 'view', schema: 'staging', api: false, lecture: 'connectes', upstream: [], downstream: ['ventes_par_mois'], reads: ['public.commandes'], stale: false, last_run: { run_id: RUN, status: 'ok', rows: null, duration_ms: 7, at: '2026-12-04T10:00:00Z', error: null } },
|
|
22
|
+
{ name: 'ventes_par_mois', file: 'poad/transforms/ventes_par_mois.sql', stored: 'file', valid: true, problems: [], warnings: [], materialized: 'table', schema: 'public', api: true, lecture: 'connectes', upstream: ['commandes_propres'], downstream: [], reads: ['public.magasins'], stale: false, last_run: { run_id: RUN, status: 'failed', rows: null, duration_ms: 3, at: '2026-12-04T10:00:00Z', error: { code: '42703', message: 'column "x" does not exist', line: 9, col: 8 } } },
|
|
23
|
+
{ name: 'casse', file: 'poad/transforms/casse.sql', stored: 'file', valid: false, problems: [{ path: 'sql', message: 'cycle : casse → casse', line: 1 }], warnings: [], materialized: null, upstream: [], downstream: [], reads: [], stale: false, last_run: null },
|
|
24
|
+
],
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
function sandbox(t, { engine = '0.72.0' } = {}) {
|
|
28
|
+
const dir = tmpdir(t, 'poad-transform-');
|
|
29
|
+
const app = path.join(dir, 'app');
|
|
30
|
+
fs.mkdirSync(path.join(app, 'poad'), { recursive: true });
|
|
31
|
+
fs.writeFileSync(path.join(app, 'poad', 'config.toml'), `project_id = "demo"\nproject_uuid = "poad-transform-test-not-a-container"\nengine = "${engine}"\n[web]\nport = 1\n[db]\nport = 1\n`);
|
|
32
|
+
fs.writeFileSync(path.join(app, 'poad', 'secrets.toml'), '[auth]\nsecret = "LOCAL-SECRET-x"\nanon = "LOCAL-ANON-x"\nservice = "LOCAL-SERVICE-x"\nadmin = "LOCAL-ADMIN-x"\n');
|
|
33
|
+
return { dir, app };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Faux engine : rend des réponses selon le chemin ; garde les appels */
|
|
37
|
+
function fakeEngine(routes) {
|
|
38
|
+
const calls = [];
|
|
39
|
+
const fetchImpl = async (url, init = {}) => {
|
|
40
|
+
const u = new URL(url);
|
|
41
|
+
const body = init.body ? JSON.parse(init.body) : undefined;
|
|
42
|
+
calls.push({ method: init.method || 'GET', path: u.pathname, headers: init.headers, body });
|
|
43
|
+
const r = routes(init.method || 'GET', u.pathname, body, calls);
|
|
44
|
+
const [status, data] = r || [404, { error: { code: 'not_found', message: 'no route' } }];
|
|
45
|
+
return { status, ok: status >= 200 && status < 300, json: async () => data };
|
|
46
|
+
};
|
|
47
|
+
return { calls, fetchImpl };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const capture = async (fn) => {
|
|
51
|
+
const lines = [];
|
|
52
|
+
const log = console.log;
|
|
53
|
+
console.log = (...a) => lines.push(a.join(' '));
|
|
54
|
+
const before = process.exitCode;
|
|
55
|
+
process.exitCode = undefined;
|
|
56
|
+
try {
|
|
57
|
+
await fn();
|
|
58
|
+
} finally {
|
|
59
|
+
console.log = log;
|
|
60
|
+
}
|
|
61
|
+
const code = process.exitCode;
|
|
62
|
+
process.exitCode = before;
|
|
63
|
+
return { out: lines.join('\n').replace(/\x1b\[[0-9;]*m/g, ''), code };
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
test('ls : état, erreur située, modèle invalide, clé service_role et x-poad-by', async (t) => {
|
|
67
|
+
const box = sandbox(t);
|
|
68
|
+
const e = fakeEngine((m, p) => (m === 'GET' && p === '/meta/v1/transforms' ? [200, LIST] : null));
|
|
69
|
+
const r = await capture(() => transform.main({}, ['ls'], { cwd: box.app, fetch: e.fetchImpl, started: async () => true }));
|
|
70
|
+
assert.match(r.out, /commandes_propres {2}view staging/);
|
|
71
|
+
assert.match(r.out, /ventes_par_mois {2}table, API \(connectes\)/);
|
|
72
|
+
assert.match(r.out, /column "x" does not exist \(poad\/transforms\/ventes_par_mois.sql:9\)/);
|
|
73
|
+
assert.match(r.out, /casse.sql:1 {2}cycle : casse → casse/);
|
|
74
|
+
assert.strictEqual(e.calls[0].headers.authorization, 'Bearer LOCAL-SERVICE-x');
|
|
75
|
+
assert.strictEqual(e.calls[0].headers['x-poad-by'], 'cli');
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
test('check : code 1 si un modèle est invalide', async (t) => {
|
|
79
|
+
const box = sandbox(t);
|
|
80
|
+
const e = fakeEngine((m, p) => (p === '/meta/v1/transforms' ? [200, LIST] : null));
|
|
81
|
+
const r = await capture(() => transform.main({}, ['check'], { cwd: box.app, fetch: e.fetchImpl, started: async () => true }));
|
|
82
|
+
assert.strictEqual(r.code, 1);
|
|
83
|
+
assert.match(r.out, /✖ poad\/transforms\/casse.sql:1 {2}cycle/);
|
|
84
|
+
assert.match(r.out, /1 of 3 model\(s\) invalid/);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
test('run : sélecteurs envoyés, passage suivi modèle par modèle', async (t) => {
|
|
88
|
+
const box = sandbox(t);
|
|
89
|
+
let polls = 0;
|
|
90
|
+
const e = fakeEngine((m, p) => {
|
|
91
|
+
if (m === 'POST' && p === '/meta/v1/transforms/run') return [202, { queued: 4, run_id: RUN, waiting: false }];
|
|
92
|
+
if (m === 'GET' && p === `/meta/v1/transforms/runs/${RUN}`) {
|
|
93
|
+
polls++;
|
|
94
|
+
return [200, polls < 2 ? { status: 'running', models: [{ model: 'commandes_propres', status: 'ok', materialized: 'view', duration_ms: 7 }] } : { status: 'failed', ok: 1, failed: 1, skipped: 1, duration_ms: 40, models: [{ model: 'commandes_propres', status: 'ok', materialized: 'view', duration_ms: 7 }, { model: 'ventes_par_mois', status: 'failed', error_message: 'boom', error_line: 9, error_col: 8 }, { model: 'top', status: 'skipped', because: 'ventes_par_mois' }] }];
|
|
95
|
+
}
|
|
96
|
+
return null;
|
|
97
|
+
});
|
|
98
|
+
const r = await capture(() => transform.main({}, ['run', 'commandes_propres+'], { cwd: box.app, fetch: e.fetchImpl, started: async () => true, sleep: async () => {} }));
|
|
99
|
+
assert.deepStrictEqual(e.calls[0].body, { trigger: 'manual', selection: ['commandes_propres+'] });
|
|
100
|
+
assert.strictEqual(r.code, 1);
|
|
101
|
+
assert.match(r.out, /✔ commandes_propres {2}view, 7 ms/);
|
|
102
|
+
assert.match(r.out, /✖ ventes_par_mois {2}boom {2}\(line 9, column 8\)/);
|
|
103
|
+
assert.match(r.out, /- top {2}skipped: ventes_par_mois failed/);
|
|
104
|
+
assert.strictEqual((r.out.match(/commandes_propres {2}view/g) || []).length, 1);
|
|
105
|
+
assert.match(r.out, /poad logs transform run=7c2e1d90/);
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
test('run : sélecteur mal formé, engine trop ancien', async (t) => {
|
|
109
|
+
const box = sandbox(t);
|
|
110
|
+
let r = await capture(() => transform.main({}, ['run', 'Ventes!'], { cwd: box.app, fetch: async () => assert.fail('no call'), started: async () => true }));
|
|
111
|
+
assert.strictEqual(r.code, 2);
|
|
112
|
+
const old = sandbox(t, { engine: '0.71.0' });
|
|
113
|
+
r = await capture(() => transform.main({}, ['ls'], { cwd: old.app, fetch: async () => assert.fail('no call'), started: async () => true }));
|
|
114
|
+
assert.match(r.out, /engine 0.72.0 or later/);
|
|
115
|
+
assert.ok(transform.supportsTransforms({ engine: '0.72.0-transform' }));
|
|
116
|
+
assert.ok(!transform.supportsTransforms({ engine: '0.71.0' }));
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
test('new : fichier avec un en-tête minimal, jamais écrasé', async (t) => {
|
|
120
|
+
const box = sandbox(t);
|
|
121
|
+
let r = await capture(() => transform.main({}, ['new', 'ventes', '--table', '--from', 'commandes'], { cwd: box.app }));
|
|
122
|
+
const file = path.join(box.app, 'poad', 'transforms', 'ventes.sql');
|
|
123
|
+
assert.strictEqual(fs.readFileSync(file, 'utf8'), '/* ---\nmaterialized: table\napi: false\n--- */\nselect *\nfrom commandes\n');
|
|
124
|
+
r = await capture(() => transform.main({}, ['new', 'ventes'], { cwd: box.app }));
|
|
125
|
+
assert.match(r.out, /already exists/);
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
test('preview : tableau, rien d’écrit', async (t) => {
|
|
129
|
+
const box = sandbox(t);
|
|
130
|
+
const e = fakeEngine((m, p, b) => (p === '/meta/v1/transforms/preview' ? [200, { name: b.name, columns: [{ name: 'mois', type: 'date' }, { name: 'n', type: 'bigint' }], rows: [{ mois: '2026-09-01', n: 3 }], truncated: false, duration_ms: 4 }] : null));
|
|
131
|
+
const r = await capture(() => transform.main({}, ['preview', 'ventes_par_mois', '--limit', '5'], { cwd: box.app, fetch: e.fetchImpl, started: async () => true }));
|
|
132
|
+
assert.deepStrictEqual(e.calls[0].body, { name: 'ventes_par_mois', limit: 5 });
|
|
133
|
+
assert.match(r.out, /2026-09-01 {2}3/);
|
|
134
|
+
assert.match(r.out, /nothing was written/);
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
test('pull : le texte gardé en base devient poad/transforms/<nom>.sql', async (t) => {
|
|
138
|
+
const box = sandbox(t);
|
|
139
|
+
const e = fakeEngine((m, p) => (p === '/meta/v1/transforms/ventes/sql' ? [200, { name: 'ventes', stored: 'console', text: 'select 1' }] : null));
|
|
140
|
+
await capture(() => transform.main({}, ['pull', 'ventes'], { cwd: box.app, fetch: e.fetchImpl, started: async () => true }));
|
|
141
|
+
assert.strictEqual(fs.readFileSync(path.join(box.app, 'poad', 'transforms', 'ventes.sql'), 'utf8'), 'select 1\n');
|
|
142
|
+
const r = await capture(() => transform.main({}, ['pull', 'ventes'], { cwd: box.app, fetch: e.fetchImpl, started: async () => true }));
|
|
143
|
+
assert.match(r.out, /already exists/);
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
test('poad logs : « transform » est un service, transform=<nom> filtre le modèle', () => {
|
|
147
|
+
const { attrConditions } = require('../utils/logline');
|
|
148
|
+
assert.deepStrictEqual(attrConditions({ transform: true }).conditions, []);
|
|
149
|
+
assert.deepStrictEqual(attrConditions({ transform: 'ventes' }).conditions, [["attrs->>'model' = ?", 'ventes']]);
|
|
150
|
+
assert.deepStrictEqual(attrConditions({ model: 'ventes' }).conditions, [["attrs->>'model' = ?", 'ventes']]);
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
test('poad deploy : poad/transforms (sous-dossiers compris) est dans l’archive', (t) => {
|
|
154
|
+
const dir = tmpdir(t, 'poad-transform-bundle-');
|
|
155
|
+
fs.mkdirSync(path.join(dir, 'transforms', 'staging'), { recursive: true });
|
|
156
|
+
fs.writeFileSync(path.join(dir, 'config.toml'), 'project_id = "demo"\n');
|
|
157
|
+
fs.writeFileSync(path.join(dir, 'transforms', 'staging', 'a.sql'), 'select 1\n');
|
|
158
|
+
const bundle = require('../utils/cloud/bundle');
|
|
159
|
+
assert.ok(bundle.DIRS.includes('transforms'));
|
|
160
|
+
const { files } = bundle.build(dir);
|
|
161
|
+
assert.ok(files.some((f) => f.path === 'transforms/staging/a.sql'), JSON.stringify(files));
|
|
162
|
+
assert.ok(zlib.gunzipSync(bundle.build(dir).tgz).includes(Buffer.from('transforms/staging/a.sql')));
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
test('poad start : un dossier sans .sql ne demande rien à l’engine', (t) => {
|
|
166
|
+
const box = sandbox(t);
|
|
167
|
+
const { hasModels } = require('../utils/transforms');
|
|
168
|
+
// root : comme findPoadDir, un chemin dans poad/ (le dossier des modèles est à côté)
|
|
169
|
+
const poadDir = path.join(box.app, 'poad');
|
|
170
|
+
const root = path.join(poadDir, 'config.toml');
|
|
171
|
+
assert.strictEqual(hasModels(root), false);
|
|
172
|
+
fs.mkdirSync(path.join(poadDir, 'transforms', 'tests'), { recursive: true });
|
|
173
|
+
fs.writeFileSync(path.join(poadDir, 'transforms', 'tests', 'x.sql'), 'select 1');
|
|
174
|
+
assert.strictEqual(hasModels(root), false);
|
|
175
|
+
fs.writeFileSync(path.join(poadDir, 'transforms', 'a.sql'), 'select 1');
|
|
176
|
+
assert.strictEqual(hasModels(root), true);
|
|
177
|
+
});
|
|
@@ -39,7 +39,8 @@ const quote = (s) => (/^[a-z_][a-z0-9_]*$/.test(s) ? s : `"${String(s).replace(/
|
|
|
39
39
|
/** Le correctif qui sert de nouveau l'objet à anon et authenticated, sous RLS */
|
|
40
40
|
function fixFor(i) {
|
|
41
41
|
const id = `${quote(i.schema)}.${quote(i.name)}`;
|
|
42
|
-
if (i.reason === 'security_definer')
|
|
42
|
+
if (i.reason === 'security_definer')
|
|
43
|
+
return `alter function ${i.signature ? (/^[^(]*\./.test(i.signature) ? i.signature : `${quote(i.schema)}.${i.signature}`) : `${id}(…)`} security invoker; or, if it needs its owner's rights: move the body to private.${quote(i.name)} (SECURITY DEFINER, revoke execute from anon, authenticated) and keep ${id} as a SECURITY INVOKER function that checks auth.uid() and calls it`;
|
|
43
44
|
if (i.reason === 'view_owner_rights') return `alter view ${id} set (security_invoker = true);`;
|
|
44
45
|
return 'read it through a SECURITY INVOKER function that returns only allowed rows, or replace it with a table and policies';
|
|
45
46
|
}
|
|
@@ -75,6 +76,56 @@ function readLocal(container) {
|
|
|
75
76
|
}
|
|
76
77
|
}
|
|
77
78
|
|
|
79
|
+
/**
|
|
80
|
+
* La même requête, par une connexion pg déjà ouverte (poad migrate, poad start, poad db reset) : les lignes de
|
|
81
|
+
* psql (lecture seule, ON_ERROR_STOP) sont retirées, :'schemas' devient un paramètre. Renvoie les objets ; null si
|
|
82
|
+
* illisible (rôles anon / authenticated absents…).
|
|
83
|
+
*/
|
|
84
|
+
async function query(client, schemas) {
|
|
85
|
+
const text = fs
|
|
86
|
+
.readFileSync(path.join(__dirname, 'api-exposure.sql'), 'utf8')
|
|
87
|
+
.split('\n')
|
|
88
|
+
.filter((l) => !/^\s*(set default_transaction_read_only|\\set)\b/.test(l))
|
|
89
|
+
.join('\n')
|
|
90
|
+
.replace(":'schemas'", '$1');
|
|
91
|
+
try {
|
|
92
|
+
const { rows } = await client.query(text, [schemas.filter((s) => /^[A-Za-z0-9_]{1,63}$/.test(s)).join(',')]);
|
|
93
|
+
const o = JSON.parse(Object.values(rows[0] || {})[0] || 'null');
|
|
94
|
+
return o && Array.isArray(o.items) ? o.items : null;
|
|
95
|
+
} catch {
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const keyOf = (i) => `${i.kind}:${i.schema}.${i.name}`;
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Après poad migrate : objets accordés à anon ou authenticated (GRANT EXECUTE / SELECT : le signal d'intention) que
|
|
104
|
+
* l'API de cet engine ne leur sert pas. before : la liste avant les migrations (null : inconnue) ; created : ceux que
|
|
105
|
+
* les migrations de ce passage ont fait apparaître. Rien à dire avant 0.64.0 (l'API les servait). Pure.
|
|
106
|
+
*/
|
|
107
|
+
function afterMigrate({ engine = null, before = null, after = null } = {}) {
|
|
108
|
+
if (!Array.isArray(after) || phaseOf(engine) === 'served') return { engine, count: 0, created: [], items: [] };
|
|
109
|
+
const had = new Set((before || []).map(keyOf));
|
|
110
|
+
const x = impact({ current: engine, target: engine, items: after });
|
|
111
|
+
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 };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** 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 [];
|
|
118
|
+
const n = `${x.count} function(s) or view(s)`;
|
|
119
|
+
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
|
+
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).`)];
|
|
121
|
+
for (const i of x.items.slice(0, max)) {
|
|
122
|
+
out.push(` ${chalk.bold(`${i.schema}.${i.name}`)}${i.created ? chalk.yellowBright(' (new)') : ''} ${chalk.grey(`(${i.why}; granted to ${i.roles.join(', ')})`)}`);
|
|
123
|
+
out.push(chalk.grey(` fix: ${i.fix}`));
|
|
124
|
+
}
|
|
125
|
+
if (x.items.length > max) out.push(chalk.grey(` … and ${x.items.length - max} more (poad migrate --json lists them all)`));
|
|
126
|
+
return out;
|
|
127
|
+
}
|
|
128
|
+
|
|
78
129
|
/** Lignes à montrer (poad deploy, poad upgrade) ; [] si rien à dire */
|
|
79
130
|
function lines(x, chalk, { max = 20 } = {}) {
|
|
80
131
|
if (!x || !x.count || !x.change || x.change === 'none') return [];
|
|
@@ -94,4 +145,4 @@ function lines(x, chalk, { max = 20 } = {}) {
|
|
|
94
145
|
return out;
|
|
95
146
|
}
|
|
96
147
|
|
|
97
|
-
module.exports = { HIDDEN_SINCE, SERVICE_ROLE_SINCE, phaseOf, fixFor, impact, readLocal, lines };
|
|
148
|
+
module.exports = { HIDDEN_SINCE, SERVICE_ROLE_SINCE, phaseOf, fixFor, impact, readLocal, lines, query, afterMigrate, migrateLines };
|
package/utils/cloud/bundle.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Archive de déploiement : le dossier poad/ en tar.gz, par liste blanche.
|
|
2
2
|
//
|
|
3
3
|
// Entrent (chemins relatifs à poad/, sans préfixe) :
|
|
4
|
-
// dossiers migrations queries auth storage functions flows api reference sources variables types
|
|
4
|
+
// dossiers migrations queries auth storage functions flows api reference sources transforms connections variables types
|
|
5
5
|
// credentials/manifest.json noms, types et usages des credentials, sans valeur
|
|
6
6
|
// (les valeurs restent dans le coffre de chaque engine)
|
|
7
7
|
// fichiers seed.sql, config.toml (sans aucune clé secrète : stripSecrets)
|
|
@@ -19,7 +19,7 @@ const fs = require('fs');
|
|
|
19
19
|
const path = require('path');
|
|
20
20
|
const zlib = require('zlib');
|
|
21
21
|
|
|
22
|
-
const DIRS = ['migrations', 'queries', 'auth', 'storage', 'functions', 'flows', 'api', 'reference', 'sources', 'connections', 'variables', 'types'];
|
|
22
|
+
const DIRS = ['migrations', 'queries', 'auth', 'storage', 'functions', 'flows', 'api', 'reference', 'sources', 'transforms', 'connections', 'variables', 'types'];
|
|
23
23
|
const FILES = ['seed.sql', 'config.toml'];
|
|
24
24
|
const NEVER = [/^secrets\.toml$/i, /^\.env$/i, /^\.env\..*/i, /^\.DS_Store$/, /^Thumbs\.db$/i, /^desktop\.ini$/i, /~$/, /\.swp$/];
|
|
25
25
|
const SKIP_DIRS = new Set(['node_modules', '.git', 'data', 'backups', '.cache']);
|
package/utils/help-details.js
CHANGED
|
@@ -328,17 +328,27 @@ const sheets = {
|
|
|
328
328
|
],
|
|
329
329
|
},
|
|
330
330
|
migrate: {
|
|
331
|
-
usage: ['poad migrate', 'poad migrate --force-reference'],
|
|
332
|
-
text: [
|
|
333
|
-
|
|
331
|
+
usage: ['poad migrate', 'poad migrate --force-reference', 'poad migrate --json', 'poad migrate list [--env <name>] [--json]', 'poad migrate pull [--env <name>] [--yes] [--dry-run] [--json]', 'poad migrate renumber <version|file> [--env <name>] [--yes] [--json]'],
|
|
332
|
+
text: [
|
|
333
|
+
'Apply pending migrations of poad/migrations and named queries of poad/queries, then the reference tables of poad/reference (the file is the source of truth).',
|
|
334
|
+
'Then warns (never blocks) about functions and views granted to anon or authenticated that the API does not serve them (403 not_exposed: SECURITY DEFINER functions, views without security_invoker, materialized views), each with its fix; the ones a migration just created also go to the log sink (poad logs cli event=api_exposure).',
|
|
335
|
+
],
|
|
336
|
+
options: [
|
|
337
|
+
['--force-reference', 'also apply a reference file that would remove many rows: an empty file for a table that has rows, or more than 20% of its rows (refused otherwise, nothing removed)'],
|
|
338
|
+
['--json', 'one JSON object: applied, failed, pending, api_exposure (items with reason, roles, fix, created), unprotected tables'],
|
|
339
|
+
['list', 'poad/migrations against an environment of poad.io (--env, else the git branch, else main; the local engine when the project is not linked): applied on both sides, pending here, missing here, written on poad.io without being applied, same version under another name, changed since applied, older than the last one applied (poad deploy refuses it); with version, name and date'],
|
|
340
|
+
['pull', 'same as poad migration pull'],
|
|
341
|
+
['renumber <version>', 'give a pending migration a version after the last one of the environment and of the folder (the file is renamed, its SQL is unchanged) when poad deploy refuses it as out of order. Refused when it is applied on any environment of poad.io; applied on the local engine only: the local history follows. Logs: poad logs cli event=migration_renumbered'],
|
|
342
|
+
],
|
|
334
343
|
},
|
|
335
344
|
migration: {
|
|
336
|
-
usage: ['poad migration new <name>', 'poad migration list'],
|
|
345
|
+
usage: ['poad migration new <name>', 'poad migration list [--env <name>]', 'poad migration pull [--env <name>] [--yes] [--dry-run] [--json]'],
|
|
337
346
|
options: [
|
|
338
347
|
['new <name>', 'create poad/migrations/<timestamp>_<name>.sql'],
|
|
339
|
-
['list', 'applied and pending migrations'],
|
|
348
|
+
['list', 'applied and pending migrations of the local engine; with --env <name>: against poad.io (as poad migrate list)'],
|
|
349
|
+
['pull', 'write into poad/migrations the migrations of a poad.io environment missing from the folder (--env, else the git branch, else main): those written there by the console, the MCP or the assistant, applied (their exact SQL from the migration history) or not yet applied. Each keeps its exact version, name and content (sha256 of the history checked); an existing file is never overwritten: a version already used here under another name is a conflict, said and left alone. Then commit them and poad deploy. Exit code 5 when one could not be pulled'],
|
|
340
350
|
],
|
|
341
|
-
notes: ['poad migrate applies the pending ones (poad start does it too).'],
|
|
351
|
+
notes: ['poad migrate applies the pending ones (poad start does it too).', 'poad deploy refuses while a migration applied on poad.io is missing from the folder: it lists them (version, name, date) and gives the poad migration pull command, --dry-run included.', 'Logs, never any SQL: poad logs cli event=migrations_pulled --env <name> (written by poad.io: versions and files).'],
|
|
342
352
|
},
|
|
343
353
|
kc: {
|
|
344
354
|
usage: ['poad kc', 'poad kc export'],
|
|
@@ -357,6 +367,24 @@ const alias = (of, name) => ({
|
|
|
357
367
|
sheets.function = alias('functions', 'function');
|
|
358
368
|
sheets.flow = alias('flows', 'flow');
|
|
359
369
|
sheets.sources = alias('source', 'sources');
|
|
370
|
+
sheets.transform = {
|
|
371
|
+
usage: ['poad transform ls [--json]', 'poad transform new <name> [--table|--view] [--from <table>]', 'poad transform check', 'poad transform run [<selector>…] [--changed] [--detach]', 'poad transform preview <name> [--limit <n>]', 'poad transform graph', 'poad transform pull <name> [--force] [--stdout] --env <name>'],
|
|
372
|
+
text: [
|
|
373
|
+
'Transformations (engine 0.72.0+): one select per file, poad/transforms/<name>.sql, with a YAML header in a comment (/* --- materialized: view|table, schema, api, lecture, depends_on, timeout --- */). poad builds it as a view (security_invoker) or a table recomputed in one transaction, in the order of their dependencies (read from the SQL: from, join; cycles refused).',
|
|
374
|
+
'The file is the declaration: the engine creates and reshapes the object, outside the migrations and "poad db diff" (marked poad:transform). Built at poad start, poad db reset and poad deploy when the file changed, or on demand. Not served by the API unless api: true.',
|
|
375
|
+
],
|
|
376
|
+
options: [
|
|
377
|
+
['ls', 'models, their last build (rows, duration, error with its line), what they read'],
|
|
378
|
+
['new <name>', 'write poad/transforms/<name>.sql with a minimal header (--table, --from <table>)'],
|
|
379
|
+
['check', 'read every model through the engine: header, query, graph, cycles; nothing is built (exit 1 if one is invalid)'],
|
|
380
|
+
['run [<selector>…]', 'build now and follow the run (all by default); name, name+ (and what reads it), +name (and what it reads); --changed: only what changed since its last build'],
|
|
381
|
+
['preview <name>', 'first rows, computed in a transaction rolled back (30 s at most)'],
|
|
382
|
+
['graph', 'lineage as text'],
|
|
383
|
+
['pull <name>', 'bring a model created in the poad.io console into poad/transforms (--env)'],
|
|
384
|
+
],
|
|
385
|
+
notes: ['Logs: poad logs transform (model=<name>, run=<id>, event=model_failed, trigger=manual|deploy|reset|start). Never a row value.'],
|
|
386
|
+
};
|
|
387
|
+
sheets.transforms = alias('transform', 'transforms');
|
|
360
388
|
sheets.relation = {
|
|
361
389
|
usage: ['poad relation ls [table] [--json]', 'poad relation add <table.column> <table.column> [--name <relation>]', 'poad relation rm <table.column> <table.column>', 'poad relation suggest <table>', 'poad relation check <table.column> <table.column>'],
|
|
362
390
|
text: [
|
package/utils/logline.js
CHANGED
|
@@ -5,8 +5,8 @@ const LEVELS = ['debug', 'info', 'warn', 'error', 'fatal'];
|
|
|
5
5
|
|
|
6
6
|
// Options de filtre → attribut de la ligne (attrs). Mêmes noms et même sens
|
|
7
7
|
// que les paramètres de /logs/v1 (services/logs/src/api.ts de l'infra).
|
|
8
|
-
const ATTR_OPTIONS = { flow: 'flow', step: 'step', function: 'function', tool: 'tool', outcome: 'outcome', provider: 'provider', model: 'model', event: 'event', table: 'table', channel: 'channel', front: 'front', page: 'page', source: 'source_name', upload: 'upload_id', bucket: 'bucket', object: 'object', trigger: 'trigger_kind', connection: 'connection', action: 'action', type: 'connection_type', host: 'host', user: 'user_id', device: 'device' };
|
|
9
|
-
const EXAMPLES = { flow: 'demo-flux', step: 'appel', function: 'demo-stats', tool: 'select_rows', outcome: 'refused', provider: 'anthropic', model: 'claude-opus-5-5', event: 'ai_default_model_changed', table: 'notes', channel: 'notes', front: 'k3x9q2m7a1bc', page: 'accueil', source: 'communes', upload: '0b8e8f7e-1b2c-4d5e-8f90-123456789abc', bucket: 'documents', object: 'releves/mars.csv', trigger: 'storage', connection: 'sncf', action: 'create_task', type: 'todoist', host: 'api.sncf.com', user: '4dbcaf19-7549-4c48-a3ad-f6bc173d3c48', device: 'alice-tel' };
|
|
8
|
+
const ATTR_OPTIONS = { flow: 'flow', step: 'step', function: 'function', tool: 'tool', outcome: 'outcome', provider: 'provider', model: 'model', event: 'event', table: 'table', channel: 'channel', front: 'front', page: 'page', source: 'source_name', upload: 'upload_id', bucket: 'bucket', object: 'object', trigger: 'trigger_kind', connection: 'connection', action: 'action', type: 'connection_type', host: 'host', user: 'user_id', device: 'device', transform: 'model' };
|
|
9
|
+
const EXAMPLES = { flow: 'demo-flux', step: 'appel', function: 'demo-stats', tool: 'select_rows', outcome: 'refused', provider: 'anthropic', model: 'claude-opus-5-5', event: 'ai_default_model_changed', table: 'notes', channel: 'notes', front: 'k3x9q2m7a1bc', page: 'accueil', source: 'communes', upload: '0b8e8f7e-1b2c-4d5e-8f90-123456789abc', bucket: 'documents', object: 'releves/mars.csv', trigger: 'storage', connection: 'sncf', action: 'create_task', type: 'todoist', host: 'api.sncf.com', user: '4dbcaf19-7549-4c48-a3ad-f6bc173d3c48', device: 'alice-tel', transform: 'ventes_par_mois' };
|
|
10
10
|
// Identifiant d'exécution (UUID) entier, ou son début : 8 caractères au moins
|
|
11
11
|
const RUN_RE = /^[0-9a-f-]{8,36}$/;
|
|
12
12
|
|
|
@@ -23,6 +23,8 @@ const attrConditions = (args = {}) => {
|
|
|
23
23
|
for (const [option, attr] of Object.entries(ATTR_OPTIONS)) {
|
|
24
24
|
const value = args[option];
|
|
25
25
|
if (value === undefined) continue;
|
|
26
|
+
// « poad logs transform » : le service, pas l'option transform=<modèle>
|
|
27
|
+
if (value === true && option === 'transform') continue;
|
|
26
28
|
if (value === true || value === '') return { error: `${option}=<${option === 'outcome' ? 'outcome' : 'name'}>: a value is expected, such as ${option}=${EXAMPLES[option]}` };
|
|
27
29
|
conditions.push([`attrs->>'${attr}' = ?`, String(value)]);
|
|
28
30
|
}
|
package/utils/migrate-run.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
// Application des migrations avec affichage, partagée par poad migrate et poad start
|
|
2
2
|
const path = require('path');
|
|
3
3
|
|
|
4
|
-
|
|
4
|
+
// report : objet rempli pour --json (applied, failed, api_exposure, unprotected, queries)
|
|
5
|
+
module.exports = async (root, config, { quietWhenNone = false, report = null, exposureList = false } = {}) => {
|
|
5
6
|
const chalk = require('chalk-v2');
|
|
6
7
|
const migrations = require('./migrations');
|
|
7
8
|
const rel = (p) => path.relative(process.cwd(), p);
|
|
@@ -16,6 +17,16 @@ module.exports = async (root, config, { quietWhenNone = false } = {}) => {
|
|
|
16
17
|
return false;
|
|
17
18
|
}
|
|
18
19
|
const { applied, failed, state } = result;
|
|
20
|
+
if (report) {
|
|
21
|
+
Object.assign(report, {
|
|
22
|
+
applied: applied.map((m) => m.file),
|
|
23
|
+
failed: failed ? { file: failed.migration.file, message: failed.message } : null,
|
|
24
|
+
pending: state.pending.filter((m) => !applied.includes(m)).map((m) => m.file),
|
|
25
|
+
unprotected: result.unprotected || [],
|
|
26
|
+
queries: result.queries || null,
|
|
27
|
+
api_exposure: result.apiExposure || null,
|
|
28
|
+
});
|
|
29
|
+
}
|
|
19
30
|
|
|
20
31
|
for (const m of state.changed) {
|
|
21
32
|
console.log(chalk.yellowBright(` ${m.file} changed after it was applied: it is not replayed. Write a new migration instead.`));
|
|
@@ -53,5 +64,8 @@ module.exports = async (root, config, { quietWhenNone = false } = {}) => {
|
|
|
53
64
|
console.log(chalk.yellowBright(` ⚠ ${t.schema}.${t.name}: row level security is off, so ${who} can read${t.anon_write ? ' and change' : ''} every row.`));
|
|
54
65
|
console.log(chalk.grey(` alter table ${t.schema}.${t.name} enable row level security; (then add policies)`));
|
|
55
66
|
}
|
|
67
|
+
// Fonctions et vues accordées à anon ou authenticated que l'API ne leur sert pas (SECURITY DEFINER, vues sans
|
|
68
|
+
// security_invoker, vues matérialisées) : même règle que poad deploy et poad upgrade (utils/api-exposure)
|
|
69
|
+
for (const l of require('./api-exposure').migrateLines(result.apiExposure, chalk, { full: exposureList || applied.length > 0 })) console.log(l);
|
|
56
70
|
return qr.errors.length === 0;
|
|
57
71
|
};
|
package/utils/migrations.js
CHANGED
|
@@ -143,6 +143,10 @@ async function migrate(root, config, { onApply } = {}) {
|
|
|
143
143
|
try {
|
|
144
144
|
await client.query('select pg_advisory_lock($1)', [LOCK_ID]);
|
|
145
145
|
const state = await status(root, client);
|
|
146
|
+
// Ce que l'API ne sert pas à anon ni à authenticated alors qu'ils en ont le droit, avant les migrations : ce
|
|
147
|
+
// qu'elles font apparaître est signalé et va au puits de logs (event=api_exposure)
|
|
148
|
+
const exposure = require('./api-exposure');
|
|
149
|
+
const before = state.pending.length ? await exposure.query(client, exposedSchemas(config)) : null;
|
|
146
150
|
for (const m of state.pending) {
|
|
147
151
|
try {
|
|
148
152
|
await client.query('begin');
|
|
@@ -164,13 +168,39 @@ async function migrate(root, config, { onApply } = {}) {
|
|
|
164
168
|
// exposées sans RLS
|
|
165
169
|
const queries = await require('./queries').sync(root, client);
|
|
166
170
|
const unprotected = await unprotectedTables(client, exposedSchemas(config));
|
|
167
|
-
|
|
171
|
+
const apiExposure = exposure.afterMigrate({ engine: config.engine, before, after: await exposure.query(client, exposedSchemas(config)) });
|
|
172
|
+
if (apiExposure.created.length) await logApiExposure(client, apiExposure, applied);
|
|
173
|
+
return { applied, failed: null, state, queries, unprotected, apiExposure };
|
|
168
174
|
} finally {
|
|
169
175
|
await client.query('select pg_advisory_unlock($1)', [LOCK_ID]).catch(() => {});
|
|
170
176
|
await client.end().catch(() => {});
|
|
171
177
|
}
|
|
172
178
|
}
|
|
173
179
|
|
|
180
|
+
/**
|
|
181
|
+
* Puits de logs (service cli, event=api_exposure) : une migration vient de créer des fonctions ou vues accordées à
|
|
182
|
+
* anon ou authenticated que l'API ne leur sert pas. Noms et raisons seulement, jamais de SQL ni de secret.
|
|
183
|
+
*/
|
|
184
|
+
async function logApiExposure(client, x, applied) {
|
|
185
|
+
const created = x.items.filter((i) => i.created);
|
|
186
|
+
const attrs = {
|
|
187
|
+
event: 'api_exposure',
|
|
188
|
+
via: 'poad migrate',
|
|
189
|
+
migrations: applied.map((m) => `poad/migrations/${m.file}`).slice(-20),
|
|
190
|
+
api_hidden: created.length,
|
|
191
|
+
functions: created.filter((i) => i.kind === 'function').length,
|
|
192
|
+
views: created.filter((i) => i.kind !== 'function').length,
|
|
193
|
+
objects: created.slice(0, 40).map((i) => `${i.schema}.${i.name}`),
|
|
194
|
+
reasons: [...new Set(created.map((i) => i.reason))],
|
|
195
|
+
roles: [...new Set(created.flatMap((i) => i.roles))],
|
|
196
|
+
granted_total: x.count,
|
|
197
|
+
engine: x.engine || null,
|
|
198
|
+
fix: created.some((i) => i.reason === 'security_definer') ? 'public SECURITY INVOKER function that checks auth.uid() and calls a SECURITY DEFINER body in private (or alter function … security invoker)' : created[0].fix,
|
|
199
|
+
};
|
|
200
|
+
const msg = `API : ${created.length} fonction(s) ou vue(s) accordée(s) à anon ou authenticated mais non servie(s) (403 not_exposed) : ${attrs.objects.slice(0, 5).join(', ')}${created.length > 5 ? '…' : ''}`;
|
|
201
|
+
await client.query("insert into _logs.entries (ts, level, service, msg, attrs) values (now(), 'warn', 'cli', $1, $2::jsonb)", [msg, JSON.stringify(attrs)]).catch(() => {});
|
|
202
|
+
}
|
|
203
|
+
|
|
174
204
|
/** Schémas servis par /rest/v1 : [data] schemas de config.toml, public par défaut */
|
|
175
205
|
const exposedSchemas = (config) => {
|
|
176
206
|
const s = config.data && config.data.schemas;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// Transformations (poad/transforms, engine 0.72.0+) : après les migrations, les tables de référence et le seed de
|
|
2
|
+
// poad start (et donc de poad db reset), le CLI demande à l'engine de construire les modèles : tous sur une base
|
|
3
|
+
// neuve (le seed vient d'arriver), sinon ceux dont le fichier a changé depuis leur dernière construction. Le
|
|
4
|
+
// passage est suivi jusqu'à sa fin ; ses journaux sont dans poad logs transform.
|
|
5
|
+
const fs = require('fs');
|
|
6
|
+
const path = require('path');
|
|
7
|
+
|
|
8
|
+
const dir = (root) => path.join(path.dirname(root), 'transforms');
|
|
9
|
+
|
|
10
|
+
/** Le dossier contient-il au moins un modèle (.sql, sous-dossiers compris, sauf tests/) ? */
|
|
11
|
+
const hasModels = (root) => {
|
|
12
|
+
const walk = (d, depth) => {
|
|
13
|
+
let entries = [];
|
|
14
|
+
try {
|
|
15
|
+
entries = fs.readdirSync(d, { withFileTypes: true });
|
|
16
|
+
} catch {
|
|
17
|
+
return false;
|
|
18
|
+
}
|
|
19
|
+
return entries.some((e) => (e.isDirectory() ? !(depth === 0 && e.name === 'tests') && !e.name.startsWith('.') && depth < 6 && walk(path.join(d, e.name), depth + 1) : e.name.endsWith('.sql')));
|
|
20
|
+
};
|
|
21
|
+
return walk(dir(root), 0);
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/** Lance le passage et le suit ; rend false si un modèle a échoué */
|
|
25
|
+
const build = async (root, config, { fresh = false, fetchImpl = fetch, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}) => {
|
|
26
|
+
const chalk = require('chalk-v2');
|
|
27
|
+
if (!hasModels(root)) return true;
|
|
28
|
+
if (!require('../project/transform').supportsTransforms(config)) {
|
|
29
|
+
console.log(chalk.yellowBright(` poad/transforms holds models, but engine ${config.engine} does not build them: "poad upgrade" (0.72.0+).`));
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
const base = `http://localhost:${config.web.port}/meta/v1/transforms`;
|
|
33
|
+
const headers = { apikey: config.auth.service, authorization: `Bearer ${config.auth.service}`, 'content-type': 'application/json', 'x-poad-by': 'cli' };
|
|
34
|
+
const call = async (method, route, body) => {
|
|
35
|
+
const res = await fetchImpl(`${base}${route}`, { method, headers, ...(body ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout(30000) });
|
|
36
|
+
const data = await res.json().catch(() => null);
|
|
37
|
+
if (!res.ok) throw new Error((data && data.error && data.error.message) || `HTTP ${res.status}`);
|
|
38
|
+
return data;
|
|
39
|
+
};
|
|
40
|
+
try {
|
|
41
|
+
const q = await call('POST', '/run', fresh ? { trigger: 'reset' } : { trigger: 'start', stale: true });
|
|
42
|
+
let runId = q.run_id;
|
|
43
|
+
for (let i = 0; !runId && i < 3600; i++) {
|
|
44
|
+
await sleep(500);
|
|
45
|
+
runId = (await call('GET', `/queue/${q.queued}`)).run_id;
|
|
46
|
+
}
|
|
47
|
+
let run;
|
|
48
|
+
for (let i = 0; i < 7200; i++) {
|
|
49
|
+
run = await call('GET', `/runs/${runId}`);
|
|
50
|
+
if (run.status !== 'running') break;
|
|
51
|
+
await sleep(500);
|
|
52
|
+
}
|
|
53
|
+
if (run.status === 'empty') return true;
|
|
54
|
+
for (const m of run.models.filter((x) => x.status !== 'ok')) console.log(chalk.yellowBright(` transform ${m.model}: ${m.status === 'skipped' ? `skipped (${m.because} failed)` : `${m.error_message}${m.error_line ? ` (line ${m.error_line})` : ''}`}`));
|
|
55
|
+
const line = `${run.ok} model(s) built${run.failed ? `, ${run.failed} failed` : ''}${run.skipped ? `, ${run.skipped} skipped` : ''} (${run.duration_ms} ms)`;
|
|
56
|
+
console.log(run.status === 'ok' ? `${chalk.greenBright('✔')} Transformations: ${chalk.grey(line)}` : chalk.yellowBright(` Transformations: ${line}: poad logs transform run=${runId.slice(0, 8)}`));
|
|
57
|
+
return run.status === 'ok';
|
|
58
|
+
} catch (err) {
|
|
59
|
+
console.log(chalk.yellowBright(` Transformations not built: ${err.message} ("poad transform run" later).`));
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
module.exports = { dir, hasModels, build };
|