@friggframework/core 2.0.0--canary.657.f16d20b.0 → 2.0.0--canary.737.83b4e17.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/CLAUDE.md +48 -93
- package/application/commands/README.md +17 -11
- package/application/commands/entity-commands.js +18 -60
- package/application/commands/integration-commands.js +63 -0
- package/core/CLAUDE.md +1 -33
- package/core/Worker.js +11 -317
- package/core/create-handler.js +0 -3
- package/core/index.js +0 -6
- package/core/invocation-scope.js +24 -30
- package/database/documentdb-encryption-service.js +2 -33
- package/database/documentdb-utils.js +4 -1
- package/database/encryption/README.md +3 -3
- package/database/encryption/ciphertext-format.js +24 -0
- package/database/encryption/encryption-schema-registry.js +109 -29
- package/database/encryption/field-encryption-service.js +55 -16
- package/database/encryption/prisma-encryption-extension.js +6 -9
- package/database/prisma.js +10 -1
- package/encrypt/Cryptor.js +90 -38
- package/errors/fetch-error.js +18 -11
- package/errors/index.js +4 -2
- package/errors/mapping-already-exists-error.js +14 -0
- package/generated/prisma-mongodb/edge.js +6 -2
- package/generated/prisma-mongodb/index.js +10 -2
- package/generated/prisma-mongodb/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
- package/generated/prisma-mongodb/package.json +1 -1
- package/generated/prisma-mongodb/schema.prisma +1 -1
- package/generated/prisma-mongodb/wasm.js +6 -2
- package/generated/prisma-postgresql/edge.js +6 -2
- package/generated/prisma-postgresql/index.js +10 -2
- package/generated/prisma-postgresql/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
- package/generated/prisma-postgresql/package.json +1 -1
- package/generated/prisma-postgresql/schema.prisma +1 -1
- package/generated/prisma-postgresql/wasm.js +6 -2
- package/handlers/WEBHOOKS.md +29 -0
- package/handlers/app-definition-loader.js +9 -2
- package/handlers/app-handler-helpers.js +12 -1
- package/handlers/backend-utils.js +1 -30
- package/handlers/workers/integration-defined-workers.js +0 -2
- package/index.js +2 -18
- package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +67 -15
- package/integrations/integration-base.js +52 -9
- package/integrations/integration-router.js +30 -22
- package/integrations/repositories/integration-mapping-repository-documentdb.js +50 -0
- package/integrations/repositories/integration-mapping-repository-interface.js +15 -0
- package/integrations/repositories/integration-mapping-repository-mongo.js +29 -0
- package/integrations/repositories/integration-mapping-repository-postgres.js +30 -0
- package/integrations/repositories/integration-mapping-repository.js +29 -0
- package/integrations/repositories/integration-repository-documentdb.js +32 -0
- package/integrations/repositories/integration-repository-interface.js +30 -0
- package/integrations/repositories/integration-repository-mongo.js +53 -1
- package/integrations/repositories/integration-repository-postgres.js +58 -0
- package/integrations/repositories/process-repository-mongo.js +1 -1
- package/integrations/use-cases/add-entities-to-integration.js +92 -0
- package/integrations/use-cases/create-integration.js +57 -19
- package/integrations/use-cases/delete-integration-for-user.js +8 -11
- package/integrations/use-cases/get-integration-instance.js +12 -12
- package/integrations/use-cases/index.js +1 -5
- package/integrations/use-cases/remove-entities-from-integration.js +70 -0
- package/integrations/use-cases/update-integration.js +12 -12
- package/integrations/utils/assert-entity-ids-input.js +42 -0
- package/jest-setup.js +13 -2
- package/jest-teardown.js +5 -2
- package/jest.config.js +4 -0
- package/jest.db.config.js +23 -0
- package/logs/serialize.js +0 -15
- package/modules/requester/oauth-2.js +0 -7
- package/modules/requester/requester.js +9 -187
- package/modules/use-cases/create-entity-from-credential.js +105 -0
- package/modules/use-cases/get-entity-options-by-id.js +7 -5
- package/modules/use-cases/get-module.js +29 -8
- package/modules/use-cases/process-authorization-callback.js +78 -27
- package/modules/use-cases/refresh-entity-options.js +7 -5
- package/modules/use-cases/test-module-auth.js +7 -5
- package/modules/utils/find-module-definition.js +23 -0
- package/modules/utils/map-module-dto.js +5 -3
- package/modules/utils/to-credential-id.js +14 -0
- package/package.json +9 -8
- package/prisma-mongodb/schema.prisma +1 -1
- package/prisma-postgresql/schema.prisma +1 -1
- package/queues/queue-delivery.js +0 -1
- package/queues/queuer-util.js +10 -8
- package/queues/sqs-message-body.js +17 -0
- package/telemetry/otel-telemetry.js +76 -3
- package/telemetry/telemetry-config.js +16 -5
- package/telemetry/telemetry-runtime.js +14 -1
- package/token/repositories/token-repository-documentdb.js +13 -1
- package/token/repositories/token-repository-mongo.js +13 -1
- package/token/repositories/token-repository-postgres.js +13 -1
- package/types/core/index.d.ts +0 -52
- package/types/errors/index.d.ts +0 -47
- package/types/module-plugin/index.d.ts +0 -43
- package/user/tests/doubles/test-user-repository.js +1 -1
- package/user/use-cases/authenticate-user.js +23 -7
- package/user/use-cases/get-user-from-bearer-token.js +7 -2
- package/core/invocation-deadline.js +0 -91
- package/errors/rate-limit-error.js +0 -46
- package/integrations/use-cases/clear-rate-limit-wait.js +0 -28
- package/integrations/use-cases/record-rate-limit-wait.js +0 -36
- package/modules/requester/rate-limit/index.js +0 -4
- package/modules/requester/rate-limit/parsers.js +0 -245
- package/modules/requester/rate-limit/policy.js +0 -304
- package/queues/queue-deferral.js +0 -74
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
const Boom = require('@hapi/boom');
|
|
1
2
|
// Removed Integration wrapper - using IntegrationBase directly
|
|
2
3
|
|
|
3
4
|
/**
|
|
@@ -24,15 +25,20 @@ class GetIntegrationInstance {
|
|
|
24
25
|
* @param {string} integrationId - ID of the integration to retrieve.
|
|
25
26
|
* @param {string} userId - ID of the user requesting the integration.
|
|
26
27
|
* @returns {Promise<Integration>} The fully initialized integration instance.
|
|
27
|
-
* @throws {
|
|
28
|
+
* @throws {Boom.notFound} When integration is not found or doesn't belong to user.
|
|
29
|
+
* @throws {Error} When integration class is not found.
|
|
28
30
|
*/
|
|
29
31
|
async execute(integrationId, userId) {
|
|
30
|
-
const integrationRecord =
|
|
31
|
-
|
|
32
|
+
const integrationRecord = await this.integrationRepository
|
|
33
|
+
.findIntegrationById(integrationId)
|
|
34
|
+
.catch((error) => {
|
|
35
|
+
if (error.message?.includes('not found')) return null;
|
|
36
|
+
throw error;
|
|
37
|
+
});
|
|
32
38
|
|
|
33
|
-
if (!integrationRecord) {
|
|
34
|
-
throw
|
|
35
|
-
`
|
|
39
|
+
if (!integrationRecord || integrationRecord.userId !== userId) {
|
|
40
|
+
throw Boom.notFound(
|
|
41
|
+
`Integration with id of ${integrationId} does not exist`
|
|
36
42
|
);
|
|
37
43
|
}
|
|
38
44
|
|
|
@@ -48,12 +54,6 @@ class GetIntegrationInstance {
|
|
|
48
54
|
);
|
|
49
55
|
}
|
|
50
56
|
|
|
51
|
-
if (integrationRecord.userId !== userId) {
|
|
52
|
-
throw new Error(
|
|
53
|
-
`Integration ${integrationId} does not belong to User ${userId}`
|
|
54
|
-
);
|
|
55
|
-
}
|
|
56
|
-
|
|
57
57
|
const modules = [];
|
|
58
58
|
for (const entityId of integrationRecord.entitiesIds) {
|
|
59
59
|
const moduleInstance = await this.moduleFactory.getModuleInstance(
|
|
@@ -6,8 +6,6 @@ const { CreateProcess } = require('./create-process');
|
|
|
6
6
|
const { UpdateProcessState } = require('./update-process-state');
|
|
7
7
|
const { UpdateProcessMetrics } = require('./update-process-metrics');
|
|
8
8
|
const { GetProcess } = require('./get-process');
|
|
9
|
-
const { RecordRateLimitWait } = require('./record-rate-limit-wait');
|
|
10
|
-
const { ClearRateLimitWait } = require('./clear-rate-limit-wait');
|
|
11
9
|
|
|
12
10
|
module.exports = {
|
|
13
11
|
GetIntegrationsForUser,
|
|
@@ -18,6 +16,4 @@ module.exports = {
|
|
|
18
16
|
UpdateProcessState,
|
|
19
17
|
UpdateProcessMetrics,
|
|
20
18
|
GetProcess,
|
|
21
|
-
|
|
22
|
-
ClearRateLimitWait,
|
|
23
|
-
};
|
|
19
|
+
};
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
const {
|
|
2
|
+
assertEntityIdsInput,
|
|
3
|
+
integrationNotFound,
|
|
4
|
+
loadIntegration,
|
|
5
|
+
} = require('../utils/assert-entity-ids-input');
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Detaches entities from an integration. Entities that are not attached are
|
|
9
|
+
* ignored, and detached entities are not deleted. Every module the
|
|
10
|
+
* integration holds must keep at least one entity, so the integration can
|
|
11
|
+
* still hydrate each of its modules.
|
|
12
|
+
* @class RemoveEntitiesFromIntegration
|
|
13
|
+
*/
|
|
14
|
+
class RemoveEntitiesFromIntegration {
|
|
15
|
+
/**
|
|
16
|
+
* @param {Object} params
|
|
17
|
+
* @param {import('../repositories/integration-repository-interface').IntegrationRepositoryInterface} params.integrationRepository
|
|
18
|
+
* @param {import('../../modules/repositories/module-repository-interface').ModuleRepositoryInterface} params.moduleRepository
|
|
19
|
+
*/
|
|
20
|
+
constructor({ integrationRepository, moduleRepository }) {
|
|
21
|
+
this.integrationRepository = integrationRepository;
|
|
22
|
+
this.moduleRepository = moduleRepository;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* @param {string} integrationId
|
|
27
|
+
* @param {string[]} entityIds
|
|
28
|
+
* @returns {Promise<Object>} The updated integration record.
|
|
29
|
+
*/
|
|
30
|
+
async execute(integrationId, entityIds) {
|
|
31
|
+
assertEntityIdsInput(integrationId, entityIds);
|
|
32
|
+
|
|
33
|
+
const integration = await loadIntegration(
|
|
34
|
+
this.integrationRepository,
|
|
35
|
+
integrationId
|
|
36
|
+
);
|
|
37
|
+
|
|
38
|
+
const removing = new Set(entityIds.map(String));
|
|
39
|
+
const attached = await this.moduleRepository.findEntitiesByIds(
|
|
40
|
+
integration.entitiesIds ?? []
|
|
41
|
+
);
|
|
42
|
+
const emptied = [...new Set(attached.map((e) => e.moduleName))].filter(
|
|
43
|
+
(moduleName) =>
|
|
44
|
+
!attached.some(
|
|
45
|
+
(e) =>
|
|
46
|
+
e.moduleName === moduleName &&
|
|
47
|
+
!removing.has(String(e.id))
|
|
48
|
+
)
|
|
49
|
+
);
|
|
50
|
+
if (emptied.length > 0) {
|
|
51
|
+
const error = new Error(
|
|
52
|
+
`Removing these entities would leave no entity for module(s): ${emptied.join(
|
|
53
|
+
', '
|
|
54
|
+
)}`
|
|
55
|
+
);
|
|
56
|
+
error.code = 'LAST_ENTITY_OF_MODULE';
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const updated =
|
|
61
|
+
await this.integrationRepository.removeEntitiesFromIntegration(
|
|
62
|
+
integrationId,
|
|
63
|
+
entityIds
|
|
64
|
+
);
|
|
65
|
+
if (!updated) throw integrationNotFound(integrationId);
|
|
66
|
+
return updated;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
module.exports = { RemoveEntitiesFromIntegration };
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
const Boom = require('@hapi/boom');
|
|
1
2
|
const {
|
|
2
3
|
mapIntegrationClassToIntegrationDTO,
|
|
3
4
|
} = require('../utils/map-integration-dto');
|
|
@@ -27,16 +28,21 @@ class UpdateIntegration {
|
|
|
27
28
|
* @param {string} userId - ID of the user requesting the update.
|
|
28
29
|
* @param {Object} config - New configuration object for the integration.
|
|
29
30
|
* @returns {Promise<Object>} The updated integration DTO.
|
|
30
|
-
* @throws {
|
|
31
|
+
* @throws {Boom.notFound} When integration is not found or doesn't belong to user.
|
|
32
|
+
* @throws {Error} When integration class is not found.
|
|
31
33
|
*/
|
|
32
34
|
async execute(integrationId, userId, config) {
|
|
33
35
|
// 1. Get integration record from repository
|
|
34
|
-
const integrationRecord =
|
|
35
|
-
|
|
36
|
+
const integrationRecord = await this.integrationRepository
|
|
37
|
+
.findIntegrationById(integrationId)
|
|
38
|
+
.catch((error) => {
|
|
39
|
+
if (error.message?.includes('not found')) return null;
|
|
40
|
+
throw error;
|
|
41
|
+
});
|
|
36
42
|
|
|
37
|
-
if (!integrationRecord) {
|
|
38
|
-
throw
|
|
39
|
-
`
|
|
43
|
+
if (!integrationRecord || integrationRecord.userId !== userId) {
|
|
44
|
+
throw Boom.notFound(
|
|
45
|
+
`Integration with id of ${integrationId} does not exist`
|
|
40
46
|
);
|
|
41
47
|
}
|
|
42
48
|
|
|
@@ -53,12 +59,6 @@ class UpdateIntegration {
|
|
|
53
59
|
);
|
|
54
60
|
}
|
|
55
61
|
|
|
56
|
-
if (integrationRecord.userId !== userId) {
|
|
57
|
-
throw new Error(
|
|
58
|
-
`Integration ${integrationId} does not belong to User ${userId}`
|
|
59
|
-
);
|
|
60
|
-
}
|
|
61
|
-
|
|
62
62
|
// 3. Load modules based on entity references
|
|
63
63
|
const modules = [];
|
|
64
64
|
for (const entityId of integrationRecord.entitiesIds) {
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Throws INVALID_INTEGRATION_DATA unless an integration id and a non-empty
|
|
3
|
+
* list of entity ids are given.
|
|
4
|
+
* @param {string} integrationId
|
|
5
|
+
* @param {string[]} entityIds
|
|
6
|
+
*/
|
|
7
|
+
function assertEntityIdsInput(integrationId, entityIds) {
|
|
8
|
+
if (!integrationId || !Array.isArray(entityIds) || entityIds.length === 0) {
|
|
9
|
+
const error = new Error(
|
|
10
|
+
'integrationId and a non-empty entityIds array are required'
|
|
11
|
+
);
|
|
12
|
+
error.code = 'INVALID_INTEGRATION_DATA';
|
|
13
|
+
throw error;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function integrationNotFound(integrationId) {
|
|
18
|
+
const error = new Error(`Integration ${integrationId} not found`);
|
|
19
|
+
error.code = 'INTEGRATION_NOT_FOUND';
|
|
20
|
+
return error;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Loads an integration, mapping the repositories' "not found" error to
|
|
25
|
+
* INTEGRATION_NOT_FOUND. Any other failure (connection, invalid id) is
|
|
26
|
+
* rethrown unchanged.
|
|
27
|
+
* @param {Object} integrationRepository
|
|
28
|
+
* @param {string} integrationId
|
|
29
|
+
* @returns {Promise<Object>} The integration record.
|
|
30
|
+
*/
|
|
31
|
+
async function loadIntegration(integrationRepository, integrationId) {
|
|
32
|
+
try {
|
|
33
|
+
return await integrationRepository.findIntegrationById(integrationId);
|
|
34
|
+
} catch (error) {
|
|
35
|
+
if (/^Integration with id .* not found$/.test(error?.message)) {
|
|
36
|
+
throw integrationNotFound(integrationId);
|
|
37
|
+
}
|
|
38
|
+
throw error;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
module.exports = { assertEntityIdsInput, integrationNotFound, loadIntegration };
|
package/jest-setup.js
CHANGED
|
@@ -1,2 +1,13 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
// Core's unit suites must not need a database, so this global setup only
|
|
2
|
+
// sets the test environment. It deliberately does not start an in-memory
|
|
3
|
+
// MongoDB (as @friggframework/test's globalSetup does): nothing in the default
|
|
4
|
+
// suite talks to a live server, and a binary that failed to start used to stop
|
|
5
|
+
// every core suite from running. Suites that need a real database are
|
|
6
|
+
// `*.db.test.js` files, run by `npm run test:db` (see jest.db.config.js).
|
|
7
|
+
const { overrideEnvironment } = require('@friggframework/test');
|
|
8
|
+
|
|
9
|
+
module.exports = async function () {
|
|
10
|
+
if (!process.env.STAGE) {
|
|
11
|
+
overrideEnvironment({ STAGE: 'dev' });
|
|
12
|
+
}
|
|
13
|
+
};
|
package/jest-teardown.js
CHANGED
package/jest.config.js
CHANGED
|
@@ -20,4 +20,8 @@ module.exports = {
|
|
|
20
20
|
globalTeardown: './jest-teardown.js',
|
|
21
21
|
|
|
22
22
|
setupFilesAfterEnv: ['./logs/jest-logger-setup.js'],
|
|
23
|
+
|
|
24
|
+
// `*.db.test.js` suites talk to a real MongoDB replica set / PostgreSQL
|
|
25
|
+
// and run separately via `npm run test:db` (jest.db.config.js).
|
|
26
|
+
testPathIgnorePatterns: ['/node_modules/', '\\.db\\.test\\.js$'],
|
|
23
27
|
};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Database integration suites (`*.db.test.js`).
|
|
3
|
+
*
|
|
4
|
+
* These talk to real databases instead of mocking Prisma, so they are kept
|
|
5
|
+
* out of the default `npm test` run and executed with `npm run test:db`.
|
|
6
|
+
* They need generated Prisma clients (`npm run prisma:generate`) and:
|
|
7
|
+
* - a MongoDB replica set (Prisma requires one for MongoDB writes):
|
|
8
|
+
* FRIGG_TEST_MONGODB_URL, default
|
|
9
|
+
* mongodb://localhost:27017/frigg?replicaSet=rs0
|
|
10
|
+
* - PostgreSQL with the prisma-postgresql migrations applied:
|
|
11
|
+
* FRIGG_TEST_POSTGRES_URL, default
|
|
12
|
+
* postgresql://postgres:postgres@localhost:5432/frigg?schema=public
|
|
13
|
+
* The repository parity suites skip themselves unless their own URLs are
|
|
14
|
+
* set (INTEGRATION_ENTITIES_PARITY_* / QUERY_MAPPINGS_PARITY_*).
|
|
15
|
+
*/
|
|
16
|
+
const base = require('./jest.config');
|
|
17
|
+
|
|
18
|
+
module.exports = {
|
|
19
|
+
...base,
|
|
20
|
+
coverageThreshold: undefined,
|
|
21
|
+
testMatch: ['**/*.db.test.js'],
|
|
22
|
+
testPathIgnorePatterns: ['/node_modules/'],
|
|
23
|
+
};
|
package/logs/serialize.js
CHANGED
|
@@ -235,20 +235,6 @@ function errorCode(err) {
|
|
|
235
235
|
return undefined;
|
|
236
236
|
}
|
|
237
237
|
|
|
238
|
-
function rateLimitFields(err) {
|
|
239
|
-
const retryAt = attempt(
|
|
240
|
-
() => (err.isRateLimited ? err.retryAt : undefined),
|
|
241
|
-
undefined
|
|
242
|
-
);
|
|
243
|
-
if (!(retryAt instanceof Date) || Number.isNaN(retryAt.getTime())) {
|
|
244
|
-
return {};
|
|
245
|
-
}
|
|
246
|
-
const reason = attempt(() => err.reason, undefined);
|
|
247
|
-
return typeof reason === 'string'
|
|
248
|
-
? { retryAt: retryAt.toISOString(), reason: cleanString(reason) }
|
|
249
|
-
: { retryAt: retryAt.toISOString() };
|
|
250
|
-
}
|
|
251
|
-
|
|
252
238
|
function errorStack(err, type, message) {
|
|
253
239
|
const stack = attempt(() => err.stack, undefined);
|
|
254
240
|
if (typeof stack !== 'string') return undefined;
|
|
@@ -293,7 +279,6 @@ function serializeErrorAt(err, depth, seen) {
|
|
|
293
279
|
if (code !== undefined) out.code = code;
|
|
294
280
|
const status = errorStatus(err);
|
|
295
281
|
if (status !== undefined) out.status = status;
|
|
296
|
-
Object.assign(out, rateLimitFields(err));
|
|
297
282
|
const stack = errorStack(err, type, message);
|
|
298
283
|
if (stack !== undefined) out.stack = stack;
|
|
299
284
|
|
|
@@ -398,13 +398,6 @@ class OAuth2Requester extends Requester {
|
|
|
398
398
|
);
|
|
399
399
|
transportError.statusCode = status;
|
|
400
400
|
transportError.isTokenRefreshTransportFailure = true;
|
|
401
|
-
if (error?.isRateLimited) {
|
|
402
|
-
transportError.isRateLimited = true;
|
|
403
|
-
transportError.retryAt = error.retryAt;
|
|
404
|
-
transportError.waitMs = error.waitMs;
|
|
405
|
-
transportError.reason = error.reason;
|
|
406
|
-
transportError.module = error.module;
|
|
407
|
-
}
|
|
408
401
|
return transportError;
|
|
409
402
|
}
|
|
410
403
|
|
|
@@ -1,24 +1,13 @@
|
|
|
1
1
|
const fetch = require('node-fetch');
|
|
2
2
|
const { AsyncLocalStorage } = require('async_hooks');
|
|
3
3
|
const { Delegate } = require('../../core');
|
|
4
|
-
const {
|
|
5
|
-
invocationMaxInProcessWaitMs,
|
|
6
|
-
remainingInvocationMs,
|
|
7
|
-
} = require('../../core/invocation-deadline');
|
|
8
|
-
const { FetchError, RateLimitError } = require('../../errors');
|
|
4
|
+
const { FetchError } = require('../../errors');
|
|
9
5
|
const { get } = require('../../assertions');
|
|
10
6
|
const { getTelemetry } = require('../../telemetry/telemetry-runtime');
|
|
11
7
|
const { getLogger } = require('../../logs');
|
|
12
8
|
const { redactUrl } = require('../../logs/redact');
|
|
13
9
|
const { toSanitizedSurrogate } = require('../../logs/serialize');
|
|
14
10
|
const { getLoggerScope } = require('../../logs/context');
|
|
15
|
-
const {
|
|
16
|
-
computeScopeKey,
|
|
17
|
-
computeWaitMs,
|
|
18
|
-
inProcessBudgetMs,
|
|
19
|
-
readRateLimitPolicy,
|
|
20
|
-
resolveRateLimitHint,
|
|
21
|
-
} = require('./rate-limit');
|
|
22
11
|
|
|
23
12
|
const DEFAULT_REQUEST_TIMEOUT_MS = 60_000;
|
|
24
13
|
|
|
@@ -33,10 +22,6 @@ function sanitizedCause(err) {
|
|
|
33
22
|
}
|
|
34
23
|
const MAX_AUTH_RETRIES = 3;
|
|
35
24
|
|
|
36
|
-
// Hinted waits are bounded by time, but a provider that always answers with a
|
|
37
|
-
// short Retry-After would still keep the request in a long loop.
|
|
38
|
-
const MAX_HINTED_RETRIES = 10;
|
|
39
|
-
|
|
40
25
|
// This context marks the async call chain that holds the refresh slot, and
|
|
41
26
|
// names the requester that holds it. Token requests re-enter _rawRequest
|
|
42
27
|
// through this._post. A 401 from inside that chain must fail fast: if it
|
|
@@ -49,8 +34,6 @@ class Requester extends Delegate {
|
|
|
49
34
|
constructor(params) {
|
|
50
35
|
super(params);
|
|
51
36
|
this.backOff = get(params, 'backOff', [1, 3, 10, 30, 60, 180]);
|
|
52
|
-
this._rateLimitPolicy = readRateLimitPolicy(this.constructor);
|
|
53
|
-
this._random = params?.random ?? Math.random;
|
|
54
37
|
this.isRefreshable = false;
|
|
55
38
|
this.refreshCount = 0;
|
|
56
39
|
this.authGraceRetryCount = 0;
|
|
@@ -228,16 +211,9 @@ class Requester extends Delegate {
|
|
|
228
211
|
* @param {Object} options - Fetch options, as built by `_request`.
|
|
229
212
|
* @param {number} attempt - 0-based count of retries already made for
|
|
230
213
|
* this call. Indexes `this.backOff` for the next delay and is passed
|
|
231
|
-
* back in on each recursive retry.
|
|
232
|
-
* @param {{ waitedMs: number, retries: number }} hinted - The time slept
|
|
233
|
-
* and the retries made for rate-limit hints, for the whole call.
|
|
214
|
+
* back in on each recursive retry.
|
|
234
215
|
*/
|
|
235
|
-
async _rawRequest(
|
|
236
|
-
url,
|
|
237
|
-
options,
|
|
238
|
-
attempt = 0,
|
|
239
|
-
hinted = { waitedMs: 0, retries: 0 }
|
|
240
|
-
) {
|
|
216
|
+
async _rawRequest(url, options, attempt = 0) {
|
|
241
217
|
let encodedUrl = encodeURI(url);
|
|
242
218
|
if (options.query) {
|
|
243
219
|
let queryBuild = '?';
|
|
@@ -303,7 +279,7 @@ class Requester extends Delegate {
|
|
|
303
279
|
clearRequestTimer();
|
|
304
280
|
const delay = this.backOff[attempt] * 1000;
|
|
305
281
|
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
306
|
-
return this._rawRequest(url, options, attempt + 1
|
|
282
|
+
return this._rawRequest(url, options, attempt + 1);
|
|
307
283
|
}
|
|
308
284
|
const fetchError = await FetchError.create({
|
|
309
285
|
resource: encodedUrl,
|
|
@@ -322,41 +298,15 @@ class Requester extends Delegate {
|
|
|
322
298
|
|
|
323
299
|
const { status } = response;
|
|
324
300
|
|
|
325
|
-
const throttle = await this._detectThrottle(
|
|
326
|
-
response,
|
|
327
|
-
status,
|
|
328
|
-
attempt
|
|
329
|
-
);
|
|
330
|
-
const hintedDelayMs = await this._hintedRetryDelayMs({
|
|
331
|
-
throttle,
|
|
332
|
-
status,
|
|
333
|
-
attempt,
|
|
334
|
-
hinted,
|
|
335
|
-
encodedUrl,
|
|
336
|
-
options,
|
|
337
|
-
response,
|
|
338
|
-
timeoutMs,
|
|
339
|
-
});
|
|
340
|
-
if (hintedDelayMs !== null) {
|
|
341
|
-
clearRequestTimer();
|
|
342
|
-
await new Promise((resolve) =>
|
|
343
|
-
setTimeout(resolve, hintedDelayMs)
|
|
344
|
-
);
|
|
345
|
-
return this._rawRequest(url, options, attempt, {
|
|
346
|
-
waitedMs: hinted.waitedMs + hintedDelayMs,
|
|
347
|
-
retries: hinted.retries + 1,
|
|
348
|
-
});
|
|
349
|
-
}
|
|
350
|
-
|
|
351
301
|
// If the status is retriable and there are back off requests left, retry the request
|
|
352
302
|
if (
|
|
353
|
-
(
|
|
303
|
+
(status === 429 || status >= 500) &&
|
|
354
304
|
attempt < this.backOff.length
|
|
355
305
|
) {
|
|
356
306
|
clearRequestTimer();
|
|
357
307
|
const delay = this.backOff[attempt] * 1000;
|
|
358
308
|
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
359
|
-
return this._rawRequest(url, options, attempt + 1
|
|
309
|
+
return this._rawRequest(url, options, attempt + 1);
|
|
360
310
|
}
|
|
361
311
|
|
|
362
312
|
if (status === 401) {
|
|
@@ -377,7 +327,7 @@ class Requester extends Delegate {
|
|
|
377
327
|
// This request did not try the current token. Retry with
|
|
378
328
|
// it. Do not spend one more provider-side rotation.
|
|
379
329
|
clearRequestTimer();
|
|
380
|
-
return this._rawRequest(url, options, attempt + 1
|
|
330
|
+
return this._rawRequest(url, options, attempt + 1);
|
|
381
331
|
}
|
|
382
332
|
|
|
383
333
|
if (!this.isRefreshable) {
|
|
@@ -394,12 +344,7 @@ class Requester extends Delegate {
|
|
|
394
344
|
await new Promise((resolve) =>
|
|
395
345
|
setTimeout(resolve, delay)
|
|
396
346
|
);
|
|
397
|
-
return this._rawRequest(
|
|
398
|
-
url,
|
|
399
|
-
options,
|
|
400
|
-
attempt + 1,
|
|
401
|
-
hinted
|
|
402
|
-
);
|
|
347
|
+
return this._rawRequest(url, options, attempt + 1);
|
|
403
348
|
}
|
|
404
349
|
|
|
405
350
|
throw await this._invalidateAuth(
|
|
@@ -432,7 +377,7 @@ class Requester extends Delegate {
|
|
|
432
377
|
const refreshSucceeded = await this._refreshAuthOnce();
|
|
433
378
|
if (refreshSucceeded) {
|
|
434
379
|
clearRequestTimer();
|
|
435
|
-
return this._rawRequest(url, options, attempt + 1
|
|
380
|
+
return this._rawRequest(url, options, attempt + 1);
|
|
436
381
|
}
|
|
437
382
|
|
|
438
383
|
throw await this._invalidateAuth(encodedUrl, options, response);
|
|
@@ -447,7 +392,6 @@ class Requester extends Delegate {
|
|
|
447
392
|
resource: encodedUrl,
|
|
448
393
|
init: options,
|
|
449
394
|
response,
|
|
450
|
-
responseBody: throttle?.responseBody,
|
|
451
395
|
});
|
|
452
396
|
throw this._maybeFlagTimeoutDuringBodyRead(
|
|
453
397
|
fetchError,
|
|
@@ -477,128 +421,6 @@ class Requester extends Delegate {
|
|
|
477
421
|
}
|
|
478
422
|
}
|
|
479
423
|
|
|
480
|
-
async _hintedRetryDelayMs({
|
|
481
|
-
throttle,
|
|
482
|
-
status,
|
|
483
|
-
attempt,
|
|
484
|
-
hinted,
|
|
485
|
-
encodedUrl,
|
|
486
|
-
options,
|
|
487
|
-
response,
|
|
488
|
-
timeoutMs,
|
|
489
|
-
}) {
|
|
490
|
-
if (!throttle?.throttled || throttle.hint.source === 'backoff') {
|
|
491
|
-
return null;
|
|
492
|
-
}
|
|
493
|
-
const { hint } = throttle;
|
|
494
|
-
const untimed = hint.waitMs === undefined;
|
|
495
|
-
const mayWait =
|
|
496
|
-
this.backOff.length > 0 && hinted.retries < MAX_HINTED_RETRIES;
|
|
497
|
-
const budgetMs = mayWait
|
|
498
|
-
? inProcessBudgetMs({
|
|
499
|
-
maxInProcessWaitMs: invocationMaxInProcessWaitMs(),
|
|
500
|
-
requestTimeoutMs: this.requestTimeoutMs,
|
|
501
|
-
remainingMs: remainingInvocationMs(),
|
|
502
|
-
waitedMs: hinted.waitedMs,
|
|
503
|
-
})
|
|
504
|
-
: 0;
|
|
505
|
-
const { waitMs, fits } = untimed
|
|
506
|
-
? { waitMs: undefined, fits: false }
|
|
507
|
-
: computeWaitMs({
|
|
508
|
-
hint,
|
|
509
|
-
policy: this._rateLimitPolicy,
|
|
510
|
-
budgetMs,
|
|
511
|
-
random: this._random,
|
|
512
|
-
});
|
|
513
|
-
if (fits) {
|
|
514
|
-
this._logRateLimited({
|
|
515
|
-
status,
|
|
516
|
-
hint,
|
|
517
|
-
waitMs,
|
|
518
|
-
attempt,
|
|
519
|
-
waitedMs: hinted.waitedMs,
|
|
520
|
-
});
|
|
521
|
-
return waitMs;
|
|
522
|
-
}
|
|
523
|
-
|
|
524
|
-
this._logRequestFailed(encodedUrl, options, status);
|
|
525
|
-
const rateLimitError = await RateLimitError.create({
|
|
526
|
-
resource: encodedUrl,
|
|
527
|
-
init: options,
|
|
528
|
-
response,
|
|
529
|
-
responseBody: throttle.responseBody,
|
|
530
|
-
hint,
|
|
531
|
-
waitMs,
|
|
532
|
-
module: this._telemetryModuleLabel(),
|
|
533
|
-
scopeKey: computeScopeKey(this._rateLimitPolicy, this),
|
|
534
|
-
});
|
|
535
|
-
throw this._maybeFlagTimeoutDuringBodyRead(rateLimitError, timeoutMs);
|
|
536
|
-
}
|
|
537
|
-
|
|
538
|
-
async _detectThrottle(response, status, attempt) {
|
|
539
|
-
const policy = this._rateLimitPolicy;
|
|
540
|
-
const canClassify =
|
|
541
|
-
typeof policy?.classify === 'function' &&
|
|
542
|
-
status >= 400 &&
|
|
543
|
-
status !== 401;
|
|
544
|
-
if (status !== 429 && !canClassify) return null;
|
|
545
|
-
|
|
546
|
-
let responseBody;
|
|
547
|
-
let body;
|
|
548
|
-
if (canClassify) {
|
|
549
|
-
({ text: responseBody, json: body } =
|
|
550
|
-
await this._readBodyForClassify(response));
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
const hint = resolveRateLimitHint(
|
|
554
|
-
policy,
|
|
555
|
-
{ status, headers: response.headers, body },
|
|
556
|
-
{
|
|
557
|
-
attempt,
|
|
558
|
-
backOff: this.backOff,
|
|
559
|
-
now: Date.now(),
|
|
560
|
-
onClassifyError: (error) =>
|
|
561
|
-
this._logClassifyFailed(status, error),
|
|
562
|
-
}
|
|
563
|
-
);
|
|
564
|
-
return { throttled: Boolean(hint), hint, responseBody };
|
|
565
|
-
}
|
|
566
|
-
|
|
567
|
-
async _readBodyForClassify(response) {
|
|
568
|
-
if (response.bodyUsed || typeof response.text !== 'function') {
|
|
569
|
-
return {};
|
|
570
|
-
}
|
|
571
|
-
const text = await response.text();
|
|
572
|
-
try {
|
|
573
|
-
return { text, json: JSON.parse(text) };
|
|
574
|
-
} catch {
|
|
575
|
-
return { text };
|
|
576
|
-
}
|
|
577
|
-
}
|
|
578
|
-
|
|
579
|
-
_logRateLimited({ status, hint, waitMs, attempt, waitedMs }) {
|
|
580
|
-
const logger = this.logger;
|
|
581
|
-
logger.trace('Rate limited', {
|
|
582
|
-
eventName: `${logger.name}.rate_limited`,
|
|
583
|
-
statusCode: status,
|
|
584
|
-
waitMs,
|
|
585
|
-
retryAt: new Date(Date.now() + waitMs).toISOString(),
|
|
586
|
-
reason: hint.reason,
|
|
587
|
-
hintSource: hint.source,
|
|
588
|
-
attempt,
|
|
589
|
-
waitedMs,
|
|
590
|
-
});
|
|
591
|
-
}
|
|
592
|
-
|
|
593
|
-
_logClassifyFailed(status, error) {
|
|
594
|
-
const logger = this.logger;
|
|
595
|
-
logger.warn('Rate limit classifier failed', {
|
|
596
|
-
eventName: `${logger.name}.rate_limit_classify_failed`,
|
|
597
|
-
statusCode: status,
|
|
598
|
-
error,
|
|
599
|
-
});
|
|
600
|
-
}
|
|
601
|
-
|
|
602
424
|
_logRequestFailed(encodedUrl, options, status) {
|
|
603
425
|
const logger = this.logger;
|
|
604
426
|
if (!logger.isLevelEnabled('DEBUG')) return;
|