@wildix/xbees-conversations-utils 1.1.56 → 1.1.58

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 (50) hide show
  1. package/dist-cjs/index.js +2 -2
  2. package/dist-cjs/rateLimits/RedisCooldown.js +45 -35
  3. package/dist-cjs/rateLimits/constants.js +6 -13
  4. package/dist-cjs/rateLimits/createRateLimitedStreamProxy.js +30 -73
  5. package/dist-cjs/rateLimits/exception/createRateLimitExceededException.js +17 -14
  6. package/dist-cjs/rateLimits/exception/processStreamRateLimitException.js +39 -23
  7. package/dist-cjs/rateLimits/executeStreamRequestWithRateLimitHandling.js +86 -67
  8. package/dist-cjs/rateLimits/helpers/RedisCooldown.js +56 -0
  9. package/dist-cjs/rateLimits/helpers/createRateLimitExceededException.js +18 -0
  10. package/dist-cjs/rateLimits/helpers/executeWithRateLimitHandling.js +72 -0
  11. package/dist-cjs/rateLimits/helpers/isStreamChannelLike.js +15 -0
  12. package/dist-cjs/rateLimits/helpers/processStreamRateLimitException.js +31 -0
  13. package/dist-cjs/rateLimits/helpers/splitCallArgsAndOptions.js +21 -0
  14. package/dist-cjs/rateLimits/index.js +1 -0
  15. package/dist-cjs/rateLimits/types.js +1 -0
  16. package/dist-cjs/rateLimits/withStreamRateLimitOptions.js +10 -0
  17. package/dist-es/index.js +2 -2
  18. package/dist-es/rateLimits/RedisCooldown.js +43 -33
  19. package/dist-es/rateLimits/constants.js +5 -12
  20. package/dist-es/rateLimits/createRateLimitedStreamProxy.js +30 -72
  21. package/dist-es/rateLimits/exception/createRateLimitExceededException.js +15 -12
  22. package/dist-es/rateLimits/exception/processStreamRateLimitException.js +32 -22
  23. package/dist-es/rateLimits/executeStreamRequestWithRateLimitHandling.js +87 -65
  24. package/dist-es/rateLimits/helpers/RedisCooldown.js +52 -0
  25. package/dist-es/rateLimits/helpers/createRateLimitExceededException.js +14 -0
  26. package/dist-es/rateLimits/helpers/executeWithRateLimitHandling.js +68 -0
  27. package/dist-es/rateLimits/helpers/isStreamChannelLike.js +11 -0
  28. package/dist-es/rateLimits/helpers/processStreamRateLimitException.js +27 -0
  29. package/dist-es/rateLimits/helpers/splitCallArgsAndOptions.js +17 -0
  30. package/dist-es/rateLimits/index.js +1 -0
  31. package/dist-es/rateLimits/types.js +1 -1
  32. package/dist-es/rateLimits/withStreamRateLimitOptions.js +6 -0
  33. package/dist-types/index.d.ts +2 -2
  34. package/dist-types/rateLimits/RedisCooldown.d.ts +5 -3
  35. package/dist-types/rateLimits/constants.d.ts +3 -5
  36. package/dist-types/rateLimits/createRateLimitedStreamProxy.d.ts +6 -13
  37. package/dist-types/rateLimits/exception/createRateLimitExceededException.d.ts +8 -6
  38. package/dist-types/rateLimits/exception/processStreamRateLimitException.d.ts +8 -3
  39. package/dist-types/rateLimits/executeStreamRequestWithRateLimitHandling.d.ts +8 -2
  40. package/dist-types/rateLimits/helpers/RedisCooldown.d.ts +5 -0
  41. package/dist-types/rateLimits/helpers/createRateLimitExceededException.d.ts +10 -0
  42. package/dist-types/rateLimits/helpers/executeWithRateLimitHandling.d.ts +2 -0
  43. package/dist-types/rateLimits/helpers/isStreamChannelLike.d.ts +6 -0
  44. package/dist-types/rateLimits/helpers/processStreamRateLimitException.d.ts +2 -0
  45. package/dist-types/rateLimits/helpers/splitCallArgsAndOptions.d.ts +6 -0
  46. package/dist-types/rateLimits/index.d.ts +1 -0
  47. package/dist-types/rateLimits/types.d.ts +15 -3
  48. package/dist-types/rateLimits/withStreamRateLimitOptions.d.ts +6 -0
  49. package/dist-types/types.d.ts +1 -1
  50. package/package.json +7 -2
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.executeWithRateLimitHandling = void 0;
4
+ const promises_1 = require("node:timers/promises");
5
+ const constants_1 = require("../constants");
6
+ const createRateLimitExceededException_1 = require("./createRateLimitExceededException");
7
+ const processStreamRateLimitException_1 = require("./processStreamRateLimitException");
8
+ const RedisCooldown_1 = require("./RedisCooldown");
9
+ function calculateRateLimitDelayMs(error, maxDelayMs) {
10
+ const retryAfterMs = typeof error.retryAfter === 'number' ? error.retryAfter + constants_1.RETRY_AFTER_BUFFER_MS : constants_1.DEFAULT_RETRY_AFTER_MS;
11
+ if (retryAfterMs > 0) {
12
+ const jitterMs = Math.floor(Math.random() * constants_1.DEFAULT_JITTER_MS);
13
+ return Math.min(maxDelayMs, retryAfterMs + jitterMs);
14
+ }
15
+ return Math.min(maxDelayMs, constants_1.DEFAULT_FIXED_RATE_LIMIT_DELAY_MS);
16
+ }
17
+ async function executeWithRateLimitHandling(execute, operation, context, options) {
18
+ const { redis } = context;
19
+ const { enableCooldown, maxAttempts, maxDelayMs, maxRetryableDelayMs } = options;
20
+ let attempt = 1;
21
+ if (enableCooldown) {
22
+ const cooldownMs = await RedisCooldown_1.RedisCooldown.getRemainingMs(operation, { redis });
23
+ if (cooldownMs > 0) {
24
+ console.warn('Skipping stream request due to active rate-limit cooldown', {
25
+ operation,
26
+ cooldown: cooldownMs,
27
+ });
28
+ throw (0, createRateLimitExceededException_1.createRateLimitExceededException)({ operation, retryAfterMs: cooldownMs });
29
+ }
30
+ }
31
+ for (;;) {
32
+ try {
33
+ return await execute();
34
+ }
35
+ catch (error) {
36
+ const rateLimitError = (0, processStreamRateLimitException_1.processStreamRateLimitException)(error);
37
+ if (!rateLimitError) {
38
+ throw error;
39
+ }
40
+ const retryAfterMs = calculateRateLimitDelayMs(rateLimitError, maxDelayMs);
41
+ if (enableCooldown) {
42
+ await RedisCooldown_1.RedisCooldown.setRemainingMs(operation, retryAfterMs, { redis });
43
+ }
44
+ if (attempt < maxAttempts && retryAfterMs <= maxRetryableDelayMs) {
45
+ console.warn('Retrying stream request after rate limit', {
46
+ operation,
47
+ attempt,
48
+ maxAttempts,
49
+ retryAfterMs,
50
+ rateLimit: rateLimitError.rateLimit,
51
+ rateLimitRemaining: rateLimitError.rateLimitRemaining,
52
+ rateLimitReset: rateLimitError.rateLimitReset,
53
+ });
54
+ await (0, promises_1.setTimeout)(retryAfterMs);
55
+ attempt++;
56
+ continue;
57
+ }
58
+ console.warn('Propagating stream rate limit w/o retry', {
59
+ operation,
60
+ attempt,
61
+ maxAttempts,
62
+ retryAfterMs,
63
+ maxRetryableDelayMs,
64
+ rateLimit: rateLimitError.rateLimit,
65
+ rateLimitRemaining: rateLimitError.rateLimitRemaining,
66
+ rateLimitReset: rateLimitError.rateLimitReset,
67
+ });
68
+ throw rateLimitError;
69
+ }
70
+ }
71
+ }
72
+ exports.executeWithRateLimitHandling = executeWithRateLimitHandling;
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isStreamChannelLike = void 0;
4
+ function hasFunctionProperty(value, key) {
5
+ return key in value && typeof value[key] === 'function';
6
+ }
7
+ function isStreamChannelLike(value) {
8
+ if (typeof value !== 'object' || value === null) {
9
+ return false;
10
+ }
11
+ return (hasFunctionProperty(value, 'sendMessage') &&
12
+ hasFunctionProperty(value, 'queryMembers') &&
13
+ hasFunctionProperty(value, 'updatePartial'));
14
+ }
15
+ exports.isStreamChannelLike = isStreamChannelLike;
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.processStreamRateLimitException = void 0;
4
+ const createRateLimitExceededException_1 = require("./createRateLimitExceededException");
5
+ function isStreamException(error) {
6
+ return (typeof error === 'object' &&
7
+ error !== null &&
8
+ 'metadata' in error &&
9
+ typeof error.metadata === 'object' &&
10
+ error.metadata !== null &&
11
+ 'responseCode' in error.metadata);
12
+ }
13
+ function isStreamAPIException(error) {
14
+ return typeof error === 'object' && !!error.code;
15
+ }
16
+ function processStreamRateLimitException(error) {
17
+ if (isStreamException(error) && error.metadata?.responseCode === 429) {
18
+ const rateLimit = error.metadata?.rateLimit;
19
+ console.warn('Stream rate limit exceeded [StreamException]', { rateLimit });
20
+ return (0, createRateLimitExceededException_1.createRateLimitExceededException)({ rateLimit, message: error.message || 'Rate limit exceeded' });
21
+ }
22
+ if (isStreamAPIException(error) && (error.code === 429 || error.StatusCode === 429)) {
23
+ console.warn('Stream rate limit exceeded [StreamAPIException]', { code: error.code, StatusCode: error.StatusCode });
24
+ return (0, createRateLimitExceededException_1.createRateLimitExceededException)({ message: error.message || 'Rate limit exceeded' });
25
+ }
26
+ if (typeof error === 'object' && error !== null && 'status' in error && error.status === 429) {
27
+ console.warn('Stream rate limit exceeded [error.status === 429]');
28
+ return (0, createRateLimitExceededException_1.createRateLimitExceededException)({ message: 'Rate limit exceeded' });
29
+ }
30
+ }
31
+ exports.processStreamRateLimitException = processStreamRateLimitException;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.splitCallArgsAndOptions = void 0;
4
+ const constants_1 = require("../constants");
5
+ function isStreamRateLimitOptionsToken(value) {
6
+ return typeof value === 'object' && value !== null && constants_1.STREAM_RATE_LIMIT_OPTIONS_MARKER in value;
7
+ }
8
+ function splitCallArgsAndOptions(args) {
9
+ if (args.length === 0) {
10
+ return { callArgs: args, callOptions: {} };
11
+ }
12
+ const lastArg = args[args.length - 1];
13
+ if (isStreamRateLimitOptionsToken(lastArg)) {
14
+ return {
15
+ callArgs: args.slice(0, -1),
16
+ callOptions: lastArg[constants_1.STREAM_RATE_LIMIT_OPTIONS_MARKER],
17
+ };
18
+ }
19
+ return { callArgs: args, callOptions: {} };
20
+ }
21
+ exports.splitCallArgsAndOptions = splitCallArgsAndOptions;
@@ -2,3 +2,4 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const tslib_1 = require("tslib");
4
4
  tslib_1.__exportStar(require("./createRateLimitedStreamProxy"), exports);
5
+ tslib_1.__exportStar(require("./withStreamRateLimitOptions"), exports);
@@ -1,2 +1,3 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ const constants_1 = require("./constants");
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.withStreamRateLimitOptions = void 0;
4
+ const constants_1 = require("./constants");
5
+ function withStreamRateLimitOptions(options) {
6
+ return {
7
+ [constants_1.STREAM_RATE_LIMIT_OPTIONS_MARKER]: options,
8
+ };
9
+ }
10
+ exports.withStreamRateLimitOptions = withStreamRateLimitOptions;
package/dist-es/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export * from './types';
2
1
  export * from './normalization';
3
- export * from './stream';
4
2
  export * from './rateLimits';
3
+ export * from './stream';
4
+ export * from './types';
@@ -1,29 +1,36 @@
1
- import { STREAM_RATE_LIMIT_COOLDOWN_KEY_PREFIX } from './constants';
1
+ import {STREAM_RATE_LIMIT_COOLDOWN_KEY_PREFIX} from './constants';
2
+
2
3
  export class RedisCooldown {
3
- static async getRemainingMs(cooldownKey, context) {
4
- const { redis, logger } = context;
5
- try {
6
- const ttlMs = await redis.pttl(`${STREAM_RATE_LIMIT_COOLDOWN_KEY_PREFIX}${cooldownKey}`);
7
- if (ttlMs > 0) {
8
- return ttlMs;
9
- }
10
- }
11
- catch (error) {
12
- logger.warn('Failed to read stream rate-limit cooldown from Redis', {
13
- cooldownKey,
14
- error,
15
- });
16
- }
17
- return 0;
4
+ static async getRemainingMs(cooldownKey, context) {
5
+ const {redis} = context;
6
+
7
+ try {
8
+ const ttlMs = await redis.pttl(`${STREAM_RATE_LIMIT_COOLDOWN_KEY_PREFIX}${cooldownKey}`);
9
+
10
+ if (ttlMs > 0) {
11
+ return ttlMs;
12
+ }
13
+ } catch (error) {
14
+ console.warn('Failed to read stream rate-limit cooldown from Redis', {
15
+ cooldownKey,
16
+ error,
17
+ });
18
+ }
19
+
20
+ return 0;
21
+ }
22
+
23
+ static async setRemainingMs(cooldownKey, cooldownMs, context) {
24
+ if (cooldownMs <= 0) {
25
+ return;
18
26
  }
19
- static async setRemainingMs(cooldownKey, cooldownMs, context) {
20
- if (cooldownMs <= 0) {
21
- return;
22
- }
23
- const { redis, logger } = context;
24
- const redisKey = `${STREAM_RATE_LIMIT_COOLDOWN_KEY_PREFIX}${cooldownKey}`;
25
- try {
26
- await redis.eval(`
27
+
28
+ const {redis} = context;
29
+ const redisKey = `${STREAM_RATE_LIMIT_COOLDOWN_KEY_PREFIX}${cooldownKey}`;
30
+
31
+ try {
32
+ await redis.eval(
33
+ `
27
34
  local key = KEYS[1]
28
35
  local new_ttl = tonumber(ARGV[1])
29
36
  local current_ttl = redis.call('PTTL', key)
@@ -39,14 +46,17 @@ export class RedisCooldown {
39
46
  end
40
47
 
41
48
  return 0
42
- `, 1, redisKey, cooldownMs.toString());
43
- }
44
- catch (error) {
45
- logger.warn('Failed to write stream rate-limit cooldown to Redis', {
46
- cooldownKey,
47
- cooldownMs,
48
- error,
49
- });
50
- }
49
+ `,
50
+ 1,
51
+ redisKey,
52
+ cooldownMs.toString(),
53
+ );
54
+ } catch (error) {
55
+ console.warn('Failed to write stream rate-limit cooldown to Redis', {
56
+ cooldownKey,
57
+ cooldownMs,
58
+ error,
59
+ });
51
60
  }
61
+ }
52
62
  }
@@ -1,19 +1,12 @@
1
1
  export const DEFAULT_FIXED_RATE_LIMIT_DELAY_MS = 15000;
2
- export const DEFAULT_MAX_DELAY_MS = 15000;
3
- export const DEFAULT_MAX_RETRYABLE_DELAY_MS = 5000;
4
2
  export const DEFAULT_JITTER_MS = 150;
5
3
  export const RETRY_AFTER_BUFFER_MS = 1000;
6
- export const STREAM_RATE_LIMIT_COOLDOWN_KEY_PREFIX = 'stream-rate-limit-cooldown:';
7
4
  export const DEFAULT_RETRY_AFTER_MS = 10000;
8
- export const DEFAULT_OPTS_1_ATTEMPT_NO_COOLDOWN = {
9
- maxAttempts: 1,
10
- enableCooldown: false,
11
- maxDelayMs: DEFAULT_MAX_DELAY_MS,
12
- maxRetryableDelayMs: DEFAULT_MAX_RETRYABLE_DELAY_MS,
13
- };
14
- export const DEFAULT_OPTS_3_ATTEMPTS_WITH_COOLDOWN = {
5
+ export const STREAM_RATE_LIMIT_COOLDOWN_KEY_PREFIX = 'stream-rate-limit-cooldown:';
6
+ export const STREAM_RATE_LIMIT_OPTIONS_MARKER = '__xbsRateLimitOptions';
7
+ export const DEFAULT_OPTIONS = {
15
8
  maxAttempts: 3,
16
9
  enableCooldown: true,
17
- maxDelayMs: DEFAULT_MAX_DELAY_MS,
18
- maxRetryableDelayMs: DEFAULT_MAX_RETRYABLE_DELAY_MS,
10
+ maxDelayMs: 15000,
11
+ maxRetryableDelayMs: 5000,
19
12
  };
@@ -1,68 +1,33 @@
1
- import { DEFAULT_OPTS_3_ATTEMPTS_WITH_COOLDOWN } from './constants';
2
- import { executeStreamRequestWithRateLimitHandling } from './executeStreamRequestWithRateLimitHandling';
3
- const STREAM_RATE_LIMIT_OPTIONS_MARKER = '__xbsRateLimitOptions';
4
- const STREAM_RATE_LIMIT_PROXY_MARKER = Symbol('xbsStreamRateLimitProxy');
5
- const OPERATION_DEFAULT_OPTIONS = {
6
- queryChannels: DEFAULT_OPTS_3_ATTEMPTS_WITH_COOLDOWN,
7
- };
8
- function isObject(value) {
9
- return typeof value === 'object' && value !== null;
10
- }
11
- function hasFunctionProperty(value, key) {
12
- return key in value && typeof value[key] === 'function';
13
- }
14
- function isStreamChannelLike(value) {
15
- if (!isObject(value)) {
16
- return false;
17
- }
18
- return (hasFunctionProperty(value, 'sendMessage') &&
19
- hasFunctionProperty(value, 'queryMembers') &&
20
- hasFunctionProperty(value, 'updatePartial'));
21
- }
22
- function isStreamRateLimitOptionsToken(value) {
23
- return isObject(value) && STREAM_RATE_LIMIT_OPTIONS_MARKER in value;
24
- }
25
- function splitCallArgsAndOptions(args) {
26
- if (args.length === 0) {
27
- return { callArgs: args, callOptions: {} };
1
+ import { DEFAULT_OPTIONS } from './constants';
2
+ import { executeWithRateLimitHandling } from './helpers/executeWithRateLimitHandling';
3
+ import { isStreamChannelLike } from './helpers/isStreamChannelLike';
4
+ import { splitCallArgsAndOptions } from './helpers/splitCallArgsAndOptions';
5
+ function normalizeStreamCallResult(result, dependencies) {
6
+ if (Array.isArray(result)) {
7
+ return result.map((item) => normalizeStreamCallResult(item, dependencies));
28
8
  }
29
- const lastArg = args[args.length - 1];
30
- if (isStreamRateLimitOptionsToken(lastArg)) {
31
- return {
32
- callArgs: args.slice(0, -1),
33
- callOptions: lastArg[STREAM_RATE_LIMIT_OPTIONS_MARKER],
34
- };
9
+ if (!isStreamChannelLike(result)) {
10
+ return result;
35
11
  }
36
- return { callArgs: args, callOptions: {} };
37
- }
38
- export function withStreamRateLimitOptions(options) {
39
- return {
40
- [STREAM_RATE_LIMIT_OPTIONS_MARKER]: options,
12
+ return wrapTarget(result, dependencies);
13
+ }
14
+ function createRateLimitedMethodWrapper(target, value, operation, dependencies) {
15
+ return async (...args) => {
16
+ const { callArgs, callOptions } = splitCallArgsAndOptions(args);
17
+ const result = await executeWithRateLimitHandling(() => Reflect.apply(value, target, callArgs), operation, dependencies.context, {
18
+ ...DEFAULT_OPTIONS,
19
+ ...callOptions,
20
+ });
21
+ return normalizeStreamCallResult(result, dependencies);
41
22
  };
42
23
  }
43
- function createRateLimitedProxy(target, context, cache) {
44
- const cached = cache.get(target);
45
- if (cached) {
46
- return cached;
24
+ function wrapTarget(target, dependencies) {
25
+ const cachedObject = dependencies.cache.get(target);
26
+ if (cachedObject) {
27
+ return cachedObject;
47
28
  }
48
- const wrapResult = (result) => {
49
- if (Array.isArray(result)) {
50
- return result.map((item) => wrapResult(item));
51
- }
52
- if (!isStreamChannelLike(result)) {
53
- return result;
54
- }
55
- const cachedResult = cache.get(result);
56
- if (cachedResult) {
57
- return cachedResult;
58
- }
59
- return createRateLimitedProxy(result, context, cache);
60
- };
61
29
  const proxy = new Proxy(target, {
62
30
  get: (originalTarget, property, receiver) => {
63
- if (property === STREAM_RATE_LIMIT_PROXY_MARKER) {
64
- return true;
65
- }
66
31
  const value = Reflect.get(originalTarget, property, receiver);
67
32
  if (typeof property !== 'string' || typeof value !== 'function') {
68
33
  return value;
@@ -70,25 +35,18 @@ function createRateLimitedProxy(target, context, cache) {
70
35
  if (property === 'channel') {
71
36
  return (...args) => {
72
37
  const channel = Reflect.apply(value, originalTarget, args);
73
- return wrapResult(channel);
38
+ return normalizeStreamCallResult(channel, dependencies);
74
39
  };
75
40
  }
76
- return async (...args) => {
77
- const { callArgs, callOptions } = splitCallArgsAndOptions(args);
78
- const operation = property;
79
- const defaultOptions = OPERATION_DEFAULT_OPTIONS[operation] || {};
80
- const result = await executeStreamRequestWithRateLimitHandling(() => Reflect.apply(value, originalTarget, callArgs), operation, context, {
81
- ...defaultOptions,
82
- ...callOptions,
83
- });
84
- return wrapResult(result);
85
- };
41
+ return createRateLimitedMethodWrapper(originalTarget, value, property, dependencies);
86
42
  },
87
43
  });
88
- cache.set(target, proxy);
44
+ dependencies.cache.set(target, proxy);
89
45
  return proxy;
90
46
  }
91
47
  export function createRateLimitedStreamProxy(stream, context) {
92
- const cache = new WeakMap();
93
- return createRateLimitedProxy(stream, context, cache);
48
+ return wrapTarget(stream, {
49
+ context,
50
+ cache: new WeakMap(),
51
+ });
94
52
  }
@@ -1,14 +1,17 @@
1
- import { RateLimitExceededException } from '@wildix/xbees-conversations-client';
2
- import { DEFAULT_RETRY_AFTER_MS } from '../constants';
1
+ import {RateLimitExceededException} from '@wildix/xbees-conversations-client';
2
+
3
+ import {DEFAULT_RETRY_AFTER_MS} from '../constants';
4
+
3
5
  export function createRateLimitExceededException(options = {}) {
4
- const { rateLimit, message, operation, retryAfterMs = DEFAULT_RETRY_AFTER_MS } = options;
5
- const defaultMessage = operation ? `Rate limit exceeded for ${operation}` : 'Rate limit exceeded';
6
- return new RateLimitExceededException({
7
- $metadata: {},
8
- message: message || defaultMessage,
9
- rateLimitRemaining: rateLimit?.remaining || 0,
10
- retryAfter: rateLimit?.reset ? rateLimit.reset - Date.now() : retryAfterMs,
11
- rateLimit: rateLimit?.limit?.toString() || 'unknown',
12
- rateLimitReset: rateLimit?.reset || Date.now() + retryAfterMs,
13
- });
6
+ const {rateLimit, message, operation, retryAfterMs = DEFAULT_RETRY_AFTER_MS} = options;
7
+ const defaultMessage = operation ? `Rate limit exceeded for ${operation}` : 'Rate limit exceeded';
8
+
9
+ return new RateLimitExceededException({
10
+ $metadata: {},
11
+ message: message || defaultMessage,
12
+ rateLimitRemaining: rateLimit?.remaining || 0,
13
+ retryAfter: rateLimit?.reset ? rateLimit.reset - Date.now() : retryAfterMs,
14
+ rateLimit: rateLimit?.limit?.toString() || 'unknown',
15
+ rateLimitReset: rateLimit?.reset || Date.now() + retryAfterMs,
16
+ });
14
17
  }
@@ -1,27 +1,37 @@
1
- import { createRateLimitExceededException } from './createRateLimitExceededException';
1
+ import {createRateLimitExceededException} from './createRateLimitExceededException';
2
+
2
3
  function isStreamException(error) {
3
- return (typeof error === 'object' &&
4
- error !== null &&
5
- 'metadata' in error &&
6
- typeof error.metadata === 'object' &&
7
- error.metadata !== null &&
8
- 'responseCode' in error.metadata);
4
+ return (
5
+ typeof error === 'object' &&
6
+ error !== null &&
7
+ 'metadata' in error &&
8
+ typeof error.metadata === 'object' &&
9
+ error.metadata !== null &&
10
+ 'responseCode' in error.metadata
11
+ );
9
12
  }
13
+
10
14
  function isStreamAPIException(error) {
11
- return typeof error === 'object' && !!error.code;
15
+ return typeof error === 'object' && !!error.code;
12
16
  }
13
- export function processStreamRateLimitException(error, logger) {
14
- if (isStreamException(error) && error.metadata?.responseCode === 429) {
15
- const rateLimit = error.metadata?.rateLimit;
16
- logger.warn('Stream rate limit exceeded [StreamException]', { rateLimit });
17
- return createRateLimitExceededException({ rateLimit, message: error.message || 'Rate limit exceeded' });
18
- }
19
- if (isStreamAPIException(error) && (error.code === 429 || error.StatusCode === 429)) {
20
- logger.warn('Stream rate limit exceeded [StreamAPIException]', { code: error.code, StatusCode: error.StatusCode });
21
- return createRateLimitExceededException({ message: error.message || 'Rate limit exceeded' });
22
- }
23
- if (typeof error === 'object' && error !== null && 'status' in error && error.status === 429) {
24
- logger.warn('Stream rate limit exceeded [error.status === 429]');
25
- return createRateLimitExceededException({ message: 'Rate limit exceeded' });
26
- }
17
+
18
+ export function processStreamRateLimitException(error) {
19
+ if (isStreamException(error) && error.metadata?.responseCode === 429) {
20
+ const rateLimit = error.metadata?.rateLimit;
21
+ console.warn('Stream rate limit exceeded [StreamException]', {rateLimit});
22
+
23
+ return createRateLimitExceededException({rateLimit, message: error.message || 'Rate limit exceeded'});
24
+ }
25
+
26
+ if (isStreamAPIException(error) && (error.code === 429 || error.StatusCode === 429)) {
27
+ console.warn('Stream rate limit exceeded [StreamAPIException]', {code: error.code, StatusCode: error.StatusCode});
28
+
29
+ return createRateLimitExceededException({message: error.message || 'Rate limit exceeded'});
30
+ }
31
+
32
+ if (typeof error === 'object' && error !== null && 'status' in error && error.status === 429) {
33
+ console.warn('Stream rate limit exceeded [error.status === 429]');
34
+
35
+ return createRateLimitExceededException({message: 'Rate limit exceeded'});
36
+ }
27
37
  }