poad 2.11.0 → 2.12.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/init.js +32 -47
- package/global/run.js +2 -2
- package/global/start.js +22 -1
- package/global/stop.js +2 -1
- package/package.json +3 -2
- package/project/cli.js +2 -0
- package/project/info.js +17 -1
- package/project/kc.js +1 -1
- package/project/migrate.js +16 -0
- package/project/migration.js +62 -0
- package/utils/config.js +111 -0
- package/utils/migrate-run.js +40 -0
- package/utils/migrations.js +189 -0
package/global/init.js
CHANGED
|
@@ -1,56 +1,41 @@
|
|
|
1
|
-
|
|
1
|
+
// poad init : crée le dossier poad/ du projet
|
|
2
|
+
// poad/config.toml ports, engine, services : versionné
|
|
3
|
+
// poad/secrets.toml secret JWT et clés : propre à la machine, hors git
|
|
4
|
+
// poad/migrations/ schéma de la base, appliqué par poad start / poad migrate
|
|
5
|
+
// poad/.gitignore data/ et secrets.toml
|
|
6
|
+
// poad/data/ base et fichiers du projet local, hors git
|
|
7
|
+
module.exports = async () => {
|
|
2
8
|
const path = require('path');
|
|
3
|
-
const
|
|
9
|
+
const fs = require('fs');
|
|
4
10
|
const { findFreePorts } = require('../utils/ports');
|
|
5
|
-
const { generateSecret } = require('../utils/jwtkey');
|
|
6
11
|
const json2toml = require('json2toml');
|
|
7
|
-
const fs = require('fs').promises;
|
|
8
12
|
const generateUniqueId = require('generate-unique-id');
|
|
9
13
|
const chalk = require('chalk-v2');
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
const
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
};
|
|
18
|
-
const admin = {
|
|
19
|
-
role: 'admin',
|
|
20
|
-
iss: 'poad',
|
|
21
|
-
};
|
|
22
|
-
let config = {};
|
|
23
|
-
config.project_id = path.basename(process.cwd());
|
|
24
|
-
config.project_uuid = generateUniqueId();
|
|
25
|
-
await fs.mkdir(path.join(process.cwd(), 'poad', 'data'), { recursive: true });
|
|
14
|
+
const { generateSecrets, writeSecrets, ensureGitignore } = require('../utils/config');
|
|
15
|
+
const migrations = require('../utils/migrations');
|
|
16
|
+
|
|
17
|
+
const dir = path.join(process.cwd(), 'poad');
|
|
18
|
+
const root = path.join(dir, 'config.toml');
|
|
19
|
+
if (fs.existsSync(root)) return console.log(chalk.bold('\n ✅ Your project has already been initialized'));
|
|
20
|
+
|
|
21
|
+
fs.mkdirSync(path.join(dir, 'data'), { recursive: true });
|
|
26
22
|
const ports = await findFreePorts(3);
|
|
27
|
-
config
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
port: ports[1],
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
port: ports[2],
|
|
37
|
-
};
|
|
38
|
-
const key = generateSecret();
|
|
39
|
-
config.auth = {
|
|
40
|
-
jwt_expiry: 3600,
|
|
41
|
-
secret: key,
|
|
42
|
-
anon: jwt.sign(anon, key),
|
|
43
|
-
service: jwt.sign(service, key),
|
|
44
|
-
admin: jwt.sign(admin, key),
|
|
23
|
+
const config = {
|
|
24
|
+
project_id: path.basename(process.cwd()),
|
|
25
|
+
project_uuid: generateUniqueId(),
|
|
26
|
+
engine: global.package.engine,
|
|
27
|
+
db: { port: ports[0] },
|
|
28
|
+
web: { port: ports[1] },
|
|
29
|
+
// Interface web de Mailpit (e-mails du projet local)
|
|
30
|
+
mail: { port: ports[2] },
|
|
31
|
+
auth: { jwt_expiry: 3600 },
|
|
45
32
|
};
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
chalk.bold('\n ✅ Your project has already been initialized')
|
|
53
|
-
);
|
|
54
|
-
await fs.writeFile(path.join(process.cwd(), 'poad', 'config.toml'), toml);
|
|
33
|
+
fs.writeFileSync(root, json2toml(config));
|
|
34
|
+
writeSecrets(root, generateSecrets());
|
|
35
|
+
ensureGitignore(root);
|
|
36
|
+
fs.mkdirSync(migrations.dir(root), { recursive: true });
|
|
37
|
+
fs.writeFileSync(path.join(migrations.dir(root), '.gitkeep'), '');
|
|
38
|
+
|
|
55
39
|
console.log(chalk.bold('\n ✅ Your project has been initialized'));
|
|
40
|
+
console.log(chalk.grey(' poad/config.toml and poad/migrations/ are versioned; poad/secrets.toml and poad/data/ stay on this machine.'));
|
|
56
41
|
};
|
package/global/run.js
CHANGED
|
@@ -37,8 +37,8 @@ module.exports = async (args = {}) => {
|
|
|
37
37
|
|
|
38
38
|
const root = findPoadDir(process.cwd());
|
|
39
39
|
if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
|
|
40
|
-
const readConfig = () =>
|
|
41
|
-
let config = readConfig();
|
|
40
|
+
const readConfig = () => require('../utils/config').loadConfig(root);
|
|
41
|
+
let config = require('../utils/config').readConfig(root);
|
|
42
42
|
|
|
43
43
|
if (!(await isDockerExist(config.project_uuid))) {
|
|
44
44
|
if (!all) return console.log(chalk.redBright('The project is not started: run "poad start" first (or "poad run --all").'));
|
package/global/start.js
CHANGED
|
@@ -16,7 +16,8 @@ module.exports = async (args = {}) => {
|
|
|
16
16
|
const mail = require('../utils/mail');
|
|
17
17
|
const valkey = require('../utils/valkey');
|
|
18
18
|
const root = findPoadDir(process.cwd());
|
|
19
|
-
|
|
19
|
+
if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
|
|
20
|
+
const config = require('../utils/config').readConfig(root);
|
|
20
21
|
const containerName = config.project_uuid;
|
|
21
22
|
console.log(' ');
|
|
22
23
|
const { wantsAll } = require('../utils/services');
|
|
@@ -98,5 +99,25 @@ module.exports = async (args = {}) => {
|
|
|
98
99
|
'service_role key': config.auth.service,
|
|
99
100
|
};
|
|
100
101
|
console.log(prettyoutput(info));
|
|
102
|
+
|
|
103
|
+
// Migrations en attente de poad/migrations ([db] auto_migrate = false pour
|
|
104
|
+
// les appliquer à la main avec poad migrate)
|
|
105
|
+
const migrations = require('../utils/migrations');
|
|
106
|
+
if (migrations.files(root).list.length) {
|
|
107
|
+
if (!migrations.autoMigrate(config)) {
|
|
108
|
+
console.log(chalk.grey(' auto_migrate is off: run "poad migrate" to apply pending migrations.'));
|
|
109
|
+
} else {
|
|
110
|
+
const waiting = ora('Waiting for the database to apply migrations').start();
|
|
111
|
+
const ready = (await migrations.waitForDb(config)) && (await migrations.waitForServices(config));
|
|
112
|
+
if (!ready) {
|
|
113
|
+
waiting.fail(chalk.redBright('Migrations not applied: the engine does not answer (poad migrate later).'));
|
|
114
|
+
} else {
|
|
115
|
+
waiting.stop();
|
|
116
|
+
await require('../utils/migrate-run')(root, config, { quietWhenNone: false });
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
console.log(' ');
|
|
120
|
+
}
|
|
121
|
+
|
|
101
122
|
if (all) await require('./run')({ all: true });
|
|
102
123
|
};
|
package/global/stop.js
CHANGED
|
@@ -12,7 +12,8 @@ module.exports = async (args) => {
|
|
|
12
12
|
const mail = require('../utils/mail');
|
|
13
13
|
const valkey = require('../utils/valkey');
|
|
14
14
|
const root = findPoadDir(process.cwd());
|
|
15
|
-
|
|
15
|
+
if (!root) return console.log(require('chalk-v2').redBright('You are not in a poad project directory.'));
|
|
16
|
+
const config = require('../utils/config').readConfig(root);
|
|
16
17
|
const containerName = config.project_uuid;
|
|
17
18
|
const ora = require('ora');
|
|
18
19
|
const chalk = require('chalk-v2');
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "poad",
|
|
3
|
-
"version": "2.
|
|
4
|
-
"engine": "0.7.
|
|
3
|
+
"version": "2.12.0",
|
|
4
|
+
"engine": "0.7.1",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"bin": {
|
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
"listr": "^0.14.3",
|
|
24
24
|
"log-beautify": "^1.2.0",
|
|
25
25
|
"ora": "^5.4.1",
|
|
26
|
+
"pg": "8.16.3",
|
|
26
27
|
"prettyoutput": "^1.2.0",
|
|
27
28
|
"toml": "^3.0.0"
|
|
28
29
|
}
|
package/project/cli.js
CHANGED
|
@@ -9,6 +9,8 @@
|
|
|
9
9
|
module.exports = {
|
|
10
10
|
info: `Information about your project`,
|
|
11
11
|
kc: 'Keycloak test set of the project (poad/keycloak.json; kc export saves the running realm)',
|
|
12
|
+
migrate: 'Apply pending migrations of poad/migrations (poad start does it too)',
|
|
13
|
+
migration: 'Database migrations: migration new <name>, migration list',
|
|
12
14
|
/* status: `[AI] Vérification du statut de l'environnement`,
|
|
13
15
|
gen: {
|
|
14
16
|
description: 'Génération automatique des éléments clés pour votre projet',
|
package/project/info.js
CHANGED
|
@@ -12,7 +12,8 @@ module.exports = async () => {
|
|
|
12
12
|
const { storageInfo } = require('../utils/engine');
|
|
13
13
|
const { SERVICES, containerState } = require('../utils/services');
|
|
14
14
|
const root = findPoadDir(process.cwd());
|
|
15
|
-
|
|
15
|
+
if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
|
|
16
|
+
const config = require('../utils/config').readConfig(root);
|
|
16
17
|
console.log(' ');
|
|
17
18
|
if (!(await isDockerExist(config.project_uuid))) {
|
|
18
19
|
return console.log(chalk.redBright('Container not found'));
|
|
@@ -29,6 +30,21 @@ module.exports = async () => {
|
|
|
29
30
|
'anon key': config.auth.anon,
|
|
30
31
|
'service_role key': config.auth.service,
|
|
31
32
|
};
|
|
33
|
+
// Migrations : appliquées / en attente (poad/migrations)
|
|
34
|
+
const migrations = require('../utils/migrations');
|
|
35
|
+
if (migrations.files(root).list.length) {
|
|
36
|
+
let client;
|
|
37
|
+
try {
|
|
38
|
+
client = await migrations.connect(config);
|
|
39
|
+
const st = await migrations.status(root, client);
|
|
40
|
+
const done = st.list.length - st.pending.length;
|
|
41
|
+
info.Migrations = `${done} applied${st.pending.length ? `, ${st.pending.length} pending (poad migrate)` : ''}${st.changed.length ? `, ${st.changed.length} changed after apply` : ''}`;
|
|
42
|
+
} catch {
|
|
43
|
+
info.Migrations = `${migrations.files(root).list.length} file(s), state unknown`;
|
|
44
|
+
} finally {
|
|
45
|
+
if (client) await client.end().catch(() => {});
|
|
46
|
+
}
|
|
47
|
+
}
|
|
32
48
|
console.log(prettyoutput(info));
|
|
33
49
|
|
|
34
50
|
// Panneau des services : en cours, arrêtés (configurés), ou disponibles
|
package/project/kc.js
CHANGED
|
@@ -13,7 +13,7 @@ module.exports = async (args = {}) => {
|
|
|
13
13
|
|
|
14
14
|
const root = findPoadDir(process.cwd());
|
|
15
15
|
if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
|
|
16
|
-
const config =
|
|
16
|
+
const config = require('../utils/config').readConfig(root);
|
|
17
17
|
console.log(' ');
|
|
18
18
|
|
|
19
19
|
if (args.export) {
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// poad migrate : applique les migrations en attente de poad/migrations
|
|
2
|
+
module.exports = async () => {
|
|
3
|
+
const chalk = require('chalk-v2');
|
|
4
|
+
const { findPoadDir } = require('../utils/findpoad');
|
|
5
|
+
const { isDockerExist } = require('../utils/docker');
|
|
6
|
+
const { readConfig } = require('../utils/config');
|
|
7
|
+
|
|
8
|
+
const root = findPoadDir(process.cwd());
|
|
9
|
+
if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
|
|
10
|
+
const config = readConfig(root);
|
|
11
|
+
if (!(await isDockerExist(config.project_uuid))) {
|
|
12
|
+
return console.log(chalk.redBright('The project is not started: run "poad start" (it applies pending migrations too).'));
|
|
13
|
+
}
|
|
14
|
+
const ok = await require('../utils/migrate-run')(root, config);
|
|
15
|
+
if (!ok) process.exitCode = 1;
|
|
16
|
+
};
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// poad migration new <nom> crée poad/migrations/<horodatage>_<nom>.sql
|
|
2
|
+
// poad migration list migrations appliquées et en attente
|
|
3
|
+
// (poad migrate applique celles en attente)
|
|
4
|
+
module.exports = async (args = {}) => {
|
|
5
|
+
const chalk = require('chalk-v2');
|
|
6
|
+
const path = require('path');
|
|
7
|
+
const { findPoadDir } = require('../utils/findpoad');
|
|
8
|
+
const { isDockerExist } = require('../utils/docker');
|
|
9
|
+
const { readConfig } = require('../utils/config');
|
|
10
|
+
const migrations = require('../utils/migrations');
|
|
11
|
+
|
|
12
|
+
const root = findPoadDir(process.cwd());
|
|
13
|
+
if (!root) return console.log(chalk.redBright('You are not in a poad project directory.'));
|
|
14
|
+
const words = Object.keys(args);
|
|
15
|
+
const rel = (p) => path.relative(process.cwd(), p);
|
|
16
|
+
|
|
17
|
+
if (words[0] === 'new') {
|
|
18
|
+
try {
|
|
19
|
+
const file = migrations.create(root, words.slice(1).join('_'));
|
|
20
|
+
console.log(`${chalk.greenBright('✔')} ${chalk.bold(rel(file))}`);
|
|
21
|
+
console.log(chalk.grey(' Write your SQL in it, then "poad migrate".'));
|
|
22
|
+
} catch (err) {
|
|
23
|
+
console.log(chalk.redBright(err.message));
|
|
24
|
+
}
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
if (words[0] === 'list' || !words.length) {
|
|
29
|
+
const config = readConfig(root);
|
|
30
|
+
const { list, ignored } = migrations.files(root);
|
|
31
|
+
console.log(`${chalk.bold('Migrations')} ${chalk.grey(rel(migrations.dir(root)))}`);
|
|
32
|
+
console.log(' ');
|
|
33
|
+
if (!(await isDockerExist(config.project_uuid))) {
|
|
34
|
+
for (const m of list) console.log(` ${chalk.grey('?')} ${m.file}`);
|
|
35
|
+
if (!list.length) console.log(chalk.grey(' None yet: "poad migration new <name>".'));
|
|
36
|
+
console.log(' ');
|
|
37
|
+
return console.log(chalk.grey(' The project is not started: applied state unknown.'));
|
|
38
|
+
}
|
|
39
|
+
let client;
|
|
40
|
+
try {
|
|
41
|
+
client = await migrations.connect(config);
|
|
42
|
+
const state = await migrations.status(root, client);
|
|
43
|
+
for (const m of state.list) {
|
|
44
|
+
const mark = m.changed ? chalk.yellowBright('!') : m.applied ? chalk.greenBright('✔') : chalk.cyanBright('○');
|
|
45
|
+
const note = m.changed ? chalk.yellowBright(' changed after it was applied') : m.applied ? chalk.grey(` ${new Date(m.applied).toISOString().slice(0, 16).replace('T', ' ')}`) : chalk.cyanBright(' pending');
|
|
46
|
+
console.log(` ${mark} ${m.file}${note}`);
|
|
47
|
+
}
|
|
48
|
+
for (const r of state.missing) console.log(` ${chalk.yellowBright('!')} ${r.version}_${r.name}.sql${chalk.yellowBright(' applied, file missing')}`);
|
|
49
|
+
if (!state.list.length && !state.missing.length) console.log(chalk.grey(' None yet: "poad migration new <name>".'));
|
|
50
|
+
for (const f of ignored) console.log(chalk.grey(` ${f} ignored (expected <YYYYMMDDHHMMSS>_<name>.sql)`));
|
|
51
|
+
console.log(' ');
|
|
52
|
+
if (state.pending.length) console.log(chalk.cyanBright(` ${state.pending.length} pending: "poad migrate".`));
|
|
53
|
+
} catch (err) {
|
|
54
|
+
console.log(chalk.redBright(`Cannot read the migration state: ${err.message}`));
|
|
55
|
+
} finally {
|
|
56
|
+
if (client) await client.end().catch(() => {});
|
|
57
|
+
}
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
console.log(`${chalk.bold(' Usage :')} ${chalk.cyanBright('poad migration new <name>')} | ${chalk.cyanBright('poad migration list')} | ${chalk.cyanBright('poad migrate')}`);
|
|
62
|
+
};
|
package/utils/config.js
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// Configuration d'un projet poad, en deux fichiers :
|
|
2
|
+
// poad/config.toml versionné : ports, engine, services… aucun secret
|
|
3
|
+
// poad/secrets.toml propre à la machine, hors git : secret JWT et clés
|
|
4
|
+
// (anon, service_role, admin) signées avec lui
|
|
5
|
+
//
|
|
6
|
+
// loadConfig() fusionne les deux : le reste du CLI lit config.auth.secret,
|
|
7
|
+
// config.auth.anon… comme avant. Un ancien config.toml qui contient encore
|
|
8
|
+
// les secrets est migré à la première lecture ; un projet cloné sans
|
|
9
|
+
// secrets.toml en reçoit de nouveaux.
|
|
10
|
+
const fs = require('fs');
|
|
11
|
+
const path = require('path');
|
|
12
|
+
const toml = require('toml');
|
|
13
|
+
|
|
14
|
+
const SECRET_KEYS = ['secret', 'anon', 'service', 'admin'];
|
|
15
|
+
|
|
16
|
+
const GITIGNORE = `# Généré par poad : propre à chaque machine, jamais versionné
|
|
17
|
+
data/
|
|
18
|
+
secrets.toml
|
|
19
|
+
`;
|
|
20
|
+
|
|
21
|
+
const poadDir = (root) => path.dirname(root);
|
|
22
|
+
const secretsFile = (root) => path.join(poadDir(root), 'secrets.toml');
|
|
23
|
+
|
|
24
|
+
/** Nouveau secret JWT et clés signées avec lui */
|
|
25
|
+
function generateSecrets() {
|
|
26
|
+
const jwt = require('jsonwebtoken');
|
|
27
|
+
const { generateSecret } = require('./jwtkey');
|
|
28
|
+
const secret = generateSecret();
|
|
29
|
+
return {
|
|
30
|
+
secret,
|
|
31
|
+
anon: jwt.sign({ role: 'anon', iss: 'poad' }, secret),
|
|
32
|
+
service: jwt.sign({ role: 'service_role', iss: 'poad' }, secret),
|
|
33
|
+
admin: jwt.sign({ role: 'admin', iss: 'poad' }, secret),
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function writeSecrets(root, auth) {
|
|
38
|
+
const lines = ['# Secrets du projet poad local : hors git (poad/.gitignore)', '[auth]'];
|
|
39
|
+
for (const k of SECRET_KEYS) lines.push(`${k} = ${JSON.stringify(auth[k])}`);
|
|
40
|
+
fs.writeFileSync(secretsFile(root), lines.join('\n') + '\n', { mode: 0o600 });
|
|
41
|
+
fs.chmodSync(secretsFile(root), 0o600);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** poad/.gitignore : data/ et secrets.toml (complète un fichier existant) */
|
|
45
|
+
function ensureGitignore(root) {
|
|
46
|
+
const file = path.join(poadDir(root), '.gitignore');
|
|
47
|
+
if (!fs.existsSync(file)) return fs.writeFileSync(file, GITIGNORE);
|
|
48
|
+
const text = fs.readFileSync(file, 'utf-8');
|
|
49
|
+
const missing = ['data/', 'secrets.toml'].filter((l) => !text.split(/\r?\n/).includes(l));
|
|
50
|
+
if (missing.length) fs.writeFileSync(file, `${text.replace(/\s*$/, '')}\n${missing.join('\n')}\n`);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Retire les lignes secrètes de la section [auth] du texte de config.toml */
|
|
54
|
+
function stripSecrets(text) {
|
|
55
|
+
const lines = text.split(/\r?\n/);
|
|
56
|
+
let section = '';
|
|
57
|
+
const kept = lines.filter((line) => {
|
|
58
|
+
const head = /^\s*\[([^\]]+)\]\s*$/.exec(line);
|
|
59
|
+
if (head) section = head[1].trim();
|
|
60
|
+
if (section !== 'auth') return true;
|
|
61
|
+
const key = /^\s*([A-Za-z_]+)\s*=/.exec(line);
|
|
62
|
+
return !(key && SECRET_KEYS.includes(key[1]));
|
|
63
|
+
});
|
|
64
|
+
return kept.join('\n');
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Lit config.toml et secrets.toml, migre ou crée les secrets si besoin.
|
|
69
|
+
* Renvoie la configuration fusionnée ; notices : ce qui a été fait (à afficher).
|
|
70
|
+
*/
|
|
71
|
+
function loadConfig(root, notices = []) {
|
|
72
|
+
const text = fs.readFileSync(root, 'utf-8');
|
|
73
|
+
const config = toml.parse(text);
|
|
74
|
+
const auth = config.auth || {};
|
|
75
|
+
const inline = SECRET_KEYS.filter((k) => auth[k] !== undefined);
|
|
76
|
+
let secrets = null;
|
|
77
|
+
|
|
78
|
+
if (fs.existsSync(secretsFile(root))) {
|
|
79
|
+
secrets = (toml.parse(fs.readFileSync(secretsFile(root), 'utf-8')).auth || {});
|
|
80
|
+
}
|
|
81
|
+
if (inline.length) {
|
|
82
|
+
// Ancien format : les secrets de config.toml priment (ce sont ceux que
|
|
83
|
+
// l'engine et les fronts utilisent déjà), puis on les sort du fichier.
|
|
84
|
+
secrets = { ...(secrets || {}), ...Object.fromEntries(inline.map((k) => [k, auth[k]])) };
|
|
85
|
+
writeSecrets(root, secrets);
|
|
86
|
+
fs.writeFileSync(root, stripSecrets(text));
|
|
87
|
+
ensureGitignore(root);
|
|
88
|
+
notices.push(`Secrets moved from config.toml to ${path.relative(process.cwd(), secretsFile(root))} (not versioned).`);
|
|
89
|
+
} else if (!secrets || SECRET_KEYS.some((k) => !secrets[k])) {
|
|
90
|
+
secrets = generateSecrets();
|
|
91
|
+
writeSecrets(root, secrets);
|
|
92
|
+
ensureGitignore(root);
|
|
93
|
+
notices.push(`New project secrets written to ${path.relative(process.cwd(), secretsFile(root))} (not versioned).`);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
config.auth = { ...auth, ...Object.fromEntries(SECRET_KEYS.map((k) => [k, secrets[k]])) };
|
|
97
|
+
return config;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** loadConfig + affichage des notices */
|
|
101
|
+
function readConfig(root) {
|
|
102
|
+
const notices = [];
|
|
103
|
+
const config = loadConfig(root, notices);
|
|
104
|
+
if (notices.length) {
|
|
105
|
+
const chalk = require('chalk-v2');
|
|
106
|
+
for (const n of notices) console.log(chalk.grey(` ${n}`));
|
|
107
|
+
}
|
|
108
|
+
return config;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
module.exports = { loadConfig, readConfig, generateSecrets, writeSecrets, ensureGitignore, secretsFile, stripSecrets, GITIGNORE };
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// Application des migrations avec affichage, partagée par poad migrate et poad start
|
|
2
|
+
const path = require('path');
|
|
3
|
+
|
|
4
|
+
module.exports = async (root, config, { quietWhenNone = false } = {}) => {
|
|
5
|
+
const chalk = require('chalk-v2');
|
|
6
|
+
const migrations = require('./migrations');
|
|
7
|
+
const rel = (p) => path.relative(process.cwd(), p);
|
|
8
|
+
|
|
9
|
+
let result;
|
|
10
|
+
try {
|
|
11
|
+
result = await migrations.migrate(root, config, {
|
|
12
|
+
onApply: (m) => console.log(`${chalk.greenBright('✔')} ${chalk.bold(m.file)}`),
|
|
13
|
+
});
|
|
14
|
+
} catch (err) {
|
|
15
|
+
console.log(chalk.redBright(`Migrations not applied: ${err.message}`));
|
|
16
|
+
return false;
|
|
17
|
+
}
|
|
18
|
+
const { applied, failed, state } = result;
|
|
19
|
+
|
|
20
|
+
for (const m of state.changed) {
|
|
21
|
+
console.log(chalk.yellowBright(` ${m.file} changed after it was applied: it is not replayed. Write a new migration instead.`));
|
|
22
|
+
}
|
|
23
|
+
for (const r of state.missing) {
|
|
24
|
+
console.log(chalk.yellowBright(` ${r.version}_${r.name}.sql was applied but is no longer in ${rel(migrations.dir(root))}.`));
|
|
25
|
+
}
|
|
26
|
+
for (const f of state.ignored) {
|
|
27
|
+
console.log(chalk.grey(` ${f} ignored: migration files are named <YYYYMMDDHHMMSS>_<name>.sql`));
|
|
28
|
+
}
|
|
29
|
+
if (failed) {
|
|
30
|
+
console.log(`${chalk.redBright('✖')} ${chalk.bold(failed.migration.file)}`);
|
|
31
|
+
console.log(chalk.redBright(` ${failed.message}`));
|
|
32
|
+
console.log(chalk.grey(' Rolled back: fix the file, then "poad migrate".'));
|
|
33
|
+
const left = state.pending.length - applied.length - 1;
|
|
34
|
+
if (left > 0) console.log(chalk.grey(` ${left} later migration(s) not attempted.`));
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
if (applied.length) console.log(chalk.bold(` ${applied.length} migration(s) applied.`));
|
|
38
|
+
else if (!quietWhenNone) console.log(chalk.grey(` Database up to date (${state.list.length} migration(s)).`));
|
|
39
|
+
return true;
|
|
40
|
+
};
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
// Migrations du schéma de la base : poad/migrations/<AAAAMMJJHHMMSS>_<nom>.sql
|
|
2
|
+
//
|
|
3
|
+
// - appliquées dans l'ordre des noms, chacune dans sa transaction, avec son
|
|
4
|
+
// inscription dans poad_migrations.history (version, nom, empreinte) ;
|
|
5
|
+
// - une migration déjà appliquée n'est jamais rejouée : si son fichier a
|
|
6
|
+
// changé depuis, on le signale (écrivez plutôt une nouvelle migration) ;
|
|
7
|
+
// - un verrou consultatif évite deux applications simultanées.
|
|
8
|
+
//
|
|
9
|
+
// Le CLI se connecte à la base du projet local (port [db] de config.toml).
|
|
10
|
+
const fs = require('fs');
|
|
11
|
+
const path = require('path');
|
|
12
|
+
const crypto = require('crypto');
|
|
13
|
+
|
|
14
|
+
const FILE_RE = /^(\d{14})_([A-Za-z0-9_-]+)\.sql$/;
|
|
15
|
+
const LOCK_ID = 7_340_201; // pg_advisory_lock : propre aux migrations poad
|
|
16
|
+
|
|
17
|
+
const dir = (root) => path.join(path.dirname(root), 'migrations');
|
|
18
|
+
|
|
19
|
+
const checksum = (sql) => crypto.createHash('sha256').update(sql).digest('hex');
|
|
20
|
+
|
|
21
|
+
/** Fichiers de migration du projet, triés ; les autres fichiers sont ignorés */
|
|
22
|
+
function files(root) {
|
|
23
|
+
const d = dir(root);
|
|
24
|
+
if (!fs.existsSync(d)) return { list: [], ignored: [] };
|
|
25
|
+
const names = fs.readdirSync(d).filter((f) => !f.startsWith('.')).sort();
|
|
26
|
+
const list = [];
|
|
27
|
+
const ignored = [];
|
|
28
|
+
for (const file of names) {
|
|
29
|
+
const m = FILE_RE.exec(file);
|
|
30
|
+
if (!m) {
|
|
31
|
+
ignored.push(file);
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
const sql = fs.readFileSync(path.join(d, file), 'utf-8');
|
|
35
|
+
list.push({ version: m[1], name: m[2], file, path: path.join(d, file), sql, checksum: checksum(sql) });
|
|
36
|
+
}
|
|
37
|
+
return { list, ignored };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Horodatage UTC AAAAMMJJHHMMSS */
|
|
41
|
+
function timestamp(date = new Date()) {
|
|
42
|
+
return date.toISOString().replace(/[-:T]/g, '').slice(0, 14);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Crée poad/migrations/<horodatage>_<nom>.sql ; renvoie son chemin */
|
|
46
|
+
function create(root, name) {
|
|
47
|
+
const slug = String(name || '')
|
|
48
|
+
.normalize('NFD')
|
|
49
|
+
.replace(/[̀-ͯ]/g, '')
|
|
50
|
+
.replace(/[^A-Za-z0-9_-]+/g, '_')
|
|
51
|
+
.replace(/^_+|_+$/g, '')
|
|
52
|
+
.toLowerCase();
|
|
53
|
+
if (!slug) throw new Error('a migration needs a name: poad migration new <name>');
|
|
54
|
+
fs.mkdirSync(dir(root), { recursive: true });
|
|
55
|
+
let version = timestamp();
|
|
56
|
+
// Deux migrations créées dans la même seconde : la seconde passe après
|
|
57
|
+
while (files(root).list.some((m) => m.version === version)) version = String(Number(version) + 1);
|
|
58
|
+
const file = path.join(dir(root), `${version}_${slug}.sql`);
|
|
59
|
+
fs.writeFileSync(
|
|
60
|
+
file,
|
|
61
|
+
`-- ${slug}\n-- Appliquée une seule fois, dans une transaction, par "poad migrate" (ou poad start).\n-- Une fois appliquée, ne la modifiez plus : écrivez une nouvelle migration.\n\n`
|
|
62
|
+
);
|
|
63
|
+
return file;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function connect(config) {
|
|
67
|
+
const { Client } = require('pg');
|
|
68
|
+
const client = new Client({
|
|
69
|
+
host: '127.0.0.1',
|
|
70
|
+
port: Number(config.db.port),
|
|
71
|
+
user: 'postgres',
|
|
72
|
+
password: 'postgres',
|
|
73
|
+
database: 'postgres',
|
|
74
|
+
connectionTimeoutMillis: 5000,
|
|
75
|
+
application_name: 'poad-cli',
|
|
76
|
+
});
|
|
77
|
+
await client.connect();
|
|
78
|
+
client.on('error', () => {}); // fermeture de la connexion par le serveur
|
|
79
|
+
return client;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function ensureHistory(client) {
|
|
83
|
+
await client.query(`
|
|
84
|
+
create schema if not exists poad_migrations;
|
|
85
|
+
create table if not exists poad_migrations.history (
|
|
86
|
+
version text primary key,
|
|
87
|
+
name text not null,
|
|
88
|
+
checksum text not null,
|
|
89
|
+
applied_at timestamptz not null default now()
|
|
90
|
+
);
|
|
91
|
+
revoke all on schema poad_migrations from public;
|
|
92
|
+
`);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** État : appliquées, en attente, modifiées après application, absentes du dossier */
|
|
96
|
+
async function status(root, client) {
|
|
97
|
+
const { list, ignored } = files(root);
|
|
98
|
+
await ensureHistory(client);
|
|
99
|
+
const { rows } = await client.query('select version, name, checksum, applied_at from poad_migrations.history order by version');
|
|
100
|
+
const applied = new Map(rows.map((r) => [r.version, r]));
|
|
101
|
+
const local = new Set(list.map((m) => m.version));
|
|
102
|
+
return {
|
|
103
|
+
list: list.map((m) => {
|
|
104
|
+
const row = applied.get(m.version);
|
|
105
|
+
return { ...m, applied: row ? row.applied_at : null, changed: Boolean(row && row.checksum !== m.checksum) };
|
|
106
|
+
}),
|
|
107
|
+
pending: list.filter((m) => !applied.has(m.version)),
|
|
108
|
+
changed: list.filter((m) => applied.has(m.version) && applied.get(m.version).checksum !== m.checksum),
|
|
109
|
+
missing: rows.filter((r) => !local.has(r.version)),
|
|
110
|
+
ignored,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Ligne et colonne d'une position (1-based) dans le texte */
|
|
115
|
+
function lineOf(sql, position) {
|
|
116
|
+
const before = sql.slice(0, Math.max(0, Number(position) - 1));
|
|
117
|
+
const line = before.split('\n').length;
|
|
118
|
+
return line;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Applique les migrations en attente. S'arrête à la première erreur (sa
|
|
123
|
+
* transaction est annulée, les suivantes ne sont pas tentées).
|
|
124
|
+
* Renvoie { applied: [...], failed: { migration, message } | null, state }.
|
|
125
|
+
*/
|
|
126
|
+
async function migrate(root, config, { onApply } = {}) {
|
|
127
|
+
const client = await connect(config);
|
|
128
|
+
const applied = [];
|
|
129
|
+
try {
|
|
130
|
+
await client.query('select pg_advisory_lock($1)', [LOCK_ID]);
|
|
131
|
+
const state = await status(root, client);
|
|
132
|
+
for (const m of state.pending) {
|
|
133
|
+
try {
|
|
134
|
+
await client.query('begin');
|
|
135
|
+
await client.query(m.sql);
|
|
136
|
+
await client.query('insert into poad_migrations.history (version, name, checksum) values ($1, $2, $3)', [m.version, m.name, m.checksum]);
|
|
137
|
+
await client.query('commit');
|
|
138
|
+
applied.push(m);
|
|
139
|
+
if (onApply) onApply(m);
|
|
140
|
+
} catch (err) {
|
|
141
|
+
await client.query('rollback').catch(() => {});
|
|
142
|
+
const where = err.position ? ` (line ${lineOf(m.sql, err.position)})` : '';
|
|
143
|
+
return { applied, failed: { migration: m, message: `${err.message}${where}` }, state };
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return { applied, failed: null, state };
|
|
147
|
+
} finally {
|
|
148
|
+
await client.query('select pg_advisory_unlock($1)', [LOCK_ID]).catch(() => {});
|
|
149
|
+
await client.end().catch(() => {});
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Attend que la base accepte les connexions (démarrage de l'engine) */
|
|
154
|
+
async function waitForDb(config, seconds = 90) {
|
|
155
|
+
for (let i = 0; i < seconds; i++) {
|
|
156
|
+
try {
|
|
157
|
+
const client = await connect(config);
|
|
158
|
+
await client.query('select 1');
|
|
159
|
+
await client.end();
|
|
160
|
+
return true;
|
|
161
|
+
} catch {
|
|
162
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return false;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Attend que les services de l'engine aient créé leurs schémas (auth,
|
|
170
|
+
* storage) : une migration peut y écrire (buckets, politiques).
|
|
171
|
+
*/
|
|
172
|
+
async function waitForServices(config, seconds = 90) {
|
|
173
|
+
const base = `http://localhost:${config.web.port}`;
|
|
174
|
+
const ok = (url, headers) => fetch(url, { headers }).then((r) => r.ok, () => false);
|
|
175
|
+
for (let i = 0; i < seconds; i++) {
|
|
176
|
+
const [auth, storage] = await Promise.all([
|
|
177
|
+
ok(`${base}/auth/v1/settings`, { apikey: config.auth.anon }),
|
|
178
|
+
ok(`${base}/storage/v1/status`, { apikey: config.auth.anon }),
|
|
179
|
+
]);
|
|
180
|
+
if (auth && storage) return true;
|
|
181
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
182
|
+
}
|
|
183
|
+
return false;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Les migrations s'appliquent-elles à poad start ? ([db] auto_migrate, vrai par défaut) */
|
|
187
|
+
const autoMigrate = (config) => !(config.db && config.db.auto_migrate === false);
|
|
188
|
+
|
|
189
|
+
module.exports = { dir, files, create, status, migrate, connect, waitForDb, waitForServices, autoMigrate, timestamp, FILE_RE };
|