@open-mercato/shared 0.10.1-develop.8182.1.0acd6a564c → 0.10.1-develop.8191.1.2563ac3bfc
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/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.8191.1.2563ac3bfc';\nexport const appVersion = APP_VERSION;\n"],
|
|
5
5
|
"mappings": "AACO,MAAM,cAAc;AACpB,MAAM,aAAa;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/jest.config.cjs
CHANGED
|
@@ -25,6 +25,8 @@ module.exports = {
|
|
|
25
25
|
rootDir: '.',
|
|
26
26
|
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json'],
|
|
27
27
|
moduleNameMapper: {
|
|
28
|
+
'^@open-mercato/cache$': '<rootDir>/../cache/src/index.ts',
|
|
29
|
+
'^@open-mercato/cache/(.*)$': '<rootDir>/../cache/src/$1',
|
|
28
30
|
'^@open-mercato/shared/(.*)$': '<rootDir>/src/$1',
|
|
29
31
|
'^@open-mercato/core/(.*)$': '<rootDir>/../core/src/$1',
|
|
30
32
|
},
|
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.8191.1.2563ac3bfc",
|
|
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.8191.1.2563ac3bfc",
|
|
134
134
|
"@types/html-to-text": "^9.0.4",
|
|
135
135
|
"@types/sanitize-html": "^2.16.1",
|
|
136
136
|
"dotenv": "^17.4.2",
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
/** @jest-environment node */
|
|
2
|
+
// Component integration: production CRUD/cache code + real Redis; auth, DI and query DB are mocked.
|
|
3
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
4
|
+
import Redis from 'ioredis'
|
|
5
|
+
import { z } from 'zod'
|
|
6
|
+
import { createCacheService, runWithCacheTenant, type CacheStrategy } from '@open-mercato/cache'
|
|
7
|
+
import { makeCrudRoute } from '@open-mercato/shared/lib/crud/factory'
|
|
8
|
+
import { invalidateCrudCache } from '@open-mercato/shared/lib/crud/cache'
|
|
9
|
+
import { collectCrudCacheStats, purgeCrudCacheSegment } from '@open-mercato/shared/lib/crud/cache-stats'
|
|
10
|
+
import { registerApiInterceptors } from '@open-mercato/shared/lib/crud/interceptor-registry'
|
|
11
|
+
|
|
12
|
+
const redisUrl = process.env.CACHE_REDIS_URL
|
|
13
|
+
const describeWithRedis = redisUrl ? describe : describe.skip
|
|
14
|
+
const resource = 'redisregression.lot'
|
|
15
|
+
type Actor = { sub: string; orgId: string; tenantId: string }
|
|
16
|
+
type Lot = { id: string; title: string; storage: string }
|
|
17
|
+
let mockActor: Actor
|
|
18
|
+
let mockRevision = 0
|
|
19
|
+
let mockCache: CacheStrategy
|
|
20
|
+
const queryEngine = { query: jest.fn(async () => ({ items: [{ ...lot(), organization_id: mockActor.orgId, tenant_id: mockActor.tenantId }], total: 1 })) }
|
|
21
|
+
const accessLogService = { log: jest.fn(async () => {}) }
|
|
22
|
+
const container = { resolve: (name: string): unknown => ({ em: {}, queryEngine, cache: mockCache, accessLogService } as Record<string, unknown>)[name] }
|
|
23
|
+
|
|
24
|
+
jest.mock('@open-mercato/shared/lib/di/container', () => ({ createRequestContainer: async () => container }))
|
|
25
|
+
jest.mock('@open-mercato/shared/lib/auth/server', () => ({
|
|
26
|
+
getAuthFromCookies: async () => ({ ...mockActor, roles: ['admin'] }),
|
|
27
|
+
getAuthFromRequest: async () => ({ ...mockActor, roles: ['admin'] }),
|
|
28
|
+
}))
|
|
29
|
+
jest.mock('@open-mercato/core/modules/directory/utils/organizationScope', () => ({
|
|
30
|
+
resolveOrganizationScopeForRequest: async () => ({ selectedId: mockActor.orgId, filterIds: [mockActor.orgId], allowedIds: [mockActor.orgId], tenantId: mockActor.tenantId }),
|
|
31
|
+
}))
|
|
32
|
+
jest.mock('@open-mercato/core/modules/entities/lib/helpers', () => ({ setRecordCustomFields: jest.fn(async () => {}) }))
|
|
33
|
+
|
|
34
|
+
function lot(): Lot {
|
|
35
|
+
return { id: mockActor.orgId, title: `Frozen vegetable QC ${mockRevision}: ${mockActor.sub}/${mockActor.orgId}/${mockActor.tenantId}`,
|
|
36
|
+
storage: 'Agram frozen peas, local growers, quality control; keep at -18°C. '.repeat(80) }
|
|
37
|
+
}
|
|
38
|
+
class FrozenLot {}
|
|
39
|
+
const route = makeCrudRoute({
|
|
40
|
+
metadata: { GET: { requireAuth: true } },
|
|
41
|
+
orm: { entity: FrozenLot, idField: 'id', orgField: 'organizationId', tenantField: 'tenantId', softDeleteField: 'deletedAt' },
|
|
42
|
+
events: { module: 'redisregression', entity: 'lot' },
|
|
43
|
+
indexer: { entityType: 'redisregression:lot' },
|
|
44
|
+
list: {
|
|
45
|
+
schema: z.object({ page: z.coerce.number().default(1), pageSize: z.coerce.number().default(10) }),
|
|
46
|
+
entityId: 'redisregression:lot', fields: ['id', 'title', 'storage'],
|
|
47
|
+
transformItem: (item: Lot) => ({ id: item.id, title: item.title, storage: item.storage }),
|
|
48
|
+
},
|
|
49
|
+
})
|
|
50
|
+
const url = 'http://fixture.invalid/api/redisregression/lots?page=1&pageSize=10'
|
|
51
|
+
async function read(expected: 'miss' | 'hit', target = url): Promise<{ items: Lot[] }> {
|
|
52
|
+
// The app's request boundary owns tenant context; makeCrudRoute consumes it.
|
|
53
|
+
const response = await runWithCacheTenant(mockActor.tenantId, () => route.GET(new Request(target)))
|
|
54
|
+
expect(response.status).toBe(200)
|
|
55
|
+
expect(response.headers.get('x-om-cache')).toBe(expected)
|
|
56
|
+
return response.json()
|
|
57
|
+
}
|
|
58
|
+
const scoped = <T>(actor: Actor, run: () => Promise<T>) => runWithCacheTenant(actor.tenantId, run)
|
|
59
|
+
async function invalidate(actor: Actor) {
|
|
60
|
+
await invalidateCrudCache(container as never, resource, { id: actor.orgId, organizationId: actor.orgId, tenantId: actor.tenantId }, actor.tenantId, 'redis-live-test')
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Require an explicit test DB. Each fixture owns fresh tenant namespaces;
|
|
64
|
+
// cleanup never uses FLUSHDB/FLUSHALL or removes another tenant's keys.
|
|
65
|
+
async function fixture(compression: 'off' | 'gzip', run: (actors: Actor[], admin: Redis) => Promise<void>) {
|
|
66
|
+
const parsed = new URL(redisUrl!)
|
|
67
|
+
expect(['redis:', 'rediss:']).toContain(parsed.protocol)
|
|
68
|
+
expect(parsed.pathname).toMatch(/^\/\d+$/)
|
|
69
|
+
expect(parsed.search).toBe('')
|
|
70
|
+
const tenants = [randomUUID(), randomUUID()], orgs = [randomUUID(), randomUUID()]
|
|
71
|
+
const actors = [
|
|
72
|
+
{ sub: 'user-a', orgId: orgs[0], tenantId: tenants[0] },
|
|
73
|
+
{ sub: 'user-b', orgId: orgs[0], tenantId: tenants[0] },
|
|
74
|
+
{ sub: 'user-a', orgId: orgs[1], tenantId: tenants[0] },
|
|
75
|
+
{ sub: 'user-a', orgId: orgs[0], tenantId: tenants[1] },
|
|
76
|
+
]
|
|
77
|
+
mockActor = actors[0]; mockRevision = 0
|
|
78
|
+
queryEngine.query.mockClear(); accessLogService.log.mockClear(); registerApiInterceptors([])
|
|
79
|
+
mockCache = createCacheService({ strategy: 'redis', redisUrl, compression, defaultTtl: 60_000 })
|
|
80
|
+
const admin = new Redis(redisUrl!, { protocol: 2, maxRetriesPerRequest: 1 })
|
|
81
|
+
try {
|
|
82
|
+
expect(mockCache.healthcheck).toEqual(expect.any(Function))
|
|
83
|
+
await mockCache.healthcheck!()
|
|
84
|
+
// A raw physical read in every fixture catches dependency fallback and missing tenant wrapping.
|
|
85
|
+
const proof = `proof:${randomUUID()}`
|
|
86
|
+
await scoped(actors[0], () => mockCache.set(proof, { physical: true }, { ttl: 60_000 }))
|
|
87
|
+
const digest = createHash('sha256').update(proof).digest('hex')
|
|
88
|
+
expect(await admin.exists(`cache:tenant:${tenants[0]}:key:k:${digest}`)).toBe(1)
|
|
89
|
+
expect(await scoped(actors[0], () => mockCache.delete(proof))).toBe(true)
|
|
90
|
+
await run(actors, admin)
|
|
91
|
+
} finally {
|
|
92
|
+
// Collect our tenant namespaces first so deleting pages does not perturb SCAN iteration.
|
|
93
|
+
try {
|
|
94
|
+
for (const tenant of tenants) {
|
|
95
|
+
const keys = new Set<string>(); let cursor = '0'
|
|
96
|
+
do {
|
|
97
|
+
const [next, page] = await admin.scan(cursor, 'MATCH', `*tenant:${tenant}:*`, 'COUNT', 256)
|
|
98
|
+
cursor = next; for (const key of page) keys.add(key)
|
|
99
|
+
} while (cursor !== '0')
|
|
100
|
+
const ownKeys = [...keys]
|
|
101
|
+
for (let offset = 0; offset < ownKeys.length; offset += 256) await admin.del(...ownKeys.slice(offset, offset + 256))
|
|
102
|
+
}
|
|
103
|
+
} finally { await Promise.all([admin.quit(), mockCache.close?.()]) }
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
describeWithRedis.each(['off', 'gzip'] as const)('CRUD factory with live Redis (%s)', compression => {
|
|
108
|
+
const previousFlag = process.env.ENABLE_CRUD_API_CACHE
|
|
109
|
+
beforeAll(() => { process.env.ENABLE_CRUD_API_CACHE = 'true' })
|
|
110
|
+
afterAll(() => {
|
|
111
|
+
if (previousFlag === undefined) delete process.env.ENABLE_CRUD_API_CACHE
|
|
112
|
+
else process.env.ENABLE_CRUD_API_CACHE = previousFlag
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
it('round-trips miss -> hit -> real tag invalidation -> fresh miss', async () => fixture(compression, async ([actor], admin) => {
|
|
116
|
+
const expected = lot()
|
|
117
|
+
expect((await read('miss')).items).toEqual([expected])
|
|
118
|
+
expect((await read('hit')).items).toEqual([expected])
|
|
119
|
+
expect(queryEngine.query).toHaveBeenCalledTimes(1)
|
|
120
|
+
const [key] = await scoped(actor, () => mockCache.keys('crud|*'))
|
|
121
|
+
expect(key).toBeDefined()
|
|
122
|
+
const digest = createHash('sha256').update(key).digest('hex')
|
|
123
|
+
const stored = await admin.getBuffer(`cache:tenant:${actor.tenantId}:key:k:${digest}`)
|
|
124
|
+
expect(stored).not.toBeNull()
|
|
125
|
+
if (compression === 'gzip') expect(stored!.subarray(0, 2)).toEqual(Buffer.from([0x1f, 0x8b]))
|
|
126
|
+
else expect(JSON.parse(stored!.toString('utf8')).value.payload.items).toEqual([expected])
|
|
127
|
+
mockRevision = 1
|
|
128
|
+
await invalidate(actor)
|
|
129
|
+
expect(await scoped(actor, () => mockCache.keys('crud|*'))).toEqual([])
|
|
130
|
+
const fresh = lot()
|
|
131
|
+
expect((await read('miss')).items).toEqual([fresh])
|
|
132
|
+
expect((await read('hit')).items).toEqual([fresh])
|
|
133
|
+
expect(queryEngine.query).toHaveBeenCalledTimes(2)
|
|
134
|
+
}))
|
|
135
|
+
|
|
136
|
+
it('isolates users, organizations and tenants, including scoped invalidation', async () => fixture(compression, async actors => {
|
|
137
|
+
const stored = []
|
|
138
|
+
for (const actor of actors) {
|
|
139
|
+
mockActor = actor; const expected = lot(); stored.push(expected)
|
|
140
|
+
expect((await read('miss')).items).toEqual([expected])
|
|
141
|
+
expect((await read('hit')).items).toEqual([expected])
|
|
142
|
+
}
|
|
143
|
+
expect(queryEngine.query).toHaveBeenCalledTimes(4)
|
|
144
|
+
mockRevision = 1
|
|
145
|
+
await invalidate(actors[0])
|
|
146
|
+
for (const index of [2, 3]) {
|
|
147
|
+
mockActor = actors[index]
|
|
148
|
+
expect((await read('hit')).items).toEqual([stored[index]])
|
|
149
|
+
}
|
|
150
|
+
for (const index of [0, 1]) {
|
|
151
|
+
mockActor = actors[index]
|
|
152
|
+
expect((await read('miss')).items).toEqual([lot()])
|
|
153
|
+
}
|
|
154
|
+
expect(queryEngine.query).toHaveBeenCalledTimes(6)
|
|
155
|
+
}))
|
|
156
|
+
|
|
157
|
+
it('exposes logical keys/stats and purges one real CRUD segment', async () => fixture(compression, async actors => {
|
|
158
|
+
const otherUrl = url.replace('/lots?', '/growers?')
|
|
159
|
+
await read('miss'); await read('miss', otherUrl)
|
|
160
|
+
const keys = await scoped(actors[0], () => mockCache.keys('crud|*'))
|
|
161
|
+
expect(keys).toHaveLength(2); expect(new Set(keys).size).toBe(2)
|
|
162
|
+
expect(keys.every(key => key.startsWith(`crud|${resource}|`))).toBe(true)
|
|
163
|
+
expect(await scoped(actors[0], () => mockCache.stats())).toEqual({ size: 2, expired: 0 })
|
|
164
|
+
const stats = await scoped(actors[0], () => collectCrudCacheStats(mockCache))
|
|
165
|
+
expect(stats.totalKeys).toBe(2)
|
|
166
|
+
expect(stats.segments).toHaveLength(2)
|
|
167
|
+
expect(stats.segments.flatMap(segment => segment.keys).sort()).toEqual([...keys].sort())
|
|
168
|
+
const segment = stats.segments.find(item => item.path?.includes('/lots'))
|
|
169
|
+
expect(segment).toBeDefined()
|
|
170
|
+
mockActor = actors[3]; const otherTenantPayload = (await read('miss')).items
|
|
171
|
+
const purged = await scoped(actors[0], () => purgeCrudCacheSegment(mockCache, segment!.segment))
|
|
172
|
+
expect(purged.deleted).toBe(1); expect(purged.keys).toEqual(segment!.keys)
|
|
173
|
+
expect((await read('hit')).items).toEqual(otherTenantPayload)
|
|
174
|
+
mockActor = actors[0]
|
|
175
|
+
expect(await scoped(actors[0], () => mockCache.keys('crud|*'))).toHaveLength(1)
|
|
176
|
+
await read('hit', otherUrl); await read('miss')
|
|
177
|
+
expect(queryEngine.query).toHaveBeenCalledTimes(4)
|
|
178
|
+
}))
|
|
179
|
+
|
|
180
|
+
it('clears only the selected tenant and keeps another tenant cached', async () => fixture(compression, async actors => {
|
|
181
|
+
await read('miss'); await read('miss', url.replace('/lots?', '/growers?'))
|
|
182
|
+
mockActor = actors[3]; const otherTenantPayload = (await read('miss')).items
|
|
183
|
+
expect(await scoped(actors[0], () => mockCache.clear())).toBe(2)
|
|
184
|
+
expect(await scoped(actors[0], () => mockCache.keys())).toEqual([])
|
|
185
|
+
expect(await scoped(actors[0], () => mockCache.stats())).toEqual({ size: 0, expired: 0 })
|
|
186
|
+
expect((await read('hit')).items).toEqual(otherTenantPayload)
|
|
187
|
+
mockActor = actors[0]; await read('miss')
|
|
188
|
+
expect(queryEngine.query).toHaveBeenCalledTimes(4)
|
|
189
|
+
}))
|
|
190
|
+
})
|