All files / apps/web/src/providers exchange-rate.ts

11.88% Statements 12/101
0% Branches 0/34
0% Functions 0/28
12.37% Lines 12/97

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 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249                                      6x   6x     6x                                                                     6x 6x                                                                                               6x                                                                                                           6x                         6x   6x                                                         6x   6x     6x                                                                          
import Dataloader from "dataloader";
import { entries, fromEntries, keys } from "remeda";
import { z } from "zod";
 
import type { CurrencyCode } from "~app/utils/currency";
import type { UnauthorizedContext } from "~web/handlers/context";
import type { CacheInstance } from "~web/providers/cache-db";
import { getCacheInstance } from "~web/providers/cache-db";
import { env } from "~web/utils/env";
 
export type ExchangeRateOptions = {
	mock?: {
		fn: (from: CurrencyCode, to: CurrencyCode) => Promise<number>;
	};
};
 
type ExchangeRateInput = { fromCode: CurrencyCode; toCode: CurrencyCode };
 
// see https://github.com/fawazahmed0/exchange-api
const CDN_MAIN_BASE_URL = `https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/{fromCode}.min.json`;
// see https://github.com/fawazahmed0/exchange-api/blob/main/README.md#additional-fallback-url-on-cloudflare
const CDN_BACKUP_BASE_URL = `https://latest.currency-api.pages.dev/v1/currencies/{fromCode}.min.json`;
 
const fetchCDNRate =
	(baseUrl: string) =>
	async (fromCode: CurrencyCode, toCodes: CurrencyCode[]) => {
		const fromCodeLower = fromCode.toLowerCase();
		const toCodesLower = toCodes.map((code) => code.toLowerCase()) as [
			string,
			...string[],
		];
		const response = await fetch(baseUrl.replace("{fromCode}", fromCodeLower));
		if (response.status !== 200) {
			throw new Error(
				`Response to exchange rate request is ${response.status}`,
			);
		}
		const json: unknown = await response.json();
		const parsedJson = z
			.object({
				[fromCodeLower]: z.record(z.string(), z.float32()).refine((obj) => {
					const actualKeys = keys(obj);
					return toCodesLower.every((code) => actualKeys.includes(code));
				}),
			})
			.safeParse(json);
		if (!parsedJson.success) {
			throw parsedJson.error;
		}
		return toCodesLower.map((toCodeLower) =>
			Number(
				// We just verified it exists
				// oxlint-disable-next-line typescript/no-non-null-assertion
				parsedJson.data[fromCodeLower]![toCodeLower]!.toFixed(6),
			),
		);
	};
 
// see https://www.exchangerate-api.com/docs/standard-requests
const ERA_BASE_URL = "https://v6.exchangerate-api.com/v6/";
const fetchERARate = async (
	fromCode: CurrencyCode,
	toCodes: CurrencyCode[],
) => {
	const { ERA_API_KEY } = env;
	if (!ERA_API_KEY) {
		throw new Error(`Expected to have env.ERA_API_KEY`);
	}
	const fromCodeUpper = fromCode.toUpperCase();
	const toCodesUpper = toCodes.map((code) => code.toUpperCase());
	const response = await fetch(
		`${ERA_BASE_URL}${ERA_API_KEY}/latest/${fromCodeUpper}`,
	);
	if (response.status !== 200) {
		throw new Error(`Response to exchange rate request is ${response.status}`);
	}
	const json: unknown = await response.json();
	const parsedJson = z
		.discriminatedUnion("result", [
			z.object({
				result: z.literal("success"),
				base_code: z.literal(fromCodeUpper),
				conversion_rates: z.record(z.string(), z.number()),
			}),
			z.object({
				result: z.literal("error"),
				"error-type": z.string(),
			}),
		])
		.safeParse(json);
	if (!parsedJson.success) {
		throw parsedJson.error;
	}
	const { data } = parsedJson;
	if (data.result === "error") {
		throw new Error(`Error fetching ERA result: "${data["error-type"]}"`);
	}
	return toCodesUpper.map((toCodeUpper) => {
		const matchedRate = data.conversion_rates[toCodeUpper];
		if (!matchedRate) {
			throw new Error(
				`Error getting ERA rate for "${fromCodeUpper}" -> "${toCodeUpper}"`,
			);
		}
		return Number(matchedRate.toFixed(6));
	});
};
 
const fetchWithBatches = async (
	inputs: readonly ExchangeRateInput[],
	fetcher: (
		fromCode: CurrencyCode,
		toCodes: CurrencyCode[],
	) => Promise<number[]>,
) => {
	const batches = inputs.reduce<Record<CurrencyCode, CurrencyCode[]>>(
		(acc, input) => {
			const batch = acc[input.fromCode] || [];
			if (!batch.includes(input.toCode)) {
				batch.push(input.toCode);
			}
			return { ...acc, [input.fromCode]: batch };
		},
		{},
	);
	const batchResults = await Promise.all(
		entries(batches).map(async ([fromCode, toCodes]) => {
			const batchResult = await fetcher(fromCode, toCodes);
			return {
				fromCode,
				toRates: toCodes.map((toCode, index) => {
					const toRate = batchResult[index];
					if (toRate === undefined) {
						throw new Error("Expected length to match in response");
					}
					return {
						code: toCode,
						rate: toRate,
					};
				}),
			};
		}),
	);
	return inputs.map((input) => {
		const matchedBatch = batchResults.find(
			({ fromCode }) => fromCode === input.fromCode,
		);
		if (!matchedBatch) {
			throw new Error(`No batch from code "${input.fromCode}"`);
		}
		const matchedRate = matchedBatch.toRates.find(
			({ code }) => code === input.toCode,
		);
		if (!matchedRate) {
			throw new Error(
				`No batch from code "${input.fromCode}" to code "${input.toCode}"`,
			);
		}
		return matchedRate.rate;
	});
};
 
const fetchPipeline = (fetchers: (() => Promise<number[]>)[]) =>
	fetchers.reduce<Promise<number[] | Error[]>>(async (acc, fetcher) => {
		const results = await acc;
		try {
			if (typeof results[0] !== "number") {
				return await fetcher();
			}
			return results;
		} catch (error) {
			return [...(results as Error[]), error as Error];
		}
	}, Promise.resolve([]));
 
const SCHEDULE_DELAY = 100;
 
const exchangeRateDataloader = new Dataloader<
	ExchangeRateInput,
	number,
	string
>(
	async (inputs) => {
		const result = await fetchPipeline([
			() => fetchWithBatches(inputs, fetchCDNRate(CDN_MAIN_BASE_URL)),
			() => fetchWithBatches(inputs, fetchCDNRate(CDN_BACKUP_BASE_URL)),
			() => fetchWithBatches(inputs, fetchERARate),
		]);
		if (typeof result[0] === "number") {
			return result;
		}
		throw new AggregateError(
			result,
			"All exchange rate resolution options failed",
		);
	},
	{
		batchScheduleFn: (callback) => {
			setTimeout(callback, SCHEDULE_DELAY);
		},
		cacheKeyFn: JSON.stringify,
		name: "exchange-rate",
	},
);
 
// Seconds
const CACHE_TTL = 24 * 60 * 1000;
 
const getKey = (fromCode: CurrencyCode, toCode: CurrencyCode): string =>
	`${fromCode}->${toCode}`;
 
export const getExchangeRates = async (
	ctx: UnauthorizedContext,
	fromCode: CurrencyCode,
	toCodes: CurrencyCode[],
): Promise<Record<CurrencyCode, number>> => {
	let cacheInstance: CacheInstance | null = null;
	try {
		cacheInstance = await getCacheInstance(ctx);
	} catch {
		/* empty */
	}
	const rates = await Promise.all(
		toCodes.map(async (toCode) => {
			const cacheKey = getKey(fromCode, toCode);
			const cachedRate = cacheInstance
				? await cacheInstance.getValue(cacheKey)
				: null;
			if (cachedRate) {
				return { toCode, rate: Number(cachedRate) };
			}
			const fetchedRate = await (ctx.exchangeRateOptions.mock
				? ctx.exchangeRateOptions.mock.fn(fromCode, toCode)
				: exchangeRateDataloader.load({
						fromCode,
						toCode,
					}));
			cacheInstance
				?.setValue(cacheKey, fetchedRate.toString(), { expiryInS: CACHE_TTL })
				.catch((error) => {
					// Failing on this action doesn't matter much
					ctx.logger.warn("Cache DB setex action failed", error);
				});
			return { toCode, rate: fetchedRate };
		}),
	);
	return fromEntries(rates.map(({ toCode, rate }) => [toCode, rate]));
};