Skip to content

Commit e72ca20

Browse files
committed
feat: add admin dashboard and logging enhancements
- Implemented a new admin dashboard that starts on http://localhost:9000 using create-polyglot. - Added logging initialization for services, creating a logger helper if it doesn't exist. - Integrated chokidar for real-time log file monitoring and updates. - Enhanced log retrieval with filtering options for level and timestamp. - Updated service index.js to dynamically import the logger for better ESM compatibility. - Improved error handling and graceful shutdown procedures in the Node service. Signed-off-by: kaifcoder <kaifmohd2014@gmail.com>
1 parent c5c29f5 commit e72ca20

File tree

9 files changed

+858
-256
lines changed

9 files changed

+858
-256
lines changed

.github/copilot-instructions.md

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,5 +63,87 @@ Purpose: This repo is a CLI (`bin/index.js`) that scaffolds a polyglot monorepo
6363

6464
If adding major refactors (e.g., splitting CLI), document new module boundaries here.
6565

66+
## Admin Dashboard & Log Streaming (Updated)
67+
The admin dashboard (`startAdminDashboard` in `bin/lib/admin.js`) now uses a chokidar-powered file watcher for real-time service logs.
68+
69+
### Log Watching Implementation
70+
- Class: `LogFileWatcher` in `bin/lib/logs.js`.
71+
- Dependency added: `chokidar` (installed in root `package.json`).
72+
- Watches each service's `.logs/*.log` files (supports both legacy `apps/<service>` and new `services/<service>` paths).
73+
- Maintains an in-memory cache (`serviceLogsCache`) with latest logs per service (capped to 1000 per service when merging updates).
74+
- Emits events to listeners: `logsUpdated` (with `event: add|change`), `logsCleared` (on file deletion).
75+
76+
### WebSocket Protocol (Simplified)
77+
- Endpoint: `/ws` (still a minimal custom implementation—no external WS library).
78+
- Client sends `{ type: 'start_log_stream', service: <optionalServiceName|null> }` to (re)subscribe.
79+
- Server pushes messages:
80+
- `log_data`: initial batch (tail 100) for requested service or all services.
81+
- `log_update`: incremental updates (new lines) as files change.
82+
- `logs_cleared`: emitted when a log file is deleted (e.g., rotation/cleanup).
83+
- `error`: watcher or processing failures.
84+
85+
### Removed UI Elements / Behavior
86+
- Manual "Refresh" and "Live Stream" buttons removed; streaming starts automatically on page load.
87+
- No explicit "Start/Stop" toggling—connection auto-reconnects with exponential backoff on disconnect.
88+
- Filtering (service, level, search text) is applied client-side against the cached `allLogsCache`.
89+
- Re-sending `start_log_stream` with a new service filter requests a narrower set without page reload.
90+
91+
### Server-Side Changes
92+
- `globalLogWatcher` initialized when dashboard starts; falls back gracefully if initialization fails.
93+
- `/api/logs` now serves from watcher cache if available (still present for manual export and any non-WS consumers).
94+
95+
### Client-Side Changes (`admin.js` embedded script)
96+
- Removed functions: `fetchLogs`, `toggleLogStream`, `stopLogStream`, `updateStreamButton`, incremental DOM `appendLogs` logic.
97+
- Added in-memory `allLogsCache` and `applyClientFilters()` for dynamic filtering without refetch.
98+
- Reconnect logic retains filters by re-sending latest `start_log_stream` payload on open.
99+
100+
### Considerations / Future Enhancements
101+
- Potential optimization: send only new log line(s) instead of array (currently small overhead acceptable).
102+
- Add backend endpoint for clearing logs (currently UI shows confirmation but warns unimplemented).
103+
- Could expose a `since` param in WebSocket start message for time-based tailing.
104+
- Log rotation: `cleanupOldLogs` keeps most recent 10 daily files; watcher handles file add/delete events transparently.
105+
106+
### Pitfalls to Avoid When Extending
107+
- If introducing batching: ensure not to stall UI; prefer immediate push for smaller latency.
108+
- When adjusting max cache size, reflect limits both server-side (merge logic) and client-side (slice for rendering).
109+
- Avoid blocking operations in watcher event handler; heavy parsing should be deferred if logs grow large.
110+
111+
### Testing Notes
112+
- Existing Vitest suite did not reference removed buttons; no test changes required.
113+
- For new tests: simulate writing to `.logs/<date>.log` and assert WebSocket `log_update` is received (could add an integration test harness later).
114+
115+
Update this section if log streaming protocol or watcher boundaries change.
116+
117+
## CLI Usage Summary (Reference)
118+
For detailed, user-facing examples see the README (search for "Quick Start", "Commands"). This section is a concise operator guide.
119+
120+
Primary commands:
121+
- `create-polyglot init <name> [flags]` – Scaffold a new workspace. Flags: `-s, --services`, `--preset <turbo|nx|none>`, `--package-manager <npm|pnpm|yarn|bun>`, `--git`, `--yes`, `--frontend-generator`.
122+
- `create-polyglot add service <name> --type <node|python|go|java|frontend> [--port <p>] [--yes]` – Append a service to an existing workspace.
123+
- `create-polyglot dev [--docker]` – Local dev runner (frontend + node by default). With `--docker` delegates to Docker Compose for all services.
124+
- `create-polyglot hot [--services a,b] [--dry-run]` – Unified hot reload orchestrator across selected services.
125+
- `create-polyglot admin [--port <p>] [--open false]` – Start admin dashboard (status + real-time logs).
126+
- `create-polyglot logs [<service>] [--tail <n>] [--level <error|warn|info|debug>] [--filter <regex>] [--since <relative|ISO>] [--clear]` – CLI log viewing / maintenance.
127+
128+
Behavior notes:
129+
- `init` writes `polyglot.json` manifest which powers all subsequent commands.
130+
- Port uniqueness enforced during `init` and `add service`; collisions abort early.
131+
- `hot` uses language-specific runners (e.g. Node via `nodemon` or custom; Python via `uvicorn`; Go recompile; Java Spring Boot restart) aggregated in a single multiplexed output.
132+
- `admin` now auto-streams logs (no refresh or manual toggle) leveraging `LogFileWatcher` + WebSocket events described above.
133+
- `logs --clear` performs per-service log directory cleanup (invokes helper in `logs.js`). Non-critical failures warn.
134+
- `dev --docker` assumes generated Dockerfiles; if one is missing for a service, generation logic from scaffold covers it.
135+
136+
Error handling conventions:
137+
- Hard validation failures → red emoji + `process.exit(1)` prior to partial writes.
138+
- Soft failures (git init, dependency install, external generators) log yellow warning and continue.
139+
140+
Testing guidance:
141+
- Prefer `execa` for invoking CLI within tests; set generous timeouts (≥30s) for Next.js or Java operations.
142+
- For admin log stream tests, you can simulate writes to `.logs/<date>.log` then assert WebSocket `log_update` message.
143+
144+
When extending:
145+
- Add new command flags in `bin/index.js` commander chain; reflect in README and this summary.
146+
- Keep README examples authoritative; this section should remain concise.
147+
66148
---
67149
Feedback: Let me know if any sections need more depth (e.g., Docker generation, prompt flow, adding new presets) or if emerging conventions should be captured.

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ Use it to prototype architectures, onboard teams faster, or spin up reproducible
6767
- 📄 Single source of truth: `polyglot.json`
6868
- ✅ Safe guards: port collision checks, reserved name checks, graceful fallbacks
6969
- 📝 Friendly chalk-based CLI output with clear status symbols
70+
- 📡 Admin dashboard with real-time log streaming (chokidar file watching, no manual refresh needed)
7071

7172
## Quick Start
7273
Scaffold a workspace named `my-org` with multiple services:

0 commit comments

Comments
 (0)