All files / src blob-batch-client.ts

91.93% Statements 57/62
81.81% Branches 36/44
100% Functions 9/9
91.8% Lines 56/61

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157                                      2x 2x 2x 2x 2x 2x 2x             3x 3x               3x     3x 3x 4x   3x 4x   3x 2x         1x 1x   2x 2x 2x   2x   2x             6x             1x         1x       1x 3x       1x   1x 2x   1x                           1x 1x   1x 1x 14x     14x 11x 11x   3x 2x   3x 1x 1x   2x     1x     1x     2x 2x 2x 2x 2x 2x     2x              
import type { BlobDeleteOptions } from './block-blob-client'
import {
  StorageTransport,
  multipartBoundary,
  storageRequestError,
} from './internal/storage-request'
import type { StorageClientOptions, StorageCredential } from './internal/storage-request'
 
export interface BlobBatchSubResponse {
  status: number
  errorCode?: string
}
 
export interface BlobBatchSubmitResponse {
  subResponses: BlobBatchSubResponse[]
  subResponsesSucceededCount: number
  subResponsesFailedCount: number
}
 
const contentIdPattern = /^content-id:[\t ]*(\d+)[\t ]*$/imu
const statusLinePattern = /^HTTP\/1\.1 (\d{3})(?:[ \r\n]|$)/u
const errorCodePattern = /^x-ms-error-code:\s*(\S+)/imu
const boundaryPattern = /boundary=([^;\s]+)/u
const headerSeparator = /\r?\n\r?\n/u
const lineSeparator = /\r?\n/u
const boundarySuffix = /^(--)?[\t ]*$/u
 
export class BlobBatchClient {
  private readonly url: string
  private readonly transport: StorageTransport
 
  public constructor(url: string, credential?: StorageCredential, options?: StorageClientOptions) {
    this.url = url
    this.transport = new StorageTransport(credential, options)
  }
 
  /** Deletes up to 256 blobs of the account in one batch request. */
  public async deleteBlobs(
    blobUrls: string[],
    options: BlobDeleteOptions = {},
  ): Promise<BlobBatchSubmitResponse> {
    Iif (blobUrls.length === 0 || blobUrls.length > 256) {
      throw new RangeError('Blob batch requires 1 to 256 blob URLs')
    }
    const account = new URL(this.url)
    const accountPath = account.pathname.endsWith('/') ? account.pathname : `${account.pathname}/`
    const urls = blobUrls.map((blobUrl) => new URL(blobUrl))
    // Sub-requests carry only the path, so a blob of another account would hit this one.
    const foreign = urls.find(
      (url) => url.origin !== account.origin || !url.pathname.startsWith(accountPath),
    )
    if (foreign !== undefined) {
      throw new TypeError(
        `Blob ${foreign.origin}${foreign.pathname} does not belong to ${account.origin}${account.pathname}`,
      )
    }
 
    const boundary = multipartBoundary('batch')
    const parts = await Promise.all(
      urls.map(async (url, index) => {
        const headers = new Headers({ 'x-ms-date': new Date().toUTCString() })
        Eif (options.deleteSnapshots !== undefined) {
          headers.set('x-ms-delete-snapshots', options.deleteSnapshots)
        }
        await this.transport.authorize('DELETE', url, headers)
 
        return [
          `--${boundary}`,
          'Content-Type: application/http',
          'Content-Transfer-Encoding: binary',
          `Content-ID: ${index}`,
          '',
          `DELETE ${url.pathname}${url.search} HTTP/1.1`,
          ...Array.from(headers, ([name, value]) => `${name}: ${value}`),
          '',
          '',
        ].join('\r\n')
      }),
    )
 
    const response = await this.transport.send('POST', this.url, {
      query: { comp: 'batch' },
      headers: { 'Content-Type': `multipart/mixed; boundary=${boundary}` },
      body: `${parts.join('\r\n')}\r\n--${boundary}--\r\n`,
    })
    Iif (response.status !== 202) {
      throw storageRequestError('Blob batch', response)
    }
 
    const responseBoundary = boundaryPattern.exec(response.headers.get('content-type') ?? '')?.[1]
    Iif (responseBoundary === undefined) {
      throw new Error('Blob batch response is missing its multipart boundary')
    }
 
    const subResponses = parseSubResponses(await response.text(), responseBoundary, urls.length)
 
    const succeeded = subResponses.filter(
      ({ status, errorCode }) => status >= 200 && status < 300 && errorCode === undefined,
    ).length
    return {
      subResponses,
      subResponsesSucceededCount: succeeded,
      subResponsesFailedCount: subResponses.length - succeeded,
    }
  }
}
 
/** Orders sub-responses by the Content-ID of the sub-request they answer. */
function parseSubResponses(
  body: string,
  boundary: string,
  expected: number,
): BlobBatchSubResponse[] {
  const subResponses: BlobBatchSubResponse[] = []
  const delimiter = `--${boundary}`
  let partLines: string[] | undefined
  let closed = false
  for (const line of body.split(lineSeparator)) {
    const boundaryLine = line.startsWith(delimiter)
      ? boundarySuffix.exec(line.slice(delimiter.length))
      : null
    if (boundaryLine === null) {
      partLines?.push(line)
      continue
    }
    if (partLines !== undefined) {
      addSubResponse(partLines.join('\n'))
    }
    if (boundaryLine[1] !== undefined) {
      closed = true
      break
    }
    partLines = []
  }
 
  Iif (!closed || Object.keys(subResponses).length !== expected) {
    throw new Error('Blob batch response does not match its sub-requests')
  }
  return subResponses
 
  function addSubResponse(part: string): void {
    const [mimeHeaders = '', response = ''] = part.split(headerSeparator, 2)
    const contentId = contentIdPattern.exec(mimeHeaders)?.[1]
    const status = statusLinePattern.exec(response)?.[1]
    Eif (contentId !== undefined && status !== undefined) {
      const index = Number(contentId)
      Iif (index >= expected || subResponses[index] !== undefined) {
        throw new Error('Blob batch response does not match its sub-requests')
      }
      subResponses[index] = {
        status: Number(status),
        errorCode: errorCodePattern.exec(response)?.[1],
      }
    }
  }
}