|
| 1 | +import type { OpenClawPluginApi } from "openclaw/plugin-sdk"; |
| 2 | +import { refreshTokenProactively } from "../api/linear-api.js"; |
| 3 | + |
| 4 | +const REFRESH_INTERVAL_MS = 6 * 60 * 60 * 1000; // 6 hours |
| 5 | + |
| 6 | +let timer: ReturnType<typeof setInterval> | null = null; |
| 7 | + |
| 8 | +/** |
| 9 | + * Start the proactive token refresh timer. |
| 10 | + * Runs immediately on start, then every 6 hours. |
| 11 | + */ |
| 12 | +export function startTokenRefreshTimer( |
| 13 | + api: OpenClawPluginApi, |
| 14 | + pluginConfig?: Record<string, unknown>, |
| 15 | +): void { |
| 16 | + // Run immediately |
| 17 | + doRefresh(api, pluginConfig); |
| 18 | + |
| 19 | + // Then schedule periodic refresh |
| 20 | + timer = setInterval(() => doRefresh(api, pluginConfig), REFRESH_INTERVAL_MS); |
| 21 | + // Don't keep the process alive just for this timer |
| 22 | + if (timer && typeof timer === "object" && "unref" in timer) { |
| 23 | + timer.unref(); |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +/** |
| 28 | + * Stop the proactive token refresh timer. |
| 29 | + */ |
| 30 | +export function stopTokenRefreshTimer(): void { |
| 31 | + if (timer) { |
| 32 | + clearInterval(timer); |
| 33 | + timer = null; |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +async function doRefresh( |
| 38 | + api: OpenClawPluginApi, |
| 39 | + pluginConfig?: Record<string, unknown>, |
| 40 | +): Promise<void> { |
| 41 | + try { |
| 42 | + const result = await refreshTokenProactively(pluginConfig); |
| 43 | + if (result.refreshed) { |
| 44 | + api.logger.info(`Token refresh: ${result.reason}`); |
| 45 | + } else { |
| 46 | + api.logger.debug?.(`Token refresh skipped: ${result.reason}`); |
| 47 | + } |
| 48 | + } catch (err) { |
| 49 | + api.logger.warn(`Token refresh failed: ${err}`); |
| 50 | + } |
| 51 | +} |
0 commit comments