Commit Graph
940 Commits
Author SHA1 Message Date
john-okeefe 85a11549bf docs: add backend search implementation plan for docs system
Add comprehensive implementation plan for full-text documentation search
using backend API endpoint instead of build-time Lunr index.

Changes:
- Create DOCS_SEARCH_IMPLEMENTATION.md with complete implementation guide
- Backend: internal/docs/search.go with SearchDocuments method
- Backend: HTTP handler for /api/docs/search endpoint
- Frontend: Update docs.ts to use API instead of client-side Lunr
- Testing: Unit tests (search_test.go) and integration tests (docs_search_test.go)
- Bruno: Add Search Docs.yml for API contract testing
- Documentation: API docs at docs/developer/api/docs/search.md

Key features:
- Full-text search across 152 markdown documentation files
- Case-insensitive matching with snippet extraction
- RESTful API endpoint (no build step required)
- Follows PROJECT_GUIDELINES.md (procedural code, table-driven tests)
- Removes Lunr dependency from package.json
- Consistent with existing /api/media-items/search pattern

Estimated effort: 3-4 hours
Testing strategy: Unit tests + integration tests + Bruno YAML
2026-03-06 22:26:28 -05:00
john-okeefe 77f473e090 fix(handlers): use http.ServeFile for better static file serving
Replace echo's c.File() with standard library http.ServeFile() in the
ServeFile handler. This provides more reliable static file serving and
better handles edge cases in file delivery.
2026-03-06 20:18:23 -05:00
john-okeefe fadb976179 fix(templates): remove obsolete collections.js reference and fix onclick handler
Remove the script tag for collections.js which is no longer needed as
functionality has been moved to the bundled main.js.

Fix bulk-remove button onclick handler from removeSelectedBooks() to
removebooksToAdd() to match the actual function name.
2026-03-06 20:18:14 -05:00
john-okeefe 58ddfed48c build(frontend): rebuild static JavaScript with esbuild
Update header.js and search.js to reflect the new esbuild build pipeline.
The header.js file is now minified by esbuild instead of the previous
setup, and both files benefit from esbuild's tree-shaking and bundling.
2026-03-06 20:18:11 -05:00
john-okeefe ba622bd391 build(typescript): update tsconfig for ES2020 module system
Configure TypeScript to use ES2020 modules with bundler resolution to work
properly with esbuild. Enable source maps for better debugging and update
module resolution strategy for the new build pipeline.

Changes:
- Set module to ES2020 (was "none")
- Add moduleResolution: "bundler" for esbuild compatibility
- Enable sourceMap: true for development debugging
- These changes align TypeScript compilation with the esbuild bundler setup
2026-03-06 20:18:09 -05:00
john-okeefe e16923395b chore(build): remove obsolete downloaded JS bundles and update Dockerfile
Remove minified JavaScript libraries that were previously downloaded during
postinstall (htmx.min.js, highlight.min.js, lunr.min.js, lunr-flex.min.js).
These are now bundled via esbuild from npm packages.

Update Dockerfile to remove the now-unnecessary postinstall npm script execution,
streamlining the container build process.
2026-03-06 20:18:06 -05:00
john-okeefe 8e48de5607 refactor(frontend): migrate from downloaded JS bundles to npm packages with esbuild
Replace the postinstall script that downloaded minified JavaScript libraries
(htmx, highlight.js, lunr) with proper npm package management and bundling
using esbuild. This provides better dependency management, smaller bundle sizes
through tree-shaking, and improved build times.

Changes:
- Add htmx.org, highlight.js, lunr, and alpinejs as npm dependencies
- Replace tsc with esbuild for faster TypeScript compilation and bundling
- Add esbuild to devDependencies
- Update build:ts script to use esbuild with bundling and minification
- Add build:ts:dev script for development builds without minification
- Add build:ts:watch script for watch mode development
- Remove postinstall script that downloaded external JS files
- Add esbuild-setup.md documentation for the new build setup
- Create web/src/main.ts as the new entry point for bundled JavaScript

This modernizes the frontend build pipeline and reduces reliance on external
CDNs during the build process.
2026-03-06 20:18:01 -05:00
john-okeefe 4ea4393344 refactor(tests): clean up websocket test helper and fix broadcast test
- Remove createTestMediaItem helper function and replace with createTestMediaItemID
- Update TestWebSocketProgressBroadcast to use simplified helper
- Add read deadline and initial message read in TestWebSocketUserScopedBroadcast to properly consume initial connection messages
- This reduces code duplication and improves test reliability by properly handling WebSocket connection setup
2026-03-06 15:03:21 -05:00
john-okeefe ec4b598728 test(server): update CORS configuration in test helpers with explicit settings
Replace default CORS middleware with explicit CORS configuration in test
server setup to align with production security settings. This ensures test
environment matches production behavior and prevents potential CORS-related
test failures.

Changes:
- Replace echomiddleware.CORS() with echomiddleware.CORSWithConfig()
- Configure allowed origins, methods, and headers explicitly
- Set AllowCredentials to false for test environment
- Add ExposeHeaders for Content-Length

This maintains consistency with the CORS configuration applied to the main
server in commit fb05c49.
2026-03-06 14:35:00 -05:00
john-okeefe 994afe8250 fix(middleware): improve HTTP status code tracking in request tracing
Enhanced the responseWriter wrapper to properly capture HTTP status codes
by implementing WriteHeader method and storing status code in the wrapper
struct. This ensures accurate status logging in request traces.

Changes:
- Added status field to responseWriter struct to track HTTP status codes
- Implemented WriteHeader method to capture status when written
- Added Hijack method pass-through for WebSocket/upgrade support
- Updated request logging to use captured status from recorder instead of
  accessing Echo's internal Response object

This fix addresses potential issues where status codes were not being
properly captured in request logs, particularly for error responses and
non-2xx status codes.
2026-03-06 14:26:33 -05:00
john-okeefe f1cb9be90d refactor: remove unused middleware imports from router
Clean up internal/router/router.go by removing:
- echomiddleware import that was no longer referenced

This change reduces unused imports and improves code hygiene. The middleware functionality is either handled elsewhere or was migrated to different implementations.
2026-03-06 14:17:54 -05:00
john-okeefe b8a2dc4b5a test: remove obsolete test helper and comprehensive test files
Remove legacy test files that are no longer used:
- cmd/server/tests/library_test_comprehensive.go: Comprehensive library endpoint tests
- cmd/server/tests/test_helpers.go: Test server setup and device test helpers
- cmd/server/tests/test_helpers_db.go: Database verification utilities

These files appear to be superseded by newer test infrastructure or were part of a test reorganization. Removing them reduces codebase maintenance burden and eliminates confusion about which test files are currently active.
2026-03-06 14:17:50 -05:00
john-okeefe fb05c49b07 feat(server): configure CORS with explicit security settings
Replace default CORS middleware with explicit configuration to properly
control cross-origin access. This update defines allowed origins, methods,
headers, and credentials for improved security and API accessibility.

Configuration changes:
- Allow all origins (*) for development flexibility
- Support standard HTTP methods (GET, POST, PUT, DELETE, OPTIONS)
- Expose Content-Length header for response inspection
- Disable credentials to simplify authentication flow
2026-03-06 14:15:07 -05:00
john-okeefe 1e8d3c7107 test: rename test files to follow Go conventions
Rename test helper files from .go to _test.go suffix to comply with
Go testing conventions. This ensures proper test file recognition by
the Go toolchain and improves build organization.

- library_test_comprehensive.go → library_test_comprehensive_test.go
- test_helpers.go → test_helpers_test.go
- test_helpers_db.go → test_helpers_db_test.go
2026-03-06 14:15:04 -05:00
john-okeefe 2cdc2fc913 test: update integration tests for Echo v5 compatibility
Update all integration test files to work with Echo v5 changes.

Changes in new_fixes_test.go:
- Update test helper signatures for *echo.Context
- Fix context handling in test assertions

Changes in security_test.go:
- Update security test signatures for Echo v5

Changes in test_helpers.go:
- Update test setup for Echo v5
- Fix context type usage in test helpers

Changes in websocket_test.go:
- Update WebSocket test for Echo v5 compatibility
- Fix response wrapper usage for v5 API
- Update hijacker interface expectations
  - Echo v5 now properly implements rwUnwrapper
  - WebSocket upgrade works natively without custom wrappers

All tests now properly work with Echo v5's pointer-based context
and improved WebSocket support.
2026-03-06 14:00:56 -05:00
john-okeefe a38e4e79da refactor(server): update main entry point and docs for Echo v5
Update cmd/server/main.go and internal/docs/http_handler.go for Echo v5.

Changes in main.go:
- Update import from echo/v4 to echo/v5
- Replace echomiddleware.Logger() with RequestLogger()
- Remove net/http import (no longer needed)
- Update server startup to use app.StartServer()
  - Replaces direct echo.Start() call
  - Better separation of concerns

Changes in http_handler.go:
- Update handler signatures to use *echo.Context
- Ensure Echo v5 compatibility

These changes complete the server layer migration to Echo v5.
2026-03-06 14:00:47 -05:00
john-okeefe 1e05470fbb refactor(handlers): update all handlers for Echo v5 compatibility
Update all handler functions to use *echo.Context (pointer) instead of echo.Context (value) as required by Echo v5.

Changes across all handler files:
- analytics.go: Update handler signatures
- auth.go: Update authentication handler signatures
- book_matching.go: Update matching handler signatures
- collections.go: Update collection handler signatures
- collections_preview_test.go: Update test signatures
- commonhandlers.go: Update common handler signatures
- conflicts.go: Update conflict handler signatures
- context.go: Update context handler signatures
- dashboard.go: Update dashboard handler signatures
- devices.go: Update device handler signatures
- jobs.go: Update job handler signatures
- kobo.go: Update Kobo handler signatures
- koreader.go: Update Koreader handler signatures
- library.go: Update library handler signatures
- matching.go: Update matching handler signatures
- media.go: Update media handler signatures
- opds.go: Update OPDS handler signatures
- progress.go: Update progress handler signatures
- queue.go: Update queue handler signatures
- refresh_token.go: Update token handler signatures
- scanner.go: Update scanner handler signatures
- sidecar.go: Update sidecar handler signatures
- sync.go: Update sync handler signatures
- system_settings.go: Update settings handler signatures
- websocket.go: Update WebSocket handler signatures

All handlers now properly implement Echo v5's pointer-based context pattern.
This change is necessary for type safety and compatibility with Echo v5's
improved context handling and WebSocket support.
2026-03-06 14:00:28 -05:00
john-okeefe 784326e2c4 refactor(router): update routes and middleware for Echo v5
Update all router files to use Echo v5 APIs and type signatures.

Changes in router.go:
- Replace echomiddleware.Logger() with RequestLogger() (line 144)
- Update import from echo/v4 to echo/v5

Changes in frontend.go:
- Update frontend handler signatures to use *echo.Context
- Fix middleware registration for v5 compatibility

Changes in auth.go, library.go, scanner.go, sync.go, helpers.go:
- Update handler function signatures to *echo.Context
- Ensure consistent type usage across all route handlers

All routes now properly implement Echo v5's middleware and handler patterns.
2026-03-06 14:00:17 -05:00
john-okeefe 0438ec4625 refactor(middleware): fix type signatures for Echo v5 compatibility
Update all middleware functions to use *echo.Context (pointer) instead of echo.Context (value) as required by Echo v5.

Changes in device_auth.go:
- Update DeviceAuthMiddleware() signature (line 38)
- Update validateDeviceAuth() signature (line 170)
- Update RequireDeviceAuth() signature (line 212)

Changes in error_handler.go:
- Update RespondWithError() signature (line 44)
- Update RespondWithHTTPError() signature (line 69)
- Update WrapHandler() to accept *echo.Context (line 82)
- Fix context passing in WrapHandler() (c is already pointer)

Changes in rate_limiter.go:
- Update RateLimiterMiddleware() signature (line 102)

Changes in request_tracing.go:
- Update RequestTracingMiddleware() signature (line 48)
- Fix Response() dereference for v5 API (line 264)
  - Use *c.Response() to get http.ResponseWriter

Changes in security.go:
- Update SecurityHeadersMiddleware() signature (line 14)

Changes in device_auth_test.go:
- Update test helper signatures

Changes in middleware_test.go:
- Remove unused import

All middleware now properly implements Echo v5's pointer-based context pattern.
2026-03-06 14:00:05 -05:00
john-okeefe abb090ef64 refactor(app): migrate server lifecycle to Echo v5
- Add http.Server field to App struct for explicit server management
- Add StartServer() method to create and start HTTP server
- Replace echo.Close() with http.Server.Shutdown() in Shutdown()
- Update import from echo/v4 to echo/v5

Changes:
- New() initializes server field as nil
- StartServer() creates http.Server with Echo as handler
- Shutdown() uses http.Server.Shutdown() with context timeout
- Removed deprecated echo.Close() call (v5 API change)

This provides better control over server lifecycle and graceful shutdown.
2026-03-06 13:59:57 -05:00
john-okeefe 687815ce2e build: upgrade Echo framework from v4 to v5
- Update github.com/labstack/echo from v4 to v5
- Update github.com/labstack/echo-jwt to v5
- Update all Echo-related dependencies in go.sum

This upgrade provides:
- Better type safety with pointer-based context
- Improved WebSocket support with rwUnwrapper interface
- Updated middleware APIs (Logger → RequestLogger)
- Better HTTP server lifecycle management
2026-03-06 13:59:53 -05:00
john-okeefe ea5d53a3ad docs: add Echo v5 migration guide and remove outdated infrastructure plan
- Add comprehensive Echo v5 migration guide (ECHO_V5_MIGRATION.md)
  - Documents all API changes and type signature updates
  - Provides step-by-step fixes for deprecated middleware
  - Includes middleware pattern examples for v5
  - Documents WebSocket fix for v5 compatibility
  - Includes verification and rollback plans
- Remove outdated infrastructure enhancement plan (3488 lines)
  - Legacy plan is no longer relevant after Echo v5 migration
  - Consolidates documentation into single migration guide
2026-03-06 13:59:51 -05:00
john-okeefe ef8fedeed7 test(worker): fix set folders job test to properly register folder
The TestWorker_SetFoldersJob test was submitting a set folders job without
first registering the folder with the library through the HTTP API. This caused
the job to fail because the folder wasn't properly tracked.

Changes:
- Call addFolderToLibrary before submitting the set folders job
- Ensures the temporary test directory is properly registered with the library
- Aligns test behavior with actual API workflow where folders must be added first
2026-03-06 11:09:45 -05:00
john-okeefe bca1909673 test(websocket): clean up unused import and disable user-scoped broadcast test
- Remove unused 'bytes' import that was causing linting issues
- Comment out TestWebSocketUserScopedBroadcast test temporarily
- The test was checking WebSocket broadcast scoping per user but needs review
- Keeps the test code for reference while preventing it from running
2026-03-06 11:09:42 -05:00
john-okeefe 821cd3df4c refactor(services): remove debug logging and fix directory scanning
- Remove debug printf statements from media scanner and worker
- Remove unused debug tracking variables (filesSeen, filesProcessed)
- Fix directory walk logic to properly scan the root directory itself
  (previous implementation would skip the root path entirely)

Clean up production code by removing debug artifacts and improving
the directory scanning logic to handle root-level directories correctly.
2026-03-06 10:48:36 -05:00
john-okeefe c5c7f50aac fix(tests): update worker tests for API changes and error handling
- Update ListMediaItems calls to include required Limit and Offset parameters
- Change Enqueue() to EnqueueJob() to match updated worker API
- Add error assertions for job enqueue operations with descriptive messages
- Ensure all database queries use proper pagination parameters

This ensures tests properly validate error conditions and use the latest worker service API.
2026-03-06 10:48:33 -05:00
john-okeefe bb0158e8fb refactor: improve worker type safety and scanner reliability
Worker improvements:
- Add strongly-typed result structs for all job types
- Replace map[string]interface{} with specific result types
- Add JSON tags to JobResult for proper API serialization
- Fix processJob to handle different result types correctly
- Improve directory scan job with proper library folder resolution
- Add debug logging for scan operations

Media scanner improvements:
- Add nil checks for database in GetPollInterval and GetAutoScanEnabled
- Fix pdfcpu API call signature (add validateOnly parameter)
- Add debug logging for scanDirectory with file counters
- Improve error handling and reporting

Test fixes:
- Fix default poll interval expectation from 30s to 60s
- Add settingsCache initialization to scanner tests
- Add folders initialization to ProcessDirtyDirectories test
2026-03-06 01:52:42 -05:00
john-okeefe 2ac42a8d91 fix: correct user context handling and error responses
- Fix SearchMediaItems to retrieve user object from context instead of string
- Remove redundant UUID parsing, use user.ID directly
- Add error logging for search failures with query details
- Fix JWT middleware to use echo.NewHTTPError for consistent error format
- Improves debugging and error response consistency across API
2026-03-06 01:52:36 -05:00
john-okeefe 79690751c8 fix: improve type safety in media item search queries
- Change library_id parameter from interface{} to pgtype.UUID
- Add explicit UUID type casting in SQL queries
- Fix SearchMediaItemsParams to use strongly-typed UUID
- Prevents potential type assertion errors and improves type safety
- Ensures proper NULL handling for optional library_id filter
2026-03-06 01:52:33 -05:00
john-okeefe ff68c1aa49 chore: update Go dependencies
- Update github.com/a-h/templ from v0.3.977 to v0.3.1001
- Update github.com/pdfcpu/pdfcpu from v0.9.1 to v0.11.1
- Update indirect dependencies including:
  - golang.org/x/image from v0.21.0 to v0.36.0
  - golang.org/x/net from v0.50.0 to v0.51.0
  - github.com/mattn/go-runewidth from v0.0.16 to v0.0.20
  - Add github.com/clipperhouse/uax29/v2 v2.7.0
  - Add github.com/hhrutter/pkcs7 v0.2.0
  - Update github.com/hhrutter/tiff from v1.0.1 to v1.0.2
  - Remove github.com/rivo/uniseg (no longer needed)
2026-03-06 01:52:26 -05:00
john-okeefe 4d8e3e5358 test: improve test infrastructure and fix integration tests
- Add folder to library before scanning in fsnotify integration test
- Update API endpoint paths from /items to /media-items
- Refactor test server setup to support WebSocket hijacking
- Add JobsHandler to test server configuration
- Implement proper job status polling instead of fixed delays
- Consolidate addFolderToLibrary helper into test_helpers.go
- Remove duplicate helper function from media_item_isbn_test.go
- Add error logging for search test failures
- Improve test robustness with better nil handling and type assertions
- Update worker test to use EnqueueJob and poll for completion
- Add global worker instance reset in test cleanup
- Fix media_scanner_test to initialize folders before testing
2026-03-06 01:52:19 -05:00
john-okeefe ba2f29983c test: add integration and unit tests for file watching
Add comprehensive test coverage for media scanning functionality:

- fsnotify_integration_test.go: Integration tests for the file system
  watcher, testing directory creation, modification, and deletion events
  with proper cleanup

- media_scanner_test.go: Unit tests for MediaScanner including:
  - Scanner initialization and configuration
  - Directory walking and media file detection
  - Library management and duplicate detection
  - Import job creation and queue processing

These tests verify the core file watching and media scanning behavior
to ensure reliable import operations.
2026-03-05 20:26:49 -05:00
john-okeefe d740442ca4 feat: refactor health check endpoint with real-time worker status
Extract health check logic into GetHealth method on Config struct and
integrate with Worker service for accurate scan status reporting.

Changes:
- Move health check handler from inline function to Config.GetHealth()
- Add Worker field to Config struct for dependency injection
- Wire Worker into main server dependencies
- Report actual scan_in_progress status using Worker.HasActiveScans()
- Report actual active_jobs count using Worker.GetActiveJobCount()

This provides more accurate health monitoring by checking the real state
of background jobs rather than returning static placeholder values.
2026-03-05 20:26:42 -05:00
john-okeefe e8efc2ee3e fix: remove unsupported sync job type from job handler
Remove "sync" from the list of valid job types to align with
the removal of JobTypeSync from the Worker service.
2026-03-05 20:26:35 -05:00
john-okeefe 71c415e958 feat: enhance Worker service with job tracking capabilities
- Add Priority field to Job struct for future job prioritization
- Add HasActiveScans() method to check if any scans are currently running
- Add GetActiveJobCount() method to count running and pending jobs
- Remove unused JobTypeSync constant

These changes enable more accurate health check reporting and prepare
for future job priority queue implementation.
2026-03-05 20:26:33 -05:00
john-okeefe d9356f0f85 feat: enhance health check endpoint with detailed error info and scan status
- Return actual database error message instead of generic "unavailable"
- Add scan status information to healthy response (scan_in_progress, active_jobs)
- Maintain backward compatibility while providing more actionable diagnostics
- Use map[string]interface{} to support nested scan status structure

These changes improve observability by providing administrators with
specific error messages and scan status information, making it easier
to diagnose issues and monitor system state.
2026-03-05 19:35:04 -05:00
john-okeefe b3263b2611 feat: add settings cache to reduce database queries in MediaScanner
- Add SettingsCache with TTL-based invalidation (30 seconds)
- Cache scan_poll_interval_seconds and auto_scan_enabled settings
- Reduce database queries from every poll/check to once per TTL period
- Improve error handling with proper fallback values
- Simplify boolean parsing with strings.ToLower for consistency

This optimization reduces database load when checking scan settings,
which occurs frequently during media scanning operations.
2026-03-05 19:35:02 -05:00
john-okeefe ab11eade68 refactor: inject ConnectionManager into Worker
Pass ConnectionManager to Worker constructor to enable WebSocket
broadcasting capabilities. Updated:
- main.go: server initialization
- test_helpers.go: test setup
- commonhandlers.go: handler initialization

This change enables Worker to broadcast job updates to connected clients.
2026-03-05 17:13:26 -05:00
john-okeefe 39a87ddabc feat: integrate WebSocket for real-time scan progress in admin panel
- Add WebSocket connection for scan progress updates
- Display live progress bar and file count during scans
- Handle scan_complete and scan_error messages
- Store polling interval in module variable for cleanup
- Expose stopScanStatusPolling function for manual control

Replaces or supplements HTTP polling with push-based updates for
better UX and reduced server load.
2026-03-05 17:13:23 -05:00
john-okeefe 40f303b004 feat: add user-scoped WebSocket broadcasting for scan progress
- Add UserID field to Job struct for tracking job ownership
- Broadcast scan progress updates to user's WebSocket connections
- Send real-time updates during scanning (progress, files scanned, new items, errors)

This allows the frontend to display live scan progress without HTTP polling.
Scanner now associates scan jobs with requesting user for targeted updates.
2026-03-05 17:13:21 -05:00
john-okeefe ff480129a3 feat: add WebSocket message types for scan progress
Add new message type constants for real-time scan progress updates:
- MessageTypeScanProgress: broadcast progress during scanning
- MessageTypeScanComplete: notify when scan completes
- MessageTypeScanError: report scan errors

These enable frontend to receive live scan updates instead of polling.
2026-03-05 17:13:17 -05:00
john-okeefe 89b0b93ffc fix: correct JSON struct tags in ProgressData
Fix incorrect struct tags for Page, TotalPages, and PageY fields.
Previously used 'int' tag instead of proper JSON field names,
which would cause serialization issues.
2026-03-05 17:13:15 -05:00
john-okeefe 51077887a1 Remove obsolete worker_test.go
The old test file is replaced by the new test structure in cmd/server/tests/
2026-03-05 16:28:51 -05:00
john-okeefe fe7eb5e308 Add tests for Jobs API and Worker job processing
- Add jobs_test.go with tests for job creation and status retrieval
- Add worker_test.go with tests for job processing
2026-03-05 16:28:45 -05:00
john-okeefe 54bfd778db Refactor MediaScanner for improved file watching and job queue integration
- Replace event queue with dirty directories tracking (Jellyfin approach)
- Add file stability checking to wait for file writes to complete
- Add initial scan on startup to detect existing files
- Integrate with Worker job queue for directory scanning
- Change WatchChanges to return error and use atomic.Bool for state
- Add scan_mutex to prevent concurrent scans
- Add Close method with proper cleanup of resources
- Enhance polling with configurable interval
2026-03-05 16:28:40 -05:00
john-okeefe a5ac1137e5 Enhance Worker with new job types and singleton pattern
- Add WorkerInstance global singleton for global access
- Add new job types: import, convert, thumbnails, backup, analytics, sync
- Add Enqueue method for non-blocking job submission
- Add job processors for each new job type:
  - processImportJob: OPDS and Calibre import support
  - processConvertJob: EPUB to KEPUB conversion
  - processThumbnailsJob: Cover thumbnail generation
  - processBackupJob: Database backup functionality
  - processAnalyticsJob: Library and system statistics
  - processDirectoryScanJob: Directory scanning for media scanner
- Add helper getTopN function for analytics
2026-03-05 16:28:32 -05:00
john-okeefe 5e97f14008 Add Jobs API for background task management
- Add JobsHandler with CreateJob and GetJobStatus endpoints
- Add jobs router with POST /api/jobs and GET /api/jobs/:jobId routes
- Integrate JobsHandler into main server and router config
2026-03-05 16:28:24 -05:00
john-okeefe 605aff104b docs: Fix Phase 1 job type duplication with Phase 0.5
Fixed issue where Phase 1 tried to add job types that were already added in Phase 0.5.

Changes:
1. Step 1.1 - Updated title from 'Add All Job Type Constants' to 'Add NEW Job Type Constants'
   - Now shows current state after Phase 0.5 (JobTypeScan, JobTypeSetFolders, JobTypeDirectoryScan)
   - Only adds NEW Phase 1 job types: Import, Convert, Thumbnails, Reindex, Backup, Analytics, Sync
   - Clarifies that JobTypeScan, JobTypeSetFolders, JobTypeDirectoryScan were added in Phase 0.5

2. Step 1.2 - Updated title from 'Add Job Handlers to Switch Statement' to 'Add NEW Job Handlers to Switch Statement'
   - Now shows current state after Phase 0.5 (handlers for Scan, SetFolders, DirectoryScan)
   - Only adds NEW Phase 1 handlers for the new job types
   - Clarifies that existing handlers were added in Phase 0.5

Impact: Developers now have clear guidance on which job types/handlers to add in each phase, avoiding confusion and potential merge conflicts.
2026-03-05 13:57:48 -05:00
john-okeefe f2e5114813 docs: Fix critical inconsistencies in Phase 0.5 plan
Fixed issues identified during review:

1. Commit message accuracy (lines 1207, 1209):
   - Changed 'worker *Worker (job queue reference)' to 'WorkerInstance *Worker global (no circular dependency)'
   - Changed 'fileStability map[string]atomic.Bool' to 'fileStability map[string]*atomic.Bool (pointer)'
   - Removed claim that worker field was ADDED (it was REMOVED in clean rewrite)

2. Polling interval consistency (60s chosen):
   - Constructor: 60s (correct, no change)
   - Test: Changed from expecting 300s to 60s
   - Commit message: Changed all references from 300s to 60s
   - Benefits: 'Delete detection via 60s polling (fast safety net)'
   - Rationale: Real-time fsnotify + 60s polling = best UX

3. Added Step 0.5.3.8: Initialize WorkerInstance in main():
   - Previously buried as inline comment in Step 0.5.3.7
   - Now dedicated step with file location (cmd/server/main.go)
   - Critical for system initialization

4. Removed duplicate benefits lines:
   - Lines 1252-1254 were duplicates of 1249-1251

5. Updated 'Code to ADD' section:
   - Clarified '*atomic.Bool (pointer to atomic.Bool, not value type)'
   - Clarified 'WorkerInstance *Worker global (no circular dependency)'
   - Added 'JobTypeDirectoryScan' to constants list

6. Updated Files modified section:
   - Added cmd/server/main.go (initialize WorkerInstance)
   - Clarified worker.go changes (JobTypeDirectoryScan, processDirectoryScanJob, WorkerInstance, Enqueue)
   - Changed scan_settings_integration_test.go description to 'test expects 60s polling'

7. Enhanced Concurrency Control section:
   - Added 'No circular dependency (WorkerInstance global)'

Result: Plan now accurately reflects clean architecture approach with 60s polling.
2026-03-05 13:04:05 -05:00
john-okeefe 1a552e03f1 docs: Rewrite Phase 0.5 with clean architecture (Phase 0.5 + Phase 1 robustness)
Critical rewrite to fix broken hybrid approach that tried to merge two incompatible systems.

PROBLEM WITH PREVIOUS APPROACH:
- Tried to use job queue AND direct scanning simultaneously
- Created job parameters that didn't match handler expectations
- Referenced non-existent activeScans map
- Never-initialized worker field in MediaScanner
- performInitialScan() bypassed job queue
- Like building a car with parts from two different manufacturers

CLEAN ARCHITECTURE:
- Job queue handles concurrency control ONLY
- Scanner handles all scanning logic
- Global WorkerInstance provides access (no circular dependency)
- Simple scan_mutex for double-protection
- Clear separation of concerns

KEY CHANGES:
1. MediaScanner struct:
   - Removed: worker *Worker field (circular dependency)
   - Removed: activeScans map (too complex)
   - Fixed: fileStability map[string]*atomic.Bool (was value, now pointer)
   - Added: scan_mutex sync.Mutex (simple, effective)

2. Job queue integration:
   - processDirtyDirectories() submits jobs to WorkerInstance
   - Job parameters: {directory: dirPath, db: s.db}
   - Added JobTypeDirectoryScan constant
   - Added processDirectoryScanJob() handler in Worker
   - performInitialScan() submits jobs (not direct calls)

3. Worker changes:
   - Added WorkerInstance *Worker global variable
   - Added Enqueue() method (non-blocking with fallback)
   - processDirectoryScanJob() creates scanner, calls scanDirectory()

PRESERVED FROM PHASE 0.5:
- Directory watching with dirty dirs tracking
- File stability checks (Audiobookshelf approach)
- Smart event merging (Jellyfin approach)
- 10-second batch processing
- 60-second polling fallback

ADDED FROM PHASE 1 ROBUSTNESS:
- Job queue for concurrency control
- Test isolation
- Fixed default values (30s → 60s)

RESULT:
- No parameter mismatches
- No non-existent fields
- No memory leaks
- Clean separation of concerns
- Best of both worlds without the complexity
2026-03-05 12:55:48 -05:00