117 lines
5.3 KiB
TypeScript
117 lines
5.3 KiB
TypeScript
// AK-P16a · calendar sync engine (M25 Block D/E). The external -> HiveGrid
|
|
// read-only path: pull the provider delta via the stored cursor and upsert each
|
|
// event into the CalendarEvent cache (through the pure eventMapping). Tokens are
|
|
// refreshed transparently when expired. The cache feeds availability (busy slots
|
|
// only — leak-protection happens at the availability boundary, not here).
|
|
//
|
|
// A 410 (sync_token_invalid) triggers a full re-pull of the rolling window. The
|
|
// bidirectional WRITE path (HiveGrid -> Google) + the conflict-on-mapped-event
|
|
// path build on top of this and the ConflictResolver; they require the write
|
|
// service (mappings) and are wired as that lands.
|
|
|
|
import { encryptTenantField } from "@hivegrid/db/crypto/tenant-envelope.server";
|
|
import { db } from "~/utils/db.server";
|
|
import { googleCalendarAdapter } from "./adapters/GoogleCalendarAdapter.server";
|
|
import type { CalendarCreds } from "./adapters/CalendarAdapter";
|
|
import { loadConnectionCreds } from "./CalendarConnectionService.server";
|
|
import { toExternalEventFields } from "./eventMapping";
|
|
|
|
const WINDOW_PAST_DAYS = 7;
|
|
const WINDOW_FUTURE_DAYS = 60;
|
|
const PRIMARY_CALENDAR = "primary";
|
|
|
|
/** Ensure the access token is fresh; refresh + re-seal when within 60s of expiry. */
|
|
async function ensureFreshCreds(tenantId: string, connectionId: string, creds: CalendarCreds): Promise<CalendarCreds> {
|
|
const soon = Date.now() + 60_000;
|
|
if (creds.expiresAt && creds.expiresAt.getTime() > soon) {
|
|
return creds;
|
|
}
|
|
const next = await googleCalendarAdapter.refreshTokens(creds.refreshToken);
|
|
const accessCiphertext = await encryptTenantField(tenantId, next.accessToken);
|
|
await db.calendarConnection.update({
|
|
where: { id: connectionId },
|
|
data: { oauthAccessTokenCiphertext: accessCiphertext, oauthAccessTokenExpiresAt: next.expiresAt, status: "active", lastErrorText: null },
|
|
});
|
|
return { accessToken: next.accessToken, refreshToken: creds.refreshToken, expiresAt: next.expiresAt };
|
|
}
|
|
|
|
export interface SyncResult {
|
|
readonly upserted: number;
|
|
readonly fullResync: boolean;
|
|
}
|
|
|
|
/**
|
|
* Run one incremental external -> cache sync for a connection's primary calendar.
|
|
* Idempotent: re-running with the same cursor is a no-op; a 410 forces a full
|
|
* window re-pull. Returns the number of events written.
|
|
*/
|
|
export async function syncConnection(tenantId: string, connectionId: string, now: Date = new Date()): Promise<SyncResult> {
|
|
const baseCreds = await loadConnectionCreds(tenantId, connectionId);
|
|
if (!baseCreds) {
|
|
return { upserted: 0, fullResync: false };
|
|
}
|
|
const connection = await db.calendarConnection.findFirst({ where: { id: connectionId, tenantId }, select: { userId: true } });
|
|
if (!connection) {
|
|
return { upserted: 0, fullResync: false };
|
|
}
|
|
|
|
let creds: CalendarCreds;
|
|
try {
|
|
creds = await ensureFreshCreds(tenantId, connectionId, baseCreds);
|
|
} catch {
|
|
await db.calendarConnection.update({ where: { id: connectionId }, data: { status: "error", lastErrorText: "calendar.health.tokenExpired" } });
|
|
return { upserted: 0, fullResync: false };
|
|
}
|
|
|
|
const cursor = await db.calendarSyncCursor.findFirst({ where: { connectionId, externalCalendarId: PRIMARY_CALENDAR }, select: { cursorToken: true } });
|
|
|
|
let upserted = 0;
|
|
let fullResync = false;
|
|
let pageToken: string | undefined;
|
|
let nextSyncToken: string | undefined;
|
|
let syncToken = cursor?.cursorToken ?? undefined;
|
|
|
|
do {
|
|
const page = await googleCalendarAdapter.fetchEvents(creds, PRIMARY_CALENDAR, {
|
|
syncToken,
|
|
pageToken,
|
|
timeMin: syncToken ? undefined : new Date(now.getTime() - WINDOW_PAST_DAYS * 86_400_000),
|
|
timeMax: syncToken ? undefined : new Date(now.getTime() + WINDOW_FUTURE_DAYS * 86_400_000),
|
|
});
|
|
|
|
if (page.fullResyncRequired) {
|
|
// Cursor expired (410): drop it and restart this run as an initial pull.
|
|
fullResync = true;
|
|
syncToken = undefined;
|
|
pageToken = undefined;
|
|
await db.calendarSyncCursor.updateMany({ where: { connectionId, externalCalendarId: PRIMARY_CALENDAR }, data: { cursorToken: null } });
|
|
continue;
|
|
}
|
|
|
|
for (const event of page.events) {
|
|
const fields = toExternalEventFields(event, { tenantId, userId: connection.userId, connectionId, provider: "google", externalCalendarId: PRIMARY_CALENDAR }, now);
|
|
await db.calendarEvent.upsert({
|
|
where: { tenantId_userId_provider_externalEventId: { tenantId, userId: connection.userId, provider: "google", externalEventId: event.externalId } },
|
|
create: fields,
|
|
update: { ...fields, createdAt: undefined } as never,
|
|
});
|
|
upserted += 1;
|
|
}
|
|
|
|
pageToken = page.nextPageToken;
|
|
nextSyncToken = page.nextSyncToken ?? nextSyncToken;
|
|
} while (pageToken);
|
|
|
|
// Persist the new cursor + stamp the successful sync.
|
|
if (nextSyncToken) {
|
|
await db.calendarSyncCursor.upsert({
|
|
where: { connectionId_externalCalendarId: { connectionId, externalCalendarId: PRIMARY_CALENDAR } },
|
|
create: { tenantId, connectionId, externalCalendarId: PRIMARY_CALENDAR, cursorToken: nextSyncToken, lastFullSyncAt: fullResync ? now : null },
|
|
update: { cursorToken: nextSyncToken, ...(fullResync ? { lastFullSyncAt: now } : {}) },
|
|
});
|
|
}
|
|
await db.calendarConnection.update({ where: { id: connectionId }, data: { lastSyncAt: now, status: "active" } });
|
|
|
|
return { upserted, fullResync };
|
|
}
|