@nestjs/observe 0.1.4 → 0.1.5

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.
@@ -48,6 +48,42 @@ export const detachedObserveWorker = () => {
48
48
  * that it never competes with anything.
49
49
  */
50
50
  const AUTH_REJECTION_REPORT_EVERY = 720;
51
+ /**
52
+ * When sending may resume after the collector answered 429.
53
+ *
54
+ * A 429 means the account is out of credits or over budget, and that does
55
+ * not change batch to batch: retrying at the flush cadence is sixty more
56
+ * refusals in five minutes, each costing the collector a request and this
57
+ * process a log line. So sends pause outright. The main thread keeps
58
+ * overwriting the shared buffer with newer batches in the meantime - the
59
+ * buffer holds exactly one, so pausing drops data by replacement rather
60
+ * than growing a queue - and once the pause lapses the next flush goes out
61
+ * normally. If the collector is still refusing, it answers 429 again and
62
+ * the pause restarts.
63
+ */
64
+ let rateLimitedUntil = 0;
65
+ /**
66
+ * How long to pause when the 429 carries no usable Retry-After. Long enough
67
+ * that a depleted account is not being polled, short enough that a topped-up
68
+ * one resumes within minutes.
69
+ */
70
+ const RATE_LIMIT_PAUSE_MS = 5 * 60 * 1000;
71
+ /** Ceiling on a server-sent Retry-After, so a bad header cannot park the
72
+ * worker for a day. */
73
+ const RATE_LIMIT_PAUSE_MAX_MS = 60 * 60 * 1000;
74
+ /**
75
+ * How long to pause for, from the response's Retry-After when it carries
76
+ * one. Only the delta-seconds form is parsed - the HTTP-date form is rare
77
+ * on rate limits and mis-parsing it risks an enormous pause - and anything
78
+ * absent, malformed, or out of range falls back to the default.
79
+ */
80
+ const rateLimitPauseMs = (response) => {
81
+ const retryAfter = Number(response.headers.get("retry-after"));
82
+ if (Number.isFinite(retryAfter) && retryAfter > 0) {
83
+ return Math.min(retryAfter * 1000, RATE_LIMIT_PAUSE_MAX_MS);
84
+ }
85
+ return RATE_LIMIT_PAUSE_MS;
86
+ };
51
87
  /**
52
88
  * How long to block waiting for the main thread to release the lock, and how
53
89
  * long to sleep when the buffer holds nothing.
@@ -96,6 +132,12 @@ export const detachedObserveWorker = () => {
96
132
  * immediately or to sleep first.
97
133
  */
98
134
  const sendInstrumentationJsonData = async () => {
135
+ if (Date.now() < rateLimitedUntil) {
136
+ // Rate-limited: not even worth taking the lock. Returning false routes
137
+ // through the idle sleep, and the main thread goes on replacing the
138
+ // buffered batch with fresher ones.
139
+ return false;
140
+ }
99
141
  waitWhileLocked();
100
142
  if (!acquireLock()) {
101
143
  // Lost the race to the main thread, which is flushing. Nothing to report
@@ -145,6 +187,16 @@ export const detachedObserveWorker = () => {
145
187
  }
146
188
  return true;
147
189
  }
190
+ if (response.status === 429) {
191
+ const pauseMs = rateLimitPauseMs(response);
192
+ rateLimitedUntil = Date.now() + pauseMs;
193
+ // One line per pause window, so a long depletion reads as one line
194
+ // every few minutes rather than one per flush. The batch is dropped
195
+ // - `finally` clears the buffer - same as every other failure here.
196
+ parentPort.postMessage(`Error: Telemetry rate-limited (429) - the account may be out of credits or over budget. ` +
197
+ `Pausing sends for ${Math.round(pauseMs / 60000)} minute(s); batches in the meantime are dropped.`);
198
+ return true;
199
+ }
148
200
  // Read as text, defensively: an error body is not guaranteed to be
149
201
  // JSON, and a parse failure here must not fall through to the catch
150
202
  // below and report a reachable collector as unreachable.
@@ -20,6 +20,12 @@ export declare class ProfileUploader {
20
20
  private readonly options;
21
21
  private readonly pending;
22
22
  private inFlight;
23
+ /**
24
+ * When uploads may resume after a 429. Windows enqueued while paused sit in
25
+ * `pending` under its usual two-window cap, so a lapsed pause resumes with
26
+ * the freshest profiles rather than a backlog.
27
+ */
28
+ private rateLimitedUntil;
23
29
  constructor(options: ProfileUploaderOptions);
24
30
  enqueue(window: ProfileWindow, sampleRateHz: number): void;
25
31
  /**
@@ -41,5 +47,12 @@ export declare class ProfileUploader {
41
47
  * that path retries and the entitlement path discards.
42
48
  */
43
49
  private isEntitlementError;
50
+ /**
51
+ * How long to pause for, honouring the response's Retry-After when it
52
+ * carries one. Only the delta-seconds form is parsed - the HTTP-date form
53
+ * is rare on rate limits and mis-parsing it risks an enormous pause - and
54
+ * anything absent, malformed, or out of range falls back to the default.
55
+ */
56
+ private rateLimitPauseMs;
44
57
  pendingCount(): number;
45
58
  }
@@ -8,6 +8,15 @@
8
8
  * that the oldest is dropped.
9
9
  */
10
10
  const MAX_PENDING_WINDOWS = 2;
11
+ /**
12
+ * How long to stop uploading after a 429, when the response carries no usable
13
+ * Retry-After. Out-of-credits does not clear between windows, so retrying at
14
+ * the once-a-minute cadence only spends requests on refusals.
15
+ */
16
+ const RATE_LIMIT_PAUSE_MS = 5 * 60 * 1000;
17
+ /** Ceiling on a server-sent Retry-After, so a bad header cannot park uploads
18
+ * for a day. */
19
+ const RATE_LIMIT_PAUSE_MAX_MS = 60 * 60 * 1000;
11
20
  /**
12
21
  * Ships one folded-stack window per upload.
13
22
  *
@@ -21,6 +30,12 @@ export class ProfileUploader {
21
30
  options;
22
31
  pending = [];
23
32
  inFlight = false;
33
+ /**
34
+ * When uploads may resume after a 429. Windows enqueued while paused sit in
35
+ * `pending` under its usual two-window cap, so a lapsed pause resumes with
36
+ * the freshest profiles rather than a backlog.
37
+ */
38
+ rateLimitedUntil = 0;
24
39
  constructor(options) {
25
40
  this.options = options;
26
41
  }
@@ -42,7 +57,7 @@ export class ProfileUploader {
42
57
  * duplicate rather than an addition.
43
58
  */
44
59
  async drain() {
45
- if (this.inFlight) {
60
+ if (this.inFlight || Date.now() < this.rateLimitedUntil) {
46
61
  return;
47
62
  }
48
63
  this.inFlight = true;
@@ -94,6 +109,18 @@ export class ProfileUploader {
94
109
  this.options.onError?.("profiling is not included in this plan; discarding the window");
95
110
  return true;
96
111
  }
112
+ if (response.status === 429) {
113
+ // Out of credits or over budget. Pause outright instead of retrying
114
+ // every minute: the answer will not change window to window, and each
115
+ // retry is a request spent on a refusal. The window stays queued -
116
+ // `drain` skips while paused - so the first upload after the pause
117
+ // carries the freshest profiles the two-window cap kept.
118
+ const pauseMs = this.rateLimitPauseMs(response);
119
+ this.rateLimitedUntil = Date.now() + pauseMs;
120
+ this.options.onError?.(`profile upload rate-limited (429) - the account may be out of credits or over budget; ` +
121
+ `pausing uploads for ${Math.round(pauseMs / 60000)} minute(s)`);
122
+ return false;
123
+ }
97
124
  if (response.status === 401 || response.status === 403) {
98
125
  // A credential problem, not an entitlement one. Reported specifically
99
126
  // and not discarded: it is a misconfiguration the operator can fix,
@@ -134,6 +161,19 @@ export class ProfileUploader {
134
161
  return false;
135
162
  }
136
163
  }
164
+ /**
165
+ * How long to pause for, honouring the response's Retry-After when it
166
+ * carries one. Only the delta-seconds form is parsed - the HTTP-date form
167
+ * is rare on rate limits and mis-parsing it risks an enormous pause - and
168
+ * anything absent, malformed, or out of range falls back to the default.
169
+ */
170
+ rateLimitPauseMs(response) {
171
+ const retryAfter = Number(response.headers.get("retry-after"));
172
+ if (Number.isFinite(retryAfter) && retryAfter > 0) {
173
+ return Math.min(retryAfter * 1000, RATE_LIMIT_PAUSE_MAX_MS);
174
+ }
175
+ return RATE_LIMIT_PAUSE_MS;
176
+ }
137
177
  pendingCount() {
138
178
  return this.pending.length;
139
179
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nestjs/observe",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
4
4
  "description": "Observability and APM agent for NestJS - traces, runtime metrics, custom metrics and CPU profiles",
5
5
  "author": "Kamil Mysliwiec",
6
6
  "homepage": "https://nestjs.com",