Skip to content

refactor(logging): use structured error logs in auth and live-query paths (#294) - #438

Open
ankit-0903 wants to merge 6 commits into
modelence:mainfrom
ankit-0903:refactor/auth-livequery-logging
Open

ankit-0903 wants to merge 6 commits into
modelence:mainfrom
ankit-0903:refactor/auth-livequery-logging

Conversation

@ankit-0903

@ankit-0903 ankit-0903 commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Resolves #294

Summary

Replaces raw console.error calls across production authentication and realtime live-query paths with structured logError(message, { ...context, error }) from the telemetry module.

This complements #422 (which migrated server paths) by completing the remaining unmigrated production call sites:

  • Live Query: packages/modelence/src/live-query/handlers.ts (subscription initializers, data fetch errors, cleanup errors on unsubscribe, and disconnect handlers)
  • Authentication:
    • packages/modelence/src/auth/magicLink.ts
    • packages/modelence/src/auth/providers/oauthCommon.ts
  • Tests: Comprehensive unit tests added in packages/modelence/src/live-query/handlers.test.ts covering error logging on fetch failure, method rejection, cleanup errors, disconnect during setup, and session preservation.

(Note: verification.ts, resetPassword.ts, github.ts, and google.ts were already migrated on main and are omitted from this diff).

Logging Configuration

Structured logging respects the MODELENCE_LOG_LEVEL environment variable (e.g., MODELENCE_LOG_LEVEL=debug or MODELENCE_LOG_LEVEL=error). When set to a level above the emitted event, structured logs are suppressed accordingly.

Verification

  • npm --prefix packages/modelence run test -- src/live-query/ src/telemetry/ src/auth/ (36 files / 653 tests passed)
  • npm --prefix packages/modelence run lint:check (0 errors, 0 warnings)

Note

Low Risk
Observability-only refactor in error paths; behavior and client responses are unchanged aside from richer server logs.

Overview
Replaces remaining console.error calls in live-query subscription handlers and OAuth common with logError from @/telemetry, attaching structured fields (method, subscriptionId, socketId, redirectUri, siteUrl, etc.) alongside the error object.

Live-query paths now log consistently for fetch failures, method setup failures, and cleanup errors on unsubscribe, disconnect, duplicate subscription IDs, and disconnect-during-setup. OAuth rejection of non-allowlisted mobile redirectUri and failure to build the web OAuth error redirect use the same pattern instead of string-concatenated console output.

Tests were extended or tightened: live-query handler coverage for each error log shape; OAuth/mobile tests assert mockLogError payloads; magic-link tests drop redundant console.error spies where telemetry mocks already assert behavior.

Reviewed by Cursor Bugbot for commit 655c7f4. Bugbot is set up for automated code reviews on this repo. Configure here.

@omegascorp omegascorp left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for picking this up! This merges cleanly onto current main, and the auth, live-query and telemetry suites all pass. A few things before it goes in:

Should fix

1. Two server-side console.error calls remain in oauthCommon.ts. #294 lists this file, and they're the last server-side ones in auth:

  • ~L210: fallback when the OAuth error redirect can't be built
  • ~L877: rejected mobile OAuth redirectUri

Both put their context into the message string, so they're good candidates for structured fields, e.g.:

logError('[modelence] Rejected mobile OAuth redirectUri', {
  redirectUri,
  allowed: getAllowedMobileRedirectUrls(),
});

(The ones in auth/client/index.ts run in the browser, so leaving them is correct.)

2. Keep the message constant and put the variable in context. A few messages still interpolate a value that's already passed as a field:

  • `[LiveQuery] Error fetching data for ${method}` / `[LiveQuery] Error in ${method}` (already pass method)
  • `Error in ${name} hook` (already passes hook)

With the variable in the message, these can't be grouped by message in log tooling. Suggest '[LiveQuery] Error fetching data' + { method }, and so on.

Worth noting

3. These errors can now be silenced. logError only prints when MODELENCE_LOG_LEVEL is debug/info/error. Any other value (e.g. warn, or a typo) now hides OAuth callback failures and email-verification and magic-link errors, which used to print unconditionally. That matches #422, so it's fine, but please mention it in the description.

Nits

4. Only the magic-link hook path has assertions, and it spies on console.error with the exact (message, args) shape, so it depends on how logError prints internally. Mocking @/telemetry's logError (as #422 did with mockLogError) would be more robust and would make it easy to cover the live-query and OAuth sites too.

5. In handleLiveQueryDisconnect, iterating subs.entries() would let the cleanup log include subscriptionId (not just socketId), like the other live-query messages.

6. handlers.ts imports from '../telemetry', while the rest of this PR uses '@/telemetry'.

@ankit-0903

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review and actionable guidance, @omegascorp!

I have updated the PR to address all feedback and merged latest main:

How Review Feedback Was Addressed

  1. Migrated remaining server-side logs in oauthCommon.ts:
    • Converted the fallback in buildOAuthErrorRedirect from console.error to logError('[modelence] Could not build the OAuth error redirect', { oauthErrorRedirectUrl, siteUrl, error }).
    • Converted the rejected mobile OAuth deep link check in resolveMobileRedirectRequest to logError('[modelence] Rejected mobile OAuth redirectUri', { redirectUri, allowed: getAllowedMobileRedirectUrls() }).
  2. Normalized log messages to constant strings:
    • In src/live-query/handlers.ts: changed dynamic messages to constant strings '[LiveQuery] Error fetching data' and '[LiveQuery] Error in method', keeping method inside the structured context object so log tooling can aggregate them properly.
    • In src/auth/magicLink.ts: changed Error in ${name} hook to constant 'Error in auth hook', preserving { hook: name } in the structured context.
  3. Structured logs on disconnect:
    • Updated handleLiveQueryDisconnect in src/live-query/handlers.ts to iterate subs.entries() instead of subs.values(), including subscriptionId alongside socketId in cleanup logs.
  4. Import path consistency:
    • Updated src/live-query/handlers.ts to import logError directly from '@/telemetry'.
  5. Robust Mocking & Test Coverage:
    • Replaced fragile console.error spies in src/auth/magicLink.test.ts, oauthCommon.mobile.test.ts, and oauthCommon.test.ts with direct mocks of @/telemetry's logError (following the pattern in refactor(logging): use structured error logs in server paths #422).
    • Added a dedicated test suite in src/live-query/handlers.test.ts covering live-query data fetch errors, method errors, and disconnect cleanup logging.
  6. Log Level Visibility Note:

Merge Conflict Resolution

  • Merged the latest changes from upstream/main (including commit f4e04ab4 / PR fix: print and capture auth handler errors #454).
  • Resolved all conflicts cleanly across the authentication files by harmonizing our constant structured messages and mocks with the newly added captureError calls.

Verification:

  • npx vitest run src/auth/ src/live-query/ (35/35 test files passed, 601/601 tests passed)
  • npx prettier --check (all matched files use Prettier code style)
  • npm run lint:check (0 errors)
  • npm run build (ESM & DTS built cleanly with 0 errors)

@omegascorp omegascorp left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the thorough follow-up, all six points are addressed and the auth/live-query/telemetry suites pass on the branch.

Blocking: this now conflicts with main. #456 added src/live-query/handlers.test.ts with two authenticate(..., { persistNewSession: false }) tests. Please merge main and keep both sets of tests in one file (one socket helper, and keep your @/telemetry mock; main's beforeEach rejects runLiveMethod, so without the mock those tests print to the console).

Description: please update it. verification.ts, resetPassword.ts, github.ts and google.ts were already migrated on main and aren't in this diff anymore. Please also add the MODELENCE_LOG_LEVEL note.

Nits:

  • In the fetch-error test, await vi.waitFor(...) would be more reliable than setTimeout(resolve, 10).
  • "Error cleaning up existing subscription" and "Error cleaning up after disconnect during setup" have no test yet.

@ankit-0903

Copy link
Copy Markdown
Contributor Author

Thanks @omegascorp! I've merged main and addressed all review items:

  1. Conflict resolved: Merged main and combined both sets of tests in src/live-query/handlers.test.ts into a single file with one socket helper and the @/telemetry mock.
  2. Reliable fetch-error test: Replaced setTimeout with await vi.waitFor(...).
  3. Additional test coverage: Added tests covering:
    • [LiveQuery] Error cleaning up existing subscription (when resubscribing with the same ID and previous cleanup fails)
    • [LiveQuery] Error cleaning up after disconnect during setup (when a disconnect occurs during async subscription setup and cleanup throws)
  4. Description updated: Updated the PR description to remove files already migrated on main and added the MODELENCE_LOG_LEVEL configuration note.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Replace console.error with structured logError in production paths

2 participants