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