File size: 4,696 Bytes
c6afb12
 
 
 
 
 
 
644ba85
 
c6afb12
 
 
 
 
 
 
644ba85
c6afb12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
644ba85
 
 
 
 
 
c6afb12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
644ba85
 
c6afb12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
644ba85
c6afb12
644ba85
 
 
 
 
 
 
 
 
c6afb12
 
644ba85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6afb12
 
644ba85
 
c6afb12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { env } from '$env/dynamic/private';
import { parseHfBucketManifest } from './manifest';
import type { HfBucketManifest } from './types';

const DEFAULT_ENDPOINT = 'https://huggingface.co';
const DEFAULT_BUCKET_ID = 'hivetrace/leaderboard_frontend_v2';
const DEFAULT_PREFIX = 'latest';
const DEFAULT_REQUEST_TIMEOUT_MS = 60_000;
const DEFAULT_REQUEST_RETRIES = 2;

type HfBucketConfig = {
	token: string;
	bucketId: string;
	prefix: string;
	endpoint: string;
	requestTimeoutMs: number;
	requestRetries: number;
};

export class HfBucketError extends Error {
	readonly status?: number;

	constructor(message: string, options?: { cause?: unknown; status?: number }) {
		super(message, { cause: options?.cause });
		this.name = 'HfBucketError';
		this.status = options?.status;
	}
}

function positiveInteger(value: string | undefined, fallback: number) {
	if (!value) return fallback;
	const parsed = Number(value);
	return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
}

function nonNegativeInteger(value: string | undefined, fallback: number) {
	if (!value) return fallback;
	const parsed = Number(value);
	return Number.isInteger(parsed) && parsed >= 0 ? parsed : fallback;
}

function normalizePrefix(value: string) {
	return value
		.split('/')
		.map((part) => part.trim())
		.filter(Boolean)
		.join('/');
}

function getConfig(): HfBucketConfig {
	const token = env.HF_TOKEN?.trim();
	if (!token) {
		throw new HfBucketError('HF_TOKEN is not configured on the server.');
	}

	const bucketId = (env.HF_BUCKET_ID ?? DEFAULT_BUCKET_ID).trim();
	if (!/^[^/\s]+\/[^/\s]+$/.test(bucketId)) {
		throw new HfBucketError('HF_BUCKET_ID must use the "namespace/bucket" format.');
	}

	return {
		token,
		bucketId,
		prefix: normalizePrefix(env.HF_BUCKET_PREFIX ?? DEFAULT_PREFIX),
		endpoint: (env.HF_BUCKET_ENDPOINT ?? DEFAULT_ENDPOINT).replace(/\/+$/, ''),
		requestTimeoutMs: positiveInteger(env.HF_BUCKET_REQUEST_TIMEOUT_MS, DEFAULT_REQUEST_TIMEOUT_MS),
		requestRetries: nonNegativeInteger(env.HF_BUCKET_REQUEST_RETRIES, DEFAULT_REQUEST_RETRIES)
	};
}

function remotePath(prefix: string, path: string) {
	return [prefix, path].filter(Boolean).join('/').split('/').filter(Boolean).join('/');
}

function bucketFileUrl(config: HfBucketConfig, path: string) {
	const encodedBucketId = config.bucketId.split('/').map(encodeURIComponent).join('/');
	const encodedPath = encodeURIComponent(remotePath(config.prefix, path));
	return `${config.endpoint}/buckets/${encodedBucketId}/resolve/${encodedPath}`;
}

function responseErrorMessage(status: number, path: string) {
	if (status === 401) return `Hugging Face rejected authentication while reading "${path}".`;
	if (status === 403) return `HF_TOKEN has no permission to read "${path}".`;
	if (status === 404) return `Bucket file "${path}" was not found.`;
	return `Hugging Face returned HTTP ${status} while reading "${path}".`;
}

export async function fetchHfBucketText(path: string): Promise<string> {
	const config = getConfig();
	const maxAttempts = config.requestRetries + 1;

	for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
		const controller = new AbortController();
		const timeout = setTimeout(() => controller.abort(), config.requestTimeoutMs);

		try {
			const response = await fetch(bucketFileUrl(config, path), {
				headers: { Authorization: `Bearer ${config.token}` },
				redirect: 'follow',
				signal: controller.signal
			});

			if (!response.ok) {
				throw new HfBucketError(responseErrorMessage(response.status, path), {
					status: response.status
				});
			}

			return await response.text();
		} catch (cause) {
			if (cause instanceof HfBucketError) throw cause;

			if (attempt < maxAttempts) continue;
			if (cause instanceof Error && cause.name === 'AbortError') {
				throw new HfBucketError(
					`Timed out after ${config.requestTimeoutMs} ms while reading "${path}" after ${maxAttempts} attempts.`,
					{ cause }
				);
			}
			throw new HfBucketError(`Failed to read bucket file "${path}".`, { cause });
		} finally {
			clearTimeout(timeout);
		}
	}

	throw new HfBucketError(`Failed to read bucket file "${path}".`);
}

export async function fetchHfBucketJson(path: string): Promise<unknown> {
	const text = await fetchHfBucketText(path);
	try {
		return JSON.parse(text) as unknown;
	} catch (cause) {
		throw new HfBucketError(`Bucket file "${path}" is not valid JSON.`, { cause });
	}
}

export async function fetchHfBucketManifest(): Promise<HfBucketManifest> {
	const value = await fetchHfBucketJson('manifest.json');
	try {
		return parseHfBucketManifest(value);
	} catch (cause) {
		throw new HfBucketError('Bucket manifest failed validation.', { cause });
	}
}