poad 2.77.0 → 2.78.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/utils/seed/run.js CHANGED
@@ -110,7 +110,7 @@ async function pushTable(id, t, { mode, source, onProgress }) {
110
110
  const written = await encryptFile(t.file, enc, key(prep.key));
111
111
  if (written !== stored) throw new api.CloudError(`internal: encrypted size ${written} differs from ${stored}`);
112
112
  if (prep.upload.kind === 'single') {
113
- await putWithRetry(prep.upload.url, fs.readFileSync(enc));
113
+ await putWithRetry(prep.upload.url, fs.readFileSync(enc), { onSent: (n) => onProgress && onProgress(n, stored) });
114
114
  onProgress && onProgress(stored, stored);
115
115
  } else {
116
116
  const { part_size: size, urls, upload_id: uploadId } = prep.upload;
@@ -121,7 +121,8 @@ async function pushTable(id, t, { mode, source, onProgress }) {
121
121
  const len = Math.min(size, stored - i * size);
122
122
  const buf = Buffer.alloc(len);
123
123
  fs.readSync(fd, buf, 0, len, i * size);
124
- const etag = await putWithRetry(urls[i], buf);
124
+ // Octets de cette partie au fil de l'envoi : la progression avance même sur une partie de 32 Mo
125
+ const etag = await putWithRetry(urls[i], buf, { onSent: (n) => onProgress && onProgress(i * size + n, stored) });
125
126
  parts.push({ n: i + 1, etag });
126
127
  onProgress && onProgress(Math.min(stored, (i + 1) * size), stored);
127
128
  }
@@ -135,35 +136,80 @@ async function pushTable(id, t, { mode, source, onProgress }) {
135
136
  return { ...r, uploaded: !prep.exists, stored };
136
137
  }
137
138
 
138
- async function putWithRetry(url, buf, tries = 3) {
139
+ /** Délai sans aucun octet envoyé (ni réponse) avant de dire un envoi bloqué (POAD_STALL_TIMEOUT, s) */
140
+ const stallMs = () => {
141
+ const v = Number(process.env.POAD_STALL_TIMEOUT);
142
+ return Number.isFinite(v) && v > 0 ? v * 1000 : 5 * 60 * 1000;
143
+ };
144
+
145
+ /**
146
+ * PUT d'un morceau vers une URL signée, en flux de 64 Kio : onSent(octets) au fil de l'envoi. Délai
147
+ * d'INACTIVITÉ (une connexion lente qui avance n'est jamais coupée, une connexion figée l'est), puis attente
148
+ * de la réponse. Nouvelles tentatives sur coupure, délai ou 5xx : 1 s, 2 s, 4 s… (5 essais).
149
+ */
150
+ async function putWithRetry(url, buf, { tries = 5, onSent, stall = stallMs(), fetchImpl = fetch, sleep } = {}) {
151
+ const wait = sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
139
152
  let last;
140
153
  for (let i = 0; i < tries; i++) {
154
+ const ctl = new AbortController();
155
+ let timer = null;
156
+ const arm = () => {
157
+ clearTimeout(timer);
158
+ timer = setTimeout(() => ctl.abort(), stall);
159
+ };
160
+ let at = 0;
161
+ const body = new ReadableStream({
162
+ pull(c) {
163
+ if (at >= buf.length) return c.close();
164
+ const end = Math.min(buf.length, at + 64 * 1024);
165
+ c.enqueue(new Uint8Array(buf.buffer, buf.byteOffset + at, end - at));
166
+ at = end;
167
+ arm();
168
+ if (onSent) onSent(at);
169
+ },
170
+ });
171
+ arm();
141
172
  try {
142
- const res = await fetch(url, { method: 'PUT', body: buf, headers: { 'content-type': 'application/octet-stream' }, signal: AbortSignal.timeout(15 * 60 * 1000) });
173
+ const res = await fetchImpl(url, { method: 'PUT', body, duplex: 'half', headers: { 'content-type': 'application/octet-stream', 'content-length': String(buf.length) }, signal: ctl.signal });
174
+ clearTimeout(timer);
143
175
  if (res.ok) return res.headers.get('etag') || '';
144
176
  last = new Error(`storage refused the upload (HTTP ${res.status})`);
145
- if (res.status < 500) break;
177
+ if (res.status < 500 && res.status !== 408 && res.status !== 429) break;
146
178
  } catch (e) {
147
- last = e;
179
+ clearTimeout(timer);
180
+ last = ctl.signal.aborted ? new Error(`no progress for ${Math.round(stall / 1000)} s (connection lost or too slow)`) : e;
148
181
  }
149
- await new Promise((r) => setTimeout(r, 1000 * (i + 1)));
182
+ if (onSent) onSent(0);
183
+ if (i < tries - 1) await wait(Math.min(30000, 1000 * 2 ** i));
150
184
  }
151
185
  throw new api.CloudError(`Upload failed: ${last && last.message}`, { code: 'seed_upload_failed' });
152
186
  }
153
187
 
154
188
  /** Attend la fin d'un chargement hébergé ; onStep à chaque changement */
155
- async function waitLoad(id, loadId, { onStep, interval = 2000, timeout = 60 * 60 * 1000 } = {}) {
189
+ async function waitLoad(id, loadId, { onStep, interval = 2000, timeout = 4 * 60 * 60 * 1000, unreachable = 5 * 60 * 1000 } = {}) {
156
190
  const until = Date.now() + timeout;
157
191
  let seen = '';
192
+ let lost = null;
158
193
  for (;;) {
159
- const l = await api.call('GET', `v1/projects/${api.enc(id)}/seeds/loads/${api.enc(loadId)}`, { what: 'seed load' });
194
+ let l;
195
+ try {
196
+ l = await api.call('GET', `v1/projects/${api.enc(id)}/seeds/loads/${api.enc(loadId)}`, { what: 'seed load' });
197
+ lost = null;
198
+ } catch (e) {
199
+ // Connexion qui saute pendant que poad.io charge : le chargement continue là-bas, on redemande
200
+ if (e.code !== 'network_error') throw e;
201
+ lost = lost || Date.now();
202
+ if (Date.now() - lost > unreachable) throw new api.CloudError(`poad.io unreachable for ${Math.round(unreachable / 60000)} min while it loads the references (${e.message}); the load goes on there: "poad ref ls" shows it.`, { code: 'network_error' });
203
+ await new Promise((r) => setTimeout(r, interval));
204
+ continue;
205
+ }
160
206
  const sig = JSON.stringify(l.steps.map((s) => s.status));
161
207
  if (sig !== seen) {
162
208
  seen = sig;
163
209
  onStep && onStep(l);
164
210
  }
165
211
  if (l.status !== 'running') return l;
166
- if (Date.now() > until) throw new api.CloudError('Still loading after an hour: "poad seed ls" shows the progress.', { code: 'timeout' });
212
+ if (Date.now() > until) throw new api.CloudError('Still loading after 4 hours: "poad ref ls" shows the progress.', { code: 'timeout' });
167
213
  await new Promise((r) => setTimeout(r, interval));
168
214
  }
169
215
  }
@@ -276,4 +322,4 @@ function localEdges(container) {
276
322
  });
277
323
  }
278
324
 
279
- module.exports = { convertFile, pushTable, waitLoad, loadLocal, loadLocalFile, localState, localLog, localEdges, fmt, tmpDir };
325
+ module.exports = { convertFile, pushTable, putWithRetry, waitLoad, loadLocal, loadLocalFile, localState, localLog, localEdges, fmt, tmpDir };
@@ -155,8 +155,14 @@ function plan(src, dst, { prune = false } = {}) {
155
155
  * la commande, reprend là où la destination en est (clé de reprise : destination + empreinte du contenu).
156
156
  * Sinon : une requête, en flux, sous un délai d'inactivité (utils/storage.js).
157
157
  */
158
- async function copyBytes(from, to, bucket, o, { onResume, sleep } = {}) {
158
+ async function copyBytes(from, to, bucket, o, { onResume, sleep, onBytes } = {}) {
159
159
  const t = require('./storage-tus');
160
+ // Octets de ce fichier déjà sur la cible (envoyés, ou trouvés là à la reprise) : onBytes(écart) à chaque avancée
161
+ let sent = 0;
162
+ const reach = (n) => {
163
+ if (onBytes && n > sent) onBytes(n - sent);
164
+ if (n > sent) sent = n;
165
+ };
160
166
  if (Number.isFinite(o.size) && o.size > t.CHUNK && to.raw && !to.noTus) {
161
167
  const type = o.mimetype || 'application/octet-stream';
162
168
  let source = await t.rangeSource(from, bucket, o.name, o.size).catch(() => null);
@@ -166,7 +172,7 @@ async function copyBytes(from, to, bucket, o, { onResume, sleep } = {}) {
166
172
  source = t.streamSource(res.body, o.size);
167
173
  }
168
174
  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 });
175
+ 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: (offset) => (reach(offset), onResume && onResume(offset)), onProgress: (offset) => reach(offset), sleep });
170
176
  return o.size;
171
177
  } catch (e) {
172
178
  if (e.code !== 'tus_unsupported') throw e;
@@ -175,8 +181,12 @@ async function copyBytes(from, to, bucket, o, { onResume, sleep } = {}) {
175
181
  }
176
182
  }
177
183
  const res = await from.get(bucket, o.name);
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 });
179
- return o.size || Number(res.headers.get('content-length')) || 0;
184
+ // Compté au fil de la lecture (fetch lit la source au rythme où la cible reçoit)
185
+ const body = onBytes && res.body ? res.body.pipeThrough(new TransformStream({ transform: (c, ctl) => (reach(sent + c.length), ctl.enqueue(c)) })) : res.body;
186
+ await to.put(bucket, o.name, body, { type: o.mimetype || res.headers.get('content-type') || 'application/octet-stream', cacheControl: o.cacheControl || undefined, length: Number.isFinite(o.size) ? o.size : undefined });
187
+ const n = o.size || Number(res.headers.get('content-length')) || 0;
188
+ reach(n);
189
+ return n;
180
190
  }
181
191
 
182
192
  /** Une nouvelle tentative a-t-elle un sens (coupure, délai, 5xx, 429) ? Un refus (4xx) est définitif. Pure. */
@@ -294,6 +304,8 @@ async function sync(from, to, opts = {}) {
294
304
  };
295
305
  const result = { mode, reason, from: srcLoc, to: dstLoc, buckets: plans, totals, errors: [], dryRun: Boolean(opts.dryRun) };
296
306
  if (opts.dryRun) return result;
307
+ // Ce qui va partir : fichiers et octets (barre de progression de l'appelant)
308
+ if (opts.onPlan) opts.onPlan({ files: totals.added + totals.updated, bytes: mode === 'bytes' ? plans.reduce((n, p) => n + [...p.add, ...p.update].reduce((m, o) => m + (Number.isFinite(o.size) ? o.size : 0), 0), 0) : 0, mode });
297
309
  if (opts.confirm && (totals.updated || totals.removed)) await opts.confirm(totals);
298
310
 
299
311
  // Références : la source note aussi que son lieu sert à un autre environnement du projet ; ses
@@ -350,8 +362,18 @@ async function sync(from, to, opts = {}) {
350
362
  const errs = await adaptive(
351
363
  work,
352
364
  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 }) });
365
+ event({ bucket: p.bucket, name: o.name, action: 'start', size: o.size });
366
+ // Octets comptés pendant cet essai : retirés s'il échoue (l'essai suivant les recompte)
367
+ let counted = 0;
368
+ const onBytes = opts.onBytes ? (d) => ((counted += d), opts.onBytes(d)) : undefined;
369
+ let n;
370
+ try {
371
+ // Lu après l'attente : « totals.bytes += await … » perdrait les transferts parallèles
372
+ n = await copyBytes(from, to, p.bucket, o, { sleep: opts.sleep, onBytes, onResume: (offset) => offset > 0 && event({ bucket: p.bucket, name: o.name, action: 'resume', offset, size: o.size }) });
373
+ } catch (e) {
374
+ if (counted && opts.onBytes) opts.onBytes(-counted);
375
+ throw e;
376
+ }
355
377
  totals.bytes += n;
356
378
  sent.push([action, o]);
357
379
  done(action, o);
package/utils/storage.js CHANGED
@@ -218,9 +218,25 @@ function client({ base, key, apikey, renew, fetch: doFetch = fetch, timeout = TI
218
218
  /** Réponse fetch brute, quel que soit son code (envois en morceaux, utils/storage-tus.js) */
219
219
  async function raw(method, route, { headers: extra = {}, body } = {}) {
220
220
  await fresh();
221
- const wd = watchdog(timeoutFor(body && body.length, timeout * 4));
221
+ // Morceau en mémoire (TUS, 6 Mio) : envoyé par pièces de 64 Kio, le délai repart à chaque pièce. Une
222
+ // connexion très lente qui avance n'est jamais coupée ; une connexion figée l'est après timeout × 4.
223
+ const big = Buffer.isBuffer(body) && body.length > 256 * 1024;
224
+ const wd = watchdog(big ? timeout * 4 : timeoutFor(body && body.length, timeout * 4));
225
+ let sendBody = body;
226
+ if (big) {
227
+ let at = 0;
228
+ sendBody = new ReadableStream({
229
+ pull(c) {
230
+ if (at >= body.length) return c.close();
231
+ const end = Math.min(body.length, at + 64 * 1024);
232
+ c.enqueue(new Uint8Array(body.buffer, body.byteOffset + at, end - at));
233
+ at = end;
234
+ wd.bump();
235
+ },
236
+ });
237
+ }
222
238
  try {
223
- return await doFetch(`${base}/storage/v1${route}`, { method, headers: headers({ ...(body ? { 'content-length': String(body.length) } : {}), ...extra }), body, signal: wd.signal });
239
+ return await doFetch(`${base}/storage/v1${route}`, { method, headers: headers({ ...(body ? { 'content-length': String(body.length) } : {}), ...extra }), body: sendBody, ...(big ? { duplex: 'half' } : {}), signal: wd.signal });
224
240
  } catch (err) {
225
241
  throw failed(err, wd);
226
242
  } finally {