@friggframework/core 2.0.0--canary.737.83b4e17.0 → 2.0.0--canary.743.57dc4bf.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 +173 -7
- package/core/CLAUDE.md +57 -1
- package/core/Worker.js +440 -11
- package/core/create-handler.js +20 -0
- package/core/index.js +6 -0
- package/core/invocation-deadline.js +91 -0
- package/core/invocation-scope.js +30 -24
- package/core/rate-limited-response.js +27 -0
- package/errors/fetch-error.js +10 -6
- package/errors/index.js +2 -0
- package/errors/rate-limit-error.js +46 -0
- package/handlers/app-handler-helpers.js +15 -0
- package/handlers/backend-utils.js +75 -1
- package/handlers/workers/integration-defined-workers.js +2 -0
- package/index.js +26 -0
- package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +2 -0
- package/integrations/repositories/integration-repository-documentdb.js +59 -10
- package/integrations/repositories/integration-repository-interface.js +50 -7
- package/integrations/repositories/integration-repository-mongo.js +88 -16
- package/integrations/repositories/integration-repository-postgres.js +89 -16
- package/integrations/repositories/message-item-shared.js +17 -0
- package/integrations/tests/doubles/prisma-message-row.js +24 -0
- package/integrations/tests/doubles/test-integration-repository.js +32 -2
- package/integrations/use-cases/clear-rate-limit-wait.js +28 -0
- package/integrations/use-cases/index.js +7 -1
- package/integrations/use-cases/record-rate-limit-message.js +104 -0
- package/integrations/use-cases/record-rate-limit-wait.js +36 -0
- package/integrations/use-cases/update-integration-messages.js +28 -9
- package/logs/serialize.js +15 -0
- package/modules/requester/oauth-2.js +8 -0
- package/modules/requester/rate-limit/index.js +6 -0
- package/modules/requester/rate-limit/pacer.js +551 -0
- package/modules/requester/rate-limit/parsers.js +249 -0
- package/modules/requester/rate-limit/policy.js +326 -0
- package/modules/requester/rate-limit/state/rate-limit-state-repository-factory.js +35 -0
- package/modules/requester/rate-limit/state/rate-limit-state-repository-interface.js +69 -0
- package/modules/requester/rate-limit/state/rate-limit-state-repository-memory.js +62 -0
- package/modules/requester/rate-limit/state/rate-limit-state-repository-mongo.js +148 -0
- package/modules/requester/rate-limit/state/rate-limit-state-repository-postgres.js +93 -0
- package/modules/requester/requester.js +357 -11
- package/package.json +7 -6
- package/queues/queue-deferral.js +155 -0
- package/queues/queue-delivery.js +1 -0
- package/queues/queuer-util.js +3 -4
- package/types/core/consumer.fixture.ts +12 -0
- package/types/core/index.d.ts +84 -0
- package/types/errors/index.d.ts +47 -0
- package/types/integrations/index.d.ts +25 -4
- package/types/module-plugin/index.d.ts +53 -0
- package/queues/sqs-message-body.js +0 -17
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
const {
|
|
2
|
+
RateLimitStateRepositoryInterface,
|
|
3
|
+
} = require('./rate-limit-state-repository-interface');
|
|
4
|
+
|
|
5
|
+
const MAX_KEYS = 10_000;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* In-process state. It is shared by every requester in one process (one
|
|
9
|
+
* Lambda container), but not across containers. It is the reference for the
|
|
10
|
+
* semantics of the shared stores. The entity id is optional here.
|
|
11
|
+
*/
|
|
12
|
+
class RateLimitStateRepositoryMemory extends RateLimitStateRepositoryInterface {
|
|
13
|
+
constructor({ maxKeys = MAX_KEYS } = {}) {
|
|
14
|
+
super();
|
|
15
|
+
this.maxKeys = maxKeys;
|
|
16
|
+
this.rows = new Map();
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
_key({ entityId, scopeKey }) {
|
|
20
|
+
return `${entityId ?? ''}\u0000${scopeKey}`;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
_row(location) {
|
|
24
|
+
const key = this._key(location);
|
|
25
|
+
let row = this.rows.get(key);
|
|
26
|
+
if (!row) {
|
|
27
|
+
// A long-lived process can see many keys. Drop the oldest one.
|
|
28
|
+
if (this.rows.size >= this.maxKeys) {
|
|
29
|
+
this.rows.delete(this.rows.keys().next().value);
|
|
30
|
+
}
|
|
31
|
+
row = { blockedUntil: null, nextSlotMs: null };
|
|
32
|
+
this.rows.set(key, row);
|
|
33
|
+
}
|
|
34
|
+
return row;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async read(location) {
|
|
38
|
+
const row = this.rows.get(this._key(location));
|
|
39
|
+
return row ? { blockedUntil: row.blockedUntil } : null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async block(location, until) {
|
|
43
|
+
const row = this._row(location);
|
|
44
|
+
if (!row.blockedUntil || row.blockedUntil < until) {
|
|
45
|
+
row.blockedUntil = new Date(until.getTime());
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async reserveSlot(location, { notBefore, intervalMs }) {
|
|
50
|
+
const row = this._row(location);
|
|
51
|
+
const slot = Math.max(row.nextSlotMs ?? 0, notBefore.getTime());
|
|
52
|
+
row.nextSlotMs = slot + slotStepMs(intervalMs);
|
|
53
|
+
return new Date(slot);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Whole milliseconds, at least 1, so slots stay apart. */
|
|
58
|
+
function slotStepMs(intervalMs) {
|
|
59
|
+
return Math.max(1, Math.ceil(intervalMs));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
module.exports = { RateLimitStateRepositoryMemory, slotStepMs };
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
const {
|
|
2
|
+
RateLimitStateRepositoryInterface,
|
|
3
|
+
STATE_FIELD,
|
|
4
|
+
stateMemberName,
|
|
5
|
+
} = require('./rate-limit-state-repository-interface');
|
|
6
|
+
const { slotStepMs } = require('./rate-limit-state-repository-memory');
|
|
7
|
+
|
|
8
|
+
const COLLECTION = 'Entity';
|
|
9
|
+
const MAX_ATTEMPTS = 5;
|
|
10
|
+
const OBJECT_ID = /^[0-9a-f]{24}$/i;
|
|
11
|
+
|
|
12
|
+
function toNumber(value) {
|
|
13
|
+
if (value === null || value === undefined) return null;
|
|
14
|
+
if (typeof value === 'object') {
|
|
15
|
+
const raw =
|
|
16
|
+
value.$numberDouble ?? value.$numberLong ?? value.$numberInt;
|
|
17
|
+
return raw === undefined ? null : Number(raw);
|
|
18
|
+
}
|
|
19
|
+
const number = Number(value);
|
|
20
|
+
return Number.isFinite(number) ? number : null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const entityFilter = (entityId) =>
|
|
24
|
+
typeof entityId === 'string' && OBJECT_ID.test(entityId)
|
|
25
|
+
? { _id: { $oid: entityId } }
|
|
26
|
+
: undefined;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* MongoDB and DocumentDB: the state is in the `data` document of the Entity
|
|
30
|
+
* collection, written with raw commands (DocumentDB does not accept every
|
|
31
|
+
* command shape that Prisma's Mongo engine sends). No upsert: an entity that
|
|
32
|
+
* does not exist has no state. Every write is one atomic command:
|
|
33
|
+
*
|
|
34
|
+
* - block: one conditional update ($lt) of `blockedUntil`.
|
|
35
|
+
* - reserveSlot: a findAndModify that $inc's a slot sequence that is still
|
|
36
|
+
* ahead, else one that restarts a stale or missing one at notBefore. Each
|
|
37
|
+
* successful command hands out one distinct slot. When both miss, another
|
|
38
|
+
* worker moved the sequence between them: try again.
|
|
39
|
+
*/
|
|
40
|
+
class RateLimitStateRepositoryMongo extends RateLimitStateRepositoryInterface {
|
|
41
|
+
constructor({ prisma } = {}) {
|
|
42
|
+
super();
|
|
43
|
+
this.prisma = prisma ?? require('../../../../database/prisma').prisma;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async _command(command) {
|
|
47
|
+
const result = await this.prisma.$runCommandRaw(command);
|
|
48
|
+
const writeError = result?.writeErrors?.[0];
|
|
49
|
+
if (writeError) {
|
|
50
|
+
throw Object.assign(new Error(writeError.errmsg), {
|
|
51
|
+
code: writeError.code,
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
return result;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
_path(scopeKey, field) {
|
|
58
|
+
return `data.${STATE_FIELD}.${stateMemberName(scopeKey)}.${field}`;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async read({ entityId, scopeKey }) {
|
|
62
|
+
const filter = entityFilter(entityId);
|
|
63
|
+
if (!filter) return null;
|
|
64
|
+
const path = this._path(scopeKey, 'blockedUntil');
|
|
65
|
+
const result = await this._command({
|
|
66
|
+
find: COLLECTION,
|
|
67
|
+
filter,
|
|
68
|
+
projection: { [path]: 1 },
|
|
69
|
+
limit: 1,
|
|
70
|
+
});
|
|
71
|
+
const doc = result?.cursor?.firstBatch?.[0];
|
|
72
|
+
if (!doc) return null;
|
|
73
|
+
const ms = toNumber(
|
|
74
|
+
doc.data?.[STATE_FIELD]?.[stateMemberName(scopeKey)]?.blockedUntil
|
|
75
|
+
);
|
|
76
|
+
return { blockedUntil: ms === null ? null : new Date(ms) };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async block({ entityId, scopeKey }, until) {
|
|
80
|
+
const filter = entityFilter(entityId);
|
|
81
|
+
if (!filter) return;
|
|
82
|
+
const path = this._path(scopeKey, 'blockedUntil');
|
|
83
|
+
const untilMs = until.getTime();
|
|
84
|
+
await this._command({
|
|
85
|
+
update: COLLECTION,
|
|
86
|
+
updates: [
|
|
87
|
+
{
|
|
88
|
+
q: {
|
|
89
|
+
...filter,
|
|
90
|
+
$or: [{ [path]: null }, { [path]: { $lt: untilMs } }],
|
|
91
|
+
},
|
|
92
|
+
u: { $set: { [path]: untilMs } },
|
|
93
|
+
},
|
|
94
|
+
],
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async reserveSlot({ entityId, scopeKey }, { notBefore, intervalMs }) {
|
|
99
|
+
const filter = entityFilter(entityId);
|
|
100
|
+
if (!filter) return null;
|
|
101
|
+
const path = this._path(scopeKey, 'nextSlotMs');
|
|
102
|
+
const step = slotStepMs(intervalMs);
|
|
103
|
+
const notBeforeMs = notBefore.getTime();
|
|
104
|
+
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
|
|
105
|
+
const advanced = await this._command({
|
|
106
|
+
findAndModify: COLLECTION,
|
|
107
|
+
query: { ...filter, [path]: { $gte: notBeforeMs } },
|
|
108
|
+
update: { $inc: { [path]: step } },
|
|
109
|
+
fields: { [path]: 1 },
|
|
110
|
+
new: false,
|
|
111
|
+
});
|
|
112
|
+
const before =
|
|
113
|
+
advanced?.value?.data?.[STATE_FIELD]?.[
|
|
114
|
+
stateMemberName(scopeKey)
|
|
115
|
+
]?.nextSlotMs;
|
|
116
|
+
const slot = toNumber(before);
|
|
117
|
+
if (slot !== null) return new Date(slot);
|
|
118
|
+
|
|
119
|
+
const restarted = await this._command({
|
|
120
|
+
findAndModify: COLLECTION,
|
|
121
|
+
query: {
|
|
122
|
+
...filter,
|
|
123
|
+
$or: [{ [path]: null }, { [path]: { $lt: notBeforeMs } }],
|
|
124
|
+
},
|
|
125
|
+
update: { $set: { [path]: notBeforeMs + step } },
|
|
126
|
+
fields: { _id: 1 },
|
|
127
|
+
new: false,
|
|
128
|
+
});
|
|
129
|
+
if (restarted?.value) return new Date(notBeforeMs);
|
|
130
|
+
|
|
131
|
+
// Neither matched: the entity is gone, or another worker moved
|
|
132
|
+
// the sequence between the two commands.
|
|
133
|
+
if (attempt === MAX_ATTEMPTS) break;
|
|
134
|
+
const exists = await this._command({
|
|
135
|
+
find: COLLECTION,
|
|
136
|
+
filter,
|
|
137
|
+
projection: { _id: 1 },
|
|
138
|
+
limit: 1,
|
|
139
|
+
});
|
|
140
|
+
if (!exists?.cursor?.firstBatch?.length) return null;
|
|
141
|
+
}
|
|
142
|
+
throw new Error(
|
|
143
|
+
`rate-limit slot for ${scopeKey} not reserved after ${MAX_ATTEMPTS} attempts`
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
module.exports = { RateLimitStateRepositoryMongo, toNumber };
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
const {
|
|
2
|
+
RateLimitStateRepositoryInterface,
|
|
3
|
+
STATE_FIELD,
|
|
4
|
+
stateMemberName,
|
|
5
|
+
} = require('./rate-limit-state-repository-interface');
|
|
6
|
+
const { slotStepMs } = require('./rate-limit-state-repository-memory');
|
|
7
|
+
|
|
8
|
+
const toEntityId = (entityId) => {
|
|
9
|
+
const id = Number(entityId);
|
|
10
|
+
return Number.isSafeInteger(id) && id > 0 ? id : undefined;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* PostgreSQL: the state is in the `data` JSONB column of "Entity". Each write
|
|
15
|
+
* is one UPDATE statement. PostgreSQL locks the row and evaluates the SET on
|
|
16
|
+
* the newest row version, so concurrent workers each get their own slot and a
|
|
17
|
+
* block only moves later. The UPDATE writes only `data`; it does not touch
|
|
18
|
+
* `updatedAt`.
|
|
19
|
+
*/
|
|
20
|
+
class RateLimitStateRepositoryPostgres extends RateLimitStateRepositoryInterface {
|
|
21
|
+
constructor({ prisma } = {}) {
|
|
22
|
+
super();
|
|
23
|
+
this.prisma = prisma ?? require('../../../../database/prisma').prisma;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async read({ entityId, scopeKey }) {
|
|
27
|
+
const id = toEntityId(entityId);
|
|
28
|
+
if (id === undefined) return null;
|
|
29
|
+
const member = stateMemberName(scopeKey);
|
|
30
|
+
const rows = await this.prisma.$queryRaw`
|
|
31
|
+
SELECT ("data" -> ${STATE_FIELD}::text -> ${member}::text
|
|
32
|
+
->> 'blockedUntil')::bigint AS "blockedUntil"
|
|
33
|
+
FROM "Entity" WHERE "id" = ${id}`;
|
|
34
|
+
if (rows.length === 0) return null;
|
|
35
|
+
const value = rows[0].blockedUntil;
|
|
36
|
+
return {
|
|
37
|
+
blockedUntil: value === null ? null : new Date(Number(value)),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async block({ entityId, scopeKey }, until) {
|
|
42
|
+
const id = toEntityId(entityId);
|
|
43
|
+
if (id === undefined) return;
|
|
44
|
+
const member = stateMemberName(scopeKey);
|
|
45
|
+
const untilMs = BigInt(until.getTime());
|
|
46
|
+
await this.prisma.$executeRaw`
|
|
47
|
+
UPDATE "Entity" SET "data" =
|
|
48
|
+
COALESCE("data", '{}'::jsonb) || jsonb_build_object(
|
|
49
|
+
${STATE_FIELD}::text,
|
|
50
|
+
COALESCE("data" -> ${STATE_FIELD}::text, '{}'::jsonb)
|
|
51
|
+
|| jsonb_build_object(
|
|
52
|
+
${member}::text,
|
|
53
|
+
COALESCE("data" -> ${STATE_FIELD}::text -> ${member}::text, '{}'::jsonb)
|
|
54
|
+
|| jsonb_build_object('blockedUntil', GREATEST(
|
|
55
|
+
COALESCE(("data" -> ${STATE_FIELD}::text -> ${member}::text
|
|
56
|
+
->> 'blockedUntil')::bigint, 0),
|
|
57
|
+
${untilMs}::bigint
|
|
58
|
+
))
|
|
59
|
+
)
|
|
60
|
+
)
|
|
61
|
+
WHERE "id" = ${id}`;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async reserveSlot({ entityId, scopeKey }, { notBefore, intervalMs }) {
|
|
65
|
+
const id = toEntityId(entityId);
|
|
66
|
+
if (id === undefined) return null;
|
|
67
|
+
const member = stateMemberName(scopeKey);
|
|
68
|
+
const step = BigInt(slotStepMs(intervalMs));
|
|
69
|
+
const notBeforeMs = BigInt(notBefore.getTime());
|
|
70
|
+
const rows = await this.prisma.$queryRaw`
|
|
71
|
+
UPDATE "Entity" SET "data" =
|
|
72
|
+
COALESCE("data", '{}'::jsonb) || jsonb_build_object(
|
|
73
|
+
${STATE_FIELD}::text,
|
|
74
|
+
COALESCE("data" -> ${STATE_FIELD}::text, '{}'::jsonb)
|
|
75
|
+
|| jsonb_build_object(
|
|
76
|
+
${member}::text,
|
|
77
|
+
COALESCE("data" -> ${STATE_FIELD}::text -> ${member}::text, '{}'::jsonb)
|
|
78
|
+
|| jsonb_build_object('nextSlotMs', GREATEST(
|
|
79
|
+
COALESCE(("data" -> ${STATE_FIELD}::text -> ${member}::text
|
|
80
|
+
->> 'nextSlotMs')::bigint, 0),
|
|
81
|
+
${notBeforeMs}::bigint
|
|
82
|
+
) + ${step}::bigint)
|
|
83
|
+
)
|
|
84
|
+
)
|
|
85
|
+
WHERE "id" = ${id}
|
|
86
|
+
RETURNING ("data" -> ${STATE_FIELD}::text -> ${member}::text
|
|
87
|
+
->> 'nextSlotMs')::bigint AS "nextSlotMs"`;
|
|
88
|
+
if (rows.length === 0) return null;
|
|
89
|
+
return new Date(Number(rows[0].nextSlotMs) - Number(step));
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
module.exports = { RateLimitStateRepositoryPostgres };
|