poad 2.58.1 → 2.60.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/package.json +1 -1
- package/project/cli.js +7 -0
- 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/test/storage.test.js +186 -0
- package/utils/help-details.js +27 -0
- package/utils/runner.js +1 -1
- package/utils/storage-copy.js +141 -0
- package/utils/storage.js +275 -0
package/package.json
CHANGED
package/project/cli.js
CHANGED
|
@@ -39,6 +39,13 @@ module.exports = {
|
|
|
39
39
|
load: 'Same as poad ref load',
|
|
40
40
|
rm: 'Same as poad ref rm',
|
|
41
41
|
},
|
|
42
|
+
storage: {
|
|
43
|
+
description: 'Files of the project storage, local engine or poad.io (--env <name>): ls, cp (disk ↔ storage, storage → storage), mv, rm; a storage path is bucket/path (poad:bucket/path for cp)',
|
|
44
|
+
ls: 'Buckets, or the files and folders of a folder: ls [bucket[/folder]] [-r] [--json]',
|
|
45
|
+
cp: 'Copy files, -r for a folder: cp ./a.png poad:images/ | cp poad:images/a.png ./ | cp -r poad:images/2024 poad:archives/',
|
|
46
|
+
mv: 'Move or rename inside the storage (copy, then delete the source): mv <bucket/path> <bucket/path> [-r]',
|
|
47
|
+
rm: 'Delete files, or a whole folder with -r (asks first, --yes outside a terminal): rm <bucket/path…> [-r] [--yes]',
|
|
48
|
+
},
|
|
42
49
|
link: 'Link this project to a poad.io project: [cloud] project = "<id>" in poad/config.toml (no secret): link [<id>]',
|
|
43
50
|
unlink: 'Remove the link to poad.io from poad/config.toml (nothing changes on poad.io)',
|
|
44
51
|
env: {
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// poad storage cp <source> <destination> [-r] [--json]
|
|
2
|
+
// poad storage cp ./photo.png poad:images/ disque → Stockage
|
|
3
|
+
// poad storage cp -r ./site poad:web/ un dossier entier
|
|
4
|
+
// poad storage cp poad:images/photo.png ./ Stockage → disque
|
|
5
|
+
// poad storage cp -r poad:images/2024 poad:archives/ Stockage → Stockage
|
|
6
|
+
module.exports = (args, raw) =>
|
|
7
|
+
require('../../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['recursive'], alias: { r: 'recursive', R: 'recursive' } }, ({ opts, positionals, out }) => copy({ opts, positionals, out, move: false }));
|
|
8
|
+
|
|
9
|
+
/** Partagé avec mv (move : sources supprimées une fois copiées, Stockage seulement) */
|
|
10
|
+
async function copy({ opts, positionals, out, move }) {
|
|
11
|
+
const s = require('../../utils/storage');
|
|
12
|
+
const c = require('../../utils/storage-copy');
|
|
13
|
+
const { usageError } = require('../../utils/cloud/api');
|
|
14
|
+
const { chalk } = out;
|
|
15
|
+
const verb = move ? 'mv' : 'cp';
|
|
16
|
+
if (positionals.length !== 2) throw usageError(`Usage: poad storage ${verb} <source> <destination> [-r]${move ? '' : ' (a storage path is written poad:bucket/path)'}`);
|
|
17
|
+
const api = s.client(await s.target(opts));
|
|
18
|
+
const { items } = await c.plan(api, positionals[0], positionals[1], { recursive: opts.recursive, remoteOnly: move });
|
|
19
|
+
const r = await c.run(api, items, {
|
|
20
|
+
onDone: (it) => out.log(` ${chalk.greenBright('✔')} ${c.label(it.from)} ${chalk.grey('→')} ${c.label(it.to)} ${chalk.grey(s.size(it.size))}`),
|
|
21
|
+
});
|
|
22
|
+
let deleted = [];
|
|
23
|
+
if (move && r.done.length) {
|
|
24
|
+
// Seules les sources bien copiées sont supprimées
|
|
25
|
+
const byBucket = new Map();
|
|
26
|
+
for (const it of r.done) byBucket.set(it.from.bucket, [...(byBucket.get(it.from.bucket) || []), it.from.key]);
|
|
27
|
+
for (const [bucket, keys] of byBucket)
|
|
28
|
+
for (let i = 0; i < keys.length; i += 1000) deleted.push(...((await api.remove(bucket, keys.slice(i, i + 1000))) || []).map((o) => s.show(bucket, o.name)));
|
|
29
|
+
}
|
|
30
|
+
for (const e of r.errors) out.log(chalk.redBright(` ✖ ${c.label(e.item.from)} → ${c.label(e.item.to)}: ${e.error.message}`));
|
|
31
|
+
const n = r.done.length;
|
|
32
|
+
out.log(chalk.grey(` ${n} file${n === 1 ? '' : 's'} ${move ? 'moved' : 'copied'}, ${s.size(r.bytes)}${r.errors.length ? `, ${r.errors.length} failed${move ? ' (left in place)' : ''}` : ''}`));
|
|
33
|
+
out.result({
|
|
34
|
+
[move ? 'moved' : 'copied']: r.done.map((it) => ({ from: c.label(it.from), to: c.label(it.to), size: it.size })),
|
|
35
|
+
...(move ? { deleted } : {}),
|
|
36
|
+
failed: r.errors.map((e) => ({ from: c.label(e.item.from), to: c.label(e.item.to), error: e.error.message })),
|
|
37
|
+
});
|
|
38
|
+
return r.errors.length ? 1 : 0;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
module.exports.copy = copy;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// poad storage ls [bucket[/dossier]] [-r] [--json] : buckets, ou le contenu d'un dossier
|
|
2
|
+
module.exports = (args, raw) =>
|
|
3
|
+
require('../../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['recursive'], alias: { r: 'recursive', R: 'recursive' } }, async ({ opts, positionals, out }) => {
|
|
4
|
+
const s = require('../../utils/storage');
|
|
5
|
+
const { chalk } = out;
|
|
6
|
+
if (positionals.length > 1) throw require('../../utils/cloud/api').usageError('Usage: poad storage ls [bucket[/folder]] [-r]');
|
|
7
|
+
const target = await s.target(opts);
|
|
8
|
+
const api = s.client(target);
|
|
9
|
+
const date = s.when;
|
|
10
|
+
|
|
11
|
+
if (!positionals.length) {
|
|
12
|
+
const buckets = await api.buckets();
|
|
13
|
+
out.result({ buckets });
|
|
14
|
+
if (!buckets.length) return out.log(chalk.grey(' No bucket yet: create one in the console (Storage), or with the API.'));
|
|
15
|
+
const w = Math.max(...buckets.map((b) => b.id.length));
|
|
16
|
+
for (const b of buckets) out.log(` ${chalk.bold(b.id.padEnd(w))} ${b.public ? chalk.yellowBright('public ') : chalk.grey('private')} ${chalk.grey(date(b.updated_at || b.created_at))}`);
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const where = s.parseRemote(positionals[0]);
|
|
21
|
+
await api.bucket(where.bucket).catch((e) => {
|
|
22
|
+
throw e.status === 404 ? new (require('../../utils/cloud/api').CloudError)(`No bucket "${where.bucket}".`, { code: 'not_found' }) : e;
|
|
23
|
+
});
|
|
24
|
+
const rows = await api.list(where.bucket, where.key);
|
|
25
|
+
const exact = !where.dir && rows.find((o) => o.name === where.key);
|
|
26
|
+
const prefix = where.key ? `${where.key}/` : '';
|
|
27
|
+
let list;
|
|
28
|
+
if (exact) list = [{ kind: 'file', name: exact.name, size: Number(exact.metadata && exact.metadata.size) || 0, updated: exact.updated_at, type: exact.metadata && exact.metadata.mimetype }];
|
|
29
|
+
else if (opts.recursive) list = rows.filter((o) => o.name.startsWith(prefix)).map((o) => ({ kind: 'file', name: o.name.slice(prefix.length), size: Number(o.metadata && o.metadata.size) || 0, updated: o.updated_at, type: o.metadata && o.metadata.mimetype }));
|
|
30
|
+
else list = s.entries(rows, prefix);
|
|
31
|
+
out.result({ bucket: where.bucket, path: where.key, entries: list });
|
|
32
|
+
if (out.json) return;
|
|
33
|
+
if (!list.length) {
|
|
34
|
+
process.exitCode = where.key ? 1 : 0;
|
|
35
|
+
return out.log(chalk.grey(where.key ? ` ${s.show(where.bucket, where.key)}: no such file or folder` : ` Bucket "${where.bucket}" is empty.`));
|
|
36
|
+
}
|
|
37
|
+
const sizes = list.map((e) => s.size(e.size));
|
|
38
|
+
const sw = Math.max(...sizes.map((x) => x.length));
|
|
39
|
+
let total = 0;
|
|
40
|
+
let files = 0;
|
|
41
|
+
list.forEach((e, i) => {
|
|
42
|
+
total += e.size;
|
|
43
|
+
files += e.kind === 'folder' ? e.count : 1;
|
|
44
|
+
const name = e.kind === 'folder' ? chalk.cyanBright(`${e.name}/`) : e.name;
|
|
45
|
+
const extra = e.kind === 'folder' ? chalk.grey(`${e.count} file${e.count === 1 ? '' : 's'}`) : chalk.grey(e.type || '');
|
|
46
|
+
out.log(` ${sizes[i].padStart(sw)} ${chalk.grey(date(e.updated))} ${name} ${extra}`);
|
|
47
|
+
});
|
|
48
|
+
out.log(chalk.grey(` ${files} file${files === 1 ? '' : 's'}, ${s.size(total)}`));
|
|
49
|
+
});
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// poad storage mv <bucket/chemin> <bucket/chemin> [-r] [--json] : déplacer ou renommer dans le Stockage
|
|
2
|
+
// (copie puis suppression de la source ; une source dont la copie échoue reste en place).
|
|
3
|
+
// « poad: » devant les chemins est facultatif ici : les deux sont dans le Stockage.
|
|
4
|
+
module.exports = (args, raw) =>
|
|
5
|
+
require('../../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['recursive'], alias: { r: 'recursive', R: 'recursive' } }, ({ opts, positionals, out }) =>
|
|
6
|
+
require('./cp').copy({ opts, positionals, out, move: true }),
|
|
7
|
+
);
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// poad storage rm <bucket/chemin…> [-r] [--yes] [--json] : fichiers, ou tout un dossier avec -r
|
|
2
|
+
// Le contenu est retiré du backend (disque, S3, 1fichier) par le nettoyage du Stockage, une minute après.
|
|
3
|
+
module.exports = (args, raw) =>
|
|
4
|
+
require('../../utils/cloud/cli').run(raw, { values: ['env', 'project'], flags: ['recursive'], alias: { r: 'recursive', R: 'recursive' } }, async ({ opts, positionals, out }) => {
|
|
5
|
+
const s = require('../../utils/storage');
|
|
6
|
+
const cli = require('../../utils/cloud/cli');
|
|
7
|
+
const { usageError } = require('../../utils/cloud/api');
|
|
8
|
+
const { chalk } = out;
|
|
9
|
+
if (!positionals.length) throw usageError('Usage: poad storage rm <bucket/path…> [-r] [--yes]');
|
|
10
|
+
const target = await s.target(opts);
|
|
11
|
+
const api = s.client(target);
|
|
12
|
+
|
|
13
|
+
// Tout est résolu avant de supprimer quoi que ce soit : un chemin inconnu n'en laisse pas d'autres à moitié faits
|
|
14
|
+
const groups = [];
|
|
15
|
+
for (const p of positionals) {
|
|
16
|
+
const where = s.parseRemote(p);
|
|
17
|
+
if (!where.key && !opts.recursive) throw usageError(`${where.bucket}: a whole bucket needs -r (its files only; the bucket stays)`);
|
|
18
|
+
const r = await s.resolve(api, where, opts.recursive);
|
|
19
|
+
groups.push({ where, ...r });
|
|
20
|
+
}
|
|
21
|
+
const count = groups.reduce((n, g) => n + g.objects.length, 0);
|
|
22
|
+
if (groups.some((g) => g.kind === 'folder')) {
|
|
23
|
+
const what = groups.map((g) => `${s.show(g.where.bucket, g.where.key)}${g.kind === 'folder' ? '/' : ''}`).join(', ');
|
|
24
|
+
await cli.confirm(`Delete ${count} file${count === 1 ? '' : 's'} (${what}) on the ${target.label}? This cannot be undone.`, { yes: opts.yes, json: out.json });
|
|
25
|
+
}
|
|
26
|
+
const removed = [];
|
|
27
|
+
for (const g of groups) {
|
|
28
|
+
const keys = g.objects.map((o) => o.name);
|
|
29
|
+
for (let i = 0; i < keys.length; i += 1000) {
|
|
30
|
+
const rows = await api.remove(g.where.bucket, keys.slice(i, i + 1000));
|
|
31
|
+
for (const r of rows || []) {
|
|
32
|
+
removed.push(s.show(g.where.bucket, r.name));
|
|
33
|
+
if (g.kind === 'file') out.log(` ${chalk.greenBright('✔')} ${s.show(g.where.bucket, r.name)} ${chalk.grey('deleted')}`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
if (g.kind === 'folder') out.log(` ${chalk.greenBright('✔')} ${s.show(g.where.bucket, g.where.key)}/ ${chalk.grey(`${keys.length} file${keys.length === 1 ? '' : 's'} deleted`)}`);
|
|
37
|
+
}
|
|
38
|
+
out.result({ deleted: removed });
|
|
39
|
+
});
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
const { test } = require('node:test');
|
|
2
|
+
const assert = require('node:assert');
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const os = require('os');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const s = require('../utils/storage');
|
|
7
|
+
const c = require('../utils/storage-copy');
|
|
8
|
+
|
|
9
|
+
test('parseRemote: bucket, key, folder', () => {
|
|
10
|
+
assert.deepStrictEqual(s.parseRemote('poad:images/a/b.png'), { bucket: 'images', key: 'a/b.png', dir: false });
|
|
11
|
+
assert.deepStrictEqual(s.parseRemote('poad://images/'), { bucket: 'images', key: '', dir: true });
|
|
12
|
+
assert.deepStrictEqual(s.parseRemote('images'), { bucket: 'images', key: '', dir: true });
|
|
13
|
+
assert.deepStrictEqual(s.parseRemote('images/2024/'), { bucket: 'images', key: '2024', dir: true });
|
|
14
|
+
assert.deepStrictEqual(s.parseRemote('images//a//b'), { bucket: 'images', key: 'a/b', dir: false });
|
|
15
|
+
assert.throws(() => s.parseRemote('poad:'), /storage path/);
|
|
16
|
+
assert.throws(() => s.parseRemote('images/../x'), /not allowed/);
|
|
17
|
+
assert.throws(() => s.parseRemote('bad name/x'), /not a bucket/);
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
test('isRemote, size, joinKey, mimeOf', () => {
|
|
21
|
+
assert.ok(s.isRemote('poad:a/b'));
|
|
22
|
+
assert.ok(!s.isRemote('./poad:a'));
|
|
23
|
+
assert.strictEqual(s.size(0), '0 B');
|
|
24
|
+
assert.strictEqual(s.size(1536), '1.5 KB');
|
|
25
|
+
assert.strictEqual(s.size(3 * 1024 * 1024), '3.0 MB');
|
|
26
|
+
assert.strictEqual(s.joinKey('', 'a.png'), 'a.png');
|
|
27
|
+
assert.strictEqual(s.joinKey('x/', 'a.png'), 'x/a.png');
|
|
28
|
+
assert.strictEqual(s.mimeOf('A.PNG'), 'image/png');
|
|
29
|
+
assert.strictEqual(s.mimeOf('data.unknown'), 'application/octet-stream');
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
test('entries: folders first with count and size, then files', () => {
|
|
33
|
+
const o = (name, size) => ({ name, metadata: { size }, updated_at: '2026-12-01T10:00:00Z' });
|
|
34
|
+
const list = s.entries([o('a.txt', 3), o('site/index.html', 10), o('site/css/s.css', 5), o('data/x', 1), o('other', 9)], '');
|
|
35
|
+
assert.deepStrictEqual(list.map((e) => `${e.kind}:${e.name}`), ['folder:data', 'folder:site', 'file:a.txt', 'file:other']);
|
|
36
|
+
assert.strictEqual(list[1].count, 2);
|
|
37
|
+
assert.strictEqual(list[1].size, 15);
|
|
38
|
+
assert.deepStrictEqual(s.entries([o('site/index.html', 1), o('site/css/s.css', 1), o('sitemap', 1)], 'site/').map((e) => e.name), ['css', 'index.html']);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
// Faux Stockage en mémoire, derrière un fetch : les routes que le CLI appelle
|
|
42
|
+
function fakeStorage(initial = {}) {
|
|
43
|
+
const objects = new Map(Object.entries(initial));
|
|
44
|
+
const seen = [];
|
|
45
|
+
const doFetch = async (url, init = {}) => {
|
|
46
|
+
const u = new URL(url);
|
|
47
|
+
const route = decodeURIComponent(u.pathname.replace('/storage/v1', ''));
|
|
48
|
+
seen.push({ method: init.method, route, auth: init.headers.authorization });
|
|
49
|
+
const json = (status, body) => new Response(body === undefined ? null : JSON.stringify(body), { status });
|
|
50
|
+
let m;
|
|
51
|
+
if ((m = /^\/object\/list\/([^/]+)$/.exec(route))) {
|
|
52
|
+
const { prefix, limit, offset } = JSON.parse(init.body);
|
|
53
|
+
const rows = [...objects.keys()]
|
|
54
|
+
.filter((k) => k.startsWith(`${m[1]}/${prefix}`))
|
|
55
|
+
.sort()
|
|
56
|
+
.slice(offset, offset + limit)
|
|
57
|
+
.map((k) => ({ name: k.slice(m[1].length + 1), metadata: { size: objects.get(k).body.length, mimetype: objects.get(k).type }, updated_at: '2026-12-01T10:00:00Z' }));
|
|
58
|
+
return json(200, rows);
|
|
59
|
+
}
|
|
60
|
+
if ((m = /^\/object\/([^/]+)$/.exec(route)) && init.method === 'DELETE') {
|
|
61
|
+
const { prefixes } = JSON.parse(init.body);
|
|
62
|
+
const gone = prefixes.filter((p) => objects.delete(`${m[1]}/${p}`)).map((name) => ({ name }));
|
|
63
|
+
return json(200, gone);
|
|
64
|
+
}
|
|
65
|
+
if ((m = /^\/object\/(.+)$/.exec(route))) {
|
|
66
|
+
if (init.method === 'PUT') {
|
|
67
|
+
const chunks = [];
|
|
68
|
+
for await (const ch of init.body) chunks.push(Buffer.from(ch));
|
|
69
|
+
objects.set(m[1], { body: Buffer.concat(chunks), type: init.headers['content-type'] });
|
|
70
|
+
return json(201, { name: m[1] });
|
|
71
|
+
}
|
|
72
|
+
const o = objects.get(m[1]);
|
|
73
|
+
if (!o) return json(404, { message: 'objet introuvable' });
|
|
74
|
+
return new Response(o.body, { status: 200, headers: { 'content-type': `${o.type}; charset=utf-8` } });
|
|
75
|
+
}
|
|
76
|
+
return json(404, { message: 'route inconnue' });
|
|
77
|
+
};
|
|
78
|
+
const obj = (body, type = 'text/plain') => ({ body: Buffer.from(body), type });
|
|
79
|
+
return { objects, seen, doFetch, obj };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const filled = () => {
|
|
83
|
+
const f = fakeStorage();
|
|
84
|
+
f.objects.set('img/a.png', f.obj('AAA', 'image/png'));
|
|
85
|
+
f.objects.set('img/2024/b.png', f.obj('BB', 'image/png'));
|
|
86
|
+
f.objects.set('img/2024/sub/c.png', f.obj('C', 'image/png'));
|
|
87
|
+
return f;
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
test('client: list pages, sends the key only in headers', async () => {
|
|
91
|
+
const f = filled();
|
|
92
|
+
const api = s.client({ base: 'http://localhost:1', key: 'secret-key', fetch: f.doFetch });
|
|
93
|
+
const rows = await api.list('img', '2024/');
|
|
94
|
+
assert.deepStrictEqual(rows.map((r) => r.name), ['2024/b.png', '2024/sub/c.png']);
|
|
95
|
+
assert.ok(f.seen.every((x) => x.auth === 'Bearer secret-key' && !x.route.includes('secret-key')));
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
test('client: an HTTP error becomes a message, never the key', async () => {
|
|
99
|
+
const api = s.client({ base: 'http://localhost:1', key: 'secret-key', fetch: async () => new Response(JSON.stringify({ message: 'invalid token' }), { status: 401 }) });
|
|
100
|
+
await assert.rejects(api.buckets(), (e) => /refused by the storage \(HTTP 401\)/.test(e.message) && !e.message.includes('secret-key'));
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
test('resolve: file, folder needs -r, unknown path', async () => {
|
|
104
|
+
const f = filled();
|
|
105
|
+
const api = s.client({ base: 'http://x', key: 'k', fetch: f.doFetch });
|
|
106
|
+
assert.strictEqual((await s.resolve(api, s.parseRemote('img/a.png'), false)).kind, 'file');
|
|
107
|
+
await assert.rejects(s.resolve(api, s.parseRemote('img/2024'), false), /is a folder: add -r/);
|
|
108
|
+
const r = await s.resolve(api, s.parseRemote('img/2024'), true);
|
|
109
|
+
assert.strictEqual(r.objects.length, 2);
|
|
110
|
+
await assert.rejects(s.resolve(api, s.parseRemote('img/none'), true), /no such file or folder/);
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
test('plan and run: storage → storage keeps the base name and the original type', async () => {
|
|
114
|
+
const f = filled();
|
|
115
|
+
const api = s.client({ base: 'http://x', key: 'k', fetch: f.doFetch });
|
|
116
|
+
const { items } = await c.plan(api, 'poad:img/2024', 'poad:archive/', { recursive: true });
|
|
117
|
+
assert.deepStrictEqual(items.map((i) => i.to.key).sort(), ['2024/b.png', '2024/sub/c.png']);
|
|
118
|
+
const r = await c.run(api, items);
|
|
119
|
+
assert.strictEqual(r.errors.length, 0);
|
|
120
|
+
assert.strictEqual(r.bytes, 3);
|
|
121
|
+
assert.strictEqual(f.objects.get('archive/2024/sub/c.png').type, 'image/png');
|
|
122
|
+
// Renommer un fichier : la destination est le nouveau nom
|
|
123
|
+
const one = await c.plan(api, 'poad:img/a.png', 'poad:img/z.png');
|
|
124
|
+
assert.strictEqual(one.items[0].to.key, 'z.png');
|
|
125
|
+
// Copie dans elle-même refusée
|
|
126
|
+
await assert.rejects(c.plan(api, 'poad:img/2024', 'poad:img/2024/', { recursive: true }), /inside/);
|
|
127
|
+
// Les deux chemins sur le disque : refusé
|
|
128
|
+
await assert.rejects(c.plan(api, 'a', 'b'), /must be in the storage/);
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
test('plan and run: disk ↔ storage', async () => {
|
|
132
|
+
const f = fakeStorage();
|
|
133
|
+
const api = s.client({ base: 'http://x', key: 'k', fetch: f.doFetch });
|
|
134
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'poad-storage-'));
|
|
135
|
+
try {
|
|
136
|
+
fs.mkdirSync(path.join(dir, 'site', 'css'), { recursive: true });
|
|
137
|
+
fs.writeFileSync(path.join(dir, 'site', 'index.html'), '<h1>x</h1>');
|
|
138
|
+
fs.writeFileSync(path.join(dir, 'site', 'css', 's.css'), 'body{}');
|
|
139
|
+
await assert.rejects(c.plan(api, path.join(dir, 'site'), 'poad:web/'), /is a folder: add -r/);
|
|
140
|
+
const up = await c.plan(api, path.join(dir, 'site'), 'poad:web/', { recursive: true });
|
|
141
|
+
await c.run(api, up.items);
|
|
142
|
+
assert.deepStrictEqual([...f.objects.keys()].sort(), ['web/site/css/s.css', 'web/site/index.html']);
|
|
143
|
+
assert.strictEqual(f.objects.get('web/site/css/s.css').type, 'text/css');
|
|
144
|
+
// Dossier existant dans le Stockage : la source y entre sous son nom
|
|
145
|
+
const again = await c.plan(api, path.join(dir, 'site', 'index.html'), 'poad:web/site');
|
|
146
|
+
assert.strictEqual(again.items[0].to.key, 'site/index.html');
|
|
147
|
+
// Retour sur le disque, dans un dossier qui existe
|
|
148
|
+
const out = path.join(dir, 'out');
|
|
149
|
+
fs.mkdirSync(out);
|
|
150
|
+
const down = await c.plan(api, 'poad:web/site', out, { recursive: true });
|
|
151
|
+
const r = await c.run(api, down.items);
|
|
152
|
+
assert.strictEqual(r.errors.length, 0);
|
|
153
|
+
assert.strictEqual(fs.readFileSync(path.join(out, 'site', 'css', 's.css'), 'utf8'), 'body{}');
|
|
154
|
+
assert.ok(!fs.existsSync(path.join(out, 'site', 'css', 's.css.poad-part')));
|
|
155
|
+
} finally {
|
|
156
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
157
|
+
}
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
test('each: runs everything, collects errors', async () => {
|
|
161
|
+
const done = [];
|
|
162
|
+
const errors = await s.each([1, 2, 3, 4, 5], async (n) => {
|
|
163
|
+
if (n === 3) throw new Error('boom');
|
|
164
|
+
done.push(n);
|
|
165
|
+
}, 2);
|
|
166
|
+
assert.deepStrictEqual(done.sort(), [1, 2, 4, 5]);
|
|
167
|
+
assert.strictEqual(errors.length, 1);
|
|
168
|
+
assert.strictEqual(errors[0].item, 3);
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
test('client: hosted, anon key for the gateway, storage token renewed before it expires', async () => {
|
|
172
|
+
const seen = [];
|
|
173
|
+
const doFetch = async (url, init) => (seen.push([init.headers.apikey, init.headers.authorization]), new Response('[]', { status: 200 }));
|
|
174
|
+
let asked = 0;
|
|
175
|
+
const soon = new Date(Date.now() + 30000).toISOString();
|
|
176
|
+
const later = new Date(Date.now() + 900000).toISOString();
|
|
177
|
+
const api = s.client({ base: 'https://p.example.com', key: 'tok1', apikey: 'anon', fetch: doFetch, renew: { first: soon, next: async () => (asked++, { token: 'tok2', anon_key: 'anon', expires_at: later }) } });
|
|
178
|
+
await api.buckets();
|
|
179
|
+
await api.buckets();
|
|
180
|
+
assert.strictEqual(asked, 1);
|
|
181
|
+
assert.deepStrictEqual(seen, [['anon', 'Bearer tok2'], ['anon', 'Bearer tok2']]);
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
test('target: --env or --project goes to poad.io, else the local engine', async () => {
|
|
185
|
+
await assert.rejects(s.target({}, { started: async () => true }), /not in a poad project|service_role|started/);
|
|
186
|
+
});
|
package/utils/help-details.js
CHANGED
|
@@ -117,6 +117,33 @@ const sheets = {
|
|
|
117
117
|
],
|
|
118
118
|
notes: ['Everything combines: poad logs flows run=dafb44e1 step=call level=warn -f'],
|
|
119
119
|
},
|
|
120
|
+
storage: {
|
|
121
|
+
usage: ['poad storage ls [bucket[/folder]] [-r]', 'poad storage cp <source> <destination> [-r]', 'poad storage mv <bucket/path> <bucket/path> [-r]', 'poad storage rm <bucket/path…> [-r] [--yes]'],
|
|
122
|
+
text: [
|
|
123
|
+
'Files of the project storage, local engine (poad start) or poad.io (--env), whatever its backend: engine disk, S3 or 1fichier. A storage path is bucket/path; folders exist through their files ("a/b/c.png"), as in the console. For cp, write a storage path poad:bucket/path so that it is not taken for a file of the disk.',
|
|
124
|
+
],
|
|
125
|
+
options: [
|
|
126
|
+
['ls', 'buckets; ls <bucket[/folder]>: its folders (files, size) then its files'],
|
|
127
|
+
['cp ./a.png poad:images/', 'disk → storage; a destination ending with "/", a bucket alone or an existing folder keeps the source name'],
|
|
128
|
+
['cp poad:images/a.png ./', 'storage → disk'],
|
|
129
|
+
['cp poad:images/a.png poad:backup/a.png', 'storage → storage'],
|
|
130
|
+
['mv', 'move or rename inside the storage: copy, then delete each source copied (a failed copy leaves its source in place)'],
|
|
131
|
+
['rm', 'delete files; a folder or a whole bucket needs -r and a confirmation (the bucket itself stays)'],
|
|
132
|
+
['-r', 'folders, recursively'],
|
|
133
|
+
['--env <name>', 'the storage of a poad.io environment of the linked project (main: production) instead of the local engine'],
|
|
134
|
+
['--project <id>', 'another poad.io project (poad login); with --env for one of its environments'],
|
|
135
|
+
['--yes', 'no question (required outside a terminal for rm -r)'],
|
|
136
|
+
['--json', 'the result as JSON'],
|
|
137
|
+
],
|
|
138
|
+
notes: [
|
|
139
|
+
'Transfers stream through the CLI (4 at a time). Local engine: the service_role key of poad/config.toml, never shown. poad.io: a storage token of 15 minutes given to the owner (renewed during long transfers), never the service_role key. A file already there is replaced. Every request is logged by the storage service: poad logs storage.',
|
|
140
|
+
'Deleted content leaves the backend a minute later (storage sweeper).',
|
|
141
|
+
],
|
|
142
|
+
},
|
|
143
|
+
'storage ls': { usage: ['poad storage ls [bucket[/folder]] [-r] [--json]'], text: ['Buckets, or the folders then files of a folder (-r: every file under it, full path).'] },
|
|
144
|
+
'storage cp': { usage: ['poad storage cp <source> <destination> [-r] [--json]'], text: ['Copy between the disk and the storage, or inside the storage. A storage path is written poad:bucket/path. Example: poad storage cp -r ./site poad:web/'] },
|
|
145
|
+
'storage mv': { usage: ['poad storage mv <bucket/path> <bucket/path> [-r] [--json]'], text: ['Move or rename inside the storage: copy, then delete each source copied.'] },
|
|
146
|
+
'storage rm': { usage: ['poad storage rm <bucket/path…> [-r] [--yes] [--json]'], text: ['Delete files; -r for a folder or every file of a bucket, after a confirmation (--yes outside a terminal).'] },
|
|
120
147
|
functions: {
|
|
121
148
|
usage: ['poad functions new <name>', 'poad functions list', 'poad functions types'],
|
|
122
149
|
text: [
|
package/utils/runner.js
CHANGED
|
@@ -19,7 +19,7 @@ const mail = require('./mail');
|
|
|
19
19
|
const valkey = require('./valkey');
|
|
20
20
|
|
|
21
21
|
// Version de l'image par défaut (aussi dans package.json, champ "runner")
|
|
22
|
-
const RUNNER_VERSION = '0.
|
|
22
|
+
const RUNNER_VERSION = '0.3.0';
|
|
23
23
|
const NAMES = ['runner'];
|
|
24
24
|
const ALIAS = 'runner';
|
|
25
25
|
const DOCKER_SOCKET = '/var/run/docker.sock';
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// Copie pour poad storage cp et mv : plan (quoi va où), puis transferts en flux.
|
|
2
|
+
//
|
|
3
|
+
// Règles, comme cp -r :
|
|
4
|
+
// - une source dossier (du disque ou du Stockage) demande -r ;
|
|
5
|
+
// - une destination qui finit par « / », un bucket seul, ou un dossier qui existe déjà
|
|
6
|
+
// reçoit la source sous son nom de base ; sinon la destination est le nouveau nom.
|
|
7
|
+
const fs = require('fs');
|
|
8
|
+
const path = require('path');
|
|
9
|
+
const { Readable } = require('stream');
|
|
10
|
+
const { pipeline } = require('stream/promises');
|
|
11
|
+
const { CloudError, usageError } = require('./cloud/api');
|
|
12
|
+
const s = require('./storage');
|
|
13
|
+
|
|
14
|
+
const base = (key, bucket) => (key ? key.split('/').pop() : bucket);
|
|
15
|
+
|
|
16
|
+
/** Le dossier du Stockage existe-t-il (au moins un fichier dessous) ? */
|
|
17
|
+
async function remoteFolder(api, { bucket, key }) {
|
|
18
|
+
if (!key) return true;
|
|
19
|
+
const rows = await api.list(bucket, `${key}/`);
|
|
20
|
+
return rows.length > 0;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Plan : { items: [{ from, to, size }], kind } ; from/to : { local } ou { bucket, key }.
|
|
25
|
+
* api : client du Stockage ; src/dst : mots tapés.
|
|
26
|
+
*/
|
|
27
|
+
async function plan(api, srcText, dstText, { recursive = false, remoteOnly = false } = {}) {
|
|
28
|
+
const srcRemote = remoteOnly || s.isRemote(srcText);
|
|
29
|
+
const dstRemote = remoteOnly || s.isRemote(dstText);
|
|
30
|
+
if (!srcRemote && !dstRemote) throw usageError('One of the two paths must be in the storage: write it poad:bucket/path (poad storage cp ./a.png poad:photos/).');
|
|
31
|
+
const items = [];
|
|
32
|
+
|
|
33
|
+
if (!srcRemote) {
|
|
34
|
+
// Disque → Stockage
|
|
35
|
+
const src = path.resolve(String(srcText));
|
|
36
|
+
let st;
|
|
37
|
+
try {
|
|
38
|
+
st = fs.statSync(src);
|
|
39
|
+
} catch {
|
|
40
|
+
throw new CloudError(`${srcText}: no such file or folder`, { code: 'not_found' });
|
|
41
|
+
}
|
|
42
|
+
const dst = s.parseRemote(dstText);
|
|
43
|
+
if (st.isDirectory()) {
|
|
44
|
+
if (!recursive) throw usageError(`${srcText} is a folder: add -r`);
|
|
45
|
+
const into = dst.dir || (await remoteFolder(api, dst)) ? s.joinKey(dst.key, path.basename(src)) : dst.key;
|
|
46
|
+
for (const rel of s.walk(src)) {
|
|
47
|
+
const file = path.join(src, ...rel.split('/'));
|
|
48
|
+
items.push({ from: { local: file }, to: { bucket: dst.bucket, key: s.joinKey(into, rel) }, size: fs.statSync(file).size });
|
|
49
|
+
}
|
|
50
|
+
if (!items.length) throw new CloudError(`${srcText}: empty folder, nothing to copy`, { code: 'empty' });
|
|
51
|
+
return { items, kind: 'folder' };
|
|
52
|
+
}
|
|
53
|
+
if (!st.isFile()) throw usageError(`${srcText} is not a file`);
|
|
54
|
+
const key = dst.dir || (await remoteFolder(api, dst)) ? s.joinKey(dst.key, path.basename(src)) : dst.key;
|
|
55
|
+
items.push({ from: { local: src }, to: { bucket: dst.bucket, key }, size: st.size });
|
|
56
|
+
return { items, kind: 'file' };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const src = s.parseRemote(srcText);
|
|
60
|
+
const found = await s.resolve(api, src, recursive);
|
|
61
|
+
const name = base(found.base, src.bucket);
|
|
62
|
+
const relOf = (o) => (found.base ? o.name.slice(found.base.length + 1) : o.name);
|
|
63
|
+
const sizeOf = (o) => Number(o.metadata && o.metadata.size) || 0;
|
|
64
|
+
// Le type d'origine (fiche de l'objet), pas celui de la réponse HTTP (qui peut gagner « ; charset=… »)
|
|
65
|
+
const typeOf = (o) => (o.metadata && o.metadata.mimetype) || undefined;
|
|
66
|
+
|
|
67
|
+
if (!dstRemote) {
|
|
68
|
+
// Stockage → disque
|
|
69
|
+
const dst = path.resolve(String(dstText));
|
|
70
|
+
const isDir = String(dstText).endsWith('/') || String(dstText).endsWith(path.sep) || (fs.existsSync(dst) && fs.statSync(dst).isDirectory());
|
|
71
|
+
if (found.kind === 'file') {
|
|
72
|
+
items.push({ from: { bucket: src.bucket, key: found.objects[0].name }, to: { local: isDir ? path.join(dst, name) : dst }, size: sizeOf(found.objects[0]) });
|
|
73
|
+
} else {
|
|
74
|
+
const into = isDir ? path.join(dst, name) : dst;
|
|
75
|
+
for (const o of found.objects) items.push({ from: { bucket: src.bucket, key: o.name }, to: { local: path.join(into, ...relOf(o).split('/')) }, size: sizeOf(o) });
|
|
76
|
+
}
|
|
77
|
+
return { items, kind: found.kind };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Stockage → Stockage
|
|
81
|
+
const dst = s.parseRemote(dstText);
|
|
82
|
+
const isDir = dst.dir || (await remoteFolder(api, dst));
|
|
83
|
+
if (found.kind === 'file') {
|
|
84
|
+
items.push({ from: { bucket: src.bucket, key: found.objects[0].name }, to: { bucket: dst.bucket, key: isDir ? s.joinKey(dst.key, name) : dst.key }, size: sizeOf(found.objects[0]), type: typeOf(found.objects[0]) });
|
|
85
|
+
} else {
|
|
86
|
+
const into = isDir ? s.joinKey(dst.key, name) : dst.key;
|
|
87
|
+
if (dst.bucket === src.bucket && (into === found.base || (found.base ? into.startsWith(`${found.base}/`) : true)))
|
|
88
|
+
throw usageError(`${s.show(dst.bucket, into)} is inside ${s.show(src.bucket, found.base)}: choose another destination`);
|
|
89
|
+
for (const o of found.objects) items.push({ from: { bucket: src.bucket, key: o.name }, to: { bucket: dst.bucket, key: s.joinKey(into, relOf(o)) }, size: sizeOf(o), type: typeOf(o) });
|
|
90
|
+
}
|
|
91
|
+
for (const it of items) {
|
|
92
|
+
if (it.from.bucket === it.to.bucket && it.from.key === it.to.key) throw usageError(`${s.show(it.from.bucket, it.from.key)}: source and destination are the same`);
|
|
93
|
+
}
|
|
94
|
+
return { items, kind: found.kind };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Un bout de la copie, lisible : chemin relatif s'il est sous le dossier courant, sinon absolu */
|
|
98
|
+
const label = (end) => {
|
|
99
|
+
if (end.local === undefined) return s.show(end.bucket, end.key);
|
|
100
|
+
const rel = path.relative(process.cwd(), end.local);
|
|
101
|
+
return rel && !rel.startsWith('..') && !path.isAbsolute(rel) ? rel : end.local;
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
/** Un transfert, en flux ; rend le nombre d'octets */
|
|
105
|
+
async function transfer(api, { from, to, size, type }) {
|
|
106
|
+
if (from.local !== undefined) {
|
|
107
|
+
await api.put(to.bucket, to.key, fs.createReadStream(from.local), { type: s.mimeOf(from.local) });
|
|
108
|
+
return size;
|
|
109
|
+
}
|
|
110
|
+
const res = await api.get(from.bucket, from.key);
|
|
111
|
+
if (to.local !== undefined) {
|
|
112
|
+
fs.mkdirSync(path.dirname(to.local), { recursive: true });
|
|
113
|
+
// Écrit à côté puis renomme : jamais de fichier à moitié écrit sous le nom final
|
|
114
|
+
const tmp = `${to.local}.poad-part`;
|
|
115
|
+
try {
|
|
116
|
+
await pipeline(Readable.fromWeb(res.body), fs.createWriteStream(tmp));
|
|
117
|
+
fs.renameSync(tmp, to.local);
|
|
118
|
+
} catch (e) {
|
|
119
|
+
fs.rmSync(tmp, { force: true });
|
|
120
|
+
throw e;
|
|
121
|
+
}
|
|
122
|
+
return fs.statSync(to.local).size;
|
|
123
|
+
}
|
|
124
|
+
await api.put(to.bucket, to.key, res.body, { type: type || res.headers.get('content-type') || 'application/octet-stream' });
|
|
125
|
+
return size;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Exécute le plan ; rend { done: [item], errors: [{ item, error }], bytes } */
|
|
129
|
+
async function run(api, items, { onDone } = {}) {
|
|
130
|
+
const done = [];
|
|
131
|
+
let bytes = 0;
|
|
132
|
+
const errors = await s.each(items, async (item) => {
|
|
133
|
+
const n = await transfer(api, item);
|
|
134
|
+
bytes += n || 0;
|
|
135
|
+
done.push(item);
|
|
136
|
+
if (onDone) onDone(item);
|
|
137
|
+
});
|
|
138
|
+
return { done, errors, bytes };
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
module.exports = { plan, run, transfer, label };
|
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 };
|