poad 2.75.0 → 2.75.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/global/start.js +14 -0
- package/package.json +1 -1
- package/project/db/reset.js +35 -0
- package/project/deploy.js +1 -1
- package/project/functions.js +4 -47
- package/project/ref/push.js +16 -2
- package/test/db-reset.test.js +20 -0
- package/test/function-types.test.js +51 -0
- package/test/reference-reload.test.js +113 -0
- package/utils/cloud/api.js +4 -2
- package/utils/function-types.js +98 -0
- package/utils/reference-store.js +7 -0
package/global/start.js
CHANGED
|
@@ -43,12 +43,26 @@ module.exports = async (args = {}) => {
|
|
|
43
43
|
const all = wantsAll(args);
|
|
44
44
|
const bare = Boolean(args.bare || args['--bare']);
|
|
45
45
|
|
|
46
|
+
// Types des fonctions (poad/functions/.poad/types) : rafraîchis à chaque démarrage, pour suivre le runtime
|
|
47
|
+
// de l'engine lancé (sinon un projet garde ceux de l'engine où il les a posés). Seulement si le projet a
|
|
48
|
+
// des fonctions ou des types déjà posés ; silencieux si rien ne change.
|
|
49
|
+
const refreshFunctionTypes = async () => {
|
|
50
|
+
const fsSync = require('fs');
|
|
51
|
+
const dir = path.join(path.dirname(root), 'functions');
|
|
52
|
+
const has = fsSync.existsSync(path.join(dir, '.poad', 'types')) || (fsSync.existsSync(dir) && fsSync.readdirSync(dir).some((n) => fsSync.existsSync(path.join(dir, n, 'index.ts')) || fsSync.existsSync(path.join(dir, n, 'index.js'))));
|
|
53
|
+
if (!has) return;
|
|
54
|
+
const types = require('../utils/function-types');
|
|
55
|
+
const done = types.write(dir, await types.fetchBundle(require('../utils/config').loadConfig(root), 30));
|
|
56
|
+
if (done && done.changed) console.log(chalk.grey(` Editor types of the functions refreshed: ${path.relative(process.cwd(), path.join(dir, '.poad', 'types')) || '.'} (${done.count} files).`));
|
|
57
|
+
};
|
|
58
|
+
|
|
46
59
|
// Services optionnels à lancer, puis l'état complet du projet
|
|
47
60
|
const finish = async () => {
|
|
48
61
|
const targets = bare ? [] : all ? SERVICES.filter((s) => s.optional && s.configured(config)) : autostartServices(config, root);
|
|
49
62
|
// Groupe « Services » de la console (Mailpit, Keycloak) : ports de cette machine, après leur réattribution
|
|
50
63
|
require('../utils/console-services').write(root);
|
|
51
64
|
if (targets.length) await require('./run')({ services: targets.map((s) => s.id), quiet: true });
|
|
65
|
+
await refreshFunctionTypes();
|
|
52
66
|
console.log(' ');
|
|
53
67
|
await require('../utils/report').printReport(root, require('../utils/config').loadConfig(root), { justStarted: true });
|
|
54
68
|
};
|
package/package.json
CHANGED
package/project/db/reset.js
CHANGED
|
@@ -89,4 +89,39 @@ module.exports = async (args = {}) => {
|
|
|
89
89
|
console.log(' ');
|
|
90
90
|
await require('../../utils/report').printServices(root, readConfig(root));
|
|
91
91
|
}
|
|
92
|
+
// Sources « Fichier envoyé » : leur fichier n'était que dans le stockage local, effacé avec lui. Le bucket
|
|
93
|
+
// poad-sources revient (meta), la déclaration aussi, mais le fichier ne revient que par un nouvel envoi.
|
|
94
|
+
const uploads = uploadSources(path.dirname(root));
|
|
95
|
+
if (uploads.length) {
|
|
96
|
+
console.log(' ');
|
|
97
|
+
console.log(chalk.yellowBright(` ${uploads.length} source(s) loaded from a sent file: the file was erased with the local storage, send it again to reload the table:`));
|
|
98
|
+
for (const u of uploads) console.log(chalk.grey(` poad source import <file> --table ${u.table}`));
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
/** Sources « Fichier envoyé » déclarées dans poad/sources (origin.kind: upload) : { name, table } */
|
|
103
|
+
const uploadSources = (root) => {
|
|
104
|
+
const fs = require('fs');
|
|
105
|
+
const path = require('path');
|
|
106
|
+
const dir = path.join(root, 'sources');
|
|
107
|
+
let files = [];
|
|
108
|
+
try {
|
|
109
|
+
files = fs.readdirSync(dir).filter((f) => /\.ya?ml$/.test(f));
|
|
110
|
+
} catch {
|
|
111
|
+
return [];
|
|
112
|
+
}
|
|
113
|
+
const out = [];
|
|
114
|
+
for (const f of files) {
|
|
115
|
+
let text = '';
|
|
116
|
+
try {
|
|
117
|
+
text = fs.readFileSync(path.join(dir, f), 'utf8');
|
|
118
|
+
} catch {
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
if (!/^\s+kind:\s*['"]?upload['"]?\s*(#.*)?$/m.test(text) && !/kind:\s*['"]?upload['"]?\s*[,}]/.test(text)) continue;
|
|
122
|
+
const table = (/^table:\s*['"]?(?:public\.)?([A-Za-z0-9_]+)/m.exec(text) || [])[1] || f.replace(/\.ya?ml$/, '');
|
|
123
|
+
out.push({ name: f.replace(/\.ya?ml$/, ''), table });
|
|
124
|
+
}
|
|
125
|
+
return out;
|
|
92
126
|
};
|
|
127
|
+
module.exports.uploadSources = uploadSources;
|
package/project/deploy.js
CHANGED
|
@@ -148,7 +148,7 @@ module.exports = (args, raw) =>
|
|
|
148
148
|
if (b.deps && b.deps.packages.length) out.log(chalk.grey(` npm packages of the functions: ${b.deps.packages.join(', ')} (${b.deps.files} file(s) of poad/functions/node_modules)`));
|
|
149
149
|
for (const m of (b.deps && b.deps.missing) || []) out.log(chalk.yellowBright(` ⚠ ${m.from} imports "${m.spec}", not installed in poad/functions/node_modules: run "npm install ${m.spec}" in poad/functions, or this function will not build on poad.io.`));
|
|
150
150
|
if (b.deps && b.deps.outside.length) out.log(chalk.yellowBright(` ⚠ ${b.deps.outside.join(', ')}: installed above poad/functions, not sent. Install in poad/functions (npm install there).`));
|
|
151
|
-
for (const f of large) out.log(chalk.grey(` ${f.rel} (${kb(f.size)}): too large for git: reference store, sent
|
|
151
|
+
for (const f of large) out.log(chalk.grey(` ${f.rel} (${kb(f.size)}): too large for git: reference store, sent only if it changed (sha256), loaded if not yet loaded in ${env.branch}`));
|
|
152
152
|
for (const f of ignored.tracked) out.log(chalk.yellowBright(` ⚠ poad/${f.rel} is tracked by git although it is too large: git rm --cached poad/${f.rel}`));
|
|
153
153
|
|
|
154
154
|
if (env.production && !dryRun) {
|
package/project/functions.js
CHANGED
|
@@ -25,29 +25,6 @@ export default {
|
|
|
25
25
|
};
|
|
26
26
|
`;
|
|
27
27
|
|
|
28
|
-
// tsconfig.json de poad/functions : API web (celles de workerd) et @poadio/*
|
|
29
|
-
// relié aux types déposés par l'engine, pour l'autocomplétion sans node_modules
|
|
30
|
-
const TSCONFIG = `{
|
|
31
|
-
"compilerOptions": {
|
|
32
|
-
"target": "ES2022",
|
|
33
|
-
"module": "ESNext",
|
|
34
|
-
"moduleResolution": "bundler",
|
|
35
|
-
"lib": ["ES2022", "WebWorker"],
|
|
36
|
-
"types": [],
|
|
37
|
-
"strict": true,
|
|
38
|
-
"noEmit": true,
|
|
39
|
-
"skipLibCheck": true,
|
|
40
|
-
"allowImportingTsExtensions": true,
|
|
41
|
-
"paths": {
|
|
42
|
-
"@poadio/*": ["./.poad/types/@poadio/*/index.d.ts"]
|
|
43
|
-
}
|
|
44
|
-
},
|
|
45
|
-
"include": ["**/*.ts", "**/*.tsx"],
|
|
46
|
-
"exclude": ["node_modules"]
|
|
47
|
-
}
|
|
48
|
-
`;
|
|
49
|
-
const TYPE_FILE_RE = /^@poadio\/[a-z][a-z0-9-]*(\/[A-Za-z0-9_-]+)*\/[A-Za-z0-9_.-]+\.d\.ts$/;
|
|
50
|
-
|
|
51
28
|
module.exports = async (args = {}) => {
|
|
52
29
|
const chalk = require('chalk-v2');
|
|
53
30
|
const fs = require('fs');
|
|
@@ -62,34 +39,14 @@ module.exports = async (args = {}) => {
|
|
|
62
39
|
const rel = (p) => path.relative(process.cwd(), p) || p;
|
|
63
40
|
const words = Object.keys(args);
|
|
64
41
|
|
|
65
|
-
// Types pour l'éditeur : lus sur l'engine lancé (accordés à son
|
|
42
|
+
// Types pour l'éditeur : lus sur l'engine lancé (accordés à son runtime)
|
|
66
43
|
// et déposés dans poad/functions/.poad/types. Renvoie le nombre de fichiers, ou null.
|
|
67
44
|
const installTypes = async () => {
|
|
68
45
|
const config = readConfig(root);
|
|
69
46
|
if (!(await isDockerExist(config.project_uuid))) return null;
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
if (!res.ok) return null;
|
|
74
|
-
bundle = await res.json();
|
|
75
|
-
} catch {
|
|
76
|
-
return null;
|
|
77
|
-
}
|
|
78
|
-
const files = Object.entries((bundle && bundle.files) || {}).filter(([name, text]) => TYPE_FILE_RE.test(name) && !name.includes('..') && typeof text === 'string');
|
|
79
|
-
if (!files.length) return null;
|
|
80
|
-
const typesDir = path.join(dir, '.poad', 'types');
|
|
81
|
-
fs.rmSync(typesDir, { recursive: true, force: true });
|
|
82
|
-
for (const [name, text] of files) {
|
|
83
|
-
const target = path.join(typesDir, name);
|
|
84
|
-
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
85
|
-
fs.writeFileSync(target, text);
|
|
86
|
-
}
|
|
87
|
-
// L'ancien fichier de types (client en « any ») masquerait les nouveaux
|
|
88
|
-
const old = path.join(dir, 'poad-functions.d.ts');
|
|
89
|
-
if (fs.existsSync(old) && fs.readFileSync(old, 'utf8').startsWith('// Généré par poad')) fs.rmSync(old);
|
|
90
|
-
const tsconfig = path.join(dir, 'tsconfig.json');
|
|
91
|
-
if (!fs.existsSync(tsconfig)) fs.writeFileSync(tsconfig, TSCONFIG);
|
|
92
|
-
return files.length;
|
|
47
|
+
const types = require('../utils/function-types');
|
|
48
|
+
const done = types.write(dir, await types.fetchBundle(config));
|
|
49
|
+
return done ? done.count : null;
|
|
93
50
|
};
|
|
94
51
|
const reportTypes = (count) => {
|
|
95
52
|
if (count) console.log(chalk.grey(` Editor types: ${rel(path.join(dir, '.poad', 'types'))} (${count} files) and ${rel(path.join(dir, 'tsconfig.json'))}. No install needed.`));
|
package/project/ref/push.js
CHANGED
|
@@ -88,9 +88,21 @@ async function startAndWait(id, branch, targets, opts, out) {
|
|
|
88
88
|
try {
|
|
89
89
|
started = await api.call('POST', `v1/projects/${api.enc(id)}/seeds/load`, { body: { branch, targets }, what: 'reference load' });
|
|
90
90
|
} catch (e) {
|
|
91
|
-
|
|
91
|
+
// Place insuffisante, même table par table : rien n'est lancé ; chaque table dite (refusée, en attente)
|
|
92
|
+
if (e.code !== 'seed_no_space') throw e;
|
|
93
|
+
const d = e.details || {};
|
|
94
|
+
const tables = Array.isArray(d.tables) && d.tables.length ? d.tables : targets.map((t) => ({ target: t, status: 'refused' }));
|
|
95
|
+
out.log(`${chalk.redBright('✖')} Reference load refused on ${branch}: ${d.message || e.message}`);
|
|
96
|
+
for (const t of tables) {
|
|
97
|
+
if (t.status === 'refused') out.log(` ${chalk.redBright('✖')} ${t.target}: refused, not enough room${t.need ? ` (about ${S.fmt(t.need)} + 10 %)` : ''}`);
|
|
98
|
+
else out.log(` ${chalk.yellow('○')} ${t.target}: pending, not loaded`);
|
|
99
|
+
}
|
|
100
|
+
out.log(chalk.grey(' Nothing was loaded. The next "poad deploy" loads them once there is room (no need to send them again).'));
|
|
101
|
+
return { status: 'failed', refused: true, error: d.message || e.message, steps: tables.map((t) => ({ target: t.target, status: t.status === 'refused' ? 'failed' : 'skipped', reason: 'space' })), space: { required: d.required, free: d.free, limit: d.limit, margin: d.margin } };
|
|
92
102
|
}
|
|
93
|
-
|
|
103
|
+
const plan = started.plan || {};
|
|
104
|
+
if (plan.mode === 'stepwise') out.log(chalk.grey(` Loading into ${branch} table by table (${plan.order.length} tables, not enough room for all at once): ${plan.order.join(', ')}…`));
|
|
105
|
+
else out.log(chalk.grey(` Loading into ${branch} (${started.targets.length} table(s))…`));
|
|
94
106
|
const done = new Set();
|
|
95
107
|
const l = await S.waitLoad(id, started.load_id, {
|
|
96
108
|
onStep: (st) => {
|
|
@@ -105,6 +117,8 @@ async function startAndWait(id, branch, targets, opts, out) {
|
|
|
105
117
|
}
|
|
106
118
|
},
|
|
107
119
|
});
|
|
120
|
+
// Tables pas chargées (une précédente refusée ou en échec) : le prochain poad deploy les reprend
|
|
121
|
+
for (const s of l.steps || []) if (s.status === 'skipped' || s.status === 'pending') out.log(`${chalk.yellow('○')} ${s.target}: pending, not loaded into ${branch}; the next "poad deploy" loads it`);
|
|
108
122
|
if (l.status === 'failed') out.log(chalk.grey(' Nothing was half-loaded: each table is all or nothing.'));
|
|
109
123
|
return l;
|
|
110
124
|
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// poad db reset : sources « Fichier envoyé » rappelées (leur fichier est effacé avec le stockage local)
|
|
2
|
+
const test = require('node:test');
|
|
3
|
+
const assert = require('node:assert');
|
|
4
|
+
const fs = require('fs');
|
|
5
|
+
const os = require('os');
|
|
6
|
+
const path = require('path');
|
|
7
|
+
const { uploadSources } = require('../project/db/reset');
|
|
8
|
+
|
|
9
|
+
test('uploadSources : seules les sources origin.kind upload, avec leur table', () => {
|
|
10
|
+
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-reset-'));
|
|
11
|
+
const dir = path.join(root, 'sources');
|
|
12
|
+
fs.mkdirSync(dir);
|
|
13
|
+
fs.writeFileSync(path.join(dir, 'mesures.yaml'), 'name: mesures\nmode: imported\norigin:\n kind: upload # fichier envoyé : une nouvelle version se charge en l’envoyant de nouveau\n path: poad-sources/sources/20261204-ab/mesures.csv\n format: csv\ntable: public.mesures\nkey: [a]\n');
|
|
14
|
+
fs.writeFileSync(path.join(dir, 'gares.yaml'), 'name: gares\nmode: imported\norigin: { kind: upload, path: poad-sources/x/gares.csv, format: csv }\ntable: gares_fr\n');
|
|
15
|
+
fs.writeFileSync(path.join(dir, 'communes.yaml'), 'name: communes\norigin:\n kind: file\n url: https://example.org/c.csv\ntable: public.communes\n');
|
|
16
|
+
fs.writeFileSync(path.join(dir, 'notes.txt'), 'kind: upload\n');
|
|
17
|
+
const got = uploadSources(root).sort((a, b) => a.name.localeCompare(b.name));
|
|
18
|
+
assert.deepStrictEqual(got, [{ name: 'gares', table: 'gares_fr' }, { name: 'mesures', table: 'mesures' }]);
|
|
19
|
+
assert.deepStrictEqual(uploadSources(path.join(root, 'absent')), []);
|
|
20
|
+
});
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// Types des fonctions déposés dans poad/functions/.poad/types (utils/function-types.js)
|
|
2
|
+
const test = require('node:test');
|
|
3
|
+
const assert = require('node:assert');
|
|
4
|
+
const fs = require('fs');
|
|
5
|
+
const os = require('os');
|
|
6
|
+
const path = require('path');
|
|
7
|
+
const types = require('../utils/function-types');
|
|
8
|
+
|
|
9
|
+
const bundle = (text) => ({ files: { '@poadio/functions/index.d.ts': text, '@poadio/client-js/index.d.ts': 'export {};\n', '../evil.d.ts': 'x', '@poadio/x/a.js': 'x' } });
|
|
10
|
+
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'poad-fntypes-'));
|
|
11
|
+
|
|
12
|
+
test('dépose les types valides seulement, et le tsconfig qui inclut @poadio/functions', () => {
|
|
13
|
+
const dir = tmp();
|
|
14
|
+
const done = types.write(dir, bundle('export declare const flowStep: () => null;\n'));
|
|
15
|
+
assert.deepStrictEqual(done, { count: 2, changed: true });
|
|
16
|
+
assert.match(fs.readFileSync(path.join(dir, '.poad/types/@poadio/functions/index.d.ts'), 'utf8'), /flowStep/);
|
|
17
|
+
assert.ok(!fs.existsSync(path.join(dir, '.poad/evil.d.ts')));
|
|
18
|
+
const tsconfig = JSON.parse(fs.readFileSync(path.join(dir, 'tsconfig.json'), 'utf8'));
|
|
19
|
+
assert.ok(tsconfig.include.includes('.poad/types/@poadio/functions/index.d.ts'));
|
|
20
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
test('rien ne change si les types sont les mêmes ; des types périmés sont remplacés', () => {
|
|
24
|
+
const dir = tmp();
|
|
25
|
+
types.write(dir, bundle('export declare const caller: () => null;\n'));
|
|
26
|
+
assert.deepStrictEqual(types.write(dir, bundle('export declare const caller: () => null;\n')), { count: 2, changed: false });
|
|
27
|
+
const done = types.write(dir, bundle('export declare const caller: () => null;\nexport declare const flowStep: () => null;\n'));
|
|
28
|
+
assert.strictEqual(done.changed, true);
|
|
29
|
+
assert.match(fs.readFileSync(path.join(dir, '.poad/types/@poadio/functions/index.d.ts'), 'utf8'), /flowStep/);
|
|
30
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test('le tsconfig d\'un ancien CLI est mis à niveau, un tsconfig modifié à la main est gardé', () => {
|
|
34
|
+
const dir = tmp();
|
|
35
|
+
fs.writeFileSync(path.join(dir, 'tsconfig.json'), types.OLD_TSCONFIGS[0]);
|
|
36
|
+
types.write(dir, bundle('export {};\n'));
|
|
37
|
+
assert.strictEqual(fs.readFileSync(path.join(dir, 'tsconfig.json'), 'utf8'), types.TSCONFIG);
|
|
38
|
+
const mine = '{ "compilerOptions": { "strict": false } }\n';
|
|
39
|
+
fs.writeFileSync(path.join(dir, 'tsconfig.json'), mine);
|
|
40
|
+
types.write(dir, bundle('export {};\n'));
|
|
41
|
+
assert.strictEqual(fs.readFileSync(path.join(dir, 'tsconfig.json'), 'utf8'), mine);
|
|
42
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test('sans types servis : null, rien d\'écrit', () => {
|
|
46
|
+
const dir = tmp();
|
|
47
|
+
assert.strictEqual(types.write(dir, null), null);
|
|
48
|
+
assert.strictEqual(types.write(dir, { files: {} }), null);
|
|
49
|
+
assert.ok(!fs.existsSync(path.join(dir, 'tsconfig.json')));
|
|
50
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
51
|
+
});
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// poad deploy et les grosses références : une table envoyée mais jamais chargée dans cet environnement
|
|
2
|
+
// est chargée au deploy suivant (sans renvoi) ; refus de place de poad.io dit table par table.
|
|
3
|
+
const { test } = require('node:test');
|
|
4
|
+
const assert = require('node:assert');
|
|
5
|
+
const fs = require('fs');
|
|
6
|
+
const os = require('os');
|
|
7
|
+
const path = require('path');
|
|
8
|
+
const api = require('../utils/cloud/api');
|
|
9
|
+
const store = require('../utils/reference-store');
|
|
10
|
+
|
|
11
|
+
const SHA = 'a'.repeat(64);
|
|
12
|
+
const chalk = new Proxy({}, { get: () => { const f = (s) => s; return new Proxy(f, { get: () => f }); } });
|
|
13
|
+
|
|
14
|
+
function project() {
|
|
15
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-reload-'));
|
|
16
|
+
fs.mkdirSync(path.join(dir, 'reference'));
|
|
17
|
+
fs.writeFileSync(path.join(dir, 'reference', 'public.commune.jsonl'), '{"id":1}\n'.repeat(4));
|
|
18
|
+
const files = store.largeFiles(dir, 5);
|
|
19
|
+
// Déjà envoyée par un deploy précédent : la mémoire locale garde son empreinte
|
|
20
|
+
fs.mkdirSync(path.join(dir, 'data'));
|
|
21
|
+
const f = files[0];
|
|
22
|
+
fs.writeFileSync(path.join(dir, 'data', 'reference-store.json'), JSON.stringify({ [f.file]: { size: f.size, mtimeMs: f.mtimeMs, sha256: SHA, target: f.target } }));
|
|
23
|
+
return { dir, files };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function fakeApi(t, routes) {
|
|
27
|
+
const calls = [];
|
|
28
|
+
const orig = api.call;
|
|
29
|
+
api.call = async (method, route, o = {}) => {
|
|
30
|
+
calls.push([method, route, o.body]);
|
|
31
|
+
for (const [re, fn] of routes) if (re.test(`${method} ${route}`)) return fn(o);
|
|
32
|
+
throw new Error(`route inattendue ${method} ${route}`);
|
|
33
|
+
};
|
|
34
|
+
t.after(() => (api.call = orig));
|
|
35
|
+
return calls;
|
|
36
|
+
}
|
|
37
|
+
const output = () => {
|
|
38
|
+
const lines = [];
|
|
39
|
+
return { lines, out: { chalk, json: false, log: (l) => lines.push(String(l)) } };
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
test('envoyée, jamais chargée dans cet environnement → chargée au deploy suivant, sans renvoi', async (t) => {
|
|
43
|
+
const { dir, files } = project();
|
|
44
|
+
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
|
|
45
|
+
let polls = 0;
|
|
46
|
+
const calls = fakeApi(t, [
|
|
47
|
+
[/^GET .*\/seeds$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA }], applied: { dev: { 'public.commune': { sha256: SHA } } } })],
|
|
48
|
+
[/^POST .*\/seeds\/load$/, () => ({ load_id: 'l1', targets: ['public.commune'], plan: { mode: 'together', order: ['public.commune'] } })],
|
|
49
|
+
[/^GET .*\/seeds\/loads\/l1$/, () => (++polls < 2 ? { status: 'running', steps: [{ target: 'public.commune', status: 'running' }] } : { status: 'done', steps: [{ target: 'public.commune', status: 'done', written: 4, deleted: 0, duration_ms: 1200 }] })],
|
|
50
|
+
]);
|
|
51
|
+
const { lines, out } = output();
|
|
52
|
+
// Chargée en dev, pas en main : main la charge
|
|
53
|
+
const r = await store.sendAndLoad('abcdefghijkl', 'main', dir, files, {}, out);
|
|
54
|
+
assert.strictEqual(r.failed, false);
|
|
55
|
+
assert.deepStrictEqual(r.tables.map((x) => [x.target, x.action, x.state]), [['public.commune', 'load', 'loaded']]);
|
|
56
|
+
assert.ok(!calls.some(([, route]) => /seeds\/upload/.test(route)), 'rien renvoyé');
|
|
57
|
+
assert.deepStrictEqual(calls.find(([, route]) => /seeds\/load$/.test(route))[2], { branch: 'main', targets: ['public.commune'] });
|
|
58
|
+
assert.ok(lines.some((l) => /public\.commune loaded into main: 4 rows/.test(l)), lines.join('\n'));
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
test('déjà chargée dans cet environnement : ni envoi ni chargement', async (t) => {
|
|
62
|
+
const { dir, files } = project();
|
|
63
|
+
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
|
|
64
|
+
const calls = fakeApi(t, [[/^GET .*\/seeds$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA }], applied: { main: { 'public.commune': { sha256: SHA } } } })]]);
|
|
65
|
+
const { out } = output();
|
|
66
|
+
const r = await store.sendAndLoad('abcdefghijkl', 'main', dir, files, {}, out);
|
|
67
|
+
assert.deepStrictEqual(r.tables.map((x) => [x.action, x.state]), [['unchanged', 'loaded']]);
|
|
68
|
+
assert.strictEqual(calls.length, 1);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
test('poad.io refuse faute de place (aucun ordre ne tient) : chaque table dite, deploy en échec, rien lancé', async (t) => {
|
|
72
|
+
const { dir, files } = project();
|
|
73
|
+
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
|
|
74
|
+
const message = 'place insuffisante, même table par table : public.commune demande à elle seule environ 700.0 Mio, + 10 % de marge = 770.0 Mio, plus 256.0 Mio pour le journal (il manquerait 76.3 Mio). Pour passer : poad ref inspect public.commune, --exclude, ou une offre plus grande.';
|
|
75
|
+
fakeApi(t, [
|
|
76
|
+
[/^GET .*\/seeds$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA }], applied: {} })],
|
|
77
|
+
[/^POST .*\/seeds\/load$/, () => {
|
|
78
|
+
throw new api.CloudError(`reference load: ${message} (seed_no_space)`, { status: 413, code: 'seed_no_space', details: { code: 'seed_no_space', message, margin: 1.1, required: 1100, free: 1000, limit: 1024, tables: [{ target: 'public.commune', need: 734003200, status: 'refused' }, { target: 'public.region', need: 1, status: 'pending' }] } });
|
|
79
|
+
}],
|
|
80
|
+
]);
|
|
81
|
+
const { lines, out } = output();
|
|
82
|
+
const r = await store.sendAndLoad('abcdefghijkl', 'main', dir, files, {}, out);
|
|
83
|
+
assert.strictEqual(r.failed, true);
|
|
84
|
+
assert.deepStrictEqual(r.tables.map((x) => [x.target, x.state]), [['public.commune', 'refused']]);
|
|
85
|
+
const text = lines.join('\n');
|
|
86
|
+
assert.match(text, /Reference load refused on main: place insuffisante/);
|
|
87
|
+
assert.match(text, /public\.commune: refused, not enough room \(about 700\.0 M/);
|
|
88
|
+
assert.match(text, /public\.region: pending, not loaded/);
|
|
89
|
+
assert.match(text, /next "poad deploy" loads them/);
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
test('chargement table par table : annoncé, puis une table refusée en cours et la suivante en attente', async (t) => {
|
|
93
|
+
const { dir, files } = project();
|
|
94
|
+
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
|
|
95
|
+
fakeApi(t, [
|
|
96
|
+
[/^GET .*\/seeds$/, () => ({ store: true, items: [{ target: 'public.commune', sha256: SHA }], applied: {} })],
|
|
97
|
+
[/^POST .*\/seeds\/load$/, () => ({ load_id: 'l2', targets: ['public.commune'], plan: { mode: 'stepwise', order: ['public.a', 'public.commune', 'public.c'] } })],
|
|
98
|
+
[/^GET .*\/seeds\/loads\/l2$/, () => ({ status: 'failed', steps: [
|
|
99
|
+
{ target: 'public.a', status: 'done', written: 1, deleted: 0, duration_ms: 10, warnings: ['place restante faible sur l’engine main : 200.0 Mio libres sur 1.00 Gio (20 %)'] },
|
|
100
|
+
{ target: 'public.commune', status: 'failed', reason: 'space', error: 'refusée : place insuffisante pour cette table…' },
|
|
101
|
+
{ target: 'public.c', status: 'skipped', error: 'en attente' },
|
|
102
|
+
] })],
|
|
103
|
+
]);
|
|
104
|
+
const { lines, out } = output();
|
|
105
|
+
const r = await store.sendAndLoad('abcdefghijkl', 'main', dir, files, {}, out);
|
|
106
|
+
assert.strictEqual(r.failed, true);
|
|
107
|
+
assert.deepStrictEqual(r.tables.map((x) => x.state), ['refused']);
|
|
108
|
+
const text = lines.join('\n');
|
|
109
|
+
assert.match(text, /table by table \(3 tables, not enough room for all at once\): public\.a, public\.commune, public\.c/);
|
|
110
|
+
assert.match(text, /⚠ place restante faible/);
|
|
111
|
+
assert.match(text, /public\.commune: refusée : place insuffisante/);
|
|
112
|
+
assert.match(text, /public\.c: pending, not loaded into main; the next "poad deploy" loads it/);
|
|
113
|
+
});
|
package/utils/cloud/api.js
CHANGED
|
@@ -14,10 +14,12 @@ const DEFAULT_API = 'https://poad.io/_poad/cloud';
|
|
|
14
14
|
const EXIT = { ok: 0, error: 1, usage: 2, auth: 3, confirm: 4, failed: 5 };
|
|
15
15
|
|
|
16
16
|
class CloudError extends Error {
|
|
17
|
-
constructor(message, { status = 0, code = 'error', exit } = {}) {
|
|
17
|
+
constructor(message, { status = 0, code = 'error', exit, details } = {}) {
|
|
18
18
|
super(message);
|
|
19
19
|
this.status = status;
|
|
20
20
|
this.code = code;
|
|
21
|
+
// Champs du refus rendus par poad.io (tailles, tables…), jamais de secret
|
|
22
|
+
if (details) this.details = details;
|
|
21
23
|
this.exit = exit || (status === 401 || code === 'not_logged_in' ? EXIT.auth : EXIT.error);
|
|
22
24
|
}
|
|
23
25
|
}
|
|
@@ -104,7 +106,7 @@ function errorOf(res, what) {
|
|
|
104
106
|
const message = typeof e.message === 'string' && e.message ? e.message : `HTTP ${res.status}`;
|
|
105
107
|
if (res.status === 401) return new CloudError(`poad.io refused the session (${message}): run "poad login".`, { status: 401, code });
|
|
106
108
|
if (res.status === 404) return new CloudError(`${what ? `${what}: ` : ''}not found (${message}).`, { status: 404, code });
|
|
107
|
-
return new CloudError(`${what ? `${what}: ` : ''}${message}${code && !message.includes(code) ? ` (${code})` : ''}`, { status: res.status, code });
|
|
109
|
+
return new CloudError(`${what ? `${what}: ` : ''}${message}${code && !message.includes(code) ? ` (${code})` : ''}`, { status: res.status, code, details: e });
|
|
108
110
|
}
|
|
109
111
|
|
|
110
112
|
/** Appel authentifié : la réponse JSON, ou CloudError */
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// Types pour l'éditeur des fonctions du projet (poad/functions) : lus sur
|
|
2
|
+
// l'engine lancé (/functions/v1/types.json, accordés à son runtime) et déposés
|
|
3
|
+
// dans poad/functions/.poad/types, avec le tsconfig.json qui les relie.
|
|
4
|
+
// poad functions types les pose à la demande ; poad start les rafraîchit, pour
|
|
5
|
+
// qu'un projet ne garde pas les types d'une engine plus ancienne (murex :
|
|
6
|
+
// flowStep absent des types alors que le runtime l'exporte).
|
|
7
|
+
const fs = require('fs');
|
|
8
|
+
const path = require('path');
|
|
9
|
+
|
|
10
|
+
// tsconfig.json de poad/functions : API web (celles de workerd) et @poadio/*
|
|
11
|
+
// relié aux types déposés par l'engine. Il inclut le .d.ts de @poadio/functions
|
|
12
|
+
// lui-même : ses déclarations globales (fetch qui accepte tout ArrayBufferView,
|
|
13
|
+
// comme workerd) valent aussi pour une fonction qui ne l'importe pas.
|
|
14
|
+
const TSCONFIG = `{
|
|
15
|
+
"compilerOptions": {
|
|
16
|
+
"target": "ES2022",
|
|
17
|
+
"module": "ESNext",
|
|
18
|
+
"moduleResolution": "bundler",
|
|
19
|
+
"lib": ["ES2022", "WebWorker"],
|
|
20
|
+
"types": [],
|
|
21
|
+
"strict": true,
|
|
22
|
+
"noEmit": true,
|
|
23
|
+
"skipLibCheck": true,
|
|
24
|
+
"allowImportingTsExtensions": true,
|
|
25
|
+
"paths": {
|
|
26
|
+
"@poadio/*": ["./.poad/types/@poadio/*/index.d.ts"]
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
"include": ["**/*.ts", "**/*.tsx", ".poad/types/@poadio/functions/index.d.ts"],
|
|
30
|
+
"exclude": ["node_modules"]
|
|
31
|
+
}
|
|
32
|
+
`;
|
|
33
|
+
// Le tsconfig écrit par les CLI précédents : remplacé tel quel, jamais un tsconfig modifié à la main
|
|
34
|
+
const OLD_TSCONFIGS = [TSCONFIG.replace(', ".poad/types/@poadio/functions/index.d.ts"', '')];
|
|
35
|
+
|
|
36
|
+
const TYPE_FILE_RE = /^@poadio\/[a-z][a-z0-9-]*(\/[A-Za-z0-9_-]+)*\/[A-Za-z0-9_.-]+\.d\.ts$/;
|
|
37
|
+
|
|
38
|
+
/** Fichiers de types valides d'une réponse de /types.json */
|
|
39
|
+
const typeFiles = (bundle) =>
|
|
40
|
+
Object.entries((bundle && bundle.files) || {}).filter(([name, text]) => TYPE_FILE_RE.test(name) && !name.includes('..') && typeof text === 'string');
|
|
41
|
+
|
|
42
|
+
/** Lit les types sur l'engine lancé ; réessaie pendant `waitSeconds` le temps que le service functions démarre */
|
|
43
|
+
async function fetchBundle(config, waitSeconds = 0) {
|
|
44
|
+
const deadline = Date.now() + waitSeconds * 1000;
|
|
45
|
+
for (;;) {
|
|
46
|
+
try {
|
|
47
|
+
const res = await fetch(`http://localhost:${config.web.port}/functions/v1/types.json`, { signal: AbortSignal.timeout(5000) });
|
|
48
|
+
if (res.ok) return await res.json();
|
|
49
|
+
} catch {
|
|
50
|
+
/* engine pas encore prêt, ou sans service functions */
|
|
51
|
+
}
|
|
52
|
+
if (Date.now() >= deadline) return null;
|
|
53
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Dépose les types dans <dir>/.poad/types (dir = poad/functions) et pose ou met à
|
|
59
|
+
* niveau tsconfig.json. Renvoie { count, changed } ou null si l'engine ne les sert pas.
|
|
60
|
+
*/
|
|
61
|
+
function write(dir, bundle) {
|
|
62
|
+
const files = typeFiles(bundle);
|
|
63
|
+
if (!files.length) return null;
|
|
64
|
+
const typesDir = path.join(dir, '.poad', 'types');
|
|
65
|
+
const read = (p) => {
|
|
66
|
+
try {
|
|
67
|
+
return fs.readFileSync(p, 'utf8');
|
|
68
|
+
} catch {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
const listed = (d, prefix = '') =>
|
|
73
|
+
!fs.existsSync(d)
|
|
74
|
+
? []
|
|
75
|
+
: fs.readdirSync(d, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? listed(path.join(d, e.name), `${prefix}${e.name}/`) : [`${prefix}${e.name}`]));
|
|
76
|
+
const same = listed(typesDir).sort().join('\n') === files.map(([n]) => n).sort().join('\n') && files.every(([n, text]) => read(path.join(typesDir, n)) === text);
|
|
77
|
+
if (!same) {
|
|
78
|
+
fs.rmSync(typesDir, { recursive: true, force: true });
|
|
79
|
+
for (const [name, text] of files) {
|
|
80
|
+
const target = path.join(typesDir, name);
|
|
81
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
82
|
+
fs.writeFileSync(target, text);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
// L'ancien fichier de types (client en « any ») masquerait les nouveaux
|
|
86
|
+
const old = path.join(dir, 'poad-functions.d.ts');
|
|
87
|
+
if (fs.existsSync(old) && fs.readFileSync(old, 'utf8').startsWith('// Généré par poad')) fs.rmSync(old);
|
|
88
|
+
const tsconfig = path.join(dir, 'tsconfig.json');
|
|
89
|
+
const current = read(tsconfig);
|
|
90
|
+
let tsconfigChanged = false;
|
|
91
|
+
if (current === null || OLD_TSCONFIGS.includes(current)) {
|
|
92
|
+
fs.writeFileSync(tsconfig, TSCONFIG);
|
|
93
|
+
tsconfigChanged = true;
|
|
94
|
+
}
|
|
95
|
+
return { count: files.length, changed: !same || tsconfigChanged };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
module.exports = { TSCONFIG, OLD_TSCONFIGS, typeFiles, fetchBundle, write };
|
package/utils/reference-store.js
CHANGED
|
@@ -152,6 +152,13 @@ async function sendAndLoad(id, branch, poadDir, files, opts, out) {
|
|
|
152
152
|
}
|
|
153
153
|
let load = null;
|
|
154
154
|
if (toLoad.length) load = await startAndWait(id, branch, toLoad, opts, out);
|
|
155
|
+
// État de chaque table dans cet environnement : loaded, pending (pas encore chargée), refused (place), failed
|
|
156
|
+
for (const t of tables) {
|
|
157
|
+
const st = load && (load.steps || []).find((x) => x.target === t.target);
|
|
158
|
+
if (t.action === 'unchanged') t.state = 'loaded';
|
|
159
|
+
else if (st) t.state = st.status === 'done' ? 'loaded' : st.status === 'failed' ? (st.reason === 'space' ? 'refused' : 'failed') : 'pending';
|
|
160
|
+
else t.state = 'pending';
|
|
161
|
+
}
|
|
155
162
|
return { tables, load, failed: Boolean(load && load.status === 'failed') };
|
|
156
163
|
}
|
|
157
164
|
|