upstreamReadCache.ts 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. import { AsyncLocalStorage } from 'node:async_hooks'
  2. import { HttpError } from './errors.js'
  3. import type { UpstreamResponse } from './upstream.js'
  4. export interface ReadCacheContext { scope: string; fresh?: boolean }
  5. export const readCacheContext = new AsyncLocalStorage<ReadCacheContext>()
  6. export interface ReadPolicy { tags: string[]; freshMs: number; staleMs: number }
  7. interface Entry { value: UpstreamResponse; policy: ReadPolicy; savedAt: number; bytes: number }
  8. interface Flight { promise: Promise<UpstreamResponse>; tags: string[]; invalidated: boolean }
  9. /** Application-data cache. Only authenticated HTTP request scopes opt in; background
  10. * recovery, authentication and command acknowledgement reads remain authoritative. */
  11. export class UpstreamReadCache {
  12. private entries = new Map<string, Entry>()
  13. private flights = new Map<string, Flight>()
  14. private bytes = 0
  15. private loading = 0
  16. private closed = false
  17. private counters = { hits: 0, misses: 0, staleHits: 0, coalesced: 0, evictions: 0 }
  18. constructor(readonly now = Date.now, readonly maxBytes = 64 * 1024 * 1024,
  19. readonly maxEntries = 512, readonly maxEntryBytes = 2 * 1024 * 1024) {}
  20. stats() { return { ...this.counters, entries: this.entries.size, bytes: this.bytes, inFlight: this.loading } }
  21. async read(key: string, policy: ReadPolicy, load: () => Promise<UpstreamResponse>): Promise<UpstreamResponse> {
  22. const entry = this.entries.get(key)
  23. if (entry) {
  24. const age = this.now() - entry.savedAt
  25. if (age < policy.freshMs) {
  26. this.counters.hits++; this.touch(key, entry)
  27. return copy(entry.value)
  28. }
  29. if (age < policy.freshMs + policy.staleMs) {
  30. this.counters.staleHits++; this.touch(key, entry)
  31. if (!this.flights.has(key) && this.loading < 128) void this.refresh(key, policy, load).catch(() => {})
  32. return copy(entry.value)
  33. }
  34. this.remove(key)
  35. }
  36. const flight = this.flights.get(key)
  37. if (flight) { this.counters.coalesced++; return copy(await flight.promise) }
  38. this.counters.misses++
  39. return copy(await this.refresh(key, policy, load))
  40. }
  41. invalidate(tags?: readonly string[]): void {
  42. const matches = (entryTags: string[]) => !tags || entryTags.some(tag => tags.includes(tag))
  43. for (const [key, entry] of this.entries) if (matches(entry.policy.tags)) this.remove(key)
  44. for (const [key, flight] of this.flights) if (matches(flight.tags)) {
  45. flight.invalidated = true
  46. this.flights.delete(key) // A newer request must not join an obsolete snapshot.
  47. }
  48. }
  49. close(): void { this.closed = true; this.invalidate() }
  50. private refresh(key: string, policy: ReadPolicy, load: () => Promise<UpstreamResponse>): Promise<UpstreamResponse> {
  51. if (this.loading >= 128) return Promise.reject(new HttpError(429, 'Too many pending reads', 'read_capacity'))
  52. this.loading++
  53. const flight: Flight = { tags: policy.tags, invalidated: false, promise: Promise.resolve(undefined as never) }
  54. // Defer load until the flight is registered, so synchronous invalidations cannot be lost.
  55. flight.promise = Promise.resolve().then(load).then(value => {
  56. if (!flight.invalidated && !this.closed && cacheable(value) && value.body.byteLength <= this.maxEntryBytes) {
  57. this.remove(key)
  58. const bytes = value.body.byteLength + key.length * 2 + 512
  59. this.entries.set(key, { value: copy(value), policy, savedAt: this.now(), bytes })
  60. this.bytes += bytes
  61. while (this.entries.size > this.maxEntries || this.bytes > this.maxBytes) {
  62. this.remove(this.entries.keys().next().value!); this.counters.evictions++
  63. }
  64. }
  65. return value
  66. }).finally(() => {
  67. this.loading--
  68. if (this.flights.get(key) === flight) this.flights.delete(key)
  69. })
  70. this.flights.set(key, flight)
  71. return flight.promise
  72. }
  73. private touch(key: string, entry: Entry): void { this.entries.delete(key); this.entries.set(key, entry) }
  74. private remove(key: string): void {
  75. const entry = this.entries.get(key)
  76. if (entry) { this.bytes -= entry.bytes; this.entries.delete(key) }
  77. }
  78. }
  79. function copy(value: UpstreamResponse): UpstreamResponse {
  80. return { status: value.status, headers: new Headers(value.headers), body: Buffer.from(value.body) }
  81. }
  82. function cacheable(value: UpstreamResponse): boolean {
  83. return value.status === 200
  84. && (value.headers.get('content-type') ?? '').includes('application/json')
  85. && !/\bno-store\b/i.test(value.headers.get('cache-control') ?? '')
  86. && value.headers.get('vary') !== '*'
  87. && !value.headers.has('set-cookie')
  88. }
  89. export function readPolicy(path: string, search?: URLSearchParams): ReadPolicy | undefined {
  90. if (path === '/api/profiles') {
  91. return { tags: ['profiles'], freshMs: 5_000, staleMs: 15_000 }
  92. }
  93. if (path === '/api/model/options') return { tags: ['models'], freshMs: 30_000, staleMs: 60_000 }
  94. if (path === '/api/sessions' || path === '/api/profiles/sessions') {
  95. return { tags: ['sessions', 'session-list'], freshMs: 2_000, staleMs: 0 }
  96. }
  97. const session = /^\/api\/sessions\/([^/]+)(?:\/messages)?$/.exec(path)
  98. if (session && !['search', 'unread', 'prune', 'export'].includes(session[1]!)) {
  99. const oldPage = Number(search?.get('offset') ?? 0) > 0
  100. return { tags: ['sessions', `session:${decodeURIComponent(session[1]!)}`], freshMs: oldPage ? 10_000 : 1_000, staleMs: 0 }
  101. }
  102. }
  103. export function mutationTags(path: string): string[] | undefined {
  104. if (path.startsWith('/auth/') || path.startsWith('/api/auth/')) return undefined
  105. const session = /^\/api\/sessions\/([^/]+)/.exec(path)
  106. if (session) return ['session-list', `session:${decodeURIComponent(session[1]!)}`]
  107. if (path.startsWith('/api/sessions')) return ['sessions']
  108. if (/^\/api\/(profiles|model|config|env|providers|dashboard\/agent-plugins)/.test(path)) return ['profiles', 'models', 'sessions', 'groups']
  109. return undefined
  110. }