Skip to content
This repository was archived by the owner on Aug 2, 2025. It is now read-only.

Conversation

@Its4Nik
Copy link
Owner

@Its4Nik Its4Nik commented Jun 29, 2025

@sourcery-ai

Summary by Sourcery

Move API logic into a dedicated handlers layer, centralize WebSocket broadcasting, reorganize project structure for better modularity, and enhance scheduler, plugin loading, and database initialization.

New Features:

  • Introduce structured handler classes for all API endpoints (config, stacks, docker, logs, store, themes, database, health)
  • Implement a unified WebSocket broadcast server for streaming Docker stats, application logs, and stack events
  • Expand database schema with themes and store_repos tables and seed default values

Enhancements:

  • Refactor scheduler logic to use a reusable scheduledJob loop instead of setInterval
  • Replace all postToClient calls in stack operations with a unified broadcast function
  • Enhance PluginManager to dynamically load plugins on start and report plugin version
  • Decouple server initialization from index.ts by centralizing startup in a Starter class
  • Clean up package.json dependencies and update TypeScript config for bundler resolution and path aliases
  • Adjust docker-compose.dev settings for restart policy and mount paths
  • Standardize error handling across database backup/restore and utility functions

Its4Nik added 2 commits June 29, 2025 17:36
feat: Refactor routes and handlers

This commit introduces a refactoring of the application's route handling and logic by moving route definitions into dedicated handler files.

The commit includes the following changes:

- Removed the route files
- Created handler files
- Fixed all the imports/exports

This change improves the overall organization and maintainability of the codebase.
```
This commit improves code readability and consistency across handler files by:

- Standardizing import statements to be grouped and ordered.
- Ensuring consistent spacing and formatting within the code.
@sourcery-ai
Copy link

sourcery-ai bot commented Jun 29, 2025

Reviewer's Guide

This PR refactors the API by extracting routing and logic into dedicated handler classes, replacing the previous Elysia server setup with a unified handlers export; implements a generic WebSocket broadcasting layer for logs, stack events, and Docker stats; refactors the core scheduler to use a reusable job loop; enhances plugin management with asynchronous startup and consolidated reporting; expands the database schema to include store repositories and themes (while removing API key storage); cleans up dependencies and configuration; and strengthens error handling and data validation throughout backup, restore, and stats operations.

Sequence diagram for WebSocket broadcast of stack events

sequenceDiagram
    participant StackHandler
    participant Controller as StackController
    participant Broadcast as broadcast (WebSocket)
    participant Client
    StackHandler->>Controller: deployStack(config)
    Controller->>Broadcast: broadcast({topic: "stack", data: {...}})
    Broadcast-->>Client: WebSocket message (stack event)
    Note over Client: Client receives stack status/progress/error
Loading

Sequence diagram for unified handler invocation

sequenceDiagram
    actor User
    participant App as Application
    participant Handlers as handlers/index.ts
    participant ApiHandler
    User->>App: API request (e.g. updateConfig)
    App->>Handlers: handlers.ApiHandler.updateConfig(...)
    Handlers->>ApiHandler: updateConfig(...)
    ApiHandler-->>Handlers: result
    Handlers-->>App: result
    App-->>User: response
Loading

ER diagram for updated database schema (config, store_repos, themes)

erDiagram
    CONFIG {
        NUMBER keep_data_for
        NUMBER fetching_interval
    }
    STORE_REPOS {
        TEXT slug
        TEXT base
    }
    THEMES {
        TEXT name PK
        TEXT creator
        TEXT vars
        TEXT tags
    }
Loading

File-Level Changes

Change Details Files
Centralize API routing and logic into handler classes
  • Replaced Elysia server setup in src/index.ts with default handlers export
  • Moved route definitions into src/handlers as classes (config, stacks, docker, logs, store, themes)
  • Added Starter module to orchestrate scheduler, plugin startup, and WebSocket server
src/index.ts
src/handlers/index.ts
src/handlers/config.ts
src/handlers/stacks.ts
src/handlers/docker.ts
src/handlers/logs.ts
src/handlers/store.ts
src/handlers/themes.ts
src/handlers/modules/starter.ts
Introduce generic WebSocket broadcast layer
  • Added broadcast utility and WSServer in handlers/modules/docker-socket.ts
  • Unified log and stack stream modules using PassThrough in handlers/modules/logs-socket.ts and live-stacks.ts
  • Updated core stacks controller and runStackCommand to use broadcast instead of postToClient
src/handlers/modules/docker-socket.ts
src/handlers/modules/logs-socket.ts
src/handlers/modules/live-stacks.ts
src/core/stacks/controller.ts
src/core/stacks/operations/runStackCommand.ts
Refactor core scheduler to reusable job loop
  • Replaced setInterval with scheduledJob loop handling timing and errors
  • Centralized task logging and delay calculation in scheduledJob
src/core/docker/scheduler.ts
Enhance plugin manager for async startup and reporting
  • Added async start() to initialize plugins before server start
  • Consolidated active and failed plugin info (including version) in getPlugins
  • Adjusted loader to supply default version on failure
src/core/plugins/plugin-manager.ts
src/core/plugins/loader.ts
Expand database schema and store repository support
  • Added store_repos and themes tables (with default seeds) and removed api_key column
  • Created stores and themes modules under core/database with CRUD operations
  • Updated database index exports to include new store and theme functions
src/core/database/database.ts
src/core/database/config.ts
src/core/database/stores.ts
src/core/database/themes.ts
src/core/database/index.ts
Clean up dependencies and configuration
  • Removed Elysia, CORS, Swagger, static, and other unused packages from package.json
  • Updated tsconfig with bundler resolution and new path mappings
  • Pruned outdated middleware/routes and refreshed dependency-graph files
package.json
tsconfig.json
dependency-graph.mmd
dependency-graph.svg
Improve error handling and data validation
  • Wrapped non-Error exceptions in backup and restore operations as Error instances
  • Strengthened type validation in addContainerStats signature and usage
  • Adjusted updateConfig to remove api_key parameter and enforce types
src/core/database/backup.ts
src/core/database/containerStats.ts

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai bot changed the title @sourcery-ai Refactor: Move API logic to handlers Jun 29, 2025
@Its4Nik Its4Nik self-assigned this Jun 29, 2025
@Its4Nik Its4Nik added enhancement New feature or request Breaking change labels Jun 29, 2025
@Its4Nik Its4Nik added this to the v3 milestone Jun 29, 2025
This commit removes the API key functionality from the DockStatAPI.
The API key column is removed from the config table in the database,
and the updateConfig function no longer accepts or updates the API key.
This change simplifies the configuration and security of the application.

The Docker websocket route and auth middleware was removed, since it is not used anymore.

BREAKING CHANGE: The API key functionality has been removed.
Users will no longer be able to set or validate an API key.
The config endpoint takes only keep_data_for and fetching_interval now.
@Its4Nik Its4Nik force-pushed the remove-elysia-for-direct-integration branch from 6c1269e to d3601a5 Compare June 29, 2025 22:53
actions-user and others added 9 commits June 29, 2025 22:53
This commit moves the `typings` directory to the root of the project.
This change affects the import paths in `runStackCommand.ts` and `logger.ts`, which have been updated accordingly.

The diff includes:
- Update import path for `postToClient` in `runStackCommand.ts` to `~/handlers/modules/live-stacks`.
- Update import path for `Stack` in `runStackCommand.ts` to `~/../typings/docker-compose`.
- Update import path for `log_message` in `logger.ts` to `../../../typings/database`.
- Moves the typings dir to the root of the project

The reason for this change is to simplify the project structure and make the typings more accessible to other parts of the application.
@Its4Nik Its4Nik force-pushed the remove-elysia-for-direct-integration branch from b547fae to fd4e219 Compare June 30, 2025 19:35
@Its4Nik Its4Nik force-pushed the remove-elysia-for-direct-integration branch from 85ab23e to 6ef8769 Compare July 3, 2025 13:22
@Its4Nik Its4Nik force-pushed the remove-elysia-for-direct-integration branch from 5f47dbf to 082bfa8 Compare July 6, 2025 14:58
Its4Nik and others added 3 commits July 8, 2025 22:34
This commit introduces the ability to manage store repositories within the application. It includes:

- Creation of a  table in the database to store repository information (slug and base URL).
- Implementation of functions to add, retrieve, and delete store repositories from the database.
- Creation of a new handler  to expose store repository management functionalities via API.
…4Nik/DockStatAPI into remove-elysia-for-direct-integration
@Its4Nik
Copy link
Owner Author

Its4Nik commented Jul 8, 2025

@sourcery-ai review

sourcery-ai[bot]

This comment was marked as resolved.

Its4Nik added 2 commits July 10, 2025 00:47
This commit introduces a new table  to the database, allowing users to store and manage custom themes for the application. It also provides the ability to save a default theme on first start.

The following changes were made:

- Added a  table to the database schema.
- Added functions to interact with the  table.
- Add a Theme handler to expose theme actions
Updates the theme colors to a dark mode palette. This includes changes to accent colors, border colors, background colors, and gradient colors.
@Its4Nik Its4Nik force-pushed the remove-elysia-for-direct-integration branch from 4017eb6 to 4ac7e14 Compare July 9, 2025 22:53
This commit introduces a transformation of the `vars` field in the `addTheme` function. It converts a JSON object of CSS variables into a string of CSS rules that target the root element. Additionally, it updates the themes table to set the name field as the primary key. This change is crucial for ensuring data integrity and efficient theme management.
@Its4Nik Its4Nik force-pushed the remove-elysia-for-direct-integration branch from 3502579 to 503db97 Compare July 10, 2025 09:34
Its4Nik and others added 5 commits July 10, 2025 09:34
This commit introduces new CSS variables for text colors: `--text-primary`, `--text-secondary`, and `--text-muted`. These variables are defined within the `:root, #root, #docs-root` CSS selector and provide a centralized way to manage text colors across the application. This will improve consistency and make it easier to adjust the color scheme in the future.
This commit introduces several enhancements to the configuration handling and adds functionality to retrieve the package.json data.

The changes include:

- Update config to use package.json
- Enhanced config handling in `src/handlers/config.ts`:
  - Updated the getConfig, updateConfig, getPlugins, createbackup, listBackups, downloadbackup, restoreBackup, addHost, updateHost, and removeHost functions to improve error handling and logging.
- Added a new getPackage function to retrieve package.json data.
- Updated the index file to export new handlers
The `PackageJson` type from `knip` was imported but not used in the `config.ts` file. This commit removes the unused import to improve code clarity and reduce unnecessary dependencies.
- Updated the default theme variables in the database initialization to improve the initial user experience.
- Minor formatting and consistency improvements in database initialization logic.
@Its4Nik
Copy link
Owner Author

Its4Nik commented Jul 12, 2025

@sourcery-ai review

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @Its4Nik - I've reviewed your changes - here's some feedback:

  • Avoid performing heavy startup tasks (like scheduling jobs and launching the WebSocket server) as side-effects during module imports in handlers/index.ts; decouple initialization into an explicit start function so the entry point controls when and how the system comes up.
  • Standardize error handling by preserving original Error instances instead of wrapping everything in new Error(error as string), which strips stack traces and context—consider rethrowing or using cause to retain full error information.
  • Remove hard-coded plugin paths in PluginManager.start (e.g. './server/src/plugins') and make the plugin directory configurable or aligned with the actual project layout to prevent path mismatches during startup.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Avoid performing heavy startup tasks (like scheduling jobs and launching the WebSocket server) as side-effects during module imports in handlers/index.ts; decouple initialization into an explicit start function so the entry point controls when and how the system comes up.
- Standardize error handling by preserving original Error instances instead of wrapping everything in `new Error(error as string)`, which strips stack traces and context—consider rethrowing or using `cause` to retain full error information.
- Remove hard-coded plugin paths in PluginManager.start (e.g. './server/src/plugins') and make the plugin directory configurable or aligned with the actual project layout to prevent path mismatches during startup.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines 33 to 45
while (true) {
const start = Date.now();
logger.info(`Task Start: ${name}`);
try {
await jobFn();
logger.info(`Task End: ${name} succeeded.`);
} catch (e) {
logger.error(`Task End: ${name} failed:`, e);
}
const elapsed = Date.now() - start;
const delay = Math.max(0, intervalMs - elapsed);
await new Promise((r) => setTimeout(r, delay));
}
Copy link

Choose a reason for hiding this comment

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

issue (code-quality): Avoid loops with missing or constant end conditions. (avoid-infinite-loops)

ExplanationLoops with a constant condition, or no terminator, can be useful in certain contexts, but it's easy to forget to break out of them. This rule highlights loops which may never end.

Copy link
Owner Author

Choose a reason for hiding this comment

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

@sourcery-ai issue

Copy link

Choose a reason for hiding this comment

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

I have created an issue for your comment: #52

This commit introduces a mechanism to reload the schedules when the configuration is updated. This ensures that the scheduler is always running with the latest configuration settings. It also adds logging to the deletion of Themes

The changes include:

- Added a  function to the  file. This function clears all existing schedules and restarts them.
- Modified the  function in  to call the  function after updating the configuration in the database.
- Added logging to theme deletion
@Its4Nik Its4Nik force-pushed the remove-elysia-for-direct-integration branch from b51e708 to 253b084 Compare July 13, 2025 12:17
@Its4Nik Its4Nik merged commit e4d1eb3 into dev Jul 13, 2025
2 checks passed
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

Breaking change enhancement New feature or request

Projects

No open projects
Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants