@andrian.yablonskyy/thub-common 1.0.31 → 1.0.33

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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/src/api-client.js +29 -3
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andrian.yablonskyy/thub-common",
3
- "version": "1.0.31",
3
+ "version": "1.0.33",
4
4
  "description": "Shared job-spec schema, state enums and a thin API client used by the Agent and Client",
5
5
  "main": "src/index.js",
6
6
  "files": [
package/src/api-client.js CHANGED
@@ -19,6 +19,21 @@
19
19
  * both speak the exact same protocol (README.md §1: "This keeps CI
20
20
  * and manual usage identical").
21
21
  */
22
+ const RATE_LIMIT_RETRIES = 3,
23
+ RATE_LIMIT_MAX_WAIT_SEC = 60;
24
+
25
+ // Resolves after `ms`, or early (no rejection) once `signal` aborts — the
26
+ // caller's next fetch then rejects with the abort as usual.
27
+ function sleep(ms, signal){
28
+ return new Promise((resolve) => {
29
+ const timer = setTimeout(resolve, ms);
30
+ signal?.addEventListener('abort', () => {
31
+ clearTimeout(timer);
32
+ resolve();
33
+ }, { once: true });
34
+ });
35
+ }
36
+
22
37
  class ApiClient{
23
38
  // `userAgent` (e.g. "thub-agent/1.0.8") is how the Coordinator learns
24
39
  // which Agent/Client version is talking to it, for the dashboard.
@@ -58,7 +73,7 @@ class ApiClient{
58
73
  }
59
74
 
60
75
  const isJsonBody = body !== undefined && !(body instanceof FormData),
61
- res = await fetch(url, {
76
+ send = () => fetch(url, {
62
77
  method,
63
78
  signal,
64
79
  headers: this._headers({
@@ -66,9 +81,20 @@ class ApiClient{
66
81
  ...headers
67
82
  }),
68
83
  body: isJsonBody ? JSON.stringify(body) : body
69
- }),
84
+ });
85
+
86
+ // 429 (the Coordinator's rate limit): wait as long as Retry-After says
87
+ // (capped) and try again, a few times, instead of failing the command
88
+ // or the job outright.
89
+ let res = await send();
90
+ for (let attempt = 1; res.status === 429 && attempt <= RATE_LIMIT_RETRIES && !signal?.aborted; attempt++){
91
+ const waitSec = Math.min(Number(res.headers.get('retry-after')) || attempt * 2, RATE_LIMIT_MAX_WAIT_SEC);
92
+ await res.text().catch(() => {});
93
+ await sleep(waitSec * 1000, signal);
94
+ res = await send();
95
+ }
70
96
 
71
- text = await res.text(),
97
+ const text = await res.text(),
72
98
  data = text ? safeJson(text) : undefined;
73
99
 
74
100
  if (!res.ok){