file-upload-http.host.spec.ts 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. import { runInNewContext } from 'node:vm'
  2. import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
  3. import { describe, expect, it, vi } from 'vitest'
  4. import type { Mock } from 'vitest'
  5. import { handleFileUploadHttp } from '../src/http-route.ts'
  6. import type { FileUploads } from '../src/index.ts'
  7. function request(input: {
  8. method?: string
  9. sessionId?: string
  10. name?: string
  11. contentType?: string
  12. body?: Uint8Array
  13. } = {}): Request {
  14. const query = new URLSearchParams()
  15. if (input.sessionId !== undefined) query.set('sessionId', input.sessionId)
  16. if (input.name !== undefined) query.set('name', input.name)
  17. const suffix = query.size === 0 ? '' : `?${query.toString()}`
  18. return new Request(`http://host/api/session/uploadFileBinary${suffix}`, {
  19. method: input.method ?? 'POST',
  20. headers: input.contentType === undefined ? {} : { 'content-type': input.contentType },
  21. ...(input.body === undefined ? {} : { body: new Blob([Uint8Array.from(input.body).buffer]) }),
  22. })
  23. }
  24. function uploads(result: unknown): FileUploads & {
  25. uploadStream: Mock<FileUploads['uploadStream']>
  26. uploadedChunks: Uint8Array[]
  27. } {
  28. const uploadedChunks: Uint8Array[] = []
  29. const uploadStream = vi.fn<FileUploads['uploadStream']>(async (input) => {
  30. for await (const chunk of input.data) uploadedChunks.push(chunk)
  31. return await result as Awaited<ReturnType<FileUploads['uploadStream']>>
  32. })
  33. return {
  34. uploadedChunks,
  35. uploadStream,
  36. } as unknown as FileUploads & {
  37. uploadStream: Mock<FileUploads['uploadStream']>
  38. uploadedChunks: Uint8Array[]
  39. }
  40. }
  41. describe('background file upload Fetch route', () => {
  42. it('accepts one authenticated streaming POST request', async () => {
  43. const service = uploads(Promise.resolve({}))
  44. expect((await handleFileUploadHttp(service, request({
  45. sessionId: 's1', contentType: 'application/octet-stream',
  46. }))).status).toBe(200)
  47. })
  48. it('rejects the wrong method, media type, and missing Session id without storing', async () => {
  49. const service = uploads(Promise.resolve({}))
  50. const wrongMethod = await handleFileUploadHttp(service, request({ method: 'GET' }))
  51. expect(wrongMethod.status).toBe(405)
  52. expect(wrongMethod.headers.get('allow')).toBe('POST')
  53. const wrongType = await handleFileUploadHttp(service, request({ contentType: 'application/json' }))
  54. expect(wrongType.status).toBe(415)
  55. expect(await wrongType.text()).toBe('content type must be application/octet-stream')
  56. const missingSession = await handleFileUploadHttp(
  57. service,
  58. request({ contentType: 'application/octet-stream' }),
  59. )
  60. expect(missingSession.status).toBe(400)
  61. expect(await missingSession.text()).toBe('sessionId is required')
  62. expect(service.uploadStream).not.toHaveBeenCalled()
  63. })
  64. it('stores the request bytes and returns the staged receipt', async () => {
  65. const value = {
  66. receiptId: 'receipt-1',
  67. file: { attachmentId: 'file-1', name: 'large & final.bin', bytes: 4 },
  68. }
  69. const service = uploads(Promise.resolve(value))
  70. const response = await handleFileUploadHttp(service, request({
  71. sessionId: 's1',
  72. name: 'large & final.bin',
  73. contentType: 'application/octet-stream; charset=binary',
  74. body: Uint8Array.of(1, 2, 3, 4),
  75. }))
  76. expect(service.uploadStream).toHaveBeenCalledOnce()
  77. const upload = service.uploadStream.mock.calls[0]?.[0]
  78. expect(upload).toMatchObject({ sessionId: 's1', name: 'large & final.bin' })
  79. expect(upload?.signal).toBeInstanceOf(AbortSignal)
  80. expect(service.uploadedChunks).toEqual([Uint8Array.of(1, 2, 3, 4)])
  81. expect(response.status).toBe(200)
  82. expect(response.headers.get('content-type')).toBe('application/json; charset=utf-8')
  83. expect(response.headers.get('cache-control')).toBe('no-store')
  84. expect(await response.json()).toEqual({ ok: true, value })
  85. })
  86. it('returns business and internal storage failures and keeps an absent name absent', async () => {
  87. const business = uploads(Promise.reject(new RemoteError(
  88. 'session/attachment-invalid', 'denied', { reason: 'NOPE' },
  89. )))
  90. const businessResponse = await handleFileUploadHttp(business, request({
  91. sessionId: 's1', contentType: 'application/octet-stream',
  92. }))
  93. expect(business.uploadStream).toHaveBeenCalledOnce()
  94. const upload = business.uploadStream.mock.calls[0]?.[0]
  95. expect(upload).toMatchObject({ sessionId: 's1' })
  96. expect(upload?.signal).toBeInstanceOf(AbortSignal)
  97. expect(business.uploadedChunks).toEqual([])
  98. expect(await businessResponse.json()).toEqual({
  99. ok: false,
  100. error: { code: 'session/attachment-invalid', message: 'denied', details: { reason: 'NOPE' } },
  101. })
  102. const internal = uploads(Promise.reject(new Error('disk offline')))
  103. expect(await (await handleFileUploadHttp(internal, request({
  104. sessionId: 's1', contentType: 'application/octet-stream',
  105. }))).json()).toEqual({
  106. ok: false, error: { code: 'gateway/internal', message: 'disk offline', details: {} },
  107. })
  108. const foreignError = runInNewContext('new Error("disk exception")') as unknown as Error
  109. const exception = uploads(Promise.reject(foreignError))
  110. expect(await (await handleFileUploadHttp(exception, request({
  111. sessionId: 's1', contentType: 'application/octet-stream',
  112. }))).json()).toEqual({
  113. ok: false, error: { code: 'gateway/internal', message: 'Error: disk exception', details: {} },
  114. })
  115. })
  116. })