@richardmcquiston01/error-log-adapter 0.7.0 → 0.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/dist/index.mjs CHANGED
@@ -140,6 +140,12 @@ var ConsoleErrorAdapter = class {
140
140
  }
141
141
  };
142
142
 
143
+ // src/backoff.ts
144
+ function backoffDelayMs(retryNumber, baseMs, maxMs) {
145
+ const ceiling = Math.min(maxMs, baseMs * 2 ** (retryNumber - 1));
146
+ return ceiling / 2 + Math.random() * ceiling / 2;
147
+ }
148
+
143
149
  // src/uuid.ts
144
150
  function generateId() {
145
151
  const cryptoApi = globalThis.crypto;
@@ -241,10 +247,10 @@ async function hmacSha256Hex(secret, message) {
241
247
  "signingSecret needs Web Crypto (crypto.subtle), which this runtime does not provide, so the entry was not sent unsigned"
242
248
  );
243
249
  }
244
- const encoder = new TextEncoder();
250
+ const encoder2 = new TextEncoder();
245
251
  const key = await subtle.importKey(
246
252
  "raw",
247
- encoder.encode(secret),
253
+ encoder2.encode(secret),
248
254
  { name: "HMAC", hash: "SHA-256" },
249
255
  false,
250
256
  ["sign"]
@@ -252,7 +258,7 @@ async function hmacSha256Hex(secret, message) {
252
258
  const signature = await subtle.sign(
253
259
  "HMAC",
254
260
  key,
255
- encoder.encode(message)
261
+ encoder2.encode(message)
256
262
  );
257
263
  return Array.from(
258
264
  new Uint8Array(signature),
@@ -351,6 +357,36 @@ var WebhookErrorAdapter = class {
351
357
  `could not prepare the entry: ${this.redact(describeError(error))}`
352
358
  );
353
359
  }
360
+ return this.deliver(body);
361
+ }
362
+ /**
363
+ * Sends several entries in one request, as a JSON array of the same records
364
+ * `log` sends one at a time (each with an `id`). `BatchingErrorAdapter` uses
365
+ * this when it wraps a webhook, so the receiver must accept an array. The
366
+ * whole request succeeds or fails together.
367
+ */
368
+ async logBatch(entries) {
369
+ if (entries.length === 0) {
370
+ return { ok: true };
371
+ }
372
+ let body;
373
+ try {
374
+ body = JSON.stringify(
375
+ entries.map((entry) => ({
376
+ id: resolveEntryId(entry),
377
+ ...serializeEntry(entry)
378
+ }))
379
+ );
380
+ } catch (error) {
381
+ console.error(`${this.prefix} WebhookErrorAdapter:`, error);
382
+ return this.fail(
383
+ `could not prepare the entries: ${this.redact(describeError(error))}`
384
+ );
385
+ }
386
+ return this.deliver(body);
387
+ }
388
+ /** Sends one prepared body, trying again as `retries` allows. */
389
+ async deliver(body) {
354
390
  let attempt = await this.send(body);
355
391
  let attempts = 1;
356
392
  while (!attempt.ok && attempt.retryable && attempts <= this.retries) {
@@ -370,11 +406,7 @@ var WebhookErrorAdapter = class {
370
406
  if (retryAfterMs !== void 0) {
371
407
  return Math.min(retryAfterMs, this.maxRetryDelayMs);
372
408
  }
373
- const ceiling = Math.min(
374
- this.maxRetryDelayMs,
375
- this.retryDelayMs * 2 ** (retryNumber - 1)
376
- );
377
- return ceiling / 2 + Math.random() * ceiling / 2;
409
+ return backoffDelayMs(retryNumber, this.retryDelayMs, this.maxRetryDelayMs);
378
410
  }
379
411
  async send(body) {
380
412
  const controller = new AbortController();
@@ -1806,7 +1838,547 @@ var WebSocketErrorAdapter = class {
1806
1838
  }
1807
1839
  }
1808
1840
  };
1841
+
1842
+ // src/adapters/cloudwatch-logs-error-adapter.ts
1843
+ var MAX_EVENT_BYTES = 262144;
1844
+ var EVENT_OVERHEAD_BYTES = 26;
1845
+ var MAX_BATCH_BYTES = 1048576;
1846
+ var MAX_BATCH_EVENTS = 1e4;
1847
+ var MAX_BATCH_SPAN_MS = 24 * 60 * 60 * 1e3;
1848
+ var BUFFER_LIMIT_MULTIPLIER2 = 10;
1849
+ var encoder = new TextEncoder();
1850
+ function eventBytes(message) {
1851
+ return encoder.encode(message).length + EVENT_OVERHEAD_BYTES;
1852
+ }
1853
+ function errorName(error) {
1854
+ return typeof error === "object" && error !== null ? error.name : void 0;
1855
+ }
1856
+ function splitIntoRequests(events) {
1857
+ const requests = [];
1858
+ let current = [];
1859
+ let bytes = 0;
1860
+ for (const event of events) {
1861
+ const size = eventBytes(event.message);
1862
+ const first = current[0];
1863
+ if (first !== void 0 && (current.length >= MAX_BATCH_EVENTS || bytes + size > MAX_BATCH_BYTES || event.timestamp - first.timestamp > MAX_BATCH_SPAN_MS)) {
1864
+ requests.push(current);
1865
+ current = [];
1866
+ bytes = 0;
1867
+ }
1868
+ current.push(event);
1869
+ bytes += size;
1870
+ }
1871
+ if (current.length > 0) {
1872
+ requests.push(current);
1873
+ }
1874
+ return requests;
1875
+ }
1876
+ var CloudWatchLogsErrorAdapter = class {
1877
+ /** @throws {RangeError} if a name is empty, the batch or timeout options are invalid, or `createMissing` is on but the client cannot create streams. */
1878
+ constructor(client, logGroupName, logStreamName, options = {}) {
1879
+ this.client = client;
1880
+ this.logGroupName = logGroupName;
1881
+ this.logStreamName = logStreamName;
1882
+ this.buffer = [];
1883
+ this.timer = null;
1884
+ this.flushQueue = new SerialQueue();
1885
+ this.createMissing = options.createMissing ?? true;
1886
+ this.batch = options.batch;
1887
+ this.logPrefix = options.prefix ?? DEFAULT_PREFIX;
1888
+ this.timeoutMs = resolveTimeoutMs(
1889
+ options.timeoutMs,
1890
+ "CloudWatchLogsErrorAdapter"
1891
+ );
1892
+ if (logGroupName === "") {
1893
+ throw new RangeError(
1894
+ "CloudWatchLogsErrorAdapter: logGroupName must not be empty."
1895
+ );
1896
+ }
1897
+ if (logStreamName === "") {
1898
+ throw new RangeError(
1899
+ "CloudWatchLogsErrorAdapter: logStreamName must not be empty."
1900
+ );
1901
+ }
1902
+ if (this.createMissing && typeof client.createLogStream !== "function") {
1903
+ throw new RangeError(
1904
+ "CloudWatchLogsErrorAdapter: createMissing is on, but the client has no createLogStream method. Pass createMissing: false, or use an AWS SDK CloudWatchLogs client."
1905
+ );
1906
+ }
1907
+ if (this.batch !== void 0) {
1908
+ if (!Number.isInteger(this.batch.batchSize) || this.batch.batchSize < 1) {
1909
+ throw new RangeError(
1910
+ `CloudWatchLogsErrorAdapter: batch.batchSize must be a positive integer, received ${String(this.batch.batchSize)}.`
1911
+ );
1912
+ }
1913
+ if (this.batch.maxWaitMs !== void 0 && (!Number.isFinite(this.batch.maxWaitMs) || this.batch.maxWaitMs <= 0)) {
1914
+ throw new RangeError(
1915
+ `CloudWatchLogsErrorAdapter: batch.maxWaitMs must be a positive number, received ${String(this.batch.maxWaitMs)}.`
1916
+ );
1917
+ }
1918
+ }
1919
+ }
1920
+ async log(entry) {
1921
+ try {
1922
+ const id = resolveEntryId(entry);
1923
+ const record = { id, ...serializeEntry(entry) };
1924
+ const timestamp = Date.parse(record.timestamp);
1925
+ if (Number.isNaN(timestamp)) {
1926
+ throw new RangeError(
1927
+ `timestamp "${record.timestamp}" is not a valid ISO 8601 date`
1928
+ );
1929
+ }
1930
+ const message = JSON.stringify(record);
1931
+ const size = eventBytes(message);
1932
+ if (size > MAX_EVENT_BYTES) {
1933
+ throw new RangeError(
1934
+ `the event is ${size} bytes, over the ${MAX_EVENT_BYTES} byte limit CloudWatch Logs puts on one event, so it was not sent; shorten the message or cause`
1935
+ );
1936
+ }
1937
+ const event = { id, timestamp, message };
1938
+ if (this.batch === void 0) {
1939
+ const rejection = await this.send([event]);
1940
+ if (rejection !== void 0) {
1941
+ throw new Error(rejection);
1942
+ }
1943
+ return { ok: true };
1944
+ }
1945
+ return await this.addToBatch(event, this.batch);
1946
+ } catch (error) {
1947
+ return this.fail(error);
1948
+ }
1949
+ }
1950
+ /**
1951
+ * Sends any buffered events now. Resolves ok when nothing is buffered. Events
1952
+ * from a failed send stay buffered and are retried by the next flush.
1953
+ */
1954
+ flush() {
1955
+ return this.flushQueue.run(
1956
+ () => this.sendBuffered()
1957
+ );
1958
+ }
1959
+ async addToBatch(event, batch) {
1960
+ this.buffer.push(event);
1961
+ const limit = batch.batchSize * BUFFER_LIMIT_MULTIPLIER2;
1962
+ if (this.buffer.length > limit) {
1963
+ const dropped = this.buffer.length - limit;
1964
+ this.buffer = this.buffer.slice(dropped);
1965
+ console.error(
1966
+ `${this.logPrefix} CloudWatchLogsErrorAdapter: dropped the ${dropped} oldest buffered events because sends to log stream "${this.logStreamName}" keep failing and the buffer is full (${limit} events).`
1967
+ );
1968
+ }
1969
+ if (this.buffer.length >= batch.batchSize) {
1970
+ return this.flush();
1971
+ }
1972
+ this.scheduleFlush(batch);
1973
+ return { ok: true };
1974
+ }
1975
+ scheduleFlush(batch) {
1976
+ if (batch.maxWaitMs === void 0 || this.timer !== null) {
1977
+ return;
1978
+ }
1979
+ const timer = setTimeout(() => {
1980
+ this.timer = null;
1981
+ void this.flush();
1982
+ }, batch.maxWaitMs);
1983
+ timer.unref?.();
1984
+ this.timer = timer;
1985
+ }
1986
+ async sendBuffered() {
1987
+ if (this.timer !== null) {
1988
+ clearTimeout(this.timer);
1989
+ this.timer = null;
1990
+ }
1991
+ const pending = this.buffer.slice();
1992
+ if (pending.length === 0) {
1993
+ return { ok: true };
1994
+ }
1995
+ pending.sort(
1996
+ (a, b) => a.timestamp - b.timestamp
1997
+ );
1998
+ let rejectedTotal = 0;
1999
+ let lastRejection = "";
2000
+ try {
2001
+ for (const request of splitIntoRequests(pending)) {
2002
+ const rejection = await this.send(request);
2003
+ const sent = new Set(request);
2004
+ this.buffer = this.buffer.filter(
2005
+ (event) => !sent.has(event)
2006
+ );
2007
+ if (rejection !== void 0) {
2008
+ rejectedTotal += request.length;
2009
+ lastRejection = rejection;
2010
+ }
2011
+ }
2012
+ } catch (error) {
2013
+ if (this.batch !== void 0) {
2014
+ this.scheduleFlush(this.batch);
2015
+ }
2016
+ return this.fail(error, this.buffer.length);
2017
+ }
2018
+ if (rejectedTotal > 0) {
2019
+ return this.fail(new Error(lastRejection), rejectedTotal);
2020
+ }
2021
+ return { ok: true };
2022
+ }
2023
+ /**
2024
+ * Sends one request, creating the stream first if CloudWatch says it is
2025
+ * missing. Resolves to a description of any events CloudWatch refused, or
2026
+ * undefined when it took them all.
2027
+ */
2028
+ async send(events) {
2029
+ let output;
2030
+ try {
2031
+ output = await this.putLogEvents(events);
2032
+ } catch (error) {
2033
+ if (!this.createMissing || errorName(error) !== "ResourceNotFoundException") {
2034
+ throw error;
2035
+ }
2036
+ await this.createStream();
2037
+ output = await this.putLogEvents(events);
2038
+ }
2039
+ return describeRejection(output, events.length);
2040
+ }
2041
+ putLogEvents(events) {
2042
+ return withTimeout(
2043
+ () => this.client.putLogEvents({
2044
+ logGroupName: this.logGroupName,
2045
+ logStreamName: this.logStreamName,
2046
+ logEvents: events.map(
2047
+ ({ timestamp, message }) => ({
2048
+ timestamp,
2049
+ message
2050
+ })
2051
+ )
2052
+ }),
2053
+ this.timeoutMs,
2054
+ timeoutMessage("CloudWatch Logs", this.timeoutMs)
2055
+ );
2056
+ }
2057
+ async createStream() {
2058
+ const createStream = () => withTimeout(
2059
+ () => this.client.createLogStream({
2060
+ logGroupName: this.logGroupName,
2061
+ logStreamName: this.logStreamName
2062
+ }),
2063
+ this.timeoutMs,
2064
+ timeoutMessage("CloudWatch Logs", this.timeoutMs, "create the stream")
2065
+ );
2066
+ try {
2067
+ await createStream();
2068
+ } catch (error) {
2069
+ const name = errorName(error);
2070
+ if (name === "ResourceAlreadyExistsException") {
2071
+ return;
2072
+ }
2073
+ if (name !== "ResourceNotFoundException" || typeof this.client.createLogGroup !== "function") {
2074
+ throw error;
2075
+ }
2076
+ const createGroup = this.client.createLogGroup.bind(this.client);
2077
+ try {
2078
+ await withTimeout(
2079
+ () => createGroup({ logGroupName: this.logGroupName }),
2080
+ this.timeoutMs,
2081
+ timeoutMessage("CloudWatch Logs", this.timeoutMs, "create the group")
2082
+ );
2083
+ } catch (groupError) {
2084
+ if (errorName(groupError) !== "ResourceAlreadyExistsException") {
2085
+ throw groupError;
2086
+ }
2087
+ }
2088
+ try {
2089
+ await createStream();
2090
+ } catch (retryError) {
2091
+ if (errorName(retryError) !== "ResourceAlreadyExistsException") {
2092
+ throw retryError;
2093
+ }
2094
+ }
2095
+ }
2096
+ }
2097
+ fail(error, count) {
2098
+ return reportFailure({
2099
+ adapterName: "CloudWatchLogsErrorAdapter",
2100
+ prefix: this.logPrefix,
2101
+ action: `to send to log stream "${this.logStreamName}" in log group "${this.logGroupName}"${count === void 0 ? "" : ` (${count} event${count === 1 ? "" : "s"} affected)`}`,
2102
+ error
2103
+ });
2104
+ }
2105
+ };
2106
+ function describeRejection(output, eventCount) {
2107
+ const info = typeof output === "object" && output !== null ? output.rejectedLogEventsInfo : void 0;
2108
+ if (info === void 0 || info === null) {
2109
+ return void 0;
2110
+ }
2111
+ const reasons = [];
2112
+ if (info.tooOldLogEventEndIndex !== void 0) {
2113
+ reasons.push(
2114
+ `${info.tooOldLogEventEndIndex} event(s) were older than the 14 days CloudWatch accepts`
2115
+ );
2116
+ }
2117
+ if (info.expiredLogEventEndIndex !== void 0) {
2118
+ reasons.push(
2119
+ `${info.expiredLogEventEndIndex} event(s) were older than the log group's retention period`
2120
+ );
2121
+ }
2122
+ if (info.tooNewLogEventStartIndex !== void 0) {
2123
+ reasons.push(
2124
+ `${Math.max(0, eventCount - info.tooNewLogEventStartIndex)} event(s) were more than 2 hours ahead of the current time`
2125
+ );
2126
+ }
2127
+ return reasons.length === 0 ? void 0 : `CloudWatch Logs accepted the request but rejected events: ${reasons.join("; ")}`;
2128
+ }
2129
+
2130
+ // src/adapters/batching-error-adapter.ts
2131
+ var DEFAULT_BATCH_SIZE = 20;
2132
+ var DEFAULT_MAX_WAIT_MS = 5e3;
2133
+ var DEFAULT_RETRIES = 3;
2134
+ var DEFAULT_RETRY_DELAY_MS2 = 500;
2135
+ var DEFAULT_MAX_RETRY_DELAY_MS2 = 3e4;
2136
+ var DEFAULT_MAX_BUFFERED = 1e3;
2137
+ function hasLogBatch(adapter) {
2138
+ return typeof adapter.logBatch === "function";
2139
+ }
2140
+ var BatchingErrorAdapter = class {
2141
+ /** @throws {RangeError} if an option is out of range. */
2142
+ constructor(inner, options = {}) {
2143
+ this.inner = inner;
2144
+ this.queue = [];
2145
+ this.waitTimer = null;
2146
+ this.backoffTimer = null;
2147
+ this.draining = null;
2148
+ this.flushers = 0;
2149
+ this.droppedSinceFlush = 0;
2150
+ this.lastDropReason = "";
2151
+ this.batchSize = options.batchSize ?? DEFAULT_BATCH_SIZE;
2152
+ this.maxWaitMs = options.maxWaitMs ?? DEFAULT_MAX_WAIT_MS;
2153
+ this.retries = options.retries ?? DEFAULT_RETRIES;
2154
+ this.retryDelayMs = options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS2;
2155
+ this.maxRetryDelayMs = options.maxRetryDelayMs ?? DEFAULT_MAX_RETRY_DELAY_MS2;
2156
+ this.maxBuffered = options.maxBuffered ?? DEFAULT_MAX_BUFFERED;
2157
+ this.useBatchMethod = options.useBatchMethod ?? true;
2158
+ this.onDrop = options.onDrop;
2159
+ this.logPrefix = options.prefix ?? DEFAULT_PREFIX;
2160
+ if (!Number.isInteger(this.batchSize) || this.batchSize < 1) {
2161
+ throw new RangeError(
2162
+ `BatchingErrorAdapter: batchSize must be a positive integer, received ${String(options.batchSize)}.`
2163
+ );
2164
+ }
2165
+ if (Number.isNaN(this.maxWaitMs) || this.maxWaitMs <= 0) {
2166
+ throw new RangeError(
2167
+ `BatchingErrorAdapter: maxWaitMs must be a positive number or Infinity, received ${String(options.maxWaitMs)}.`
2168
+ );
2169
+ }
2170
+ if (!Number.isInteger(this.retries) || this.retries < 0) {
2171
+ throw new RangeError(
2172
+ `BatchingErrorAdapter: retries must be a whole number of 0 or more, received ${String(options.retries)}.`
2173
+ );
2174
+ }
2175
+ if (!Number.isFinite(this.retryDelayMs) || this.retryDelayMs <= 0) {
2176
+ throw new RangeError(
2177
+ `BatchingErrorAdapter: retryDelayMs must be a positive number, received ${String(options.retryDelayMs)}.`
2178
+ );
2179
+ }
2180
+ if (!Number.isFinite(this.maxRetryDelayMs) || this.maxRetryDelayMs < this.retryDelayMs) {
2181
+ throw new RangeError(
2182
+ `BatchingErrorAdapter: maxRetryDelayMs must be a number no smaller than retryDelayMs (${this.retryDelayMs}), received ${String(options.maxRetryDelayMs)}.`
2183
+ );
2184
+ }
2185
+ if (!Number.isInteger(this.maxBuffered) || this.maxBuffered < this.batchSize) {
2186
+ throw new RangeError(
2187
+ `BatchingErrorAdapter: maxBuffered must be a whole number no smaller than batchSize (${this.batchSize}), received ${String(options.maxBuffered)}.`
2188
+ );
2189
+ }
2190
+ }
2191
+ /** Queues the entry. Resolves ok straight away; delivery happens in the background. */
2192
+ log(entry) {
2193
+ this.queue.push({ entry, failures: 0 });
2194
+ if (this.queue.length > this.maxBuffered) {
2195
+ const overflow = this.queue.splice(
2196
+ 0,
2197
+ this.queue.length - this.maxBuffered
2198
+ );
2199
+ this.drop(
2200
+ overflow,
2201
+ `the buffer of ${this.maxBuffered} entries was full because the wrapped adapter keeps failing`
2202
+ );
2203
+ }
2204
+ if (this.queue.length >= this.batchSize) {
2205
+ this.startDraining();
2206
+ } else {
2207
+ this.scheduleDrain();
2208
+ }
2209
+ return Promise.resolve({ ok: true });
2210
+ }
2211
+ /**
2212
+ * Delivers everything queued, retrying as configured, and resolves once the
2213
+ * queue is empty. Resolves `ok: false` if any entries were given up on since
2214
+ * the last flush. With retries on and the sink down this can take a while
2215
+ * (the waits add up to well over a minute with the defaults).
2216
+ */
2217
+ async flush() {
2218
+ this.flushers += 1;
2219
+ this.backoffTimer?.ref?.();
2220
+ try {
2221
+ this.startDraining();
2222
+ while (this.draining !== null) {
2223
+ await this.draining;
2224
+ }
2225
+ } finally {
2226
+ this.flushers -= 1;
2227
+ }
2228
+ if (this.droppedSinceFlush > 0) {
2229
+ const count = this.droppedSinceFlush;
2230
+ const reason = this.lastDropReason;
2231
+ this.droppedSinceFlush = 0;
2232
+ this.lastDropReason = "";
2233
+ return {
2234
+ ok: false,
2235
+ error: `BatchingErrorAdapter gave up on ${count} entr${count === 1 ? "y" : "ies"}: ${reason}`
2236
+ };
2237
+ }
2238
+ return { ok: true };
2239
+ }
2240
+ scheduleDrain() {
2241
+ if (this.waitTimer !== null || this.maxWaitMs === Infinity) {
2242
+ return;
2243
+ }
2244
+ const timer = setTimeout(() => {
2245
+ this.waitTimer = null;
2246
+ this.startDraining();
2247
+ }, this.maxWaitMs);
2248
+ timer.unref?.();
2249
+ this.waitTimer = timer;
2250
+ }
2251
+ startDraining() {
2252
+ if (this.waitTimer !== null) {
2253
+ clearTimeout(this.waitTimer);
2254
+ this.waitTimer = null;
2255
+ }
2256
+ if (this.draining !== null || this.queue.length === 0) {
2257
+ return;
2258
+ }
2259
+ this.draining = this.drain().catch((error) => {
2260
+ console.error(`${this.logPrefix} BatchingErrorAdapter:`, error);
2261
+ }).finally(() => {
2262
+ this.draining = null;
2263
+ if (this.queue.length > 0) {
2264
+ this.scheduleDrain();
2265
+ }
2266
+ });
2267
+ }
2268
+ /** Delivers batches until the queue is empty, waiting out a backoff after each failure. */
2269
+ async drain() {
2270
+ let failedRounds = 0;
2271
+ while (this.queue.length > 0) {
2272
+ const batch = this.queue.slice(0, this.batchSize);
2273
+ const failure = await this.deliver(batch);
2274
+ if (failure === void 0) {
2275
+ failedRounds = 0;
2276
+ continue;
2277
+ }
2278
+ failedRounds += 1;
2279
+ const exhausted = this.queue.filter(
2280
+ (item) => item.failures > this.retries
2281
+ );
2282
+ if (exhausted.length > 0) {
2283
+ this.queue = this.queue.filter(
2284
+ (item) => item.failures <= this.retries
2285
+ );
2286
+ this.drop(
2287
+ exhausted,
2288
+ `delivery failed ${this.retries + 1} time${this.retries === 0 ? "" : "s"}; last error: ${failure}`
2289
+ );
2290
+ }
2291
+ if (this.queue.length > 0) {
2292
+ await this.backoff(failedRounds);
2293
+ }
2294
+ }
2295
+ }
2296
+ /**
2297
+ * Tries to deliver `batch` (the front of the queue). Delivered entries leave
2298
+ * the queue; an entry that failed has its failure count raised and stays.
2299
+ * Resolves to the failure message, or undefined when everything went through.
2300
+ */
2301
+ async deliver(batch) {
2302
+ const remove = (delivered) => {
2303
+ const gone = new Set(delivered);
2304
+ this.queue = this.queue.filter(
2305
+ (item) => !gone.has(item)
2306
+ );
2307
+ };
2308
+ if (this.useBatchMethod && hasLogBatch(this.inner)) {
2309
+ const result = await this.safely(
2310
+ () => this.inner.logBatch(
2311
+ batch.map(
2312
+ (item) => item.entry
2313
+ )
2314
+ )
2315
+ );
2316
+ if (result.ok) {
2317
+ remove(batch);
2318
+ return void 0;
2319
+ }
2320
+ for (const item of batch) {
2321
+ item.failures += 1;
2322
+ }
2323
+ return result.error ?? "the wrapped adapter reported a failure";
2324
+ }
2325
+ for (const item of batch) {
2326
+ const result = await this.safely(
2327
+ () => this.inner.log(item.entry)
2328
+ );
2329
+ if (result.ok) {
2330
+ remove([item]);
2331
+ continue;
2332
+ }
2333
+ item.failures += 1;
2334
+ return result.error ?? "the wrapped adapter reported a failure";
2335
+ }
2336
+ return void 0;
2337
+ }
2338
+ /** The wrapped adapter should not throw, but a bug in one must not stop the queue. */
2339
+ async safely(call) {
2340
+ try {
2341
+ return await call();
2342
+ } catch (error) {
2343
+ return { ok: false, error: describeError(error) };
2344
+ }
2345
+ }
2346
+ backoff(failedRounds) {
2347
+ return new Promise((resolve) => {
2348
+ const timer = setTimeout(
2349
+ () => {
2350
+ this.backoffTimer = null;
2351
+ resolve();
2352
+ },
2353
+ backoffDelayMs(failedRounds, this.retryDelayMs, this.maxRetryDelayMs)
2354
+ );
2355
+ if (this.flushers === 0) {
2356
+ timer.unref?.();
2357
+ }
2358
+ this.backoffTimer = timer;
2359
+ });
2360
+ }
2361
+ drop(items, reason) {
2362
+ if (items.length === 0) {
2363
+ return;
2364
+ }
2365
+ this.droppedSinceFlush += items.length;
2366
+ this.lastDropReason = reason;
2367
+ console.error(
2368
+ `${this.logPrefix} BatchingErrorAdapter: gave up on ${items.length} entr${items.length === 1 ? "y" : "ies"}: ${reason}`
2369
+ );
2370
+ try {
2371
+ this.onDrop?.(
2372
+ items.map((item) => item.entry),
2373
+ reason
2374
+ );
2375
+ } catch {
2376
+ }
2377
+ }
2378
+ };
1809
2379
  export {
2380
+ BatchingErrorAdapter,
2381
+ CloudWatchLogsErrorAdapter,
1810
2382
  CompositeErrorAdapter,
1811
2383
  ConsoleErrorAdapter,
1812
2384
  EventEmitterErrorAdapter,