Skip to content

Commit f2469d0

Browse files
authored
Merge pull request #1571 from qtomlinson/qt/enqueue_dedup
Introduce generic ISyncCache<T> and apply to DelayedComputePolicy dedup
2 parents 00b13d6 + 0af2863 commit f2469d0

4 files changed

Lines changed: 147 additions & 33 deletions

File tree

‎providers/caching/index.d.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,3 +51,18 @@ export interface ICache {
5151
*/
5252
delete(item: string): Promise<void> | void
5353
}
54+
55+
/**
56+
* Synchronous cache interface for use cases where get/set must be atomic within
57+
* a single event loop turn (e.g. dedup checks before an async operation).
58+
*/
59+
export interface ISyncCache<ValueType> {
60+
/** Retrieves an item synchronously. Returns null if not found or expired. */
61+
get(item: string): ValueType | null
62+
63+
/** Stores an item synchronously with an optional TTL in seconds. */
64+
set(item: string, value: ValueType, ttlSeconds?: number): undefined
65+
66+
/** Removes an item synchronously. */
67+
delete(item: string): undefined
68+
}

‎providers/caching/memory.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,13 @@
33

44
import { Cache } from 'memory-cache'
55

6-
import type { BaseCacheOptions, ICache } from './index.js'
6+
import type { BaseCacheOptions, ICache, ISyncCache } from './index.js'
77

88
/** Configuration options for MemoryCache */
99
export interface MemoryCacheOptions extends BaseCacheOptions {}
1010

1111
/** In-memory cache implementation using memory-cache library */
12-
class MemoryCache implements ICache {
12+
class MemoryCache implements ICache, ISyncCache<unknown> {
1313
private declare cache: any
1414
private declare defaultTtlSeconds: number | undefined
1515

@@ -31,14 +31,16 @@ class MemoryCache implements ICache {
3131
}
3232

3333
/** Stores an item in the cache */
34-
set(item: string, value: any, ttlSeconds: number | null = null): void {
34+
set(item: string, value: any, ttlSeconds: number | null = null): undefined {
3535
const expiration = ttlSeconds || this.defaultTtlSeconds
3636
this.cache.put(item, value, expiration ? expiration * 1000 : undefined)
37+
return undefined
3738
}
3839

3940
/** Removes an item from the cache */
40-
delete(item: string): void {
41+
delete(item: string): undefined {
4142
this.cache.del(item)
43+
return undefined
4244
}
4345
}
4446

‎providers/recompute/delayedComputePolicy.ts‎

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
import type { Definition, DefinitionService, RecomputeContext } from '../../business/definitionService.ts'
55
import type { EntityCoordinates } from '../../lib/entityCoordinates.ts'
6-
import type { ICache } from '../caching/index.js'
6+
import type { ISyncCache } from '../caching/index.js'
77
import Cache from '../caching/memory.ts'
88
import type { Logger } from '../logging/index.js'
99
import logger from '../logging/logger.ts'
@@ -15,7 +15,7 @@ import { SkipUpgradePolicy } from './skipUpgradePolicy.ts'
1515

1616
export interface DelayedComputePolicyOptions extends DefinitionQueueUpgraderOptions {
1717
/** Injectable for testing; defaults to an in-memory cache with 20-minute TTL */
18-
enqueueCache?: ICache
18+
enqueueCache?: ISyncCache<boolean>
1919
}
2020

2121
class DelayedComputePolicy implements MissingDefinitionComputePolicy {
@@ -24,7 +24,7 @@ class DelayedComputePolicy implements MissingDefinitionComputePolicy {
2424

2525
options: DelayedComputePolicyOptions
2626
logger: Logger
27-
declare _enqueueCache: ICache
27+
declare _enqueueCache: ISyncCache<boolean>
2828
declare _compute: IQueue
2929

3030
constructor(options: DelayedComputePolicyOptions) {
@@ -54,14 +54,20 @@ class DelayedComputePolicy implements MissingDefinitionComputePolicy {
5454
throw new Error('Compute queue is not set. DelayedComputePolicy.initialize() must be called before compute()')
5555
}
5656
const key = coordinates.toString()
57-
const alreadyQueued = await this._enqueueCache.get(key)
58-
if (alreadyQueued) {
57+
const alreadyQueued = this._enqueueCache.get(key)
58+
if (alreadyQueued === true) {
5959
this.logger.debug('Skipped duplicate enqueue for delayed definition compute', { coordinates: key })
6060
return
6161
}
62-
const message = this._constructMessage(coordinates)
63-
await this._compute.queue(message)
64-
await this._enqueueCache.set(key, true, DelayedComputePolicy._enqueueCacheTtlSeconds)
62+
this._enqueueCache.set(key, true, DelayedComputePolicy._enqueueCacheTtlSeconds)
63+
try {
64+
const message = this._constructMessage(coordinates)
65+
await this._compute.queue(message)
66+
} catch (error) {
67+
// Roll back optimistic dedup marker so retries can enqueue after transient queue failures.
68+
this._enqueueCache.delete(key)
69+
throw error
70+
}
6571
this.logger.info('Queued for delayed definition compute', {
6672
coordinates: key
6773
})

‎test/providers/recompute/delayedComputePolicy.ts‎

Lines changed: 112 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { expect } from 'chai'
1010
import sinon from 'sinon'
1111
import type { Definition, DefinitionService, RecomputeContext } from '../../../business/definitionService.ts'
1212
import EntityCoordinates from '../../../lib/entityCoordinates.ts'
13-
import type { ICache } from '../../../providers/caching/index.js'
13+
import type { ISyncCache } from '../../../providers/caching/index.js'
1414
import type { IQueue } from '../../../providers/queueing/index.js'
1515
import { DelayedComputePolicy } from '../../../providers/recompute/delayedComputePolicy.ts'
1616
import { createMockLogger } from '../../helpers/mockLogger.ts'
@@ -30,19 +30,25 @@ describe('DelayedComputePolicy', () => {
3030
})
3131

3232
describe('compute()', () => {
33+
let definitionService: RecomputeContext
34+
35+
beforeEach(() => {
36+
definitionService = createDefinitionService()
37+
})
38+
3339
it('throws if called before initialize()', async () => {
3440
const uninitializedPolicy = new DelayedComputePolicy({
3541
logger: createMockLogger(),
3642
queue: () => queue
3743
})
3844

39-
await expect(uninitializedPolicy.compute(definitionService(), coordinates)).to.be.rejectedWith(
45+
await expect(uninitializedPolicy.compute(definitionService, coordinates)).to.be.rejectedWith(
4046
'DelayedComputePolicy.initialize() must be called before compute()'
4147
)
4248
})
4349

4450
it('enqueues coordinates and returns placeholder definition', async () => {
45-
const result = await policy.compute(definitionService(), coordinates)
51+
const result = await policy.compute(definitionService, coordinates)
4652
validateEmptyDefinition(result, coordinates)
4753
validateQueuedCoordinates(queue, coordinates)
4854
})
@@ -51,11 +57,11 @@ describe('DelayedComputePolicy', () => {
5157
const enqueueError = new Error('compute queue unavailable')
5258
queue.queue.rejects(enqueueError)
5359

54-
await expect(policy.compute(definitionService(), coordinates)).to.be.rejectedWith(enqueueError)
60+
await expect(policy.compute(definitionService, coordinates)).to.be.rejectedWith(enqueueError)
5561
})
5662

5763
describe('with enqueueCache', () => {
58-
let enqueueCache: { [K in keyof ICache]: sinon.SinonStub }
64+
let enqueueCache: { [K in keyof ISyncCache<boolean>]: sinon.SinonStub }
5965
let dedupPolicy: DelayedComputePolicy
6066

6167
beforeEach(async () => {
@@ -65,27 +71,108 @@ describe('DelayedComputePolicy', () => {
6571
})
6672

6773
it('skips enqueue for duplicate coordinates within cache TTL', async () => {
68-
await dedupPolicy.compute(definitionService(), coordinates)
69-
await dedupPolicy.compute(definitionService(), coordinates)
74+
await dedupPolicy.compute(definitionService, coordinates)
75+
await dedupPolicy.compute(definitionService, coordinates)
7076

7177
expect(queue.queue.calledOnce).to.be.true
7278
})
7379

74-
it('enqueues again after cache entry expires', async () => {
75-
await dedupPolicy.compute(definitionService(), coordinates)
76-
enqueueCache.delete.callsFake((key: string) => enqueueCache.get.withArgs(key).returns(null))
80+
it('passes the correct TTL to the cache set', async () => {
81+
await dedupPolicy.compute(definitionService, coordinates)
82+
83+
const [, , ttl] = enqueueCache.set.getCall(0).args
84+
expect(ttl).to.equal(DelayedComputePolicy._enqueueCacheTtlSeconds)
85+
})
86+
87+
it('enqueues again when cache returns null (stub-simulated expiry)', async () => {
88+
await dedupPolicy.compute(definitionService, coordinates)
7789
enqueueCache.get.returns(null)
7890

79-
await dedupPolicy.compute(definitionService(), coordinates)
91+
await dedupPolicy.compute(definitionService, coordinates)
8092

8193
expect(queue.queue.calledTwice).to.be.true
8294
})
8395

96+
it('enqueues only once when two requests arrive concurrently', async () => {
97+
await Promise.all([
98+
dedupPolicy.compute(definitionService, coordinates),
99+
dedupPolicy.compute(definitionService, coordinates)
100+
])
101+
102+
expect(queue.queue.calledOnce).to.be.true
103+
})
104+
105+
it('clears dedup marker when enqueue fails so retries can enqueue', async () => {
106+
const enqueueError = new Error('transient queue failure')
107+
queue.queue.onFirstCall().rejects(enqueueError)
108+
queue.queue.onSecondCall().resolves()
109+
110+
await expect(dedupPolicy.compute(definitionService, coordinates)).to.be.rejectedWith(enqueueError)
111+
await dedupPolicy.compute(definitionService, coordinates)
112+
113+
expect(enqueueCache.delete.calledOnceWith(coordinates.toString())).to.be.true
114+
expect(queue.queue.calledTwice).to.be.true
115+
})
116+
84117
it('enqueues independently for different coordinates', async () => {
85118
const other = EntityCoordinates.fromString('npm/npmjs/-/debug/4.3.4')
86119

87-
await dedupPolicy.compute(definitionService(), coordinates)
88-
await dedupPolicy.compute(definitionService(), other)
120+
await dedupPolicy.compute(definitionService, coordinates)
121+
await dedupPolicy.compute(definitionService, other)
122+
123+
expect(queue.queue.calledTwice).to.be.true
124+
})
125+
})
126+
127+
describe('with real cache and fake timers', () => {
128+
let clock: sinon.SinonFakeTimers
129+
let realCachePolicy: DelayedComputePolicy
130+
131+
beforeEach(async () => {
132+
clock = sinon.useFakeTimers()
133+
realCachePolicy = new DelayedComputePolicy({ logger: createMockLogger(), queue: () => queue })
134+
await realCachePolicy.initialize()
135+
})
136+
137+
afterEach(() => {
138+
clock.restore()
139+
})
140+
141+
it('enqueues again after cache TTL expires', async () => {
142+
await realCachePolicy.compute(definitionService, coordinates)
143+
expect(queue.queue.calledOnce).to.be.true
144+
145+
clock.tick(DelayedComputePolicy._enqueueCacheTtlSeconds * 1000 + 1)
146+
147+
await realCachePolicy.compute(definitionService, coordinates)
148+
expect(queue.queue.calledTwice).to.be.true
149+
})
150+
151+
it('does not enqueue again before cache TTL expires', async () => {
152+
await realCachePolicy.compute(definitionService, coordinates)
153+
154+
clock.tick(DelayedComputePolicy._enqueueCacheTtlSeconds * 1000 - 1)
155+
156+
await realCachePolicy.compute(definitionService, coordinates)
157+
expect(queue.queue.calledOnce).to.be.true
158+
})
159+
160+
it('enqueues only once when two requests arrive concurrently', async () => {
161+
await Promise.all([
162+
realCachePolicy.compute(definitionService, coordinates),
163+
realCachePolicy.compute(definitionService, coordinates)
164+
])
165+
166+
expect(queue.queue.calledOnce).to.be.true
167+
})
168+
169+
it('clears dedup marker when enqueue fails so retries can enqueue', async () => {
170+
const enqueueError = new Error('transient queue failure')
171+
queue.queue.onFirstCall().rejects(enqueueError)
172+
queue.queue.onSecondCall().resolves()
173+
174+
await expect(realCachePolicy.compute(definitionService, coordinates)).to.be.rejectedWith(enqueueError)
175+
await realCachePolicy.compute(definitionService, coordinates)
89176

90177
expect(queue.queue.calledTwice).to.be.true
91178
})
@@ -145,7 +232,7 @@ const createQueue = (): { [K in keyof IQueue]: sinon.SinonStub } => ({
145232
delete: sinon.stub().resolves()
146233
})
147234

148-
const definitionService = (): RecomputeContext =>
235+
const createDefinitionService = (): RecomputeContext =>
149236
({
150237
currentSchema: '1.7.0',
151238
buildEmptyDefinition: (coordinates: unknown) => ({
@@ -170,13 +257,17 @@ function validateQueuedCoordinates(queue: { [K in keyof IQueue]: sinon.SinonStub
170257
expect(queued._meta).to.be.undefined
171258
}
172259

173-
const createEnqueueCache = (): { [K in keyof ICache]: sinon.SinonStub } => {
174-
const store = new Map<string, unknown>()
260+
const createEnqueueCache = (): { [K in keyof ISyncCache<boolean>]: sinon.SinonStub } => {
261+
const store = new Map<string, boolean>()
175262
return {
176-
initialize: sinon.stub().resolves(),
177-
get: sinon.stub().callsFake((key: string) => store.get(key) ?? null),
178-
set: sinon.stub().callsFake((key: string, value: unknown) => store.set(key, value)),
179-
delete: sinon.stub().callsFake((key: string) => store.delete(key)),
180-
done: sinon.stub().resolves()
263+
get: sinon.stub().callsFake((key: string) => {
264+
return store.get(key) ?? null
265+
}),
266+
set: sinon.stub().callsFake((key: string, value: boolean) => {
267+
store.set(key, value)
268+
}),
269+
delete: sinon.stub().callsFake((key: string) => {
270+
store.delete(key)
271+
})
181272
}
182273
}

0 commit comments

Comments
 (0)