Registry Mirror
Skip to content

File tree

‎packages/openapi/src/adapters/standard/openapi-matcher.test.ts‎

Lines changed: 77 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -188,23 +188,24 @@ describe('standardOpenAPIMatcher', () => {
188188
it('lazy router inside lazy router with concurrent requests', async () => {
189189
const base = os.$context<any>()
190190

191-
let resolveNested!: (value: { default: any }) => void
191+
const resolvers: ((value: { default: any }) => void)[] = []
192192
const nestedLoader = vi.fn(() => new Promise<{ default: any }>((resolve) => {
193-
resolveNested = resolve
193+
resolvers.push(resolve)
194194
}))
195195
const pongLoader = vi.fn(() => Promise.resolve({ default: pong }))
196196

197197
const rpcMatcher = new StandardOpenAPIMatcher()
198198
rpcMatcher.init(base.router({
199199
nested: base.lazy(nestedLoader),
200200
}))
201+
const initSpy = vi.spyOn(rpcMatcher, 'init')
201202

202203
const match1 = rpcMatcher.match('POST', '/nested/pong')
203204
const match2 = rpcMatcher.match('POST', '/nested/pong')
204205

205-
expect(nestedLoader).toHaveBeenCalledTimes(1)
206+
expect(nestedLoader).toHaveBeenCalledTimes(2)
206207

207-
resolveNested({ default: { pong: base.lazy(pongLoader) } })
208+
resolvers.forEach(resolve => resolve({ default: { pong: base.lazy(pongLoader) } }))
208209

209210
expect(await match1).toEqual({
210211
path: ['nested', 'pong'],
@@ -216,17 +217,82 @@ describe('standardOpenAPIMatcher', () => {
216217
procedure: pong,
217218
})
218219

219-
expect(nestedLoader).toHaveBeenCalledTimes(1)
220-
expect(pongLoader).toHaveBeenCalledTimes(1)
221-
222220
// subsequent requests still work without reloading
223221
expect(await rpcMatcher.match('POST', '/nested/pong')).toEqual({
224222
path: ['nested', 'pong'],
225223
procedure: pong,
226224
})
227225

228-
expect(nestedLoader).toHaveBeenCalledTimes(1)
229-
expect(pongLoader).toHaveBeenCalledTimes(1)
226+
expect(initSpy.mock.calls.map(([, path]) => path)).toEqual([['nested'], ['nested', 'pong']])
227+
})
228+
229+
it('matches while another match is still loading, and drops the slower load', async () => {
230+
const base = os.$context<any>()
231+
232+
let resolveFirst!: (value: { default: any }) => void
233+
const nestedLoader = vi.fn()
234+
.mockReturnValueOnce(new Promise((resolve) => {
235+
resolveFirst = resolve
236+
}))
237+
.mockResolvedValueOnce({ default: { pong } })
238+
239+
const rpcMatcher = new StandardOpenAPIMatcher()
240+
rpcMatcher.init(base.router({
241+
nested: base.lazy(nestedLoader),
242+
}))
243+
const initSpy = vi.spyOn(rpcMatcher, 'init')
244+
245+
const slow = rpcMatcher.match('POST', '/nested/pong')
246+
247+
expect(await rpcMatcher.match('POST', '/nested/pong')).toEqual({
248+
path: ['nested', 'pong'],
249+
procedure: pong,
250+
})
251+
252+
// the slower load resolves to a different router
253+
resolveFirst({ default: { pong: ping } })
254+
255+
expect(await slow).toEqual({
256+
path: ['nested', 'pong'],
257+
procedure: pong,
258+
})
259+
260+
expect(initSpy).toHaveBeenCalledTimes(1)
261+
})
262+
263+
it('indexes lazy routers sharing a prefix once each while one load is stuck', async () => {
264+
const base = os.$context<any>()
265+
266+
const find = base.route({ method: 'GET', path: '/find' }).handler(() => 'find')
267+
const list = base.route({ method: 'GET', path: '/list' }).handler(() => 'list')
268+
269+
let resolveStuck!: (value: { default: any }) => void
270+
const findLoader = vi.fn()
271+
.mockReturnValueOnce(new Promise((resolve) => {
272+
resolveStuck = resolve
273+
}))
274+
.mockResolvedValue({ default: { find } })
275+
276+
const rpcMatcher = new StandardOpenAPIMatcher()
277+
rpcMatcher.init(base.router({
278+
a: base.prefix('/users').lazy(findLoader),
279+
b: base.prefix('/users').lazy(() => Promise.resolve({ default: { list } })),
280+
}))
281+
const initSpy = vi.spyOn(rpcMatcher, 'init')
282+
283+
const stuck = rpcMatcher.match('GET', '/users/find')
284+
const [found, listed] = await Promise.all([
285+
rpcMatcher.match('GET', '/users/find'),
286+
rpcMatcher.match('GET', '/users/list'),
287+
])
288+
289+
expect(found).toEqual({ path: ['a', 'find'], procedure: expect.any(Object), params: undefined })
290+
expect(listed).toEqual({ path: ['b', 'list'], procedure: expect.any(Object), params: undefined })
291+
292+
resolveStuck({ default: { find } })
293+
294+
expect(await stuck).toEqual({ path: ['a', 'find'], procedure: expect.any(Object), params: undefined })
295+
expect(initSpy.mock.calls.map(([, path]) => path!.join('/')).sort()).toEqual(['a', 'b'])
230296
})
231297

232298
it('multiple lazy routers with lazy router inside lazy router', async () => {
@@ -260,6 +326,7 @@ describe('standardOpenAPIMatcher', () => {
260326
planets: base.prefix('/planets').lazy(planetsLoader),
261327
unused: base.prefix('/unused').lazy(unusedLoader),
262328
}))
329+
const initSpy = vi.spyOn(rpcMatcher, 'init')
263330

264331
// concurrent requests across different lazy branches
265332
const [match1, match2, match3] = await Promise.all([
@@ -283,12 +350,6 @@ describe('standardOpenAPIMatcher', () => {
283350
procedure: pong,
284351
})
285352

286-
expect(usersLoader).toHaveBeenCalledTimes(1)
287-
expect(userFindLoader).toHaveBeenCalledTimes(1)
288-
expect(planetsLoader).toHaveBeenCalledTimes(1)
289-
expect(planetNestedLoader).toHaveBeenCalledTimes(1)
290-
expect(planetDeepLoader).toHaveBeenCalledTimes(1)
291-
292353
// prefixed router not matched by any request stays lazy
293354
expect(unusedLoader).toHaveBeenCalledTimes(0)
294355

@@ -298,10 +359,8 @@ describe('standardOpenAPIMatcher', () => {
298359
procedure: pong,
299360
})
300361

301-
expect(planetsLoader).toHaveBeenCalledTimes(1)
302-
expect(planetNestedLoader).toHaveBeenCalledTimes(1)
303-
expect(planetDeepLoader).toHaveBeenCalledTimes(1)
304362
expect(unusedLoader).toHaveBeenCalledTimes(0)
363+
expect(initSpy.mock.calls.map(([, path]) => path!.join('.')).sort()).toEqual(['planets', 'planets.nested', 'planets.nested.deep', 'users', 'users.find'])
305364
})
306365

307366
it('lazy router can retry after loader failure', async () => {

‎packages/openapi/src/adapters/standard/openapi-matcher.ts‎

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@ export class StandardOpenAPIMatcher implements StandardMatcher {
3232
private readonly pendingRouters: (LazyTraverseContractProceduresOptions & {
3333
httpPathPrefix: HTTPPath
3434
laziedPrefix: string | undefined
35-
initPromise?: Promise<void>
3635
}) [] = []
3736

3837
constructor(options: StandardOpenAPIMatcherOptions = {}) {
@@ -91,20 +90,14 @@ export class StandardOpenAPIMatcher implements StandardMatcher {
9190
break
9291
}
9392

94-
/**
95-
* Memoize the init work and only remove the pending router after it finishes,
96-
* so concurrent requests share a single init instead of re-initializing
97-
* the same router or dropping pending routers pushed by each other.
98-
*/
99-
pendingRouter.initPromise ??= unlazy(pendingRouter.router).then(({ default: router }) => {
100-
this.init(router, pendingRouter.path)
101-
this.pendingRouters.splice(this.pendingRouters.indexOf(pendingRouter), 1)
102-
}).catch((error) => {
103-
pendingRouter.initPromise = undefined // allow retrying on failure
104-
throw error
105-
})
93+
// Not shared across requests: on Cloudflare Workers a promise can't settle once its request ends
94+
const { default: router } = await unlazy(pendingRouter.router)
95+
const index = this.pendingRouters.indexOf(pendingRouter)
10696

107-
await pendingRouter.initPromise
97+
if (index !== -1) {
98+
this.init(router, pendingRouter.path)
99+
this.pendingRouters.splice(index, 1)
100+
}
108101
}
109102

110103
const match = findRoute(this.tree, method, pathname)

‎packages/server/src/adapters/standard/rpc-matcher.test.ts‎

Lines changed: 42 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -172,9 +172,9 @@ describe('standardRPCMatcher', () => {
172172
it('lazy router inside lazy router with concurrent requests', async () => {
173173
const base = os.$context<any>()
174174

175-
let resolveNested!: (value: { default: any }) => void
175+
const resolvers: ((value: { default: any }) => void)[] = []
176176
const nestedLoader = vi.fn(() => new Promise<{ default: any }>((resolve) => {
177-
resolveNested = resolve
177+
resolvers.push(resolve)
178178
}))
179179
const pingLoader = vi.fn(() => Promise.resolve({ default: ping }))
180180

@@ -183,20 +183,21 @@ describe('standardRPCMatcher', () => {
183183
pong,
184184
nested: base.lazy(nestedLoader),
185185
}))
186+
const initSpy = vi.spyOn(rpcMatcher, 'init')
186187

187188
const match1 = rpcMatcher.match('POST', '/nested/ping')
188189
const match2 = rpcMatcher.match('POST', '/nested/ping')
189190
// non-matching request should not wait for or drop pending lazy routers
190191
const match3 = rpcMatcher.match('POST', '/pong')
191192

192-
expect(nestedLoader).toHaveBeenCalledTimes(1)
193+
expect(nestedLoader).toHaveBeenCalledTimes(2)
193194

194195
expect(await match3).toEqual({
195196
path: ['pong'],
196197
procedure: pong,
197198
})
198199

199-
resolveNested({ default: { ping: base.lazy(pingLoader) } })
200+
resolvers.forEach(resolve => resolve({ default: { ping: base.lazy(pingLoader) } }))
200201

201202
expect(await match1).toEqual({
202203
path: ['nested', 'ping'],
@@ -208,17 +209,47 @@ describe('standardRPCMatcher', () => {
208209
procedure: ping,
209210
})
210211

211-
expect(nestedLoader).toHaveBeenCalledTimes(1)
212-
expect(pingLoader).toHaveBeenCalledTimes(1)
213-
214212
// subsequent requests still work without reloading
215213
expect(await rpcMatcher.match('POST', '/nested/ping')).toEqual({
216214
path: ['nested', 'ping'],
217215
procedure: ping,
218216
})
219217

220-
expect(nestedLoader).toHaveBeenCalledTimes(1)
221-
expect(pingLoader).toHaveBeenCalledTimes(1)
218+
expect(initSpy.mock.calls.map(([, path]) => path)).toEqual([['nested'], ['nested', 'ping']])
219+
})
220+
221+
it('matches while another match is still loading, and drops the slower load', async () => {
222+
const base = os.$context<any>()
223+
224+
let resolveFirst!: (value: { default: any }) => void
225+
const nestedLoader = vi.fn()
226+
.mockReturnValueOnce(new Promise((resolve) => {
227+
resolveFirst = resolve
228+
}))
229+
.mockResolvedValueOnce({ default: { ping } })
230+
231+
const rpcMatcher = new StandardRPCMatcher()
232+
rpcMatcher.init(base.router({
233+
nested: base.lazy(nestedLoader),
234+
}))
235+
const initSpy = vi.spyOn(rpcMatcher, 'init')
236+
237+
const slow = rpcMatcher.match('POST', '/nested/ping')
238+
239+
expect(await rpcMatcher.match('POST', '/nested/ping')).toEqual({
240+
path: ['nested', 'ping'],
241+
procedure: ping,
242+
})
243+
244+
// the slower load resolves to a different router
245+
resolveFirst({ default: { ping: pong } })
246+
247+
expect(await slow).toEqual({
248+
path: ['nested', 'ping'],
249+
procedure: ping,
250+
})
251+
252+
expect(initSpy).toHaveBeenCalledTimes(1)
222253
})
223254

224255
it('multiple lazy routers with lazy router inside lazy router', async () => {
@@ -254,6 +285,7 @@ describe('standardRPCMatcher', () => {
254285
planets: base.lazy(planetsLoader),
255286
unused: base.lazy(unusedLoader),
256287
}))
288+
const initSpy = vi.spyOn(rpcMatcher, 'init')
257289

258290
// concurrent requests across different lazy branches
259291
const [match1, match2, match3] = await Promise.all([
@@ -277,12 +309,6 @@ describe('standardRPCMatcher', () => {
277309
procedure: pong,
278310
})
279311

280-
expect(usersLoader).toHaveBeenCalledTimes(1)
281-
expect(userFindLoader).toHaveBeenCalledTimes(1)
282-
expect(planetsLoader).toHaveBeenCalledTimes(1)
283-
expect(planetNestedLoader).toHaveBeenCalledTimes(1)
284-
expect(planetDeepLoader).toHaveBeenCalledTimes(1)
285-
286312
// routers not matched by any request stay lazy
287313
expect(userListLoader).toHaveBeenCalledTimes(0)
288314
expect(unusedLoader).toHaveBeenCalledTimes(0)
@@ -293,9 +319,9 @@ describe('standardRPCMatcher', () => {
293319
procedure: pong,
294320
})
295321

296-
expect(usersLoader).toHaveBeenCalledTimes(1)
297322
expect(userListLoader).toHaveBeenCalledTimes(1)
298323
expect(unusedLoader).toHaveBeenCalledTimes(0)
324+
expect(initSpy.mock.calls.map(([, path]) => path!.join('.')).sort()).toEqual(['planets', 'planets.nested', 'planets.nested.deep', 'users', 'users.find', 'users.list'])
299325
})
300326

301327
it('lazy router can retry after loader failure', async () => {

‎packages/server/src/adapters/standard/rpc-matcher.ts‎

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@ export class StandardRPCMatcher implements StandardMatcher {
3636

3737
private readonly pendingRouters: (LazyTraverseContractProceduresOptions & {
3838
httpPathPrefix: HTTPPath
39-
initPromise?: Promise<void>
4039
}) [] = []
4140

4241
constructor(options: StandardRPCMatcherOptions = {}) {
@@ -91,20 +90,14 @@ export class StandardRPCMatcher implements StandardMatcher {
9190
break
9291
}
9392

94-
/**
95-
* Memoize the init work and only remove the pending router after it finishes,
96-
* so concurrent requests share a single init instead of re-initializing
97-
* the same router or dropping pending routers pushed by each other.
98-
*/
99-
pendingRouter.initPromise ??= unlazy(pendingRouter.router).then(({ default: router }) => {
100-
this.init(router, pendingRouter.path)
101-
this.pendingRouters.splice(this.pendingRouters.indexOf(pendingRouter), 1)
102-
}).catch((error) => {
103-
pendingRouter.initPromise = undefined // allow retrying on failure
104-
throw error
105-
})
93+
// Not shared across requests: on Cloudflare Workers a promise can't settle once its request ends
94+
const { default: router } = await unlazy(pendingRouter.router)
95+
const index = this.pendingRouters.indexOf(pendingRouter)
10696

107-
await pendingRouter.initPromise
97+
if (index !== -1) {
98+
this.init(router, pendingRouter.path)
99+
this.pendingRouters.splice(index, 1)
100+
}
108101
}
109102

110103
const match = this.tree[pathname]

0 commit comments

Comments
 (0)