Google Calendar Sync#
Google Calendar sync in MeetingBar is handled by two cooperating components: GCEventStore (GoogleCalendarEventStore.swift) manages OAuth authentication and Google API requests, while CalendarSync (CalendarSync.swift) drives the periodic refresh loop and publishes events to the UI.
The sync cycle runs every 180 seconds by default and is also triggered by manual refresh, settings changes, wake/sleep transitions, and โ as of PR #974 โ network-reachability changes .
Recurring failure pattern (v4.11.x โ v5.0.0 RC): Events stop refreshing silently overnight or after a commute. The menu shows yesterday's grayed-out events. Pressing Quick Actions โ Refresh Sources recovers the state. There is no single trigger โ four independent failure modes all share the theme that every path is unbounded: nothing times out, nothing retries with backoff, and nothing reacts to the network coming back.
Token Refresh and Authentication State#
validAccessToken is the central auth primitive. It returns a cached access token if still fresh (>5 min to expiry), otherwise calls OIDAuthState.performAction to get a new one. Refreshes are serialized through a stored pendingRefresh (a PendingRefresh holding the task, the OIDAuthState it is refreshing, and a generation counter) to avoid concurrent requests . A forced refresh never joins an in-flight one (the token that refresh will return was already rejected), and a refresh belonging to a superseded OIDAuthState is not joined either.
Root cause โ transient error destroys saved session (v4.11.x โ v5.0.0 RC): AppAuth's performAction callback on a transient (network) refresh failure passes the old, already-expired accessToken alongside the error. The prior code checked accessToken first and silently discarded the error, causing the chain: expired token โ Google 401 โ retryWithForcedTokenRefresh โ same expired token (still offline) โ 401 again โ clearAuthAndThrowAuthRequired (later renamed throwAuthRequired) โ clearAuthState() deletes the refresh token from Keychain, forcing full re-consent. A laptop waking before Wi-Fi reconnects is sufficient to trigger this.
PR #974 fix: validAccessToken now checks error before accessToken. Non-OIDOAuthTokenErrorDomain errors (transient network failures) throw a new AuthError.temporarilyUnavailable(underlying:) (offline, VPN still connecting, captive portal) instead of falling through to the 401 retry chain; it keeps the refresh token and is mapped to .failed โ not auth-required/reconnect โ in ProviderHealth/CalendarSync. OIDOAuthTokenErrorDomain errors map to AuthError.notSignedIn. The session is cleared only when the token endpoint rejects the refresh token โ which AppAuth reports via didEncounterAuthorizationError โ not for 401 API responses. Both that delegate and didChange ignore callbacks from an OIDAuthState that is no longer the installed authState. persistAuthState no longer deletes the Keychain entry when authState is nil; only an explicit clearAuthState() does.
GoogleHTTPStatusPolicy.classify maps HTTP status codes to one of four decisions: .proceed, .retryWithForcedTokenRefresh, .throwAuthRequired, or .throwError. .throwAuthRequired (formerly .clearAuthAndThrowAuthRequired) is reached only on a 401 after a forced token refresh retry (retrying == true). It throws AuthError.notSignedIn ("reconnect required") without clearing the stored session or Keychain entry, since a 401 only proves the access token was refused.
Hung Requests and Timeout Bounds#
waitsForConnectivity = true (v4.11.x โ v5.0.0): The shared URLSession was configured with waitsForConnectivity = true and no explicit timeoutIntervalForResource. With this combination, timeoutIntervalForRequest does not apply while waiting for connectivity; timeoutIntervalForResource controls the total wait instead, defaulting to 604,800 s (7 days). An offline fetch would park indefinitely rather than fail fast.
PR #974 fix: Sets waitsForConnectivity = false and adds explicit timeoutIntervalForRequest = 30 s and timeoutIntervalForResource = 90 s on the shared session, bounding fetch failures so the next periodic cycle self-heals.
OIDAuthState.performAction hang (PR #950): The AppAuth callback can be "parked" across a sleep/wake cycle and never invoke its completion handler. The old code wrapped it in a checked continuation with no timeout; defer { refreshTask = nil } never ran, leaving every subsequent fetch awaiting a dead task forever. PR #950 introduced TimeoutGuardedCompletion to race the callback against a hard timeout.
PR #974 bounds the token refresh with its own deadline, tokenRefreshTimeout = 90 s. AppAuth issues token requests on URLSession.shared, not the hardened session above, so the session timeouts do not apply to it. A SingleResumeGuard arbitrates the AppAuth callback against the deadline so the continuation resumes exactly once. On timeout the refresh throws AuthError.temporarilyUnavailable and discardStuckAuthState() rebuilds the in-memory auth state from the Keychain โ AppAuth serializes pending actions, so a stuck request would otherwise block every later one โ without deleting the persisted session.
flatMap(maxPublishers: .max(1)) deadlock (v5.0.0): CalendarSync serializes refresh cycles through a flatMap(.max(1)) over a Combine Future. If the inner Future never completes (due to a hung fetch), no further triggers โ including the timer, settings changes, and the manual Refresh button โ are delivered for the lifetime of the process. The only escape was switching providers, which is why "switch to Apple Calendar and back" became the community workaround. PR #974 runs each refresh cycle step (fetchAllCalendars and fetchEvents) under withRefreshTimeout (refreshTimeout = 120 s). On expiry it throws CalendarSyncError.refreshTimedOut(seconds) and the cycle is reported as failed/stale, so the Future always resolves โ its promise is fulfilled even if self has been deallocated.
Interactive Sign-In in Background Fetches#
Before PR #974, ensureSignedIn was called before every fetchAllCalendars and fetchEventsForDateRange. It checked hasReusableSession (authorized + non-nil refresh token) and, if missing, fell through to signIn, which opened an OAuth browser tab via NSWorkspace.open and awaited a user callback.
Known bug (v5.0.0): If the user is asleep, the browser tab opens unnoticed and the continuation awaits indefinitely. The stored signInTask was never cleared (the defer lived in the suspended ensureSignedIn scope), so every subsequent background refresh would try await signInTask.value on a dead task โ permanently blocking sync without any visible error.
PR #974 fix: fetchAllCalendars and fetchEventsForDateRange now call requireReusableSession() (replacing ensureSignedIn), which throws AuthError.notSignedIn when no reusable session exists instead of launching an interactive browser sign-in from a background refresh. Interactive auth happens only via an explicit signIn(forcePrompt:) (provider selection or the Reconnect button). If authorization completes without a refresh token (a silent grant from a previous install), signIn automatically retries once with forced consent.
Network-Recovery Trigger#
The periodic 180 s timer fires regardless of network state; before PR #974 there was no NWPathMonitor integration (grep NWPathMonitor returned nothing in the main target). Wake triggers were added in v5.0 but fire before Wi-Fi reassociates or a VPN connects โ the worst possible moment given the waitsForConnectivity and token-refresh bugs.
PR #974 adds an NWPathMonitor-based monitor in LifecycleObserver.swift that fires onNetworkBecameReachable on unusable โ usable path transitions (not on the first path update at launch). Flap protection is applied: calls are throttled to at most one per 60 s, with a trailing deferred call, so a reconnecting VPN triggers at most one fetch per minute rather than a fetch per reconnect event. The hook is wired through AppDelegate โ AppModel.handleNetworkBecameReachable() โ AppAction.networkBecameReachable, which, like didWake and dayChanged, calls scheduleRefresh() (and so CalendarSync.refreshSubject).
Scope Limits and Genuine Revocations#
The fixes above address transient failures. They cannot recover from a genuine Google-side revocation:
- User revokes access in their Google account security settings.
- OAuth client in "Testing" publishing status: Google expires refresh tokens after 7 days for unverified OAuth apps.
In both cases re-consent is required. The correct behavior post-fix is a visible Reconnect prompt rather than silent stale data. If re-authentication is triggered too frequently (more than once per week without user action), the most likely cause is the "Testing" publishing status or a calendar/account configured to time-limit third-party access.
Workaround (pre-fix builds): Use macOS Calendar as the sync source (System Settings โ Calendar โ Accounts) and set MeetingBar to use macOS Calendar. macOS Calendar handles its own OAuth refresh and does not suffer from the same issues.
Key Files and References#
| File | Role |
|---|---|
GoogleCalendarEventStore.swift | OAuth sign-in, token refresh, API requests |
GoogleCalendarPolicy.swift | AuthError, GoogleHTTPStatusPolicy, SingleResumeGuard |
CalendarSync.swift | Refresh loop, Combine pipeline, refreshCycleTask |
LifecycleObserver.swift | Wake/sleep/network triggers |
AppModel.swift | Routes lifecycle actions to CalendarSync |
Related issues and PRs:
- Issue #869 โ Primary bug report with root-cause analysis
- PR #974 โ Comprehensive fix: error-before-token ordering, bounded timeouts,
NWPathMonitor, session-clearing policy - PR #950 โ
TimeoutGuardedCompletionfor hung AppAuth callbacks - PR #904 โ Earlier OAuth retry/backoff and wake-refresh attempt
- PR #912 โ Refresh-token presence check to prevent false signed-out detection