All files / dicomImageLoader/src/imageLoader/internal rangeRequest.ts

0% Statements 0/69
0% Branches 0/53
0% Functions 0/7
0% Lines 0/69

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 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206                                                                                                                                                                                                                                                                                                                                                                                                                           
import type { Types, Enums } from '@cornerstonejs/core';
import { getOptions } from './options';
import type {
  LoaderXhrRequestError,
  LoaderXhrRequestPromise,
} from '../../types';
import metaDataManager from '../wadors/metaDataManager';
import extractMultipart from '../wadors/extractMultipart';
import { getImageQualityStatus } from '../wadors/getImageQualityStatus';
import type { CornerstoneWadoRsLoaderOptions } from '../wadors/loadImage';
 
type RangeRetrieveOptions = Types.RangeRetrieveOptions;
 
/**
 * Performs a range request to fetch part of an encoded image, typically
 * so that partial resolution images can be fetched.
 * The configuration of exactly what is requested is based on the transfer
 * syntax provided.
 * Note this generates 1 response for each call, and those reponses may or may
 * not be combined with each other depending on the configuration applied.
 *
 * * HTJ2K Streaming TSUID -> Use actual range requests, and set it up for streaming
 *   image decoding of byte range requests
 * * JLS and Non-streaming HTJ2K -> Use a sub-resolution (or thumbnail) endpoint
 *   followed by normal endpoint
 *
 * @param url - including an fsiz parameter
 * @param imageId - to fetch for
 * @param defaultHeaders  - to add to the request
 * @returns Compressed image data
 */
export default function rangeRequest(
  url: string,
  imageId: string,
  defaultHeaders: Record<string, string> = {},
  options: CornerstoneWadoRsLoaderOptions = {}
): LoaderXhrRequestPromise<{
  contentType: string;
  pixelData: Uint8Array;
  imageQualityStatus: Enums.ImageQualityStatus;
  percentComplete: number;
}> {
  const globalOptions = getOptions();
  const { retrieveOptions = {} as RangeRetrieveOptions, streamingData } =
    options;
  const chunkSize =
    streamingData.chunkSize ||
    getValue(imageId, retrieveOptions, 'chunkSize') ||
    65536;
 
  const errorInterceptor = (err) => {
    if (typeof globalOptions.errorInterceptor === 'function') {
      const error = new Error('request failed') as LoaderXhrRequestError;
      globalOptions.errorInterceptor(error);
    } else {
      console.warn('rangeRequest:Caught', err);
    }
  };
 
  // Make the request for the streamable image frame (i.e. HTJ2K)
  const promise = new Promise<{
    contentType: string;
    pixelData: Uint8Array;
    percentComplete: number;
    imageQualityStatus: Enums.ImageQualityStatus;
    // eslint-disable-next-line no-async-promise-executor
  }>(async (resolve, reject) => {
    const headers = Object.assign(
      {},
      defaultHeaders
      /* beforeSendHeaders */
    );
 
    Object.keys(headers).forEach(function (key) {
      if (headers[key] === null || headers[key] === undefined) {
        delete headers[key];
      }
    });
 
    try {
      if (!streamingData.encodedData) {
        streamingData.chunkSize = chunkSize;
        streamingData.rangesFetched = 0;
      }
      const byteRange = getByteRange(streamingData, retrieveOptions);
 
      const { encodedData, responseHeaders } = await fetchRangeAndAppend(
        url,
        headers,
        byteRange,
        streamingData
      );
 
      // Resolve promise with the first range, so it can be passed through to
      // cornerstone via the usual image loading pathway. All subsequent
      // ranges will be passed and decoded via events.
      const contentType = responseHeaders.get('content-type');
      const { totalBytes } = streamingData;
      const doneAllBytes = totalBytes === encodedData.byteLength;
      const extract = extractMultipart(contentType, encodedData, {
        isPartial: true,
      });
 
      // Allow over-writing the done status to indicate complete on partial
      const imageQualityStatus = getImageQualityStatus(
        retrieveOptions,
        doneAllBytes || extract.extractDone === true
      );
      resolve({
        ...extract,
        imageQualityStatus,
        percentComplete: extract.extractDone
          ? 100
          : (chunkSize * 100) / totalBytes,
      });
    } catch (err) {
      errorInterceptor(err);
      console.error(err);
      reject(err);
    }
  });
 
  return promise;
}
 
async function fetchRangeAndAppend(
  url: string,
  headers: Record<string, string>,
  range: [number, number | ''],
  streamingData
) {
  if (range) {
    headers = Object.assign(headers, {
      Range: `bytes=${range[0]}-${range[1]}`,
    });
  }
  let { encodedData } = streamingData;
  if (range[1] && encodedData?.byteLength > range[1]) {
    return streamingData;
  }
  const response = await fetch(url, {
    headers,
    signal: undefined,
  });
 
  const responseArrayBuffer = await response.arrayBuffer();
  const responseTypedArray = new Uint8Array(responseArrayBuffer);
  const { status } = response;
 
  // Append new data
  let newByteArray: Uint8Array;
  if (encodedData) {
    newByteArray = new Uint8Array(
      encodedData.length + responseTypedArray.length
    );
    newByteArray.set(encodedData, 0);
    newByteArray.set(responseTypedArray, encodedData.length);
    streamingData.rangesFetched = 1;
  } else {
    newByteArray = new Uint8Array(responseTypedArray.length);
    newByteArray.set(responseTypedArray, 0);
    streamingData.rangesFetched++;
  }
  streamingData.encodedData = encodedData = newByteArray;
  streamingData.responseHeaders = response.headers;
 
  const contentRange = response.headers.get('Content-Range');
  if (contentRange) {
    streamingData.totalBytes = Number(contentRange.split('/')[1]);
  } else if (status !== 206 || !range) {
    streamingData.totalBytes = encodedData?.byteLength;
  } else if (range[1] === '' || encodedData?.length < range[1]) {
    streamingData.totalBytes = encodedData.byteLength;
  } else {
    streamingData.totalBytes = Number.MAX_SAFE_INTEGER;
  }
 
  return streamingData;
}
 
function getValue(imageId: string, src, attr: string) {
  const value = src[attr];
  if (typeof value !== 'function') {
    return value;
  }
  const metaData = metaDataManager.get(imageId);
  return value(metaData, imageId);
}
 
function getByteRange(
  streamingData,
  retrieveOptions: RangeRetrieveOptions
): [number, number | ''] {
  const { totalBytes, encodedData, chunkSize = 65536 } = streamingData;
  const { rangeIndex = 0 } = retrieveOptions;
  if (rangeIndex === -1 && (!totalBytes || !encodedData)) {
    return [0, ''];
  }
  if (rangeIndex === -1 || encodedData?.byteLength > totalBytes - chunkSize) {
    return [encodedData?.byteLength || 0, ''];
  }
  // Note the byte range is inclusive at both ends and zero based,
  // so the byteLength is the next index to fetch.
  return [encodedData?.byteLength || 0, chunkSize * (rangeIndex + 1) - 1];
}