Tom716 commited on
Commit
74dc076
·
verified ·
1 Parent(s): 4b0f340

Upload system_knowledge_base.md

Browse files
Files changed (1) hide show
  1. system_knowledge_base.md +225 -0
system_knowledge_base.md ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SYSTEM ARCHITECTURE & OPERATIONAL MANUAL (`KNOWLEDGE.md`)
2
+
3
+ > **Target Audience:** AI Coding Agents, Automated CI/CD Pipelines, and Systems Engineers.
4
+ > **Scope:** Architecture, configuration standards, service management SOPs, and troubleshooting guides for the `Tom716/set-api` Hugging Face Space.
5
+
6
+ ---
7
+
8
+ ## 1. System Overview & Architecture
9
+
10
+ This repository hosts a multi-service backend environment on **Hugging Face Spaces (Free Tier)**. It utilizes a mono-repo structure where multiple isolated backend services run concurrently inside a single Docker container managed by **Supervisord** and routed externally via a **Caddy** reverse proxy.
11
+
12
+ ### System Stack Summary
13
+ - **Infrastructure Provider:** Hugging Face Spaces (Docker SDK)
14
+ - **Container Base OS:** Ubuntu 22.04 LTS
15
+ - **Process Manager:** Supervisord (`supervisord`)
16
+ - **Reverse Proxy / Router:** Caddy Server v2
17
+ - **Public Ingress Port:** `7860` (Hard requirement by Hugging Face)
18
+ - **Container User Security:** Non-root execution under User ID `1000` (`user:user`)
19
+ - **Keep-Alive Engine:** External HTTP pinging (e.g., Better Stack) targeting `/status` every 5 minutes
20
+
21
+ ```
22
+ Public Web Traffic (HTTPS Edge)
23
+ │
24
+ ▼
25
+ ┌─────────────────────────────┐
26
+ │ Hugging Face Edge Proxy │
27
+ └──────────────┬──────────────┘
28
+ │ Port 7860
29
+ ▼
30
+ ┌─────────────────────────────┐
31
+ │ Caddy Reverse Proxy │
32
+ └──────────────┬──────────────┘
33
+ │
34
+ ┌───────────────────────┼───────────────────────┐
35
+ │ │ │
36
+ ▼ ▼ ▼
37
+ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐
38
+ │ Caddy /status │ │ NestJS API │ │ FastAPI App │
39
+ │ Health Endpoint│ │ Telegram Demo │ │ K3s Test App │
40
+ │ (Internal) │ │ (Port 3000) │ │ (Port 8000) │
41
+ └───────────────┘ └───────────────┘ └───────────────┘
42
+ ```
43
+
44
+ ---
45
+
46
+ ## 2. Directory Layout & Routing Matrix
47
+
48
+ ### Directory Layout
49
+ ```text
50
+ / (Repository Root)
51
+ ├── Dockerfile # Container build instructions & runtime setup
52
+ ├── Caddyfile # Reverse proxy routing rules
53
+ ├── supervisord.conf # Multi-process supervisor configuration
54
+ ├── KNOWLEDGE.md # System documentation (This File)
55
+ └── projects/ # Multi-service monorepo directory
56
+ ├── telegram-send-demo/ # Service 1: NestJS + Telegram Bot Engine
57
+ │ └── backend/ # NestJS API source code
58
+ └── k3s-test-app/ # Service 2: Python FastAPI Service
59
+ ├── pyproject.toml # Python build metadata
60
+ └── src/k3s_test_app/ # FastAPI source code
61
+ ```
62
+
63
+ ### Port Allocation & Ingress Matrix
64
+
65
+ | Service | Internal Port | Ingress Path | Health / Docs Path |
66
+ | :--- | :--- | :--- | :--- |
67
+ | **Caddy Proxy** | `7860` (Public) | `/` | `GET /status` |
68
+ | **Caddy Admin API** | `2019` (Local) | `localhost:2019` | N/A |
69
+ | **NestJS Telegram Service** | `3000` (Internal)| `/api/telegram/*` | `GET /api/telegram/health`, `/api/docs` |
70
+ | **Python FastAPI Service** | `8000` (Internal)| `/api/k3s/*` | `GET /api/k3s/health`, `/api/k3s/docs` |
71
+
72
+ ---
73
+
74
+ ## 3. Configuration File Standards
75
+
76
+ ### 3.1 `Caddyfile` Standard
77
+ ```caddy
78
+ {
79
+ admin localhost:2019
80
+ auto_https off
81
+ }
82
+
83
+ :7860 {
84
+ # Keep-Alive Status Check
85
+ handle /status {
86
+ respond "Caddy Proxy Active" 200
87
+ }
88
+
89
+ # Service: Telegram NestJS Backend
90
+ handle /api/telegram/* {
91
+ reverse_proxy localhost:3000
92
+ }
93
+
94
+ # Service: Python FastAPI Backend (Strips prefix for internal app routing)
95
+ handle /api/k3s/* {
96
+ uri strip_prefix /api/k3s
97
+ reverse_proxy localhost:8000
98
+ }
99
+
100
+ # Default Fallback (Routes to primary API service)
101
+ handle {
102
+ reverse_proxy localhost:3000
103
+ }
104
+ }
105
+ ```
106
+
107
+ ### 3.2 `supervisord.conf` Standard
108
+ ```ini
109
+ [supervisord]
110
+ nodaemon=true
111
+ user=user
112
+
113
+ [program:caddy]
114
+ command=caddy run --config /etc/caddy/Caddyfile --adapter caddyfile
115
+ autostart=true
116
+ autorestart=true
117
+ stdout_logfile=/dev/stdout
118
+ stdout_logfile_maxbytes=0
119
+ stderr_logfile=/dev/stderr
120
+ stderr_logfile_maxbytes=0
121
+
122
+ [program:nestjs_backend]
123
+ command=node /app/projects/telegram-send-demo/backend/dist/main.js
124
+ directory=/app/projects/telegram-send-demo/backend
125
+ autostart=true
126
+ autorestart=true
127
+ stdout_logfile=/dev/stdout
128
+ stdout_logfile_maxbytes=0
129
+ stderr_logfile=/dev/stderr
130
+ stderr_logfile_maxbytes=0
131
+
132
+ [program:k3s_backend]
133
+ command=/app/projects/k3s-test-app/.venv/bin/uvicorn k3s_test_app.main:app --host 127.0.0.1 --port 8000 --root-path /api/k3s
134
+ directory=/app/projects/k3s-test-app
135
+ autostart=true
136
+ autorestart=true
137
+ stdout_logfile=/dev/stdout
138
+ stdout_logfile_maxbytes=0
139
+ stderr_logfile=/dev/stderr
140
+ stderr_logfile_maxbytes=0
141
+ ```
142
+
143
+ ---
144
+
145
+ ## 4. Standard Operating Procedures (SOPs)
146
+
147
+ ### 4.1 How to Add a New API Backend Service
148
+
149
+ When adding a new backend (e.g., `analytics-service` running on port `4000`):
150
+
151
+ 1. **Upload Source:** Place the project files inside `/projects/analytics-service`.
152
+ 2. **Update `Dockerfile`:** Add the build steps for the new runtime/dependencies:
153
+ ```dockerfile
154
+ COPY projects/analytics-service /app/projects/analytics-service
155
+ RUN cd /app/projects/analytics-service && npm install && npm run build
156
+ ```
157
+ 3. **Update `supervisord.conf`:** Define a new supervisor process block:
158
+ ```ini
159
+ [program:analytics_service]
160
+ command=node /app/projects/analytics-service/dist/main.js
161
+ directory=/app/projects/analytics-service
162
+ autostart=true
163
+ autorestart=true
164
+ stdout_logfile=/dev/stdout
165
+ stdout_logfile_maxbytes=0
166
+ stderr_logfile=/dev/stderr
167
+ stderr_logfile_maxbytes=0
168
+ ```
169
+ 4. **Update `Caddyfile`:** Route a unique path prefix to the allocated internal port:
170
+ ```caddy
171
+ handle /api/analytics/* {
172
+ reverse_proxy localhost:4000
173
+ }
174
+ ```
175
+ 5. **Commit & Deploy:** Commit changes to `main`. Hugging Face will trigger a fresh container build automatically.
176
+
177
+ ---
178
+
179
+ ### 4.2 How to Remove an Existing Service
180
+
181
+ To decommission a service (e.g., `projects/k3s-test-app`):
182
+
183
+ 1. **Update `Caddyfile`:** Remove the corresponding `handle /api/k3s/*` block.
184
+ 2. **Update `supervisord.conf`:** Remove the `[program:k3s_backend]` block.
185
+ 3. **Update `Dockerfile`:** Remove build lines associated with that project.
186
+ 4. **Delete Directory:** Delete `/projects/k3s-test-app`.
187
+ 5. **Commit Changes:** Push to `main`.
188
+
189
+ ---
190
+
191
+ ## 5. Critical Troubleshooting & System Rules
192
+
193
+ Any agent modifying this repository must follow these rules to avoid production breakages:
194
+
195
+ ### 1. Node.js IPv6 DNS Resolution Fix (`ipv4first`)
196
+ - **Problem:** Node.js 20+ defaults to IPv6 DNS resolution. Inside Hugging Face Docker containers without outbound IPv6 routing, outbound HTTP requests (e.g., grammY hitting `api.telegram.org`) hang until timing out, returning a `503` error.
197
+ - **Mandatory Fix:** Always include the following at the top of Node.js entrypoints (`main.ts`):
198
+ ```typescript
199
+ import * as dns from 'dns';
200
+ dns.setDefaultResultOrder('ipv4first');
201
+ ```
202
+
203
+ ### 2. FastAPI Behind Reverse Proxy Subpaths (`--root-path`)
204
+ - **Problem:** When FastAPI is proxied under a subpath like `/api/k3s/*`, Swagger UI fails to fetch OpenAPI specs (`/openapi.json` returns 404).
205
+ - **Mandatory Fix:** Always launch Uvicorn with `--root-path /api/<service_name>` or configure `root_path="/api/<service_name>"` inside `FastAPI()`.
206
+
207
+ ### 3. NPM Lockfile Synchronization (`npm install` vs `npm ci`)
208
+ - **Problem:** `npm ci` fails if `package.json` and `package-lock.json` are slightly out of sync during container builds.
209
+ - **Mandatory Fix:** Use `npm install` inside the container build steps in `Dockerfile` to dynamically install missing transitive dependencies.
210
+
211
+ ### 4. Base Image Python Versioning
212
+ - **Problem:** Ubuntu 22.04 LTS provides **Python 3.10.12**. Setting `requires-python = ">=3.14"` in `pyproject.toml` causes `pip` installation failures.
213
+ - **Mandatory Fix:** Ensure all Python projects set `requires-python = ">=3.10"`.
214
+
215
+ ### 5. Non-Root File Permissions (`User 1000`)
216
+ - **Problem:** Hugging Face executes containers strictly as User ID `1000` (`user`). System services expecting root access fail to start.
217
+ - **Mandatory Fix:** Include `chown -R user:user /app /etc/caddy /var/log/supervisor /var/lib/caddy /var/log/caddy` in `Dockerfile` before switching to `USER user`.
218
+
219
+ ### 6. Ephemeral Filesystem Limitation
220
+ - **Warning:** Storage in free Hugging Face Spaces is **ephemeral**. Any local files, database files (e.g., SQLite), or authentication keys (e.g., Baileys WhatsApp sessions) written to disk will be wiped when the container restarts.
221
+ - **Mandatory Requirement:** All persistent application state must be stored in external managed databases (e.g., Supabase, Neon PostgreSQL, or Redis).
222
+
223
+ ### 7. Container Sleep Prevention
224
+ - **Mechanism:** Hugging Face Space containers go to sleep after 15–45 minutes of HTTP inactivity.
225
+ - **Mandatory Requirement:** An external monitoring service (Better Stack, UptimeRobot) must issue an HTTP `GET` ping to `https://tom716-set-api.hf.space/status` every **5 minutes**.