poad 2.14.1 → 2.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/global/run.js +1 -0
- package/global/start.js +18 -2
- package/package.json +2 -2
- package/project/cli.js +6 -1
- package/project/gen/index.js +8 -0
- package/project/gen/types.js +44 -0
- package/project/logs.js +129 -0
- package/utils/engine.js +15 -1
- package/utils/logs.js +77 -0
- package/utils/mail.js +1 -0
- package/utils/migrate-run.js +18 -1
- package/utils/migrations.js +32 -2
- package/utils/queries.js +164 -0
- package/utils/report.js +2 -1
- package/utils/valkey.js +1 -0
package/global/run.js
CHANGED
|
@@ -140,6 +140,7 @@ module.exports = async (args = {}) => {
|
|
|
140
140
|
PortBindings: { '8080/tcp': [{ HostPort: String(port) }] },
|
|
141
141
|
Binds: [`${importDir}:/opt/keycloak/data/import:ro`],
|
|
142
142
|
AutoRemove: true,
|
|
143
|
+
...require('../utils/logs').containerLogConfig(config),
|
|
143
144
|
},
|
|
144
145
|
});
|
|
145
146
|
await container.start();
|
package/global/start.js
CHANGED
|
@@ -58,9 +58,13 @@ module.exports = async (args = {}) => {
|
|
|
58
58
|
const progress = ora('Starting containers').start();
|
|
59
59
|
try {
|
|
60
60
|
// Réseau du projet : l'engine y joint Mailpit (« mail ») et Keycloak
|
|
61
|
+
// Collecteur des journaux : port GELF de l'engine, choisi avant de lancer
|
|
62
|
+
// Mailpit (qui y envoie ses journaux)
|
|
63
|
+
const logs = require('../utils/logs');
|
|
64
|
+
await logs.ensureGelfPort(root, config);
|
|
61
65
|
await mail.ensureNetwork(docker, config);
|
|
62
|
-
if (mailpit) await mail.startMailpit(docker, config);
|
|
63
66
|
const net = mail.onNetwork(config, 'engine');
|
|
67
|
+
const gelf = logs.engineBindings(config);
|
|
64
68
|
const container = await docker.createContainer({
|
|
65
69
|
name: containerName,
|
|
66
70
|
Image: image,
|
|
@@ -71,6 +75,9 @@ module.exports = async (args = {}) => {
|
|
|
71
75
|
// http://localhost:* (désactivé par défaut, hors du CLI)
|
|
72
76
|
'OMNEEDIA_AUTH_ALLOW_LOCALHOST_REDIRECTS=true',
|
|
73
77
|
'DATA_VOLUME_MOUNTPOINT=/data',
|
|
78
|
+
// Projet local : journaux détaillés (SQL, requêtes lentes dès 100 ms).
|
|
79
|
+
// Sans cette variable, l'engine démarre en production.
|
|
80
|
+
'POAD_MODE=development',
|
|
74
81
|
'POSTGRES_PASSWORD=postgres',
|
|
75
82
|
'ADMIN_API_KEY=' + config.auth.admin,
|
|
76
83
|
'JWT_SECRET=' + config.auth.secret,
|
|
@@ -79,11 +86,13 @@ module.exports = async (args = {}) => {
|
|
|
79
86
|
...mail.smtpEnv(config),
|
|
80
87
|
...valkey.engineEnv(config),
|
|
81
88
|
],
|
|
89
|
+
ExposedPorts: { '5432/tcp': {}, '8000/tcp': {}, ...gelf.exposed },
|
|
82
90
|
HostConfig: {
|
|
83
91
|
NetworkMode: net.NetworkMode,
|
|
84
92
|
PortBindings: {
|
|
85
93
|
'5432/tcp': [{ HostPort: config.db.port.toString() }],
|
|
86
94
|
'8000/tcp': [{ HostPort: config.web.port.toString() }],
|
|
95
|
+
...gelf.bindings,
|
|
87
96
|
},
|
|
88
97
|
Binds: [path.dirname(root) + '/data:/data'],
|
|
89
98
|
// Services lancés sur la machine : joignables depuis l'engine, y
|
|
@@ -94,6 +103,12 @@ module.exports = async (args = {}) => {
|
|
|
94
103
|
NetworkingConfig: net.endpoint,
|
|
95
104
|
});
|
|
96
105
|
await container.start();
|
|
106
|
+
// Mailpit après le collecteur de l'engine, pour qu'il reçoive ses journaux
|
|
107
|
+
// (GELF) dès le départ. L'engine ne joint Mailpit qu'à l'envoi d'un e-mail.
|
|
108
|
+
if (mailpit) {
|
|
109
|
+
await logs.waitForCollector(container);
|
|
110
|
+
await mail.startMailpit(docker, config);
|
|
111
|
+
}
|
|
97
112
|
} catch (err) {
|
|
98
113
|
progress.fail(chalk.redBright(`Error: containers failed to start: ${err.message}`));
|
|
99
114
|
await mail.stopMailpit(docker, config);
|
|
@@ -105,7 +120,8 @@ module.exports = async (args = {}) => {
|
|
|
105
120
|
// toujours), puis seed.sql sur une base neuve
|
|
106
121
|
const migrations = require('../utils/migrations');
|
|
107
122
|
const { seedFile, runSeed } = require('../utils/seed');
|
|
108
|
-
|
|
123
|
+
// Migrations, ou requêtes nommées (poad/queries) à synchroniser
|
|
124
|
+
const hasMigrations = migrations.files(root).list.length > 0 || require('../utils/queries').read(root).queries.length > 0;
|
|
109
125
|
const migrate = hasMigrations && (migrations.autoMigrate(config) || args.forceMigrate);
|
|
110
126
|
const seed = fresh && fsSync.existsSync(seedFile(root));
|
|
111
127
|
if (hasMigrations && !migrate) console.log(chalk.grey(' auto_migrate is off: run "poad migrate" to apply pending migrations.'));
|
package/package.json
CHANGED
package/project/cli.js
CHANGED
|
@@ -16,7 +16,12 @@ module.exports = {
|
|
|
16
16
|
seed: 'Apply poad/seed.sql (development data)',
|
|
17
17
|
},
|
|
18
18
|
upgrade: 'Upgrade the engine of the project (backs up poad/ first): upgrade, upgrade to=<version>, upgrade --rollback, upgrade --list (--yes outside a terminal)',
|
|
19
|
-
|
|
19
|
+
logs: 'Unified logs of the project: logs [service…] level=warn since=15m request=<id> grep=<text> limit=100 -f --json',
|
|
20
|
+
gen: {
|
|
21
|
+
description: 'Generators: gen types (TypeScript types of the database)',
|
|
22
|
+
types: 'TypeScript types of the database for createClient<Database>() (out=src/types/database.ts)',
|
|
23
|
+
},
|
|
24
|
+
migrate: 'Apply pending migrations of poad/migrations and named queries of poad/queries (poad start does it too)',
|
|
20
25
|
migration: 'Database migrations: migration new <name>, migration list',
|
|
21
26
|
/* status: `[AI] Vérification du statut de l'environnement`,
|
|
22
27
|
gen: {
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// poad gen : aide des générateurs
|
|
2
|
+
module.exports = async () => {
|
|
3
|
+
const chalk = require('chalk-v2');
|
|
4
|
+
console.log(`${chalk.bold(' Usage :')}`);
|
|
5
|
+
console.log(' ');
|
|
6
|
+
console.log(` ${chalk.cyanBright('poad gen types')} TypeScript types of the database for createClient<Database>() (out=src/types/database.ts)`);
|
|
7
|
+
console.log(' ');
|
|
8
|
+
};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// poad gen types : types TypeScript du schéma de la base, pour
|
|
2
|
+
// createClient<Database>(url, anonKey). Le service data du projet les produit
|
|
3
|
+
// à partir de ce qu'il lit dans Postgres (/rest/v1/types.ts) ; le CLI les
|
|
4
|
+
// écrit dans src/types/database.ts (ou out=<chemin>).
|
|
5
|
+
// À relancer après une migration qui change les tables ou les fonctions.
|
|
6
|
+
module.exports = async (args = {}) => {
|
|
7
|
+
const chalk = require('chalk-v2');
|
|
8
|
+
const fs = require('fs');
|
|
9
|
+
const path = require('path');
|
|
10
|
+
const { findPoadDir } = require('../../utils/findpoad');
|
|
11
|
+
const { isDockerExist } = require('../../utils/docker');
|
|
12
|
+
const { readConfig } = require('../../utils/config');
|
|
13
|
+
const { supportsData } = require('../../utils/engine');
|
|
14
|
+
|
|
15
|
+
const root = findPoadDir(process.cwd());
|
|
16
|
+
if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
|
|
17
|
+
const config = readConfig(root);
|
|
18
|
+
if (!supportsData(config)) {
|
|
19
|
+
process.exitCode = 1;
|
|
20
|
+
return console.log(chalk.redBright(`Engine ${config.engine} has no data service: "poad upgrade" to 0.8.0 or later.`));
|
|
21
|
+
}
|
|
22
|
+
if (!(await isDockerExist(config.project_uuid))) {
|
|
23
|
+
process.exitCode = 1;
|
|
24
|
+
return console.log(chalk.redBright('The project is not started: run "poad start".'));
|
|
25
|
+
}
|
|
26
|
+
const out = path.resolve(path.dirname(path.dirname(root)), String(args.out || path.join('src', 'types', 'database.ts')));
|
|
27
|
+
const url = `http://localhost:${config.web.port}/rest/v1/types.ts`;
|
|
28
|
+
let text;
|
|
29
|
+
try {
|
|
30
|
+
const res = await fetch(url, { headers: { apikey: config.auth.service, authorization: `Bearer ${config.auth.service}` } });
|
|
31
|
+
text = await res.text();
|
|
32
|
+
if (!res.ok) throw new Error(`HTTP ${res.status} ${text.slice(0, 200)}`);
|
|
33
|
+
} catch (err) {
|
|
34
|
+
process.exitCode = 1;
|
|
35
|
+
return console.log(chalk.redBright(`Types not generated: ${err.message}`));
|
|
36
|
+
}
|
|
37
|
+
fs.mkdirSync(path.dirname(out), { recursive: true });
|
|
38
|
+
const before = fs.existsSync(out) ? fs.readFileSync(out, 'utf-8') : null;
|
|
39
|
+
fs.writeFileSync(out, text);
|
|
40
|
+
const tables = (text.match(/^ {6}\w+: \{$/gm) || []).length;
|
|
41
|
+
const shown = path.relative(process.cwd(), out).startsWith('..') ? out : path.relative(process.cwd(), out);
|
|
42
|
+
console.log(`${chalk.greenBright('✔')} ${chalk.bold(shown)}${before === text ? chalk.grey(' (unchanged)') : ''}`);
|
|
43
|
+
console.log(chalk.grey(` ${tables} table(s). Use it with: createClient<Database>(url, anonKey)`));
|
|
44
|
+
};
|
package/project/logs.js
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// poad logs : les journaux unifiés du projet (schéma _logs, engine 0.8.1+).
|
|
2
|
+
// poad logs les 100 dernières lignes, tous services
|
|
3
|
+
// poad logs data auth seulement ces services (gateway, data, auth,
|
|
4
|
+
// storage, meta, postgres, logs, engine,
|
|
5
|
+
// mailpit, keycloak, valkey)
|
|
6
|
+
// poad logs level=warn warn, error et fatal
|
|
7
|
+
// poad logs since=15m depuis 15 minutes (s, m, h, d)
|
|
8
|
+
// poad logs request=6f1c… tout le chemin d'une requête (début de l'id suffit)
|
|
9
|
+
// poad logs grep=timeout messages qui contiennent ce texte
|
|
10
|
+
// poad logs limit=500 nombre de lignes (100 par défaut)
|
|
11
|
+
// poad logs -f | --follow suivi en direct
|
|
12
|
+
// poad logs --json une ligne JSON par entrée (pour jq)
|
|
13
|
+
module.exports = async (args = {}) => {
|
|
14
|
+
const chalk = require('chalk-v2');
|
|
15
|
+
const { findPoadDir } = require('../utils/findpoad');
|
|
16
|
+
const { isDockerExist } = require('../utils/docker');
|
|
17
|
+
const { readConfig } = require('../utils/config');
|
|
18
|
+
const { supportsLogs } = require('../utils/logs');
|
|
19
|
+
const { connect } = require('../utils/migrations');
|
|
20
|
+
|
|
21
|
+
const root = findPoadDir(process.cwd());
|
|
22
|
+
if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
|
|
23
|
+
const config = readConfig(root);
|
|
24
|
+
if (!supportsLogs(config)) {
|
|
25
|
+
process.exitCode = 1;
|
|
26
|
+
return console.log(chalk.redBright(`Engine ${config.engine} has no log collector: "poad upgrade" to 0.8.1 or later (meanwhile: docker logs ${config.project_uuid}).`));
|
|
27
|
+
}
|
|
28
|
+
if (!(await isDockerExist(config.project_uuid))) {
|
|
29
|
+
process.exitCode = 1;
|
|
30
|
+
return console.log(chalk.redBright('The project is not started: run "poad start".'));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const OPTIONS = ['level', 'since', 'request', 'grep', 'limit', '-f', '--follow', 'follow', '--json', 'json'];
|
|
34
|
+
const flag = (...names) => names.some((n) => args[n] === true);
|
|
35
|
+
const follow = flag('-f', '--follow', 'follow');
|
|
36
|
+
const asJson = flag('--json', 'json');
|
|
37
|
+
const services = Object.keys(args).filter((k) => args[k] === true && !OPTIONS.includes(k) && !k.startsWith('-'));
|
|
38
|
+
const LEVELS = ['debug', 'info', 'warn', 'error', 'fatal'];
|
|
39
|
+
const level = args.level ? String(args.level).toLowerCase() : null;
|
|
40
|
+
if (level && !LEVELS.includes(level)) {
|
|
41
|
+
process.exitCode = 1;
|
|
42
|
+
return console.log(chalk.redBright(`level=${level}: debug, info, warn, error or fatal`));
|
|
43
|
+
}
|
|
44
|
+
let since = null;
|
|
45
|
+
if (args.since) {
|
|
46
|
+
const m = /^(\d+)\s*(s|m|h|d)$/.exec(String(args.since));
|
|
47
|
+
if (!m) {
|
|
48
|
+
process.exitCode = 1;
|
|
49
|
+
return console.log(chalk.redBright(`since=${args.since}: a duration such as 30s, 15m, 2h, 1d`));
|
|
50
|
+
}
|
|
51
|
+
since = `${m[1]} ${{ s: 'seconds', m: 'minutes', h: 'hours', d: 'days' }[m[2]]}`;
|
|
52
|
+
}
|
|
53
|
+
const limit = Math.min(Number(args.limit) || (args.request ? 1000 : 100), 10000);
|
|
54
|
+
|
|
55
|
+
// Conditions communes à la première lecture et au suivi
|
|
56
|
+
const where = [];
|
|
57
|
+
const values = [];
|
|
58
|
+
const add = (sql, v) => {
|
|
59
|
+
values.push(v);
|
|
60
|
+
where.push(sql.replace('?', `$${values.length}`));
|
|
61
|
+
};
|
|
62
|
+
if (services.length) add('service = any(?)', services);
|
|
63
|
+
if (level) add('level = any(?)', LEVELS.slice(LEVELS.indexOf(level)));
|
|
64
|
+
if (since) add("ts >= now() - ?::interval", since);
|
|
65
|
+
if (args.request) add('request_id like ?', `${String(args.request).replace(/[%_]/g, '')}%`);
|
|
66
|
+
if (args.grep) add('msg ilike ?', `%${String(args.grep).replace(/[%_\\]/g, (c) => `\\${c}`)}%`);
|
|
67
|
+
|
|
68
|
+
const COLORS = ['cyanBright', 'magentaBright', 'blueBright', 'greenBright', 'yellow', 'cyan', 'magenta', 'blue'];
|
|
69
|
+
const colorOf = (s) => COLORS[[...s].reduce((h, c) => (h * 31 + c.charCodeAt(0)) >>> 0, 7) % COLORS.length];
|
|
70
|
+
const LEVEL_STYLE = { debug: chalk.grey, info: chalk.green, warn: chalk.yellowBright, error: chalk.redBright, fatal: chalk.bgRed.white };
|
|
71
|
+
const width = 8;
|
|
72
|
+
|
|
73
|
+
const print = (r) => {
|
|
74
|
+
if (asJson) return console.log(JSON.stringify(r));
|
|
75
|
+
const a = r.attrs || {};
|
|
76
|
+
const time = new Date(r.ts).toISOString().slice(11, 23);
|
|
77
|
+
const svc = chalk[colorOf(r.service)](r.service.padEnd(width).slice(0, width));
|
|
78
|
+
const lvl = (LEVEL_STYLE[r.level] || chalk.white)(r.level.padEnd(5));
|
|
79
|
+
const extra = [];
|
|
80
|
+
// La durée d'une requête lente de Postgres est déjà dans son message
|
|
81
|
+
if (a.duration_ms !== undefined && r.service !== 'postgres') extra.push(`${a.duration_ms} ms`);
|
|
82
|
+
if (a.role) extra.push(a.role);
|
|
83
|
+
if (a.error_code || a.error) extra.push(chalk.yellow([a.error_code, a.error].filter(Boolean).join(': ')));
|
|
84
|
+
if (a.err && a.err.message) extra.push(chalk.redBright(a.err.message));
|
|
85
|
+
if (a.sql) extra.push(chalk.grey(String(a.sql).replace(/\s+/g, ' ').slice(0, 160)));
|
|
86
|
+
if (a.statement && r.service === 'postgres') extra.push(chalk.grey(String(a.statement).replace(/\s+/g, ' ').slice(0, 160)));
|
|
87
|
+
const req = r.request_id ? chalk.grey(` ·${r.request_id.slice(0, 8)}`) : '';
|
|
88
|
+
console.log(`${chalk.grey(time)} ${svc} ${lvl} ${r.msg}${extra.length ? ' ' + extra.join(' ') : ''}${req}`);
|
|
89
|
+
if (a.err && a.err.stack && r.level !== 'debug') console.log(chalk.grey(String(a.err.stack).split('\n').slice(1, 6).join('\n')));
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
const client = await connect(config);
|
|
93
|
+
const cond = (extra) => [...where, ...(extra ? [extra] : [])].join(' and ') || 'true';
|
|
94
|
+
let lastId = 0;
|
|
95
|
+
try {
|
|
96
|
+
const first = await client.query(
|
|
97
|
+
`select id, ts, level, service, msg, request_id, attrs from _logs.entries where ${cond()} order by ts desc, id desc limit ${limit}`,
|
|
98
|
+
values,
|
|
99
|
+
);
|
|
100
|
+
for (const r of first.rows.reverse()) {
|
|
101
|
+
print(r);
|
|
102
|
+
lastId = Math.max(lastId, Number(r.id));
|
|
103
|
+
}
|
|
104
|
+
if (!follow) {
|
|
105
|
+
if (!first.rows.length && !asJson) console.log(chalk.grey(' No log line matches.'));
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
if (!lastId) lastId = Number((await client.query('select coalesce(max(id), 0) as id from _logs.entries')).rows[0].id);
|
|
109
|
+
// Suivi : les lignes arrivent par lots du collecteur (toutes les 500 ms)
|
|
110
|
+
let stopped = false;
|
|
111
|
+
process.on('SIGINT', () => (stopped = true));
|
|
112
|
+
while (!stopped) {
|
|
113
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
114
|
+
const next = await client.query(
|
|
115
|
+
`select id, ts, level, service, msg, request_id, attrs from _logs.entries where ${cond(`id > ${lastId}`)} order by id limit 2000`,
|
|
116
|
+
values,
|
|
117
|
+
);
|
|
118
|
+
for (const r of next.rows) {
|
|
119
|
+
print(r);
|
|
120
|
+
lastId = Math.max(lastId, Number(r.id));
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
} catch (err) {
|
|
124
|
+
process.exitCode = 1;
|
|
125
|
+
console.log(chalk.redBright(`Logs not readable: ${err.message}`));
|
|
126
|
+
} finally {
|
|
127
|
+
await client.end().catch(() => {});
|
|
128
|
+
}
|
|
129
|
+
};
|
package/utils/engine.js
CHANGED
|
@@ -23,7 +23,21 @@ const storageInfo = (config) => {
|
|
|
23
23
|
};
|
|
24
24
|
};
|
|
25
25
|
|
|
26
|
-
|
|
26
|
+
// Engine 0.8.0 et plus : service data (/rest/v1) avec sa documentation
|
|
27
|
+
const supportsData = (config) => {
|
|
28
|
+
const [major, minor] = String(config.engine || '').split('.').map(Number);
|
|
29
|
+
return major > 0 || minor >= 8;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const dataInfo = (config) =>
|
|
33
|
+
supportsData(config)
|
|
34
|
+
? {
|
|
35
|
+
'REST URL': `http://localhost:${config.web.port}/rest/v1`,
|
|
36
|
+
'API docs': `http://localhost:${config.web.port}/rest/v1/docs#apikey=${config.auth.anon}`,
|
|
37
|
+
}
|
|
38
|
+
: {};
|
|
39
|
+
|
|
40
|
+
module.exports = { usesMinio, storageInfo, supportsData, dataInfo };
|
|
27
41
|
|
|
28
42
|
// Projet resté sur un engine plus ancien que celui du CLI : propose de mettre
|
|
29
43
|
// à jour `engine` dans config.toml. La mise à jour migre poad/data : le projet
|
package/utils/logs.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// Journaux unifiés (engine 0.8.1 et plus, docs/logging.md de l'infra) :
|
|
2
|
+
// - l'engine publie le port GELF de son collecteur (12201/udp) sur
|
|
3
|
+
// 127.0.0.1:<[logs] gelf_port de config.toml> ;
|
|
4
|
+
// - Mailpit, Keycloak et Valkey y envoient leurs journaux (pilote gelf de
|
|
5
|
+
// Docker) ; docker logs continue de fonctionner (copie locale de Docker).
|
|
6
|
+
// Si l'engine est arrêté, leurs messages sont perdus pour _logs (UDP), mais
|
|
7
|
+
// restent dans docker logs.
|
|
8
|
+
const { setKeys } = require('./tomlfile');
|
|
9
|
+
|
|
10
|
+
const GELF_CONTAINER_PORT = '12201/udp';
|
|
11
|
+
|
|
12
|
+
const supportsLogs = (config) => {
|
|
13
|
+
const [major, minor, patch] = String(config.engine || '').split('.').map(Number);
|
|
14
|
+
return major > 0 || minor > 8 || (minor === 8 && patch >= 1);
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const gelfPort = (config) => Number(config.logs && config.logs.gelf_port) || null;
|
|
18
|
+
|
|
19
|
+
/** Port GELF du projet, choisi et écrit dans config.toml au premier besoin */
|
|
20
|
+
async function ensureGelfPort(root, config) {
|
|
21
|
+
if (!supportsLogs(config)) return null;
|
|
22
|
+
const existing = gelfPort(config);
|
|
23
|
+
if (existing) return existing;
|
|
24
|
+
const { findFreePorts } = require('./ports');
|
|
25
|
+
const [port] = await findFreePorts(1);
|
|
26
|
+
setKeys(root, 'logs', { gelf_port: port });
|
|
27
|
+
config.logs = { ...(config.logs || {}), gelf_port: port };
|
|
28
|
+
return port;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Ports de l'engine pour le collecteur : ExposedPorts et PortBindings à fusionner */
|
|
32
|
+
const engineBindings = (config) => {
|
|
33
|
+
const port = supportsLogs(config) && gelfPort(config);
|
|
34
|
+
if (!port) return { exposed: {}, bindings: {} };
|
|
35
|
+
return {
|
|
36
|
+
exposed: { [GELF_CONTAINER_PORT]: {} },
|
|
37
|
+
bindings: { [GELF_CONTAINER_PORT]: [{ HostIp: '127.0.0.1', HostPort: String(port) }] },
|
|
38
|
+
};
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/** HostConfig.LogConfig d'un conteneur du CLI (rien si l'engine n'a pas de collecteur) */
|
|
42
|
+
const containerLogConfig = (config) => {
|
|
43
|
+
const port = supportsLogs(config) && gelfPort(config);
|
|
44
|
+
if (!port) return {};
|
|
45
|
+
return {
|
|
46
|
+
LogConfig: {
|
|
47
|
+
Type: 'gelf',
|
|
48
|
+
Config: {
|
|
49
|
+
'gelf-address': `udp://127.0.0.1:${port}`,
|
|
50
|
+
'gelf-compression-type': 'none',
|
|
51
|
+
// Ne jamais bloquer le conteneur si le collecteur ne répond pas
|
|
52
|
+
mode: 'non-blocking',
|
|
53
|
+
},
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Attend (5 s au plus) que le collecteur de l'engine écoute : sa ligne de
|
|
60
|
+
* démarrage apparaît dans les journaux du conteneur. Sans collecteur (engine
|
|
61
|
+
* plus ancien), rend la main après le délai.
|
|
62
|
+
*/
|
|
63
|
+
async function waitForCollector(container, timeoutMs = 5000) {
|
|
64
|
+
const end = Date.now() + timeoutMs;
|
|
65
|
+
while (Date.now() < end) {
|
|
66
|
+
try {
|
|
67
|
+
const buf = await container.logs({ stdout: true, stderr: true, tail: 200 });
|
|
68
|
+
if (String(buf).includes('"service":"logs"')) return true;
|
|
69
|
+
} catch {
|
|
70
|
+
/* conteneur pas encore prêt */
|
|
71
|
+
}
|
|
72
|
+
await new Promise((r) => setTimeout(r, 100));
|
|
73
|
+
}
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
module.exports = { supportsLogs, gelfPort, ensureGelfPort, engineBindings, containerLogConfig, waitForCollector };
|
package/utils/mail.js
CHANGED
|
@@ -73,6 +73,7 @@ const startMailpit = async (docker, config) => {
|
|
|
73
73
|
NetworkMode: net.NetworkMode,
|
|
74
74
|
PortBindings: { '8025/tcp': [{ HostPort: String(mailPort(config)) }] },
|
|
75
75
|
AutoRemove: true,
|
|
76
|
+
...require('./logs').containerLogConfig(config),
|
|
76
77
|
},
|
|
77
78
|
NetworkingConfig: net.endpoint,
|
|
78
79
|
});
|
package/utils/migrate-run.js
CHANGED
|
@@ -36,5 +36,22 @@ module.exports = async (root, config, { quietWhenNone = false } = {}) => {
|
|
|
36
36
|
}
|
|
37
37
|
if (applied.length) console.log(chalk.bold(` ${applied.length} migration(s) applied.`));
|
|
38
38
|
else if (!quietWhenNone) console.log(chalk.grey(` Database up to date (${state.list.length} migration(s)).`));
|
|
39
|
-
|
|
39
|
+
|
|
40
|
+
// Requêtes nommées (poad/queries) : des fonctions queries.<nom>
|
|
41
|
+
const qr = result.queries || { applied: [], dropped: [], errors: [] };
|
|
42
|
+
const qdir = rel(require('./queries').dir(root));
|
|
43
|
+
if (qr.applied.length) console.log(`${chalk.greenBright('✔')} ${chalk.bold(`${qdir}`)} ${chalk.grey(`: ${qr.applied.join(', ')}`)}`);
|
|
44
|
+
if (qr.dropped.length) console.log(chalk.grey(` Named queries removed (no file any more): ${qr.dropped.join(', ')}`));
|
|
45
|
+
for (const e of qr.errors) {
|
|
46
|
+
console.log(`${chalk.redBright('✖')} ${chalk.bold(`${qdir}/${e.file}`)}`);
|
|
47
|
+
console.log(chalk.redBright(` ${e.message}`));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Tables exposées sans RLS : lisibles par tous avec la clé anon
|
|
51
|
+
for (const t of result.unprotected || []) {
|
|
52
|
+
const who = [t.anon && 'anon', t.authenticated && 'authenticated'].filter(Boolean).join(' and ');
|
|
53
|
+
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
|
+
console.log(chalk.grey(` alter table ${t.schema}.${t.name} enable row level security; (then add policies)`));
|
|
55
|
+
}
|
|
56
|
+
return qr.errors.length === 0;
|
|
40
57
|
};
|
package/utils/migrations.js
CHANGED
|
@@ -143,13 +143,43 @@ async function migrate(root, config, { onApply } = {}) {
|
|
|
143
143
|
return { applied, failed: { migration: m, message: `${err.message}${where}` }, state };
|
|
144
144
|
}
|
|
145
145
|
}
|
|
146
|
-
|
|
146
|
+
// Après les migrations : requêtes nommées (poad/queries), puis les tables
|
|
147
|
+
// exposées sans RLS
|
|
148
|
+
const queries = await require('./queries').sync(root, client);
|
|
149
|
+
const unprotected = await unprotectedTables(client, exposedSchemas(config));
|
|
150
|
+
return { applied, failed: null, state, queries, unprotected };
|
|
147
151
|
} finally {
|
|
148
152
|
await client.query('select pg_advisory_unlock($1)', [LOCK_ID]).catch(() => {});
|
|
149
153
|
await client.end().catch(() => {});
|
|
150
154
|
}
|
|
151
155
|
}
|
|
152
156
|
|
|
157
|
+
/** Schémas servis par /rest/v1 : [data] schemas de config.toml, public par défaut */
|
|
158
|
+
const exposedSchemas = (config) => {
|
|
159
|
+
const s = config.data && config.data.schemas;
|
|
160
|
+
return Array.isArray(s) && s.length ? s.map(String) : ['public'];
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Tables exposées sans RLS qu'anon ou authenticated peuvent lire : par défaut,
|
|
165
|
+
* le schéma public donne tous les droits à ces rôles, donc une table sans RLS
|
|
166
|
+
* est lisible (et modifiable) par n'importe qui avec la clé anon.
|
|
167
|
+
*/
|
|
168
|
+
async function unprotectedTables(client, schemas) {
|
|
169
|
+
const { rows } = await client.query(
|
|
170
|
+
`select n.nspname as schema, c.relname as name,
|
|
171
|
+
has_table_privilege('anon', c.oid, 'select') as anon,
|
|
172
|
+
has_table_privilege('authenticated', c.oid, 'select') as authenticated,
|
|
173
|
+
has_table_privilege('anon', c.oid, 'insert') or has_table_privilege('anon', c.oid, 'update') or has_table_privilege('anon', c.oid, 'delete') as anon_write
|
|
174
|
+
from pg_class c join pg_namespace n on n.oid = c.relnamespace
|
|
175
|
+
where n.nspname = any($1) and c.relkind in ('r', 'p') and not c.relrowsecurity
|
|
176
|
+
and (has_table_privilege('anon', c.oid, 'select') or has_table_privilege('authenticated', c.oid, 'select'))
|
|
177
|
+
order by 1, 2`,
|
|
178
|
+
[schemas],
|
|
179
|
+
);
|
|
180
|
+
return rows;
|
|
181
|
+
}
|
|
182
|
+
|
|
153
183
|
/** Attend que la base accepte les connexions (démarrage de l'engine) */
|
|
154
184
|
async function waitForDb(config, seconds = 90) {
|
|
155
185
|
for (let i = 0; i < seconds; i++) {
|
|
@@ -186,4 +216,4 @@ async function waitForServices(config, seconds = 90) {
|
|
|
186
216
|
/** Les migrations s'appliquent-elles à poad start ? ([db] auto_migrate, vrai par défaut) */
|
|
187
217
|
const autoMigrate = (config) => !(config.db && config.db.auto_migrate === false);
|
|
188
218
|
|
|
189
|
-
module.exports = { dir, files, create, status, migrate, connect, waitForDb, waitForServices, autoMigrate, timestamp, FILE_RE };
|
|
219
|
+
module.exports = { dir, files, create, status, migrate, connect, waitForDb, waitForServices, autoMigrate, timestamp, exposedSchemas, unprotectedTables, FILE_RE };
|
package/utils/queries.js
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
// Requêtes SQL nommées : poad/queries/<nom>.sql devient la fonction
|
|
2
|
+
// queries.<nom>, appelée depuis le front avec poad.query('<nom>', { … }).
|
|
3
|
+
// Le SQL reste côté serveur, le front n'envoie que des arguments : c'est la
|
|
4
|
+
// façon sûre d'écrire du SQL pour le navigateur. La fonction s'exécute avec
|
|
5
|
+
// les droits de l'appelant (security invoker) : le RLS s'applique.
|
|
6
|
+
//
|
|
7
|
+
// -- @description Les auteurs qui ont le plus de notes
|
|
8
|
+
// -- @param limit int = 10
|
|
9
|
+
// -- @param since timestamptz
|
|
10
|
+
// select p.name, count(*) as notes
|
|
11
|
+
// from profiles p join notes n on n.author_id = p.id
|
|
12
|
+
// where n.created_at >= :since
|
|
13
|
+
// group by p.name order by notes desc limit :limit
|
|
14
|
+
//
|
|
15
|
+
// Les colonnes du résultat (et leurs types) sont demandées à Postgres. Les
|
|
16
|
+
// fonctions sont recréées à chaque poad migrate (et poad start) ; celles dont
|
|
17
|
+
// le fichier a disparu sont supprimées. `-- @volatile` permet une requête qui
|
|
18
|
+
// écrit (par défaut : stable, lecture seule).
|
|
19
|
+
const fs = require('fs');
|
|
20
|
+
const path = require('path');
|
|
21
|
+
|
|
22
|
+
const NAME_RE = /^[a-z_][a-z0-9_]*$/;
|
|
23
|
+
const SCHEMA = 'queries';
|
|
24
|
+
|
|
25
|
+
const dir = (root) => path.join(path.dirname(root), 'queries');
|
|
26
|
+
|
|
27
|
+
const q = (id) => `"${id.replace(/"/g, '""')}"`;
|
|
28
|
+
|
|
29
|
+
/** Lit et analyse les fichiers ; renvoie { queries, errors } */
|
|
30
|
+
function read(root) {
|
|
31
|
+
const d = dir(root);
|
|
32
|
+
if (!fs.existsSync(d)) return { queries: [], errors: [] };
|
|
33
|
+
const queries = [];
|
|
34
|
+
const errors = [];
|
|
35
|
+
for (const file of fs.readdirSync(d).filter((f) => f.endsWith('.sql')).sort()) {
|
|
36
|
+
const name = file.replace(/\.sql$/, '');
|
|
37
|
+
try {
|
|
38
|
+
if (!NAME_RE.test(name)) throw new Error('nom invalide : lettres minuscules, chiffres et _');
|
|
39
|
+
queries.push(parse(name, fs.readFileSync(path.join(d, file), 'utf-8')));
|
|
40
|
+
} catch (err) {
|
|
41
|
+
errors.push({ file, message: err.message });
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return { queries, errors };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function parse(name, text) {
|
|
48
|
+
const params = [];
|
|
49
|
+
let description = null;
|
|
50
|
+
let volatile = false;
|
|
51
|
+
for (const line of text.split(/\r?\n/)) {
|
|
52
|
+
const m = /^\s*--\s*@(\w+)\s*(.*)$/.exec(line);
|
|
53
|
+
if (!m) continue;
|
|
54
|
+
const [, tag, rest] = m;
|
|
55
|
+
if (tag === 'description') description = rest.trim();
|
|
56
|
+
else if (tag === 'volatile') volatile = true;
|
|
57
|
+
else if (tag === 'param') {
|
|
58
|
+
const p = /^([a-z_][a-z0-9_]*)\s+([^=]+?)\s*(?:=\s*(.+))?$/i.exec(rest.trim());
|
|
59
|
+
if (!p) throw new Error(`@param illisible : « ${rest.trim()} » (attendu : @param nom type [= défaut])`);
|
|
60
|
+
if (params.some((x) => x.name === p[1])) throw new Error(`@param ${p[1]} déclaré deux fois`);
|
|
61
|
+
params.push({ name: p[1], type: p[2].trim(), default: p[3] === undefined ? null : p[3].trim() });
|
|
62
|
+
} else throw new Error(`annotation inconnue : @${tag} (@description, @param, @volatile)`);
|
|
63
|
+
}
|
|
64
|
+
// Les paramètres sans valeur par défaut d'abord (contrainte de Postgres)
|
|
65
|
+
const firstDefault = params.findIndex((p) => p.default !== null);
|
|
66
|
+
if (firstDefault >= 0 && params.slice(firstDefault).some((p) => p.default === null))
|
|
67
|
+
throw new Error('les @param avec une valeur par défaut doivent venir après les autres');
|
|
68
|
+
|
|
69
|
+
// :nom → $n, hors chaînes, identifiants entre guillemets, commentaires et ::casts
|
|
70
|
+
const used = new Set();
|
|
71
|
+
let body = '';
|
|
72
|
+
let i = 0;
|
|
73
|
+
while (i < text.length) {
|
|
74
|
+
const c = text[i];
|
|
75
|
+
const rest = text.slice(i);
|
|
76
|
+
let m;
|
|
77
|
+
if ((m = /^--[^\n]*/.exec(rest)) || (m = /^\/\*[\s\S]*?\*\//.exec(rest)) || (m = /^'(?:[^']|'')*'/.exec(rest)) || (m = /^"(?:[^"]|"")*"/.exec(rest)) || (m = /^\$([a-z_]*)\$[\s\S]*?\$\1\$/i.exec(rest))) {
|
|
78
|
+
body += m[0].startsWith('--') ? '' : m[0];
|
|
79
|
+
i += m[0].length;
|
|
80
|
+
} else if ((m = /^::/.exec(rest))) {
|
|
81
|
+
body += '::';
|
|
82
|
+
i += 2;
|
|
83
|
+
} else if ((m = /^:([a-z_][a-z0-9_]*)/i.exec(rest))) {
|
|
84
|
+
const idx = params.findIndex((p) => p.name === m[1]);
|
|
85
|
+
if (idx < 0) throw new Error(`:${m[1]} utilisé sans @param ${m[1]}`);
|
|
86
|
+
used.add(m[1]);
|
|
87
|
+
body += `$${idx + 1}`;
|
|
88
|
+
i += m[0].length;
|
|
89
|
+
} else {
|
|
90
|
+
body += c;
|
|
91
|
+
i += 1;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
body = body.trim().replace(/;\s*$/, '');
|
|
95
|
+
if (!body) throw new Error('requête vide');
|
|
96
|
+
if (/;/.test(body.replace(/'(?:[^']|'')*'/g, ''))) throw new Error('une seule instruction SQL par fichier');
|
|
97
|
+
const unused = params.filter((p) => !used.has(p.name)).map((p) => p.name);
|
|
98
|
+
if (unused.length) throw new Error(`@param déclaré mais pas utilisé : ${unused.join(', ')}`);
|
|
99
|
+
return { name, params, description, volatile, body };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Crée ou recrée les fonctions de queries, supprime celles sans fichier.
|
|
104
|
+
* Renvoie { applied: [noms], dropped: [noms], errors: [{ file, message }] }.
|
|
105
|
+
*/
|
|
106
|
+
async function sync(root, client) {
|
|
107
|
+
const { queries, errors } = read(root);
|
|
108
|
+
const applied = [];
|
|
109
|
+
const existing = (
|
|
110
|
+
await client.query(`select p.proname as name, pg_get_function_identity_arguments(p.oid) as args from pg_proc p join pg_namespace n on n.oid = p.pronamespace where n.nspname = $1`, [SCHEMA])
|
|
111
|
+
).rows;
|
|
112
|
+
if (!queries.length && !existing.length) return { applied, dropped: [], errors };
|
|
113
|
+
|
|
114
|
+
await client.query(`create schema if not exists ${SCHEMA}`);
|
|
115
|
+
await client.query(`grant usage on schema ${SCHEMA} to anon, authenticated, service_role`);
|
|
116
|
+
|
|
117
|
+
for (const query of queries) {
|
|
118
|
+
try {
|
|
119
|
+
// Colonnes du résultat, telles que Postgres les voit
|
|
120
|
+
await client.query('begin');
|
|
121
|
+
const probe = `select * from (${query.body}) r limit 0`;
|
|
122
|
+
// Sonde sans valeurs : chaque paramètre devient un null de son type
|
|
123
|
+
const typed = query.params.map((p) => `(null::${p.type})`);
|
|
124
|
+
const res = await client.query({ text: probe.replace(/\$(\d+)/g, (_, n) => typed[Number(n) - 1]), values: [], rowMode: 'array' });
|
|
125
|
+
await client.query('rollback');
|
|
126
|
+
if (!res.fields.length) throw new Error('la requête ne renvoie aucune colonne');
|
|
127
|
+
const oids = res.fields.map((f) => f.dataTypeID);
|
|
128
|
+
const types = (await client.query('select oid, format_type(oid, null) as t from pg_type where oid = any($1)', [oids])).rows;
|
|
129
|
+
const typeOf = new Map(types.map((r) => [r.oid, r.t]));
|
|
130
|
+
const seen = new Set();
|
|
131
|
+
const columns = res.fields.map((f) => {
|
|
132
|
+
if (seen.has(f.name)) throw new Error(`colonne ${f.name} en double dans le résultat : donnez-lui un alias`);
|
|
133
|
+
seen.add(f.name);
|
|
134
|
+
return `${q(f.name)} ${typeOf.get(f.dataTypeID) || 'text'}`;
|
|
135
|
+
});
|
|
136
|
+
const args = query.params.map((p) => `${q(p.name)} ${p.type}${p.default !== null ? ` default ${p.default}` : ''}`).join(', ');
|
|
137
|
+
const fn = `${SCHEMA}.${q(query.name)}`;
|
|
138
|
+
await client.query('begin');
|
|
139
|
+
for (const e of existing.filter((x) => x.name === query.name)) await client.query(`drop function ${fn}(${e.args})`);
|
|
140
|
+
await client.query(
|
|
141
|
+
`create function ${fn}(${args}) returns table (${columns.join(', ')}) language sql ${query.volatile ? 'volatile' : 'stable'} security invoker as $poad$\n${query.body}\n$poad$`,
|
|
142
|
+
);
|
|
143
|
+
if (query.description) await client.query(`comment on function ${fn}(${query.params.map((p) => p.type).join(', ')}) is ${client.escapeLiteral(query.description)}`);
|
|
144
|
+
await client.query(`grant execute on function ${fn}(${query.params.map((p) => p.type).join(', ')}) to anon, authenticated, service_role`);
|
|
145
|
+
await client.query('commit');
|
|
146
|
+
applied.push(query.name);
|
|
147
|
+
} catch (err) {
|
|
148
|
+
await client.query('rollback').catch(() => {});
|
|
149
|
+
errors.push({ file: `${query.name}.sql`, message: err.message });
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// Fichiers disparus : fonctions supprimées (celles en erreur sont gardées)
|
|
154
|
+
const keep = new Set([...queries.map((x) => x.name), ...errors.map((e) => e.file.replace(/\.sql$/, ''))]);
|
|
155
|
+
const dropped = [];
|
|
156
|
+
for (const e of existing) {
|
|
157
|
+
if (keep.has(e.name)) continue;
|
|
158
|
+
await client.query(`drop function if exists ${SCHEMA}.${q(e.name)}(${e.args})`);
|
|
159
|
+
dropped.push(e.name);
|
|
160
|
+
}
|
|
161
|
+
return { applied, dropped, errors };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
module.exports = { dir, read, parse, sync, SCHEMA };
|
package/utils/report.js
CHANGED
|
@@ -23,7 +23,7 @@ async function migrationsLine(root, config) {
|
|
|
23
23
|
async function printProject(root, config) {
|
|
24
24
|
const chalk = require('chalk-v2');
|
|
25
25
|
const prettyoutput = require('prettyoutput');
|
|
26
|
-
const { storageInfo } = require('./engine');
|
|
26
|
+
const { storageInfo, dataInfo } = require('./engine');
|
|
27
27
|
const mail = require('./mail');
|
|
28
28
|
console.log(chalk.bold('POAD project'));
|
|
29
29
|
console.log(' ');
|
|
@@ -32,6 +32,7 @@ async function printProject(root, config) {
|
|
|
32
32
|
'API URL': `http://localhost:${config.web.port}`,
|
|
33
33
|
'DB URL': `postgres://postgres:postgres@localhost:${config.db.port}/postgres`,
|
|
34
34
|
...storageInfo(config),
|
|
35
|
+
...dataInfo(config),
|
|
35
36
|
...(mail.usesMailpit(config) ? {} : { SMTP: `${config.smtp.host}:${config.smtp.port || 587}` }),
|
|
36
37
|
'JWT secret': `${config.auth.secret}`,
|
|
37
38
|
'anon key': config.auth.anon,
|
package/utils/valkey.js
CHANGED
|
@@ -54,6 +54,7 @@ const containerOptions = (config, root, net) => ({
|
|
|
54
54
|
PortBindings: { '6379/tcp': [{ HostIp: '127.0.0.1', HostPort: String(config.valkey.port) }] },
|
|
55
55
|
Binds: [`${dataDir(root)}:/data`],
|
|
56
56
|
AutoRemove: true,
|
|
57
|
+
...require('./logs').containerLogConfig(config),
|
|
57
58
|
},
|
|
58
59
|
});
|
|
59
60
|
|