|
| 1 | +import type { AddressInfo } from 'node:net' |
| 2 | +import type { DevframeRpcClientOptions } from './rpc' |
| 3 | +import { createServer } from 'node:http' |
| 4 | +import { defineDevframe, defineRpcFunction } from 'devframe' |
| 5 | +import { DEVFRAME_EVENTS } from 'devframe/constants' |
| 6 | +import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' |
| 7 | +import { initDevframe } from '../adapters/initiate' |
| 8 | +import { connectDevframe } from './index' |
| 9 | + |
| 10 | +const connectionGlobals = ['__DEVFRAME_CONNECTION_META__', '__DEVFRAME_CONNECTION_AUTH_TOKEN__', '__DEVFRAME_CONNECTION__'] |
| 11 | + |
| 12 | +beforeEach(() => { |
| 13 | + vi.stubGlobal('navigator', { userAgent: 'vitest' }) |
| 14 | + for (const key of connectionGlobals) delete (globalThis as any)[key] |
| 15 | +}) |
| 16 | + |
| 17 | +afterEach(() => { |
| 18 | + vi.unstubAllGlobals() |
| 19 | + for (const key of connectionGlobals) delete (globalThis as any)[key] |
| 20 | +}) |
| 21 | + |
| 22 | +async function setup(transport: 'websocket' | 'sse', cacheOptions: DevframeRpcClientOptions['cacheOptions'] = true, legacy = false) { |
| 23 | + const devframe = initDevframe(defineDevframe({ |
| 24 | + id: 'cache-test', |
| 25 | + name: 'Cache test', |
| 26 | + version: '0.0.0', |
| 27 | + packageName: 'cache-test', |
| 28 | + homepage: 'https://example.test', |
| 29 | + description: 'RPC cache regression tests.', |
| 30 | + setup: () => {}, |
| 31 | + }), { base: '/__cache/', auth: false }) |
| 32 | + const server = createServer((req, res) => devframe.nodeMiddleware(req, res)) |
| 33 | + devframe.attach(server) |
| 34 | + await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)) |
| 35 | + onTestFinished(async () => { |
| 36 | + await devframe.close() |
| 37 | + await new Promise<void>(resolve => server.close(() => resolve())) |
| 38 | + }) |
| 39 | + const ctx = await devframe.context |
| 40 | + if (legacy) |
| 41 | + ctx.rpc.definitions.delete('devframe:rpc:cacheable-functions') |
| 42 | + const counts: Record<string, number> = {} |
| 43 | + for (const [name, type, cacheable] of [ |
| 44 | + ['static', 'static', false], |
| 45 | + ['query', 'query', true], |
| 46 | + ['uncached', 'query', false], |
| 47 | + ['default', 'query', undefined], |
| 48 | + ['action', 'action', true], |
| 49 | + ['event', 'event', true], |
| 50 | + ] as const) { |
| 51 | + ctx.rpc.register(defineRpcFunction({ |
| 52 | + name: `test:${name}`, |
| 53 | + type, |
| 54 | + cacheable, |
| 55 | + handler: (value: unknown) => { |
| 56 | + counts[name] = (counts[name] ?? 0) + 1 |
| 57 | + return value |
| 58 | + }, |
| 59 | + })) |
| 60 | + } |
| 61 | + const origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}` |
| 62 | + vi.stubGlobal('location', new URL(`${origin}/__cache/`)) |
| 63 | + const client = await connectDevframe({ |
| 64 | + baseURL: `${origin}/__cache/`, |
| 65 | + transport, |
| 66 | + cacheOptions, |
| 67 | + otpParam: false, |
| 68 | + simpleAuth: false, |
| 69 | + webmcp: false, |
| 70 | + callTimeout: 3000, |
| 71 | + }) |
| 72 | + onTestFinished(() => client.close?.()) |
| 73 | + return { ctx, client, counts, call: client.call as (name: string, value?: unknown) => Promise<unknown> } |
| 74 | +} |
| 75 | + |
| 76 | +describe.each(['websocket', 'sse'] as const)('automatic RPC cache over %s', (transport) => { |
| 77 | + it('caches static and opted-in queries from the first call, by arguments', async () => { |
| 78 | + const { call, counts } = await setup(transport) |
| 79 | + for (const name of ['static', 'query', 'uncached', 'default', 'action', 'event']) { |
| 80 | + for (const value of [1, 1, 2]) |
| 81 | + await expect(call(`test:${name}`, value)).resolves.toBe(value) |
| 82 | + } |
| 83 | + expect(counts).toEqual({ static: 2, query: 2, uncached: 3, default: 3, action: 3, event: 3 }) |
| 84 | + }) |
| 85 | + |
| 86 | + it('caches falsy results and keeps event calls reaching the server', async () => { |
| 87 | + const { client, call, counts } = await setup(transport) |
| 88 | + for (const value of [false, 0, '', null, undefined]) { |
| 89 | + await expect(call('test:query', value)).resolves.toBe(value) |
| 90 | + await expect(call('test:query', value)).resolves.toBe(value) |
| 91 | + } |
| 92 | + expect(counts.query).toBe(5) |
| 93 | + await client.callEvent('test:query' as any, 0) |
| 94 | + await client.callEvent('test:query' as any, 0) |
| 95 | + await vi.waitFor(() => expect(counts.query).toBe(7)) |
| 96 | + }) |
| 97 | + |
| 98 | + it('preserves explicit function lists and custom serializers', async () => { |
| 99 | + const keySerializer = vi.fn(() => 'same-key') |
| 100 | + const { call, counts } = await setup(transport, { functions: ['test:uncached'], keySerializer }) |
| 101 | + await expect(call('test:uncached', 1)).resolves.toBe(1) |
| 102 | + await expect(call('test:uncached', 2)).resolves.toBe(1) |
| 103 | + await call('test:query', 1) |
| 104 | + await call('test:query', 1) |
| 105 | + expect(counts).toEqual({ uncached: 1, query: 2 }) |
| 106 | + expect(keySerializer).toHaveBeenCalled() |
| 107 | + }) |
| 108 | + |
| 109 | + it('keeps caching disabled with false', async () => { |
| 110 | + const { call, counts } = await setup(transport, false) |
| 111 | + await call('test:query', 1) |
| 112 | + await call('test:query', 1) |
| 113 | + expect(counts.query).toBe(2) |
| 114 | + }) |
| 115 | + |
| 116 | + it('does not cache rejected results', async () => { |
| 117 | + const { ctx, call } = await setup(transport) |
| 118 | + const handler = vi.fn() |
| 119 | + .mockRejectedValueOnce(new Error('retry me')) |
| 120 | + .mockResolvedValue('ok') |
| 121 | + ctx.rpc.register(defineRpcFunction({ name: 'test:retry', type: 'query', cacheable: true, handler })) |
| 122 | + await expect(call('test:retry')).rejects.toThrow('retry me') |
| 123 | + await expect(call('test:retry')).resolves.toBe('ok') |
| 124 | + await expect(call('test:retry')).resolves.toBe('ok') |
| 125 | + expect(handler).toHaveBeenCalledTimes(2) |
| 126 | + }) |
| 127 | + |
| 128 | + it('falls back to uncached calls with an older server', async () => { |
| 129 | + const { call, counts } = await setup(transport, true, true) |
| 130 | + await call('test:query', 1) |
| 131 | + await call('test:query', 1) |
| 132 | + expect(counts.query).toBe(2) |
| 133 | + }) |
| 134 | + |
| 135 | + it('refreshes eligibility when a function is registered or updated', async () => { |
| 136 | + const { ctx, client, call } = await setup(transport) |
| 137 | + await call('test:query', 1) |
| 138 | + const clear = vi.spyOn(client.cacheManager, 'clear') |
| 139 | + const handler = vi.fn(() => 'new') |
| 140 | + ctx.rpc.register(defineRpcFunction({ name: 'test:late', type: 'query', cacheable: true, handler })) |
| 141 | + await vi.waitFor(() => expect(clear).toHaveBeenCalled()) |
| 142 | + await expect(call('test:late')).resolves.toBe('new') |
| 143 | + await expect(call('test:late')).resolves.toBe('new') |
| 144 | + expect(handler).toHaveBeenCalledTimes(1) |
| 145 | + clear.mockClear() |
| 146 | + ctx.rpc.update(defineRpcFunction({ name: 'test:late', type: 'action', handler })) |
| 147 | + await vi.waitFor(() => expect(clear).toHaveBeenCalled()) |
| 148 | + await call('test:late') |
| 149 | + await call('test:late') |
| 150 | + expect(handler).toHaveBeenCalledTimes(3) |
| 151 | + }) |
| 152 | + |
| 153 | + it('clears results on invalidation and rejects late cache writes', async () => { |
| 154 | + const { ctx, client, call, counts } = await setup(transport) |
| 155 | + const pending = Promise.withResolvers<string>() |
| 156 | + const handler = vi.fn(() => pending.promise) |
| 157 | + ctx.rpc.register(defineRpcFunction({ name: 'test:slow', type: 'query', cacheable: true, handler })) |
| 158 | + await call('test:query', 1) |
| 159 | + const slow = call('test:slow') |
| 160 | + await vi.waitFor(() => expect(handler).toHaveBeenCalledTimes(1)) |
| 161 | + const clear = vi.spyOn(client.cacheManager, 'clear') |
| 162 | + await ctx.rpc.broadcast({ method: DEVFRAME_EVENTS.broadcast.cacheInvalidate, args: [] }) |
| 163 | + await vi.waitFor(() => expect(clear).toHaveBeenCalled()) |
| 164 | + pending.resolve('old') |
| 165 | + await slow |
| 166 | + await call('test:slow') |
| 167 | + expect(handler).toHaveBeenCalledTimes(2) |
| 168 | + await call('test:query', 1) |
| 169 | + expect(counts.query).toBe(2) |
| 170 | + }) |
| 171 | + |
| 172 | + it('clears cached results when trust is revoked and when closed', async () => { |
| 173 | + const { ctx, client, call } = await setup(transport) |
| 174 | + await call('test:query', 1) |
| 175 | + expect(client.cacheManager.has('test:query', [1])).toBe(true) |
| 176 | + await client.services.state() |
| 177 | + await ctx.rpc.broadcast({ method: DEVFRAME_EVENTS.broadcast.authRevoked, args: [] }) |
| 178 | + await vi.waitFor(() => expect(client.isTrusted).toBe(false)) |
| 179 | + expect(client.cacheManager.has('test:query', [1])).toBe(false) |
| 180 | + await expect(call('test:query', 1)).rejects.toThrow(/Not authorized/) |
| 181 | + await client.requestTrust() |
| 182 | + await call('test:query', 1) |
| 183 | + client.close?.() |
| 184 | + expect(client.cacheManager.has('test:query', [1])).toBe(false) |
| 185 | + await expect(call('test:query', 1)).rejects.toMatchObject({ kind: 'connection' }) |
| 186 | + }) |
| 187 | +}) |
0 commit comments