@open-mercato/shared 0.10.1-develop.8099.1.debd225eaa → 0.10.1-develop.8111.1.6c779bc21b
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/dist/lib/crud/factory.js +13 -7
- package/dist/lib/crud/factory.js.map +3 -3
- package/dist/lib/query/engine.js +2 -2
- package/dist/lib/query/engine.js.map +2 -2
- package/dist/lib/ratelimit/service.js +5 -4
- package/dist/lib/ratelimit/service.js.map +2 -2
- package/dist/lib/version.js +1 -1
- package/dist/lib/version.js.map +1 -1
- package/package.json +2 -2
- package/src/lib/crud/__tests__/crud-factory.test.ts +79 -0
- package/src/lib/crud/factory.ts +11 -5
- package/src/lib/query/__tests__/resolve-registered-entity-table.test.ts +19 -1
- package/src/lib/query/engine.ts +2 -2
- package/src/lib/ratelimit/__tests__/service.test.ts +111 -0
- package/src/lib/ratelimit/service.ts +6 -4
- package/src/lib/ratelimit/types.ts +7 -0
|
@@ -8,6 +8,7 @@ class RateLimiterService {
|
|
|
8
8
|
this.redisClient = null;
|
|
9
9
|
this.globalConfig = globalConfig;
|
|
10
10
|
this.trustProxyDepth = globalConfig.trustProxyDepth ?? 0;
|
|
11
|
+
this.sharedEnabled = globalConfig.enabled && globalConfig.strategy === "redis" && !!globalConfig.redisUrl;
|
|
11
12
|
}
|
|
12
13
|
async initialize() {
|
|
13
14
|
if (this.globalConfig.strategy === "redis" && this.globalConfig.redisUrl) {
|
|
@@ -20,6 +21,7 @@ class RateLimiterService {
|
|
|
20
21
|
}
|
|
21
22
|
}
|
|
22
23
|
async consume(key, config) {
|
|
24
|
+
if (config.requireShared && (!this.sharedEnabled || !this.redisClient)) return this.degradedResult(config);
|
|
23
25
|
if (!this.globalConfig.enabled) {
|
|
24
26
|
return this.disabledResult(config);
|
|
25
27
|
}
|
|
@@ -84,7 +86,7 @@ class RateLimiterService {
|
|
|
84
86
|
return { ...this.disabledResult(config), degraded: true };
|
|
85
87
|
}
|
|
86
88
|
getOrCreateLimiter(config) {
|
|
87
|
-
const cacheKey = `${config.keyPrefix ?? "default"}:${config.points}:${config.duration}:${config.blockDuration ?? 0}`;
|
|
89
|
+
const cacheKey = `${config.keyPrefix ?? "default"}:${config.points}:${config.duration}:${config.blockDuration ?? 0}:${!!config.requireShared}`;
|
|
88
90
|
let limiter = this.limiters.get(cacheKey);
|
|
89
91
|
if (limiter) return limiter;
|
|
90
92
|
const prefix = [this.globalConfig.keyPrefix, config.keyPrefix].filter(Boolean).join(":");
|
|
@@ -95,12 +97,11 @@ class RateLimiterService {
|
|
|
95
97
|
blockDuration: config.blockDuration ?? 0
|
|
96
98
|
};
|
|
97
99
|
if (this.globalConfig.strategy === "redis" && this.redisClient) {
|
|
98
|
-
const insuranceLimiter = new RateLimiterMemory(baseOpts);
|
|
99
100
|
limiter = new RateLimiterRedis({
|
|
100
101
|
...baseOpts,
|
|
101
102
|
storeClient: this.redisClient,
|
|
102
|
-
insuranceLimiter,
|
|
103
|
-
rejectIfRedisNotReady:
|
|
103
|
+
...config.requireShared ? {} : { insuranceLimiter: new RateLimiterMemory(baseOpts) },
|
|
104
|
+
rejectIfRedisNotReady: !!config.requireShared
|
|
104
105
|
});
|
|
105
106
|
} else {
|
|
106
107
|
limiter = new RateLimiterMemory(baseOpts);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/lib/ratelimit/service.ts"],
|
|
4
|
-
"sourcesContent": ["import { RateLimiterMemory, RateLimiterRedis, RateLimiterRes } from 'rate-limiter-flexible'\nimport { createLogger } from '../logger'\nimport { parseRedisUrl } from '../redis/connection'\nimport type { RateLimitConfig, RateLimitResult, RateLimitGlobalConfig } from './types'\n\nconst logger = createLogger('ratelimit')\n\n/** Narrow interface for the ioredis client \u2014 only the methods we actually use. */\ninterface RedisClient {\n disconnect(): void\n}\n\nexport class RateLimiterService {\n private globalConfig: RateLimitGlobalConfig\n private limiters = new Map<string, RateLimiterMemory | RateLimiterRedis>()\n private redisClient: RedisClient | null = null\n\n readonly trustProxyDepth: number\n\n constructor(globalConfig: RateLimitGlobalConfig) {\n this.globalConfig = globalConfig\n this.trustProxyDepth = globalConfig.trustProxyDepth ?? 0\n }\n\n async initialize(): Promise<void> {\n if (this.globalConfig.strategy === 'redis' && this.globalConfig.redisUrl) {\n const { default: Redis } = await import('ioredis')\n this.redisClient = new Redis({\n ...parseRedisUrl(this.globalConfig.redisUrl),\n enableOfflineQueue: false,\n maxRetriesPerRequest: 1,\n })\n }\n }\n\n async consume(key: string, config: RateLimitConfig): Promise<RateLimitResult> {\n if (!this.globalConfig.enabled) {\n return this.disabledResult(config)\n }\n\n const limiter = this.getOrCreateLimiter(config)\n\n try {\n const res = await limiter.consume(key, 1)\n return this.toResult(res, true)\n } catch (error) {\n if (error instanceof RateLimiterRes) {\n return this.toResult(error, false)\n }\n logger.error('Rate limiter unavailable, request was not counted', {\n err: error,\n keyPrefix: config.keyPrefix,\n strategy: this.globalConfig.strategy,\n })\n return this.degradedResult(config)\n }\n }\n\n async get(key: string, config: RateLimitConfig): Promise<RateLimitResult | null> {\n if (!this.globalConfig.enabled) return null\n\n const limiter = this.getOrCreateLimiter(config)\n const res = await limiter.get(key)\n return res ? this.toResult(res, res.remainingPoints > 0) : null\n }\n\n async delete(key: string, config: RateLimitConfig): Promise<void> {\n if (!this.globalConfig.enabled) return\n const limiter = this.getOrCreateLimiter(config)\n await limiter.delete(key)\n }\n\n async penalty(key: string, points: number, config: RateLimitConfig): Promise<RateLimitResult> {\n if (!this.globalConfig.enabled) {\n return this.disabledResult(config)\n }\n const limiter = this.getOrCreateLimiter(config)\n const res = await limiter.penalty(key, points)\n return this.toResult(res, res.remainingPoints > 0)\n }\n\n async reward(key: string, points: number, config: RateLimitConfig): Promise<RateLimitResult> {\n if (!this.globalConfig.enabled) {\n return this.disabledResult(config)\n }\n const limiter = this.getOrCreateLimiter(config)\n const res = await limiter.reward(key, points)\n return this.toResult(res, true)\n }\n\n async block(key: string, durationSec: number, config: RateLimitConfig): Promise<void> {\n if (!this.globalConfig.enabled) return\n const limiter = this.getOrCreateLimiter(config)\n await limiter.block(key, durationSec)\n }\n\n async destroy(): Promise<void> {\n if (this.redisClient) {\n this.redisClient.disconnect()\n }\n this.limiters.clear()\n }\n\n private disabledResult(config: RateLimitConfig): RateLimitResult {\n return { allowed: true, remainingPoints: config.points, msBeforeNext: 0, consumedPoints: 0 }\n }\n\n private degradedResult(config: RateLimitConfig): RateLimitResult {\n return { ...this.disabledResult(config), degraded: true }\n }\n\n private getOrCreateLimiter(config: RateLimitConfig): RateLimiterMemory | RateLimiterRedis {\n const cacheKey = `${config.keyPrefix ?? 'default'}:${config.points}:${config.duration}:${config.blockDuration ?? 0}`\n\n let limiter = this.limiters.get(cacheKey)\n if (limiter) return limiter\n\n const prefix = [this.globalConfig.keyPrefix, config.keyPrefix].filter(Boolean).join(':')\n\n const baseOpts = {\n keyPrefix: prefix,\n points: config.points,\n duration: config.duration,\n blockDuration: config.blockDuration ?? 0,\n }\n\n if (this.globalConfig.strategy === 'redis' && this.redisClient) {\n
|
|
5
|
-
"mappings": "AAAA,SAAS,mBAAmB,kBAAkB,sBAAsB;AACpE,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAG9B,MAAM,SAAS,aAAa,WAAW;AAOhC,MAAM,mBAAmB;AAAA,
|
|
4
|
+
"sourcesContent": ["import { RateLimiterMemory, RateLimiterRedis, RateLimiterRes } from 'rate-limiter-flexible'\nimport { createLogger } from '../logger'\nimport { parseRedisUrl } from '../redis/connection'\nimport type { RateLimitConfig, RateLimitResult, RateLimitGlobalConfig } from './types'\n\nconst logger = createLogger('ratelimit')\n\n/** Narrow interface for the ioredis client \u2014 only the methods we actually use. */\ninterface RedisClient {\n disconnect(): void\n}\n\nexport class RateLimiterService {\n private globalConfig: RateLimitGlobalConfig\n private limiters = new Map<string, RateLimiterMemory | RateLimiterRedis>()\n private redisClient: RedisClient | null = null\n\n readonly trustProxyDepth: number\n readonly sharedEnabled: boolean\n\n constructor(globalConfig: RateLimitGlobalConfig) {\n this.globalConfig = globalConfig\n this.trustProxyDepth = globalConfig.trustProxyDepth ?? 0\n this.sharedEnabled = globalConfig.enabled && globalConfig.strategy === 'redis' && !!globalConfig.redisUrl\n }\n\n async initialize(): Promise<void> {\n if (this.globalConfig.strategy === 'redis' && this.globalConfig.redisUrl) {\n const { default: Redis } = await import('ioredis')\n this.redisClient = new Redis({\n ...parseRedisUrl(this.globalConfig.redisUrl),\n enableOfflineQueue: false,\n maxRetriesPerRequest: 1,\n })\n }\n }\n\n async consume(key: string, config: RateLimitConfig): Promise<RateLimitResult> {\n if (config.requireShared && (!this.sharedEnabled || !this.redisClient)) return this.degradedResult(config)\n if (!this.globalConfig.enabled) {\n return this.disabledResult(config)\n }\n\n const limiter = this.getOrCreateLimiter(config)\n\n try {\n const res = await limiter.consume(key, 1)\n return this.toResult(res, true)\n } catch (error) {\n if (error instanceof RateLimiterRes) {\n return this.toResult(error, false)\n }\n logger.error('Rate limiter unavailable, request was not counted', {\n err: error,\n keyPrefix: config.keyPrefix,\n strategy: this.globalConfig.strategy,\n })\n return this.degradedResult(config)\n }\n }\n\n async get(key: string, config: RateLimitConfig): Promise<RateLimitResult | null> {\n if (!this.globalConfig.enabled) return null\n\n const limiter = this.getOrCreateLimiter(config)\n const res = await limiter.get(key)\n return res ? this.toResult(res, res.remainingPoints > 0) : null\n }\n\n async delete(key: string, config: RateLimitConfig): Promise<void> {\n if (!this.globalConfig.enabled) return\n const limiter = this.getOrCreateLimiter(config)\n await limiter.delete(key)\n }\n\n async penalty(key: string, points: number, config: RateLimitConfig): Promise<RateLimitResult> {\n if (!this.globalConfig.enabled) {\n return this.disabledResult(config)\n }\n const limiter = this.getOrCreateLimiter(config)\n const res = await limiter.penalty(key, points)\n return this.toResult(res, res.remainingPoints > 0)\n }\n\n async reward(key: string, points: number, config: RateLimitConfig): Promise<RateLimitResult> {\n if (!this.globalConfig.enabled) {\n return this.disabledResult(config)\n }\n const limiter = this.getOrCreateLimiter(config)\n const res = await limiter.reward(key, points)\n return this.toResult(res, true)\n }\n\n async block(key: string, durationSec: number, config: RateLimitConfig): Promise<void> {\n if (!this.globalConfig.enabled) return\n const limiter = this.getOrCreateLimiter(config)\n await limiter.block(key, durationSec)\n }\n\n async destroy(): Promise<void> {\n if (this.redisClient) {\n this.redisClient.disconnect()\n }\n this.limiters.clear()\n }\n\n private disabledResult(config: RateLimitConfig): RateLimitResult {\n return { allowed: true, remainingPoints: config.points, msBeforeNext: 0, consumedPoints: 0 }\n }\n\n private degradedResult(config: RateLimitConfig): RateLimitResult {\n return { ...this.disabledResult(config), degraded: true }\n }\n\n private getOrCreateLimiter(config: RateLimitConfig): RateLimiterMemory | RateLimiterRedis {\n const cacheKey = `${config.keyPrefix ?? 'default'}:${config.points}:${config.duration}:${config.blockDuration ?? 0}:${!!config.requireShared}`\n\n let limiter = this.limiters.get(cacheKey)\n if (limiter) return limiter\n\n const prefix = [this.globalConfig.keyPrefix, config.keyPrefix].filter(Boolean).join(':')\n\n const baseOpts = {\n keyPrefix: prefix,\n points: config.points,\n duration: config.duration,\n blockDuration: config.blockDuration ?? 0,\n }\n\n if (this.globalConfig.strategy === 'redis' && this.redisClient) {\n limiter = new RateLimiterRedis({\n ...baseOpts,\n storeClient: this.redisClient,\n ...(config.requireShared ? {} : { insuranceLimiter: new RateLimiterMemory(baseOpts) }),\n rejectIfRedisNotReady: !!config.requireShared,\n })\n } else {\n limiter = new RateLimiterMemory(baseOpts)\n }\n\n this.limiters.set(cacheKey, limiter)\n return limiter\n }\n\n private toResult(res: RateLimiterRes, allowed: boolean): RateLimitResult {\n return {\n allowed,\n remainingPoints: Math.max(res.remainingPoints, 0),\n msBeforeNext: res.msBeforeNext,\n consumedPoints: res.consumedPoints,\n }\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,mBAAmB,kBAAkB,sBAAsB;AACpE,SAAS,oBAAoB;AAC7B,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
|
package/dist/lib/version.js
CHANGED
package/dist/lib/version.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/lib/version.ts"],
|
|
4
|
-
"sourcesContent": ["// Build-time generated version\nexport const APP_VERSION = '0.10.1-develop.
|
|
4
|
+
"sourcesContent": ["// Build-time generated version\nexport const APP_VERSION = '0.10.1-develop.8111.1.6c779bc21b';\nexport const appVersion = APP_VERSION;\n"],
|
|
5
5
|
"mappings": "AACO,MAAM,cAAc;AACpB,MAAM,aAAa;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/shared",
|
|
3
|
-
"version": "0.10.1-develop.
|
|
3
|
+
"version": "0.10.1-develop.8111.1.6c779bc21b",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -130,7 +130,7 @@
|
|
|
130
130
|
"@mikro-orm/core": "^7.1.14",
|
|
131
131
|
"@mikro-orm/decorators": "^7.1.14",
|
|
132
132
|
"@mikro-orm/postgresql": "^7.1.14",
|
|
133
|
-
"@open-mercato/cache": "0.10.1-develop.
|
|
133
|
+
"@open-mercato/cache": "0.10.1-develop.8111.1.6c779bc21b",
|
|
134
134
|
"@types/html-to-text": "^9.0.4",
|
|
135
135
|
"@types/sanitize-html": "^2.16.1",
|
|
136
136
|
"dotenv": "^17.4.2",
|
|
@@ -1810,6 +1810,85 @@ describe('CRUD Factory', () => {
|
|
|
1810
1810
|
})
|
|
1811
1811
|
})
|
|
1812
1812
|
|
|
1813
|
+
describe('generic error bodies follow the request locale', () => {
|
|
1814
|
+
const germanErrors: Record<string, string> = {
|
|
1815
|
+
'errors.invalid_input': 'Ungültige Eingabe',
|
|
1816
|
+
'api.errors.databaseUnavailable': 'Dienst vorübergehend nicht verfügbar',
|
|
1817
|
+
'api.errors.foreignKeyViolation': 'Der Datensatz wird noch von anderen Daten referenziert oder verweist auf einen nicht vorhandenen Datensatz',
|
|
1818
|
+
'api.errors.internal': 'Interner Serverfehler',
|
|
1819
|
+
'api.errors.internalMessage': 'Etwas ist schiefgelaufen. Bitte versuchen Sie es später erneut.',
|
|
1820
|
+
}
|
|
1821
|
+
|
|
1822
|
+
beforeEach(() => {
|
|
1823
|
+
mockTranslate.mockImplementation((key: string, fallback?: string) => germanErrors[key] ?? fallback ?? key)
|
|
1824
|
+
})
|
|
1825
|
+
|
|
1826
|
+
afterEach(() => {
|
|
1827
|
+
mockTranslate.mockImplementation((key: string, fallback?: string) => fallback ?? key)
|
|
1828
|
+
})
|
|
1829
|
+
|
|
1830
|
+
it('translates the 400 validation error', async () => {
|
|
1831
|
+
const res = await interceptorErrorRoute().POST(new Request('http://x/api/example/todos/command', {
|
|
1832
|
+
method: 'POST',
|
|
1833
|
+
body: JSON.stringify({ title: '' }),
|
|
1834
|
+
headers: { 'content-type': 'application/json' },
|
|
1835
|
+
}))
|
|
1836
|
+
|
|
1837
|
+
expect(res.status).toBe(400)
|
|
1838
|
+
const body = await res.json()
|
|
1839
|
+
expect(body.error).toBe('Ungültige Eingabe')
|
|
1840
|
+
expect(Array.isArray(body.details)).toBe(true)
|
|
1841
|
+
expect(mockTranslate).toHaveBeenCalledWith('errors.invalid_input', 'Invalid input')
|
|
1842
|
+
})
|
|
1843
|
+
|
|
1844
|
+
it('translates the 503 transient database error', async () => {
|
|
1845
|
+
commandBus.execute.mockRejectedValue(Object.assign(new Error('sorry, too many clients already'), { code: '53300' }))
|
|
1846
|
+
|
|
1847
|
+
const res = await postInterceptorErrorRequest(interceptorErrorRoute())
|
|
1848
|
+
|
|
1849
|
+
expect(res.status).toBe(503)
|
|
1850
|
+
await expect(res.json()).resolves.toEqual({
|
|
1851
|
+
error: 'Dienst vorübergehend nicht verfügbar',
|
|
1852
|
+
code: 'DATABASE_UNAVAILABLE',
|
|
1853
|
+
requestId: expect.any(String),
|
|
1854
|
+
})
|
|
1855
|
+
expect(mockTranslate).toHaveBeenCalledWith('api.errors.databaseUnavailable', 'Service temporarily unavailable')
|
|
1856
|
+
})
|
|
1857
|
+
|
|
1858
|
+
it('translates the 409 foreign key violation', async () => {
|
|
1859
|
+
commandBus.execute.mockRejectedValue(Object.assign(new Error('violates foreign key constraint'), { code: '23503' }))
|
|
1860
|
+
|
|
1861
|
+
const res = await postInterceptorErrorRequest(interceptorErrorRoute())
|
|
1862
|
+
|
|
1863
|
+
expect(res.status).toBe(409)
|
|
1864
|
+
await expect(res.json()).resolves.toEqual({
|
|
1865
|
+
error: 'Der Datensatz wird noch von anderen Daten referenziert oder verweist auf einen nicht vorhandenen Datensatz',
|
|
1866
|
+
code: 'FOREIGN_KEY_VIOLATION',
|
|
1867
|
+
requestId: expect.any(String),
|
|
1868
|
+
})
|
|
1869
|
+
expect(mockTranslate).toHaveBeenCalledWith(
|
|
1870
|
+
'api.errors.foreignKeyViolation',
|
|
1871
|
+
'The record is still referenced by other data, or references a record that does not exist',
|
|
1872
|
+
)
|
|
1873
|
+
})
|
|
1874
|
+
|
|
1875
|
+
it('translates the generic 500 error and message', async () => {
|
|
1876
|
+
commandBus.execute.mockRejectedValue(new Error('boom'))
|
|
1877
|
+
|
|
1878
|
+
const res = await postInterceptorErrorRequest(interceptorErrorRoute())
|
|
1879
|
+
|
|
1880
|
+
expect(res.status).toBe(500)
|
|
1881
|
+
await expect(res.json()).resolves.toEqual({
|
|
1882
|
+
error: 'Interner Serverfehler',
|
|
1883
|
+
message: 'Etwas ist schiefgelaufen. Bitte versuchen Sie es später erneut.',
|
|
1884
|
+
requestId: expect.any(String),
|
|
1885
|
+
code: 'INTERNAL_ERROR',
|
|
1886
|
+
})
|
|
1887
|
+
expect(mockTranslate).toHaveBeenCalledWith('api.errors.internal', 'Internal server error')
|
|
1888
|
+
expect(mockTranslate).toHaveBeenCalledWith('api.errors.internalMessage', 'Something went wrong. Please try again later.')
|
|
1889
|
+
})
|
|
1890
|
+
})
|
|
1891
|
+
|
|
1813
1892
|
// Issue #5608 — a generic 500 must carry a requestId the client/support can cite, and
|
|
1814
1893
|
// that same id must appear on the server log line so the two can be correlated.
|
|
1815
1894
|
describe('generic 500 requestId correlation', () => {
|
package/src/lib/crud/factory.ts
CHANGED
|
@@ -659,7 +659,10 @@ async function handleError(err: unknown, request?: Request): Promise<Response> {
|
|
|
659
659
|
if (interceptorRejection) {
|
|
660
660
|
return json(interceptorRejection.body, { status: interceptorRejection.status })
|
|
661
661
|
}
|
|
662
|
-
|
|
662
|
+
const { translate } = await resolveTranslations()
|
|
663
|
+
if (err instanceof z.ZodError) {
|
|
664
|
+
return json({ error: translate('errors.invalid_input', 'Invalid input'), details: err.issues }, { status: 400 })
|
|
665
|
+
}
|
|
663
666
|
if (isTransientDbError(err)) {
|
|
664
667
|
// Transient DB unavailability (pool exhausted, `max_connections` reached, DB
|
|
665
668
|
// restarting) is retryable — surface a 503 with a Retry-After hint instead of
|
|
@@ -671,7 +674,7 @@ async function handleError(err: unknown, request?: Request): Promise<Response> {
|
|
|
671
674
|
requestId,
|
|
672
675
|
})
|
|
673
676
|
return json(
|
|
674
|
-
{ error: 'Service temporarily unavailable', code: 'DATABASE_UNAVAILABLE', requestId },
|
|
677
|
+
{ error: translate('api.errors.databaseUnavailable', 'Service temporarily unavailable'), code: 'DATABASE_UNAVAILABLE', requestId },
|
|
675
678
|
{ status: 503, headers: { 'Retry-After': '2', 'x-request-id': requestId } },
|
|
676
679
|
)
|
|
677
680
|
}
|
|
@@ -697,7 +700,10 @@ async function handleError(err: unknown, request?: Request): Promise<Response> {
|
|
|
697
700
|
})
|
|
698
701
|
return json(
|
|
699
702
|
{
|
|
700
|
-
error:
|
|
703
|
+
error: translate(
|
|
704
|
+
'api.errors.foreignKeyViolation',
|
|
705
|
+
'The record is still referenced by other data, or references a record that does not exist',
|
|
706
|
+
),
|
|
701
707
|
code: 'FOREIGN_KEY_VIOLATION',
|
|
702
708
|
requestId,
|
|
703
709
|
},
|
|
@@ -721,8 +727,8 @@ async function handleError(err: unknown, request?: Request): Promise<Response> {
|
|
|
721
727
|
attributes: { requestId, errorName, code, pgCode: pgSqlState ?? undefined },
|
|
722
728
|
})
|
|
723
729
|
const body: Record<string, unknown> = {
|
|
724
|
-
error: 'Internal server error',
|
|
725
|
-
message: 'Something went wrong. Please try again later.',
|
|
730
|
+
error: translate('api.errors.internal', 'Internal server error'),
|
|
731
|
+
message: translate('api.errors.internalMessage', 'Something went wrong. Please try again later.'),
|
|
726
732
|
requestId,
|
|
727
733
|
code,
|
|
728
734
|
}
|
|
@@ -5,8 +5,13 @@ import {
|
|
|
5
5
|
ENTITY_ID_PATTERN,
|
|
6
6
|
} from '../engine'
|
|
7
7
|
|
|
8
|
+
// MikroORM v7's real MetadataStorage.getAll() returns a Map, not an array (#6725,
|
|
9
|
+
// same getAll()-returns-a-Map class of bug as #5579). A plain-array double here
|
|
10
|
+
// would let the secondary lookup's broken `for...of` iteration pass trivially.
|
|
8
11
|
function makeEm(metaByClass: Record<string, string>) {
|
|
9
|
-
const all =
|
|
12
|
+
const all = new Map(
|
|
13
|
+
Object.entries(metaByClass).map(([className, tableName]) => [className, { className, tableName }]),
|
|
14
|
+
)
|
|
10
15
|
return {
|
|
11
16
|
getMetadata: () => ({
|
|
12
17
|
find: (className: string) => {
|
|
@@ -45,6 +50,19 @@ describe('resolveRegisteredEntityTableName', () => {
|
|
|
45
50
|
expect(resolveRegisteredEntityTableName(em, 'foo:auth_user')).toBeNull()
|
|
46
51
|
expect(resolveRegisteredEntityTableName(em, 'foo:user')).toBeNull()
|
|
47
52
|
})
|
|
53
|
+
|
|
54
|
+
it('the secondary lookup actually scans metadata on a real MikroORM 7 MetadataStorage (#6725)', () => {
|
|
55
|
+
// getMetadata().getAll() returns a Map keyed by class, not an array, so a
|
|
56
|
+
// registered entity whose class name does not match any PascalCase candidate
|
|
57
|
+
// (step 1 misses) must still be found by the table-name scan (step 2).
|
|
58
|
+
const em = makeEm({ SomeUnrelatedClassName: 'directory_organizations' })
|
|
59
|
+
expect(resolveRegisteredEntityTableName(em, 'directory:organization')).toBe('directory_organizations')
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
it('the secondary lookup does not match an unregistered id to an unrelated table', () => {
|
|
63
|
+
const em = makeEm({ Invoice: 'sales_invoices' })
|
|
64
|
+
expect(resolveRegisteredEntityTableName(em, 'clinic:patient')).toBeNull()
|
|
65
|
+
})
|
|
48
66
|
})
|
|
49
67
|
|
|
50
68
|
describe('resolveEntityTableName fallback (broad query path)', () => {
|
package/src/lib/query/engine.ts
CHANGED
|
@@ -51,6 +51,7 @@ import {
|
|
|
51
51
|
} from '../encryption/decryptScope'
|
|
52
52
|
import { parseNumberWithDefault } from '../number'
|
|
53
53
|
import { createLogger } from '../logger'
|
|
54
|
+
import { listEntityMetadataFromRegistry } from '../db/entityMetadata'
|
|
54
55
|
import {
|
|
55
56
|
buildArrayColumnNoOverlapPredicate,
|
|
56
57
|
buildArrayColumnOverlapPredicate,
|
|
@@ -259,8 +260,7 @@ export function resolveRegisteredEntityTableName(
|
|
|
259
260
|
`${modulePrefix}_${pluralizeBaseName(rawName)}`,
|
|
260
261
|
]
|
|
261
262
|
try {
|
|
262
|
-
const
|
|
263
|
-
for (const meta of allMeta) {
|
|
263
|
+
for (const meta of listEntityMetadataFromRegistry(metadata)) {
|
|
264
264
|
if (meta?.tableName && candidateTables.includes(String(meta.tableName))) {
|
|
265
265
|
return String(meta.tableName)
|
|
266
266
|
}
|
|
@@ -261,6 +261,117 @@ describe('RateLimiterService', () => {
|
|
|
261
261
|
})
|
|
262
262
|
})
|
|
263
263
|
|
|
264
|
+
describe('requireShared', () => {
|
|
265
|
+
const sharedLimitConfig: RateLimitConfig = { ...defaultLimitConfig, requireShared: true }
|
|
266
|
+
|
|
267
|
+
beforeEach(() => {
|
|
268
|
+
jest.spyOn(console, 'error').mockImplementation(() => {})
|
|
269
|
+
})
|
|
270
|
+
|
|
271
|
+
afterEach(() => {
|
|
272
|
+
jest.restoreAllMocks()
|
|
273
|
+
})
|
|
274
|
+
|
|
275
|
+
it('returns a degraded result instead of counting in memory when the shared store is not configured', async () => {
|
|
276
|
+
const memoryConsume = jest.spyOn(RateLimiterMemory.prototype, 'consume')
|
|
277
|
+
service = new RateLimiterService(createConfig())
|
|
278
|
+
|
|
279
|
+
const result = await service.consume('key1', sharedLimitConfig)
|
|
280
|
+
|
|
281
|
+
expect(service.sharedEnabled).toBe(false)
|
|
282
|
+
expect(result.degraded).toBe(true)
|
|
283
|
+
expect(memoryConsume).not.toHaveBeenCalled()
|
|
284
|
+
})
|
|
285
|
+
|
|
286
|
+
it('keeps the in-memory behaviour when the flag is not set', async () => {
|
|
287
|
+
service = new RateLimiterService(createConfig())
|
|
288
|
+
|
|
289
|
+
const result = await service.consume('key2', defaultLimitConfig)
|
|
290
|
+
|
|
291
|
+
expect(result.allowed).toBe(true)
|
|
292
|
+
expect(result.degraded).toBeFalsy()
|
|
293
|
+
expect(result.consumedPoints).toBe(1)
|
|
294
|
+
})
|
|
295
|
+
|
|
296
|
+
it('does not share a cached limiter between flagged and unflagged configs', async () => {
|
|
297
|
+
service = new RateLimiterService(createConfig())
|
|
298
|
+
const internals = service as unknown as {
|
|
299
|
+
getOrCreateLimiter: (config: RateLimitConfig) => unknown
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
expect(internals.getOrCreateLimiter(sharedLimitConfig))
|
|
303
|
+
.not.toBe(internals.getOrCreateLimiter(defaultLimitConfig))
|
|
304
|
+
})
|
|
305
|
+
|
|
306
|
+
// The redis branch is where the flag matters. The mocked ioredis client cannot run any
|
|
307
|
+
// command, which stands in for a Redis outage.
|
|
308
|
+
describe('redis strategy', () => {
|
|
309
|
+
async function createRedisService(): Promise<RateLimiterService> {
|
|
310
|
+
const redisService = new RateLimiterService(createConfig({
|
|
311
|
+
strategy: 'redis',
|
|
312
|
+
redisUrl: 'redis://localhost:6379',
|
|
313
|
+
}))
|
|
314
|
+
await redisService.initialize()
|
|
315
|
+
return redisService
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function buildLimiter(redisService: RateLimiterService, config: RateLimitConfig): unknown {
|
|
319
|
+
const internals = redisService as unknown as {
|
|
320
|
+
getOrCreateLimiter: (config: RateLimitConfig) => unknown
|
|
321
|
+
}
|
|
322
|
+
return internals.getOrCreateLimiter(config)
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
it('builds a flagged limiter without the in-memory insurance limiter and rejecting when redis is not ready', async () => {
|
|
326
|
+
service = await createRedisService()
|
|
327
|
+
|
|
328
|
+
const flagged = buildLimiter(service, sharedLimitConfig) as {
|
|
329
|
+
insuranceLimiter?: unknown
|
|
330
|
+
_rejectIfRedisNotReady?: boolean
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
expect(service.sharedEnabled).toBe(true)
|
|
334
|
+
expect(flagged).toBeInstanceOf(RateLimiterRedis)
|
|
335
|
+
expect(flagged.insuranceLimiter).toBeUndefined()
|
|
336
|
+
expect(flagged._rejectIfRedisNotReady).toBe(true)
|
|
337
|
+
})
|
|
338
|
+
|
|
339
|
+
it('keeps the in-memory insurance limiter for an unflagged limiter', async () => {
|
|
340
|
+
service = await createRedisService()
|
|
341
|
+
|
|
342
|
+
const unflagged = buildLimiter(service, defaultLimitConfig) as {
|
|
343
|
+
insuranceLimiter?: unknown
|
|
344
|
+
_rejectIfRedisNotReady?: boolean
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
expect(unflagged).toBeInstanceOf(RateLimiterRedis)
|
|
348
|
+
expect(unflagged.insuranceLimiter).toBeInstanceOf(RateLimiterMemory)
|
|
349
|
+
expect(unflagged._rejectIfRedisNotReady).toBe(false)
|
|
350
|
+
})
|
|
351
|
+
|
|
352
|
+
it('returns a degraded result and never counts in memory when redis fails and the limiter is flagged', async () => {
|
|
353
|
+
service = await createRedisService()
|
|
354
|
+
const memoryConsume = jest.spyOn(RateLimiterMemory.prototype, 'consume')
|
|
355
|
+
|
|
356
|
+
const result = await service.consume('redis-key', sharedLimitConfig)
|
|
357
|
+
|
|
358
|
+
expect(result.degraded).toBe(true)
|
|
359
|
+
expect(memoryConsume).not.toHaveBeenCalled()
|
|
360
|
+
})
|
|
361
|
+
|
|
362
|
+
it('still falls back to the in-memory insurance limiter when redis fails and the limiter is not flagged', async () => {
|
|
363
|
+
service = await createRedisService()
|
|
364
|
+
const memoryConsume = jest.spyOn(RateLimiterMemory.prototype, 'consume')
|
|
365
|
+
|
|
366
|
+
const result = await service.consume('redis-key', defaultLimitConfig)
|
|
367
|
+
|
|
368
|
+
expect(result.degraded).toBeFalsy()
|
|
369
|
+
expect(result.consumedPoints).toBe(1)
|
|
370
|
+
expect(memoryConsume).toHaveBeenCalledTimes(1)
|
|
371
|
+
})
|
|
372
|
+
})
|
|
373
|
+
})
|
|
374
|
+
|
|
264
375
|
describe('limiter caching', () => {
|
|
265
376
|
it('reuses the same limiter for the same config', async () => {
|
|
266
377
|
service = new RateLimiterService(createConfig())
|
|
@@ -16,10 +16,12 @@ export class RateLimiterService {
|
|
|
16
16
|
private redisClient: RedisClient | null = null
|
|
17
17
|
|
|
18
18
|
readonly trustProxyDepth: number
|
|
19
|
+
readonly sharedEnabled: boolean
|
|
19
20
|
|
|
20
21
|
constructor(globalConfig: RateLimitGlobalConfig) {
|
|
21
22
|
this.globalConfig = globalConfig
|
|
22
23
|
this.trustProxyDepth = globalConfig.trustProxyDepth ?? 0
|
|
24
|
+
this.sharedEnabled = globalConfig.enabled && globalConfig.strategy === 'redis' && !!globalConfig.redisUrl
|
|
23
25
|
}
|
|
24
26
|
|
|
25
27
|
async initialize(): Promise<void> {
|
|
@@ -34,6 +36,7 @@ export class RateLimiterService {
|
|
|
34
36
|
}
|
|
35
37
|
|
|
36
38
|
async consume(key: string, config: RateLimitConfig): Promise<RateLimitResult> {
|
|
39
|
+
if (config.requireShared && (!this.sharedEnabled || !this.redisClient)) return this.degradedResult(config)
|
|
37
40
|
if (!this.globalConfig.enabled) {
|
|
38
41
|
return this.disabledResult(config)
|
|
39
42
|
}
|
|
@@ -110,7 +113,7 @@ export class RateLimiterService {
|
|
|
110
113
|
}
|
|
111
114
|
|
|
112
115
|
private getOrCreateLimiter(config: RateLimitConfig): RateLimiterMemory | RateLimiterRedis {
|
|
113
|
-
const cacheKey = `${config.keyPrefix ?? 'default'}:${config.points}:${config.duration}:${config.blockDuration ?? 0}`
|
|
116
|
+
const cacheKey = `${config.keyPrefix ?? 'default'}:${config.points}:${config.duration}:${config.blockDuration ?? 0}:${!!config.requireShared}`
|
|
114
117
|
|
|
115
118
|
let limiter = this.limiters.get(cacheKey)
|
|
116
119
|
if (limiter) return limiter
|
|
@@ -125,12 +128,11 @@ export class RateLimiterService {
|
|
|
125
128
|
}
|
|
126
129
|
|
|
127
130
|
if (this.globalConfig.strategy === 'redis' && this.redisClient) {
|
|
128
|
-
const insuranceLimiter = new RateLimiterMemory(baseOpts)
|
|
129
131
|
limiter = new RateLimiterRedis({
|
|
130
132
|
...baseOpts,
|
|
131
133
|
storeClient: this.redisClient,
|
|
132
|
-
insuranceLimiter,
|
|
133
|
-
rejectIfRedisNotReady:
|
|
134
|
+
...(config.requireShared ? {} : { insuranceLimiter: new RateLimiterMemory(baseOpts) }),
|
|
135
|
+
rejectIfRedisNotReady: !!config.requireShared,
|
|
134
136
|
})
|
|
135
137
|
} else {
|
|
136
138
|
limiter = new RateLimiterMemory(baseOpts)
|
|
@@ -7,6 +7,13 @@ export interface RateLimitConfig {
|
|
|
7
7
|
blockDuration?: number
|
|
8
8
|
/** Key prefix for this specific limiter (appended to global prefix) */
|
|
9
9
|
keyPrefix?: string
|
|
10
|
+
/**
|
|
11
|
+
* Require the shared (redis) store for this limiter. When set, the limiter never
|
|
12
|
+
* falls back to per-process memory: if the shared store is not configured or not
|
|
13
|
+
* ready, `consume()` returns a `degraded` result so the caller can fail closed.
|
|
14
|
+
* Default: false (in-memory insurance fallback, unchanged behaviour).
|
|
15
|
+
*/
|
|
16
|
+
requireShared?: boolean
|
|
10
17
|
}
|
|
11
18
|
|
|
12
19
|
export interface RateLimitResult {
|