batch-file-uploader.test.ts 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. import { expect } from 'chai'
  2. import fetchMock from 'fetch-mock'
  3. import {
  4. uploadBatch,
  5. BatchUploadOptions,
  6. } from '@/infrastructure/batch-file-uploader'
  7. describe('uploadBatch', function () {
  8. const batchUploadOptions = {
  9. projectId: 'test-project',
  10. folderId: 'test-folder',
  11. }
  12. const batchUploadItems = [
  13. {
  14. file: new Blob(['col1,col2\n1,2\n']),
  15. name: 'data.csv',
  16. relativePath: 'output/data.csv',
  17. },
  18. {
  19. file: new Blob(['hello world']),
  20. name: 'notes.txt',
  21. relativePath: 'output/notes.txt',
  22. },
  23. {
  24. file: new Blob([new Uint8Array([137, 80, 78, 71])]),
  25. name: 'figure.png',
  26. relativePath: 'output/figure.png',
  27. },
  28. {
  29. file: new Blob(['{"result":42}']),
  30. name: 'data.json',
  31. },
  32. ]
  33. afterEach(function () {
  34. fetchMock.removeRoutes().clearHistory()
  35. })
  36. it('returns an empty array and makes no requests when items is empty', async function () {
  37. const results = await uploadBatch([], batchUploadOptions)
  38. expect(results).to.deep.equal([])
  39. expect(fetchMock.callHistory.called()).to.be.false
  40. })
  41. context('when all uploads succeed', function () {
  42. const expectedUrl = `/project/${batchUploadOptions.projectId}/upload?folder_id=${batchUploadOptions.folderId}`
  43. let results: Awaited<ReturnType<typeof uploadBatch>>
  44. let calls: ReturnType<typeof fetchMock.callHistory.calls>
  45. beforeEach(async function () {
  46. fetchMock.post(expectedUrl, {
  47. status: 200,
  48. body: { success: true },
  49. })
  50. results = await uploadBatch(batchUploadItems, batchUploadOptions)
  51. calls = fetchMock.callHistory.calls()
  52. })
  53. const findRequestFor = (name: string) =>
  54. calls.find(c => (c.options.body as FormData).get('name') === name)!
  55. it('makes one request per item', function () {
  56. expect(calls).to.have.lengthOf(4)
  57. })
  58. it('posts each request to the upload URL', function () {
  59. for (const call of calls) {
  60. expect(call.url).to.include(expectedUrl)
  61. }
  62. })
  63. it('sets the name form field from the item name', function () {
  64. for (const item of batchUploadItems) {
  65. const body = findRequestFor(item.name).options.body as FormData
  66. expect(body.get('name')).to.equal(item.name)
  67. }
  68. })
  69. it('sets the relativePath form field from the item path', function () {
  70. for (const item of batchUploadItems.filter(i => i.relativePath)) {
  71. const body = findRequestFor(item.name).options.body as FormData
  72. expect(body.get('relativePath')).to.equal(item.relativePath)
  73. }
  74. })
  75. it('omits the relativePath form field when the item has no relativePath', function () {
  76. for (const item of batchUploadItems.filter(i => !i.relativePath)) {
  77. const body = findRequestFor(item.name).options.body as FormData
  78. expect(body.has('relativePath')).to.be.false
  79. }
  80. })
  81. it('attaches the item file as qqfile', function () {
  82. for (const item of batchUploadItems) {
  83. const body = findRequestFor(item.name).options.body as FormData
  84. expect(body.get('qqfile')).to.be.instanceOf(Blob)
  85. }
  86. })
  87. it('returns a success result per item with name, relativePath, and server data', function () {
  88. expect(results).to.deep.equal([
  89. {
  90. status: 'success',
  91. name: 'data.csv',
  92. relativePath: 'output/data.csv',
  93. data: { success: true },
  94. },
  95. {
  96. status: 'success',
  97. name: 'notes.txt',
  98. relativePath: 'output/notes.txt',
  99. data: { success: true },
  100. },
  101. {
  102. status: 'success',
  103. name: 'figure.png',
  104. relativePath: 'output/figure.png',
  105. data: { success: true },
  106. },
  107. {
  108. status: 'success',
  109. name: 'data.json',
  110. relativePath: undefined,
  111. data: { success: true },
  112. },
  113. ])
  114. })
  115. })
  116. context('with mixed upload outcomes', function () {
  117. const expectedUrl = `/project/${batchUploadOptions.projectId}/upload?folder_id=${batchUploadOptions.folderId}`
  118. let results: Awaited<ReturnType<typeof uploadBatch>>
  119. beforeEach(async function () {
  120. fetchMock.post(expectedUrl, callLog => {
  121. const name = (callLog.options.body as FormData).get('name')
  122. switch (name) {
  123. case 'data.csv':
  124. return { status: 200, body: { success: true } }
  125. case 'notes.txt':
  126. return {
  127. status: 422,
  128. body: { success: false, error: 'duplicate_file_name' },
  129. }
  130. case 'figure.png':
  131. return { status: 500, body: {} }
  132. case 'data.json':
  133. return Promise.reject(new Error('network down'))
  134. default:
  135. throw new Error(`unexpected item name: ${name}`)
  136. }
  137. })
  138. results = await uploadBatch(batchUploadItems, batchUploadOptions)
  139. })
  140. it('returns a success result when the upload succeeds', function () {
  141. expect(results[0]).to.deep.equal({
  142. status: 'success',
  143. name: 'data.csv',
  144. relativePath: 'output/data.csv',
  145. data: { success: true },
  146. })
  147. })
  148. it('returns the server-provided error string when the response body has one', function () {
  149. expect(results[1]).to.deep.equal({
  150. status: 'error',
  151. name: 'notes.txt',
  152. relativePath: 'output/notes.txt',
  153. error: 'duplicate_file_name',
  154. })
  155. })
  156. it('falls back to a status-code message when the error body has no error field', function () {
  157. expect(results[2]).to.deep.equal({
  158. status: 'error',
  159. name: 'figure.png',
  160. relativePath: 'output/figure.png',
  161. error: 'Internal Server Error',
  162. })
  163. })
  164. it('returns the rejection message when fetch rejects', function () {
  165. expect(results[3]).to.deep.equal({
  166. status: 'error',
  167. name: 'data.json',
  168. relativePath: undefined,
  169. error: 'network down',
  170. })
  171. })
  172. })
  173. describe('default concurrency', function () {
  174. const expectedUrl = `/project/${batchUploadOptions.projectId}/upload?folder_id=${batchUploadOptions.folderId}`
  175. const manyItems = Array.from({ length: 6 }, (_, i) => ({
  176. file: new Blob([`content ${i}`]),
  177. name: `file-${i}.txt`,
  178. }))
  179. const waitFor = async (predicate: () => boolean, timeoutMs = 200) => {
  180. const deadline = Date.now() + timeoutMs
  181. while (!predicate()) {
  182. if (Date.now() > deadline) {
  183. throw new Error('waitFor timed out')
  184. }
  185. await new Promise(resolve => setTimeout(resolve, 0))
  186. }
  187. }
  188. const observeMaxInFlight = async (options: BatchUploadOptions) => {
  189. let inFlight = 0
  190. let maxInFlight = 0
  191. let releaseAll!: () => void
  192. const release = new Promise<void>(resolve => {
  193. releaseAll = resolve
  194. })
  195. fetchMock.post(expectedUrl, async () => {
  196. inFlight++
  197. maxInFlight = Math.max(maxInFlight, inFlight)
  198. await release
  199. inFlight--
  200. return { status: 200, body: { success: true } }
  201. })
  202. const batchPromise = uploadBatch(manyItems, options)
  203. await waitFor(() => inFlight === 3)
  204. releaseAll()
  205. await batchPromise
  206. return maxInFlight
  207. }
  208. it('uses a default cap of 3 when no concurrency is set', async function () {
  209. const max = await observeMaxInFlight(batchUploadOptions)
  210. expect(max).to.equal(3)
  211. })
  212. it('falls back to the default when concurrency is 0', async function () {
  213. const max = await observeMaxInFlight({
  214. ...batchUploadOptions,
  215. concurrency: 0,
  216. })
  217. expect(max).to.equal(3)
  218. })
  219. it('falls back to the default when concurrency is negative', async function () {
  220. const max = await observeMaxInFlight({
  221. ...batchUploadOptions,
  222. concurrency: -1,
  223. })
  224. expect(max).to.equal(3)
  225. })
  226. })
  227. })