sliftutils 1.8.20 → 1.9.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/index.d.ts CHANGED
@@ -60,6 +60,7 @@ declare module "sliftutils/misc/getSecret" {
60
60
  }
61
61
 
62
62
  declare module "sliftutils/misc/helpers" {
63
+ export declare function throwDetached(error: unknown): void;
63
64
  export declare function waitForDiskCollectionFlush(): Promise<void>;
64
65
 
65
66
  }
@@ -3023,6 +3024,9 @@ declare module "sliftutils/storage/backblaze" {
3023
3024
  private getBucketAPI;
3024
3025
  private currentReset;
3025
3026
  private last503Reset;
3027
+ private lastAPIReset;
3028
+ private consecutiveFailures;
3029
+ private resetAPIs;
3026
3030
  private apiRetryLogic;
3027
3031
  get(fileName: string, config?: GetConfig): Promise<Buffer | undefined>;
3028
3032
  get2(fileName: string, config?: GetConfig): Promise<{
package/misc/helpers.d.ts CHANGED
@@ -1 +1,2 @@
1
+ export declare function throwDetached(error: unknown): void;
1
2
  export declare function waitForDiskCollectionFlush(): Promise<void>;
package/misc/helpers.ts CHANGED
@@ -1,6 +1,12 @@
1
1
  import { delay } from "socket-function/src/batching";
2
2
  import { hasPending } from "../storage/PendingManager";
3
3
 
4
+ export function throwDetached(error: unknown): void {
5
+ void Promise.resolve().then(() => {
6
+ throw error;
7
+ });
8
+ }
9
+
4
10
  export async function waitForDiskCollectionFlush() {
5
11
  await delay(2000);
6
12
  while (hasPending()) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sliftutils",
3
- "version": "1.8.20",
3
+ "version": "1.9.0",
4
4
  "main": "index.js",
5
5
  "license": "MIT",
6
6
  "files": [
@@ -21,6 +21,9 @@ export declare class ArchivesBackblaze implements IArchives {
21
21
  private getBucketAPI;
22
22
  private currentReset;
23
23
  private last503Reset;
24
+ private lastAPIReset;
25
+ private consecutiveFailures;
26
+ private resetAPIs;
24
27
  private apiRetryLogic;
25
28
  get(fileName: string, config?: GetConfig): Promise<Buffer | undefined>;
26
29
  get2(fileName: string, config?: GetConfig): Promise<{
@@ -29,6 +29,9 @@ let backblazeCreds = lazy(async (): Promise<BackblazeCreds> => {
29
29
  const MIN_BUCKET_CACHE_TIME = 60 * 1000;
30
30
  // Backblaze requires 5MB chunks for large files, but larger is more efficient for us (and their "last part" size check misbehaves on retries, which chunks this big sidestep - see setLargeFile)
31
31
  const LARGE_FILE_MIN_CHUNK_SIZE = 32 * 1024 * 1024;
32
+ const CONSECUTIVE_FAILURES_BEFORE_RESET = 10;
33
+ const MIN_API_RESET_INTERVAL = 1000;
34
+ const CONNECTION_DEAD_MARKERS = ["TLS", "ECONNRESET", "ECONNREFUSED", "EPIPE", "socket hang up", "socket disconnected"];
32
35
 
33
36
  // A B2 download/HEAD response's headers carry the file's metadata. content-range's total wins over content-length for ranged responses (which only report the slice's length).
34
37
  function parseFileMetadataHeaders(response: HttpsResponseInfo): { size: number; writeTime: number } {
@@ -562,6 +565,17 @@ export class ArchivesBackblaze implements IArchives {
562
565
 
563
566
  // Keep track of when we last reset because of a 503
564
567
  private last503Reset = 0;
568
+ private lastAPIReset = 0;
569
+ private consecutiveFailures = 0;
570
+
571
+ private resetAPIs(context: string, reason: string, err: Error) {
572
+ if (Date.now() - this.lastAPIReset < MIN_API_RESET_INTERVAL) return;
573
+ this.lastAPIReset = Date.now();
574
+ console.warn(`[${context}] Resetting getAPI and getBucketAPI for ${this.getDebugName()} (${reason}, ${this.consecutiveFailures} consecutive failures): ${err.message}`);
575
+ getAPI.reset();
576
+ this.getBucketAPI.reset();
577
+ this.consecutiveFailures = 0;
578
+ }
565
579
  // IMPORTANT! We must always CATCH AROUND the apiRetryLogic, NEVER inside of fnc. Otherwise we won't be able to recreate the auth token. `context` is a short label (verb + file path) included in every retry/error log so a stuck silent-retry loop is identifiable from the logs.
566
580
  private async apiRetryLogic<T>(
567
581
  context: string,
@@ -571,10 +585,10 @@ export class ArchivesBackblaze implements IArchives {
571
585
  let api: B2Api | undefined;
572
586
  try {
573
587
  api = await this.getBucketAPI();
574
- return await fnc(api);
588
+ let result = await fnc(api);
589
+ this.consecutiveFailures = 0;
590
+ return result;
575
591
  } catch (err: any) {
576
- if (retries <= 0) throw err;
577
-
578
592
  // A file that does not exist is an answer, not a failure. It is the one error here that
579
593
  // cannot become anything else by asking again, so it is thrown at once instead of being
580
594
  // slept on twice - callers turn it into undefined, which is what they were asking.
@@ -583,9 +597,21 @@ export class ArchivesBackblaze implements IArchives {
583
597
  || err.stack.includes(`file_not_found`)
584
598
  || err.stack.includes(`"status": 404`)
585
599
  ) {
600
+ this.consecutiveFailures = 0;
586
601
  throw err;
587
602
  }
588
603
 
604
+ this.consecutiveFailures++;
605
+ if (!api) {
606
+ this.resetAPIs(context, "acquiring the api failed, so the lazy holds a rejected promise", err);
607
+ } else if (CONNECTION_DEAD_MARKERS.some(marker => err.stack.includes(marker))) {
608
+ this.resetAPIs(context, "connection level error", err);
609
+ } else if (this.consecutiveFailures >= CONSECUTIVE_FAILURES_BEFORE_RESET) {
610
+ this.resetAPIs(context, `${CONSECUTIVE_FAILURES_BEFORE_RESET} calls in a row failed`, err);
611
+ }
612
+
613
+ if (retries <= 0) throw err;
614
+
589
615
  // If it's a 503 and it's been a minute since we last reset, then Wait and reset.
590
616
  if (
591
617
  (err.stack.includes(`"status": 503`)
@@ -1,4 +1,5 @@
1
1
  import { runInfinitePoll } from "socket-function/src/batching";
2
+ import { throwDetached } from "../../misc/helpers";
2
3
  import {
3
4
  IArchives, ArchiveFileInfo, ArchivesConfig, ArchivesSyncStatus, ChangesAfterConfig, DelConfig,
4
5
  FindConfig, GetConfig, GetInfoConfig, SetConfig, SetLargeFileConfig, SourceConfig,
@@ -105,8 +106,13 @@ export class ArchivesDelayed implements IArchives {
105
106
  let deadlineReached = force || this.deadlinePassed();
106
107
  for (let [fileName, entry] of [...this.pending]) {
107
108
  if (!deadlineReached && entry.dueAt > now) continue;
109
+ try {
110
+ await this.write(fileName, entry);
111
+ } catch (e) {
112
+ throwDetached(new Error(`Flushing ${JSON.stringify(fileName)} (${entry.data.length} bytes, writeTime ${entry.writeTime}) to ${this.inner.getDebugName()} failed, it stays pending: ${(e as Error).stack ?? e}`));
113
+ continue;
114
+ }
108
115
  // Only drop it if it wasn't overwritten while we were writing
109
- await this.write(fileName, entry);
110
116
  if (this.pending.get(fileName) === entry) {
111
117
  this.pending.delete(fileName);
112
118
  }