poad 2.59.0 → 2.61.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/start.js +6 -0
- package/global/stop.js +52 -19
- package/package.json +1 -1
- package/poad.js +23 -0
- package/project/cli.js +8 -1
- package/project/db/diff.js +99 -1
- package/project/flows.js +133 -39
- package/project/logs.js +92 -43
- package/project/migrate.js +2 -1
- package/project/storage/cp.js +41 -0
- package/project/storage/index.js +2 -0
- package/project/storage/ls.js +49 -0
- package/project/storage/mv.js +7 -0
- package/project/storage/rm.js +39 -0
- package/project/upgrade.js +6 -0
- package/test/flows.test.js +256 -0
- package/test/project-lock.test.js +51 -0
- package/test/storage.test.js +186 -0
- package/utils/banner.js +1 -0
- package/utils/help-details.js +62 -5
- package/utils/project-lock.js +67 -0
- package/utils/reference.js +6 -3
- package/utils/storage-copy.js +141 -0
- package/utils/storage.js +275 -0
package/utils/storage.js
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
// poad storage : les fichiers du Stockage du projet, en ligne de commande.
|
|
2
|
+
//
|
|
3
|
+
// ls [bucket[/dossier]] [-r] buckets, ou le contenu d'un dossier
|
|
4
|
+
// cp <source> <destination> [-r] disque → Stockage, Stockage → disque, Stockage → Stockage
|
|
5
|
+
// mv <source> <destination> [-r] dans le Stockage (copie, puis suppression de la source)
|
|
6
|
+
// rm <chemin…> [-r] [--yes] fichiers, ou tout un dossier avec -r
|
|
7
|
+
//
|
|
8
|
+
// Un chemin du Stockage s'écrit bucket/chemin ; « poad: » devant (poad:photos/a.png)
|
|
9
|
+
// le distingue d'un fichier du disque, et il est obligatoire pour cp. Les dossiers
|
|
10
|
+
// n'existent que par leurs fichiers (noms à « / »), comme dans la console.
|
|
11
|
+
//
|
|
12
|
+
// Le CLI parle à l'API du Stockage (/storage/v1) de l'engine lancé, avec la clé
|
|
13
|
+
// service_role de poad/config.toml : jamais affichée, jamais dans un message.
|
|
14
|
+
// Chaque requête est journalisée par le service storage (poad logs storage).
|
|
15
|
+
// Copier et déplacer passent par le CLI, en flux : aucune version d'engine requise.
|
|
16
|
+
const fs = require('fs');
|
|
17
|
+
const path = require('path');
|
|
18
|
+
const { Readable } = require('stream');
|
|
19
|
+
const { pipeline } = require('stream/promises');
|
|
20
|
+
const { CloudError, EXIT, usageError } = require('./cloud/api');
|
|
21
|
+
|
|
22
|
+
const SCHEME_RE = /^poad:(\/\/)?/;
|
|
23
|
+
const BUCKET_RE = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,62}$/;
|
|
24
|
+
const PAGE = 1000;
|
|
25
|
+
const PARALLEL = 4;
|
|
26
|
+
const TIMEOUT_MS = 30000;
|
|
27
|
+
|
|
28
|
+
// Types des extensions courantes : le Stockage garde le Content-Type de l'envoi
|
|
29
|
+
const MIME = {
|
|
30
|
+
txt: 'text/plain', md: 'text/markdown', csv: 'text/csv', html: 'text/html', htm: 'text/html', css: 'text/css',
|
|
31
|
+
js: 'text/javascript', mjs: 'text/javascript', json: 'application/json', xml: 'application/xml', yaml: 'application/yaml', yml: 'application/yaml',
|
|
32
|
+
pdf: 'application/pdf', zip: 'application/zip', gz: 'application/gzip', tar: 'application/x-tar', sql: 'application/sql', geojson: 'application/geo+json',
|
|
33
|
+
png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', avif: 'image/avif', svg: 'image/svg+xml', ico: 'image/x-icon',
|
|
34
|
+
mp3: 'audio/mpeg', wav: 'audio/wav', ogg: 'audio/ogg', mp4: 'video/mp4', webm: 'video/webm', mov: 'video/quicktime', mkv: 'video/x-matroska',
|
|
35
|
+
woff: 'font/woff', woff2: 'font/woff2', ttf: 'font/ttf', otf: 'font/otf', wasm: 'application/wasm',
|
|
36
|
+
};
|
|
37
|
+
const mimeOf = (file) => MIME[path.extname(file).slice(1).toLowerCase()] || 'application/octet-stream';
|
|
38
|
+
|
|
39
|
+
/** « poad:bucket/a/b » ou « bucket/a/b » → { bucket, key, dir } ; dir : finit par « / » ou vide. Pure. */
|
|
40
|
+
function parseRemote(text) {
|
|
41
|
+
const raw = String(text || '').replace(SCHEME_RE, '').replace(/^\/+/, '');
|
|
42
|
+
if (!raw) throw usageError('a storage path is expected: bucket/path');
|
|
43
|
+
const at = raw.indexOf('/');
|
|
44
|
+
const bucket = at < 0 ? raw : raw.slice(0, at);
|
|
45
|
+
const rest = at < 0 ? '' : raw.slice(at + 1);
|
|
46
|
+
if (!BUCKET_RE.test(bucket)) throw usageError(`"${bucket}" is not a bucket name`);
|
|
47
|
+
const key = rest.replace(/\/{2,}/g, '/').replace(/^\//, '');
|
|
48
|
+
if (key.split('/').some((p) => p === '.' || p === '..')) throw usageError(`"${text}": "." and ".." are not allowed in a storage path`);
|
|
49
|
+
return { bucket, key: key.replace(/\/$/, ''), dir: !key || key.endsWith('/') };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Date locale courte (AAAA-MM-JJ HH:MM) d'une date ISO. Pure (au fuseau près). */
|
|
53
|
+
function when(iso) {
|
|
54
|
+
if (!iso) return '';
|
|
55
|
+
const d = new Date(iso);
|
|
56
|
+
if (Number.isNaN(d.getTime())) return String(iso);
|
|
57
|
+
const p = (n) => String(n).padStart(2, '0');
|
|
58
|
+
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const isRemote = (text) => SCHEME_RE.test(String(text || ''));
|
|
62
|
+
const show = (bucket, key) => `${bucket}/${key}`;
|
|
63
|
+
|
|
64
|
+
/** Taille lisible : 0 B, 12.3 KB, 4.5 MB. Pure. */
|
|
65
|
+
function size(n) {
|
|
66
|
+
if (!Number.isFinite(n)) return '';
|
|
67
|
+
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
|
68
|
+
let i = 0;
|
|
69
|
+
let v = n;
|
|
70
|
+
while (v >= 1024 && i < units.length - 1) (v /= 1024), i++;
|
|
71
|
+
return i === 0 ? `${v} B` : `${v.toFixed(v < 10 ? 1 : 0)} ${units[i]}`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Ce que montre ls sous un dossier : sous-dossiers (nombre de fichiers, taille) puis
|
|
76
|
+
* fichiers, à partir de la liste plate des objets (noms complets). Pure.
|
|
77
|
+
*/
|
|
78
|
+
function entries(objects, prefix) {
|
|
79
|
+
const folders = new Map();
|
|
80
|
+
const files = [];
|
|
81
|
+
for (const o of objects) {
|
|
82
|
+
if (!o.name.startsWith(prefix)) continue;
|
|
83
|
+
const rest = o.name.slice(prefix.length);
|
|
84
|
+
const cut = rest.indexOf('/');
|
|
85
|
+
const bytes = Number(o.metadata && o.metadata.size) || 0;
|
|
86
|
+
if (cut < 0) files.push({ kind: 'file', name: rest, size: bytes, updated: o.updated_at, type: o.metadata && o.metadata.mimetype });
|
|
87
|
+
else {
|
|
88
|
+
const name = rest.slice(0, cut);
|
|
89
|
+
const f = folders.get(name) || { kind: 'folder', name, count: 0, size: 0, updated: null };
|
|
90
|
+
f.count++;
|
|
91
|
+
f.size += bytes;
|
|
92
|
+
if (!f.updated || o.updated_at > f.updated) f.updated = o.updated_at;
|
|
93
|
+
folders.set(name, f);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return [...[...folders.values()].sort((a, b) => a.name.localeCompare(b.name)), ...files.sort((a, b) => a.name.localeCompare(b.name))];
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Plan d'une copie : liste de { from, to } (to : chemin du disque ou clé du Stockage).
|
|
101
|
+
* srcKeys noms des objets sous la source (Stockage) ; null si la source est un fichier du disque
|
|
102
|
+
* Règles de cp : une source « dossier » demande -r ; une destination qui finit par « / »
|
|
103
|
+
* (ou un dossier existant du disque) reçoit le nom de base de la source. Pure.
|
|
104
|
+
*/
|
|
105
|
+
function joinKey(dir, name) {
|
|
106
|
+
return dir ? `${dir.replace(/\/$/, '')}/${name}` : name;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Client de l'API du Stockage : base (sans « / » final), clé, fetch injectable (tests) */
|
|
110
|
+
function client({ base, key, apikey, renew, fetch: doFetch = fetch, timeout = TIMEOUT_MS }) {
|
|
111
|
+
// Hébergé : clé anon pour la passerelle (apikey), jeton court du Stockage (Bearer), renouvelé
|
|
112
|
+
// une minute avant son expiration ; local : la clé service_role pour les deux
|
|
113
|
+
let auth = { key, apikey: apikey || key, expires: null };
|
|
114
|
+
if (renew && renew.first) auth = { ...auth, expires: Date.parse(renew.first) };
|
|
115
|
+
const fresh = async () => {
|
|
116
|
+
if (renew && auth.expires && auth.expires - Date.now() < 60000) {
|
|
117
|
+
const t = await renew.next();
|
|
118
|
+
auth = { key: t.token, apikey: t.anon_key, expires: Date.parse(t.expires_at) };
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
const headers = (extra = {}) => ({ apikey: auth.apikey, authorization: `Bearer ${auth.key}`, ...extra });
|
|
122
|
+
const enc = (k) => k.split('/').map(encodeURIComponent).join('/');
|
|
123
|
+
|
|
124
|
+
async function request(method, route, { body, json, type, stream = false, ok = [200, 201, 204], length } = {}) {
|
|
125
|
+
await fresh();
|
|
126
|
+
const ctl = new AbortController();
|
|
127
|
+
// Pas de délai pour un transfert en flux : seulement pour l'en-tête de la réponse
|
|
128
|
+
const timer = setTimeout(() => ctl.abort(), timeout);
|
|
129
|
+
let res;
|
|
130
|
+
try {
|
|
131
|
+
res = await doFetch(`${base}/storage/v1${route}`, {
|
|
132
|
+
method,
|
|
133
|
+
headers: headers({
|
|
134
|
+
...(json !== undefined ? { 'content-type': 'application/json' } : {}),
|
|
135
|
+
...(type ? { 'content-type': type } : {}),
|
|
136
|
+
...(length !== undefined ? { 'content-length': String(length) } : {}),
|
|
137
|
+
}),
|
|
138
|
+
body: json !== undefined ? JSON.stringify(json) : body,
|
|
139
|
+
...(body && typeof body.pipe === 'function' ? { duplex: 'half' } : {}),
|
|
140
|
+
...(body instanceof ReadableStream ? { duplex: 'half' } : {}),
|
|
141
|
+
signal: ctl.signal,
|
|
142
|
+
});
|
|
143
|
+
} catch (err) {
|
|
144
|
+
clearTimeout(timer);
|
|
145
|
+
const cause = (err && err.cause && err.cause.message) || (err && err.message) || String(err);
|
|
146
|
+
throw new CloudError(ctl.signal.aborted ? `The storage did not answer within ${timeout / 1000} s (${base}).` : `The storage does not answer on ${base}: ${cause}`);
|
|
147
|
+
}
|
|
148
|
+
clearTimeout(timer);
|
|
149
|
+
if (!ok.includes(res.status)) {
|
|
150
|
+
let message = `HTTP ${res.status}`;
|
|
151
|
+
try {
|
|
152
|
+
const b = await res.json();
|
|
153
|
+
if (b && (b.message || b.error)) message = String(b.message || b.error);
|
|
154
|
+
} catch {}
|
|
155
|
+
if (res.status === 401 || res.status === 403) message = `refused by the storage (HTTP ${res.status}): ${message}`;
|
|
156
|
+
if (res.status === 502 || res.status === 503) message = `the storage service is not available (HTTP ${res.status})`;
|
|
157
|
+
const e = new CloudError(message, { status: res.status, code: res.status === 404 ? 'not_found' : 'error' });
|
|
158
|
+
throw e;
|
|
159
|
+
}
|
|
160
|
+
if (stream) return res;
|
|
161
|
+
if (res.status === 204) return null;
|
|
162
|
+
const text = await res.text();
|
|
163
|
+
return text ? JSON.parse(text) : null;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
return {
|
|
167
|
+
buckets: () => request('GET', '/bucket'),
|
|
168
|
+
bucket: (id) => request('GET', `/bucket/${encodeURIComponent(id)}`),
|
|
169
|
+
/** Tous les objets dont le nom commence par prefix (pages de 1000) */
|
|
170
|
+
async list(bucket, prefix = '') {
|
|
171
|
+
const all = [];
|
|
172
|
+
for (let offset = 0; ; offset += PAGE) {
|
|
173
|
+
const rows = await request('POST', `/object/list/${encodeURIComponent(bucket)}`, { json: { prefix, limit: PAGE, offset } });
|
|
174
|
+
all.push(...rows);
|
|
175
|
+
if (rows.length < PAGE) return all;
|
|
176
|
+
}
|
|
177
|
+
},
|
|
178
|
+
/** Envoi (crée ou remplace) : body est un flux Node ou un Buffer */
|
|
179
|
+
put: (bucket, k, body, { type, length } = {}) =>
|
|
180
|
+
request('PUT', `/object/${encodeURIComponent(bucket)}/${enc(k)}`, {
|
|
181
|
+
body: body && typeof body.pipe === 'function' ? Readable.toWeb(body) : body,
|
|
182
|
+
type: type || 'application/octet-stream',
|
|
183
|
+
length,
|
|
184
|
+
}),
|
|
185
|
+
/** Lecture en flux : la réponse fetch (res.body, content-length) */
|
|
186
|
+
get: (bucket, k) => request('GET', `/object/${encodeURIComponent(bucket)}/${enc(k)}`, { stream: true }),
|
|
187
|
+
remove: (bucket, keys) => request('DELETE', `/object/${encodeURIComponent(bucket)}`, { json: { prefixes: keys } }),
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Exécute fn sur chaque élément, PARALLEL à la fois ; rend les erreurs { item, error } */
|
|
192
|
+
async function each(items, fn, parallel = PARALLEL) {
|
|
193
|
+
const errors = [];
|
|
194
|
+
let next = 0;
|
|
195
|
+
const worker = async () => {
|
|
196
|
+
while (next < items.length) {
|
|
197
|
+
const item = items[next++];
|
|
198
|
+
try {
|
|
199
|
+
await fn(item);
|
|
200
|
+
} catch (error) {
|
|
201
|
+
errors.push({ item, error });
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
await Promise.all(Array.from({ length: Math.min(parallel, items.length) }, worker));
|
|
206
|
+
return errors;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Objets visés par un chemin du Stockage : le fichier exact, sinon (avec -r) tout le dossier */
|
|
210
|
+
async function resolve(api, { bucket, key, dir }, recursive) {
|
|
211
|
+
if (!dir) {
|
|
212
|
+
const rows = await api.list(bucket, key);
|
|
213
|
+
const exact = rows.find((o) => o.name === key);
|
|
214
|
+
const under = rows.filter((o) => o.name.startsWith(`${key}/`));
|
|
215
|
+
if (exact) return { kind: 'file', objects: [exact], base: key };
|
|
216
|
+
if (!under.length) throw new CloudError(`${show(bucket, key)}: no such file or folder`, { code: 'not_found' });
|
|
217
|
+
if (!recursive) throw usageError(`${show(bucket, key)} is a folder: add -r`);
|
|
218
|
+
return { kind: 'folder', objects: under, base: key };
|
|
219
|
+
}
|
|
220
|
+
const rows = await api.list(bucket, key ? `${key}/` : '');
|
|
221
|
+
if (!rows.length) throw new CloudError(`${show(bucket, key || '')}${key ? '/' : ''}: empty or no such folder`, { code: 'not_found' });
|
|
222
|
+
if (!recursive) throw usageError(`${show(bucket, key)}${key ? '/' : ''} is a folder: add -r`);
|
|
223
|
+
return { kind: 'folder', objects: rows, base: key };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Fichiers d'un dossier du disque, chemins relatifs avec « / » */
|
|
227
|
+
function walk(dir) {
|
|
228
|
+
const out = [];
|
|
229
|
+
const go = (d, rel) => {
|
|
230
|
+
for (const e of fs.readdirSync(d, { withFileTypes: true })) {
|
|
231
|
+
const r = rel ? `${rel}/${e.name}` : e.name;
|
|
232
|
+
if (e.isDirectory()) go(path.join(d, e.name), r);
|
|
233
|
+
else if (e.isFile()) out.push(r);
|
|
234
|
+
}
|
|
235
|
+
};
|
|
236
|
+
go(dir, '');
|
|
237
|
+
return out.sort();
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Engine visé : le projet local lancé. Rend { base, key, label }.
|
|
242
|
+
* deps.started(config) (tests).
|
|
243
|
+
*/
|
|
244
|
+
async function localTarget(deps = {}) {
|
|
245
|
+
const { findPoadDir } = require('./findpoad');
|
|
246
|
+
const { readConfig } = require('./config');
|
|
247
|
+
const root = findPoadDir(process.cwd());
|
|
248
|
+
if (!root) throw usageError('You are not in a poad project directory.');
|
|
249
|
+
const config = readConfig(root);
|
|
250
|
+
const started = deps.started || ((c) => require('./docker').isDockerExist(c.project_uuid));
|
|
251
|
+
if (!(await started(config))) throw new CloudError('The project is not started: run "poad start".', { code: 'not_started' });
|
|
252
|
+
const key = config.auth && config.auth.service;
|
|
253
|
+
if (!key) throw new CloudError('No service_role key in poad/config.toml: run "poad start" once.', { code: 'no_key' });
|
|
254
|
+
return { base: `http://localhost:${config.web.port}`, key, label: 'local engine' };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Engine hébergé (poad.io) : --env <nom> (production : main) et --project <id>, sinon le projet lié.
|
|
259
|
+
* poad.io remet un jeton du Stockage de 15 minutes (jamais la clé service_role) et la clé anon.
|
|
260
|
+
*/
|
|
261
|
+
async function cloudTarget(opts = {}) {
|
|
262
|
+
const api = require('./cloud/api');
|
|
263
|
+
const { targetProject, checkBranch } = require('./cloud/cli');
|
|
264
|
+
const { id } = targetProject(opts);
|
|
265
|
+
const branch = opts.env ? checkBranch(opts.env) : 'main';
|
|
266
|
+
const ask = () => api.call('POST', `v1/projects/${api.enc(id)}/storage-token`, { body: { branch }, what: 'storage access' });
|
|
267
|
+
const t = await ask();
|
|
268
|
+
if (!t || !t.token || !t.url) throw new CloudError('poad.io gave no storage access for this project.', { code: 'unavailable' });
|
|
269
|
+
return { base: String(t.url).replace(/\/+$/, ''), key: t.token, apikey: t.anon_key, renew: { first: t.expires_at, next: ask }, label: `poad.io ${id}${branch === 'main' ? '' : ` (${branch})`}` };
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** Cible : poad.io avec --env/--project, sinon l'engine local */
|
|
273
|
+
const target = (opts = {}, deps) => (opts.env || opts.project ? cloudTarget(opts) : localTarget(deps));
|
|
274
|
+
|
|
275
|
+
module.exports = { EXIT, target, cloudTarget, when, parseRemote, isRemote, size, entries, joinKey, client, each, resolve, walk, mimeOf, show, localTarget };
|