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 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 | 26x 26x 366x 366x 366x 366x 366x 366x 366x 366x 39x 1x 38x 38x 38x 1x 2x 7x 7x 6x 1x 6x 4x 37x 36x 36x 3x 315x 315x 315x 35x 4x 4x 35x 2x 35x 2x 315x 2x 2x 315x 14x 14x 2x 12x 3x 3x 2x 1x 1x 1x 1x 1x 20x 20x 19x 20x 35x 35x 6x 5x 4x 4x 4x 4x 4x 20x 4x 16x 16x 16x 16x 16x 16x 33x 33x 16x 16x 16x 10x 10x 16x 9x 9x 9x 9x 16x 10x 7x 7x 7x 7x 7x 7x 1x 1x 1x 1x 7x 16x 16x 16x 16x 16x 16x 16x | import type Database from "better-sqlite3-multiple-ciphers";
import { ConnectionPool, type ConnectionPoolOptions } from "./connection-pool.js";
import type {
ImapConfig,
RelabelResult,
SyncAllResult,
SyncError,
SyncProgress,
} from "./imap-sync.js";
/**
* Progress snapshot for an actively-running sync, as exposed to callers
* via getStatus(). Includes a startedAt timestamp so callers can compute
* elapsed time and estimate remaining time.
*/
export interface ActiveSyncProgress {
currentFolder: string | null;
foldersCompleted: number;
totalFolders: number;
messagesNew: number;
errors: number;
startedAt: number;
}
export interface ConnectorSyncConfig {
inboundConnectorId: number;
imapConfig: ImapConfig;
/** Sync interval in ms (default: 5 minutes) */
intervalMs?: number;
}
/** @deprecated Use ConnectorSyncConfig */
export type IdentitySyncConfig = ConnectorSyncConfig;
export interface SyncSchedulerOptions {
/** Default sync interval in ms (default: 5 minutes) */
defaultIntervalMs?: number;
/** Connection pool options */
poolOptions?: ConnectionPoolOptions;
/** Called when a sync completes */
onSyncComplete?: (inboundConnectorId: number, result: SyncAllResult) => void;
/** Called immediately when a sync error is recorded (for inline logging) */
onSyncRecordError?: (inboundConnectorId: number, error: SyncError) => void;
/** Called when a sync fails */
onSyncError?: (inboundConnectorId: number, error: Error) => void;
}
interface ScheduledConnector {
config: ConnectorSyncConfig;
timer: ReturnType<typeof setInterval> | null;
running: boolean;
lastSync: number | null;
lastError: string | null;
consecutiveErrors: number;
/** Active abort controller for cancelling a running sync */
abortController: AbortController | null;
/** Promise that resolves when the current sync completes */
syncPromise: Promise<void> | null;
/** Real-time progress of the current sync, null when not running */
progress: ActiveSyncProgress | null;
}
const DEFAULT_INTERVAL_MS = 5 * 60 * 1000;
const MAX_BACKOFF_MS = 30 * 60 * 1000;
/**
* Manages periodic background sync for multiple IMAP inbound connectors.
*
* Each connector syncs on its own interval. Failed syncs use exponential
* backoff to avoid hammering a broken server. Uses ConnectionPool to
* reuse IMAP connections across sync cycles.
*/
export class SyncScheduler {
private connectors: Map<number, ScheduledConnector> = new Map();
private pool: ConnectionPool;
private db: Database.Database;
private defaultIntervalMs: number;
private onSyncComplete?: (inboundConnectorId: number, result: SyncAllResult) => void;
private onSyncRecordError?: (inboundConnectorId: number, error: SyncError) => void;
private onSyncError?: (inboundConnectorId: number, error: Error) => void;
private started = false;
constructor(db: Database.Database, options: SyncSchedulerOptions = {}) {
this.db = db;
this.defaultIntervalMs = options.defaultIntervalMs ?? DEFAULT_INTERVAL_MS;
this.pool = new ConnectionPool(db, options.poolOptions);
this.onSyncComplete = options.onSyncComplete;
this.onSyncRecordError = options.onSyncRecordError;
this.onSyncError = options.onSyncError;
}
/**
* Adds an inbound connector to the scheduler.
* If the scheduler is already started, begins syncing immediately.
*/
addConnector(config: ConnectorSyncConfig): void {
if (this.connectors.has(config.inboundConnectorId)) {
throw new Error(`Connector ${config.inboundConnectorId} is already scheduled`);
}
const scheduled: ScheduledConnector = {
config,
timer: null,
running: false,
lastSync: null,
lastError: null,
consecutiveErrors: 0,
abortController: null,
syncPromise: null,
progress: null,
};
this.connectors.set(config.inboundConnectorId, scheduled);
if (this.started) {
this.startConnectorSync(scheduled);
}
}
/** @deprecated Use addConnector */
addIdentity(config: ConnectorSyncConfig): void {
this.addConnector(config);
}
/**
* Removes an inbound connector from the scheduler and releases its connections.
*/
removeConnector(inboundConnectorId: number): void {
const scheduled = this.connectors.get(inboundConnectorId);
if (!scheduled) return;
if (scheduled.timer) {
clearInterval(scheduled.timer);
}
this.connectors.delete(inboundConnectorId);
}
/** @deprecated Use removeConnector */
removeIdentity(inboundConnectorId: number): void {
this.removeConnector(inboundConnectorId);
}
/**
* Starts the scheduler — begins periodic sync for all registered connectors.
*/
start(): void {
if (this.started) return;
this.started = true;
for (const scheduled of this.connectors.values()) {
this.startConnectorSync(scheduled);
}
}
/**
* Stops the scheduler — cancels all timers, aborts running syncs,
* waits for them to finish (up to 5s), then closes all connections.
*/
async stop(): Promise<void> {
this.started = false;
const pendingSyncs: Promise<void>[] = [];
for (const scheduled of this.connectors.values()) {
if (scheduled.timer) {
clearInterval(scheduled.timer);
scheduled.timer = null;
}
// Signal running syncs to stop
if (scheduled.abortController) {
scheduled.abortController.abort();
}
if (scheduled.syncPromise) {
pendingSyncs.push(scheduled.syncPromise);
}
}
// Wait for running syncs to finish gracefully (max 5 seconds)
if (pendingSyncs.length > 0) {
const timeout = new Promise<void>((resolve) => setTimeout(resolve, 5000));
await Promise.race([Promise.allSettled(pendingSyncs), timeout]);
}
await this.pool.shutdown();
}
/**
* Triggers an immediate sync for a specific inbound connector.
* Returns the sync result, or throws if the connector is already syncing.
*/
async syncNow(inboundConnectorId: number): Promise<SyncAllResult> {
const scheduled = this.connectors.get(inboundConnectorId);
if (!scheduled) {
throw new Error(`Connector ${inboundConnectorId} is not registered`);
}
return this.runSync(scheduled);
}
/**
* Deletes all locally-synced messages (deleted_from_server = 0) from the IMAP server
* for a specific inbound connector. Used as a one-time cleanup when transitioning
* from mirror mode to connector mode.
*
* Groups messages by folder and uses the existing deleteFromServer() batch-delete
* pattern (100 UIDs at a time) for crash safety.
*/
async cleanServerNow(inboundConnectorId: number): Promise<{ deleted: number }> {
const scheduled = this.connectors.get(inboundConnectorId);
if (!scheduled) {
throw new Error(`Connector ${inboundConnectorId} is not registered`);
}
const rows = this.db
.prepare(
`SELECT f.path AS folder_path, m.uid
FROM messages m
JOIN folders f ON m.folder_id = f.id
WHERE m.inbound_connector_id = ? AND m.deleted_from_server = 0
ORDER BY f.path`,
)
.all(inboundConnectorId) as { folder_path: string; uid: number }[];
Eif (rows.length === 0) return { deleted: 0 };
// Group UIDs by folder path
const byFolder = new Map<string, number[]>();
for (const row of rows) {
const uids = byFolder.get(row.folder_path) ?? [];
uids.push(row.uid);
byFolder.set(row.folder_path, uids);
}
const sync = await this.pool.acquire(inboundConnectorId, scheduled.config.imapConfig);
let totalDeleted = 0;
try {
for (const [folderPath, uids] of byFolder) {
totalDeleted += await sync.deleteFromServer(folderPath, uids);
}
} finally {
this.pool.release(inboundConnectorId, sync);
}
return { deleted: totalDeleted };
}
/**
* Reconciles folder labels against current server state for a specific
* inbound connector. Detects cross-folder moves via Message-ID and updates
* labels to match the server's current folder memberships.
*/
async relabelFromServerNow(inboundConnectorId: number): Promise<RelabelResult> {
const scheduled = this.connectors.get(inboundConnectorId);
Eif (!scheduled) {
throw new Error(`Connector ${inboundConnectorId} is not registered`);
}
const sync = await this.pool.acquire(inboundConnectorId, scheduled.config.imapConfig);
try {
return await sync.relabelFromServer();
} finally {
this.pool.release(inboundConnectorId, sync);
}
}
/**
* Returns the status of all scheduled connectors.
*/
getStatus(): Map<
number,
{
running: boolean;
lastSync: number | null;
lastError: string | null;
consecutiveErrors: number;
progress: ActiveSyncProgress | null;
}
> {
const status = new Map<
number,
{
running: boolean;
lastSync: number | null;
lastError: string | null;
consecutiveErrors: number;
progress: ActiveSyncProgress | null;
}
>();
for (const [inboundConnectorId, scheduled] of this.connectors) {
status.set(inboundConnectorId, {
running: scheduled.running,
lastSync: scheduled.lastSync,
lastError: scheduled.lastError,
consecutiveErrors: scheduled.consecutiveErrors,
progress: scheduled.progress,
});
}
return status;
}
/**
* Loads all IMAP inbound connectors from the database and adds them to the scheduler.
* Cloudflare Email connectors are push-based (webhook/R2) and don't need polling.
*/
loadConnectorsFromDb(): void {
const connectors = this.db
.prepare(
`SELECT id, imap_host, imap_port, imap_tls, imap_user, imap_pass
FROM inbound_connectors
WHERE type = 'imap'`,
)
.all() as {
id: number;
imap_host: string;
imap_port: number;
imap_tls: number;
imap_user: string;
imap_pass: string;
}[];
for (const connector of connectors) {
if (this.connectors.has(connector.id)) continue;
this.addConnector({
inboundConnectorId: connector.id,
imapConfig: {
host: connector.imap_host,
port: connector.imap_port,
secure: connector.imap_tls === 1,
auth: {
user: connector.imap_user,
pass: connector.imap_pass,
},
},
});
}
}
/** @deprecated Use loadConnectorsFromDb */
loadIdentitiesFromDb(): void {
this.loadConnectorsFromDb();
}
private startConnectorSync(scheduled: ScheduledConnector): void {
// Run an initial sync immediately
this.runSync(scheduled).catch(() => {});
const intervalMs = scheduled.config.intervalMs ?? this.defaultIntervalMs;
scheduled.timer = setInterval(() => {
this.runSync(scheduled).catch(() => {});
}, intervalMs);
}
private async runSync(scheduled: ScheduledConnector): Promise<SyncAllResult> {
if (scheduled.running) {
throw new Error(`Connector ${scheduled.config.inboundConnectorId} is already syncing`);
}
scheduled.running = true;
scheduled.progress = {
currentFolder: null,
foldersCompleted: 0,
totalFolders: 0,
messagesNew: 0,
errors: 0,
startedAt: Date.now(),
};
const inboundConnectorId = scheduled.config.inboundConnectorId;
const abortController = new AbortController();
scheduled.abortController = abortController;
const onProgress = (p: SyncProgress) => {
Iif (!scheduled.progress) return;
scheduled.progress = {
currentFolder: p.currentFolder ?? null,
foldersCompleted: p.foldersCompleted,
totalFolders: p.totalFolders,
messagesNew: p.messagesNew,
errors: p.errors,
startedAt: scheduled.progress.startedAt,
};
};
const doSync = async (): Promise<SyncAllResult> => {
try {
const sync = await this.pool.acquire(inboundConnectorId, scheduled.config.imapConfig);
try {
const onError = this.onSyncRecordError
? (err: SyncError) => this.onSyncRecordError?.(inboundConnectorId, err)
: undefined;
const result = await sync.syncAll(abortController.signal, onProgress, onError);
scheduled.lastSync = Date.now();
scheduled.lastError = null;
scheduled.consecutiveErrors = 0;
this.onSyncComplete?.(inboundConnectorId, result);
return result;
} finally {
this.pool.release(inboundConnectorId, sync);
}
} catch (err) {
const error = err instanceof Error ? err : new Error(String(err));
// ImapFlow puts the actual server response in responseText, not message
const imapErr = error as Error & { responseText?: string; responseStatus?: string };
scheduled.lastError = imapErr.responseText
? `${imapErr.responseStatus ?? "ERROR"}: ${imapErr.responseText}`
: error.message;
scheduled.consecutiveErrors++;
this.onSyncError?.(inboundConnectorId, error);
// Apply exponential backoff by rescheduling with delay
if (scheduled.consecutiveErrors > 1 && scheduled.timer) {
clearInterval(scheduled.timer);
const baseInterval = scheduled.config.intervalMs ?? this.defaultIntervalMs;
const backoffMs = Math.min(
baseInterval * 2 ** (scheduled.consecutiveErrors - 1),
MAX_BACKOFF_MS,
);
scheduled.timer = setInterval(() => {
this.runSync(scheduled).catch(() => {});
}, backoffMs);
}
throw error;
} finally {
scheduled.running = false;
scheduled.progress = null;
scheduled.abortController = null;
scheduled.syncPromise = null;
}
};
const promise = doSync();
scheduled.syncPromise = promise.then(() => {}).catch(() => {}); // Track without propagating rejection
return promise;
}
}
|