poad 2.75.3 → 2.76.1
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 +2 -0
- package/project/pull.js +4 -0
- package/project/push.js +4 -0
- package/test/cloud.test.js +5 -2
- package/test/fake-storage.js +150 -0
- package/test/project-sync.test.js +413 -0
- package/test/push-resume.test.js +179 -0
- package/utils/banner.js +2 -0
- package/utils/cloud/db.js +6 -7
- package/utils/data-loss.js +4 -4
- package/utils/help-details.js +58 -3
- package/utils/project-sync/code.js +122 -0
- package/utils/project-sync/pg.js +130 -0
- package/utils/project-sync/plan.js +491 -0
- package/utils/project-sync/run.js +910 -0
- package/utils/storage-sync.js +164 -24
- package/utils/storage-tus.js +40 -4
- package/utils/storage.js +69 -19
package/utils/storage-sync.js
CHANGED
|
@@ -137,7 +137,8 @@ function plan(src, dst, { prune = false } = {}) {
|
|
|
137
137
|
const d = byName.get(o.name);
|
|
138
138
|
if (!d) out.add.push(o);
|
|
139
139
|
else if (sameContent(o, d)) out.unchanged.push(o);
|
|
140
|
-
|
|
140
|
+
// Taille de ce qui est remplacé : place libérée sur la destination (contrôle de place de poad push)
|
|
141
|
+
else out.update.push({ ...o, targetSize: Number.isFinite(d.size) ? d.size : null });
|
|
141
142
|
}
|
|
142
143
|
if (prune)
|
|
143
144
|
for (const d of dst) {
|
|
@@ -148,13 +149,112 @@ function plan(src, dst, { prune = false } = {}) {
|
|
|
148
149
|
return out;
|
|
149
150
|
}
|
|
150
151
|
|
|
151
|
-
/**
|
|
152
|
-
|
|
152
|
+
/**
|
|
153
|
+
* Copie des octets d'un objet ; rend sa taille. Au-delà d'un morceau (6 Mio) et si la destination connaît
|
|
154
|
+
* TUS : envoi en morceaux reprenables, la source lue par plages (Range) — un envoi coupé, même par la fin de
|
|
155
|
+
* la commande, reprend là où la destination en est (clé de reprise : destination + empreinte du contenu).
|
|
156
|
+
* Sinon : une requête, en flux, sous un délai d'inactivité (utils/storage.js).
|
|
157
|
+
*/
|
|
158
|
+
async function copyBytes(from, to, bucket, o, { onResume, sleep } = {}) {
|
|
159
|
+
const t = require('./storage-tus');
|
|
160
|
+
if (Number.isFinite(o.size) && o.size > t.CHUNK && to.raw && !to.noTus) {
|
|
161
|
+
const type = o.mimetype || 'application/octet-stream';
|
|
162
|
+
let source = await t.rangeSource(from, bucket, o.name, o.size).catch(() => null);
|
|
163
|
+
let res = null;
|
|
164
|
+
if (!source) {
|
|
165
|
+
res = await from.get(bucket, o.name);
|
|
166
|
+
source = t.streamSource(res.body, o.size);
|
|
167
|
+
}
|
|
168
|
+
try {
|
|
169
|
+
await t.tusUpload(to, source, { bucket, key: o.name, type, cacheControl: o.cacheControl || undefined, upsert: true, base: to.base, version: o.etag || o.key || null, onResume, sleep });
|
|
170
|
+
return o.size;
|
|
171
|
+
} catch (e) {
|
|
172
|
+
if (e.code !== 'tus_unsupported') throw e;
|
|
173
|
+
to.noTus = true;
|
|
174
|
+
if (res) await res.body?.cancel().catch(() => {});
|
|
175
|
+
}
|
|
176
|
+
}
|
|
153
177
|
const res = await from.get(bucket, o.name);
|
|
154
|
-
await to.put(bucket, o.name, res.body, { type: o.mimetype || res.headers.get('content-type') || 'application/octet-stream', cacheControl: o.cacheControl || undefined });
|
|
178
|
+
await to.put(bucket, o.name, res.body, { type: o.mimetype || res.headers.get('content-type') || 'application/octet-stream', cacheControl: o.cacheControl || undefined, length: Number.isFinite(o.size) ? o.size : undefined });
|
|
155
179
|
return o.size || Number(res.headers.get('content-length')) || 0;
|
|
156
180
|
}
|
|
157
181
|
|
|
182
|
+
/** Une nouvelle tentative a-t-elle un sens (coupure, délai, 5xx, 429) ? Un refus (4xx) est définitif. Pure. */
|
|
183
|
+
function retriable(e) {
|
|
184
|
+
if (!e) return false;
|
|
185
|
+
if (e.retriable) return true;
|
|
186
|
+
if (['network', 'timeout'].includes(e.code)) return true;
|
|
187
|
+
return [408, 425, 429, 500, 502, 503, 504].includes(e.status);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Attente avant la tentative n (1, 2, 3…) : 1 s, 2 s, 4 s… plafonnée à 30 s, ±25 %. Pure (au hasard près). */
|
|
191
|
+
const backoff = (n, rnd = Math.random) => Math.round(Math.min(30_000, 1000 * 2 ** (n - 1)) * (0.75 + rnd() * 0.5));
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Exécute fn sur chaque élément, avec nouvelles tentatives et une concurrence qui baisse quand les erreurs
|
|
195
|
+
* montent : une erreur passagère divise le nombre de transferts en parallèle par deux (au moins 1), puis
|
|
196
|
+
* chaque série de succès le remonte d'un cran jusqu'à la valeur de départ. Rend les erreurs { item, error }.
|
|
197
|
+
* opts : { concurrency, retries, sleep, onRetry(item, attempt, error, delay), onConcurrency(n) }
|
|
198
|
+
*/
|
|
199
|
+
async function adaptive(items, fn, opts = {}) {
|
|
200
|
+
const max = Number.isInteger(opts.concurrency) && opts.concurrency > 0 ? opts.concurrency : s.PARALLEL;
|
|
201
|
+
const retries = Number.isInteger(opts.retries) ? opts.retries : 4;
|
|
202
|
+
const sleep = opts.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
203
|
+
const errors = [];
|
|
204
|
+
let limit = max;
|
|
205
|
+
let active = 0;
|
|
206
|
+
let streak = 0;
|
|
207
|
+
let next = 0;
|
|
208
|
+
const lower = () => {
|
|
209
|
+
const was = limit;
|
|
210
|
+
limit = Math.max(1, Math.floor(limit / 2));
|
|
211
|
+
streak = 0;
|
|
212
|
+
if (limit !== was && opts.onConcurrency) opts.onConcurrency(limit);
|
|
213
|
+
};
|
|
214
|
+
const raise = () => {
|
|
215
|
+
if (limit >= max) return;
|
|
216
|
+
if (++streak >= limit * 2) {
|
|
217
|
+
limit++;
|
|
218
|
+
streak = 0;
|
|
219
|
+
if (opts.onConcurrency) opts.onConcurrency(limit);
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
const worker = async (slot) => {
|
|
223
|
+
while (next < items.length) {
|
|
224
|
+
// Au-delà de la concurrence permise : on attend qu'elle remonte, ou la fin
|
|
225
|
+
if (slot >= limit) {
|
|
226
|
+
await new Promise((r) => setTimeout(r, 100));
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
const item = items[next++];
|
|
230
|
+
active++;
|
|
231
|
+
try {
|
|
232
|
+
for (let attempt = 1; ; attempt++) {
|
|
233
|
+
try {
|
|
234
|
+
await fn(item, attempt);
|
|
235
|
+
raise();
|
|
236
|
+
break;
|
|
237
|
+
} catch (error) {
|
|
238
|
+
if (!retriable(error) || attempt > retries) {
|
|
239
|
+
errors.push({ item, error, attempts: attempt });
|
|
240
|
+
if (retriable(error)) lower();
|
|
241
|
+
break;
|
|
242
|
+
}
|
|
243
|
+
lower();
|
|
244
|
+
const delay = backoff(attempt);
|
|
245
|
+
if (opts.onRetry) opts.onRetry(item, attempt, error, delay);
|
|
246
|
+
await sleep(delay);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
} finally {
|
|
250
|
+
active--;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
await Promise.all(Array.from({ length: Math.min(max, items.length) }, (_, i) => worker(i)));
|
|
255
|
+
return errors;
|
|
256
|
+
}
|
|
257
|
+
|
|
158
258
|
/**
|
|
159
259
|
* Synchronise. from/to : clients du Stockage (utils/storage.client) ; opts : { bucket, prune,
|
|
160
260
|
* dryRun, copyBytes, concurrency, fromLabel, toLabel, confirm(summary), onItem(event) }.
|
|
@@ -223,19 +323,71 @@ async function sync(from, to, opts = {}) {
|
|
|
223
323
|
}
|
|
224
324
|
}
|
|
225
325
|
}
|
|
326
|
+
// Retraits d'abord : la place qu'ils occupaient se libère avant les envois (le service retire les
|
|
327
|
+
// contenus une minute après). --clean (freeFirst) : ce qui va être remplacé part aussi d'abord.
|
|
328
|
+
const freeing = opts.freeFirst ? p.update.map((o) => o.name) : [];
|
|
329
|
+
const names = [...p.remove.map((o) => o.name), ...freeing];
|
|
330
|
+
for (let i = 0; i < names.length; i += 1000) {
|
|
331
|
+
const slice = names.slice(i, i + 1000);
|
|
332
|
+
try {
|
|
333
|
+
const rows = (await to.remove(p.bucket, slice)) || [];
|
|
334
|
+
for (const r of rows) {
|
|
335
|
+
if (freeing.includes(r.name)) continue;
|
|
336
|
+
totals.removed++;
|
|
337
|
+
event({ bucket: p.bucket, name: r.name, action: 'remove' });
|
|
338
|
+
}
|
|
339
|
+
} catch (e) {
|
|
340
|
+
for (const n of slice) fail(p.bucket, n, freeing.includes(n) ? 'update' : 'remove', e);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
226
343
|
const work = [...p.add.map((o) => ['add', o]), ...p.update.map((o) => ['update', o])];
|
|
227
344
|
const done = (action, o) => {
|
|
228
345
|
totals[action === 'add' ? 'added' : 'updated']++;
|
|
229
346
|
event({ bucket: p.bucket, name: o.name, action, size: o.size });
|
|
230
347
|
};
|
|
231
348
|
if (mode === 'bytes') {
|
|
232
|
-
const
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
349
|
+
const sent = [];
|
|
350
|
+
const errs = await adaptive(
|
|
351
|
+
work,
|
|
352
|
+
async ([action, o]) => {
|
|
353
|
+
// Lu après l'attente : « totals.bytes += await … » perdrait les transferts parallèles
|
|
354
|
+
const n = await copyBytes(from, to, p.bucket, o, { sleep: opts.sleep, onResume: (offset) => offset > 0 && event({ bucket: p.bucket, name: o.name, action: 'resume', offset, size: o.size }) });
|
|
355
|
+
totals.bytes += n;
|
|
356
|
+
sent.push([action, o]);
|
|
357
|
+
done(action, o);
|
|
358
|
+
},
|
|
359
|
+
{
|
|
360
|
+
concurrency: opts.concurrency,
|
|
361
|
+
retries: opts.retries,
|
|
362
|
+
sleep: opts.sleep,
|
|
363
|
+
onRetry: ([action, o], attempt, error, delay) => {
|
|
364
|
+
totals.retried = (totals.retried || 0) + 1;
|
|
365
|
+
event({ bucket: p.bucket, name: o.name, action: 'retry', attempt, delay, reason: s.reason(error) });
|
|
366
|
+
},
|
|
367
|
+
onConcurrency: (n) => event({ bucket: p.bucket, action: 'concurrency', concurrency: n }),
|
|
368
|
+
},
|
|
369
|
+
);
|
|
370
|
+
for (const { item, error, attempts } of errs) {
|
|
371
|
+
fail(p.bucket, item[1].name, item[0], error);
|
|
372
|
+
result.errors[result.errors.length - 1].attempts = attempts;
|
|
373
|
+
}
|
|
374
|
+
// Ce qui est arrivé est relu : taille et empreinte (MD5) doivent être celles de la source ; un objet
|
|
375
|
+
// tronqué ou différent n'est jamais compté comme fait (et la prochaine poussée le renverra)
|
|
376
|
+
if (sent.length && opts.verify !== false) {
|
|
377
|
+
let after = null;
|
|
378
|
+
try {
|
|
379
|
+
after = new Map((await listObjects(to, p.bucket, dstLoc.sync)).map((o) => [o.name, o]));
|
|
380
|
+
} catch {}
|
|
381
|
+
if (after)
|
|
382
|
+
for (const [action, o] of sent) {
|
|
383
|
+
const d = after.get(o.name);
|
|
384
|
+
const same = d && d.size === o.size && (!o.etag || !d.etag || d.etag === o.etag);
|
|
385
|
+
if (same) continue;
|
|
386
|
+
totals[action === 'add' ? 'added' : 'updated']--;
|
|
387
|
+
totals.bytes -= o.size || 0;
|
|
388
|
+
fail(p.bucket, o.name, action, new CloudError(d ? `different on the target after the upload (${d.size} bytes there, ${o.size} here, or another checksum)` : 'missing on the target after the upload', { code: 'verify' }));
|
|
389
|
+
}
|
|
390
|
+
}
|
|
239
391
|
} else {
|
|
240
392
|
for (let i = 0; i < work.length; i += REF_BATCH) {
|
|
241
393
|
const batch = work.slice(i, i + REF_BATCH);
|
|
@@ -258,20 +410,8 @@ async function sync(from, to, opts = {}) {
|
|
|
258
410
|
});
|
|
259
411
|
}
|
|
260
412
|
}
|
|
261
|
-
const names = p.remove.map((o) => o.name);
|
|
262
|
-
for (let i = 0; i < names.length; i += 1000) {
|
|
263
|
-
try {
|
|
264
|
-
const rows = (await to.remove(p.bucket, names.slice(i, i + 1000))) || [];
|
|
265
|
-
for (const r of rows) {
|
|
266
|
-
totals.removed++;
|
|
267
|
-
event({ bucket: p.bucket, name: r.name, action: 'remove' });
|
|
268
|
-
}
|
|
269
|
-
} catch (e) {
|
|
270
|
-
for (const n of names.slice(i, i + 1000)) fail(p.bucket, n, 'remove', e);
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
413
|
}
|
|
274
414
|
return result;
|
|
275
415
|
}
|
|
276
416
|
|
|
277
|
-
module.exports = { sync, plan, decideMode, sameProject, locate, listObjects, sameContent, INTERNAL };
|
|
417
|
+
module.exports = { sync, plan, adaptive, retriable, backoff, copyBytes, decideMode, sameProject, locate, listObjects, sameContent, INTERNAL };
|
package/utils/storage-tus.js
CHANGED
|
@@ -46,8 +46,16 @@ const forget = (key) =>
|
|
|
46
46
|
return s;
|
|
47
47
|
});
|
|
48
48
|
|
|
49
|
-
/**
|
|
50
|
-
|
|
49
|
+
/**
|
|
50
|
+
* Clé de reprise : même engine, même destination, même fichier (taille, date ; ou, pour un objet d'un autre
|
|
51
|
+
* Stockage, son empreinte : version). Pure.
|
|
52
|
+
*/
|
|
53
|
+
const resumeKey = ({ base, bucket, key, size, mtimeMs, version }) =>
|
|
54
|
+
crypto
|
|
55
|
+
.createHash('sha256')
|
|
56
|
+
.update(JSON.stringify([base, bucket, key, size, Math.round(mtimeMs || 0), ...(version ? [String(version)] : [])]))
|
|
57
|
+
.digest('hex')
|
|
58
|
+
.slice(0, 32);
|
|
51
59
|
|
|
52
60
|
const b64 = (v) => Buffer.from(String(v)).toString('base64');
|
|
53
61
|
/** Upload-Metadata. Pure. */
|
|
@@ -82,7 +90,7 @@ async function tusUpload(api, source, opts) {
|
|
|
82
90
|
const sleep = opts.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
83
91
|
const base = { 'tus-resumable': TUS };
|
|
84
92
|
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;
|
|
93
|
+
const rkey = source.resumable ? resumeKey({ base: opts.base, bucket: opts.bucket, key: opts.key, size: total, mtimeMs: opts.mtimeMs, version: opts.version }) : null;
|
|
86
94
|
let id = rkey ? (readState()[rkey] || {}).id : null;
|
|
87
95
|
let offset = 0;
|
|
88
96
|
let resumedFrom = null;
|
|
@@ -177,6 +185,34 @@ function fileSource(file, size) {
|
|
|
177
185
|
};
|
|
178
186
|
}
|
|
179
187
|
|
|
188
|
+
/**
|
|
189
|
+
* Source d'un objet d'un autre Stockage lu par plages (Range) : n'importe quel offset, donc reprenable d'une
|
|
190
|
+
* commande à l'autre (poad push / poad pull). null si ce Stockage ne sert pas les plages (l'appelant prend
|
|
191
|
+
* alors un flux, streamSource). Le premier morceau est lu ici pour le savoir, puis rendu au premier read.
|
|
192
|
+
*/
|
|
193
|
+
async function rangeSource(api, bucket, key, size, first = CHUNK) {
|
|
194
|
+
if (typeof api.getRange !== 'function' || !(size > 0)) return null;
|
|
195
|
+
const len = Math.min(first, size);
|
|
196
|
+
const head = await api.getRange(bucket, key, 0, len - 1);
|
|
197
|
+
if (!head || head.length !== len) return null;
|
|
198
|
+
let cached = head;
|
|
199
|
+
return {
|
|
200
|
+
size,
|
|
201
|
+
resumable: true,
|
|
202
|
+
read: async (offset, length) => {
|
|
203
|
+
if (cached && offset === 0 && length <= cached.length) {
|
|
204
|
+
const b = cached.subarray(0, length);
|
|
205
|
+
cached = null;
|
|
206
|
+
return b;
|
|
207
|
+
}
|
|
208
|
+
cached = null;
|
|
209
|
+
const b = await api.getRange(bucket, key, offset, Math.min(size, offset + length) - 1);
|
|
210
|
+
if (!b) throw new CloudError('the source storage stopped serving byte ranges', { code: 'error' });
|
|
211
|
+
return b;
|
|
212
|
+
},
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
|
|
180
216
|
/** Source d'un flux (Stockage → Stockage) : morceaux lus dans l'ordre */
|
|
181
217
|
function streamSource(webStream, size) {
|
|
182
218
|
const reader = webStream.getReader();
|
|
@@ -198,4 +234,4 @@ function streamSource(webStream, size) {
|
|
|
198
234
|
};
|
|
199
235
|
}
|
|
200
236
|
|
|
201
|
-
module.exports = { CHUNK, tusUpload, fileSource, streamSource, metadata, resumeKey, idOf, stateFile, readState };
|
|
237
|
+
module.exports = { CHUNK, tusUpload, fileSource, streamSource, rangeSource, metadata, resumeKey, idOf, stateFile, readState };
|
package/utils/storage.js
CHANGED
|
@@ -25,6 +25,12 @@ const PAGE = 1000;
|
|
|
25
25
|
const PARALLEL = 4;
|
|
26
26
|
const MAX_PARALLEL = 32;
|
|
27
27
|
const TIMEOUT_MS = 30000;
|
|
28
|
+
// Débit minimal admis d'un corps en mémoire (morceau TUS) avant de le dire coupé : 32 Kio/s
|
|
29
|
+
const MIN_RATE = 32 * 1024;
|
|
30
|
+
// Réponses qui valent une nouvelle tentative (le reste : refus définitif)
|
|
31
|
+
const RETRY_STATUS = [408, 425, 429, 500, 502, 503, 504];
|
|
32
|
+
/** CloudError qui dit si une nouvelle tentative a un sens (coupure, délai, 5xx) */
|
|
33
|
+
const cerr = (message, o = {}) => Object.assign(new CloudError(message, o), { retriable: Boolean(o.retriable) });
|
|
28
34
|
|
|
29
35
|
// Types des extensions courantes : le Stockage garde le Content-Type de l'envoi
|
|
30
36
|
const MIME = {
|
|
@@ -129,11 +135,49 @@ function client({ base, key, apikey, renew, fetch: doFetch = fetch, timeout = TI
|
|
|
129
135
|
const headers = (extra = {}) => ({ apikey: auth.apikey, authorization: `Bearer ${auth.key}`, ...extra });
|
|
130
136
|
const enc = (k) => k.split('/').map(encodeURIComponent).join('/');
|
|
131
137
|
|
|
138
|
+
/**
|
|
139
|
+
* Délai d'une requête : un délai d'INACTIVITÉ, pas un délai total. Il repart à chaque morceau du corps
|
|
140
|
+
* envoyé (un fichier de plusieurs centaines de Mo n'est jamais coupé tant qu'il avance), puis couvre
|
|
141
|
+
* l'attente de l'en-tête de la réponse. Corps en mémoire de taille connue : timeout, ou le temps de
|
|
142
|
+
* l'envoyer à MIN_RATE s'il est plus long.
|
|
143
|
+
*/
|
|
144
|
+
function watchdog(ms) {
|
|
145
|
+
const ctl = new AbortController();
|
|
146
|
+
let timer = null;
|
|
147
|
+
let limit = ms;
|
|
148
|
+
const arm = () => {
|
|
149
|
+
clearTimeout(timer);
|
|
150
|
+
timer = setTimeout(() => ctl.abort(), limit);
|
|
151
|
+
};
|
|
152
|
+
arm();
|
|
153
|
+
return { signal: ctl.signal, bump: arm, stop: () => clearTimeout(timer), aborted: () => ctl.signal.aborted, limit: () => limit, set: (v) => ((limit = v), arm()) };
|
|
154
|
+
}
|
|
155
|
+
/** Flux web qui signale chaque morceau lu (fetch le lit au rythme où le réseau l'envoie) */
|
|
156
|
+
function watched(body, bump) {
|
|
157
|
+
const web = typeof body.pipe === 'function' ? Readable.toWeb(body) : body;
|
|
158
|
+
const reader = web.getReader();
|
|
159
|
+
return new ReadableStream({
|
|
160
|
+
async pull(c) {
|
|
161
|
+
const r = await reader.read();
|
|
162
|
+
bump();
|
|
163
|
+
if (r.done) c.close();
|
|
164
|
+
else c.enqueue(r.value);
|
|
165
|
+
},
|
|
166
|
+
cancel: (why) => reader.cancel(why),
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
const timeoutFor = (bytes, base) => Math.max(base, Number.isFinite(bytes) && bytes > 0 ? Math.ceil((bytes / MIN_RATE) * 1000) : 0);
|
|
170
|
+
const failed = (err, wd) => {
|
|
171
|
+
const cause = (err && err.cause && err.cause.message) || (err && err.message) || String(err);
|
|
172
|
+
return wd.aborted()
|
|
173
|
+
? cerr(`The storage did not answer within ${+(wd.limit() / 1000).toFixed(1)} s (${base}).`, { code: 'timeout', retriable: true })
|
|
174
|
+
: cerr(`The storage does not answer on ${base}: ${cause}`, { code: 'network', retriable: true });
|
|
175
|
+
};
|
|
176
|
+
|
|
132
177
|
async function request(method, route, { body, json, type, stream = false, ok = [200, 201, 204], length, extra } = {}) {
|
|
133
178
|
await fresh();
|
|
134
|
-
const
|
|
135
|
-
|
|
136
|
-
const timer = setTimeout(() => ctl.abort(), timeout);
|
|
179
|
+
const streaming = body && (typeof body.pipe === 'function' || body instanceof ReadableStream);
|
|
180
|
+
const wd = watchdog(streaming ? timeout : timeoutFor(body && body.length, timeout));
|
|
137
181
|
let res;
|
|
138
182
|
try {
|
|
139
183
|
res = await doFetch(`${base}/storage/v1${route}`, {
|
|
@@ -144,17 +188,16 @@ function client({ base, key, apikey, renew, fetch: doFetch = fetch, timeout = TI
|
|
|
144
188
|
...(length !== undefined ? { 'content-length': String(length) } : {}),
|
|
145
189
|
...(extra || {}),
|
|
146
190
|
}),
|
|
147
|
-
body: json !== undefined ? JSON.stringify(json) : body,
|
|
148
|
-
...(
|
|
149
|
-
|
|
150
|
-
signal: ctl.signal,
|
|
191
|
+
body: json !== undefined ? JSON.stringify(json) : streaming ? watched(body, wd.bump) : body,
|
|
192
|
+
...(streaming ? { duplex: 'half' } : {}),
|
|
193
|
+
signal: wd.signal,
|
|
151
194
|
});
|
|
152
195
|
} catch (err) {
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
throw new CloudError(ctl.signal.aborted ? `The storage did not answer within ${timeout / 1000} s (${base}).` : `The storage does not answer on ${base}: ${cause}`);
|
|
196
|
+
wd.stop();
|
|
197
|
+
throw failed(err, wd);
|
|
156
198
|
}
|
|
157
|
-
|
|
199
|
+
// Pas de délai pour la lecture d'une réponse en flux : seulement pour son en-tête
|
|
200
|
+
wd.stop();
|
|
158
201
|
if (!ok.includes(res.status)) {
|
|
159
202
|
let message = `HTTP ${res.status}`;
|
|
160
203
|
try {
|
|
@@ -163,7 +206,7 @@ function client({ base, key, apikey, renew, fetch: doFetch = fetch, timeout = TI
|
|
|
163
206
|
} catch {}
|
|
164
207
|
if (res.status === 401 || res.status === 403) message = `refused by the storage (HTTP ${res.status}): ${message}`;
|
|
165
208
|
if (res.status === 502 || res.status === 503) message = `the storage service is not available (HTTP ${res.status})`;
|
|
166
|
-
const e =
|
|
209
|
+
const e = cerr(message, { status: res.status, code: res.status === 404 ? 'not_found' : 'error', retriable: RETRY_STATUS.includes(res.status) });
|
|
167
210
|
throw e;
|
|
168
211
|
}
|
|
169
212
|
if (stream) return res;
|
|
@@ -175,15 +218,13 @@ function client({ base, key, apikey, renew, fetch: doFetch = fetch, timeout = TI
|
|
|
175
218
|
/** Réponse fetch brute, quel que soit son code (envois en morceaux, utils/storage-tus.js) */
|
|
176
219
|
async function raw(method, route, { headers: extra = {}, body } = {}) {
|
|
177
220
|
await fresh();
|
|
178
|
-
const
|
|
179
|
-
const timer = setTimeout(() => ctl.abort(), timeout * 4);
|
|
221
|
+
const wd = watchdog(timeoutFor(body && body.length, timeout * 4));
|
|
180
222
|
try {
|
|
181
|
-
return await doFetch(`${base}/storage/v1${route}`, { method, headers: headers({ ...(body ? { 'content-length': String(body.length) } : {}), ...extra }), body, signal:
|
|
223
|
+
return await doFetch(`${base}/storage/v1${route}`, { method, headers: headers({ ...(body ? { 'content-length': String(body.length) } : {}), ...extra }), body, signal: wd.signal });
|
|
182
224
|
} catch (err) {
|
|
183
|
-
|
|
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}`);
|
|
225
|
+
throw failed(err, wd);
|
|
185
226
|
} finally {
|
|
186
|
-
|
|
227
|
+
wd.stop();
|
|
187
228
|
}
|
|
188
229
|
}
|
|
189
230
|
|
|
@@ -239,6 +280,15 @@ function client({ base, key, apikey, renew, fetch: doFetch = fetch, timeout = TI
|
|
|
239
280
|
markShared: (project, fingerprint) => request('POST', '/sync/shared', { json: { project, fingerprint } }),
|
|
240
281
|
/** Lecture en flux : la réponse fetch (res.body, content-length) */
|
|
241
282
|
get: (bucket, k) => request('GET', `/object/${encodeURIComponent(bucket)}/${enc(k)}`, { stream: true }),
|
|
283
|
+
/** Une plage d'octets [start, end] (Range) : Buffer, ou null si le service rend tout l'objet (pas de Range) */
|
|
284
|
+
async getRange(bucket, k, start, end) {
|
|
285
|
+
const res = await request('GET', `/object/${encodeURIComponent(bucket)}/${enc(k)}`, { stream: true, ok: [200, 206], extra: { range: `bytes=${start}-${end}` } });
|
|
286
|
+
if (res.status !== 206) {
|
|
287
|
+
await res.body?.cancel().catch(() => {});
|
|
288
|
+
return null;
|
|
289
|
+
}
|
|
290
|
+
return Buffer.from(await res.arrayBuffer());
|
|
291
|
+
},
|
|
242
292
|
remove: (bucket, keys) => request('DELETE', `/object/${encodeURIComponent(bucket)}`, { json: { prefixes: keys } }),
|
|
243
293
|
};
|
|
244
294
|
}
|
|
@@ -399,4 +449,4 @@ function fileSizeLimit(config = {}) {
|
|
|
399
449
|
/** Cible : poad.io avec --env/--project, sinon l'engine local */
|
|
400
450
|
const target = (opts = {}, deps) => (opts.env || opts.project ? cloudTarget(opts) : localTarget(deps));
|
|
401
451
|
|
|
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 };
|
|
452
|
+
module.exports = { RETRY_STATUS, MIN_RATE, TIMEOUT_MS, 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 };
|