Harden calendar sync locks and cover review follow-ups for PR #502.

Per-provider in-progress keys, compare-and-set lock acquire, duplicate cleanup on full removal, tests, and manual QA checklist.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
AdenMGBandCursor committed 2026-11-04 12:50:32 +10:30
1 parent 84922f27d2
commit 4509632774
8 files changed
+380 -35

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,117 @@
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 originalSet = browser.storage.local.set.getMockImplementation();
browser.storage.local.set.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);
});
});
+122 -12
View File
@@ -10,8 +10,22 @@ import {
} from "@/seqta/utils/calendarSync/providerStorage";
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 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 WEEKLY_SYNC_INTERVAL_MS = 7 * 24 * 60 * 60 * 1000;
@@ -109,42 +123,138 @@ export async function markWeeklySyncPending(): Promise<void> {
}
export type PendingCalendarSync = {
provider: "google" | "outlook";
provider: CalendarSyncProvider;
mode: "full" | "incremental";
origin: string;
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;
};
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> {
async function migrateLegacyCalendarSyncInProgressKey(): Promise<void> {
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;
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;
}
/** Returns a pending sync worth resuming, or clears and returns null. */
export async function readResumableCalendarSync(): Promise<PendingCalendarSync | null> {
const got = await browser.storage.local.get(BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY);
const raw = got[BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY];
/** 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;
const pending = raw as PendingCalendarSync;
const validProvider = pending.provider === "google" || pending.provider === "outlook";
const validMode = pending.mode === "full" || pending.mode === "incremental";
const fresh = Date.now() - pending.startedAt < 24 * 60 * 60 * 1000;
if (!validProvider || !validMode || pending.origin !== location.origin || !fresh) {
await browser.storage.local.remove(BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY);
if (pending.provider !== provider || !validMode || pending.origin !== location.origin || !fresh) {
await browser.storage.local.remove(key);
return null;
}
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;
}
+8 -1
View File
@@ -361,6 +361,7 @@ export async function deleteSyncedEventsFromCalendar(
};
let remoteEvents: RemoteSyncedEvent[] = [];
let duplicateIds: string[] = [];
try {
remoteEvents = await provider.listSyncedEvents(
accessToken,
@@ -368,12 +369,18 @@ export async function deleteSyncedEventsFromCalendar(
refreshAccessToken,
{ includeUnkeyed: true },
);
mergeRemoteEventsIntoMap(eventMap, origin, remoteEvents, eventMapKey);
duplicateIds = mergeRemoteEventsIntoMap(eventMap, origin, remoteEvents, eventMapKey);
} catch (err) {
verboseLog(`[BetterSEQTA+] ${provider.label} cleanup list failed:`, err);
}
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) {
clearOriginEventMapEntries(eventMap, origin);
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;
});
});
+20 -17
View File
@@ -18,13 +18,16 @@ import {
readOutlookCalendarState,
} from "@/seqta/utils/calendarSync/providerStorage";
import {
BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY,
CALENDAR_SYNC_HEARTBEAT_MS,
calendarSyncInProgressStorageKey,
clearCalendarSyncInProgressMarker,
getSyncAssessmentDueDates,
getSyncWeeksAhead,
isCalendarSyncRunningElsewhere,
readResumableCalendarSync,
type PendingCalendarSync,
releaseCalendarSyncLock,
tryAcquireCalendarSyncLock,
type CalendarSyncProvider,
} from "@/seqta/utils/calendarSync/settings";
import type {
GoogleCalendarStatus,
@@ -32,7 +35,7 @@ import type {
GoogleCalendarSyncResult,
} from "@/seqta/utils/googleCalendar/types";
export type CalendarProvider = "google" | "outlook";
export type { CalendarSyncProvider as CalendarProvider };
const MSG = {
accessToken: { google: "googleCalendarGetAccessToken", outlook: "outlookCalendarGetAccessToken" },
@@ -128,27 +131,22 @@ async function runExclusiveCalendarSync(
config: CalendarSyncRunnerConfig,
params: RunCalendarSyncParams,
): Promise<GoogleCalendarSyncResult> {
if (await isCalendarSyncRunningElsewhere()) {
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 mode = params.mode ?? "full";
const { lockId, marker } = lock;
const storageKey = calendarSyncInProgressStorageKey(config.provider);
const weeksAhead = await getSyncWeeksAhead();
const marker: PendingCalendarSync = {
provider: config.provider,
mode,
origin: location.origin,
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() },
[storageKey]: { ...marker, heartbeatAt: Date.now(), lockId },
});
}, CALENDAR_SYNC_HEARTBEAT_MS);
@@ -189,7 +187,7 @@ async function runExclusiveCalendarSync(
);
} finally {
clearInterval(heartbeat);
await browser.storage.local.remove(BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY);
await releaseCalendarSyncLock(config.provider, lockId);
}
}
@@ -199,14 +197,14 @@ export async function resumeInterruptedCalendarSync(
const pending = await readResumableCalendarSync();
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;
if (await isCalendarSyncRunningElsewhere(pending.provider)) return null;
const state =
pending.provider === "google"
? await readGoogleCalendarState()
: await readOutlookCalendarState();
if (!state.refreshToken && !state.accessToken) {
await browser.storage.local.remove(BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY);
await clearCalendarSyncInProgressMarker(pending.provider);
return null;
}
@@ -219,3 +217,8 @@ export const runGoogleCalendarSync = (params?: RunCalendarSyncParams) =>
export const runOutlookCalendarSync = (params?: RunCalendarSyncParams) =>
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,
resolveThemeIdForPostSyncDownload,
} 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", () => {
it("maps animatedbk without overwriting existing plugin fields", () => {
@@ -31,7 +31,9 @@ describe("isKeyIncludedInCloudUploadPayload", () => {
it("excludes auth and device cache prefixes", () => {
expect(isKeyIncludedInCloudUploadPayload("bsplus_token")).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("bsplus.analytics.v2.school.1")).toBe(false);
});
+3 -3
View File
@@ -1,6 +1,6 @@
import browser from "@/lib/browser";
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 */
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. */
"bsplus_pending_feedback_ids",
"bsplus_remote_status",
BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY,
...BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEYS,
] as const;
/**
@@ -68,7 +68,7 @@ const CLIENT_ONLY_CLOUD_KEYS_EXACT = [
BSPLUS_CLOUD_LAST_UPLOADED_SNAPSHOT_KEY,
"bsplus_lastCloudPoll",
BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY,
BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY,
...BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEYS,
] as const;
/** After restoring from cloud, keep local session so the user stays signed in. */