mirror of
https://github.com/BetterSEQTA/BetterSEQTA-Plus.git
synced 2026-12-06 19:56:45 +10:30
fix: stop overlapping calendar syncs from duplicating lesson events
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c12793de06
commit
84922f27d2
5 files changed
+124
-15
No files matched your search
@@ -177,6 +177,44 @@ describe("mergeRemoteEventsIntoMap", () => {
|
|||||||
);
|
);
|
||||||
expect(eventMap[key]).toMatchObject({ id: "remote-1", fingerprint: "local-fp" });
|
expect(eventMap[key]).toMatchObject({ id: "remote-1", fingerprint: "local-fp" });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("returns extra remote events for the same lesson as duplicates", () => {
|
||||||
|
const key = `${origin}::${origin}:cal:1`;
|
||||||
|
const eventMap = {
|
||||||
|
[key]: { id: "tracked", date: "2026-07-13", fingerprint: "fp" },
|
||||||
|
};
|
||||||
|
const remote = (id: string) => ({
|
||||||
|
seqtaKey: `${origin}:cal:1`,
|
||||||
|
id,
|
||||||
|
date: "2026-07-13",
|
||||||
|
fingerprint: "fp",
|
||||||
|
});
|
||||||
|
const duplicates = mergeRemoteEventsIntoMap(
|
||||||
|
eventMap,
|
||||||
|
origin,
|
||||||
|
[remote("copy-a"), remote("tracked"), remote("copy-b")],
|
||||||
|
mapKey,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(eventMap[key]).toMatchObject({ id: "tracked" });
|
||||||
|
expect(duplicates.sort()).toEqual(["copy-a", "copy-b"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps the first remote event when none is tracked", () => {
|
||||||
|
const eventMap: Record<string, { id: string; date: string; fingerprint?: string }> = {};
|
||||||
|
const duplicates = mergeRemoteEventsIntoMap(
|
||||||
|
eventMap,
|
||||||
|
origin,
|
||||||
|
[
|
||||||
|
{ seqtaKey: `${origin}:cal:1`, id: "first", date: "2026-07-13", fingerprint: "fp" },
|
||||||
|
{ seqtaKey: `${origin}:cal:1`, id: "second", date: "2026-07-13", fingerprint: "fp" },
|
||||||
|
],
|
||||||
|
mapKey,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(eventMap[`${origin}::${origin}:cal:1`]).toMatchObject({ id: "first" });
|
||||||
|
expect(duplicates).toEqual(["second"]);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("collectOriginDeleteEntries", () => {
|
describe("collectOriginDeleteEntries", () => {
|
||||||
|
|||||||
@@ -122,18 +122,33 @@ export function mergeRemoteEventsIntoMap(
|
|||||||
origin: string,
|
origin: string,
|
||||||
remoteEvents: RemoteSyncedEvent[],
|
remoteEvents: RemoteSyncedEvent[],
|
||||||
mapKey: (origin: string, seqtaKey: string) => string,
|
mapKey: (origin: string, seqtaKey: string) => string,
|
||||||
): void {
|
): string[] {
|
||||||
|
const byKey = new Map<string, RemoteSyncedEvent[]>();
|
||||||
for (const remote of remoteEvents) {
|
for (const remote of remoteEvents) {
|
||||||
if (!remote.seqtaKey.startsWith(origin)) continue;
|
if (!remote.seqtaKey.startsWith(origin)) continue;
|
||||||
const key = mapKey(origin, remote.seqtaKey);
|
const key = mapKey(origin, remote.seqtaKey);
|
||||||
|
const group = byKey.get(key);
|
||||||
|
if (group) group.push(remote);
|
||||||
|
else byKey.set(key, [remote]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Overlapping syncs can create several remote events for one lesson. Keep the tracked one
|
||||||
|
// (or the first seen) and return the rest so the caller can delete them.
|
||||||
|
const duplicateIds: string[] = [];
|
||||||
|
for (const [key, group] of byKey) {
|
||||||
const existing = normalizeEventMapEntry(eventMap[key]);
|
const existing = normalizeEventMapEntry(eventMap[key]);
|
||||||
|
const kept = group.find((remote) => remote.id === existing?.id) ?? group[0];
|
||||||
|
for (const remote of group) {
|
||||||
|
if (remote.id !== kept.id) duplicateIds.push(remote.id);
|
||||||
|
}
|
||||||
eventMap[key] = {
|
eventMap[key] = {
|
||||||
id: remote.id,
|
id: kept.id,
|
||||||
date: remote.date || existing?.date || lessonDateFromSeqtaKey(remote.seqtaKey) || "",
|
date: kept.date || existing?.date || lessonDateFromSeqtaKey(kept.seqtaKey) || "",
|
||||||
// Prefer last-written local fingerprint so skip stays stable across API format quirks.
|
// Prefer last-written local fingerprint so skip stays stable across API format quirks.
|
||||||
fingerprint: existing?.fingerprint ?? remote.fingerprint,
|
fingerprint: existing?.fingerprint ?? kept.fingerprint,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
return duplicateIds;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -108,13 +108,28 @@ export async function markWeeklySyncPending(): Promise<void> {
|
|||||||
await writeSharedCalendarSyncSettings({ pendingWeeklySync: true });
|
await writeSharedCalendarSyncSettings({ pendingWeeklySync: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
type PendingCalendarSync = {
|
export type PendingCalendarSync = {
|
||||||
provider: "google" | "outlook";
|
provider: "google" | "outlook";
|
||||||
mode: "full" | "incremental";
|
mode: "full" | "incremental";
|
||||||
origin: string;
|
origin: string;
|
||||||
startedAt: number;
|
startedAt: number;
|
||||||
|
/** Refreshed while a sync is running; a recent value means another tab is still syncing. */
|
||||||
|
heartbeatAt?: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const CALENDAR_SYNC_HEARTBEAT_MS = 10_000;
|
||||||
|
const CALENDAR_SYNC_HEARTBEAT_STALE_MS = 45_000;
|
||||||
|
|
||||||
|
/** True when another tab's sync marker has a recent heartbeat. */
|
||||||
|
export async function isCalendarSyncRunningElsewhere(): Promise<boolean> {
|
||||||
|
const got = await browser.storage.local.get(BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY);
|
||||||
|
const raw = got[BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY];
|
||||||
|
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return false;
|
||||||
|
const pending = raw as PendingCalendarSync;
|
||||||
|
const lastBeat = pending.heartbeatAt ?? pending.startedAt;
|
||||||
|
return typeof lastBeat === "number" && Date.now() - lastBeat < CALENDAR_SYNC_HEARTBEAT_STALE_MS;
|
||||||
|
}
|
||||||
|
|
||||||
/** Returns a pending sync worth resuming, or clears and returns null. */
|
/** Returns a pending sync worth resuming, or clears and returns null. */
|
||||||
export async function readResumableCalendarSync(): Promise<PendingCalendarSync | null> {
|
export async function readResumableCalendarSync(): Promise<PendingCalendarSync | null> {
|
||||||
const got = await browser.storage.local.get(BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY);
|
const got = await browser.storage.local.get(BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY);
|
||||||
|
|||||||
@@ -65,6 +65,8 @@ type CalendarStoredState = {
|
|||||||
eventMap?: EventMapRecord;
|
eventMap?: EventMapRecord;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const DUPLICATE_EVENT_MAP_KEY_PREFIX = "__duplicate__::";
|
||||||
|
|
||||||
export type CalendarLessonSyncProvider = {
|
export type CalendarLessonSyncProvider = {
|
||||||
label: string;
|
label: string;
|
||||||
isConfigured: () => boolean;
|
isConfigured: () => boolean;
|
||||||
@@ -204,13 +206,14 @@ export async function syncLessonsToCalendar(
|
|||||||
events.map((event) => eventMapKey(request.origin, event.seqtaKey)),
|
events.map((event) => eventMapKey(request.origin, event.seqtaKey)),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
let duplicateIds: string[] = [];
|
||||||
try {
|
try {
|
||||||
const remoteEvents = await provider.listSyncedEvents(
|
const remoteEvents = await provider.listSyncedEvents(
|
||||||
accessToken,
|
accessToken,
|
||||||
reconcileRange,
|
reconcileRange,
|
||||||
refreshAccessToken,
|
refreshAccessToken,
|
||||||
);
|
);
|
||||||
mergeRemoteEventsIntoMap(eventMap, request.origin, remoteEvents, eventMapKey);
|
duplicateIds = mergeRemoteEventsIntoMap(eventMap, request.origin, remoteEvents, eventMapKey);
|
||||||
const remoteIds = new Set(remoteEvents.map((event) => event.id));
|
const remoteIds = new Set(remoteEvents.map((event) => event.id));
|
||||||
for (const key of currentMapKeys) {
|
for (const key of currentMapKeys) {
|
||||||
const entry = normalizeEventMapEntry(eventMap[key]);
|
const entry = normalizeEventMapEntry(eventMap[key]);
|
||||||
@@ -238,6 +241,10 @@ export async function syncLessonsToCalendar(
|
|||||||
if (entry) staleEntries.push([mapKey, entry.id]);
|
if (entry) staleEntries.push([mapKey, entry.id]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Untracked map key so deleting a duplicate never drops the kept event's map entry.
|
||||||
|
for (const id of duplicateIds) {
|
||||||
|
staleEntries.push([`${DUPLICATE_EVENT_MAP_KEY_PREFIX}${id}`, id]);
|
||||||
|
}
|
||||||
const totalSteps = Math.max(staleEntries.length + events.length, 1);
|
const totalSteps = Math.max(staleEntries.length + events.length, 1);
|
||||||
const lastSyncAt = Date.now();
|
const lastSyncAt = Date.now();
|
||||||
|
|
||||||
|
|||||||
@@ -19,9 +19,12 @@ import {
|
|||||||
} from "@/seqta/utils/calendarSync/providerStorage";
|
} from "@/seqta/utils/calendarSync/providerStorage";
|
||||||
import {
|
import {
|
||||||
BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY,
|
BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY,
|
||||||
|
CALENDAR_SYNC_HEARTBEAT_MS,
|
||||||
getSyncAssessmentDueDates,
|
getSyncAssessmentDueDates,
|
||||||
getSyncWeeksAhead,
|
getSyncWeeksAhead,
|
||||||
|
isCalendarSyncRunningElsewhere,
|
||||||
readResumableCalendarSync,
|
readResumableCalendarSync,
|
||||||
|
type PendingCalendarSync,
|
||||||
} from "@/seqta/utils/calendarSync/settings";
|
} from "@/seqta/utils/calendarSync/settings";
|
||||||
import type {
|
import type {
|
||||||
GoogleCalendarStatus,
|
GoogleCalendarStatus,
|
||||||
@@ -105,21 +108,49 @@ const OUTLOOK_SYNC_RUNNER: CalendarSyncRunnerConfig = {
|
|||||||
lessonSyncProvider: outlookLessonSyncProvider,
|
lessonSyncProvider: outlookLessonSyncProvider,
|
||||||
};
|
};
|
||||||
|
|
||||||
export async function runCalendarSync(
|
/** In-flight syncs for this tab; overlapping syncs each create every event, duplicating them. */
|
||||||
|
const activeSyncs = new Map<CalendarProvider, Promise<GoogleCalendarSyncResult>>();
|
||||||
|
|
||||||
|
export function runCalendarSync(
|
||||||
config: CalendarSyncRunnerConfig,
|
config: CalendarSyncRunnerConfig,
|
||||||
params: RunCalendarSyncParams = {},
|
params: RunCalendarSyncParams = {},
|
||||||
): Promise<GoogleCalendarSyncResult> {
|
): Promise<GoogleCalendarSyncResult> {
|
||||||
|
const active = activeSyncs.get(config.provider);
|
||||||
|
if (active) return active;
|
||||||
|
const run = runExclusiveCalendarSync(config, params).finally(() => {
|
||||||
|
activeSyncs.delete(config.provider);
|
||||||
|
});
|
||||||
|
activeSyncs.set(config.provider, run);
|
||||||
|
return run;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runExclusiveCalendarSync(
|
||||||
|
config: CalendarSyncRunnerConfig,
|
||||||
|
params: RunCalendarSyncParams,
|
||||||
|
): Promise<GoogleCalendarSyncResult> {
|
||||||
|
if (await isCalendarSyncRunningElsewhere()) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: "A calendar sync is already running in another SEQTA tab. Try again in a minute.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
const mode = params.mode ?? "full";
|
const mode = params.mode ?? "full";
|
||||||
const weeksAhead = await getSyncWeeksAhead();
|
const weeksAhead = await getSyncWeeksAhead();
|
||||||
|
|
||||||
await browser.storage.local.set({
|
const marker: PendingCalendarSync = {
|
||||||
[BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY]: {
|
provider: config.provider,
|
||||||
provider: config.provider,
|
mode,
|
||||||
mode,
|
origin: location.origin,
|
||||||
origin: location.origin,
|
startedAt: Date.now(),
|
||||||
startedAt: Date.now(),
|
heartbeatAt: Date.now(),
|
||||||
},
|
};
|
||||||
});
|
await browser.storage.local.set({ [BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY]: marker });
|
||||||
|
const heartbeat = setInterval(() => {
|
||||||
|
void browser.storage.local.set({
|
||||||
|
[BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY]: { ...marker, heartbeatAt: Date.now() },
|
||||||
|
});
|
||||||
|
}, CALENDAR_SYNC_HEARTBEAT_MS);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
reportSyncProgress(params.onProgress, {
|
reportSyncProgress(params.onProgress, {
|
||||||
@@ -157,6 +188,7 @@ export async function runCalendarSync(
|
|||||||
{ onProgress: params.onProgress },
|
{ onProgress: params.onProgress },
|
||||||
);
|
);
|
||||||
} finally {
|
} finally {
|
||||||
|
clearInterval(heartbeat);
|
||||||
await browser.storage.local.remove(BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY);
|
await browser.storage.local.remove(BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -166,6 +198,8 @@ export async function resumeInterruptedCalendarSync(
|
|||||||
): Promise<GoogleCalendarSyncResult | null> {
|
): Promise<GoogleCalendarSyncResult | null> {
|
||||||
const pending = await readResumableCalendarSync();
|
const pending = await readResumableCalendarSync();
|
||||||
if (!pending) return null;
|
if (!pending) return null;
|
||||||
|
// Another tab is still mid-sync — leave its marker alone; a later page load resumes if it dies.
|
||||||
|
if (await isCalendarSyncRunningElsewhere()) return null;
|
||||||
|
|
||||||
const state =
|
const state =
|
||||||
pending.provider === "google"
|
pending.provider === "google"
|
||||||
|
|||||||
Reference in new issue
Block a user