poad 2.61.2 → 2.64.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 +12 -1
- package/package.json +2 -2
- package/poad.js +2 -2
- package/project/auth/import.js +68 -0
- package/project/auth/index.js +7 -0
- package/project/cli.js +11 -3
- package/project/db/import.js +138 -0
- package/project/db/index.js +1 -0
- package/project/deploy.js +4 -0
- package/project/logs.js +2 -0
- package/project/source.js +444 -0
- package/project/sources.js +2 -0
- package/project/storage/cp.js +48 -16
- package/project/storage/ls.js +20 -6
- package/project/storage/mv.js +5 -5
- package/project/storage/sync.js +101 -0
- package/test/auth-import.test.js +113 -0
- package/test/cloud.test.js +1 -0
- package/test/data.test.js +24 -0
- package/test/deps.test.js +108 -0
- package/test/import.test.js +210 -0
- package/test/logs.test.js +12 -0
- package/test/naming.test.js +18 -0
- package/test/source.test.js +282 -0
- package/test/storage-sync.test.js +283 -0
- package/test/storage-tus.test.js +169 -0
- package/test/storage.test.js +240 -4
- package/utils/auth-import.js +204 -0
- package/utils/cloud/bundle.js +18 -4
- package/utils/cloud/deps.js +297 -0
- package/utils/data.js +41 -0
- package/utils/help-details.js +113 -5
- package/utils/import-upload.js +112 -0
- package/utils/logline.js +2 -2
- package/utils/logs.js +8 -1
- package/utils/naming.js +41 -0
- package/utils/runner.js +1 -1
- package/utils/storage-copy.js +122 -18
- package/utils/storage-sync.js +277 -0
- package/utils/storage-tus.js +201 -0
- package/utils/storage.js +130 -3
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
// poad storage cp : envoi en morceaux reprenables (TUS 1.0, storage 0.6.0+) au-delà de 6 Mio.
|
|
2
|
+
//
|
|
3
|
+
// - morceaux de 6 Mio : sous la limite d'une requête de poad.io (100 Mo) et de toute passerelle ;
|
|
4
|
+
// - coupure réseau : HEAD (où en est le serveur ?) puis reprise, jusqu'à 6 essais par morceau ;
|
|
5
|
+
// - commande interrompue (Ctrl-C, panne) : l'adresse de l'envoi est gardée dans ~/.poad/uploads.json
|
|
6
|
+
// (jamais de clé ni de jeton), et la même commande reprend là où le serveur en est ;
|
|
7
|
+
// - serveur qui ne connaît pas TUS (engine plus ancien) : envoi en une requête, comme avant.
|
|
8
|
+
//
|
|
9
|
+
// Aucune dépendance : fetch de Node.
|
|
10
|
+
const fs = require('fs');
|
|
11
|
+
const os = require('os');
|
|
12
|
+
const path = require('path');
|
|
13
|
+
const crypto = require('crypto');
|
|
14
|
+
const { CloudError } = require('./cloud/api');
|
|
15
|
+
|
|
16
|
+
const CHUNK = 6 * 1024 * 1024;
|
|
17
|
+
const TUS = '1.0.0';
|
|
18
|
+
const RETRIES = 6;
|
|
19
|
+
const KEEP_MS = 24 * 3600 * 1000;
|
|
20
|
+
|
|
21
|
+
const stateFile = () => process.env.POAD_UPLOADS_FILE || path.join(os.homedir(), '.poad', 'uploads.json');
|
|
22
|
+
|
|
23
|
+
/** Envois gardés pour reprise : { clé: { id, at } }, ceux de plus de 24 h oubliés */
|
|
24
|
+
function readState() {
|
|
25
|
+
try {
|
|
26
|
+
const all = JSON.parse(fs.readFileSync(stateFile(), 'utf8'));
|
|
27
|
+
const now = Date.now();
|
|
28
|
+
return Object.fromEntries(Object.entries(all).filter(([, v]) => v && typeof v.id === 'string' && now - Number(v.at) < KEEP_MS));
|
|
29
|
+
} catch {
|
|
30
|
+
return {};
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function writeState(change) {
|
|
34
|
+
const all = change(readState());
|
|
35
|
+
try {
|
|
36
|
+
fs.mkdirSync(path.dirname(stateFile()), { recursive: true });
|
|
37
|
+
const tmp = `${stateFile()}.${process.pid}.tmp`;
|
|
38
|
+
fs.writeFileSync(tmp, JSON.stringify(all, null, 2), { mode: 0o600 });
|
|
39
|
+
fs.renameSync(tmp, stateFile());
|
|
40
|
+
} catch {}
|
|
41
|
+
}
|
|
42
|
+
const remember = (key, id) => writeState((s) => ({ ...s, [key]: { id, at: Date.now() } }));
|
|
43
|
+
const forget = (key) =>
|
|
44
|
+
writeState((s) => {
|
|
45
|
+
delete s[key];
|
|
46
|
+
return s;
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
/** Clé de reprise : même engine, même destination, même fichier (taille, date). Pure. */
|
|
50
|
+
const resumeKey = ({ base, bucket, key, size, mtimeMs }) => crypto.createHash('sha256').update(JSON.stringify([base, bucket, key, size, Math.round(mtimeMs || 0)])).digest('hex').slice(0, 32);
|
|
51
|
+
|
|
52
|
+
const b64 = (v) => Buffer.from(String(v)).toString('base64');
|
|
53
|
+
/** Upload-Metadata. Pure. */
|
|
54
|
+
const metadata = ({ bucket, key, type, cacheControl }) =>
|
|
55
|
+
[['bucketName', bucket], ['objectName', key], ['contentType', type || 'application/octet-stream'], ...(cacheControl ? [['cacheControl', cacheControl]] : [])].map(([k, v]) => `${k} ${b64(v)}`).join(',');
|
|
56
|
+
|
|
57
|
+
const idOf = (location) => {
|
|
58
|
+
const m = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/?$/i.exec(location || '');
|
|
59
|
+
return m ? m[1] : null;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
async function failure(res) {
|
|
63
|
+
let message = `HTTP ${res.status}`;
|
|
64
|
+
try {
|
|
65
|
+
const b = await res.json();
|
|
66
|
+
if (b && (b.message || b.error)) message = String(b.message || b.error);
|
|
67
|
+
} catch {}
|
|
68
|
+
return new CloudError(message, { status: res.status, code: res.status === 404 ? 'not_found' : 'error' });
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Le serveur ne connaît pas les envois en morceaux (engine sans storage 0.6.0) */
|
|
72
|
+
const unknown = (res, message) => res.status === 405 || (res.status === 404 && /route inconnue|route not found/i.test(message));
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Envoie un contenu en morceaux. api.raw(method, route, { headers, body }) : réponse fetch brute.
|
|
76
|
+
* source.size, source.read(offset, length) → Buffer (fichier du disque : n'importe quel offset ;
|
|
77
|
+
* flux : dans l'ordre), source.resumable (un fichier du disque : reprise d'une commande à l'autre)
|
|
78
|
+
* opts : { bucket, key, type, cacheControl, upsert, base, mtimeMs, onResume(offset), sleep }
|
|
79
|
+
* Rend { resumedFrom } ; lève CloudError { code: 'tus_unsupported' } si le serveur ne connaît pas TUS.
|
|
80
|
+
*/
|
|
81
|
+
async function tusUpload(api, source, opts) {
|
|
82
|
+
const sleep = opts.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
83
|
+
const base = { 'tus-resumable': TUS };
|
|
84
|
+
const total = source.size;
|
|
85
|
+
const rkey = source.resumable ? resumeKey({ base: opts.base, bucket: opts.bucket, key: opts.key, size: total, mtimeMs: opts.mtimeMs }) : null;
|
|
86
|
+
let id = rkey ? (readState()[rkey] || {}).id : null;
|
|
87
|
+
let offset = 0;
|
|
88
|
+
let resumedFrom = null;
|
|
89
|
+
if (id) {
|
|
90
|
+
const h = await api.raw('HEAD', `/upload/resumable/${id}`, { headers: base });
|
|
91
|
+
if (h.status === 200 && Number(h.headers.get('upload-length')) === total) {
|
|
92
|
+
offset = Number(h.headers.get('upload-offset') || 0);
|
|
93
|
+
resumedFrom = offset;
|
|
94
|
+
if (opts.onResume) opts.onResume(offset);
|
|
95
|
+
} else {
|
|
96
|
+
forget(rkey);
|
|
97
|
+
id = null;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
if (!id) {
|
|
101
|
+
const res = await api.raw('POST', '/upload/resumable', {
|
|
102
|
+
headers: { ...base, 'upload-length': String(total), 'upload-metadata': metadata(opts), ...(opts.upsert ? { 'x-upsert': 'true' } : {}) },
|
|
103
|
+
});
|
|
104
|
+
if (res.status !== 201) {
|
|
105
|
+
const e = await failure(res);
|
|
106
|
+
if (unknown(res, e.message)) throw new CloudError('the storage does not know chunked uploads', { code: 'tus_unsupported' });
|
|
107
|
+
throw e;
|
|
108
|
+
}
|
|
109
|
+
id = idOf(res.headers.get('location'));
|
|
110
|
+
if (!id) throw new CloudError('the storage gave no upload address', { code: 'error' });
|
|
111
|
+
if (rkey) remember(rkey, id);
|
|
112
|
+
}
|
|
113
|
+
let failures = 0;
|
|
114
|
+
let chunk = null;
|
|
115
|
+
let chunkAt = -1;
|
|
116
|
+
while (offset < total) {
|
|
117
|
+
const len = Math.min(CHUNK, total - offset);
|
|
118
|
+
// Un flux ne se relit pas : le morceau en cours est gardé tant qu'il n'est pas reçu
|
|
119
|
+
if (chunkAt !== offset || !chunk) {
|
|
120
|
+
if (!source.resumable && chunk && offset > chunkAt && offset < chunkAt + chunk.length) chunk = chunk.subarray(offset - chunkAt);
|
|
121
|
+
else chunk = await source.read(offset, len);
|
|
122
|
+
chunkAt = offset;
|
|
123
|
+
}
|
|
124
|
+
let res = null;
|
|
125
|
+
let err = null;
|
|
126
|
+
try {
|
|
127
|
+
res = await api.raw('PATCH', `/upload/resumable/${id}`, { headers: { ...base, 'content-type': 'application/offset+octet-stream', 'upload-offset': String(offset) }, body: chunk });
|
|
128
|
+
} catch (e) {
|
|
129
|
+
err = e;
|
|
130
|
+
}
|
|
131
|
+
if (res && res.status === 204) {
|
|
132
|
+
offset = Number(res.headers.get('upload-offset') || offset + chunk.length);
|
|
133
|
+
failures = 0;
|
|
134
|
+
if (opts.onProgress) opts.onProgress(offset, total);
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
if (res && [400, 403, 404, 410, 413, 415].includes(res.status)) {
|
|
138
|
+
if (rkey) forget(rkey);
|
|
139
|
+
throw await failure(res);
|
|
140
|
+
}
|
|
141
|
+
if (++failures > RETRIES) throw res ? await failure(res) : new CloudError(`connection lost during the upload: ${(err && err.message) || err}`, { code: 'network' });
|
|
142
|
+
if (res) await res.arrayBuffer().catch(() => {});
|
|
143
|
+
await sleep(Math.min(30_000, 500 * 2 ** failures));
|
|
144
|
+
const h = await api.raw('HEAD', `/upload/resumable/${id}`, { headers: base }).catch(() => null);
|
|
145
|
+
if (h && h.status === 200) {
|
|
146
|
+
const at = Number(h.headers.get('upload-offset') || offset);
|
|
147
|
+
if (at !== offset) {
|
|
148
|
+
if (!source.resumable && (at < chunkAt || at > chunkAt + chunk.length)) throw new CloudError('the upload cannot resume from a stream at this offset', { code: 'error' });
|
|
149
|
+
offset = at;
|
|
150
|
+
}
|
|
151
|
+
if (opts.onResume) opts.onResume(offset);
|
|
152
|
+
if (resumedFrom === null) resumedFrom = offset;
|
|
153
|
+
} else if (h && (h.status === 404 || h.status === 410)) {
|
|
154
|
+
if (rkey) forget(rkey);
|
|
155
|
+
throw await failure(h);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
if (rkey) forget(rkey);
|
|
159
|
+
return { resumedFrom };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Source d'un fichier du disque : lecture à n'importe quel offset */
|
|
163
|
+
function fileSource(file, size) {
|
|
164
|
+
return {
|
|
165
|
+
size,
|
|
166
|
+
resumable: true,
|
|
167
|
+
read: async (offset, length) => {
|
|
168
|
+
const fh = await fs.promises.open(file, 'r');
|
|
169
|
+
try {
|
|
170
|
+
const buf = Buffer.alloc(length);
|
|
171
|
+
const { bytesRead } = await fh.read(buf, 0, length, offset);
|
|
172
|
+
return buf.subarray(0, bytesRead);
|
|
173
|
+
} finally {
|
|
174
|
+
await fh.close();
|
|
175
|
+
}
|
|
176
|
+
},
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Source d'un flux (Stockage → Stockage) : morceaux lus dans l'ordre */
|
|
181
|
+
function streamSource(webStream, size) {
|
|
182
|
+
const reader = webStream.getReader();
|
|
183
|
+
let pending = Buffer.alloc(0);
|
|
184
|
+
let done = false;
|
|
185
|
+
return {
|
|
186
|
+
size,
|
|
187
|
+
resumable: false,
|
|
188
|
+
read: async (_offset, length) => {
|
|
189
|
+
while (pending.length < length && !done) {
|
|
190
|
+
const r = await reader.read();
|
|
191
|
+
if (r.done) done = true;
|
|
192
|
+
else pending = Buffer.concat([pending, Buffer.from(r.value)]);
|
|
193
|
+
}
|
|
194
|
+
const out = pending.subarray(0, length);
|
|
195
|
+
pending = pending.subarray(length);
|
|
196
|
+
return out;
|
|
197
|
+
},
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
module.exports = { CHUNK, tusUpload, fileSource, streamSource, metadata, resumeKey, idOf, stateFile, readState };
|
package/utils/storage.js
CHANGED
|
@@ -23,6 +23,7 @@ const SCHEME_RE = /^poad:(\/\/)?/;
|
|
|
23
23
|
const BUCKET_RE = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,62}$/;
|
|
24
24
|
const PAGE = 1000;
|
|
25
25
|
const PARALLEL = 4;
|
|
26
|
+
const MAX_PARALLEL = 32;
|
|
26
27
|
const TIMEOUT_MS = 30000;
|
|
27
28
|
|
|
28
29
|
// Types des extensions courantes : le Stockage garde le Content-Type de l'envoi
|
|
@@ -75,6 +76,13 @@ function size(n) {
|
|
|
75
76
|
* Ce que montre ls sous un dossier : sous-dossiers (nombre de fichiers, taille) puis
|
|
76
77
|
* fichiers, à partir de la liste plate des objets (noms complets). Pure.
|
|
77
78
|
*/
|
|
79
|
+
/** Lignes de « poad storage ls » d'après la vue d'un dossier rendue par le service (browse). Pure. */
|
|
80
|
+
function viewEntries(view) {
|
|
81
|
+
const folders = view.folders.map((f) => ({ kind: 'folder', name: f.name, count: Number(f.files) || 0, size: Number(f.size) || 0, updated: f.updated_at || null }));
|
|
82
|
+
const files = view.files.map((o) => ({ kind: 'file', name: o.name.slice(view.prefix.length), size: Number(o.metadata && o.metadata.size) || 0, updated: o.updated_at, type: o.metadata && o.metadata.mimetype }));
|
|
83
|
+
return [...folders.sort((a, b) => a.name.localeCompare(b.name)), ...files.sort((a, b) => a.name.localeCompare(b.name))];
|
|
84
|
+
}
|
|
85
|
+
|
|
78
86
|
function entries(objects, prefix) {
|
|
79
87
|
const folders = new Map();
|
|
80
88
|
const files = [];
|
|
@@ -121,7 +129,7 @@ function client({ base, key, apikey, renew, fetch: doFetch = fetch, timeout = TI
|
|
|
121
129
|
const headers = (extra = {}) => ({ apikey: auth.apikey, authorization: `Bearer ${auth.key}`, ...extra });
|
|
122
130
|
const enc = (k) => k.split('/').map(encodeURIComponent).join('/');
|
|
123
131
|
|
|
124
|
-
async function request(method, route, { body, json, type, stream = false, ok = [200, 201, 204], length } = {}) {
|
|
132
|
+
async function request(method, route, { body, json, type, stream = false, ok = [200, 201, 204], length, extra } = {}) {
|
|
125
133
|
await fresh();
|
|
126
134
|
const ctl = new AbortController();
|
|
127
135
|
// Pas de délai pour un transfert en flux : seulement pour l'en-tête de la réponse
|
|
@@ -134,6 +142,7 @@ function client({ base, key, apikey, renew, fetch: doFetch = fetch, timeout = TI
|
|
|
134
142
|
...(json !== undefined ? { 'content-type': 'application/json' } : {}),
|
|
135
143
|
...(type ? { 'content-type': type } : {}),
|
|
136
144
|
...(length !== undefined ? { 'content-length': String(length) } : {}),
|
|
145
|
+
...(extra || {}),
|
|
137
146
|
}),
|
|
138
147
|
body: json !== undefined ? JSON.stringify(json) : body,
|
|
139
148
|
...(body && typeof body.pipe === 'function' ? { duplex: 'half' } : {}),
|
|
@@ -163,7 +172,24 @@ function client({ base, key, apikey, renew, fetch: doFetch = fetch, timeout = TI
|
|
|
163
172
|
return text ? JSON.parse(text) : null;
|
|
164
173
|
}
|
|
165
174
|
|
|
175
|
+
/** Réponse fetch brute, quel que soit son code (envois en morceaux, utils/storage-tus.js) */
|
|
176
|
+
async function raw(method, route, { headers: extra = {}, body } = {}) {
|
|
177
|
+
await fresh();
|
|
178
|
+
const ctl = new AbortController();
|
|
179
|
+
const timer = setTimeout(() => ctl.abort(), timeout * 4);
|
|
180
|
+
try {
|
|
181
|
+
return await doFetch(`${base}/storage/v1${route}`, { method, headers: headers({ ...(body ? { 'content-length': String(body.length) } : {}), ...extra }), body, signal: ctl.signal });
|
|
182
|
+
} catch (err) {
|
|
183
|
+
const cause = (err && err.cause && err.cause.message) || (err && err.message) || String(err);
|
|
184
|
+
throw new CloudError(ctl.signal.aborted ? `The storage did not answer within ${(timeout * 4) / 1000} s (${base}).` : `The storage does not answer on ${base}: ${cause}`);
|
|
185
|
+
} finally {
|
|
186
|
+
clearTimeout(timer);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
166
190
|
return {
|
|
191
|
+
base,
|
|
192
|
+
raw,
|
|
167
193
|
buckets: () => request('GET', '/bucket'),
|
|
168
194
|
bucket: (id) => request('GET', `/bucket/${encodeURIComponent(id)}`),
|
|
169
195
|
/** Tous les objets dont le nom commence par prefix (pages de 1000) */
|
|
@@ -175,13 +201,42 @@ function client({ base, key, apikey, renew, fetch: doFetch = fetch, timeout = TI
|
|
|
175
201
|
if (rows.length < PAGE) return all;
|
|
176
202
|
}
|
|
177
203
|
},
|
|
204
|
+
/**
|
|
205
|
+
* Vue d'un dossier (storage 0.5+ : { prefix, delimiter: "/" }) : tous ses sous-dossiers, comptés par le
|
|
206
|
+
* service à toute profondeur, et tous ses fichiers directs (pages de 1000). null si le service ne connaît
|
|
207
|
+
* pas ce mode (il rend alors une liste d'objets) : l'appelant reprend l'ancienne liste.
|
|
208
|
+
*/
|
|
209
|
+
async browse(bucket, folder = '') {
|
|
210
|
+
const prefix = folder ? `${folder.replace(/\/+$/, '')}/` : '';
|
|
211
|
+
const first = await request('POST', `/object/list/${encodeURIComponent(bucket)}`, { json: { prefix, delimiter: '/', limit: PAGE, offset: 0 } });
|
|
212
|
+
if (!first || Array.isArray(first) || !Array.isArray(first.folders)) return null;
|
|
213
|
+
const files = [...first.files];
|
|
214
|
+
while (files.length < first.total_files) {
|
|
215
|
+
const next = await request('POST', `/object/list/${encodeURIComponent(bucket)}`, { json: { prefix, delimiter: '/', limit: PAGE, offset: files.length } });
|
|
216
|
+
if (!next || !Array.isArray(next.files) || !next.files.length) break;
|
|
217
|
+
files.push(...next.files);
|
|
218
|
+
}
|
|
219
|
+
return { prefix, folders: first.folders, files, total_files: first.total_files };
|
|
220
|
+
},
|
|
221
|
+
/** Premiers objets dont le nom commence par prefix (une page) */
|
|
222
|
+
page: (bucket, prefix, limit = 1) => request('POST', `/object/list/${encodeURIComponent(bucket)}`, { json: { prefix, limit, offset: 0 } }),
|
|
178
223
|
/** Envoi (crée ou remplace) : body est un flux Node ou un Buffer */
|
|
179
|
-
put: (bucket, k, body, { type, length } = {}) =>
|
|
224
|
+
put: (bucket, k, body, { type, length, cacheControl } = {}) =>
|
|
225
|
+
// length (taille connue d'un fichier du disque) : un fichier trop gros est refusé avant l'envoi
|
|
180
226
|
request('PUT', `/object/${encodeURIComponent(bucket)}/${enc(k)}`, {
|
|
181
227
|
body: body && typeof body.pipe === 'function' ? Readable.toWeb(body) : body,
|
|
182
228
|
type: type || 'application/octet-stream',
|
|
183
229
|
length,
|
|
230
|
+
extra: cacheControl ? { 'cache-control': cacheControl } : undefined,
|
|
184
231
|
}),
|
|
232
|
+
createBucket: (id, isPublic) => request('POST', '/bucket', { json: { name: id, public: Boolean(isPublic) } }),
|
|
233
|
+
/** État du service (backend en service), sans droit particulier */
|
|
234
|
+
status: () => request('GET', '/status'),
|
|
235
|
+
// poad storage sync (storage 0.4.0+, clé service_role) : 404 sur un engine plus ancien
|
|
236
|
+
syncLocation: () => request('GET', '/sync/location'),
|
|
237
|
+
syncList: (bucket, after = '', limit = PAGE) => request('POST', `/sync/list/${encodeURIComponent(bucket)}`, { json: { after, limit } }),
|
|
238
|
+
reference: (bucket, project, fingerprint, objects) => request('POST', `/sync/reference/${encodeURIComponent(bucket)}`, { json: { project, fingerprint, objects } }),
|
|
239
|
+
markShared: (project, fingerprint) => request('POST', '/sync/shared', { json: { project, fingerprint } }),
|
|
185
240
|
/** Lecture en flux : la réponse fetch (res.body, content-length) */
|
|
186
241
|
get: (bucket, k) => request('GET', `/object/${encodeURIComponent(bucket)}/${enc(k)}`, { stream: true }),
|
|
187
242
|
remove: (bucket, keys) => request('DELETE', `/object/${encodeURIComponent(bucket)}`, { json: { prefixes: keys } }),
|
|
@@ -190,6 +245,7 @@ function client({ base, key, apikey, renew, fetch: doFetch = fetch, timeout = TI
|
|
|
190
245
|
|
|
191
246
|
/** Exécute fn sur chaque élément, PARALLEL à la fois ; rend les erreurs { item, error } */
|
|
192
247
|
async function each(items, fn, parallel = PARALLEL) {
|
|
248
|
+
parallel = Number.isInteger(parallel) && parallel > 0 ? parallel : PARALLEL;
|
|
193
249
|
const errors = [];
|
|
194
250
|
let next = 0;
|
|
195
251
|
const worker = async () => {
|
|
@@ -206,6 +262,44 @@ async function each(items, fn, parallel = PARALLEL) {
|
|
|
206
262
|
return errors;
|
|
207
263
|
}
|
|
208
264
|
|
|
265
|
+
/**
|
|
266
|
+
* --concurrency <n> : nombre de transferts en parallèle, entier de 1 à MAX_PARALLEL ;
|
|
267
|
+
* absent : PARALLEL. Erreur d'usage sinon. Pure.
|
|
268
|
+
*/
|
|
269
|
+
function concurrency(value) {
|
|
270
|
+
if (value === undefined || value === null) return PARALLEL;
|
|
271
|
+
const text = String(value).trim();
|
|
272
|
+
const n = /^\d+$/.test(text) ? Number(text) : NaN;
|
|
273
|
+
if (!Number.isInteger(n) || n < 1 || n > MAX_PARALLEL) throw usageError(`--concurrency expects a whole number from 1 to ${MAX_PARALLEL} (default ${PARALLEL}), not "${String(value).slice(0, 40)}"`);
|
|
274
|
+
return n;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Raison lisible d'un échec de transfert, pour le bilan : le message du serveur, et pour
|
|
279
|
+
* un refus de taille (HTTP 413) la limite en octets quand le serveur la donne. Pure.
|
|
280
|
+
*/
|
|
281
|
+
function reason(error) {
|
|
282
|
+
if (!error) return 'unknown error';
|
|
283
|
+
const message = String(error.message || error);
|
|
284
|
+
if (error.status === 413) {
|
|
285
|
+
const m = /(\d+)\s*(?:octets|bytes|B)\b/i.exec(message);
|
|
286
|
+
return m ? `too large: the storage accepts at most ${m[1]} bytes (${size(Number(m[1]))}) per file` : `too large for the storage (HTTP 413)${message && !/^HTTP 413$/.test(message) ? `: ${message}` : ''}`;
|
|
287
|
+
}
|
|
288
|
+
return message;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** MD5 hexadécimal d'un fichier du disque, en flux (l'etag du Stockage est le MD5 du contenu) */
|
|
292
|
+
function md5File(file) {
|
|
293
|
+
const crypto = require('crypto');
|
|
294
|
+
return new Promise((ok, ko) => {
|
|
295
|
+
const hash = crypto.createHash('md5');
|
|
296
|
+
fs.createReadStream(file)
|
|
297
|
+
.on('error', ko)
|
|
298
|
+
.on('data', (c) => hash.update(c))
|
|
299
|
+
.on('end', () => ok(hash.digest('hex')));
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
|
|
209
303
|
/** Objets visés par un chemin du Stockage : le fichier exact, sinon (avec -r) tout le dossier */
|
|
210
304
|
async function resolve(api, { bucket, key, dir }, recursive) {
|
|
211
305
|
if (!dir) {
|
|
@@ -269,7 +363,40 @@ async function cloudTarget(opts = {}) {
|
|
|
269
363
|
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
364
|
}
|
|
271
365
|
|
|
366
|
+
/**
|
|
367
|
+
* Variables de l'engine local : identité du projet, sans secret (project_uuid, projet poad.io lié).
|
|
368
|
+
* Le storage (0.4.0+) n'accepte des références sans octets (poad storage sync) que d'un
|
|
369
|
+
* environnement du même projet ; un engine plus ancien les ignore. Pure.
|
|
370
|
+
*/
|
|
371
|
+
const ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
372
|
+
function engineEnv(config = {}) {
|
|
373
|
+
const env = [];
|
|
374
|
+
// [storage] file_size_limit : taille maximale d'un fichier du projet, plafond des buckets (storage 0.6.0+)
|
|
375
|
+
const limit = fileSizeLimit(config);
|
|
376
|
+
if (limit.value) env.push(`POAD_STORAGE_FILE_SIZE_LIMIT=${limit.value}`);
|
|
377
|
+
if (ID_RE.test(String(config.project_uuid || ''))) env.push(`POAD_PROJECT_UUID=${config.project_uuid}`);
|
|
378
|
+
const linked = config.cloud && config.cloud.project;
|
|
379
|
+
if (ID_RE.test(String(linked || ''))) env.push(`POAD_CLOUD_PROJECT=${linked}`);
|
|
380
|
+
return env;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* [storage] file_size_limit de poad/config.toml → octets ({ value }), ou { warning } si la valeur est
|
|
385
|
+
* illisible (elle n'est alors pas transmise : la limite de l'engine, 50 MiB, reste). Octets ou texte :
|
|
386
|
+
* « 200MB », « 1GB » (décimal, comme Supabase), « 500MiB » (binaire). Pure.
|
|
387
|
+
*/
|
|
388
|
+
function fileSizeLimit(config = {}) {
|
|
389
|
+
const raw = config.storage && config.storage.file_size_limit;
|
|
390
|
+
if (raw === undefined || raw === null || raw === '') return { value: null };
|
|
391
|
+
const units = { b: 1, kb: 1e3, mb: 1e6, gb: 1e9, tb: 1e12, kib: 1024, mib: 1024 ** 2, gib: 1024 ** 3, tib: 1024 ** 4 };
|
|
392
|
+
const m = typeof raw === 'number' ? [null, String(raw), 'b'] : /^(\d+(?:\.\d+)?)\s*([kmgt]i?b|b)?$/i.exec(String(raw).trim());
|
|
393
|
+
const n = m ? Math.round(Number(m[1]) * units[(m[2] || 'b').toLowerCase()]) : NaN;
|
|
394
|
+
if (!Number.isSafeInteger(n) || n <= 0)
|
|
395
|
+
return { value: null, warning: `[storage] file_size_limit = "${String(raw).slice(0, 32)}" in poad/config.toml is not a size (examples: "200MB", "1GB", 52428800): the engine default (50 MiB) is used.` };
|
|
396
|
+
return { value: n };
|
|
397
|
+
}
|
|
398
|
+
|
|
272
399
|
/** Cible : poad.io avec --env/--project, sinon l'engine local */
|
|
273
400
|
const target = (opts = {}, deps) => (opts.env || opts.project ? cloudTarget(opts) : localTarget(deps));
|
|
274
401
|
|
|
275
|
-
module.exports = { EXIT, target, cloudTarget, when, parseRemote, isRemote, size, entries, joinKey, client, each, resolve, walk, mimeOf, show, localTarget };
|
|
402
|
+
module.exports = { fileSizeLimit, EXIT, PARALLEL, MAX_PARALLEL, concurrency, reason, md5File, engineEnv, target, cloudTarget, when, parseRemote, isRemote, size, entries, viewEntries, joinKey, client, each, resolve, walk, mimeOf, show, localTarget };
|