@friggframework/core 2.0.0--canary.658.e11f3b0.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 +42 -58
- 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 -3
- package/core/Worker.js +2 -1
- 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/workers/integration-defined-workers.js +0 -2
- package/index.js +2 -18
- package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +67 -13
- package/integrations/integration-base.js +52 -25
- 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 +42 -23
- package/integrations/repositories/integration-repository-interface.js +37 -21
- package/integrations/repositories/integration-repository-mongo.js +69 -30
- package/integrations/repositories/integration-repository-postgres.js +74 -30
- package/integrations/repositories/process-repository-mongo.js +1 -1
- package/integrations/tests/doubles/test-integration-repository.js +2 -15
- 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/remove-entities-from-integration.js +70 -0
- package/integrations/use-cases/update-integration-messages.js +9 -28
- 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/module.js +0 -27
- package/modules/requester/requester.js +9 -211
- 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 +10 -7
- package/prisma-mongodb/schema.prisma +1 -1
- package/prisma-postgresql/schema.prisma +1 -1
- package/queues/queuer-util.js +9 -7
- 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 -33
- package/types/errors/index.d.ts +0 -47
- package/types/integrations/index.d.ts +4 -20
- package/types/module-plugin/index.d.ts +0 -47
- 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/repositories/message-item-shared.js +0 -4
- package/integrations/tests/doubles/prisma-message-row.js +0 -24
- package/integrations/use-cases/record-rate-limit-message.js +0 -110
- 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
|
@@ -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
|
|
package/modules/module.js
CHANGED
|
@@ -8,7 +8,6 @@ const {
|
|
|
8
8
|
const {
|
|
9
9
|
createModuleRepository,
|
|
10
10
|
} = require('./repositories/module-repository-factory');
|
|
11
|
-
const { readRateLimitPolicy } = require('./requester/rate-limit');
|
|
12
11
|
|
|
13
12
|
// todo: this class should be a Domain class, and the Delegate function is preventing us from
|
|
14
13
|
// doing that, we probably have to get rid of the Delegate class as well as the event based
|
|
@@ -52,8 +51,6 @@ class Module extends Delegate {
|
|
|
52
51
|
this.delegateTypes.push(this.DLGT_CREDENTIAL_INVALIDATED);
|
|
53
52
|
this.DLGT_CREDENTIAL_VALIDATED = 'CREDENTIAL_VALIDATED';
|
|
54
53
|
this.delegateTypes.push(this.DLGT_CREDENTIAL_VALIDATED);
|
|
55
|
-
this.DLGT_RATE_LIMITED = 'RATE_LIMITED';
|
|
56
|
-
this.delegateTypes.push(this.DLGT_RATE_LIMITED);
|
|
57
54
|
|
|
58
55
|
Object.assign(this, this.definition.requiredAuthMethods);
|
|
59
56
|
|
|
@@ -163,8 +160,6 @@ class Module extends Delegate {
|
|
|
163
160
|
await this.deauthorize();
|
|
164
161
|
} else if (delegateString === this.api.DLGT_INVALID_AUTH) {
|
|
165
162
|
await this.markCredentialsInvalid(object);
|
|
166
|
-
} else if (delegateString === this.api.DLGT_RATE_LIMITED) {
|
|
167
|
-
await this.reportRateLimit(object);
|
|
168
163
|
} else if (delegateString === this.api.DLGT_CREDENTIAL_RELOAD) {
|
|
169
164
|
return this.reloadCredential();
|
|
170
165
|
}
|
|
@@ -239,28 +234,6 @@ class Module extends Delegate {
|
|
|
239
234
|
}
|
|
240
235
|
}
|
|
241
236
|
|
|
242
|
-
async reportRateLimit(rateLimitError) {
|
|
243
|
-
const { reason, retryAt, policy, statusCode } = rateLimitError;
|
|
244
|
-
const links =
|
|
245
|
-
readRateLimitPolicy(this.apiClass)?.userHints?.[reason]?.links ??
|
|
246
|
-
[];
|
|
247
|
-
try {
|
|
248
|
-
await this.notify(this.DLGT_RATE_LIMITED, {
|
|
249
|
-
moduleName: this.name,
|
|
250
|
-
reason,
|
|
251
|
-
retryAt,
|
|
252
|
-
policy,
|
|
253
|
-
statusCode,
|
|
254
|
-
links,
|
|
255
|
-
});
|
|
256
|
-
} catch (err) {
|
|
257
|
-
this.logger.warn('Failed to propagate RATE_LIMITED', {
|
|
258
|
-
eventName: `${this.logger.name}.rate_limit_propagation_failed`,
|
|
259
|
-
error: err,
|
|
260
|
-
});
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
|
|
264
237
|
async deauthorize() {
|
|
265
238
|
//todo: Check if this is correct, we're instantiating a new api without params (credentials, tokens, etc...)
|
|
266
239
|
this.api = new this.apiClass();
|
|
@@ -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;
|
|
@@ -61,8 +44,6 @@ class Requester extends Delegate {
|
|
|
61
44
|
this._authGeneration = 0;
|
|
62
45
|
this.DLGT_INVALID_AUTH = 'INVALID_AUTH';
|
|
63
46
|
this.delegateTypes.push(this.DLGT_INVALID_AUTH);
|
|
64
|
-
this.DLGT_RATE_LIMITED = 'RATE_LIMITED';
|
|
65
|
-
this.delegateTypes.push(this.DLGT_RATE_LIMITED);
|
|
66
47
|
this.agent = get(params, 'agent', null);
|
|
67
48
|
|
|
68
49
|
// Per-attempt HTTP timeout. Without this the framework called fetch()
|
|
@@ -230,16 +211,9 @@ class Requester extends Delegate {
|
|
|
230
211
|
* @param {Object} options - Fetch options, as built by `_request`.
|
|
231
212
|
* @param {number} attempt - 0-based count of retries already made for
|
|
232
213
|
* this call. Indexes `this.backOff` for the next delay and is passed
|
|
233
|
-
* back in on each recursive retry.
|
|
234
|
-
* @param {{ waitedMs: number, retries: number }} hinted - The time slept
|
|
235
|
-
* and the retries made for rate-limit hints, for the whole call.
|
|
214
|
+
* back in on each recursive retry.
|
|
236
215
|
*/
|
|
237
|
-
async _rawRequest(
|
|
238
|
-
url,
|
|
239
|
-
options,
|
|
240
|
-
attempt = 0,
|
|
241
|
-
hinted = { waitedMs: 0, retries: 0 }
|
|
242
|
-
) {
|
|
216
|
+
async _rawRequest(url, options, attempt = 0) {
|
|
243
217
|
let encodedUrl = encodeURI(url);
|
|
244
218
|
if (options.query) {
|
|
245
219
|
let queryBuild = '?';
|
|
@@ -305,7 +279,7 @@ class Requester extends Delegate {
|
|
|
305
279
|
clearRequestTimer();
|
|
306
280
|
const delay = this.backOff[attempt] * 1000;
|
|
307
281
|
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
308
|
-
return this._rawRequest(url, options, attempt + 1
|
|
282
|
+
return this._rawRequest(url, options, attempt + 1);
|
|
309
283
|
}
|
|
310
284
|
const fetchError = await FetchError.create({
|
|
311
285
|
resource: encodedUrl,
|
|
@@ -324,41 +298,15 @@ class Requester extends Delegate {
|
|
|
324
298
|
|
|
325
299
|
const { status } = response;
|
|
326
300
|
|
|
327
|
-
const throttle = await this._detectThrottle(
|
|
328
|
-
response,
|
|
329
|
-
status,
|
|
330
|
-
attempt
|
|
331
|
-
);
|
|
332
|
-
const hintedDelayMs = await this._hintedRetryDelayMs({
|
|
333
|
-
throttle,
|
|
334
|
-
status,
|
|
335
|
-
attempt,
|
|
336
|
-
hinted,
|
|
337
|
-
encodedUrl,
|
|
338
|
-
options,
|
|
339
|
-
response,
|
|
340
|
-
timeoutMs,
|
|
341
|
-
});
|
|
342
|
-
if (hintedDelayMs !== null) {
|
|
343
|
-
clearRequestTimer();
|
|
344
|
-
await new Promise((resolve) =>
|
|
345
|
-
setTimeout(resolve, hintedDelayMs)
|
|
346
|
-
);
|
|
347
|
-
return this._rawRequest(url, options, attempt, {
|
|
348
|
-
waitedMs: hinted.waitedMs + hintedDelayMs,
|
|
349
|
-
retries: hinted.retries + 1,
|
|
350
|
-
});
|
|
351
|
-
}
|
|
352
|
-
|
|
353
301
|
// If the status is retriable and there are back off requests left, retry the request
|
|
354
302
|
if (
|
|
355
|
-
(
|
|
303
|
+
(status === 429 || status >= 500) &&
|
|
356
304
|
attempt < this.backOff.length
|
|
357
305
|
) {
|
|
358
306
|
clearRequestTimer();
|
|
359
307
|
const delay = this.backOff[attempt] * 1000;
|
|
360
308
|
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
361
|
-
return this._rawRequest(url, options, attempt + 1
|
|
309
|
+
return this._rawRequest(url, options, attempt + 1);
|
|
362
310
|
}
|
|
363
311
|
|
|
364
312
|
if (status === 401) {
|
|
@@ -379,7 +327,7 @@ class Requester extends Delegate {
|
|
|
379
327
|
// This request did not try the current token. Retry with
|
|
380
328
|
// it. Do not spend one more provider-side rotation.
|
|
381
329
|
clearRequestTimer();
|
|
382
|
-
return this._rawRequest(url, options, attempt + 1
|
|
330
|
+
return this._rawRequest(url, options, attempt + 1);
|
|
383
331
|
}
|
|
384
332
|
|
|
385
333
|
if (!this.isRefreshable) {
|
|
@@ -396,12 +344,7 @@ class Requester extends Delegate {
|
|
|
396
344
|
await new Promise((resolve) =>
|
|
397
345
|
setTimeout(resolve, delay)
|
|
398
346
|
);
|
|
399
|
-
return this._rawRequest(
|
|
400
|
-
url,
|
|
401
|
-
options,
|
|
402
|
-
attempt + 1,
|
|
403
|
-
hinted
|
|
404
|
-
);
|
|
347
|
+
return this._rawRequest(url, options, attempt + 1);
|
|
405
348
|
}
|
|
406
349
|
|
|
407
350
|
throw await this._invalidateAuth(
|
|
@@ -434,7 +377,7 @@ class Requester extends Delegate {
|
|
|
434
377
|
const refreshSucceeded = await this._refreshAuthOnce();
|
|
435
378
|
if (refreshSucceeded) {
|
|
436
379
|
clearRequestTimer();
|
|
437
|
-
return this._rawRequest(url, options, attempt + 1
|
|
380
|
+
return this._rawRequest(url, options, attempt + 1);
|
|
438
381
|
}
|
|
439
382
|
|
|
440
383
|
throw await this._invalidateAuth(encodedUrl, options, response);
|
|
@@ -449,7 +392,6 @@ class Requester extends Delegate {
|
|
|
449
392
|
resource: encodedUrl,
|
|
450
393
|
init: options,
|
|
451
394
|
response,
|
|
452
|
-
responseBody: throttle?.responseBody,
|
|
453
395
|
});
|
|
454
396
|
throw this._maybeFlagTimeoutDuringBodyRead(
|
|
455
397
|
fetchError,
|
|
@@ -479,150 +421,6 @@ class Requester extends Delegate {
|
|
|
479
421
|
}
|
|
480
422
|
}
|
|
481
423
|
|
|
482
|
-
async _hintedRetryDelayMs({
|
|
483
|
-
throttle,
|
|
484
|
-
status,
|
|
485
|
-
attempt,
|
|
486
|
-
hinted,
|
|
487
|
-
encodedUrl,
|
|
488
|
-
options,
|
|
489
|
-
response,
|
|
490
|
-
timeoutMs,
|
|
491
|
-
}) {
|
|
492
|
-
if (!throttle?.throttled || throttle.hint.source === 'backoff') {
|
|
493
|
-
return null;
|
|
494
|
-
}
|
|
495
|
-
const { hint } = throttle;
|
|
496
|
-
const untimed = hint.waitMs === undefined;
|
|
497
|
-
const mayWait =
|
|
498
|
-
this.backOff.length > 0 && hinted.retries < MAX_HINTED_RETRIES;
|
|
499
|
-
const budgetMs = mayWait
|
|
500
|
-
? inProcessBudgetMs({
|
|
501
|
-
maxInProcessWaitMs: invocationMaxInProcessWaitMs(),
|
|
502
|
-
requestTimeoutMs: this.requestTimeoutMs,
|
|
503
|
-
remainingMs: remainingInvocationMs(),
|
|
504
|
-
waitedMs: hinted.waitedMs,
|
|
505
|
-
})
|
|
506
|
-
: 0;
|
|
507
|
-
const { waitMs, fits } = untimed
|
|
508
|
-
? { waitMs: undefined, fits: false }
|
|
509
|
-
: computeWaitMs({
|
|
510
|
-
hint,
|
|
511
|
-
policy: this._rateLimitPolicy,
|
|
512
|
-
budgetMs,
|
|
513
|
-
random: this._random,
|
|
514
|
-
});
|
|
515
|
-
if (fits) {
|
|
516
|
-
this._logRateLimited({
|
|
517
|
-
status,
|
|
518
|
-
hint,
|
|
519
|
-
waitMs,
|
|
520
|
-
attempt,
|
|
521
|
-
waitedMs: hinted.waitedMs,
|
|
522
|
-
});
|
|
523
|
-
return waitMs;
|
|
524
|
-
}
|
|
525
|
-
|
|
526
|
-
this._logRequestFailed(encodedUrl, options, status);
|
|
527
|
-
const rateLimitError = await RateLimitError.create({
|
|
528
|
-
resource: encodedUrl,
|
|
529
|
-
init: options,
|
|
530
|
-
response,
|
|
531
|
-
responseBody: throttle.responseBody,
|
|
532
|
-
hint,
|
|
533
|
-
waitMs,
|
|
534
|
-
module: this._telemetryModuleLabel(),
|
|
535
|
-
scopeKey: computeScopeKey(this._rateLimitPolicy, this),
|
|
536
|
-
});
|
|
537
|
-
await this._notifyRateLimited(rateLimitError);
|
|
538
|
-
throw this._maybeFlagTimeoutDuringBodyRead(rateLimitError, timeoutMs);
|
|
539
|
-
}
|
|
540
|
-
|
|
541
|
-
async _detectThrottle(response, status, attempt) {
|
|
542
|
-
const policy = this._rateLimitPolicy;
|
|
543
|
-
const canClassify =
|
|
544
|
-
typeof policy?.classify === 'function' &&
|
|
545
|
-
status >= 400 &&
|
|
546
|
-
status !== 401;
|
|
547
|
-
if (status !== 429 && !canClassify) return null;
|
|
548
|
-
|
|
549
|
-
let responseBody;
|
|
550
|
-
let body;
|
|
551
|
-
if (canClassify) {
|
|
552
|
-
({ text: responseBody, json: body } =
|
|
553
|
-
await this._readBodyForClassify(response));
|
|
554
|
-
}
|
|
555
|
-
|
|
556
|
-
const hint = resolveRateLimitHint(
|
|
557
|
-
policy,
|
|
558
|
-
{ status, headers: response.headers, body },
|
|
559
|
-
{
|
|
560
|
-
attempt,
|
|
561
|
-
backOff: this.backOff,
|
|
562
|
-
now: Date.now(),
|
|
563
|
-
onClassifyError: (error) =>
|
|
564
|
-
this._logClassifyFailed(status, error),
|
|
565
|
-
}
|
|
566
|
-
);
|
|
567
|
-
return { throttled: Boolean(hint), hint, responseBody };
|
|
568
|
-
}
|
|
569
|
-
|
|
570
|
-
async _readBodyForClassify(response) {
|
|
571
|
-
if (response.bodyUsed || typeof response.text !== 'function') {
|
|
572
|
-
return {};
|
|
573
|
-
}
|
|
574
|
-
const text = await response.text();
|
|
575
|
-
try {
|
|
576
|
-
return { text, json: JSON.parse(text) };
|
|
577
|
-
} catch {
|
|
578
|
-
return { text };
|
|
579
|
-
}
|
|
580
|
-
}
|
|
581
|
-
|
|
582
|
-
_logRateLimited({ status, hint, waitMs, attempt, waitedMs }) {
|
|
583
|
-
const logger = this.logger;
|
|
584
|
-
logger.trace('Rate limited', {
|
|
585
|
-
eventName: `${logger.name}.rate_limited`,
|
|
586
|
-
statusCode: status,
|
|
587
|
-
waitMs,
|
|
588
|
-
retryAt: new Date(Date.now() + waitMs).toISOString(),
|
|
589
|
-
reason: hint.reason,
|
|
590
|
-
hintSource: hint.source,
|
|
591
|
-
attempt,
|
|
592
|
-
waitedMs,
|
|
593
|
-
});
|
|
594
|
-
}
|
|
595
|
-
|
|
596
|
-
_logClassifyFailed(status, error) {
|
|
597
|
-
const logger = this.logger;
|
|
598
|
-
logger.warn('Rate limit classifier failed', {
|
|
599
|
-
eventName: `${logger.name}.rate_limit_classify_failed`,
|
|
600
|
-
statusCode: status,
|
|
601
|
-
error,
|
|
602
|
-
});
|
|
603
|
-
}
|
|
604
|
-
|
|
605
|
-
async _notifyRateLimited(rateLimitError) {
|
|
606
|
-
if (!this._waitsLongerThanInProcessCap(rateLimitError)) return;
|
|
607
|
-
try {
|
|
608
|
-
await this.notify(this.DLGT_RATE_LIMITED, rateLimitError);
|
|
609
|
-
} catch (error) {
|
|
610
|
-
const logger = this.logger;
|
|
611
|
-
logger.warn('Rate limit notification failed', {
|
|
612
|
-
eventName: `${logger.name}.rate_limit_notify_failed`,
|
|
613
|
-
statusCode: rateLimitError.statusCode,
|
|
614
|
-
error,
|
|
615
|
-
});
|
|
616
|
-
}
|
|
617
|
-
}
|
|
618
|
-
|
|
619
|
-
_waitsLongerThanInProcessCap(rateLimitError) {
|
|
620
|
-
const waitMs = Number.isFinite(rateLimitError?.waitMs)
|
|
621
|
-
? rateLimitError.waitMs
|
|
622
|
-
: new Date(rateLimitError?.retryAt).getTime() - Date.now();
|
|
623
|
-
return waitMs > invocationMaxInProcessWaitMs();
|
|
624
|
-
}
|
|
625
|
-
|
|
626
424
|
_logRequestFailed(encodedUrl, options, status) {
|
|
627
425
|
const logger = this.logger;
|
|
628
426
|
if (!logger.isLevelEnabled('DEBUG')) return;
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
const Boom = require('@hapi/boom');
|
|
2
|
+
const { Module } = require('../module');
|
|
3
|
+
|
|
4
|
+
const sameId = (a, b) =>
|
|
5
|
+
a !== undefined &&
|
|
6
|
+
a !== null &&
|
|
7
|
+
b !== undefined &&
|
|
8
|
+
b !== null &&
|
|
9
|
+
String(a) === String(b);
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Creates (or finds) the entity for a credential the caller already holds:
|
|
13
|
+
* the v1 `POST /api/entity`.
|
|
14
|
+
*
|
|
15
|
+
* The module is built with the stored credential loaded, so the API can call
|
|
16
|
+
* the provider and a token refresh during `getEntityDetails` updates that
|
|
17
|
+
* credential. Persistence reuses `ProcessAuthorizationCallback.findOrCreateEntity`,
|
|
18
|
+
* the same find-or-create (and credential repointing) the authorization flow
|
|
19
|
+
* uses, so the two paths cannot drift.
|
|
20
|
+
*/
|
|
21
|
+
class CreateEntityFromCredential {
|
|
22
|
+
/**
|
|
23
|
+
* @param {Object} params
|
|
24
|
+
* @param {import('./process-authorization-callback').ProcessAuthorizationCallback} params.processAuthorizationCallback
|
|
25
|
+
* @param {Object} params.credentialRepository
|
|
26
|
+
* @param {Array<Object>} params.moduleDefinitions
|
|
27
|
+
* @param {Function} [params.createModule] - builds a Module; injectable for tests
|
|
28
|
+
*/
|
|
29
|
+
constructor({
|
|
30
|
+
processAuthorizationCallback,
|
|
31
|
+
credentialRepository,
|
|
32
|
+
moduleDefinitions,
|
|
33
|
+
createModule,
|
|
34
|
+
}) {
|
|
35
|
+
this.processAuthorizationCallback = processAuthorizationCallback;
|
|
36
|
+
this.credentialRepository = credentialRepository;
|
|
37
|
+
this.moduleDefinitions = moduleDefinitions || [];
|
|
38
|
+
this.createModule = createModule || ((params) => new Module(params));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* @param {Object} params
|
|
43
|
+
* @param {Object} params.user - authenticated User
|
|
44
|
+
* @param {string} params.entityType
|
|
45
|
+
* @param {string} params.credentialId
|
|
46
|
+
* @returns {Promise<Object>} the persisted entity
|
|
47
|
+
*/
|
|
48
|
+
async execute({ user, entityType, credentialId }) {
|
|
49
|
+
const userId = user?.getId?.();
|
|
50
|
+
if (userId === undefined || userId === null) {
|
|
51
|
+
throw Boom.unauthorized('No authenticated user');
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const definition = this.moduleDefinitions.find(
|
|
55
|
+
(def) => def && def.moduleName === entityType
|
|
56
|
+
);
|
|
57
|
+
if (!definition) {
|
|
58
|
+
throw Boom.badRequest(`Unknown entity type ${entityType}`, {
|
|
59
|
+
code: 'ENTITY_TYPE_NOT_FOUND',
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const credential =
|
|
64
|
+
await this.credentialRepository.findCredentialById(credentialId);
|
|
65
|
+
// A missing credential and someone else's get the same answer, so
|
|
66
|
+
// credential ids cannot be probed.
|
|
67
|
+
if (!credential || !sameId(credential.userId, userId)) {
|
|
68
|
+
throw Boom.badRequest('Invalid credential ID', {
|
|
69
|
+
code: 'INVALID_CREDENTIAL',
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// The repository returns the tokens flat; a Module reads them from
|
|
74
|
+
// `credential.data`.
|
|
75
|
+
const { id, userId: ownerId, externalId, authIsValid, ...data } =
|
|
76
|
+
credential;
|
|
77
|
+
const module = this.createModule({
|
|
78
|
+
userId,
|
|
79
|
+
definition,
|
|
80
|
+
entity: {
|
|
81
|
+
credential: { id, userId: ownerId, externalId, authIsValid, data },
|
|
82
|
+
},
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
const entityDetails =
|
|
86
|
+
await definition.requiredAuthMethods.getEntityDetails(
|
|
87
|
+
module.api,
|
|
88
|
+
null,
|
|
89
|
+
null,
|
|
90
|
+
userId
|
|
91
|
+
);
|
|
92
|
+
Object.assign(
|
|
93
|
+
entityDetails.details,
|
|
94
|
+
module.apiParamsFromEntity(module.api)
|
|
95
|
+
);
|
|
96
|
+
|
|
97
|
+
return this.processAuthorizationCallback.findOrCreateEntity(
|
|
98
|
+
entityDetails,
|
|
99
|
+
definition.moduleName,
|
|
100
|
+
credential.id
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
module.exports = { CreateEntityFromCredential };
|
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
const { Module } = require('../module');
|
|
2
|
+
const {
|
|
3
|
+
findModuleDefinitionForEntity,
|
|
4
|
+
} = require('../utils/find-module-definition');
|
|
2
5
|
|
|
3
6
|
class GetEntityOptionsById {
|
|
4
7
|
/**
|
|
@@ -45,11 +48,10 @@ class GetEntityOptionsById {
|
|
|
45
48
|
}
|
|
46
49
|
|
|
47
50
|
const entityType = entity.moduleName;
|
|
48
|
-
const moduleDefinition =
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
});
|
|
51
|
+
const moduleDefinition = findModuleDefinitionForEntity(
|
|
52
|
+
this.moduleDefinitions,
|
|
53
|
+
entity
|
|
54
|
+
);
|
|
53
55
|
|
|
54
56
|
if (!moduleDefinition) {
|
|
55
57
|
throw new Error(
|