All files / src/lib http-client.ts

41.07% Statements 69/168
41.66% Branches 10/24
62.5% Functions 5/8
41.07% Lines 69/168

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 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 2291x                       2x 2x 2x   12x 12x     12x 12x 12x     12x   1x 1x 1x 1x 1x 1x           1x                                     2x       2x 2x 2x   2x 2x 2x 2x 2x 2x   2x   2x         2x 2x   2x 2x               2x 2x 2x 2x                                                                                                                                                                                     12x 12x 12x   12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 2x 2x   12x   12x 12x   12x 1x 1x   12x       11x 11x 1x 1x 1x 1x       12x 12x 12x 12x  
import { AppError } from "@ontrack/backend-common";
 
type ProxyOptions = {
  method: "GET" | "POST" | "PUT" | "DELETE";
  url: string;
  timeoutMs: number;
  body?: unknown;
  headers?: Record<string, string>;
};
 
type JsonRecord = Record<string, unknown>;
 
function isRecord(value: unknown): value is JsonRecord {
  return typeof value === "object" && value !== null;
}
 
function tryParseJson(text: string): unknown | undefined {
  if (text.length === 0) {
    return undefined;
  }
  try {
    return JSON.parse(text) as unknown;
  } catch {
    return undefined;
  }
}
 
function normalizeUpstreamError(status: number, payload: unknown): never {
  if (isRecord(payload) && isRecord(payload.error)) {
    const code = typeof payload.error.code === "string" ? payload.error.code : "UPSTREAM_ERROR";
    const message = typeof payload.error.message === "string" ? payload.error.message : "Upstream request failed";
    throw new AppError(status, code, message);
  }
 
  throw new AppError(status, "UPSTREAM_ERROR", "Upstream request failed");
}
 
/** Для произвольного fetch (multipart и т.д.): тело ошибки — JSON с `error`. */
export function throwIfUpstreamFailed(status: number, body: Buffer): void {
  if (status < 400) {
    return;
  }
  const payload = tryParseJson(body.toString("utf8"));
  normalizeUpstreamError(status, payload);
}
 
export type ProxyRawSuccess = {
  status: number;
  body: Buffer;
  contentType: string | undefined;
  contentDisposition: string | undefined;
};
 
/**
 * GET с телом как Buffer (GPX и т.д.).
 * При `!response.ok` тело трактуется как JSON ошибки upstream → бросок `AppError` (как у `proxyJsonRequest`).
 */
export async function proxyUpstreamGetRaw(options: {
  url: string;
  headers?: Record<string, string>;
  timeoutMs: number;
}): Promise<ProxyRawSuccess> {
  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), options.timeoutMs);
 
  try {
    const response = await fetch(options.url, {
      method: "GET",
      headers: options.headers ?? {},
      signal: controller.signal,
    });
 
    const body = Buffer.from(await response.arrayBuffer());
 
    if (!response.ok) {
      const payload = tryParseJson(body.toString("utf8"));
      normalizeUpstreamError(response.status, payload);
    }
 
    const contentType = response.headers.get("content-type") ?? undefined;
    const contentDisposition = response.headers.get("content-disposition") ?? undefined;
 
    return { status: response.status, body, contentType, contentDisposition };
  } catch (error) {
    if (error instanceof AppError) {
      throw error;
    }
    if (error instanceof Error && error.name === "AbortError") {
      throw new AppError(504, "UPSTREAM_TIMEOUT", "Upstream request timed out");
    }
    throw new AppError(502, "UPSTREAM_UNAVAILABLE", "Upstream service unavailable");
  } finally {
    clearTimeout(timeout);
  }
}
 
export type ProxyJsonResult<T> = {
  status: number;
  body: T;
};
 
export async function proxyJsonRequestWithStatus<T>(
  options: ProxyOptions,
): Promise<ProxyJsonResult<T>> {
  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), options.timeoutMs);
 
  try {
    const requestInit: RequestInit = {
      method: options.method,
      headers: {
        "content-type": "application/json",
        ...(options.headers ?? {}),
      },
      signal: controller.signal,
    };
    if (options.body !== undefined) {
      requestInit.body = JSON.stringify(options.body);
    }
 
    const response = await fetch(options.url, requestInit);
    const text = await response.text();
    const payload = tryParseJson(text);
 
    if (!response.ok) {
      normalizeUpstreamError(response.status, payload);
    }
 
    if (payload === undefined) {
      throw new AppError(502, "UPSTREAM_INVALID_JSON", "Upstream returned invalid JSON");
    }
 
    return { status: response.status, body: payload as T };
  } catch (error) {
    if (error instanceof AppError) {
      throw error;
    }
    if (error instanceof Error && error.name === "AbortError") {
      throw new AppError(504, "UPSTREAM_TIMEOUT", "Upstream request timed out");
    }
    throw new AppError(502, "UPSTREAM_UNAVAILABLE", "Upstream service unavailable");
  } finally {
    clearTimeout(timeout);
  }
}
 
export async function proxyUpstreamRedirect(options: {
  url: string;
  timeoutMs: number;
}): Promise<{ status: number; location: string }> {
  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), options.timeoutMs);
 
  try {
    const response = await fetch(options.url, {
      method: "GET",
      redirect: "manual",
      signal: controller.signal,
    });
 
    if (response.status >= 300 && response.status < 400) {
      const location = response.headers.get("location");
      if (!location) {
        throw new AppError(502, "UPSTREAM_ERROR", "Upstream redirect missing Location");
      }
      return { status: response.status, location };
    }
 
    const body = Buffer.from(await response.arrayBuffer());
    const payload = tryParseJson(body.toString("utf8"));
    normalizeUpstreamError(response.status, payload);
    throw new AppError(502, "UPSTREAM_ERROR", "Upstream did not redirect");
  } catch (error) {
    if (error instanceof AppError) {
      throw error;
    }
    if (error instanceof Error && error.name === "AbortError") {
      throw new AppError(504, "UPSTREAM_TIMEOUT", "Upstream request timed out");
    }
    throw new AppError(502, "UPSTREAM_UNAVAILABLE", "Upstream service unavailable");
  } finally {
    clearTimeout(timeout);
  }
}
 
export async function proxyJsonRequest<T>(options: ProxyOptions): Promise<T> {
  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), options.timeoutMs);
 
  try {
    const requestInit: RequestInit = {
      method: options.method,
      headers: {
        "content-type": "application/json",
        ...(options.headers ?? {}),
      },
      signal: controller.signal,
    };
    if (options.body !== undefined) {
      requestInit.body = JSON.stringify(options.body);
    }
 
    const response = await fetch(options.url, requestInit);
 
    const text = await response.text();
    const payload = tryParseJson(text);
 
    if (!response.ok) {
      normalizeUpstreamError(response.status, payload);
    }
 
    if (payload === undefined) {
      throw new AppError(502, "UPSTREAM_INVALID_JSON", "Upstream returned invalid JSON");
    }
 
    return payload as T;
  } catch (error) {
    if (error instanceof AppError) {
      throw error;
    }
    if (error instanceof Error && error.name === "AbortError") {
      throw new AppError(504, "UPSTREAM_TIMEOUT", "Upstream request timed out");
    }
    throw new AppError(502, "UPSTREAM_UNAVAILABLE", "Upstream service unavailable");
  } finally {
    clearTimeout(timeout);
  }
}