refactor-initialize #221

Open
anomalist wants to merge 13 commits from refactor-initialize into master
Owner

Build Architecture Guard PR Template

Change Level

  • Level: L1 / L2 / L3 (pick one)

Why:

Scope & Impact

  • Files & platforms touched: …
  • Risk triggers (env / script flow / packaging / SW+WASM /
    Docker / signing): …
  • Mitigations/validation done: …

Commands Run (paste exact logs/snips)

  • Web: npm run build:web / :prod
  • Electron: npm run build:electron:dev / package step
  • Mobile: npm run build:android:test / iOS equivalent
  • Clean/auto-run impacted scripts

Artifacts

  • Names + sha256 of artifacts/installers:

Artifacts:

<name-1>  <sha256-1>
<name-2>  <sha256-2>

Docs

  • BUILDING.md updated (sections): …
  • Troubleshooting updated (if applicable)

Rollback

  • Verified steps (1–3 cmds) to restore previous behavior

L3 only

  • ADR link:

ADR: https://…

# Build Architecture Guard PR Template ## Change Level - [ ] Level: **L1** / **L2** / **L3** (pick one) **Why:** … ## Scope & Impact - [ ] Files & platforms touched: … - [ ] Risk triggers (env / script flow / packaging / SW+WASM / Docker / signing): … - [ ] Mitigations/validation done: … ## Commands Run (paste exact logs/snips) - [ ] Web: `npm run build:web` / `:prod` - [ ] Electron: `npm run build:electron:dev` / package step - [ ] Mobile: `npm run build:android:test` / iOS equivalent - [ ] Clean/auto-run impacted scripts ## Artifacts - [ ] Names + **sha256** of artifacts/installers: Artifacts: ```text <name-1> <sha256-1> <name-2> <sha256-2> ``` ## Docs - [ ] **BUILDING.md** updated (sections): … - [ ] Troubleshooting updated (if applicable) ## Rollback - [ ] Verified steps (1–3 cmds) to restore previous behavior ## L3 only - [ ] ADR link: ADR: https://…
anomalist added 5 commits 2025-11-09 00:02:28 +00:00
Refactored _initialize() method to eliminate brittle error message parsing,
add transactional migration safety, and improve observability.

Key improvements:
- Replaced error message parsing with deterministic capability checks
  (_ensureConnection helper)
- Wrapped migrations in BEGIN IMMEDIATE transaction with rollback
- Added platform-aware PRAGMA application (WAL on native, not web)
- Added structured phase timing logs (connect, open, pragmas, migrate, verify)
- Enhanced error cleanup with best-effort connection closure
- Updated integrity verification to throw on critical failures
- Extracted helper methods (_asMessage, _ensureConnection, _applyPragmas)
- Added configuration properties (dbVersion, encryption) to replace literals

Removed single-flight logic from _initialize() (handled by initializeDatabase()).
All connection state handling now uses isConnection() checks instead of
string matching, making initialization deterministic across JS/native
boundaries.
- Fix fallback PRAGMA method to open newly created connections immediately
- Prevents 'database not opened' errors when applying PRAGMAs
- Newly created connections are now opened before PRAGMA application
- Adds explicit logging for connection opening in fallback path
- Ensures journal_mode is correctly set to WAL instead of unknown

This fixes the issue where PRAGMAs were being applied on connections
that weren't yet opened, causing initialization failures. The fix ensures
that after creating a connection in the fallback path, it is immediately
opened before attempting to apply PRAGMAs.

Tested: Connection opens successfully, PRAGMAs apply correctly,
journal_mode set to WAL, initialization completes in ~38ms.
- Added comprehensive INVARIANTS documentation to _applyPragmasOnExistingConnection()
- Added ORDERING GUARD documentation to _initialize() and _ensureConnection()
- Enhanced iOS compatibility logging for WAL mode failures
- Added invariant reference comments throughout PRAGMA code paths
- Improved error handling with non-fatal WAL failure handling
- All invariants documented to prevent regression:
  1. foreign_keys via run()
  2. journal_mode via query() with iOS compatibility
  3. busy_timeout via query() with fallback
  4. synchronous skipped in fallback path
  5. this.db must be set before returning

This locks in the v3.3.3 fix and ensures stability on Android and iOS.
anomalist added 1 commit 2025-11-09 02:38:40 +00:00
anomalist added 1 commit 2025-11-09 06:27:51 +00:00
Extract queue management logic into reusable OperationQueue utility
shared between CapacitorPlatformService and AbsurdSqlDatabaseService.

Changes:
- Create OperationQueue.ts: shared queue handler with executor pattern
- Create types.ts: extract QueuedOperation interface to shared location
- Refactor CapacitorPlatformService: use shared queue, remove 65 lines
- Refactor AbsurdSqlDatabaseService: use shared queue, remove 22 lines
- Remove redundant logging wrapper: use centralized logger directly

Benefits:
- DRY: eliminated ~87 lines of duplicated queue logic
- Maintainability: queue behavior centralized in one place
- Consistency: both services use identical queue processing
- Flexibility: platform-specific parameter conversion preserved

File size reduction:
- CapacitorPlatformService: 1,525 → 1,465 lines (-60 lines)
- AbsurdSqlDatabaseService: 271 → 249 lines (-22 lines)
- New shared code: 150 lines (OperationQueue + types)

Net reduction: ~87 lines of duplicated code eliminated.
anomalist added 2 commits 2025-11-09 08:56:49 +00:00
- Refactor PlatformServiceFactory to use globalThis-based singleton storage
  - Store singleton in globalThis/window/self for persistence across module reloads
  - Add comprehensive debug logging for singleton lifecycle tracking
  - Implement Proxy-based lazy initialization to avoid circular dependencies
  - Add HMR support to preserve singleton across hot module replacement

- Enhance CapacitorPlatformService database connection recovery
  - Improve getOrCreateConnection() with robust error handling
  - Add recovery path for 'already exists' desync scenarios
  - Wrap retrieveConnection and db.open() calls in try-catch blocks
  - Handle cases where retrieveConnection throws instead of returning null
  - Add 50ms delay after closeConnection to allow native cleanup

- Add shared SQLite connection manager (sqlite.ts)
  - Centralize SQLiteConnection instance creation
  - Prevent connection desync issues across the application

This addresses the issue where PlatformService singleton was being
recreated on navigation, causing repeated database initialization
attempts and connection desync errors.
- Split long condition across multiple lines for better readability
- Applied by ESLint auto-fix
anomalist added 1 commit 2025-11-09 09:17:03 +00:00
- Replace window.location.href with router.push() for /seed-backup navigation
- Prevents full page reload that was causing app remount and singleton loss
- Maintains singleton persistence and database connection across navigation

This fixes the issue where navigating to seed-backup page via the reminder
modal was triggering a full page reload, causing the PlatformService singleton
to be lost and database to be re-initialized unnecessarily.
anomalist added 1 commit 2025-11-09 10:35:34 +00:00
- Removed excessive debug/success logs from CapacitorPlatformService
- Removed verbose singleton tracking logs from PlatformServiceFactory
- Removed unnecessary platform !== 'web' check in applyPragmas (service only loads for Capacitor)
- Compressed try-catch blocks in applyPragmas for cleaner code
- Extracted executor adapters to createExecutor() methods in both CapacitorPlatformService and AbsurdSqlDatabaseService for consistency and testability

This reduces console noise while maintaining essential error logging.
anomalist added 1 commit 2025-11-10 01:29:56 +00:00
- Fix window.location.href usage in DeepLinkRedirectView for Capacitor
  context: check if already in native app and use router navigation
  instead of window.location.href (which doesn't work in Capacitor)
- Consolidate teardown() and _cleanupOnFailure() by extracting shared
  cleanup logic to _performCleanup() method
- Make teardown() private since it's unused (kept for potential future use)
- Ensure both cleanup paths reset initializationPromise for consistency

This fixes navigation issues when DeepLinkRedirectView is accessed from
within the Capacitor app and removes code duplication in cleanup logic.
trentlarson added 1 commit 2025-11-12 01:59:01 +00:00
This pull request has changes conflicting with the target branch.
  • android/app/build.gradle
  • src/services/platforms/CapacitorPlatformService.ts
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin refactor-initialize:refactor-initialize
git checkout refactor-initialize
Sign in to join this conversation.
No Reviewers
No Label
2 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: trent_larson/crowd-funder-for-time-pwa#221