Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/integrations/src/admin-calendar-sync-worker.server.ts
T

369 lines
11 KiB
TypeScript

import {
createAdminCalendarService,
createPrismaAdminCalendarRepository,
type AdminCalendarBusyInterval,
} from "@hivegrid/db/admin-calendar.server";
import {
createAdminConnectionsService,
createPrismaAdminConnectionsRepository,
} from "@hivegrid/db/admin-connections.server";
import {
GoogleCalendarError,
listEvents,
refreshAccessToken,
resolveGoogleOAuthConfig,
} from "./google/googleCalendarApi.js";
import {
buildInitialCalendarDeltaUrl,
fetchCalendarDeltaPage,
GraphCalendarError,
refreshMicrosoftCalendarToken,
resolveMicrosoftCalendarOAuthConfig,
} from "./microsoft/graphCalendarApi.js";
type Provider = "google_calendar" | "microsoft_calendar";
type SyncTarget = {
readonly id: string;
readonly adminUserId: string;
readonly calendarConnectionId: string;
readonly externalCalendarId: string;
readonly cursorToken: string | null;
readonly deltaLink: string | null;
readonly busyIntervals: unknown;
readonly status: string;
readonly calendarConnection: {
readonly dataConnectionId: string;
readonly dataConnection: {
readonly provider: Provider;
readonly tokenExpiresAt: Date | null;
};
};
};
export type AdminCalendarSyncWorkerClient = {
readonly $transaction: (...args: never[]) => Promise<unknown>;
readonly adminCalendarSyncCursor: {
findMany(input: Record<string, unknown>): Promise<SyncTarget[]>;
};
};
type Credentials = {
readonly accessToken: string;
readonly refreshToken: string;
readonly expiresAt: string;
readonly scopes: readonly string[];
};
export type AdminCalendarProviderSyncInput = {
readonly provider: Provider;
readonly accessToken: string;
readonly externalCalendarId: string;
readonly cursorToken: string | null;
readonly deltaLink: string | null;
readonly busyIntervals: readonly AdminCalendarBusyInterval[];
readonly now: Date;
};
export async function syncAdminCalendarBusySnapshots(
client: AdminCalendarSyncWorkerClient,
options: {
readonly now?: Date;
readonly take?: number;
readonly env?: NodeJS.ProcessEnv;
readonly provider?: typeof defaultProvider;
} = {}
) {
const now = options.now ?? new Date();
const targets = await client.adminCalendarSyncCursor.findMany({
where: {
status: { in: ["pending", "active", "recovery_required", "failed"] },
calendarConnection: {
status: { in: ["active", "degraded"] },
archivedAt: null,
dataConnection: {
status: { in: ["active", "degraded"] },
archivedAt: null,
},
},
},
orderBy: [{ lastIncrementalSyncAt: "asc" }, { id: "asc" }],
take: options.take ?? 25,
select: {
id: true,
adminUserId: true,
calendarConnectionId: true,
externalCalendarId: true,
cursorToken: true,
deltaLink: true,
busyIntervals: true,
status: true,
calendarConnection: {
select: {
dataConnectionId: true,
dataConnection: {
select: { provider: true, tokenExpiresAt: true },
},
},
},
},
});
const connections = createAdminConnectionsService({
repository: createPrismaAdminConnectionsRepository(client as never),
authorize: () => undefined,
permission: "admin_sales.booking.manage",
});
const calendars = createAdminCalendarService({
repository: createPrismaAdminCalendarRepository(client as never),
authorize: () => undefined,
});
const provider = options.provider ?? defaultProvider;
const failed: string[] = [];
let synced = 0;
for (const target of targets) {
try {
await connections.withCredentials(
target.calendarConnection.dataConnectionId,
target.adminUserId,
async (raw) => {
let credentials = parseCredentials(raw);
if (
new Date(credentials.expiresAt).getTime() <=
now.getTime() + 60_000
) {
credentials = await provider.refresh(
target.calendarConnection.dataConnection.provider,
credentials,
options.env ?? process.env
);
await connections.refresh({
connectionId: target.calendarConnection.dataConnectionId,
adminUserId: target.adminUserId,
credentials,
scopes: credentials.scopes,
tokenExpiresAt: new Date(credentials.expiresAt),
actor: {
adminUserId: target.adminUserId,
email: "system@worker.invalid",
reason: "Automatische Kalender-Token-Erneuerung",
},
});
}
const fullSync = target.status === "recovery_required";
const result = await provider.sync({
provider:
target.calendarConnection.dataConnection.provider,
accessToken: credentials.accessToken,
externalCalendarId: target.externalCalendarId,
cursorToken: fullSync ? null : target.cursorToken,
deltaLink: fullSync ? null : target.deltaLink,
busyIntervals: parseBusyIntervals(target.busyIntervals),
now,
});
await calendars.applySync({
adminUserId: target.adminUserId,
calendarConnectionId: target.calendarConnectionId,
externalCalendarId: target.externalCalendarId,
busyIntervals: result.busyIntervals,
cursorToken: result.cursorToken,
deltaLink: result.deltaLink,
fullSync: fullSync || (!target.cursorToken && !target.deltaLink),
syncedAt: now,
});
}
);
synced += 1;
} catch (error) {
failed.push(target.id);
if (
(error instanceof GoogleCalendarError &&
error.fullResyncRequired) ||
(error instanceof GraphCalendarError &&
error.fullResyncRequired)
) {
await calendars.requireRecovery({
adminUserId: target.adminUserId,
calendarConnectionId: target.calendarConnectionId,
externalCalendarId: target.externalCalendarId,
errorCode: "provider_cursor_expired",
requestedAt: now,
});
}
}
}
return { inspected: targets.length, synced, failed };
}
const defaultProvider = {
async refresh(
provider: Provider,
current: Credentials,
env: NodeJS.ProcessEnv
): Promise<Credentials> {
if (provider === "google_calendar") {
const config = resolveGoogleOAuthConfig(env);
if (!config) throw new Error("provider_not_configured");
const next = await refreshAccessToken(config, current.refreshToken);
return {
accessToken: next.accessToken,
refreshToken: next.refreshToken ?? current.refreshToken,
expiresAt: next.expiresAt.toISOString(),
scopes: next.scopes.length ? next.scopes : current.scopes,
};
}
const config = resolveMicrosoftCalendarOAuthConfig(env);
if (!config) throw new Error("provider_not_configured");
const next = await refreshMicrosoftCalendarToken(
config,
current.refreshToken
);
return {
accessToken: next.accessToken,
refreshToken: next.refreshToken ?? current.refreshToken,
expiresAt: next.expiresAt.toISOString(),
scopes: next.scopes.length ? next.scopes : current.scopes,
};
},
async sync(input: AdminCalendarProviderSyncInput) {
return input.provider === "google_calendar"
? syncGoogleCalendarBusySnapshot(input)
: syncMicrosoftCalendarBusySnapshot(input);
},
};
export async function syncGoogleCalendarBusySnapshot(
input: AdminCalendarProviderSyncInput
) {
const intervals = new Map(
input.busyIntervals.map((interval) => [
interval.externalEventId,
interval,
])
);
let pageToken: string | undefined;
let nextCursor: string | undefined;
do {
const page = await listEvents(
input.accessToken,
input.externalCalendarId,
{
syncToken: input.cursorToken ?? undefined,
pageToken,
timeMin: input.cursorToken
? undefined
: new Date(input.now.getTime() - 30 * 86_400_000).toISOString(),
timeMax: input.cursorToken
? undefined
: new Date(input.now.getTime() + 365 * 86_400_000).toISOString(),
}
);
for (const event of page.events) {
const startsAt = event.start?.dateTime;
const endsAt = event.end?.dateTime;
if (
event.status === "cancelled" ||
event.transparency === "transparent" ||
!startsAt ||
!endsAt
) {
intervals.delete(event.id);
} else {
intervals.set(event.id, {
externalEventId: event.id,
startsAt: new Date(startsAt).toISOString(),
endsAt: new Date(endsAt).toISOString(),
opaqueVersion: event.etag,
});
}
}
pageToken = page.nextPageToken;
nextCursor = page.nextSyncToken ?? nextCursor;
} while (pageToken);
if (!nextCursor) throw new Error("provider_cursor_missing");
return {
busyIntervals: [...intervals.values()],
cursorToken: nextCursor,
deltaLink: null,
};
}
export async function syncMicrosoftCalendarBusySnapshot(
input: AdminCalendarProviderSyncInput
) {
const intervals = new Map(
input.busyIntervals.map((interval) => [
interval.externalEventId,
interval,
])
);
let url =
input.deltaLink ??
buildInitialCalendarDeltaUrl(
input.externalCalendarId,
new Date(input.now.getTime() - 30 * 86_400_000),
new Date(input.now.getTime() + 365 * 86_400_000)
);
let deltaLink: string | undefined;
do {
const page = await fetchCalendarDeltaPage(input.accessToken, url);
for (const event of page.events) {
const startsAt = event.start?.dateTime;
const endsAt = event.end?.dateTime;
if (
event["@removed"] ||
event.isCancelled ||
event.showAs === "free" ||
!startsAt ||
!endsAt
) {
intervals.delete(event.id);
} else {
intervals.set(event.id, {
externalEventId: event.id,
startsAt: new Date(startsAt).toISOString(),
endsAt: new Date(endsAt).toISOString(),
opaqueVersion: event.changeKey,
});
}
}
url = page.nextLink ?? "";
deltaLink = page.deltaLink ?? deltaLink;
} while (url);
if (!deltaLink) throw new Error("provider_cursor_missing");
return {
busyIntervals: [...intervals.values()],
cursorToken: null,
deltaLink,
};
}
function parseCredentials(
raw: Readonly<Record<string, unknown>>
): Credentials {
if (
typeof raw.accessToken !== "string" ||
typeof raw.refreshToken !== "string" ||
typeof raw.expiresAt !== "string" ||
!Array.isArray(raw.scopes) ||
raw.scopes.some((scope) => typeof scope !== "string")
) {
throw new Error("invalid_calendar_credentials");
}
return raw as Credentials;
}
function parseBusyIntervals(
value: unknown
): readonly AdminCalendarBusyInterval[] {
if (!Array.isArray(value)) return [];
return value.filter(
(entry): entry is AdminCalendarBusyInterval =>
typeof entry === "object" &&
entry !== null &&
typeof (entry as AdminCalendarBusyInterval).externalEventId ===
"string" &&
typeof (entry as AdminCalendarBusyInterval).startsAt === "string" &&
typeof (entry as AdminCalendarBusyInterval).endsAt === "string"
);
}