import { STATS_MINING_TAG } from '../shared/anki-source'; export interface PollingRunnerDeps { getDeck: () => string | undefined; getPollingRate: () => number; findNotes: ( query: string, options?: { maxRetries?: number; }, ) => Promise; shouldAutoUpdateNewCards: () => boolean; processNewCard: (noteId: number) => Promise; recordCardsAdded?: (count: number, noteIds: number[]) => void; /** Called once SubMiner is done with a new note: after enrichment, or at detection when it is off. */ onCardsReady?: (noteIds: number[]) => void; isUpdateInProgress: () => boolean; setUpdateInProgress: (value: boolean) => void; getTrackedNoteIds: () => Set; setTrackedNoteIds: (noteIds: Set) => void; showStatusNotification: (message: string) => void; logDebug: (...args: unknown[]) => void; logInfo: (...args: unknown[]) => void; logWarn: (...args: unknown[]) => void; } export class PollingRunner { private pollingInterval: ReturnType | null = null; // Keeps interval ticks from stacking up behind a slow read, now that reads skip the update lock. private pollInFlight = false; private initialized = false; private backoffMs = 200; private maxBackoffMs = 5000; private nextPollTime = 0; constructor(private readonly deps: PollingRunnerDeps) {} get isRunning(): boolean { return this.pollingInterval !== null; } start(): void { if (this.pollingInterval) { this.stop(); } void this.pollOnce(); this.pollingInterval = setInterval(() => { void this.pollOnce(); }, this.deps.getPollingRate()); } stop(): void { if (this.pollingInterval) { clearInterval(this.pollingInterval); this.pollingInterval = null; } } async pollOnce(): Promise { if (this.pollInFlight || this.deps.isUpdateInProgress()) return; if (Date.now() < this.nextPollTime) return; this.pollInFlight = true; let holdsUpdateLock = false; try { const query = this.deps.getDeck() ? `"deck:${this.deps.getDeck()}" added:1` : 'added:1'; // The read runs without the update lock: mining checks that lock and gives up when it is // held, so holding it for a routine poll would drop a card mined at the wrong moment. const noteIds = await this.deps.findNotes(query, { maxRetries: 0, }); // An update started during the read (its creator tracks any note it adds), so leave the // new notes to the next poll. if (this.deps.isUpdateInProgress()) return; this.deps.setUpdateInProgress(true); holdsUpdateLock = true; const currentNoteIds = new Set(noteIds); const previousNoteIds = this.deps.getTrackedNoteIds(); if (!this.initialized) { // Keep notes mined while the read was pending; the read may have started before they existed. for (const noteId of previousNoteIds) currentNoteIds.add(noteId); this.deps.setTrackedNoteIds(currentNoteIds); this.initialized = true; this.deps.logInfo(`AnkiConnect initialized with ${currentNoteIds.size} existing cards`); this.backoffMs = 200; return; } const newNoteIds = Array.from(currentNoteIds).filter((id) => !previousNoteIds.has(id)); if (newNoteIds.length > 0) { this.deps.logInfo('Found new cards:', newNoteIds); for (const noteId of newNoteIds) { previousNoteIds.add(noteId); } this.deps.setTrackedNoteIds(previousNoteIds); this.deps.recordCardsAdded?.(newNoteIds.length, newNoteIds); // Stats cards still count and update known words, but do not trigger plugins. const pluginNoteIds = new Set(); if (this.deps.onCardsReady) { try { const statsNoteIds = new Set( await this.deps.findNotes(`nid:${newNoteIds.join(',')} tag:"${STATS_MINING_TAG}"`, { maxRetries: 0, }), ); for (const noteId of newNoteIds) { if (!statsNoteIds.has(noteId)) pluginNoteIds.add(noteId); } } catch (error) { this.deps.logWarn( 'Skipping plugin events because note sources could not be checked:', error, ); } } if (this.deps.shouldAutoUpdateNewCards()) { for (const noteId of newNoteIds) { try { await this.deps.processNewCard(noteId); } catch (error) { // One failed note must not leave the rest of the batch unprocessed. this.deps.logWarn(`Failed to auto-enrich note ${noteId}:`, (error as Error).message); } finally { if (pluginNoteIds.has(noteId)) this.deps.onCardsReady?.([noteId]); } } } else { if (pluginNoteIds.size > 0) this.deps.onCardsReady?.([...pluginNoteIds]); this.deps.logInfo( 'New card detected (auto-update disabled). Press Ctrl+V to update from clipboard.', ); } } if (this.backoffMs > 200) { this.deps.logInfo('AnkiConnect connection restored'); } this.backoffMs = 200; } catch (error) { const wasBackingOff = this.backoffMs > 200; this.backoffMs = Math.min(this.backoffMs * 2, this.maxBackoffMs); this.nextPollTime = Date.now() + this.backoffMs; if (!wasBackingOff) { this.deps.logWarn('AnkiConnect polling failed, backing off...'); this.deps.showStatusNotification('AnkiConnect: unable to connect'); } this.deps.logWarn((error as Error).message); } finally { this.pollInFlight = false; if (holdsUpdateLock) this.deps.setUpdateInProgress(false); } } async poll(): Promise { if (this.pollingInterval) { return; } return this.pollOnce(); } }