1import { Apiauto, ApiautoError } from 'apiauto';
2
3import { InputError, normalizeInput } from './input.js';
4import { AUCTION, MARKET, MARKET_NAME, RAW_FIELDS } from './market.js';
5
6export { MARKET, RAW_FIELDS };
7
8export const API_HOST = 'api.apiauto.space';
9export const API_BASE_URL = `https://${API_HOST}/v1`;
10
11
12export const PAGE_SIZE = 20;
13export const MAX_RETRIES = 2;
14export const REQUEST_TIMEOUT_MS = 30_000;
15export const RUN_DEADLINE_MS = 10 * 60 * 1000;
16
17
18
19
20
21
22
23export const MAX_READ_FACTOR = 4;
24
25
26const RETRY_STATUSES = new Set([429, 500, 502, 503]);
27const MAX_RETRY_AFTER_SECONDS = 60;
28const MAX_DETAIL_LENGTH = 300;
29
30
31
32
33
34export function guardedFetch(fetchImpl, deadline) {
35 return (url, init) => {
36 const target = new URL(url);
37 if (target.protocol !== 'https:' || target.host !== API_HOST) {
38 return Promise.reject(new Error('Blocked a request outside the API host'));
39 }
40 const signal = deadline && init?.signal ? AbortSignal.any([init.signal, deadline]) : init?.signal;
41 return fetchImpl(target.href, { ...init, signal, redirect: 'error' });
42 };
43}
44
45
46
47
48
49
50
51
52export async function run(rawInput, deps) {
53 let input;
54 try {
55 input = normalizeInput(rawInput, (deps.now ?? Date.now)());
56 } catch (error) {
57 const message = error instanceof InputError ? error.message : 'The input could not be read.';
58 deps.log.error(message);
59 return { ok: false, saved: 0, message };
60 }
61 if (input.ignoredFilters) {
62 deps.log.warning('The change feed has no car filters: make, model, year, price and mileage are ignored in this mode.');
63 }
64
65 const state = {
66 saved: 0,
67 read: 0,
68 others: 0,
69 attempts: 1,
70 ids: new Set(),
71 clean: (text) => redact(text, input.apiKey),
72 deadline: AbortSignal.timeout(deps.deadlineMs ?? RUN_DEADLINE_MS),
73 };
74
75 const api = new Apiauto({
76 apiKey: input.apiKey,
77 baseUrl: API_BASE_URL,
78 timeout: deps.timeoutMs ?? REQUEST_TIMEOUT_MS,
79 maxRetries: 0,
80 fetch: guardedFetch(deps.fetch ?? ((url, init) => globalThis.fetch(url, init)), state.deadline),
81 });
82
83 try {
84 await readPages(api, input, state, deps);
85 } catch (rawError) {
86 const error = state.deadline.aborted ? new DeadlineError() : rawError;
87 return reportFailure(error, input, state, deps);
88 }
89 const message = state.clean(finishedMessage(input, state, api.lastResponse?.quotaRemaining));
90 deps.log.info(message);
91 return { ok: true, saved: state.saved, message };
92}
93
94class DeadlineError extends Error {}
95class KeyInRecordError extends Error {}
96class WrongRecordsError extends Error {}
97class LoopError extends Error {}
98
99class SaveError extends Error {
100 constructor(count) {
101 super('saving failed');
102 this.count = count;
103 }
104}
105
106
107async function readPages(api, input, state, deps) {
108 const fetchPage = input.mode === 'search' ? (query) => api.cars(query) : (query) => api.changes(query);
109 const seenCursors = new Set();
110 let cursor;
111 const readLimit = input.maxRecords * MAX_READ_FACTOR;
112 while (state.saved < input.maxRecords && state.read < readLimit) {
113 if (state.deadline.aborted) throw new DeadlineError();
114 const query = { ...input.query, market: MARKET, limit: Math.min(PAGE_SIZE, input.maxRecords - state.saved, readLimit - state.read) };
115 if (AUCTION !== null) query.source = AUCTION;
116 if (cursor !== undefined) query.cursor = cursor;
117 const page = await withRetries(() => fetchPage(query), state, deps);
118 await savePage(page, input, state, deps);
119
120 const next = page.next_cursor;
121 if (typeof next !== 'string' || next === '' || page.items.length === 0) return;
122 if (next === cursor || seenCursors.has(next)) throw new LoopError();
123 seenCursors.add(next);
124 cursor = next;
125 }
126}
127
128async function withRetries(attempt, state, deps) {
129 for (state.attempts = 1; ; state.attempts += 1) {
130 try {
131 return await attempt();
132 } catch (error) {
133 const retry = error instanceof ApiautoError && RETRY_STATUSES.has(error.status) && state.attempts <= MAX_RETRIES;
134 if (!retry) throw error;
135 await (deps.sleep ?? sleepUntil(state.deadline))(retryDelayMs(error, state.attempts));
136 }
137 }
138}
139
140
141function sleepUntil(deadline) {
142 return (ms) =>
143 new Promise((resolve, reject) => {
144 const timer = setTimeout(resolve, ms);
145 deadline.addEventListener('abort', () => {
146 clearTimeout(timer);
147 reject(new DeadlineError());
148 }, { once: true });
149 });
150}
151
152function retryDelayMs(error, attempt) {
153 if (typeof error.retryAfter === 'number' && error.retryAfter >= 0) {
154 return Math.min(error.retryAfter, MAX_RETRY_AFTER_SECONDS) * 1000;
155 }
156 return Math.round(Math.min(500 * 2 ** (attempt - 1), 8000) * (0.75 + Math.random() * 0.25));
157}
158
159async function savePage(page, input, state, deps) {
160 if (!Array.isArray(page?.items) || page.items.some((item) => item === null || typeof item !== 'object')) {
161 throw new WrongRecordsError();
162 }
163 state.read += page.items.length;
164 state.others += page.items.filter((item) => !isThisAuction(item)).length;
165 const left = input.maxRecords - state.saved;
166 const records = page.items.filter((item) => isThisAuction(item) && !state.ids.has(item.id)).slice(0, left);
167 const escapedKey = JSON.stringify(input.apiKey).slice(1, -1);
168 if (records.some((record) => JSON.stringify(record).includes(escapedKey))) throw new KeyInRecordError();
169 if (records.length === 0) return;
170 const rows = input.mode === 'search' ? records.map(toDatasetCar) : records;
171 try {
172 await deps.pushData(rows);
173 } catch {
174 throw new SaveError(rows.length);
175 }
176 for (const record of records) state.ids.add(record.id);
177 state.saved += rows.length;
178 await deps.setStatus(`Saved ${state.saved} records`);
179}
180
181
182function isThisAuction(item) {
183 return AUCTION === null || String(item.car_id ?? item.id).startsWith(`${AUCTION}:`);
184}
185
186function toDatasetCar({ source_mode: _sourceMode, raw, ...car }) {
187 const source = raw !== null && typeof raw === 'object' ? raw : {};
188 return { ...car, raw: Object.fromEntries(RAW_FIELDS.filter((name) => name in source).map((name) => [name, source[name]])) };
189}
190
191function reportFailure(error, input, state, deps) {
192 const quotaEnded = error instanceof ApiautoError && error.status === 402;
193 const message = state.clean(withSaved(describeError(error, input, state), state.saved) + othersNote(state.others));
194 if (quotaEnded && state.saved > 0) {
195 deps.log.warning(message);
196 return { ok: true, saved: state.saved, message };
197 }
198 deps.log.error(message);
199 return { ok: false, saved: state.saved, message };
200}
201
202function withSaved(text, saved) {
203 return saved > 0 ? `${text} The ${saved} records saved before this stay in the dataset.` : text;
204}
205
206function othersNote(others) {
207 return others > 0 ? ` The API also returned ${others} records of the other auction, which count against the quota and were not saved.` : '';
208}
209
210function finishedMessage(input, { saved, read, others }, quotaRemaining) {
211 const noun = input.mode === 'search' ? 'cars' : 'events';
212 const quota = typeof quotaRemaining === 'number' ? ` Quota left on this key: ${quotaRemaining}.` : '';
213 const note = othersNote(others);
214 const stopped = saved < input.maxRecords && read >= input.maxRecords * MAX_READ_FACTOR;
215 if (saved === 0) {
216 if (stopped) return `Stopped reading after ${read} records, the limit for "maxRecords" of ${input.maxRecords}, and found none for this Actor. Nothing was saved. Raise "maxRecords" to read further.${note}${quota}`;
217 return input.mode === 'search'
218 ? `No cars match these filters. Nothing was saved.${note}${quota}`
219 : `No events since this moment. Nothing was saved.${note}${quota}`;
220 }
221 const reached = saved >= input.maxRecords
222 ? ` Reached the limit of ${input.maxRecords} records; raise "maxRecords" to get more.`
223 : stopped ? ` Stopped reading after ${read} records, the limit for "maxRecords" of ${input.maxRecords}; raise it to read further.` : '';
224 return `Saved ${saved} ${noun}.${reached}${note}${quota}`;
225}
226
227
228function describeError(error, input, state) {
229 if (error instanceof DeadlineError) {
230 return `Stopped: the run limit of ${RUN_DEADLINE_MS / 60_000} minutes was reached. Lower "maxRecords" or run again later.`;
231 }
232 if (error instanceof KeyInRecordError) {
233 return 'Stopped: an API response contained the API key, so it was not saved. Contact the API support.';
234 }
235 if (error instanceof WrongRecordsError) {
236 return 'Stopped: the API answered with records the Actor cannot read. Nothing from that answer was saved. Please report it in the Issues tab.';
237 }
238 if (error instanceof LoopError) {
239 return 'Stopped: the API sent the same page position again, so the run ended instead of spending quota on repeats. Please report it in the Issues tab.';
240 }
241 if (error instanceof SaveError) {
242 return `Stopped: saving to the dataset failed. Some of the last ${error.count} records may be missing or saved in part; the quota for them is already spent. Run again later.`;
243 }
244 if (!(error instanceof ApiautoError)) {
245 return 'Stopped by an unexpected error in the Actor. Please report it in the Issues tab.';
246 }
247 if (error.status === null) {
248 return 'Could not get an answer from the API: network error or timeout. The request was not repeated, because the API may have counted it against your quota. Run again later.';
249 }
250 const later = readSeconds(error.retryAfter);
251 const tries = state.attempts > 1 ? ` after ${state.attempts} attempts` : '';
252 switch (error.status) {
253 case 400:
254 return `The API refused the request: ${shortDetail(error.detail, state.clean)}`;
255 case 401:
256 return 'The API key was refused: it is wrong or revoked, or its subscription has ended. Check the "apiKey" input.';
257 case 402:
258 return `The quota of this key is spent${readDate(error.resetAt)}.`;
259 case 403:
260 return describeForbidden(error, input, state.clean);
261 case 429:
262 return `The API still reports too many requests${tries}.${later} The limit depends on the plan of the key.`;
263 default:
264 return error.status >= 500
265 ? `The API is temporarily unavailable (HTTP ${error.status})${tries}.${later || ' Try again later.'}`
266 : `The API answered with HTTP ${error.status}: ${shortDetail(error.detail, state.clean)}`;
267 }
268}
269
270function describeForbidden(error, input, clean) {
271 if (error.code === 'feature_not_in_plan') {
272 return input.mode === 'changes'
273 ? 'The change feed is available on the Pro plan and higher, and this key has a lower plan. Use "Search cars" mode or change the plan of the key.'
274 : `This key's plan does not include this feature: ${shortDetail(error.detail, clean)}`;
275 }
276 if (error.code === 'market_not_in_plan') {
277 const markets = Array.isArray(error.markets) ? error.markets.filter((item) => /^[a-z]{2}$/.test(item)) : [];
278 const included = markets.length > 0 ? ` It includes: ${markets.join(', ')}.` : '';
279 return `This key's plan does not include the ${MARKET_NAME} market (${MARKET}).${included}`;
280 }
281 return 'The API refused access for this key.';
282}
283
284
285function shortDetail(detail, clean) {
286 if (typeof detail !== 'string' || detail === '') return 'no details given.';
287 const flat = clean(detail).replace(/[\u0000-\u001f\u007f]+/g, ' ').trim();
288 return flat.length > MAX_DETAIL_LENGTH ? `${flat.slice(0, MAX_DETAIL_LENGTH)}…` : flat;
289}
290
291function readSeconds(value) {
292 return typeof value === 'number' && Number.isFinite(value) && value > 0
293 ? ` Try again in ${Math.ceil(value)} s.`
294 : '';
295}
296
297function readDate(value) {
298 return typeof value === 'string' && !Number.isNaN(Date.parse(value))
299 ? `; it renews at ${new Date(value).toISOString()}`
300 : '';
301}
302
303export function redact(text, apiKey) {
304 return String(text).split(apiKey).join('[hidden]');
305}