Merge pull request #502 from maxwakelin8-a11y/fix/calendar-sync-duplicates-upstream

fix: stop overlapping calendar syncs from duplicating lesson events
This commit is contained in:
Aden Lindsay authored and GitHub committed 2026-11-04 12:55:35 +10:30
commit 5a72be2117
10 files changed
+487 -32

No files matched your search

+33
View File
@@ -0,0 +1,33 @@
# Calendar sync manual QA
Run these checks before merging calendar sync changes. Use a school SEQTA account with Google Calendar and/or Outlook connected in BetterSEQTA+ settings.
## Dual-tab overlap (duplicate prevention)
1. Open SEQTA in **Tab A** and wait for an automatic calendar sync to start (or trigger **Sync now** from settings).
2. Open the **same school** SEQTA origin in **Tab B** while Tab A is still syncing.
3. In Tab B, click **Sync now** for the same provider.
4. **Expected:** Tab B shows an error that sync is already running in another tab (no new duplicate events).
5. After Tab A finishes, sync from Tab B should succeed.
## Same-tab overlap
1. With one tab open, click **Sync now** twice quickly (or trigger sync while page-load sync is still running).
2. **Expected:** Only one sync runs; no duplicate calendar events for the same lessons.
## Google and Outlook together
1. Connect **both** Google and Outlook if available.
2. Start sync for Google, then immediately start sync for Outlook (same or different tabs).
3. **Expected:** Both providers can sync concurrently; neither blocks the other.
## Resume after interrupted sync
1. Start a full sync, then close the tab mid-sync (or kill the tab process).
2. Wait longer than the heartbeat stale window (~45s) without another tab syncing.
3. Reload SEQTA.
4. **Expected:** Sync resumes or can be started cleanly without duplicate events piling up.
## Duplicate cleanup (optional)
If duplicates already exist from an older build, run a full sync once and confirm extra remote events for the same lesson are removed from the calendar.
@@ -0,0 +1,118 @@
import { beforeEach, describe, expect, it, jest } from "@jest/globals";
import browser from "@/lib/browser";
import {
BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY,
CALENDAR_SYNC_HEARTBEAT_MS,
calendarSyncInProgressStorageKey,
isCalendarSyncRunningElsewhere,
readResumableCalendarSync,
tryAcquireCalendarSyncLock,
} from "./settings";
const origin = "https://school.seqta.com.au";
describe("calendar sync cross-tab lock", () => {
beforeEach(() => {
Object.defineProperty(globalThis, "location", {
value: { origin },
configurable: true,
});
});
it("reports no sync elsewhere when marker is missing", async () => {
expect(await isCalendarSyncRunningElsewhere("google")).toBe(false);
expect(await isCalendarSyncRunningElsewhere("outlook")).toBe(false);
});
it("uses separate in-progress keys per provider", async () => {
const now = Date.now();
await browser.storage.local.set({
[calendarSyncInProgressStorageKey("google")]: {
provider: "google",
mode: "full",
origin,
startedAt: now,
heartbeatAt: now,
lockId: "google-lock",
},
[calendarSyncInProgressStorageKey("outlook")]: {
provider: "outlook",
mode: "full",
origin,
startedAt: now,
heartbeatAt: now,
lockId: "outlook-lock",
},
});
expect(await isCalendarSyncRunningElsewhere("google")).toBe(true);
expect(await isCalendarSyncRunningElsewhere("outlook")).toBe(true);
});
it("treats stale heartbeats as not running elsewhere", async () => {
const stale = Date.now() - 60_000;
await browser.storage.local.set({
[calendarSyncInProgressStorageKey("google")]: {
provider: "google",
mode: "full",
origin,
startedAt: stale,
heartbeatAt: stale,
},
});
expect(await isCalendarSyncRunningElsewhere("google")).toBe(false);
expect(await readResumableCalendarSync()).toMatchObject({ provider: "google" });
});
it("acquires lock and rejects when another tab holds a live marker", async () => {
const first = await tryAcquireCalendarSyncLock("google", "full");
expect(first.acquired).toBe(true);
const second = await tryAcquireCalendarSyncLock("google", "full");
expect(second.acquired).toBe(false);
});
it("loses acquire when storage contains another tab's lockId after write", async () => {
const key = calendarSyncInProgressStorageKey("google");
const setMock = jest.mocked(browser.storage.local.set);
const originalSet = setMock.getMockImplementation();
setMock.mockImplementation(async (items: Record<string, unknown>) => {
if (key in items) {
await originalSet?.({
[key]: {
...(items[key] as object),
lockId: "other-tab",
},
});
return;
}
await originalSet?.(items);
});
const result = await tryAcquireCalendarSyncLock("google", "incremental");
expect(result.acquired).toBe(false);
});
it("migrates legacy in-progress key to per-provider storage", async () => {
const now = Date.now();
await browser.storage.local.set({
[BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY]: {
provider: "outlook",
mode: "incremental",
origin,
startedAt: now,
heartbeatAt: now,
},
});
expect(await isCalendarSyncRunningElsewhere("outlook")).toBe(true);
expect(await browser.storage.local.get(BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY)).toEqual({});
});
});
describe("calendar sync heartbeat constant", () => {
it("refreshes at most every ten seconds", () => {
expect(CALENDAR_SYNC_HEARTBEAT_MS).toBe(10_000);
});
});
@@ -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;
} }
/** /**
+133 -8
View File
@@ -10,8 +10,22 @@ import {
} from "@/seqta/utils/calendarSync/providerStorage"; } from "@/seqta/utils/calendarSync/providerStorage";
export const BSPLUS_CALENDAR_SYNC_SETTINGS_KEY = "bsplus_calendar_sync_settings"; export const BSPLUS_CALENDAR_SYNC_SETTINGS_KEY = "bsplus_calendar_sync_settings";
/** Device-local interrupted sync marker — never cloud-synced. */ /** @deprecated Legacy single marker; migrated to per-provider keys on read. */
export const BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY = "bsplus_calendar_sync_in_progress"; export const BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY = "bsplus_calendar_sync_in_progress";
export type CalendarSyncProvider = "google" | "outlook";
export const CALENDAR_SYNC_PROVIDERS: readonly CalendarSyncProvider[] = ["google", "outlook"];
/** Device-local interrupted sync marker per provider — never cloud-synced. */
export function calendarSyncInProgressStorageKey(provider: CalendarSyncProvider): string {
return `bsplus_calendar_sync_in_progress_${provider}`;
}
export const BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEYS = [
BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY,
...CALENDAR_SYNC_PROVIDERS.map(calendarSyncInProgressStorageKey),
] as const;
export const CALENDAR_WEEKLY_ALARM = "bsplus_calendar_weekly"; export const CALENDAR_WEEKLY_ALARM = "bsplus_calendar_weekly";
export const WEEKLY_SYNC_INTERVAL_MS = 7 * 24 * 60 * 60 * 1000; export const WEEKLY_SYNC_INTERVAL_MS = 7 * 24 * 60 * 60 * 1000;
@@ -108,28 +122,139 @@ export async function markWeeklySyncPending(): Promise<void> {
await writeSharedCalendarSyncSettings({ pendingWeeklySync: true }); await writeSharedCalendarSyncSettings({ pendingWeeklySync: true });
} }
type PendingCalendarSync = { export type PendingCalendarSync = {
provider: "google" | "outlook"; provider: CalendarSyncProvider;
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;
/** Set when this tab owns the in-progress marker; used to detect cross-tab lock races. */
lockId?: string;
}; };
/** Returns a pending sync worth resuming, or clears and returns null. */ export const CALENDAR_SYNC_HEARTBEAT_MS = 10_000;
export async function readResumableCalendarSync(): Promise<PendingCalendarSync | null> { const CALENDAR_SYNC_HEARTBEAT_STALE_MS = 45_000;
async function migrateLegacyCalendarSyncInProgressKey(): Promise<void> {
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);
const raw = got[BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY]; const raw = got[BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY];
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return;
const pending = raw as PendingCalendarSync;
if (pending.provider !== "google" && pending.provider !== "outlook") {
await browser.storage.local.remove(BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY);
return;
}
const key = calendarSyncInProgressStorageKey(pending.provider);
const existing = await browser.storage.local.get(key);
if (!existing[key]) {
await browser.storage.local.set({ [key]: pending });
}
await browser.storage.local.remove(BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY);
}
function isPendingHeartbeatLive(pending: PendingCalendarSync): boolean {
const lastBeat = pending.heartbeatAt ?? pending.startedAt;
return typeof lastBeat === "number" && Date.now() - lastBeat < CALENDAR_SYNC_HEARTBEAT_STALE_MS;
}
/** True when another tab holds a live in-progress marker for this provider. */
export async function isCalendarSyncRunningElsewhere(
provider: CalendarSyncProvider,
): Promise<boolean> {
await migrateLegacyCalendarSyncInProgressKey();
const key = calendarSyncInProgressStorageKey(provider);
const got = await browser.storage.local.get(key);
const raw = got[key];
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return false;
return isPendingHeartbeatLive(raw as PendingCalendarSync);
}
export async function clearCalendarSyncInProgressMarker(
provider: CalendarSyncProvider,
): Promise<void> {
await browser.storage.local.remove(calendarSyncInProgressStorageKey(provider));
}
/**
* Claim the cross-tab sync lock for a provider. Re-reads storage after write so only one tab wins
* a simultaneous acquire (avoids check-then-set races).
*/
export async function tryAcquireCalendarSyncLock(
provider: CalendarSyncProvider,
mode: "full" | "incremental",
): Promise<{ acquired: true; lockId: string; marker: PendingCalendarSync } | { acquired: false }> {
await migrateLegacyCalendarSyncInProgressKey();
if (await isCalendarSyncRunningElsewhere(provider)) {
return { acquired: false };
}
const lockId = crypto.randomUUID();
const marker: PendingCalendarSync = {
provider,
mode,
origin: location.origin,
startedAt: Date.now(),
heartbeatAt: Date.now(),
lockId,
};
const key = calendarSyncInProgressStorageKey(provider);
await browser.storage.local.set({ [key]: marker });
const got = await browser.storage.local.get(key);
const raw = got[key];
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
return { acquired: false };
}
const stored = raw as PendingCalendarSync;
if (stored.lockId !== lockId) {
return { acquired: false };
}
return { acquired: true, lockId, marker };
}
/** Release the in-progress marker only when this tab still owns it. */
export async function releaseCalendarSyncLock(
provider: CalendarSyncProvider,
lockId: string,
): Promise<void> {
const key = calendarSyncInProgressStorageKey(provider);
const got = await browser.storage.local.get(key);
const raw = got[key];
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return;
const stored = raw as PendingCalendarSync;
if (stored.lockId === lockId) {
await browser.storage.local.remove(key);
}
}
async function readResumableCalendarSyncForProvider(
provider: CalendarSyncProvider,
): Promise<PendingCalendarSync | null> {
const key = calendarSyncInProgressStorageKey(provider);
const got = await browser.storage.local.get(key);
const raw = got[key];
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
const pending = raw as PendingCalendarSync; const pending = raw as PendingCalendarSync;
const validProvider = pending.provider === "google" || pending.provider === "outlook";
const validMode = pending.mode === "full" || pending.mode === "incremental"; const validMode = pending.mode === "full" || pending.mode === "incremental";
const fresh = Date.now() - pending.startedAt < 24 * 60 * 60 * 1000; const fresh = Date.now() - pending.startedAt < 24 * 60 * 60 * 1000;
if (!validProvider || !validMode || pending.origin !== location.origin || !fresh) { if (pending.provider !== provider || !validMode || pending.origin !== location.origin || !fresh) {
await browser.storage.local.remove(BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY); await browser.storage.local.remove(key);
return null; return null;
} }
return pending; return pending;
} }
/** Returns a pending sync worth resuming, or clears stale markers and returns null. */
export async function readResumableCalendarSync(): Promise<PendingCalendarSync | null> {
await migrateLegacyCalendarSyncInProgressKey();
for (const provider of CALENDAR_SYNC_PROVIDERS) {
const pending = await readResumableCalendarSyncForProvider(provider);
if (pending) return pending;
}
return null;
}
+16 -2
View File
@@ -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();
@@ -354,6 +361,7 @@ export async function deleteSyncedEventsFromCalendar(
}; };
let remoteEvents: RemoteSyncedEvent[] = []; let remoteEvents: RemoteSyncedEvent[] = [];
let duplicateIds: string[] = [];
try { try {
remoteEvents = await provider.listSyncedEvents( remoteEvents = await provider.listSyncedEvents(
accessToken, accessToken,
@@ -361,12 +369,18 @@ export async function deleteSyncedEventsFromCalendar(
refreshAccessToken, refreshAccessToken,
{ includeUnkeyed: true }, { includeUnkeyed: true },
); );
mergeRemoteEventsIntoMap(eventMap, origin, remoteEvents, eventMapKey); duplicateIds = mergeRemoteEventsIntoMap(eventMap, origin, remoteEvents, eventMapKey);
} catch (err) { } catch (err) {
verboseLog(`[BetterSEQTA+] ${provider.label} cleanup list failed:`, err); verboseLog(`[BetterSEQTA+] ${provider.label} cleanup list failed:`, err);
} }
const entries = collectOriginDeleteEntries(eventMap, origin, remoteEvents, eventMapKey); const entries = collectOriginDeleteEntries(eventMap, origin, remoteEvents, eventMapKey);
const deleteIds = new Set(entries.map(([, id]) => id));
for (const id of duplicateIds) {
if (deleteIds.has(id)) continue;
entries.push([`${DUPLICATE_EVENT_MAP_KEY_PREFIX}${id}`, id]);
deleteIds.add(id);
}
if (entries.length === 0) { if (entries.length === 0) {
clearOriginEventMapEntries(eventMap, origin); clearOriginEventMapEntries(eventMap, origin);
await provider.writeState({ eventMap }); await provider.writeState({ eventMap });
@@ -0,0 +1,73 @@
import { beforeEach, describe, expect, it, jest } from "@jest/globals";
jest.mock("@/seqta/utils/googleCalendar/fetchTimetable", () => ({
fetchAssessmentsForCalendarSync: jest.fn(async () => []),
fetchTimetableForSync: jest.fn(async () => []),
fetchTimetableLessons: jest.fn(async () => []),
}));
jest.mock("@/seqta/utils/calendarSync/syncEngine", () => ({
googleLessonSyncProvider: {},
outlookLessonSyncProvider: {},
syncLessonsToCalendar: jest.fn(),
}));
jest.mock("@/seqta/utils/calendarSync/settings", () => ({
CALENDAR_SYNC_HEARTBEAT_MS: 10_000,
calendarSyncInProgressStorageKey: (provider: string) =>
`bsplus_calendar_sync_in_progress_${provider}`,
clearCalendarSyncInProgressMarker: jest.fn(async () => undefined),
getSyncAssessmentDueDates: jest.fn(async () => false),
getSyncWeeksAhead: jest.fn(async () => 12),
isCalendarSyncRunningElsewhere: jest.fn(async () => false),
readResumableCalendarSync: jest.fn(async () => null),
releaseCalendarSyncLock: jest.fn(async () => undefined),
tryAcquireCalendarSyncLock: jest.fn(async () => ({
acquired: true as const,
lockId: "test-lock",
marker: {
provider: "google" as const,
mode: "full" as const,
origin: "https://school.seqta.com.au",
startedAt: Date.now(),
heartbeatAt: Date.now(),
lockId: "test-lock",
},
})),
}));
import { syncLessonsToCalendar } from "@/seqta/utils/calendarSync/syncEngine";
import {
__resetActiveCalendarSyncsForTests,
runGoogleCalendarSync,
} from "@/seqta/utils/calendarSync/syncRunner";
describe("runCalendarSync coalescing", () => {
beforeEach(() => {
Object.defineProperty(globalThis, "location", {
value: { origin: "https://school.seqta.com.au" },
configurable: true,
});
__resetActiveCalendarSyncsForTests();
jest.mocked(syncLessonsToCalendar).mockReset();
});
it("returns the same in-flight promise for overlapping syncs in one tab", async () => {
let resolveSync!: (value: { success: true }) => void;
const syncPromise = new Promise<{ success: true }>((resolve) => {
resolveSync = resolve;
});
jest.mocked(syncLessonsToCalendar).mockReturnValue(syncPromise);
const first = runGoogleCalendarSync();
const second = runGoogleCalendarSync();
expect(second).toBe(first);
await new Promise<void>((resolve) => setImmediate(resolve));
expect(syncLessonsToCalendar).toHaveBeenCalledTimes(1);
resolveSync({ success: true });
await first;
});
});
+50 -13
View File
@@ -18,10 +18,16 @@ import {
readOutlookCalendarState, readOutlookCalendarState,
} from "@/seqta/utils/calendarSync/providerStorage"; } from "@/seqta/utils/calendarSync/providerStorage";
import { import {
BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY, CALENDAR_SYNC_HEARTBEAT_MS,
calendarSyncInProgressStorageKey,
clearCalendarSyncInProgressMarker,
getSyncAssessmentDueDates, getSyncAssessmentDueDates,
getSyncWeeksAhead, getSyncWeeksAhead,
isCalendarSyncRunningElsewhere,
readResumableCalendarSync, readResumableCalendarSync,
releaseCalendarSyncLock,
tryAcquireCalendarSyncLock,
type CalendarSyncProvider,
} from "@/seqta/utils/calendarSync/settings"; } from "@/seqta/utils/calendarSync/settings";
import type { import type {
GoogleCalendarStatus, GoogleCalendarStatus,
@@ -29,7 +35,7 @@ import type {
GoogleCalendarSyncResult, GoogleCalendarSyncResult,
} from "@/seqta/utils/googleCalendar/types"; } from "@/seqta/utils/googleCalendar/types";
export type CalendarProvider = "google" | "outlook"; export type CalendarProvider = CalendarSyncProvider;
const MSG = { const MSG = {
accessToken: { google: "googleCalendarGetAccessToken", outlook: "outlookCalendarGetAccessToken" }, accessToken: { google: "googleCalendarGetAccessToken", outlook: "outlookCalendarGetAccessToken" },
@@ -105,21 +111,44 @@ 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> {
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> { ): Promise<GoogleCalendarSyncResult> {
const mode = params.mode ?? "full"; const mode = params.mode ?? "full";
const lock = await tryAcquireCalendarSyncLock(config.provider, mode);
if (!lock.acquired) {
return {
success: false,
error: "A calendar sync is already running in another SEQTA tab. Try again in a minute.",
};
}
const { lockId, marker } = lock;
const storageKey = calendarSyncInProgressStorageKey(config.provider);
const weeksAhead = await getSyncWeeksAhead(); const weeksAhead = await getSyncWeeksAhead();
await browser.storage.local.set({ const heartbeat = setInterval(() => {
[BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY]: { void browser.storage.local.set({
provider: config.provider, [storageKey]: { ...marker, heartbeatAt: Date.now(), lockId },
mode, });
origin: location.origin, }, CALENDAR_SYNC_HEARTBEAT_MS);
startedAt: Date.now(),
},
});
try { try {
reportSyncProgress(params.onProgress, { reportSyncProgress(params.onProgress, {
@@ -157,7 +186,8 @@ export async function runCalendarSync(
{ onProgress: params.onProgress }, { onProgress: params.onProgress },
); );
} finally { } finally {
await browser.storage.local.remove(BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY); clearInterval(heartbeat);
await releaseCalendarSyncLock(config.provider, lockId);
} }
} }
@@ -166,13 +196,15 @@ 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(pending.provider)) return null;
const state = const state =
pending.provider === "google" pending.provider === "google"
? await readGoogleCalendarState() ? await readGoogleCalendarState()
: await readOutlookCalendarState(); : await readOutlookCalendarState();
if (!state.refreshToken && !state.accessToken) { if (!state.refreshToken && !state.accessToken) {
await browser.storage.local.remove(BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY); await clearCalendarSyncInProgressMarker(pending.provider);
return null; return null;
} }
@@ -185,3 +217,8 @@ export const runGoogleCalendarSync = (params?: RunCalendarSyncParams) =>
export const runOutlookCalendarSync = (params?: RunCalendarSyncParams) => export const runOutlookCalendarSync = (params?: RunCalendarSyncParams) =>
runCalendarSync(OUTLOOK_SYNC_RUNNER, params); runCalendarSync(OUTLOOK_SYNC_RUNNER, params);
/** @internal Test hook for in-tab sync coalescing. */
export function __resetActiveCalendarSyncsForTests(): void {
activeSyncs.clear();
}
@@ -4,7 +4,7 @@ import {
normalizeThemeIdForSync, normalizeThemeIdForSync,
resolveThemeIdForPostSyncDownload, resolveThemeIdForPostSyncDownload,
} from "./cloudSettingsSync"; } from "./cloudSettingsSync";
import { BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY } from "@/seqta/utils/calendarSync/settings"; import { BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEYS } from "@/seqta/utils/calendarSync/settings";
describe("migrateLegacyToPluginSettings", () => { describe("migrateLegacyToPluginSettings", () => {
it("maps animatedbk without overwriting existing plugin fields", () => { it("maps animatedbk without overwriting existing plugin fields", () => {
@@ -31,7 +31,9 @@ describe("isKeyIncludedInCloudUploadPayload", () => {
it("excludes auth and device cache prefixes", () => { it("excludes auth and device cache prefixes", () => {
expect(isKeyIncludedInCloudUploadPayload("bsplus_token")).toBe(false); expect(isKeyIncludedInCloudUploadPayload("bsplus_token")).toBe(false);
expect(isKeyIncludedInCloudUploadPayload("bsplus_install_id")).toBe(false); expect(isKeyIncludedInCloudUploadPayload("bsplus_install_id")).toBe(false);
expect(isKeyIncludedInCloudUploadPayload(BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY)).toBe(false); for (const key of BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEYS) {
expect(isKeyIncludedInCloudUploadPayload(key)).toBe(false);
}
expect(isKeyIncludedInCloudUploadPayload("plugin.global-search.storage.index")).toBe(false); expect(isKeyIncludedInCloudUploadPayload("plugin.global-search.storage.index")).toBe(false);
expect(isKeyIncludedInCloudUploadPayload("bsplus.analytics.v2.school.1")).toBe(false); expect(isKeyIncludedInCloudUploadPayload("bsplus.analytics.v2.school.1")).toBe(false);
}); });
+3 -3
View File
@@ -1,6 +1,6 @@
import browser from "@/lib/browser"; import browser from "@/lib/browser";
import isEqual from "@/seqta/utils/isEqual"; import isEqual from "@/seqta/utils/isEqual";
import { BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY } from "@/seqta/utils/calendarSync/settings"; import { BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEYS } from "@/seqta/utils/calendarSync/settings";
/** Matches the contract in docs/CLOUD_SETTINGS_SYNC_SERVER.md */ /** Matches the contract in docs/CLOUD_SETTINGS_SYNC_SERVER.md */
export const CLOUD_SETTINGS_SYNC_SCHEMA_VERSION = 1; export const CLOUD_SETTINGS_SYNC_SCHEMA_VERSION = 1;
@@ -45,7 +45,7 @@ export const KEYS_OMITTED_FROM_CLOUD_UPLOAD = [
/** Pending feedback ids awaiting a reply notification — device-local. */ /** Pending feedback ids awaiting a reply notification — device-local. */
"bsplus_pending_feedback_ids", "bsplus_pending_feedback_ids",
"bsplus_remote_status", "bsplus_remote_status",
BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY, ...BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEYS,
] as const; ] as const;
/** /**
@@ -68,7 +68,7 @@ const CLIENT_ONLY_CLOUD_KEYS_EXACT = [
BSPLUS_CLOUD_LAST_UPLOADED_SNAPSHOT_KEY, BSPLUS_CLOUD_LAST_UPLOADED_SNAPSHOT_KEY,
"bsplus_lastCloudPoll", "bsplus_lastCloudPoll",
BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY, BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY,
BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY, ...BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEYS,
] as const; ] as const;
/** After restoring from cloud, keep local session so the user stays signed in. */ /** After restoring from cloud, keep local session so the user stays signed in. */