Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions providers/caching/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,18 @@ export interface ICache {
*/
delete(item: string): Promise<void> | void
}

/**
* Synchronous cache interface for use cases where get/set must be atomic within
* a single event loop turn (e.g. dedup checks before an async operation).
*/
export interface ISyncCache<ValueType> {
/** Retrieves an item synchronously. Returns null if not found or expired. */
get(item: string): ValueType | null

/** Stores an item synchronously with an optional TTL in seconds. */
set(item: string, value: ValueType, ttlSeconds?: number): undefined

/** Removes an item synchronously. */
delete(item: string): undefined
}
10 changes: 6 additions & 4 deletions providers/caching/memory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@

import { Cache } from 'memory-cache'

import type { BaseCacheOptions, ICache } from './index.js'
import type { BaseCacheOptions, ICache, ISyncCache } from './index.js'

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

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

Expand All @@ -31,14 +31,16 @@ class MemoryCache implements ICache {
}

/** Stores an item in the cache */
set(item: string, value: any, ttlSeconds: number | null = null): void {
set(item: string, value: any, ttlSeconds: number | null = null): undefined {
const expiration = ttlSeconds || this.defaultTtlSeconds
this.cache.put(item, value, expiration ? expiration * 1000 : undefined)
return undefined
}

/** Removes an item from the cache */
delete(item: string): void {
delete(item: string): undefined {
this.cache.del(item)
return undefined
}
}

Expand Down
22 changes: 14 additions & 8 deletions providers/recompute/delayedComputePolicy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import type { Definition, DefinitionService, RecomputeContext } from '../../business/definitionService.ts'
import type { EntityCoordinates } from '../../lib/entityCoordinates.ts'
import type { ICache } from '../caching/index.js'
import type { ISyncCache } from '../caching/index.js'
import Cache from '../caching/memory.ts'
import type { Logger } from '../logging/index.js'
import logger from '../logging/logger.ts'
Expand All @@ -15,7 +15,7 @@ import { SkipUpgradePolicy } from './skipUpgradePolicy.ts'

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

class DelayedComputePolicy implements MissingDefinitionComputePolicy {
Expand All @@ -24,7 +24,7 @@ class DelayedComputePolicy implements MissingDefinitionComputePolicy {

options: DelayedComputePolicyOptions
logger: Logger
declare _enqueueCache: ICache
declare _enqueueCache: ISyncCache<boolean>
declare _compute: IQueue

constructor(options: DelayedComputePolicyOptions) {
Expand Down Expand Up @@ -54,14 +54,20 @@ class DelayedComputePolicy implements MissingDefinitionComputePolicy {
throw new Error('Compute queue is not set. DelayedComputePolicy.initialize() must be called before compute()')
}
const key = coordinates.toString()
const alreadyQueued = await this._enqueueCache.get(key)
if (alreadyQueued) {
const alreadyQueued = this._enqueueCache.get(key)
if (alreadyQueued === true) {
this.logger.debug('Skipped duplicate enqueue for delayed definition compute', { coordinates: key })
return
}
const message = this._constructMessage(coordinates)
await this._compute.queue(message)
await this._enqueueCache.set(key, true, DelayedComputePolicy._enqueueCacheTtlSeconds)
this._enqueueCache.set(key, true, DelayedComputePolicy._enqueueCacheTtlSeconds)
try {
const message = this._constructMessage(coordinates)
await this._compute.queue(message)
} catch (error) {
// Roll back optimistic dedup marker so retries can enqueue after transient queue failures.
this._enqueueCache.delete(key)
throw error
}
this.logger.info('Queued for delayed definition compute', {
coordinates: key
})
Expand Down
133 changes: 112 additions & 21 deletions test/providers/recompute/delayedComputePolicy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { expect } from 'chai'
import sinon from 'sinon'
import type { Definition, DefinitionService, RecomputeContext } from '../../../business/definitionService.ts'
import EntityCoordinates from '../../../lib/entityCoordinates.ts'
import type { ICache } from '../../../providers/caching/index.js'
import type { ISyncCache } from '../../../providers/caching/index.js'
import type { IQueue } from '../../../providers/queueing/index.js'
import { DelayedComputePolicy } from '../../../providers/recompute/delayedComputePolicy.ts'
import { createMockLogger } from '../../helpers/mockLogger.ts'
Expand All @@ -30,19 +30,25 @@ describe('DelayedComputePolicy', () => {
})

describe('compute()', () => {
let definitionService: RecomputeContext

beforeEach(() => {
definitionService = createDefinitionService()
})

it('throws if called before initialize()', async () => {
const uninitializedPolicy = new DelayedComputePolicy({
logger: createMockLogger(),
queue: () => queue
})

await expect(uninitializedPolicy.compute(definitionService(), coordinates)).to.be.rejectedWith(
await expect(uninitializedPolicy.compute(definitionService, coordinates)).to.be.rejectedWith(
'DelayedComputePolicy.initialize() must be called before compute()'
)
})

it('enqueues coordinates and returns placeholder definition', async () => {
const result = await policy.compute(definitionService(), coordinates)
const result = await policy.compute(definitionService, coordinates)
validateEmptyDefinition(result, coordinates)
validateQueuedCoordinates(queue, coordinates)
})
Expand All @@ -51,11 +57,11 @@ describe('DelayedComputePolicy', () => {
const enqueueError = new Error('compute queue unavailable')
queue.queue.rejects(enqueueError)

await expect(policy.compute(definitionService(), coordinates)).to.be.rejectedWith(enqueueError)
await expect(policy.compute(definitionService, coordinates)).to.be.rejectedWith(enqueueError)
})

describe('with enqueueCache', () => {
let enqueueCache: { [K in keyof ICache]: sinon.SinonStub }
let enqueueCache: { [K in keyof ISyncCache<boolean>]: sinon.SinonStub }
let dedupPolicy: DelayedComputePolicy

beforeEach(async () => {
Expand All @@ -65,27 +71,108 @@ describe('DelayedComputePolicy', () => {
})

it('skips enqueue for duplicate coordinates within cache TTL', async () => {
await dedupPolicy.compute(definitionService(), coordinates)
await dedupPolicy.compute(definitionService(), coordinates)
await dedupPolicy.compute(definitionService, coordinates)
await dedupPolicy.compute(definitionService, coordinates)

expect(queue.queue.calledOnce).to.be.true
})

it('enqueues again after cache entry expires', async () => {
await dedupPolicy.compute(definitionService(), coordinates)
enqueueCache.delete.callsFake((key: string) => enqueueCache.get.withArgs(key).returns(null))
it('passes the correct TTL to the cache set', async () => {
await dedupPolicy.compute(definitionService, coordinates)

const [, , ttl] = enqueueCache.set.getCall(0).args
expect(ttl).to.equal(DelayedComputePolicy._enqueueCacheTtlSeconds)
})

it('enqueues again when cache returns null (stub-simulated expiry)', async () => {
await dedupPolicy.compute(definitionService, coordinates)
enqueueCache.get.returns(null)

await dedupPolicy.compute(definitionService(), coordinates)
await dedupPolicy.compute(definitionService, coordinates)

expect(queue.queue.calledTwice).to.be.true
})

it('enqueues only once when two requests arrive concurrently', async () => {
await Promise.all([
dedupPolicy.compute(definitionService, coordinates),
dedupPolicy.compute(definitionService, coordinates)
])

expect(queue.queue.calledOnce).to.be.true
})

it('clears dedup marker when enqueue fails so retries can enqueue', async () => {
const enqueueError = new Error('transient queue failure')
queue.queue.onFirstCall().rejects(enqueueError)
queue.queue.onSecondCall().resolves()

await expect(dedupPolicy.compute(definitionService, coordinates)).to.be.rejectedWith(enqueueError)
await dedupPolicy.compute(definitionService, coordinates)

expect(enqueueCache.delete.calledOnceWith(coordinates.toString())).to.be.true
expect(queue.queue.calledTwice).to.be.true
})

it('enqueues independently for different coordinates', async () => {
const other = EntityCoordinates.fromString('npm/npmjs/-/debug/4.3.4')

await dedupPolicy.compute(definitionService(), coordinates)
await dedupPolicy.compute(definitionService(), other)
await dedupPolicy.compute(definitionService, coordinates)
await dedupPolicy.compute(definitionService, other)

expect(queue.queue.calledTwice).to.be.true
})
})

describe('with real cache and fake timers', () => {
let clock: sinon.SinonFakeTimers
let realCachePolicy: DelayedComputePolicy

beforeEach(async () => {
clock = sinon.useFakeTimers()
realCachePolicy = new DelayedComputePolicy({ logger: createMockLogger(), queue: () => queue })
await realCachePolicy.initialize()
})

afterEach(() => {
clock.restore()
})

it('enqueues again after cache TTL expires', async () => {
await realCachePolicy.compute(definitionService, coordinates)
expect(queue.queue.calledOnce).to.be.true

clock.tick(DelayedComputePolicy._enqueueCacheTtlSeconds * 1000 + 1)

await realCachePolicy.compute(definitionService, coordinates)
expect(queue.queue.calledTwice).to.be.true
})

it('does not enqueue again before cache TTL expires', async () => {
await realCachePolicy.compute(definitionService, coordinates)

clock.tick(DelayedComputePolicy._enqueueCacheTtlSeconds * 1000 - 1)

await realCachePolicy.compute(definitionService, coordinates)
expect(queue.queue.calledOnce).to.be.true
})

it('enqueues only once when two requests arrive concurrently', async () => {
await Promise.all([
realCachePolicy.compute(definitionService, coordinates),
realCachePolicy.compute(definitionService, coordinates)
])

expect(queue.queue.calledOnce).to.be.true
})

it('clears dedup marker when enqueue fails so retries can enqueue', async () => {
const enqueueError = new Error('transient queue failure')
queue.queue.onFirstCall().rejects(enqueueError)
queue.queue.onSecondCall().resolves()

await expect(realCachePolicy.compute(definitionService, coordinates)).to.be.rejectedWith(enqueueError)
await realCachePolicy.compute(definitionService, coordinates)

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

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

const createEnqueueCache = (): { [K in keyof ICache]: sinon.SinonStub } => {
const store = new Map<string, unknown>()
const createEnqueueCache = (): { [K in keyof ISyncCache<boolean>]: sinon.SinonStub } => {
const store = new Map<string, boolean>()
return {
initialize: sinon.stub().resolves(),
get: sinon.stub().callsFake((key: string) => store.get(key) ?? null),
set: sinon.stub().callsFake((key: string, value: unknown) => store.set(key, value)),
delete: sinon.stub().callsFake((key: string) => store.delete(key)),
done: sinon.stub().resolves()
get: sinon.stub().callsFake((key: string) => {
return store.get(key) ?? null
}),
set: sinon.stub().callsFake((key: string, value: boolean) => {
store.set(key, value)
}),
delete: sinon.stub().callsFake((key: string) => {
store.delete(key)
})
}
}
Loading