request-image.spec.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import { Context } from '@deepseek-ai/cordis'
  5. import sharp from 'sharp'
  6. import { afterEach, describe, expect, it, vi } from 'vitest'
  7. import { CompressionLimiter } from '../src/compression-limiter.ts'
  8. import LocalAttachmentStore from '../src/index.ts'
  9. const homes: string[] = []
  10. async function home(): Promise<string> {
  11. const dshHome = await mkdtemp(join(tmpdir(), 'dsh-request-image-'))
  12. homes.push(dshHome)
  13. return dshHome
  14. }
  15. async function store(): Promise<LocalAttachmentStore> {
  16. return new LocalAttachmentStore(new Context(), { dshHome: await home() })
  17. }
  18. async function image(width: number, height: number): Promise<Uint8Array> {
  19. return new Uint8Array(await sharp({
  20. create: { width, height, channels: 3, background: { r: 12, g: 34, b: 56 } },
  21. }).png().toBuffer())
  22. }
  23. async function complexOpaqueAlphaImage(width: number, height: number): Promise<Uint8Array> {
  24. const pixels = new Uint8Array(width * height * 4)
  25. let state = 0x2545f491
  26. for (let offset = 0; offset < pixels.length; offset += 4) {
  27. for (let channel = 0; channel < 3; channel += 1) {
  28. state ^= state << 13
  29. state ^= state >>> 17
  30. state ^= state << 5
  31. pixels[offset + channel] = state & 0xff
  32. }
  33. pixels[offset + 3] = 255
  34. }
  35. return new Uint8Array(await sharp(pixels, {
  36. raw: { width, height, channels: 4 },
  37. }).png().toBuffer())
  38. }
  39. afterEach(async () => {
  40. vi.unstubAllEnvs()
  41. await Promise.all(homes.splice(0).map(home => rm(home, { recursive: true, force: true })))
  42. })
  43. describe('local request-image cache', () => {
  44. it('rebuilds a cleared cache without moving or losing durable attachments', async () => {
  45. const fallbackHome = await home()
  46. vi.stubEnv('DSH_HOME', fallbackHome)
  47. try {
  48. const dshHome = await home()
  49. const attachments = new LocalAttachmentStore(new Context(), { dshHome })
  50. const attachment = await attachments.saveImage({ data: await image(64, 32), mediaType: 'image/png' })
  51. const stored = await attachments.readImage(attachment)
  52. const fileData = Uint8Array.of(0, 1, 2, 255)
  53. const file = await attachments.saveFile({ data: fileData, name: 'notes.bin' })
  54. const policy = { width: 22, height: 11, maxBytes: 4_096 }
  55. const initial = await attachments.readImageRequest(attachment, policy)
  56. const hash = String(initial.variantId).slice('sha256:'.length)
  57. const cacheRoot = join(dshHome, 'cache')
  58. const path = join(cacheRoot, 'attachments', 'request-images', hash.slice(0, 2), hash)
  59. expect(attachments.root).toBe(join(dshHome, 'attachments', 'v1'))
  60. await expect(readFile(path)).resolves.toEqual(Buffer.from(initial.data))
  61. await expect(readFile(join(attachments.root, 'request-images', hash.slice(0, 2), hash)))
  62. .rejects.toMatchObject({ code: 'ENOENT' })
  63. await rm(cacheRoot, { recursive: true })
  64. const reopened = new LocalAttachmentStore(new Context(), { dshHome })
  65. await expect(reopened.readImage(attachment)).resolves.toEqual(stored)
  66. await expect(readFile(reopened.fileHostPath(file))).resolves.toEqual(Buffer.from(fileData))
  67. await expect(reopened.readImageRequest(attachment, policy)).resolves.toEqual(initial)
  68. await expect(readFile(path)).resolves.toEqual(Buffer.from(initial.data))
  69. await expect(readdir(fallbackHome)).resolves.toEqual([])
  70. } finally {
  71. vi.unstubAllEnvs()
  72. }
  73. })
  74. it('passes through an in-budget attachment and composes ordered request reads', async () => {
  75. const attachments = await store()
  76. const first = await attachments.saveImage({ data: await image(8, 4), mediaType: 'image/png' })
  77. const second = await attachments.saveImage({ data: await image(4, 8), mediaType: 'image/png' })
  78. const firstStored = await attachments.readImage(first)
  79. const policy = { width: 8, height: 8, maxBytes: 1024 * 1024 }
  80. const request = await attachments.readImageRequest(first, policy)
  81. const batch = await Promise.all([first, second].map(
  82. attachment => attachments.readImageRequest(attachment, policy),
  83. ))
  84. expect(request.data).toEqual(firstStored.data)
  85. expect(batch.map(value => value.attachment.attachmentId)).toEqual([first.attachmentId, second.attachmentId])
  86. })
  87. it('rejects invalid request targets', async () => {
  88. const attachments = await store()
  89. const attachment = await attachments.saveImage({ data: await image(8, 4), mediaType: 'image/png' })
  90. await expect(attachments.readImageRequest(attachment, { width: 0, height: 4, maxBytes: 100 }))
  91. .rejects.toThrow('Image request width must be a positive integer')
  92. await expect(attachments.readImageRequest(attachment, { width: 8, height: 1.5, maxBytes: 100 }))
  93. .rejects.toThrow('Image request height must be a positive integer')
  94. await expect(attachments.readImageRequest(attachment, { width: 8, height: 4, maxBytes: 0 }))
  95. .rejects.toThrow('Image request maxBytes must be a positive integer')
  96. })
  97. it('resizes by the long edge to the exact target and keys the cache by target', async () => {
  98. const attachments = await store()
  99. const maxBytes = 2 * 1024 * 1024
  100. const square = await attachments.saveImage({ data: await image(2048, 2048), mediaType: 'image/png' })
  101. const small = await attachments.saveImage({ data: await image(800, 800), mediaType: 'image/png' })
  102. const thin = await attachments.saveImage({ data: await image(8000, 40), mediaType: 'image/png' })
  103. const wide = await attachments.saveImage({ data: await image(1920, 1080), mediaType: 'image/png' })
  104. const tall = await attachments.saveImage({ data: await image(1080, 1920), mediaType: 'image/png' })
  105. const squareRequest = await attachments.readImageRequest(square, { width: 1302, height: 1302, maxBytes })
  106. const smallRequest = await attachments.readImageRequest(small, { width: 800, height: 800, maxBytes })
  107. const thinRequest = await attachments.readImageRequest(thin, { width: 4096, height: 20, maxBytes })
  108. const wideRequest = await attachments.readImageRequest(wide, { width: 1708, height: 961, maxBytes })
  109. const tallRequest = await attachments.readImageRequest(tall, { width: 961, height: 1708, maxBytes })
  110. const smaller = await attachments.readImageRequest(square, { width: 1024, height: 1024, maxBytes })
  111. const enlarged = await attachments.readImageRequest(thin, { width: 9000, height: 45, maxBytes })
  112. expect(squareRequest).toMatchObject({ width: 1302, height: 1302, mediaType: 'image/jpeg' })
  113. expect(smallRequest).toMatchObject({ width: 800, height: 800, mediaType: 'image/png' })
  114. expect(smallRequest.data).toEqual((await attachments.readImage(small)).data)
  115. expect(thinRequest).toMatchObject({ width: 4096, height: 20 })
  116. expect(wideRequest).toMatchObject({ width: 1708, height: 961 })
  117. expect(tallRequest).toMatchObject({ width: 961, height: 1708 })
  118. expect(enlarged).toMatchObject({ width: 8000, height: 40 })
  119. expect(smaller.variantId).not.toBe(squareRequest.variantId)
  120. expect(enlarged.variantId).not.toBe(thinRequest.variantId)
  121. })
  122. it('encodes the rounded short edge at the route target', async () => {
  123. const attachments = await store()
  124. const attachment = await attachments.saveImage({ data: await image(1224, 1429), mediaType: 'image/png' })
  125. const request = await attachments.readImageRequest(attachment, {
  126. width: 1187, height: 1386, maxBytes: 2 * 1024 * 1024,
  127. })
  128. expect(request).toMatchObject({ width: 1187, height: 1386 })
  129. await expect(sharp(request.data).metadata()).resolves.toMatchObject({ width: 1187, height: 1386 })
  130. })
  131. it('keeps the smallest ladder output when the encoded-byte target is unreachable', async () => {
  132. const attachments = await store()
  133. const attachment = await attachments.saveImage({ data: await image(1, 1), mediaType: 'image/png' })
  134. const request = await attachments.readImageRequest(attachment, { width: 1, height: 1, maxBytes: 1 })
  135. expect(request.mediaType).toBe('image/jpeg')
  136. expect(request.bytes).toBeGreaterThan(1)
  137. expect(request).toMatchObject({ width: 1, height: 1 })
  138. })
  139. it('regenerates invalid, oversized, incompatible, or mismatched cached variants', async () => {
  140. const dshHome = await home()
  141. const attachments = new LocalAttachmentStore(new Context(), { dshHome })
  142. const attachment = await attachments.saveImage({ data: await image(64, 32), mediaType: 'image/png' })
  143. const policy = { width: 22, height: 11, maxBytes: 4_096 }
  144. const initial = await attachments.readImageRequest(attachment, policy)
  145. const hash = String(initial.variantId).slice('sha256:'.length)
  146. const path = join(dshHome, 'cache', 'attachments', 'request-images', hash.slice(0, 2), hash)
  147. const noisyPixels = new Uint8Array(64 * 64 * 3)
  148. let state = 0x2545f491
  149. for (let index = 0; index < noisyPixels.length; index += 1) {
  150. state ^= state << 13
  151. state ^= state >>> 17
  152. state ^= state << 5
  153. noisyPixels[index] = state & 0xff
  154. }
  155. const oversized = new Uint8Array(await sharp(noisyPixels, {
  156. raw: { width: 64, height: 64, channels: 3 },
  157. }).png().toBuffer())
  158. const depth16 = new Uint8Array(await sharp({
  159. create: { width: 16, height: 8, channels: 3, background: { r: 1, g: 2, b: 3 } },
  160. }).toColourspace('rgb16').png().toBuffer())
  161. const cmyk = new Uint8Array(await sharp({
  162. create: { width: 16, height: 8, channels: 3, background: { r: 1, g: 2, b: 3 } },
  163. }).toColourspace('cmyk').jpeg().toBuffer())
  164. const tooWide = await image(23, 11)
  165. const unexpectedAlpha = new Uint8Array(await sharp({
  166. create: { width: 16, height: 8, channels: 4, background: { r: 1, g: 2, b: 3, alpha: 0.5 } },
  167. }).png().toBuffer())
  168. for (const invalid of [
  169. oversized,
  170. depth16,
  171. cmyk,
  172. tooWide,
  173. unexpectedAlpha,
  174. Uint8Array.of(1, 2, 3),
  175. ]) {
  176. await writeFile(path, invalid)
  177. const regenerated = await attachments.readImageRequest(attachment, policy)
  178. expect(regenerated.data).toEqual(initial.data)
  179. }
  180. })
  181. it('derives stable square and wide previews and separates route budgets in the cache key', async () => {
  182. const attachments = await store()
  183. const square = await attachments.saveImage({
  184. data: await image(2048, 2048), mediaType: 'image/png', name: 'square.png',
  185. })
  186. const wide = await attachments.saveImage({
  187. data: await image(2048, 1024), mediaType: 'image/png', name: 'wide.png',
  188. })
  189. const squareRequest = await attachments.readImageRequest(square, { width: 800, height: 800, maxBytes: 1024 * 1024 })
  190. const wideRequest = await attachments.readImageRequest(wide, { width: 1130, height: 565, maxBytes: 1024 * 1024 })
  191. const repeated = await attachments.readImageRequest(wide, { width: 1130, height: 565, maxBytes: 1024 * 1024 })
  192. const low = await attachments.readImageRequest(wide, { width: 724, height: 362, maxBytes: 1024 * 1024 })
  193. expect(squareRequest).toMatchObject({ width: 800, height: 800 })
  194. expect(wideRequest).toMatchObject({ width: 1130, height: 565 })
  195. expect(repeated.variantId).toBe(wideRequest.variantId)
  196. expect(repeated.data).toEqual(wideRequest.data)
  197. expect(Buffer.from(repeated.data).toString('base64')).toBe(Buffer.from(wideRequest.data).toString('base64'))
  198. expect(low.variantId).not.toBe(wideRequest.variantId)
  199. expect(low.width * low.height).toBeLessThanOrEqual(512 * 512 + low.width)
  200. })
  201. it('routes opaque pixels to JPEG and preserves alpha on the WebP ladder', async () => {
  202. const attachments = await store()
  203. const side = 256
  204. const photoPixels = new Uint8Array(side * side * 3)
  205. const alphaPixels = new Uint8Array(side * side * 4)
  206. let state = 0x2545f491
  207. for (let pixel = 0; pixel < side * side; pixel += 1) {
  208. state ^= state << 13
  209. state ^= state >>> 17
  210. state ^= state << 5
  211. const photo = pixel * 3
  212. const alpha = pixel * 4
  213. photoPixels[photo] = state & 0xff
  214. photoPixels[photo + 1] = state >> 8 & 0xff
  215. photoPixels[photo + 2] = state >> 16 & 0xff
  216. alphaPixels[alpha] = photoPixels[photo] ?? 0
  217. alphaPixels[alpha + 1] = photoPixels[photo + 1] ?? 0
  218. alphaPixels[alpha + 2] = photoPixels[photo + 2] ?? 0
  219. alphaPixels[alpha + 3] = pixel & 0xff
  220. }
  221. const photoSource = new Uint8Array(await sharp(photoPixels, {
  222. raw: { width: side, height: side, channels: 3 },
  223. }).png().toBuffer())
  224. const alphaSource = new Uint8Array(await sharp(alphaPixels, {
  225. raw: { width: side, height: side, channels: 4 },
  226. }).png().toBuffer())
  227. const photo = await attachments.saveImage({ data: photoSource, mediaType: 'image/png' })
  228. const alpha = await attachments.saveImage({ data: alphaSource, mediaType: 'image/png' })
  229. const photoRequest = await attachments.readImageRequest(photo, { width: 128, height: 128, maxBytes: 1024 * 1024 })
  230. const alphaRequest = await attachments.readImageRequest(alpha, { width: 128, height: 128, maxBytes: 4_096 })
  231. expect(photoRequest.mediaType).toBe('image/jpeg')
  232. expect(alphaRequest.mediaType).toBe('image/webp')
  233. expect(alphaRequest.bytes).toBeGreaterThan(4_096)
  234. expect(alphaRequest).toMatchObject({ width: 128, height: 128 })
  235. await expect(sharp(alphaRequest.data).metadata()).resolves.toMatchObject({ hasAlpha: true, depth: 'uchar', space: 'srgb' })
  236. })
  237. it.each([3, 4] as const)('projects a 16-bit %s-channel PNG as a bounded 8-bit request image', async (channels) => {
  238. const attachments = await store()
  239. const source = new Uint8Array(await sharp({
  240. create: { width: 64, height: 32, channels, background: { r: 12, g: 34, b: 56, alpha: 0.5 } },
  241. }).toColourspace('rgb16').png().toBuffer())
  242. const attachment = await attachments.saveImage({ data: source, mediaType: 'image/png' })
  243. const request = await attachments.readImageRequest(attachment, { width: 22, height: 11, maxBytes: 1024 * 1024 })
  244. expect(request.bytes).toBeLessThanOrEqual(1024 * 1024)
  245. expect(request.width * request.height).toBeLessThanOrEqual(16 * 16)
  246. await expect(sharp(request.data).metadata()).resolves.toMatchObject({
  247. depth: 'uchar', space: 'srgb', hasAlpha: channels === 4,
  248. })
  249. })
  250. it('accepts a resized WebP request version that omits an all-opaque alpha plane', async () => {
  251. const attachments = await store()
  252. const source = await complexOpaqueAlphaImage(64, 32)
  253. const attachment = await attachments.saveImage({ data: source, mediaType: 'image/png' })
  254. const request = await attachments.readImageRequest(attachment, { width: 22, height: 11, maxBytes: 1024 * 1024 })
  255. expect(request.mediaType).toBe('image/webp')
  256. await expect(sharp(request.data).metadata()).resolves.toMatchObject({ hasAlpha: false })
  257. })
  258. it('keeps a complex 640,000-pixel request version below 1 MiB', async () => {
  259. const attachments = await store()
  260. const side = 1024
  261. const pixels = new Uint8Array(side * side * 3)
  262. let state = 0x6d2b79f5
  263. for (let index = 0; index < pixels.length; index += 1) {
  264. state ^= state << 13
  265. state ^= state >>> 17
  266. state ^= state << 5
  267. pixels[index] = state & 0xff
  268. }
  269. const source = new Uint8Array(await sharp(pixels, {
  270. raw: { width: side, height: side, channels: 3 },
  271. }).png().toBuffer())
  272. const attachment = await attachments.saveImage({ data: source, mediaType: 'image/png' })
  273. const request = await attachments.readImageRequest(attachment, { width: 800, height: 800, maxBytes: 1024 * 1024 })
  274. expect(request).toMatchObject({ width: 800, height: 800 })
  275. expect(request.bytes).toBeLessThanOrEqual(1024 * 1024)
  276. })
  277. it('shares one request transform between concurrent callers without sharing cancellation', async () => {
  278. const attachments = await store()
  279. const attachment = await attachments.saveImage({
  280. data: await image(2048, 1024), mediaType: 'image/png', name: 'shared.png',
  281. })
  282. const run = vi.spyOn(CompressionLimiter.prototype, 'run')
  283. const controller = new AbortController()
  284. const policy = { width: 1130, height: 565, maxBytes: 1024 * 1024 }
  285. const cancelled = attachments.readImageRequest(attachment, policy, controller.signal)
  286. const completed = attachments.readImageRequest(attachment, policy)
  287. const reason = new Error('cancel one waiter')
  288. controller.abort(reason)
  289. await expect(cancelled).rejects.toBe(reason)
  290. await expect(completed).resolves.toMatchObject({ width: 1130, height: 565 })
  291. expect(run).toHaveBeenCalledTimes(1)
  292. run.mockRestore()
  293. })
  294. it('aborts the underlying request transform after its only waiter cancels', async () => {
  295. const attachments = await store()
  296. const attachment = await attachments.saveImage({
  297. data: await image(2048, 1024), mediaType: 'image/png', name: 'cancelled.png',
  298. })
  299. let readSignal: AbortSignal | undefined
  300. const read = vi.spyOn(attachments, 'readImage').mockImplementation((_ref, signal) => {
  301. readSignal = signal
  302. return new Promise((_resolve, reject) => {
  303. signal?.addEventListener('abort', () => {
  304. reject(new Error('request transform aborted', { cause: signal.reason }))
  305. }, { once: true })
  306. })
  307. })
  308. const controller = new AbortController()
  309. const request = attachments.readImageRequest(
  310. attachment,
  311. { width: 1130, height: 565, maxBytes: 1024 * 1024 },
  312. controller.signal,
  313. )
  314. await vi.waitFor(() => {
  315. expect(read).toHaveBeenCalledTimes(1)
  316. })
  317. const reason = new Error('cancel only transform waiter')
  318. controller.abort(reason)
  319. await expect(request).rejects.toBe(reason)
  320. expect(readSignal?.reason).toBe(reason)
  321. })
  322. it('normalizes a non-Error cancellation and replaces an aborted shared transform', async () => {
  323. const attachments = await store()
  324. const attachment = await attachments.saveImage({
  325. data: await image(2048, 1024), mediaType: 'image/png', name: 'replace.png',
  326. })
  327. const actualRead = attachments.readImage.bind(attachments)
  328. let calls = 0
  329. vi.spyOn(attachments, 'readImage').mockImplementation((ref, signal) => {
  330. calls += 1
  331. if (calls === 1) {
  332. return new Promise((_resolve, reject) => {
  333. signal?.addEventListener('abort', () => {
  334. reject(new Error('request transform aborted', { cause: signal.reason }))
  335. }, { once: true })
  336. })
  337. }
  338. return actualRead(ref, signal)
  339. })
  340. const controller = new AbortController()
  341. const policy = { width: 1130, height: 565, maxBytes: 1024 * 1024 }
  342. const cancelled = attachments.readImageRequest(attachment, policy, controller.signal)
  343. await vi.waitFor(() => {
  344. expect(calls).toBe(1)
  345. })
  346. controller.abort('cancelled')
  347. const replacement = attachments.readImageRequest(attachment, policy)
  348. await expect(cancelled).rejects.toMatchObject({
  349. message: 'Attachment request cancelled with a non-Error reason.',
  350. cause: 'cancelled',
  351. })
  352. await expect(replacement).resolves.toMatchObject({ width: 1130, height: 565 })
  353. expect(calls).toBe(2)
  354. })
  355. })