mirror of
https://github.com/ipnet-mesh/meshcore-hub.git
synced 2026-03-28 17:42:56 +01:00
Compare commits
346 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
92ff1ab306 | ||
|
|
0e2a24caa6 | ||
|
|
ff36a991af | ||
|
|
fa1a2ecc17 | ||
|
|
9099ffb0cb | ||
|
|
f8219b4626 | ||
|
|
27b78d6904 | ||
|
|
d4c3e127a2 | ||
|
|
92e9ccdbfa | ||
|
|
29b5820ed1 | ||
|
|
889aa32e3a | ||
|
|
3c3873951d | ||
|
|
4b58160f31 | ||
|
|
a32255e110 | ||
|
|
59a1898824 | ||
|
|
9256f8375d | ||
|
|
e9b25c1ca7 | ||
|
|
749bed6d5b | ||
|
|
97539cb960 | ||
|
|
c418959e5d | ||
|
|
14fac89f49 | ||
|
|
8201be5a39 | ||
|
|
17fa2f1005 | ||
|
|
535186efb1 | ||
|
|
fa1db5e709 | ||
|
|
840b8636a2 | ||
|
|
cb305083e7 | ||
|
|
d475a12292 | ||
|
|
53f0ce7225 | ||
|
|
90268e9b98 | ||
|
|
18edcfe9bf | ||
|
|
2a380f88b4 | ||
|
|
c22274c4e5 | ||
|
|
54449aa5fb | ||
|
|
15556c3eb9 | ||
|
|
6a66eab663 | ||
|
|
2f40b4a730 | ||
|
|
3eff7f03db | ||
|
|
905ea0190b | ||
|
|
86cc7edca3 | ||
|
|
eb3f8508b7 | ||
|
|
74a34fdcba | ||
|
|
175fc8c524 | ||
|
|
2a153a5239 | ||
|
|
de85e0cd7a | ||
|
|
5a20da3afa | ||
|
|
dcd33711db | ||
|
|
a8cb20fea5 | ||
|
|
3ac5667d7a | ||
|
|
c8c53b25bd | ||
|
|
e4a1b005dc | ||
|
|
27adc6e2de | ||
|
|
835fb1c094 | ||
|
|
d7a351a803 | ||
|
|
317627833c | ||
|
|
f4514d1150 | ||
|
|
7be5f6afdf | ||
|
|
54695ab9e2 | ||
|
|
189eb3a139 | ||
|
|
96ca6190db | ||
|
|
baf08a9545 | ||
|
|
1d3e649ce0 | ||
|
|
45abc66816 | ||
|
|
9c8eb27455 | ||
|
|
e6c6d4aecc | ||
|
|
19bb06953e | ||
|
|
1f55d912ea | ||
|
|
5272a72647 | ||
|
|
b2f8e18f13 | ||
|
|
a15e91c754 | ||
|
|
85129e528e | ||
|
|
127cd7adf6 | ||
|
|
91b3f1926f | ||
|
|
3ef94a21df | ||
|
|
19e724fcc8 | ||
|
|
7b7910b42e | ||
|
|
c711a0eb9b | ||
|
|
dcd7ed248d | ||
|
|
b0ea6bcc0e | ||
|
|
7ef41a3671 | ||
|
|
a7611dd8d4 | ||
|
|
8f907edce6 | ||
|
|
95d1b260ab | ||
|
|
fba2656268 | ||
|
|
69adca09e3 | ||
|
|
9c2a0527ff | ||
|
|
c0db5b1da5 | ||
|
|
77dcbb77ba | ||
|
|
5bf0265fd9 | ||
|
|
1adef40fdc | ||
|
|
c9beb7e801 | ||
|
|
cd14c23cf2 | ||
|
|
708bfd1811 | ||
|
|
afdc76e546 | ||
|
|
e07b9ee2ab | ||
|
|
00851bfcaa | ||
|
|
6a035e41c0 | ||
|
|
2ffc78fda2 | ||
|
|
3f341a4031 | ||
|
|
1ea729bd51 | ||
|
|
d329f67ba8 | ||
|
|
c42a2deffb | ||
|
|
dfa4157c9c | ||
|
|
b52fd32106 | ||
|
|
4bbf43a078 | ||
|
|
deae9c67fe | ||
|
|
ceee27a3af | ||
|
|
f478096bc2 | ||
|
|
8ae94a7763 | ||
|
|
fb6cc6f5a9 | ||
|
|
a98b295618 | ||
|
|
da512c0d9f | ||
|
|
652486aa15 | ||
|
|
947c12bfe1 | ||
|
|
e80cd3a83c | ||
|
|
70ecb5e4da | ||
|
|
565e0ffc7b | ||
|
|
bdc3b867ea | ||
|
|
48786a18f9 | ||
|
|
706c32ae01 | ||
|
|
bafc16d746 | ||
|
|
9b09e32d41 | ||
|
|
2b9f83e55e | ||
|
|
75c1966385 | ||
|
|
3089ff46a8 | ||
|
|
f1bceb5780 | ||
|
|
caf88bdba1 | ||
|
|
9eb1acfc02 | ||
|
|
62e0568646 | ||
|
|
b4da93e4f0 | ||
|
|
981402f7aa | ||
|
|
76717179c2 | ||
|
|
f42987347e | ||
|
|
25831f14e6 | ||
|
|
0e6cbc8094 | ||
|
|
76630f0bb0 | ||
|
|
8fbac2cbd6 | ||
|
|
fcac5e01dc | ||
|
|
b6f3b2d864 | ||
|
|
7de6520ae7 | ||
|
|
5b8b2eda10 | ||
|
|
042a1b04fa | ||
|
|
5832cbf53a | ||
|
|
c540e15432 | ||
|
|
6b1b277c6c | ||
|
|
470c374f11 | ||
|
|
71859b2168 | ||
|
|
3d7ed53df3 | ||
|
|
ceaef9178a | ||
|
|
5ccb077188 | ||
|
|
8f660d6b94 | ||
|
|
6e40be6487 | ||
|
|
d79e29bc0a | ||
|
|
2758cf4dd5 | ||
|
|
f37e993ede | ||
|
|
b18b3c9aa4 | ||
|
|
9d99262401 | ||
|
|
adfe5bc503 | ||
|
|
deaab9b9de | ||
|
|
95636ef580 | ||
|
|
5831592f88 | ||
|
|
bc7bff8b82 | ||
|
|
9445d2150c | ||
|
|
3e9f478a65 | ||
|
|
6656bd8214 | ||
|
|
0f50bf4a41 | ||
|
|
99206f7467 | ||
|
|
3a89daa9c0 | ||
|
|
86c5ff8f1c | ||
|
|
59d0edc96f | ||
|
|
b01611e0e8 | ||
|
|
1e077f50f7 | ||
|
|
09146a2e94 | ||
|
|
56487597b7 | ||
|
|
de968f397d | ||
|
|
3ca5284c11 | ||
|
|
75d7e5bdfa | ||
|
|
927fcd6efb | ||
|
|
3132d296bb | ||
|
|
96e4215c29 | ||
|
|
fd3c3171ce | ||
|
|
345ffd219b | ||
|
|
9661b22390 | ||
|
|
31aa48c9a0 | ||
|
|
1a3649b3be | ||
|
|
33649a065b | ||
|
|
fd582bda35 | ||
|
|
c42b26c8f3 | ||
|
|
d52163949a | ||
|
|
ca101583f0 | ||
|
|
4af0f2ea80 | ||
|
|
0b3ac64845 | ||
|
|
3c7a8981ee | ||
|
|
238e28ae41 | ||
|
|
68d5049963 | ||
|
|
624fa458ac | ||
|
|
309d575fc0 | ||
|
|
f7b4df13a7 | ||
|
|
13bae5c8d7 | ||
|
|
8a6b4d8e88 | ||
|
|
b67e1b5b2b | ||
|
|
d4e3dc0399 | ||
|
|
7f0adfa6a7 | ||
|
|
94b03b49d9 | ||
|
|
20d75fe041 | ||
|
|
307f3935e0 | ||
|
|
6901bafb02 | ||
|
|
e595dc2b27 | ||
|
|
ed2cf09ff3 | ||
|
|
bec736a894 | ||
|
|
1457360703 | ||
|
|
d8a0f2abb8 | ||
|
|
367f838371 | ||
|
|
741dd3ce84 | ||
|
|
0a12f389df | ||
|
|
8240c2fd57 | ||
|
|
38f7fe291e | ||
|
|
e4087efbf0 | ||
|
|
3051984fb9 | ||
|
|
eea2c90ea4 | ||
|
|
d52c23fc29 | ||
|
|
a1fb71ce65 | ||
|
|
6a5549081f | ||
|
|
68e24ee886 | ||
|
|
61d6b6287e | ||
|
|
7007c84577 | ||
|
|
fd928d9fea | ||
|
|
68b6aa85cd | ||
|
|
abbc07edb3 | ||
|
|
b42add310e | ||
|
|
98a5526e80 | ||
|
|
db86b3198e | ||
|
|
cd4f0b91dc | ||
|
|
a290db0491 | ||
|
|
92b0b883e6 | ||
|
|
9e621c0029 | ||
|
|
a251f3a09f | ||
|
|
0fdedfe5ba | ||
|
|
243a3e8521 | ||
|
|
b24a6f0894 | ||
|
|
57f51c741c | ||
|
|
65b8418af4 | ||
|
|
89ceee8741 | ||
|
|
64ec1a7135 | ||
|
|
3d632a94b1 | ||
|
|
fbd29ff78e | ||
|
|
86bff07f7d | ||
|
|
3abd5ce3ea | ||
|
|
0bf2086f16 | ||
|
|
40dc6647e9 | ||
|
|
f4e95a254e | ||
|
|
ba43be9e62 | ||
|
|
5b22ab29cf | ||
|
|
278d102064 | ||
|
|
f0cee14bd8 | ||
|
|
5ff8d16bcb | ||
|
|
e8a60d4869 | ||
|
|
84b8614e29 | ||
|
|
3bc47a33bc | ||
|
|
3ae8ecbd70 | ||
|
|
38164380af | ||
|
|
dc3c771c76 | ||
|
|
deb307c6ae | ||
|
|
b8c8284643 | ||
|
|
d310a119ed | ||
|
|
2b307679c9 | ||
|
|
6f7521951f | ||
|
|
ab498292b2 | ||
|
|
df2b9ea432 | ||
|
|
55443376be | ||
|
|
ed7a46b1a7 | ||
|
|
c2eef3db50 | ||
|
|
4916ea0cea | ||
|
|
e3fc7e4f07 | ||
|
|
b656bfda21 | ||
|
|
fb7201dc2d | ||
|
|
74346d9c82 | ||
|
|
beb471fcd8 | ||
|
|
8597052bf7 | ||
|
|
f85768f661 | ||
|
|
79bb4a4250 | ||
|
|
714c3cbbd2 | ||
|
|
f0531c9e40 | ||
|
|
dd0b4c73c5 | ||
|
|
78a086e1ea | ||
|
|
9cd1d50bf6 | ||
|
|
733342a9ec | ||
|
|
d715e4e4f0 | ||
|
|
2ea04deb7e | ||
|
|
6e3b86a1ad | ||
|
|
b807932ca3 | ||
|
|
c80986fe67 | ||
|
|
3a060f77cc | ||
|
|
7461cf6dc1 | ||
|
|
23f6c290c9 | ||
|
|
1ae1736391 | ||
|
|
a4b13d3456 | ||
|
|
0016edbdac | ||
|
|
0b8fc6e707 | ||
|
|
d1181ae4f9 | ||
|
|
6b41e64b26 | ||
|
|
995b066b0d | ||
|
|
0d14ed0ccc | ||
|
|
e3ce1258a8 | ||
|
|
087a3c4c43 | ||
|
|
5077178a6d | ||
|
|
a44d38dad6 | ||
|
|
3469278fba | ||
|
|
89c81630c9 | ||
|
|
ab4a5886db | ||
|
|
ec7082e01a | ||
|
|
b4e7d45cf6 | ||
|
|
864494c3a8 | ||
|
|
84e83a3384 | ||
|
|
796e303665 | ||
|
|
a5d8d586e1 | ||
|
|
26239fe11f | ||
|
|
0e50a9d3b0 | ||
|
|
9b7d8cc31b | ||
|
|
d7152a5359 | ||
|
|
a1cc4388ae | ||
|
|
bb0b9f05ec | ||
|
|
fe744c7c0c | ||
|
|
cf4e82503a | ||
|
|
d6346fdfde | ||
|
|
cf2c3350cc | ||
|
|
110c701787 | ||
|
|
fc0dc1a448 | ||
|
|
d283a8c79b | ||
|
|
f129a4e0f3 | ||
|
|
90f6a68b9b | ||
|
|
6cf3152ef9 | ||
|
|
058a6e2c95 | ||
|
|
acccdfedba | ||
|
|
83f3157e8b | ||
|
|
c564a61cf7 | ||
|
|
bbe8491ff1 | ||
|
|
1d6a9638a1 | ||
|
|
cf633f9f44 | ||
|
|
102e40a395 | ||
|
|
241902685d | ||
|
|
2f2ae30c89 | ||
|
|
fff04e4b99 | ||
|
|
df05c3a462 | ||
|
|
e2d865f200 | ||
|
|
fa335bdb14 |
103
.agentmap.yaml
Normal file
103
.agentmap.yaml
Normal file
@@ -0,0 +1,103 @@
|
||||
# MeshCore Hub — codebase orientation map
|
||||
# See: https://github.com/anthropics/agentmap
|
||||
|
||||
meta:
|
||||
project: meshcore-hub
|
||||
version: 1
|
||||
updated: "2026-02-27"
|
||||
stack:
|
||||
- python 3.13
|
||||
- fastapi
|
||||
- sqlalchemy (async)
|
||||
- paho-mqtt
|
||||
- click
|
||||
- lit-html SPA
|
||||
- tailwind + daisyui
|
||||
- sqlite
|
||||
|
||||
tasks:
|
||||
install: "pip install -e '.[dev]'"
|
||||
test: "pytest"
|
||||
run: "meshcore-hub api --reload"
|
||||
lint: "pre-commit run --all-files"
|
||||
|
||||
tree:
|
||||
src/meshcore_hub/:
|
||||
__main__.py: "Click CLI entry point, registers subcommands"
|
||||
common/:
|
||||
config.py: "pydantic-settings, all env vars [config]"
|
||||
database.py: "async SQLAlchemy session management"
|
||||
mqtt.py: "MQTT client helpers"
|
||||
i18n.py: "translation loader, t() function"
|
||||
models/:
|
||||
base.py: "Base, UUIDMixin, TimestampMixin"
|
||||
node.py: null
|
||||
member.py: null
|
||||
advertisement.py: null
|
||||
message.py: null
|
||||
telemetry.py: null
|
||||
node_tag.py: null
|
||||
schemas/:
|
||||
events.py: "inbound MQTT event schemas"
|
||||
commands.py: "outbound command schemas"
|
||||
nodes.py: "API request/response schemas"
|
||||
members.py: null
|
||||
messages.py: null
|
||||
interface/:
|
||||
receiver.py: "reads device events, publishes to MQTT"
|
||||
sender.py: "subscribes MQTT commands, writes to device"
|
||||
device.py: "meshcore library wrapper"
|
||||
mock_device.py: "fake device for testing"
|
||||
collector/:
|
||||
subscriber.py: "MQTT subscriber, routes events to handlers"
|
||||
handlers/: "per-event-type DB persistence"
|
||||
cleanup.py: "data retention and node cleanup"
|
||||
webhook.py: "forward events to HTTP endpoints"
|
||||
tag_import.py: "seed node tags from YAML"
|
||||
member_import.py: "seed members from YAML"
|
||||
api/:
|
||||
app.py: "FastAPI app factory"
|
||||
auth.py: "API key authentication"
|
||||
dependencies.py: "DI for db session and auth"
|
||||
metrics.py: "Prometheus /metrics endpoint"
|
||||
routes/: "REST endpoints per resource"
|
||||
web/:
|
||||
app.py: "FastAPI app factory, SPA shell"
|
||||
pages.py: "custom markdown page loader"
|
||||
middleware.py: null
|
||||
templates/:
|
||||
spa.html: "single Jinja2 shell template"
|
||||
static/js/spa/:
|
||||
app.js: "SPA entry, route registration"
|
||||
router.js: "History API client-side router"
|
||||
api.js: "fetch wrapper for API calls"
|
||||
components.js: "shared lit-html helpers, t() re-export"
|
||||
icons.js: "SVG icon functions"
|
||||
pages/: "lazy-loaded page modules"
|
||||
alembic/: "DB migrations"
|
||||
etc/:
|
||||
prometheus/: "Prometheus scrape + alert rules"
|
||||
alertmanager/: null
|
||||
seed/: "YAML seed data (node_tags, members)"
|
||||
tests/:
|
||||
|
||||
key_symbols:
|
||||
- src/meshcore_hub/__main__.py::cli — Click root group [entry-point]
|
||||
- src/meshcore_hub/common/config.py::CommonSettings — shared env config base
|
||||
- src/meshcore_hub/common/database.py::DatabaseManager — async session factory
|
||||
- src/meshcore_hub/common/models/base.py::Base — declarative base for all models
|
||||
- src/meshcore_hub/api/app.py::create_app — API FastAPI factory
|
||||
- src/meshcore_hub/web/app.py::create_app — Web FastAPI factory
|
||||
- src/meshcore_hub/api/auth.py::require_read — read-key auth dependency
|
||||
- src/meshcore_hub/api/auth.py::require_admin — admin-key auth dependency
|
||||
- src/meshcore_hub/collector/subscriber.py::MQTTSubscriber — event ingestion loop
|
||||
- src/meshcore_hub/interface/receiver.py::Receiver — device→MQTT bridge
|
||||
- src/meshcore_hub/interface/sender.py::Sender — MQTT→device bridge
|
||||
|
||||
conventions:
|
||||
- four Click subcommands: interface, collector, api, web
|
||||
- "MQTT topic pattern: {prefix}/{pubkey}/event/{name} and .../command/{name}"
|
||||
- env config via pydantic-settings, no manual os.environ
|
||||
- web SPA: ES modules + lit-html, pages export async render()
|
||||
- i18n via t() with JSON locale files in static/locales/
|
||||
- node tags are freeform key-value pairs, standard keys in AGENTS.md
|
||||
60
.claude/commands/label-issue.md
Normal file
60
.claude/commands/label-issue.md
Normal file
@@ -0,0 +1,60 @@
|
||||
---
|
||||
allowed-tools: Bash(gh label list:*),Bash(gh issue view:*),Bash(gh issue edit:*),Bash(gh search:*)
|
||||
description: Apply labels to GitHub issues
|
||||
---
|
||||
|
||||
You're an issue triage assistant for GitHub issues. Your task is to analyze the issue and select appropriate labels from the provided list.
|
||||
|
||||
IMPORTANT: Don't post any comments or messages to the issue. Your only action should be to apply labels.
|
||||
|
||||
Issue Information:
|
||||
|
||||
- REPO: ${{ github.repository }}
|
||||
- ISSUE_NUMBER: ${{ github.event.issue.number }}
|
||||
|
||||
TASK OVERVIEW:
|
||||
|
||||
1. First, fetch the list of labels available in this repository by running: `gh label list`. Run exactly this command with nothing else.
|
||||
|
||||
2. Next, use gh commands to get context about the issue:
|
||||
|
||||
- Use `gh issue view ${{ github.event.issue.number }}` to retrieve the current issue's details
|
||||
- Use `gh search issues` to find similar issues that might provide context for proper categorization
|
||||
- You have access to these Bash commands:
|
||||
- Bash(gh label list:\*) - to get available labels
|
||||
- Bash(gh issue view:\*) - to view issue details
|
||||
- Bash(gh issue edit:\*) - to apply labels to the issue
|
||||
- Bash(gh search:\*) - to search for similar issues
|
||||
|
||||
3. Analyze the issue content, considering:
|
||||
|
||||
- The issue title and description
|
||||
- The type of issue (bug report, feature request, question, etc.)
|
||||
- Technical areas mentioned
|
||||
- Severity or priority indicators
|
||||
- User impact
|
||||
- Components affected
|
||||
|
||||
4. Select appropriate labels from the available labels list provided above:
|
||||
|
||||
- Choose labels that accurately reflect the issue's nature
|
||||
- Be specific but comprehensive
|
||||
- IMPORTANT: Add a priority label (P1, P2, or P3) based on the label descriptions from gh label list
|
||||
- Consider platform labels (android, ios) if applicable
|
||||
- If you find similar issues using gh search, consider using a "duplicate" label if appropriate. Only do so if the issue is a duplicate of another OPEN issue.
|
||||
|
||||
5. Apply the selected labels:
|
||||
- Use `gh issue edit` to apply your selected labels
|
||||
- DO NOT post any comments explaining your decision
|
||||
- DO NOT communicate directly with users
|
||||
- If no labels are clearly applicable, do not apply any labels
|
||||
|
||||
IMPORTANT GUIDELINES:
|
||||
|
||||
- Be thorough in your analysis
|
||||
- Only select labels from the provided list above
|
||||
- DO NOT post any comments to the issue
|
||||
- Your ONLY action should be to apply labels using gh issue edit
|
||||
- It's okay to not add any labels if none are clearly applicable
|
||||
|
||||
---
|
||||
44
.claude/skills/documentation/SKILL.md
Normal file
44
.claude/skills/documentation/SKILL.md
Normal file
@@ -0,0 +1,44 @@
|
||||
---
|
||||
name: documentation
|
||||
description: Audit and update project documentation to accurately reflect the current codebase. Use when documentation may be outdated, after significant code changes, or when the user asks to review or update docs.
|
||||
---
|
||||
|
||||
# Documentation Audit
|
||||
|
||||
Audit and update all project documentation so it accurately reflects the current state of the codebase. Documentation must only describe features, options, configurations, and functionality that actually exist in the code.
|
||||
|
||||
## Files to Review
|
||||
|
||||
- **README.md** - Project overview, setup instructions, usage examples
|
||||
- **AGENTS.md** - AI coding assistant guidelines, project structure, conventions
|
||||
- **.env.example** - Example environment variables
|
||||
|
||||
Also check for substantial comments or inline instructions within the codebase that may be outdated.
|
||||
|
||||
## Process
|
||||
|
||||
1. **Read all documentation files** listed above in full.
|
||||
|
||||
2. **Cross-reference against the codebase.** For every documented item (features, env vars, CLI commands, routes, models, directory paths, conventions), search the code to verify:
|
||||
- It actually exists.
|
||||
- Its described behavior matches the implementation.
|
||||
- File paths and directory structures are accurate.
|
||||
|
||||
3. **Identify and fix discrepancies:**
|
||||
- **Version updates** — ensure documentation reflects any new/updated/removed versions. Check .python-version, pyproject.toml, etc.
|
||||
- **Stale/legacy content** — documented but no longer in the code. Remove it.
|
||||
- **Missing content** — exists in the code but not documented. Add it.
|
||||
- **Inaccurate descriptions** — documented behavior doesn't match implementation. Correct it.
|
||||
|
||||
4. **Apply updates** to each file. Preserve existing style and structure.
|
||||
|
||||
5. **Verify consistency** across all documentation files — they must not contradict each other.
|
||||
|
||||
## Rules
|
||||
|
||||
- Do NOT invent features or options that don't exist in the code.
|
||||
- Do NOT remove documentation for features that DO exist.
|
||||
- Do NOT change the fundamental structure or style of the docs.
|
||||
- Do NOT modify CLAUDE.md.
|
||||
- Focus on accuracy, not cosmetic changes.
|
||||
- When in doubt, check the source code.
|
||||
49
.claude/skills/git-branch/SKILL.md
Normal file
49
.claude/skills/git-branch/SKILL.md
Normal file
@@ -0,0 +1,49 @@
|
||||
---
|
||||
name: git-branch
|
||||
description: Create a new branch from latest main with the project's naming convention (feat/fix/chore). Use when starting new work on a feature, bug fix, or chore.
|
||||
---
|
||||
|
||||
# Git Branch
|
||||
|
||||
Create a new branch from the latest `main` branch using the project's naming convention.
|
||||
|
||||
## Arguments
|
||||
|
||||
The user may provide arguments in the format: `<type>/<description>`
|
||||
|
||||
- `type` — one of `feat`, `fix`, or `chore`
|
||||
- `description` — short kebab-case description (e.g., `add-map-clustering`)
|
||||
|
||||
If not provided, ask the user for the branch type and description.
|
||||
|
||||
## Process
|
||||
|
||||
1. **Fetch latest main:**
|
||||
|
||||
```bash
|
||||
git fetch origin main
|
||||
```
|
||||
|
||||
2. **Determine branch name:**
|
||||
|
||||
- If the user provided arguments (e.g., `/git-branch feat/add-map-clustering`), use them directly.
|
||||
- Otherwise, ask the user for:
|
||||
- **Branch type**: `feat`, `fix`, or `chore`
|
||||
- **Short description**: a brief kebab-case slug describing the work
|
||||
- Construct the branch name as `{type}/{slug}` (e.g., `feat/add-map-clustering`).
|
||||
|
||||
3. **Create and switch to the new branch:**
|
||||
|
||||
```bash
|
||||
git checkout -b {branch_name} origin/main
|
||||
```
|
||||
|
||||
4. **Confirm** by reporting the new branch name to the user.
|
||||
|
||||
## Rules
|
||||
|
||||
- Branch names MUST follow the `{type}/{slug}` convention.
|
||||
- Valid types are `feat`, `fix`, and `chore` only.
|
||||
- The slug MUST be kebab-case (lowercase, hyphens, no spaces or underscores).
|
||||
- Always branch from `origin/main`, never from the current branch.
|
||||
- Do NOT push the branch — just create it locally.
|
||||
94
.claude/skills/git-pr/SKILL.md
Normal file
94
.claude/skills/git-pr/SKILL.md
Normal file
@@ -0,0 +1,94 @@
|
||||
---
|
||||
name: git-pr
|
||||
description: Create a pull request to main from the current branch. Runs quality checks, commits changes, pushes, and opens a PR via gh CLI. Use when ready to submit work for review.
|
||||
---
|
||||
|
||||
# Git PR
|
||||
|
||||
Create a pull request to `main` from the current feature branch.
|
||||
|
||||
## Process
|
||||
|
||||
### Phase 1: Pre-flight Checks
|
||||
|
||||
1. **Verify branch:**
|
||||
|
||||
```bash
|
||||
git branch --show-current
|
||||
```
|
||||
|
||||
- The current branch must NOT be `main`. If on `main`, tell the user to create a feature branch first (e.g., `/git-branch`).
|
||||
|
||||
2. **Check for uncommitted changes:**
|
||||
|
||||
```bash
|
||||
git status
|
||||
```
|
||||
|
||||
- If there are uncommitted changes, ask the user for a commit message and commit them using the `/git-commit` skill conventions (no Claude authoring details).
|
||||
|
||||
### Phase 2: Quality Checks
|
||||
|
||||
1. **Determine changed components** by comparing against `main`:
|
||||
|
||||
```bash
|
||||
git diff --name-only main...HEAD
|
||||
```
|
||||
|
||||
2. **Run targeted tests** based on changed files:
|
||||
- `tests/test_web/` for web-only changes (templates, static JS, web routes)
|
||||
- `tests/test_api/` for API changes
|
||||
- `tests/test_collector/` for collector changes
|
||||
- `tests/test_interface/` for interface/sender/receiver changes
|
||||
- `tests/test_common/` for common models/schemas/config changes
|
||||
- Run the full `pytest` if changes span multiple components
|
||||
|
||||
3. **Run pre-commit checks:**
|
||||
|
||||
```bash
|
||||
pre-commit run --all-files
|
||||
```
|
||||
|
||||
- If checks fail and auto-fix files, commit the fixes and re-run until clean.
|
||||
|
||||
4. If tests or checks fail and cannot be auto-fixed, report the issues to the user and stop.
|
||||
|
||||
### Phase 3: Push and Create PR
|
||||
|
||||
1. **Push the branch to origin:**
|
||||
|
||||
```bash
|
||||
git push -u origin HEAD
|
||||
```
|
||||
|
||||
2. **Generate PR content:**
|
||||
- **Title**: Derive from the branch name. Convert `feat/add-map-clustering` to `Add map clustering`, `fix/login-error` to `Fix login error`, etc. Keep under 70 characters.
|
||||
- **Body**: Generate a summary from the commit history:
|
||||
|
||||
```bash
|
||||
git log main..HEAD --oneline
|
||||
```
|
||||
|
||||
3. **Create the PR:**
|
||||
|
||||
```bash
|
||||
gh pr create --title "{title}" --body "$(cat <<'EOF'
|
||||
## Summary
|
||||
{bullet points summarizing the changes}
|
||||
|
||||
## Test plan
|
||||
{checklist of testing steps}
|
||||
EOF
|
||||
)"
|
||||
```
|
||||
|
||||
4. **Return the PR URL** to the user.
|
||||
|
||||
## Rules
|
||||
|
||||
- Do NOT create a PR from `main`.
|
||||
- Do NOT skip quality checks — tests and pre-commit must pass.
|
||||
- Do NOT force-push.
|
||||
- Always target `main` as the base branch.
|
||||
- Keep the PR title concise (under 70 characters).
|
||||
- If quality checks fail, fix issues or report to the user — do NOT create the PR with failing checks.
|
||||
66
.claude/skills/quality/SKILL.md
Normal file
66
.claude/skills/quality/SKILL.md
Normal file
@@ -0,0 +1,66 @@
|
||||
---
|
||||
name: quality
|
||||
description: Run the full test suite, pre-commit checks, and re-run tests to ensure code quality. Fixes any issues found. Use after code changes, before commits, or when the user asks to check quality.
|
||||
---
|
||||
|
||||
# Quality Check
|
||||
|
||||
Run the full quality pipeline: tests, pre-commit checks, and a verification test run. Fix any issues discovered at each stage.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Before running checks, ensure the environment is ready:
|
||||
|
||||
1. Check for `.venv` directory — create with `python -m venv .venv` if missing.
|
||||
2. Activate the virtual environment: `source .venv/bin/activate`
|
||||
3. Install dependencies: `pip install -e ".[dev]"`
|
||||
|
||||
## Process
|
||||
|
||||
### Phase 1: Initial Test Run
|
||||
|
||||
Run the full test suite to establish a baseline:
|
||||
|
||||
```bash
|
||||
pytest
|
||||
```
|
||||
|
||||
- If tests **pass**, proceed to Phase 2.
|
||||
- If tests **fail**, investigate and fix the failures before continuing. Re-run the failing tests to confirm fixes. Then proceed to Phase 2.
|
||||
|
||||
### Phase 2: Pre-commit Checks
|
||||
|
||||
Run all pre-commit hooks against the entire codebase:
|
||||
|
||||
```bash
|
||||
pre-commit run --all-files
|
||||
```
|
||||
|
||||
- If all checks **pass**, proceed to Phase 3.
|
||||
- If checks **fail**:
|
||||
- Many hooks (black, trailing whitespace, end-of-file) auto-fix issues. Re-run `pre-commit run --all-files` to confirm auto-fixes resolved the issues.
|
||||
- For remaining failures (flake8, mypy, etc.), investigate and fix manually.
|
||||
- Re-run `pre-commit run --all-files` until all checks pass.
|
||||
- Then proceed to Phase 3.
|
||||
|
||||
### Phase 3: Verification Test Run
|
||||
|
||||
Run the full test suite again to ensure pre-commit fixes (formatting, import sorting, etc.) haven't broken any functionality:
|
||||
|
||||
```bash
|
||||
pytest
|
||||
```
|
||||
|
||||
- If tests **pass**, the quality check is complete.
|
||||
- If tests **fail**, the pre-commit fixes introduced a regression. Investigate and fix, then re-run both `pre-commit run --all-files` and `pytest` until both pass cleanly.
|
||||
|
||||
## Rules
|
||||
|
||||
- Always run the FULL test suite (`pytest`), not targeted tests.
|
||||
- Always run pre-commit against ALL files (`--all-files`).
|
||||
- Do NOT skip or ignore failing tests — investigate and fix them.
|
||||
- Do NOT skip or ignore pre-commit failures — investigate and fix them.
|
||||
- Do NOT modify test assertions to make tests pass unless the test is genuinely wrong.
|
||||
- Do NOT disable pre-commit hooks or add noqa/type:ignore unless truly justified.
|
||||
- Fix root causes, not symptoms.
|
||||
- If a fix requires changes outside the scope of a simple quality fix (e.g., a design change), report it to the user rather than making the change silently.
|
||||
114
.claude/skills/release/SKILL.md
Normal file
114
.claude/skills/release/SKILL.md
Normal file
@@ -0,0 +1,114 @@
|
||||
---
|
||||
name: release
|
||||
description: Full release workflow — quality gate, semantic version tag, push, and GitHub release. Use when ready to cut a new release from main.
|
||||
---
|
||||
|
||||
# Release
|
||||
|
||||
Run the full release workflow: quality checks, version tagging, push, and GitHub release creation.
|
||||
|
||||
## Arguments
|
||||
|
||||
The user may optionally provide a version number (e.g., `/release 1.2.0`). If not provided, one will be suggested based on commit history.
|
||||
|
||||
## Process
|
||||
|
||||
### Phase 1: Pre-flight Checks
|
||||
|
||||
1. **Verify on `main` branch:**
|
||||
|
||||
```bash
|
||||
git branch --show-current
|
||||
```
|
||||
|
||||
- Must be on `main`. If not, tell the user to switch to `main` first.
|
||||
|
||||
2. **Verify working tree is clean:**
|
||||
|
||||
```bash
|
||||
git status --porcelain
|
||||
```
|
||||
|
||||
- If there are uncommitted changes, tell the user to commit or stash them first.
|
||||
|
||||
3. **Pull latest:**
|
||||
|
||||
```bash
|
||||
git pull origin main
|
||||
```
|
||||
|
||||
### Phase 2: Quality Gate
|
||||
|
||||
1. **Run full test suite:**
|
||||
|
||||
```bash
|
||||
pytest
|
||||
```
|
||||
|
||||
2. **Run pre-commit checks:**
|
||||
|
||||
```bash
|
||||
pre-commit run --all-files
|
||||
```
|
||||
|
||||
3. If either fails, report the issues and stop. Do NOT proceed with a release that has failing checks.
|
||||
|
||||
### Phase 3: Determine Version
|
||||
|
||||
1. **Get the latest tag:**
|
||||
|
||||
```bash
|
||||
git describe --tags --abbrev=0 2>/dev/null || echo "none"
|
||||
```
|
||||
|
||||
2. **List commits since last tag:**
|
||||
|
||||
```bash
|
||||
git log {last_tag}..HEAD --oneline
|
||||
```
|
||||
|
||||
If no previous tag exists, list the last 20 commits:
|
||||
|
||||
```bash
|
||||
git log --oneline -20
|
||||
```
|
||||
|
||||
3. **Determine next version:**
|
||||
- If the user provided a version, use it.
|
||||
- Otherwise, suggest a version based on commit prefixes:
|
||||
- Any commit starting with `feat` or `Add` → **minor** bump
|
||||
- Only `fix` or `Fix` commits → **patch** bump
|
||||
- If no previous tag, suggest `0.1.0`
|
||||
- Present the suggestion and ask the user to confirm or provide a different version.
|
||||
|
||||
### Phase 4: Tag and Release
|
||||
|
||||
1. **Create annotated tag:**
|
||||
|
||||
```bash
|
||||
git tag -a v{version} -m "Release v{version}"
|
||||
```
|
||||
|
||||
2. **Push tag to origin:**
|
||||
|
||||
```bash
|
||||
git push origin v{version}
|
||||
```
|
||||
|
||||
3. **Create GitHub release:**
|
||||
|
||||
```bash
|
||||
gh release create v{version} --title "v{version}" --generate-notes
|
||||
```
|
||||
|
||||
4. **Report** the release URL to the user.
|
||||
|
||||
## Rules
|
||||
|
||||
- MUST be on `main` branch with a clean working tree.
|
||||
- MUST pass all quality checks before tagging.
|
||||
- Tags MUST follow the `v{major}.{minor}.{patch}` format (e.g., `v1.2.0`).
|
||||
- Always create an annotated tag, not a lightweight tag.
|
||||
- Always confirm the version with the user before tagging.
|
||||
- Do NOT skip quality checks under any circumstances.
|
||||
- Do NOT force-push tags.
|
||||
337
.env.example
337
.env.example
@@ -1,110 +1,170 @@
|
||||
# MeshCore Hub - Docker Compose Environment Configuration
|
||||
# MeshCore Hub - Environment Configuration
|
||||
# Copy this file to .env and customize values
|
||||
#
|
||||
# Configuration is grouped by service. Most deployments only need:
|
||||
# - Common Settings (always required)
|
||||
# - MQTT Settings (always required)
|
||||
# - Interface Settings (for receiver/sender services)
|
||||
#
|
||||
# The Collector, API, and Web services typically run as a combined "core"
|
||||
# profile and share the same data directory.
|
||||
#
|
||||
# -----------------------------------------------------------------------------
|
||||
# QUICK START: Receiver/Sender Only
|
||||
# -----------------------------------------------------------------------------
|
||||
# For a minimal receiver or sender setup, you only need these settings:
|
||||
#
|
||||
# MQTT_HOST=your-mqtt-broker.example.com
|
||||
# MQTT_PORT=1883
|
||||
# MQTT_USERNAME=your_username
|
||||
# MQTT_PASSWORD=your_password
|
||||
# MQTT_TLS=false
|
||||
# SERIAL_PORT=/dev/ttyUSB0
|
||||
#
|
||||
# Serial ports are typically /dev/ttyUSB[0-9] or /dev/ttyACM[0-9] on Linux.
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
# ===================
|
||||
# Docker Image
|
||||
# ===================
|
||||
# =============================================================================
|
||||
# COMMON SETTINGS
|
||||
# =============================================================================
|
||||
# These settings apply to all services
|
||||
|
||||
# Leave empty to build from local Dockerfile, or set to use a pre-built image:
|
||||
# MESHCORE_IMAGE=ghcr.io/ipnet-mesh/meshcore-hub:latest
|
||||
# MESHCORE_IMAGE=ghcr.io/ipnet-mesh/meshcore-hub:main
|
||||
# MESHCORE_IMAGE=ghcr.io/ipnet-mesh/meshcore-hub:v1.0.0
|
||||
MESHCORE_IMAGE=
|
||||
# Docker image version tag to use
|
||||
# Options: latest, main, v1.0.0, etc.
|
||||
IMAGE_VERSION=latest
|
||||
|
||||
# ===================
|
||||
# Data Directory
|
||||
# ===================
|
||||
# Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
|
||||
LOG_LEVEL=INFO
|
||||
|
||||
# Base directory for all service data (collector DB, tags, members, etc.)
|
||||
# Base directory for runtime data (database, etc.)
|
||||
# Default: ./data (relative to docker-compose.yml location)
|
||||
# Inside containers this is mapped to /data
|
||||
#
|
||||
# Structure:
|
||||
# ${DATA_HOME}/
|
||||
# ├── collector/
|
||||
# │ ├── meshcore.db # SQLite database
|
||||
# │ └── tags.json # Node tags for import
|
||||
# └── web/
|
||||
# └── members.json # Network members list
|
||||
# └── collector/
|
||||
# └── meshcore.db # SQLite database
|
||||
DATA_HOME=./data
|
||||
|
||||
# ===================
|
||||
# Common Settings
|
||||
# ===================
|
||||
# Directory containing seed data files for import
|
||||
# Default: ./seed (relative to docker-compose.yml location)
|
||||
# Inside containers this is mapped to /seed
|
||||
#
|
||||
# Structure:
|
||||
# ${SEED_HOME}/
|
||||
# ├── node_tags.yaml # Node tags for import
|
||||
# └── members.yaml # Network members for import
|
||||
SEED_HOME=./seed
|
||||
|
||||
# Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
|
||||
LOG_LEVEL=INFO
|
||||
# =============================================================================
|
||||
# MQTT SETTINGS
|
||||
# =============================================================================
|
||||
# MQTT broker connection settings for interface, collector, and API services
|
||||
|
||||
# MQTT Broker Settings (internal use)
|
||||
# MQTT Broker host
|
||||
# When using the local MQTT broker (--profile mqtt), use "mqtt"
|
||||
# When using an external broker, set the hostname/IP
|
||||
MQTT_HOST=mqtt
|
||||
|
||||
# MQTT Broker port (default: 1883, or 8883 for TLS)
|
||||
MQTT_PORT=1883
|
||||
|
||||
# MQTT authentication (optional)
|
||||
MQTT_USERNAME=
|
||||
MQTT_PASSWORD=
|
||||
|
||||
# MQTT topic prefix for all MeshCore messages
|
||||
MQTT_PREFIX=meshcore
|
||||
|
||||
# External MQTT port mapping
|
||||
# Enable TLS/SSL for MQTT connection
|
||||
# When enabled, uses TLS with system CA certificates (e.g., for Let's Encrypt)
|
||||
MQTT_TLS=false
|
||||
|
||||
# MQTT transport protocol
|
||||
# Options: tcp, websockets
|
||||
MQTT_TRANSPORT=tcp
|
||||
|
||||
# MQTT WebSocket path (used only when MQTT_TRANSPORT=websockets)
|
||||
# Common values: /mqtt, /
|
||||
MQTT_WS_PATH=/mqtt
|
||||
|
||||
# External port mappings for local MQTT broker (--profile mqtt only)
|
||||
MQTT_EXTERNAL_PORT=1883
|
||||
MQTT_WS_PORT=9001
|
||||
|
||||
# ===================
|
||||
# Interface Settings
|
||||
# ===================
|
||||
# =============================================================================
|
||||
# INTERFACE SETTINGS (Receiver/Sender)
|
||||
# =============================================================================
|
||||
# Settings for the MeshCore device interface services
|
||||
|
||||
# Serial port for receiver device
|
||||
SERIAL_PORT=/dev/ttyUSB0
|
||||
|
||||
# Serial port for sender device (if separate)
|
||||
# Serial port for sender device (if using separate device)
|
||||
SERIAL_PORT_SENDER=/dev/ttyUSB1
|
||||
|
||||
# Baud rate for serial communication
|
||||
SERIAL_BAUD=115200
|
||||
|
||||
# Optional device/node name to set on startup
|
||||
# This name is broadcast to the mesh network in advertisements
|
||||
MESHCORE_DEVICE_NAME=
|
||||
|
||||
# Optional node address override (64-char hex string)
|
||||
# Only set if you need to override the device's public key
|
||||
NODE_ADDRESS=
|
||||
NODE_ADDRESS_SENDER=
|
||||
|
||||
# ===================
|
||||
# API Settings
|
||||
# ===================
|
||||
# -------------------
|
||||
# Contact Cleanup Settings (RECEIVER mode only)
|
||||
# -------------------
|
||||
# Automatic removal of stale contacts from the MeshCore companion node
|
||||
|
||||
# External API port
|
||||
API_PORT=8000
|
||||
# Enable automatic removal of stale contacts from companion node
|
||||
CONTACT_CLEANUP_ENABLED=true
|
||||
|
||||
# API Keys for authentication (generate secure keys for production!)
|
||||
# Example: openssl rand -hex 32
|
||||
API_READ_KEY=
|
||||
API_ADMIN_KEY=
|
||||
# Remove contacts not advertised for this many days
|
||||
CONTACT_CLEANUP_DAYS=7
|
||||
|
||||
# ===================
|
||||
# Web Dashboard Settings
|
||||
# ===================
|
||||
# =============================================================================
|
||||
# COLLECTOR SETTINGS
|
||||
# =============================================================================
|
||||
# The collector subscribes to MQTT events and stores them in the database
|
||||
|
||||
# External web port
|
||||
WEB_PORT=8080
|
||||
# Collector MQTT ingest mode
|
||||
# - native: expects <prefix>/<pubkey>/event/<event_name> topics
|
||||
# - letsmesh_upload: expects LetsMesh observer uploads on
|
||||
# <prefix>/<pubkey>/(packets|status|internal)
|
||||
COLLECTOR_INGEST_MODE=native
|
||||
|
||||
# Network Information (displayed on web dashboard)
|
||||
NETWORK_NAME=MeshCore Network
|
||||
NETWORK_CITY=
|
||||
NETWORK_COUNTRY=
|
||||
NETWORK_LOCATION=
|
||||
NETWORK_RADIO_CONFIG=
|
||||
NETWORK_CONTACT_EMAIL=
|
||||
NETWORK_CONTACT_DISCORD=
|
||||
# LetsMesh decoder support (used only when COLLECTOR_INGEST_MODE=letsmesh_upload)
|
||||
# Set to false to disable external packet decoding
|
||||
COLLECTOR_LETSMESH_DECODER_ENABLED=true
|
||||
|
||||
# Members file location (optional override)
|
||||
# Default: ${DATA_HOME}/web/members.json
|
||||
# Only set this if you want to use a different location
|
||||
# MEMBERS_FILE=/custom/path/to/members.json
|
||||
# Decoder command (must be available in container PATH)
|
||||
# Examples: meshcore-decoder, /usr/local/bin/meshcore-decoder, npx meshcore-decoder
|
||||
COLLECTOR_LETSMESH_DECODER_COMMAND=meshcore-decoder
|
||||
|
||||
# ===================
|
||||
# Optional: channel secret keys (comma or space separated) used to decrypt GroupText
|
||||
# packets. This supports unlimited keys.
|
||||
# Note: Public + #test keys are built into the collector code by default.
|
||||
# To show friendly channel names in the web feed, use label=hex (example: bot=ABCDEF...).
|
||||
# Without keys, encrypted packets cannot be shown as plaintext.
|
||||
# COLLECTOR_LETSMESH_DECODER_KEYS=
|
||||
|
||||
# Timeout in seconds per decode invocation
|
||||
COLLECTOR_LETSMESH_DECODER_TIMEOUT_SECONDS=2.0
|
||||
|
||||
# -------------------
|
||||
# Webhook Settings
|
||||
# ===================
|
||||
# -------------------
|
||||
# Webhooks forward mesh events to external HTTP endpoints as POST requests
|
||||
|
||||
# Webhook for advertisement events (node discovery)
|
||||
# Events are sent as POST requests with JSON payload
|
||||
WEBHOOK_ADVERTISEMENT_URL=
|
||||
WEBHOOK_ADVERTISEMENT_SECRET=
|
||||
|
||||
# Webhook for all message events (channel and direct messages)
|
||||
# Use this for a single endpoint handling all messages
|
||||
WEBHOOK_MESSAGE_URL=
|
||||
WEBHOOK_MESSAGE_SECRET=
|
||||
|
||||
@@ -119,3 +179,162 @@ WEBHOOK_MESSAGE_SECRET=
|
||||
WEBHOOK_TIMEOUT=10.0
|
||||
WEBHOOK_MAX_RETRIES=3
|
||||
WEBHOOK_RETRY_BACKOFF=2.0
|
||||
|
||||
# -------------------
|
||||
# Data Retention Settings
|
||||
# -------------------
|
||||
# Automatic cleanup of old event data (advertisements, messages, telemetry, etc.)
|
||||
|
||||
# Enable automatic cleanup of old event data
|
||||
DATA_RETENTION_ENABLED=true
|
||||
|
||||
# Number of days to retain event data
|
||||
# Events older than this are deleted during cleanup
|
||||
DATA_RETENTION_DAYS=30
|
||||
|
||||
# Hours between automatic cleanup runs
|
||||
# Applies to both event data and node cleanup
|
||||
DATA_RETENTION_INTERVAL_HOURS=24
|
||||
|
||||
# -------------------
|
||||
# Node Cleanup Settings
|
||||
# -------------------
|
||||
# Automatic removal of inactive nodes
|
||||
|
||||
# Enable automatic cleanup of inactive nodes
|
||||
# Nodes with last_seen=NULL (never seen on network) are NOT removed
|
||||
NODE_CLEANUP_ENABLED=true
|
||||
|
||||
# Remove nodes not seen for this many days (based on last_seen field)
|
||||
NODE_CLEANUP_DAYS=7
|
||||
|
||||
# =============================================================================
|
||||
# API SETTINGS
|
||||
# =============================================================================
|
||||
# REST API for querying data and sending commands
|
||||
|
||||
# External API port
|
||||
API_PORT=8000
|
||||
|
||||
# API Keys for authentication
|
||||
# Generate secure keys for production: openssl rand -hex 32
|
||||
# Leave empty to disable authentication (not recommended for production)
|
||||
API_READ_KEY=
|
||||
API_ADMIN_KEY=
|
||||
|
||||
# -------------------
|
||||
# Prometheus Metrics
|
||||
# -------------------
|
||||
# Prometheus metrics endpoint exposed at /metrics on the API service
|
||||
|
||||
# Enable Prometheus metrics endpoint
|
||||
# Default: true
|
||||
METRICS_ENABLED=true
|
||||
|
||||
# Seconds to cache metrics output (reduces database load)
|
||||
# Default: 60
|
||||
METRICS_CACHE_TTL=60
|
||||
|
||||
# External Prometheus port (when using --profile metrics)
|
||||
PROMETHEUS_PORT=9090
|
||||
|
||||
# External Alertmanager port (when using --profile metrics)
|
||||
ALERTMANAGER_PORT=9093
|
||||
|
||||
# =============================================================================
|
||||
# WEB DASHBOARD SETTINGS
|
||||
# =============================================================================
|
||||
# Web interface for visualizing network status
|
||||
|
||||
# External web port
|
||||
WEB_PORT=8080
|
||||
|
||||
# API endpoint URL for the web dashboard
|
||||
# Default: http://localhost:8000
|
||||
# API_BASE_URL=http://localhost:8000
|
||||
|
||||
# API key for web dashboard queries (optional)
|
||||
# If API_READ_KEY is set on the API, provide it here
|
||||
# API_KEY=
|
||||
|
||||
# Default theme for the web dashboard (dark or light)
|
||||
# Users can override via the theme toggle; their preference is saved in localStorage
|
||||
# Default: dark
|
||||
# WEB_THEME=dark
|
||||
|
||||
# Locale/language for the web dashboard
|
||||
# Default: en
|
||||
# Supported: en (see src/meshcore_hub/web/static/locales/ for available translations)
|
||||
# WEB_LOCALE=en
|
||||
|
||||
# Locale used for date/time formatting in the web dashboard
|
||||
# Controls date ordering only; 24-hour clock is still used by default
|
||||
# Examples: en-US (MM/DD/YYYY), en-GB (DD/MM/YYYY)
|
||||
# Default: en-US
|
||||
# WEB_DATETIME_LOCALE=en-US
|
||||
|
||||
# Auto-refresh interval in seconds for list pages (nodes, advertisements, messages)
|
||||
# Set to 0 to disable auto-refresh
|
||||
# Default: 30
|
||||
# WEB_AUTO_REFRESH_SECONDS=30
|
||||
|
||||
# Enable admin interface at /a/ (requires auth proxy in front)
|
||||
# Default: false
|
||||
# WEB_ADMIN_ENABLED=false
|
||||
|
||||
# Timezone for displaying dates/times on the web dashboard
|
||||
# Uses standard IANA timezone names (e.g., America/New_York, Europe/London)
|
||||
# Default: UTC
|
||||
TZ=UTC
|
||||
|
||||
# Directory containing custom content (pages/, media/)
|
||||
# Default: ./content
|
||||
# CONTENT_HOME=./content
|
||||
|
||||
# -------------------
|
||||
# Network Information
|
||||
# -------------------
|
||||
# Displayed on the web dashboard homepage
|
||||
|
||||
# Network domain name (optional)
|
||||
# NETWORK_DOMAIN=
|
||||
|
||||
# Network display name
|
||||
NETWORK_NAME=MeshCore Network
|
||||
|
||||
# Network location
|
||||
NETWORK_CITY=
|
||||
NETWORK_COUNTRY=
|
||||
|
||||
# Radio configuration (comma-delimited)
|
||||
# Format: <profile>,<frequency>,<bandwidth>,<spreading_factor>,<coding_rate>,<tx_power>
|
||||
# Example: EU/UK Narrow,869.618MHz,62.5kHz,SF8,CR8,22dBm
|
||||
NETWORK_RADIO_CONFIG=
|
||||
|
||||
# Welcome text displayed on the homepage (optional, plain text)
|
||||
# If not set, a default welcome message is shown
|
||||
NETWORK_WELCOME_TEXT=
|
||||
|
||||
# -------------------
|
||||
# Feature Flags
|
||||
# -------------------
|
||||
# Control which pages are visible in the web dashboard
|
||||
# Set to false to completely hide a page (nav, routes, sitemap, robots.txt)
|
||||
|
||||
# FEATURE_DASHBOARD=true
|
||||
# FEATURE_NODES=true
|
||||
# FEATURE_ADVERTISEMENTS=true
|
||||
# FEATURE_MESSAGES=true
|
||||
# FEATURE_MAP=true
|
||||
# FEATURE_MEMBERS=true
|
||||
# FEATURE_PAGES=true
|
||||
|
||||
# -------------------
|
||||
# Contact Information
|
||||
# -------------------
|
||||
# Contact links displayed in the footer
|
||||
|
||||
NETWORK_CONTACT_EMAIL=
|
||||
NETWORK_CONTACT_DISCORD=
|
||||
NETWORK_CONTACT_GITHUB=
|
||||
NETWORK_CONTACT_YOUTUBE=
|
||||
|
||||
1
.github/FUNDING.yml
vendored
Normal file
1
.github/FUNDING.yml
vendored
Normal file
@@ -0,0 +1 @@
|
||||
buy_me_a_coffee: jinglemansweep
|
||||
71
.github/workflows/ci.yml
vendored
71
.github/workflows/ci.yml
vendored
@@ -2,52 +2,43 @@ name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, master]
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main, master]
|
||||
branches: [main]
|
||||
paths:
|
||||
- "src/**"
|
||||
- "tests/**"
|
||||
- "alembic/**"
|
||||
- ".python-version"
|
||||
- "pyproject.toml"
|
||||
- ".pre-commit-config.yaml"
|
||||
- ".github/workflows/**"
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
name: Lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: "3.11"
|
||||
python-version-file: ".python-version"
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install black flake8 mypy
|
||||
pip install -e ".[dev]"
|
||||
|
||||
- name: Check formatting with black
|
||||
run: black --check src/ tests/
|
||||
|
||||
- name: Lint with flake8
|
||||
run: flake8 src/ tests/
|
||||
|
||||
- name: Type check with mypy
|
||||
run: mypy src/
|
||||
- name: Run pre-commit
|
||||
uses: pre-commit/action@v3.0.1
|
||||
|
||||
test:
|
||||
name: Test (Python ${{ matrix.python-version }})
|
||||
name: Test
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
python-version: ["3.11"]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@v5
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
python-version-file: ".python-version"
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
@@ -56,27 +47,35 @@ jobs:
|
||||
|
||||
- name: Run tests with pytest
|
||||
run: |
|
||||
pytest --cov=meshcore_hub --cov-report=xml --cov-report=term-missing
|
||||
pytest --cov=meshcore_hub --cov-report=xml --cov-report=term-missing --junitxml=junit.xml -o junit_family=legacy
|
||||
|
||||
- name: Upload coverage to Codecov
|
||||
uses: codecov/codecov-action@v4
|
||||
if: matrix.python-version == '3.11'
|
||||
uses: codecov/codecov-action@v5
|
||||
if: always()
|
||||
with:
|
||||
files: ./coverage.xml
|
||||
fail_ci_if_error: false
|
||||
verbose: true
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
|
||||
- name: Upload test results to Codecov
|
||||
uses: codecov/codecov-action@v5
|
||||
if: ${{ !cancelled() }}
|
||||
with:
|
||||
report_type: test_results
|
||||
token: ${{ secrets.CODECOV_TOKEN }}
|
||||
|
||||
build:
|
||||
name: Build Package
|
||||
runs-on: ubuntu-latest
|
||||
needs: [lint, test]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: "3.11"
|
||||
python-version-file: ".python-version"
|
||||
|
||||
- name: Install build tools
|
||||
run: |
|
||||
@@ -87,7 +86,7 @@ jobs:
|
||||
run: python -m build
|
||||
|
||||
- name: Upload artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: dist
|
||||
path: dist/
|
||||
|
||||
31
.github/workflows/docker.yml
vendored
31
.github/workflows/docker.yml
vendored
@@ -2,11 +2,18 @@ name: Docker
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, master]
|
||||
branches: [main]
|
||||
paths:
|
||||
- "src/**"
|
||||
- "alembic/**"
|
||||
- "alembic.ini"
|
||||
- ".python-version"
|
||||
- "pyproject.toml"
|
||||
- "Dockerfile"
|
||||
- "docker-compose.yml"
|
||||
- ".github/workflows/**"
|
||||
tags:
|
||||
- "v*"
|
||||
pull_request:
|
||||
branches: [main, master]
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
@@ -21,14 +28,17 @@ jobs:
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Log in to Container Registry
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
@@ -36,7 +46,7 @@ jobs:
|
||||
|
||||
- name: Extract metadata for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
uses: docker/metadata-action@v6
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||
tags: |
|
||||
@@ -47,19 +57,22 @@ jobs:
|
||||
type=sha
|
||||
|
||||
- name: Build and push Docker image
|
||||
uses: docker/build-push-action@v5
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
file: Dockerfile
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
build-args: |
|
||||
BUILD_VERSION=${{ github.ref_name }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
|
||||
- name: Test Docker image
|
||||
if: github.event_name == 'pull_request'
|
||||
run: |
|
||||
docker build -t meshcore-hub-test -f Dockerfile .
|
||||
docker build -t meshcore-hub-test --build-arg BUILD_VERSION=${{ github.ref_name }} -f Dockerfile .
|
||||
docker run --rm meshcore-hub-test --version
|
||||
docker run --rm meshcore-hub-test --help
|
||||
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -3,6 +3,7 @@
|
||||
!example/data/
|
||||
/seed/
|
||||
!example/seed/
|
||||
/content/
|
||||
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
@@ -33,6 +34,7 @@ share/python-wheels/
|
||||
MANIFEST
|
||||
uv.lock
|
||||
|
||||
docker-compose.override.yml
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
|
||||
100
.plans/2026/03/09/01-security-fixes/changelog.md
Normal file
100
.plans/2026/03/09/01-security-fixes/changelog.md
Normal file
@@ -0,0 +1,100 @@
|
||||
## TASK-001: Remove legacy HTML dashboard endpoint
|
||||
**Status:** completed
|
||||
### Files Modified
|
||||
- `src/meshcore_hub/api/routes/dashboard.py`
|
||||
- `tests/test_api/test_dashboard.py`
|
||||
### Notes
|
||||
Removed the `dashboard()` route handler and its `@router.get("")` decorator. Removed `HTMLResponse` and `Request` imports no longer used. Updated existing tests to verify the HTML endpoint returns 404/405. All JSON sub-routes (`/stats`, `/activity`, `/message-activity`, `/node-count`) remain intact.
|
||||
---
|
||||
|
||||
## TASK-002: Replace API key comparisons with constant-time comparison
|
||||
**Status:** completed
|
||||
### Files Modified
|
||||
- `src/meshcore_hub/api/auth.py`
|
||||
- `src/meshcore_hub/api/metrics.py`
|
||||
### Notes
|
||||
Added `import hmac` to both files. Replaced `==` comparisons with `hmac.compare_digest()` in `require_read`, `require_admin`, and `verify_basic_auth`. Added truthiness guards for `read_key`/`admin_key` in `require_read` since either can be `None` and `hmac.compare_digest()` raises `TypeError` on `None`.
|
||||
---
|
||||
|
||||
## TASK-003: Add WEB_TRUSTED_PROXY_HOSTS configuration setting
|
||||
**Status:** completed
|
||||
### Files Modified
|
||||
- `src/meshcore_hub/common/config.py`
|
||||
### Notes
|
||||
Added `web_trusted_proxy_hosts: str = Field(default="*", ...)` to `WebSettings` class. Automatically configurable via `WEB_TRUSTED_PROXY_HOSTS` env var through Pydantic Settings.
|
||||
---
|
||||
|
||||
## TASK-004: Integrate trusted proxy hosts into web app middleware and add startup warning
|
||||
**Status:** completed
|
||||
### Files Modified
|
||||
- `src/meshcore_hub/web/app.py`
|
||||
### Notes
|
||||
Replaced hardcoded `trusted_hosts="*"` in `ProxyHeadersMiddleware` with configured value. If value is `"*"`, passes string directly; otherwise splits on commas. Added startup warning when `WEB_ADMIN_ENABLED=true` and `WEB_TRUSTED_PROXY_HOSTS="*"`. `_is_authenticated_proxy_request` unchanged.
|
||||
---
|
||||
|
||||
## TASK-005: Escape config JSON in template script block to prevent XSS breakout
|
||||
**Status:** completed
|
||||
### Files Modified
|
||||
- `src/meshcore_hub/web/app.py`
|
||||
### Notes
|
||||
Added `.replace("</", "<\\/")` to `_build_config_json` return value. Prevents `</script>` breakout in the Jinja2 template's `<script>` block. `<\/` is valid JSON per spec and parsed correctly by `JSON.parse()`.
|
||||
---
|
||||
|
||||
## TASK-006: Fix stored XSS in admin node-tags page
|
||||
**Status:** completed
|
||||
### Files Modified
|
||||
- `src/meshcore_hub/web/static/js/spa/pages/admin/node-tags.js`
|
||||
### Notes
|
||||
Added `escapeHtml` to imports. Escaped `nodeName` with `escapeHtml()` in copy-all and delete-all confirmation dialogs (2 `unsafeHTML()` calls). Escaped `activeTagKey` with `escapeHtml()` in single tag delete confirmation (`innerHTML` assignment). Translation template `<strong>` tags preserved.
|
||||
---
|
||||
|
||||
## TASK-007: Fix stored XSS in admin members page
|
||||
**Status:** completed
|
||||
### Files Modified
|
||||
- `src/meshcore_hub/web/static/js/spa/pages/admin/members.js`
|
||||
### Notes
|
||||
Added `escapeHtml` to imports. Escaped `memberName` with `escapeHtml()` before passing to `t()` in delete confirmation dialog. `innerHTML` retained for `<strong>` tag rendering from translation template.
|
||||
---
|
||||
|
||||
## TASK-008: Write tests for legacy dashboard endpoint removal
|
||||
**Status:** completed
|
||||
### Files Modified
|
||||
- `tests/test_api/test_dashboard.py`
|
||||
### Notes
|
||||
Added 5 new tests: 1 for trailing-slash 404/405 verification, 4 for authenticated JSON sub-route responses. Total 20 dashboard tests passing.
|
||||
---
|
||||
|
||||
## TASK-009: Write tests for constant-time API key comparison
|
||||
**Status:** completed
|
||||
### Files Modified
|
||||
- `tests/test_api/test_auth.py`
|
||||
### Notes
|
||||
Restructured from 10 tests (2 classes) to 22 tests (4 classes): `TestReadAuthentication` (9), `TestAdminAuthentication` (4), `TestMetricsAuthentication` (7), `TestHealthEndpoint` (2). Added coverage for multi-endpoint read/admin key acceptance, missing auth header rejection, and metrics credential validation.
|
||||
---
|
||||
|
||||
## TASK-010: Write tests for trusted proxy hosts configuration and startup warning
|
||||
**Status:** completed
|
||||
### Files Modified
|
||||
- `tests/test_common/test_config.py`
|
||||
- `tests/test_web/test_app.py`
|
||||
### Notes
|
||||
Added 3 config tests (default value, specific IP, comma-separated list) and 5 web app tests (warning logged with wildcard+admin, no warning with specific hosts, no warning with admin disabled, comma list parsing, wildcard passed as string).
|
||||
---
|
||||
|
||||
## TASK-011: Write tests for config JSON script block escaping
|
||||
**Status:** completed
|
||||
### Files Created
|
||||
- `tests/test_web/test_app.py`
|
||||
### Notes
|
||||
Added 5 tests in `TestConfigJsonXssEscaping` class: rendered HTML escaping, normal values unaffected, escaped JSON parseable, direct `_build_config_json` escaping, direct no-escaping-needed.
|
||||
---
|
||||
|
||||
## TASK-012: Update documentation for WEB_TRUSTED_PROXY_HOSTS setting
|
||||
**Status:** completed
|
||||
### Files Modified
|
||||
- `README.md`
|
||||
- `AGENTS.md`
|
||||
- `PLAN.md`
|
||||
### Notes
|
||||
Added `WEB_TRUSTED_PROXY_HOSTS` to environment variables sections in all three docs. Documented default value (`*`), production recommendation, and startup warning behavior.
|
||||
---
|
||||
162
.plans/2026/03/09/01-security-fixes/prd.md
Normal file
162
.plans/2026/03/09/01-security-fixes/prd.md
Normal file
@@ -0,0 +1,162 @@
|
||||
# Product Requirements Document
|
||||
|
||||
> Source: `.plans/2026/03/09/01-security-fixes/prompt.md`
|
||||
|
||||
## Project Overview
|
||||
|
||||
This project addresses CRITICAL and HIGH severity vulnerabilities identified in a security audit of MeshCore Hub. The fixes span stored XSS in server-rendered and client-side code, timing attacks on authentication, proxy header forgery, and a legacy endpoint with missing authentication. All changes must be backward-compatible and preserve existing API contracts.
|
||||
|
||||
## Goals
|
||||
|
||||
- Eliminate all CRITICAL and HIGH severity security vulnerabilities found in the audit
|
||||
- Harden API key comparison against timing side-channel attacks
|
||||
- Prevent XSS vectors in both Jinja2 templates and client-side JavaScript
|
||||
- Add configurable proxy trust to defend against header forgery while maintaining backward compatibility
|
||||
- Remove the redundant legacy HTML dashboard endpoint that lacks authentication
|
||||
|
||||
## Functional Requirements
|
||||
|
||||
### REQ-001: Remove legacy HTML dashboard endpoint
|
||||
|
||||
**Description:** Remove the `GET /api/v1/dashboard/` route handler that renders a standalone HTML page with unescaped database content (stored XSS) and no authentication. The JSON sub-routes (`/stats`, `/activity`, `/message-activity`, `/node-count`) must remain intact and unchanged.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
|
||||
- [ ] The `dashboard()` route handler in `api/routes/dashboard.py` is removed
|
||||
- [ ] The `HTMLResponse` import is removed (if no longer used)
|
||||
- [ ] `GET /api/v1/dashboard/` returns 404 or Method Not Allowed
|
||||
- [ ] `GET /api/v1/dashboard/stats` continues to return valid JSON with authentication
|
||||
- [ ] `GET /api/v1/dashboard/activity` continues to return valid JSON with authentication
|
||||
- [ ] `GET /api/v1/dashboard/message-activity` continues to return valid JSON with authentication
|
||||
- [ ] `GET /api/v1/dashboard/node-count` continues to return valid JSON with authentication
|
||||
- [ ] Existing API tests for JSON sub-routes still pass
|
||||
|
||||
### REQ-002: Use constant-time comparison for API key validation
|
||||
|
||||
**Description:** Replace all Python `==` comparisons of API keys and credentials with `hmac.compare_digest()` to prevent timing side-channel attacks that could leak key material.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
|
||||
- [ ] All API key comparisons in `api/auth.py` use `hmac.compare_digest()` instead of `==`
|
||||
- [ ] All credential comparisons in `api/metrics.py` use `hmac.compare_digest()` instead of `==`
|
||||
- [ ] `hmac` is imported in all files where secret comparison occurs
|
||||
- [ ] The authentication behavior is unchanged — valid keys are accepted, invalid keys are rejected
|
||||
- [ ] Tests confirm authentication still works correctly with valid and invalid keys
|
||||
|
||||
### REQ-003: Add configurable trusted proxy hosts for admin authentication
|
||||
|
||||
**Description:** Add a `WEB_TRUSTED_PROXY_HOSTS` configuration setting that controls which hosts are trusted for proxy authentication headers (`X-Forwarded-User`, `X-Auth-Request-User`, `Authorization: Basic`). The setting defaults to `*` for backward compatibility. A startup warning is emitted when admin is enabled with the wildcard default. The `Authorization: Basic` header check must be preserved for Nginx Proxy Manager compatibility.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
|
||||
- [ ] A `WEB_TRUSTED_PROXY_HOSTS` setting is added to the configuration (Pydantic Settings)
|
||||
- [ ] The setting defaults to `*` (backward compatible)
|
||||
- [ ] `ProxyHeadersMiddleware` uses the configured `trusted_hosts` value instead of hardcoded `*`
|
||||
- [ ] A warning is logged at startup when `WEB_ADMIN_ENABLED=true` and `WEB_TRUSTED_PROXY_HOSTS` is `*`
|
||||
- [ ] The warning message recommends restricting trusted hosts to the operator's proxy IP
|
||||
- [ ] The `_is_authenticated_proxy_request` function continues to accept `X-Forwarded-User`, `X-Auth-Request-User`, and `Authorization: Basic` headers
|
||||
- [ ] OAuth2 proxy setups continue to function correctly
|
||||
- [ ] Setting `WEB_TRUSTED_PROXY_HOSTS` to a specific IP restricts proxy header trust to that IP
|
||||
|
||||
### REQ-004: Escape config JSON in template script block
|
||||
|
||||
**Description:** Prevent XSS via `</script>` breakout in the `config_json|safe` template injection by escaping `</` sequences in the serialized JSON string before passing it to the Jinja2 template.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
|
||||
- [ ] `config_json` is escaped by replacing `</` with `<\\/` before template rendering (in `web/app.py`)
|
||||
- [ ] The `|safe` filter continues to be used (the escaping happens in Python, not Jinja2)
|
||||
- [ ] A config value containing `</script><script>alert(1)</script>` does not execute JavaScript
|
||||
- [ ] The SPA application correctly parses the escaped config JSON on the client side
|
||||
- [ ] Normal config values (without special characters) render unchanged
|
||||
|
||||
### REQ-005: Fix stored XSS in admin page JavaScript
|
||||
|
||||
**Description:** Sanitize API-sourced data (node names, tag keys, member names) before rendering in admin pages. Replace `unsafeHTML()` and direct `innerHTML` assignment with safe alternatives — either `escapeHtml()` (already available in `components.js`) or lit-html safe templating (`${value}` interpolation without `unsafeHTML`).
|
||||
|
||||
**Acceptance Criteria:**
|
||||
|
||||
- [ ] Node names in `admin/node-tags.js` are escaped or safely templated before HTML rendering
|
||||
- [ ] Tag keys in `admin/node-tags.js` are escaped or safely templated before HTML rendering
|
||||
- [ ] Member names in `admin/members.js` are escaped or safely templated before HTML rendering
|
||||
- [ ] All `unsafeHTML()` calls on API-sourced data in the identified files are replaced with safe alternatives
|
||||
- [ ] All direct `innerHTML` assignments of API-sourced data in the identified files are replaced with safe alternatives
|
||||
- [ ] A node name containing `<img src=x onerror=alert(1)>` renders as text, not as an HTML element
|
||||
- [ ] A member name containing `<script>alert(1)</script>` renders as text, not as executable script
|
||||
- [ ] Normal names (without special characters) continue to display correctly
|
||||
|
||||
## Non-Functional Requirements
|
||||
|
||||
### REQ-006: Backward compatibility
|
||||
|
||||
**Category:** Reliability
|
||||
|
||||
**Description:** All security fixes must maintain backward compatibility with existing deployments. No breaking changes to API contracts, configuration defaults, or deployment workflows.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
|
||||
- [ ] All existing API endpoints (except the removed HTML dashboard) return the same response format
|
||||
- [ ] Default configuration values preserve existing behavior without requiring operator action
|
||||
- [ ] Docker Compose deployments continue to function without configuration changes
|
||||
- [ ] All existing tests pass after the security fixes are applied
|
||||
|
||||
### REQ-007: No regression in authentication flows
|
||||
|
||||
**Category:** Security
|
||||
|
||||
**Description:** The security hardening must not introduce authentication regressions. Valid credentials must continue to be accepted, and invalid credentials must continue to be rejected, across all authentication methods.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
|
||||
- [ ] API read key authentication accepts valid keys and rejects invalid keys
|
||||
- [ ] API admin key authentication accepts valid keys and rejects invalid keys
|
||||
- [ ] Metrics endpoint authentication (if configured) accepts valid credentials and rejects invalid ones
|
||||
- [ ] Proxy header authentication continues to work with OAuth2 proxy setups
|
||||
- [ ] Basic auth header forwarding from Nginx Proxy Manager continues to work
|
||||
|
||||
## Technical Constraints and Assumptions
|
||||
|
||||
### Constraints
|
||||
|
||||
- Python 3.13+ (specified by project `.python-version`)
|
||||
- Must use `hmac.compare_digest()` from the Python standard library for constant-time comparison
|
||||
- The `Authorization: Basic` header check in `_is_authenticated_proxy_request` must not be removed or modified to validate credentials server-side — credential validation is the proxy's responsibility
|
||||
- Changes must not alter existing API response schemas or status codes (except removing the HTML dashboard endpoint)
|
||||
|
||||
### Assumptions
|
||||
|
||||
- The `escapeHtml()` utility in `components.js` correctly escapes `<`, `>`, `&`, `"`, and `'` characters
|
||||
- The SPA client-side JavaScript can parse JSON containing escaped `<\/` sequences (standard behavior per JSON spec)
|
||||
- Operators using proxy authentication have a reverse proxy (e.g., Nginx, Traefik, NPM) in front of MeshCore Hub
|
||||
|
||||
## Scope
|
||||
|
||||
### In Scope
|
||||
|
||||
- Removing the legacy HTML dashboard route handler (C1 + H2)
|
||||
- Replacing `==` with `hmac.compare_digest()` for all secret comparisons (H1)
|
||||
- Adding `WEB_TRUSTED_PROXY_HOSTS` configuration and startup warning (H3)
|
||||
- Escaping `</` in config JSON template injection (H4)
|
||||
- Fixing `unsafeHTML()`/`innerHTML` XSS in admin JavaScript pages (H5)
|
||||
- Updating tests to cover the security fixes
|
||||
- Updating documentation for the new `WEB_TRUSTED_PROXY_HOSTS` setting
|
||||
|
||||
### Out of Scope
|
||||
|
||||
- MEDIUM severity findings (CORS, error detail leakage, rate limiting, security headers, CSRF, CDN SRI, markdown sanitization, input validation, channel key exposure)
|
||||
- LOW severity findings (auth warnings, version disclosure, unbounded fields, credential logging, SecretStr, port exposure, cache safety, image pinning)
|
||||
- INFO findings (OpenAPI docs, proxy IP logging, alertmanager comments, DOM XSS in error handler, locale path)
|
||||
- Adding rate limiting infrastructure
|
||||
- Adding Content-Security-Policy or other security headers
|
||||
- Dependency version pinning or lockfile generation
|
||||
- Server-side credential validation for Basic auth (proxy responsibility)
|
||||
|
||||
## Suggested Tech Stack
|
||||
|
||||
| Layer | Technology | Rationale |
|
||||
|-------|-----------|-----------|
|
||||
| Secret comparison | `hmac.compare_digest()` (stdlib) | Specified by prompt; constant-time comparison prevents timing attacks |
|
||||
| Template escaping | Python `str.replace()` | Minimal approach to escape `</` in JSON before Jinja2 rendering |
|
||||
| Client-side escaping | `escapeHtml()` from `components.js` | Already available in the codebase; standard HTML entity escaping |
|
||||
| Configuration | Pydantic Settings | Specified by project stack; used for `WEB_TRUSTED_PROXY_HOSTS` |
|
||||
| Testing | pytest, pytest-asyncio | Specified by project stack |
|
||||
65
.plans/2026/03/09/01-security-fixes/prompt.md
Normal file
65
.plans/2026/03/09/01-security-fixes/prompt.md
Normal file
@@ -0,0 +1,65 @@
|
||||
# Phase: 01-security-fixes
|
||||
|
||||
## Overview
|
||||
|
||||
Address CRITICAL and HIGH severity vulnerabilities identified in the MeshCore Hub security audit across API and Web components. These findings represent exploitable vulnerabilities including XSS, timing attacks, authentication bypasses, and insecure defaults.
|
||||
|
||||
## Goals
|
||||
|
||||
- Eliminate all CRITICAL and HIGH severity security vulnerabilities
|
||||
- Harden authentication mechanisms against timing attacks and header forgery
|
||||
- Prevent XSS vectors in both server-rendered HTML and client-side JavaScript
|
||||
- Secure default MQTT configuration against unauthenticated access
|
||||
|
||||
## Requirements
|
||||
|
||||
### C1 + H2 — Remove legacy HTML dashboard endpoint
|
||||
- **File:** `src/meshcore_hub/api/routes/dashboard.py:367-536`
|
||||
- The `GET /api/v1/dashboard/` endpoint is a standalone HTML page with two CRITICAL/HIGH issues: stored XSS (unescaped DB content in f-string HTML) and missing authentication
|
||||
- The SPA web dashboard provides a full-featured replacement, making this endpoint redundant
|
||||
- **Fix:** Remove the `dashboard()` route handler and its `HTMLResponse` import. Keep all JSON sub-routes (`/stats`, `/activity`, `/message-activity`, `/node-count`) intact.
|
||||
|
||||
### H1 — Fix timing attack on API key comparison
|
||||
- **Files:** `api/auth.py:82,127` | `api/metrics.py:57`
|
||||
- All secret comparisons use Python `==`, which is not constant-time
|
||||
- **Fix:** Replace with `hmac.compare_digest()` for all key/credential comparisons
|
||||
|
||||
### H3 — Harden admin auth against proxy header forgery
|
||||
- **File:** `web/app.py:73-86,239`
|
||||
- Admin access trusts `X-Forwarded-User`, `X-Auth-Request-User`, or `Authorization: Basic` header
|
||||
- `ProxyHeadersMiddleware(trusted_hosts="*")` accepts forged headers from any client
|
||||
- The `Authorization: Basic` check must be preserved — it is required by the Nginx Proxy Manager (NPM) Access List setup documented in README.md (NPM validates credentials and forwards the header)
|
||||
- **Fix:** Add a `WEB_TRUSTED_PROXY_HOSTS` config setting (default `*` for backward compatibility). Pass it to `ProxyHeadersMiddleware(trusted_hosts=...)`. Add a startup warning when `WEB_ADMIN_ENABLED=true` and `trusted_hosts` is still `*`, recommending operators restrict it to their proxy IP. Do NOT remove the Basic auth header check or validate credentials server-side — that is the proxy's responsibility.
|
||||
|
||||
### H4 — Fix XSS via config_json|safe script block breakout
|
||||
- **File:** `web/templates/spa.html:188` | `web/app.py:157-183`
|
||||
- Operator config values injected into `<script>` block with `|safe` — a value containing `</script>` breaks out and executes arbitrary JS
|
||||
- **Fix:** Escape `</` sequences in the JSON string: `config_json = json.dumps(config).replace("</", "<\\/")`
|
||||
|
||||
### H5 — Fix stored XSS via unsafeHTML/innerHTML with API-sourced data
|
||||
- **Files:** `web/static/js/spa/pages/admin/node-tags.js:243,272,454` | `admin/members.js:309`
|
||||
- Node names, tag keys, and member names from the API are interpolated into HTML via `unsafeHTML()` and direct `innerHTML` assignment
|
||||
- **Fix:** Use `escapeHtml()` (already in `components.js`) on API data before HTML interpolation, or replace with lit-html safe templating
|
||||
|
||||
|
||||
## Constraints
|
||||
|
||||
- Must not break existing functionality or API contracts
|
||||
- Changes to docker-compose.yml and mosquitto.conf must remain backward-compatible (use env var defaults)
|
||||
- The `_is_authenticated_proxy_request` function must continue to work with OAuth2 proxy setups — only add defense-in-depth, don't remove proxy header support entirely
|
||||
|
||||
## Out of Scope
|
||||
|
||||
- MEDIUM severity findings (CORS config, error detail leakage, rate limiting, security headers, CSRF, CDN SRI, markdown sanitization, input validation, channel key exposure)
|
||||
- LOW severity findings (auth warnings, version disclosure, unbounded fields, credential logging, SecretStr, port exposure, cache safety, image pinning)
|
||||
- INFO findings (OpenAPI docs, proxy IP logging, alertmanager comments, DOM XSS in error handler, locale path)
|
||||
- Adding rate limiting infrastructure
|
||||
- Adding Content-Security-Policy or other security headers
|
||||
- Dependency version pinning or lockfile generation
|
||||
|
||||
## References
|
||||
|
||||
- Security audit performed in this conversation (2026-03-09)
|
||||
- OWASP Top 10: XSS (A7:2017), Broken Authentication (A2:2017)
|
||||
- Python `hmac.compare_digest` documentation
|
||||
- FastAPI security best practices
|
||||
54
.plans/2026/03/09/01-security-fixes/reviews/cycle/001.yaml
Normal file
54
.plans/2026/03/09/01-security-fixes/reviews/cycle/001.yaml
Normal file
@@ -0,0 +1,54 @@
|
||||
# Code review round 001
|
||||
# Phase: .plans/2026/03/09/01-security-fixes
|
||||
# Scope: full
|
||||
# Generated by: /jp-codereview
|
||||
|
||||
issues:
|
||||
- id: "ISSUE-001"
|
||||
severity: "MINOR"
|
||||
category: "integration"
|
||||
file: "src/meshcore_hub/web/app.py"
|
||||
line: 251
|
||||
description: |
|
||||
The startup warning for insecure trusted proxy hosts checks `settings.web_admin_enabled`
|
||||
instead of the effective admin_enabled value that gets stored in `app.state.admin_enabled`.
|
||||
The `create_app()` function accepts an `admin_enabled` parameter (line 193) that can override
|
||||
the setting. If a caller passes `admin_enabled=True` but `settings.web_admin_enabled` is False,
|
||||
the warning will not fire despite admin being enabled. In practice this does not affect production
|
||||
deployments (CLI always uses the settings value), only programmatic/test usage.
|
||||
suggestion: |
|
||||
Consider computing the effective admin_enabled value before the warning check and using
|
||||
that for both the warning and `app.state.admin_enabled`, e.g.:
|
||||
`effective_admin = admin_enabled if admin_enabled is not None else settings.web_admin_enabled`
|
||||
related_tasks:
|
||||
- "TASK-004"
|
||||
|
||||
- id: "ISSUE-002"
|
||||
severity: "MINOR"
|
||||
category: "style"
|
||||
file: "src/meshcore_hub/web/static/js/spa/pages/admin/node-tags.js"
|
||||
line: 3
|
||||
description: |
|
||||
The `unsafeHTML` import is retained and still used on lines 243 and 272. Although the
|
||||
API-sourced data (`nodeName`) is now safely escaped via `escapeHtml()` before interpolation,
|
||||
the continued use of `unsafeHTML()` may confuse future reviewers into thinking the XSS
|
||||
fix is incomplete. The `unsafeHTML()` is needed to render the translation template's HTML
|
||||
tags (e.g., `<strong>`), so this is functionally correct.
|
||||
suggestion: |
|
||||
Add a brief inline comment above each `unsafeHTML()` call explaining that the dynamic
|
||||
values are pre-escaped and `unsafeHTML()` is only needed for the template's HTML formatting.
|
||||
related_tasks:
|
||||
- "TASK-006"
|
||||
|
||||
summary:
|
||||
total_issues: 2
|
||||
critical: 0
|
||||
major: 0
|
||||
minor: 2
|
||||
by_category:
|
||||
integration: 1
|
||||
architecture: 0
|
||||
security: 0
|
||||
duplication: 0
|
||||
error-handling: 0
|
||||
style: 1
|
||||
70
.plans/2026/03/09/01-security-fixes/reviews/prd.md
Normal file
70
.plans/2026/03/09/01-security-fixes/reviews/prd.md
Normal file
@@ -0,0 +1,70 @@
|
||||
# PRD Review
|
||||
|
||||
> Phase: `.plans/2026/03/09/01-security-fixes`
|
||||
> PRD: `.plans/2026/03/09/01-security-fixes/prd.md`
|
||||
> Prompt: `.plans/2026/03/09/01-security-fixes/prompt.md`
|
||||
|
||||
## Verdict: PASS
|
||||
|
||||
The PRD fully covers all five security requirements from the prompt with clear, implementable, and testable acceptance criteria. No contradictions, blocking ambiguities, or feasibility concerns were found. One prompt goal ("Secure default MQTT configuration") has no corresponding requirement in either the prompt or the PRD, but since no prompt requirement addresses it, the PRD correctly does not fabricate one.
|
||||
|
||||
## Coverage Assessment
|
||||
|
||||
| Prompt Item | PRD Section | Covered? | Notes |
|
||||
|---|---|---|---|
|
||||
| C1+H2: Remove legacy HTML dashboard endpoint | REQ-001 | Yes | Route removal, import cleanup, sub-route preservation all specified |
|
||||
| H1: Fix timing attack on API key comparison | REQ-002 | Yes | Files and `hmac.compare_digest()` approach match |
|
||||
| H3: Harden admin auth / proxy header forgery | REQ-003 | Yes | Config setting, default, warning, Basic auth preservation all covered |
|
||||
| H4: Fix XSS via config_json\|safe breakout | REQ-004 | Yes | Escape approach and XSS test payload specified |
|
||||
| H5: Fix stored XSS via unsafeHTML/innerHTML | REQ-005 | Yes | Files, fix approach, and XSS test payloads specified |
|
||||
| Constraint: No breaking changes to API contracts | REQ-006 | Yes | |
|
||||
| Constraint: docker-compose.yml/mosquitto.conf backward-compatible | REQ-006 | Partial | REQ-006 covers Docker Compose but not mosquitto.conf; moot since no requirement changes mosquitto.conf |
|
||||
| Constraint: _is_authenticated_proxy_request works with OAuth2 | REQ-003, REQ-007 | Yes | |
|
||||
| Goal: Secure default MQTT configuration | -- | No | Goal stated in prompt but no prompt requirement addresses it; PRD correctly does not fabricate one |
|
||||
| Out of scope items | Scope section | Yes | All exclusions match prompt |
|
||||
|
||||
**Coverage summary:** 5 of 5 prompt requirements fully covered, 1 constraint partially covered (moot), 1 prompt goal has no corresponding requirement in the prompt itself.
|
||||
|
||||
## Requirement Evaluation
|
||||
|
||||
All requirements passed evaluation. Minor observations noted below.
|
||||
|
||||
### REQ-003: Add configurable trusted proxy hosts
|
||||
|
||||
- **Implementability:** Pass -- A developer familiar with Pydantic Settings and `ProxyHeadersMiddleware` can implement this without ambiguity. The env var format (comma-separated list vs. single value) is not explicitly stated but follows standard Pydantic patterns.
|
||||
- **Testability:** Pass
|
||||
- **Completeness:** Pass
|
||||
- **Consistency:** Pass
|
||||
|
||||
### REQ-006: Backward compatibility
|
||||
|
||||
- **Implementability:** Pass
|
||||
- **Testability:** Pass
|
||||
- **Completeness:** Pass -- The prompt constraint about mosquitto.conf backward compatibility is not explicitly mentioned, but no requirement modifies mosquitto.conf, making this moot.
|
||||
- **Consistency:** Pass
|
||||
|
||||
## Structural Issues
|
||||
|
||||
### Contradictions
|
||||
|
||||
None found.
|
||||
|
||||
### Ambiguities
|
||||
|
||||
None that would block implementation. The `WEB_TRUSTED_PROXY_HOSTS` env var format is a minor detail resolvable by the developer from the `ProxyHeadersMiddleware` API and standard Pydantic Settings patterns.
|
||||
|
||||
### Missing Edge Cases
|
||||
|
||||
None significant. The `hmac.compare_digest()` change (REQ-002) assumes the existing code handles the "no key configured" case before reaching the comparison, which is standard practice and verifiable during implementation.
|
||||
|
||||
### Feasibility Concerns
|
||||
|
||||
None.
|
||||
|
||||
### Scope Inconsistencies
|
||||
|
||||
The prompt states a goal of "Secure default MQTT configuration against unauthenticated access" but provides no requirement for it. The PRD drops this goal without explanation. This is a prompt-level gap, not a PRD-level gap -- the PRD should not invent requirements that the prompt does not specify.
|
||||
|
||||
## Action Items
|
||||
|
||||
No action items. The PRD is ready for task breakdown.
|
||||
90
.plans/2026/03/09/01-security-fixes/reviews/tasks.md
Normal file
90
.plans/2026/03/09/01-security-fixes/reviews/tasks.md
Normal file
@@ -0,0 +1,90 @@
|
||||
# Task Review
|
||||
|
||||
> Phase: `.plans/2026/03/09/01-security-fixes`
|
||||
> Tasks: `.plans/2026/03/09/01-security-fixes/tasks.yaml`
|
||||
> PRD: `.plans/2026/03/09/01-security-fixes/prd.md`
|
||||
|
||||
## Verdict: PASS
|
||||
|
||||
The task list is structurally sound, correctly ordered, and fully covers all 7 PRD requirements. The dependency graph is a valid DAG with no cycles or invalid references. No ordering issues, coverage gaps, vague tasks, or invalid fields were found. Two non-blocking warnings are noted: TASK-006 and TASK-007 (frontend XSS fixes) lack corresponding test tasks, and two pairs of independent tasks share output files but modify independent sections.
|
||||
|
||||
## Dependency Validation
|
||||
|
||||
### Reference Validity
|
||||
|
||||
All dependency references are valid. Every task ID referenced in a `dependencies` list corresponds to an existing task in the inventory.
|
||||
|
||||
### DAG Validation
|
||||
|
||||
The dependency graph is a valid directed acyclic graph. No cycles detected.
|
||||
|
||||
Topological layers:
|
||||
- **Layer 0 (roots):** TASK-001, TASK-002, TASK-003, TASK-005, TASK-006, TASK-007
|
||||
- **Layer 1:** TASK-004 (depends on TASK-003), TASK-008 (depends on TASK-001), TASK-009 (depends on TASK-002), TASK-011 (depends on TASK-005)
|
||||
- **Layer 2:** TASK-010 (depends on TASK-003, TASK-004), TASK-012 (depends on TASK-003, TASK-004)
|
||||
|
||||
### Orphan Tasks
|
||||
|
||||
No orphan tasks detected. All non-root tasks with dependencies are either terminal test/docs tasks (TASK-008, TASK-009, TASK-010, TASK-011, TASK-012) or integration tasks (TASK-004). Root tasks without dependents (TASK-006, TASK-007) are excluded from orphan detection per the review protocol.
|
||||
|
||||
## Ordering Check
|
||||
|
||||
No blocking ordering issues detected.
|
||||
|
||||
**Observation (non-blocking):** Two pairs of independent tasks share output files:
|
||||
|
||||
1. **TASK-004 and TASK-005** both modify `src/meshcore_hub/web/app.py` without a dependency between them. TASK-004 modifies `ProxyHeadersMiddleware` (line ~239) and adds a startup warning, while TASK-005 modifies `_build_config_json` (line ~183). These are independent functions in the same file; no actual conflict exists.
|
||||
|
||||
2. **TASK-010 and TASK-011** both modify `tests/test_web/test_app.py` without a dependency between them. Both add new test functions to the same test file. No actual conflict exists.
|
||||
|
||||
These are not blocking because neither task creates the shared file — both modify existing files in independent sections. Adding artificial dependencies would unnecessarily serialize parallelizable work.
|
||||
|
||||
## Coverage Check
|
||||
|
||||
### Uncovered Requirements
|
||||
|
||||
All PRD requirements are covered.
|
||||
|
||||
### Phantom References
|
||||
|
||||
No phantom references detected.
|
||||
|
||||
**Coverage summary:** 7 of 7 PRD requirements covered by tasks.
|
||||
|
||||
| Requirement | Tasks |
|
||||
|---|---|
|
||||
| REQ-001 | TASK-001, TASK-008 |
|
||||
| REQ-002 | TASK-002, TASK-009 |
|
||||
| REQ-003 | TASK-003, TASK-004, TASK-010, TASK-012 |
|
||||
| REQ-004 | TASK-005, TASK-011 |
|
||||
| REQ-005 | TASK-006, TASK-007 |
|
||||
| REQ-006 | TASK-001, TASK-003, TASK-004, TASK-005, TASK-006, TASK-007, TASK-008, TASK-010, TASK-011, TASK-012 |
|
||||
| REQ-007 | TASK-002, TASK-004, TASK-009 |
|
||||
|
||||
## Scope Check
|
||||
|
||||
### Tasks Too Large
|
||||
|
||||
No tasks flagged as too large. No task has `estimated_complexity: large`.
|
||||
|
||||
### Tasks Too Vague
|
||||
|
||||
No tasks flagged as too vague. All tasks have detailed descriptions (>50 chars), multiple testable acceptance criteria, and specific file paths in `files_affected`.
|
||||
|
||||
### Missing Test Tasks
|
||||
|
||||
Two implementation tasks lack corresponding test tasks:
|
||||
|
||||
- **TASK-006** (Fix stored XSS in admin node-tags page) — modifies `admin/node-tags.js` but no test task verifies the XSS fix in this JavaScript file. The acceptance criteria include XSS payload testing, but no automated test is specified. This is a frontend JavaScript change where manual verification or browser-based testing may be appropriate.
|
||||
|
||||
- **TASK-007** (Fix stored XSS in admin members page) — modifies `admin/members.js` but no test task verifies the XSS fix in this JavaScript file. Same reasoning as TASK-006.
|
||||
|
||||
**Note:** These are warnings, not blocking issues. The project's test infrastructure (`tests/test_web/`) focuses on server-side rendering and API responses. Client-side JavaScript XSS fixes are typically verified through acceptance criteria rather than automated unit tests.
|
||||
|
||||
### Field Validation
|
||||
|
||||
All tasks have valid fields:
|
||||
|
||||
- **Roles:** All `suggested_role` values are valid (`python`, `frontend`, `docs`).
|
||||
- **Complexity:** All `estimated_complexity` values are valid (`small`, `medium`).
|
||||
- **Completeness:** All 12 tasks have all required fields (`id`, `title`, `description`, `requirements`, `dependencies`, `suggested_role`, `acceptance_criteria`, `estimated_complexity`, `files_affected`). All list fields have at least one entry.
|
||||
22
.plans/2026/03/09/01-security-fixes/state.yaml
Normal file
22
.plans/2026/03/09/01-security-fixes/state.yaml
Normal file
@@ -0,0 +1,22 @@
|
||||
status: running
|
||||
phase_path: .plans/2026/03/09/01-security-fixes
|
||||
branch: fix/security-fixes
|
||||
current_phase: summary
|
||||
current_task: null
|
||||
fix_round: 0
|
||||
last_review_round: 1
|
||||
review_loop_exit_reason: success
|
||||
quality_gate: pass
|
||||
tasks:
|
||||
TASK-001: completed
|
||||
TASK-002: completed
|
||||
TASK-003: completed
|
||||
TASK-004: completed
|
||||
TASK-005: completed
|
||||
TASK-006: completed
|
||||
TASK-007: completed
|
||||
TASK-008: completed
|
||||
TASK-009: completed
|
||||
TASK-010: completed
|
||||
TASK-011: completed
|
||||
TASK-012: completed
|
||||
117
.plans/2026/03/09/01-security-fixes/summary.md
Normal file
117
.plans/2026/03/09/01-security-fixes/summary.md
Normal file
@@ -0,0 +1,117 @@
|
||||
# Phase Summary
|
||||
|
||||
> Phase: `.plans/2026/03/09/01-security-fixes`
|
||||
> Generated by: `/jp-summary`
|
||||
|
||||
## Project Overview
|
||||
|
||||
This phase addresses CRITICAL and HIGH severity vulnerabilities identified in a security audit of MeshCore Hub. The fixes span stored XSS in server-rendered and client-side code, timing attacks on authentication, proxy header forgery, and a legacy endpoint with missing authentication. All changes are backward-compatible and preserve existing API contracts.
|
||||
|
||||
### Goals
|
||||
|
||||
- Eliminate all CRITICAL and HIGH severity security vulnerabilities found in the audit
|
||||
- Harden API key comparison against timing side-channel attacks
|
||||
- Prevent XSS vectors in both Jinja2 templates and client-side JavaScript
|
||||
- Add configurable proxy trust to defend against header forgery while maintaining backward compatibility
|
||||
- Remove the redundant legacy HTML dashboard endpoint that lacks authentication
|
||||
|
||||
## Task Execution
|
||||
|
||||
### Overview
|
||||
|
||||
| Metric | Value |
|
||||
|---|---|
|
||||
| Total tasks | 12 |
|
||||
| Completed | 12 |
|
||||
| Failed | 0 |
|
||||
| Blocked | 0 |
|
||||
| Skipped | 0 |
|
||||
|
||||
### Task Details
|
||||
|
||||
| ID | Title | Role | Complexity | Status |
|
||||
|---|---|---|---|---|
|
||||
| TASK-001 | Remove legacy HTML dashboard endpoint | python | small | completed |
|
||||
| TASK-002 | Replace API key comparisons with constant-time comparison | python | small | completed |
|
||||
| TASK-003 | Add WEB_TRUSTED_PROXY_HOSTS configuration setting | python | small | completed |
|
||||
| TASK-004 | Integrate trusted proxy hosts into web app middleware and add startup warning | python | medium | completed |
|
||||
| TASK-005 | Escape config JSON in template script block to prevent XSS breakout | python | small | completed |
|
||||
| TASK-006 | Fix stored XSS in admin node-tags page | frontend | medium | completed |
|
||||
| TASK-007 | Fix stored XSS in admin members page | frontend | small | completed |
|
||||
| TASK-008 | Write tests for legacy dashboard endpoint removal | python | small | completed |
|
||||
| TASK-009 | Write tests for constant-time API key comparison | python | small | completed |
|
||||
| TASK-010 | Write tests for trusted proxy hosts configuration and startup warning | python | medium | completed |
|
||||
| TASK-011 | Write tests for config JSON script block escaping | python | small | completed |
|
||||
| TASK-012 | Update documentation for WEB_TRUSTED_PROXY_HOSTS setting | docs | small | completed |
|
||||
|
||||
### Requirement Coverage
|
||||
|
||||
| Metric | Value |
|
||||
|---|---|
|
||||
| Total PRD requirements | 7 |
|
||||
| Requirements covered by completed tasks | 7 |
|
||||
| Requirements with incomplete coverage | 0 |
|
||||
|
||||
All functional requirements (REQ-001 through REQ-005) and non-functional requirements (REQ-006, REQ-007) are fully covered by completed tasks.
|
||||
|
||||
## Files Created and Modified
|
||||
|
||||
### Created
|
||||
|
||||
- `tests/test_web/test_app.py`
|
||||
|
||||
### Modified
|
||||
|
||||
- `src/meshcore_hub/api/routes/dashboard.py`
|
||||
- `src/meshcore_hub/api/auth.py`
|
||||
- `src/meshcore_hub/api/metrics.py`
|
||||
- `src/meshcore_hub/common/config.py`
|
||||
- `src/meshcore_hub/web/app.py`
|
||||
- `src/meshcore_hub/web/static/js/spa/pages/admin/node-tags.js`
|
||||
- `src/meshcore_hub/web/static/js/spa/pages/admin/members.js`
|
||||
- `tests/test_api/test_dashboard.py`
|
||||
- `tests/test_api/test_auth.py`
|
||||
- `tests/test_common/test_config.py`
|
||||
- `README.md`
|
||||
- `AGENTS.md`
|
||||
- `PLAN.md`
|
||||
|
||||
## Review Rounds
|
||||
|
||||
### Overview
|
||||
|
||||
| Metric | Value |
|
||||
|---|---|
|
||||
| Total review rounds | 1 |
|
||||
| Total issues found | 2 |
|
||||
| Issues fixed | 2 |
|
||||
| Issues deferred | 0 |
|
||||
| Issues remaining | 0 |
|
||||
| Regressions introduced | 0 |
|
||||
|
||||
### Round Details
|
||||
|
||||
#### Round 1 (scope: full)
|
||||
|
||||
- **Issues found:** 2 (0 CRITICAL, 0 MAJOR, 2 MINOR)
|
||||
- **Issues fixed:** 2 (both MINOR issues were addressed post-review)
|
||||
- **Exit reason:** success (no CRITICAL or MAJOR issues)
|
||||
|
||||
## Known Issues and Deferred Items
|
||||
|
||||
No known issues. Both MINOR issues identified in the code review were addressed:
|
||||
|
||||
- **ISSUE-001** (MINOR, integration) -- Startup warning for proxy hosts used `settings.web_admin_enabled` instead of the effective admin_enabled value. Fixed by computing `effective_admin` before the warning check.
|
||||
- **ISSUE-002** (MINOR, style) -- `unsafeHTML()` calls on pre-escaped data lacked explanatory comments. Fixed by adding inline HTML comments explaining that dynamic values are pre-escaped.
|
||||
|
||||
## Decisions
|
||||
|
||||
- **Truthiness guards for `hmac.compare_digest()`** -- Added `read_key and ...` / `admin_key and ...` guards in `require_read` because either key can be `None` when only one is configured, and `hmac.compare_digest()` raises `TypeError` on `None` arguments. This ensures the existing behavior of accepting either key type when configured.
|
||||
- **`unsafeHTML()` retained with `escapeHtml()` pre-processing** -- The `unsafeHTML()` calls in admin JS pages were retained because translation strings contain intentional HTML formatting tags (e.g., `<strong>`). API-sourced data is escaped before interpolation, making this pattern safe.
|
||||
- **`innerHTML` retained for tag delete confirmation** -- The delete confirmation in `node-tags.js` uses `innerHTML` because the translation template includes `<span>` formatting. The dynamic tag key is escaped with `escapeHtml()` before interpolation.
|
||||
|
||||
## Suggested Next Steps
|
||||
|
||||
1. Run full manual testing of admin pages (node-tags, members) with XSS payloads to verify fixes in a browser environment.
|
||||
2. Test `WEB_TRUSTED_PROXY_HOSTS` with a real reverse proxy (Traefik/Nginx) to verify proxy header trust restriction works as expected.
|
||||
3. Push commits and create a pull request for merge into `main`.
|
||||
401
.plans/2026/03/09/01-security-fixes/tasks.yaml
Normal file
401
.plans/2026/03/09/01-security-fixes/tasks.yaml
Normal file
@@ -0,0 +1,401 @@
|
||||
# Task list generated from PRD: .plans/2026/03/09/01-security-fixes/prd.md
|
||||
# Generated by: /jp-task-list
|
||||
|
||||
tasks:
|
||||
- id: "TASK-001"
|
||||
title: "Remove legacy HTML dashboard endpoint"
|
||||
description: |
|
||||
Remove the `dashboard()` route handler from `src/meshcore_hub/api/routes/dashboard.py` (lines ~367-536).
|
||||
This handler renders a standalone HTML page using f-string HTML with unescaped database content (stored XSS)
|
||||
and has no authentication. The JSON sub-routes (`/stats`, `/activity`, `/message-activity`, `/node-count`)
|
||||
must remain intact and unchanged.
|
||||
|
||||
Specifically:
|
||||
1. Delete the `dashboard()` async function and its `@router.get("")` decorator (the handler that returns HTMLResponse).
|
||||
2. Remove the `HTMLResponse` import from `fastapi.responses` if it is no longer used by any remaining route.
|
||||
3. Verify that `GET /api/v1/dashboard/stats`, `/activity`, `/message-activity`, and `/node-count` still function.
|
||||
requirements:
|
||||
- "REQ-001"
|
||||
- "REQ-006"
|
||||
dependencies: []
|
||||
suggested_role: "python"
|
||||
acceptance_criteria:
|
||||
- "The `dashboard()` route handler is removed from `api/routes/dashboard.py`"
|
||||
- "`HTMLResponse` import is removed if no longer used"
|
||||
- "`GET /api/v1/dashboard/` returns 404 or 405"
|
||||
- "`GET /api/v1/dashboard/stats` returns valid JSON with authentication"
|
||||
- "`GET /api/v1/dashboard/activity` returns valid JSON with authentication"
|
||||
- "`GET /api/v1/dashboard/message-activity` returns valid JSON with authentication"
|
||||
- "`GET /api/v1/dashboard/node-count` returns valid JSON with authentication"
|
||||
estimated_complexity: "small"
|
||||
files_affected:
|
||||
- "src/meshcore_hub/api/routes/dashboard.py"
|
||||
|
||||
- id: "TASK-002"
|
||||
title: "Replace API key comparisons with constant-time comparison"
|
||||
description: |
|
||||
Replace all Python `==` comparisons of API keys and credentials with `hmac.compare_digest()` to prevent
|
||||
timing side-channel attacks.
|
||||
|
||||
In `src/meshcore_hub/api/auth.py`:
|
||||
1. Add `import hmac` at the top of the file.
|
||||
2. Line ~82 in `require_read`: replace `if token == read_key or token == admin_key:` with
|
||||
`if hmac.compare_digest(token, read_key) or hmac.compare_digest(token, admin_key):`.
|
||||
3. Line ~127 in `require_admin`: replace `if token == admin_key:` with
|
||||
`if hmac.compare_digest(token, admin_key):`.
|
||||
|
||||
In `src/meshcore_hub/api/metrics.py`:
|
||||
1. Add `import hmac` at the top of the file.
|
||||
2. Line ~57: replace `return username == "metrics" and password == read_key` with
|
||||
`return hmac.compare_digest(username, "metrics") and hmac.compare_digest(password, read_key)`.
|
||||
|
||||
Note: `hmac.compare_digest()` requires both arguments to be strings (or both bytes). The existing code
|
||||
already works with strings, so no type conversion is needed.
|
||||
requirements:
|
||||
- "REQ-002"
|
||||
- "REQ-007"
|
||||
dependencies: []
|
||||
suggested_role: "python"
|
||||
acceptance_criteria:
|
||||
- "All API key comparisons in `api/auth.py` use `hmac.compare_digest()`"
|
||||
- "All credential comparisons in `api/metrics.py` use `hmac.compare_digest()`"
|
||||
- "`hmac` is imported in both files"
|
||||
- "Valid API keys are accepted and invalid keys are rejected (no behavior change)"
|
||||
estimated_complexity: "small"
|
||||
files_affected:
|
||||
- "src/meshcore_hub/api/auth.py"
|
||||
- "src/meshcore_hub/api/metrics.py"
|
||||
|
||||
- id: "TASK-003"
|
||||
title: "Add WEB_TRUSTED_PROXY_HOSTS configuration setting"
|
||||
description: |
|
||||
Add a `web_trusted_proxy_hosts` field to the web settings in `src/meshcore_hub/common/config.py`.
|
||||
|
||||
1. In the `WebSettings` class (or the relevant settings class containing web config), add:
|
||||
```python
|
||||
web_trusted_proxy_hosts: str = Field(default="*", description="Comma-separated list of trusted proxy hosts or '*' for all")
|
||||
```
|
||||
2. The field should accept a string value. The `ProxyHeadersMiddleware` in uvicorn accepts either `"*"` or a list of strings.
|
||||
If the value is `"*"`, pass it directly. Otherwise, split on commas and strip whitespace to produce a list.
|
||||
|
||||
This task only adds the configuration field. The middleware integration and startup warning are in TASK-004.
|
||||
requirements:
|
||||
- "REQ-003"
|
||||
- "REQ-006"
|
||||
dependencies: []
|
||||
suggested_role: "python"
|
||||
acceptance_criteria:
|
||||
- "A `web_trusted_proxy_hosts` setting exists in the configuration with default value `*`"
|
||||
- "The setting can be configured via the `WEB_TRUSTED_PROXY_HOSTS` environment variable"
|
||||
- "The setting accepts `*` or a comma-separated list of hostnames/IPs"
|
||||
estimated_complexity: "small"
|
||||
files_affected:
|
||||
- "src/meshcore_hub/common/config.py"
|
||||
|
||||
- id: "TASK-004"
|
||||
title: "Integrate trusted proxy hosts into web app middleware and add startup warning"
|
||||
description: |
|
||||
Update `src/meshcore_hub/web/app.py` to use the new `WEB_TRUSTED_PROXY_HOSTS` setting and emit a
|
||||
startup warning when using the insecure default.
|
||||
|
||||
1. Find the `ProxyHeadersMiddleware` addition (line ~239):
|
||||
```python
|
||||
app.add_middleware(ProxyHeadersMiddleware, trusted_hosts="*")
|
||||
```
|
||||
Replace the hardcoded `"*"` with the configured value. If the config value is `"*"`, pass `"*"`.
|
||||
Otherwise, split the comma-separated string into a list of strings.
|
||||
|
||||
2. Add a startup warning (in the app factory or lifespan) when `WEB_ADMIN_ENABLED=true` and
|
||||
`WEB_TRUSTED_PROXY_HOSTS` is `"*"`:
|
||||
```python
|
||||
import logging
|
||||
logger = logging.getLogger(__name__)
|
||||
if settings.web_admin_enabled and settings.web_trusted_proxy_hosts == "*":
|
||||
logger.warning(
|
||||
"WEB_ADMIN_ENABLED is true but WEB_TRUSTED_PROXY_HOSTS is '*' (trust all). "
|
||||
"Consider restricting to your reverse proxy IP for production deployments."
|
||||
)
|
||||
```
|
||||
|
||||
3. Verify that the `_is_authenticated_proxy_request` function still accepts `X-Forwarded-User`,
|
||||
`X-Auth-Request-User`, and `Authorization: Basic` headers — do not modify that function.
|
||||
requirements:
|
||||
- "REQ-003"
|
||||
- "REQ-006"
|
||||
- "REQ-007"
|
||||
dependencies:
|
||||
- "TASK-003"
|
||||
suggested_role: "python"
|
||||
acceptance_criteria:
|
||||
- "`ProxyHeadersMiddleware` uses the configured `trusted_hosts` value instead of hardcoded `*`"
|
||||
- "A warning is logged at startup when admin is enabled and trusted hosts is `*`"
|
||||
- "The warning recommends restricting trusted hosts to the proxy IP"
|
||||
- "`_is_authenticated_proxy_request` still accepts all three header types"
|
||||
- "Setting `WEB_TRUSTED_PROXY_HOSTS` to a specific IP restricts proxy header trust"
|
||||
estimated_complexity: "medium"
|
||||
files_affected:
|
||||
- "src/meshcore_hub/web/app.py"
|
||||
|
||||
- id: "TASK-005"
|
||||
title: "Escape config JSON in template script block to prevent XSS breakout"
|
||||
description: |
|
||||
Prevent XSS via `</script>` breakout in the config JSON template injection in `src/meshcore_hub/web/app.py`.
|
||||
|
||||
In the `_build_config_json` function (or wherever `config_json` is prepared for the template, around
|
||||
line 183), after calling `json.dumps(config)`, escape `</` sequences:
|
||||
```python
|
||||
config_json = json.dumps(config).replace("</", "<\\/")
|
||||
```
|
||||
|
||||
This prevents a config value containing `</script><script>alert(1)</script>` from breaking out of the
|
||||
`<script>` block in `spa.html` (line ~188: `window.__APP_CONFIG__ = {{ config_json|safe }};`).
|
||||
|
||||
The `|safe` filter in the template remains unchanged — the escaping happens in Python before the value
|
||||
reaches Jinja2. The SPA client-side JavaScript can parse JSON containing `<\/` sequences because this
|
||||
is valid JSON per the spec.
|
||||
requirements:
|
||||
- "REQ-004"
|
||||
- "REQ-006"
|
||||
dependencies: []
|
||||
suggested_role: "python"
|
||||
acceptance_criteria:
|
||||
- "`config_json` is escaped by replacing `</` with `<\\/` before template rendering"
|
||||
- "The `|safe` filter continues to be used in the template"
|
||||
- "A config value containing `</script><script>alert(1)</script>` does not execute JavaScript"
|
||||
- "The SPA application correctly parses the escaped config JSON"
|
||||
- "Normal config values without special characters render unchanged"
|
||||
estimated_complexity: "small"
|
||||
files_affected:
|
||||
- "src/meshcore_hub/web/app.py"
|
||||
|
||||
- id: "TASK-006"
|
||||
title: "Fix stored XSS in admin node-tags page"
|
||||
description: |
|
||||
Sanitize API-sourced data in `src/meshcore_hub/web/static/js/spa/pages/admin/node-tags.js` to prevent
|
||||
stored XSS.
|
||||
|
||||
Three locations need fixing:
|
||||
|
||||
1. **Line ~243** — `unsafeHTML()` with nodeName in copy-all confirmation:
|
||||
```javascript
|
||||
<p class="mb-4">${unsafeHTML(t('common.copy_all_entity_description', { count: tags.length, entity: t('entities.tags').toLowerCase(), name: nodeName }))}</p>
|
||||
```
|
||||
Replace `unsafeHTML()` with safe rendering. Either escape `nodeName` with `escapeHtml()` before
|
||||
passing to `t()`, or use `textContent`-based rendering.
|
||||
|
||||
2. **Line ~272** — `unsafeHTML()` with nodeName in delete-all confirmation:
|
||||
```javascript
|
||||
<p class="mb-4">${unsafeHTML(t('common.delete_all_entity_confirm', { count: tags.length, entity: t('entities.tags').toLowerCase(), name: nodeName }))}</p>
|
||||
```
|
||||
Same fix as above.
|
||||
|
||||
3. **Line ~454** — `innerHTML` with tag key in delete confirmation:
|
||||
```javascript
|
||||
container.querySelector('#delete_tag_confirm_message').innerHTML = confirmMsg;
|
||||
```
|
||||
where `confirmMsg` is built with `activeTagKey` interpolated into an HTML span. Replace `innerHTML`
|
||||
with `textContent`, or escape `activeTagKey` with `escapeHtml()` before interpolation.
|
||||
|
||||
Import `escapeHtml` from `../components.js` if not already imported. The function escapes `<`, `>`,
|
||||
`&`, `"`, and `'` characters using DOM textContent.
|
||||
requirements:
|
||||
- "REQ-005"
|
||||
- "REQ-006"
|
||||
dependencies: []
|
||||
suggested_role: "frontend"
|
||||
acceptance_criteria:
|
||||
- "Node names in node-tags.js are escaped before HTML rendering"
|
||||
- "Tag keys in node-tags.js are escaped before HTML rendering"
|
||||
- "All `unsafeHTML()` calls on API-sourced data are replaced with safe alternatives"
|
||||
- "All `innerHTML` assignments of API-sourced data are replaced with safe alternatives"
|
||||
- "A node name containing `<img src=x onerror=alert(1)>` renders as text"
|
||||
- "Normal names without special characters display correctly"
|
||||
estimated_complexity: "medium"
|
||||
files_affected:
|
||||
- "src/meshcore_hub/web/static/js/spa/pages/admin/node-tags.js"
|
||||
|
||||
- id: "TASK-007"
|
||||
title: "Fix stored XSS in admin members page"
|
||||
description: |
|
||||
Sanitize API-sourced data in `src/meshcore_hub/web/static/js/spa/pages/admin/members.js` to prevent
|
||||
stored XSS.
|
||||
|
||||
**Line ~309** — `innerHTML` with memberName in delete confirmation:
|
||||
```javascript
|
||||
container.querySelector('#delete_confirm_message').innerHTML = confirmMsg;
|
||||
```
|
||||
where `confirmMsg` is built from `t('common.delete_entity_confirm', { entity: ..., name: memberName })`.
|
||||
`memberName` comes from `row.dataset.memberName` which is API-sourced data.
|
||||
|
||||
Fix by escaping `memberName` with `escapeHtml()` before passing to `t()`, or replace `innerHTML` with
|
||||
`textContent`.
|
||||
|
||||
Import `escapeHtml` from `../components.js` if not already imported.
|
||||
requirements:
|
||||
- "REQ-005"
|
||||
- "REQ-006"
|
||||
dependencies: []
|
||||
suggested_role: "frontend"
|
||||
acceptance_criteria:
|
||||
- "Member names in members.js are escaped before HTML rendering"
|
||||
- "The `innerHTML` assignment of API-sourced data is replaced with a safe alternative"
|
||||
- "A member name containing `<script>alert(1)</script>` renders as text"
|
||||
- "Normal member names display correctly"
|
||||
estimated_complexity: "small"
|
||||
files_affected:
|
||||
- "src/meshcore_hub/web/static/js/spa/pages/admin/members.js"
|
||||
|
||||
- id: "TASK-008"
|
||||
title: "Write tests for legacy dashboard endpoint removal"
|
||||
description: |
|
||||
Add or update tests in `tests/test_api/` to verify that the legacy HTML dashboard endpoint is removed
|
||||
while JSON sub-routes remain functional.
|
||||
|
||||
Tests to add/update:
|
||||
1. `GET /api/v1/dashboard/` returns 404 or 405 (no longer serves HTML).
|
||||
2. `GET /api/v1/dashboard/stats` returns 200 with valid JSON when authenticated.
|
||||
3. `GET /api/v1/dashboard/activity` returns 200 with valid JSON when authenticated.
|
||||
4. `GET /api/v1/dashboard/message-activity` returns 200 with valid JSON when authenticated.
|
||||
5. `GET /api/v1/dashboard/node-count` returns 200 with valid JSON when authenticated.
|
||||
|
||||
Use the existing test fixtures and patterns from `tests/test_api/`. Check `tests/conftest.py` for
|
||||
available fixtures (test client, db session, auth headers).
|
||||
requirements:
|
||||
- "REQ-001"
|
||||
- "REQ-006"
|
||||
dependencies:
|
||||
- "TASK-001"
|
||||
suggested_role: "python"
|
||||
acceptance_criteria:
|
||||
- "Test confirms `GET /api/v1/dashboard/` returns 404 or 405"
|
||||
- "Tests confirm all four JSON sub-routes return valid JSON with authentication"
|
||||
- "All tests pass"
|
||||
estimated_complexity: "small"
|
||||
files_affected:
|
||||
- "tests/test_api/test_dashboard.py"
|
||||
|
||||
- id: "TASK-009"
|
||||
title: "Write tests for constant-time API key comparison"
|
||||
description: |
|
||||
Add or update tests in `tests/test_api/` to verify that authentication still works correctly after
|
||||
switching to `hmac.compare_digest()`.
|
||||
|
||||
Tests to add/update:
|
||||
1. Valid read key is accepted by read-protected endpoints.
|
||||
2. Valid admin key is accepted by admin-protected endpoints.
|
||||
3. Invalid keys are rejected with 401/403.
|
||||
4. Valid admin key also grants read access.
|
||||
5. Metrics endpoint accepts valid credentials and rejects invalid ones (if metrics auth is testable).
|
||||
|
||||
These tests verify no behavioral regression from the `==` to `hmac.compare_digest()` change.
|
||||
Use existing test patterns and fixtures from `tests/test_api/`.
|
||||
requirements:
|
||||
- "REQ-002"
|
||||
- "REQ-007"
|
||||
dependencies:
|
||||
- "TASK-002"
|
||||
suggested_role: "python"
|
||||
acceptance_criteria:
|
||||
- "Tests confirm valid read key is accepted"
|
||||
- "Tests confirm valid admin key is accepted"
|
||||
- "Tests confirm invalid keys are rejected"
|
||||
- "Tests confirm metrics auth works correctly"
|
||||
- "All tests pass"
|
||||
estimated_complexity: "small"
|
||||
files_affected:
|
||||
- "tests/test_api/test_auth.py"
|
||||
|
||||
- id: "TASK-010"
|
||||
title: "Write tests for trusted proxy hosts configuration and startup warning"
|
||||
description: |
|
||||
Add tests to verify the `WEB_TRUSTED_PROXY_HOSTS` configuration setting and the startup warning.
|
||||
|
||||
Tests to add:
|
||||
1. Default value of `WEB_TRUSTED_PROXY_HOSTS` is `*`.
|
||||
2. Setting `WEB_TRUSTED_PROXY_HOSTS` to a specific IP is correctly parsed.
|
||||
3. Setting `WEB_TRUSTED_PROXY_HOSTS` to a comma-separated list is correctly parsed into a list.
|
||||
4. A warning is logged when `WEB_ADMIN_ENABLED=true` and `WEB_TRUSTED_PROXY_HOSTS` is `*`.
|
||||
5. No warning is logged when `WEB_TRUSTED_PROXY_HOSTS` is set to a specific value.
|
||||
|
||||
Place config tests in `tests/test_common/` and web app tests in `tests/test_web/`.
|
||||
requirements:
|
||||
- "REQ-003"
|
||||
- "REQ-006"
|
||||
dependencies:
|
||||
- "TASK-003"
|
||||
- "TASK-004"
|
||||
suggested_role: "python"
|
||||
acceptance_criteria:
|
||||
- "Tests confirm default value is `*`"
|
||||
- "Tests confirm specific IP/list parsing works"
|
||||
- "Tests confirm startup warning is emitted with wildcard default"
|
||||
- "Tests confirm no warning when specific hosts are configured"
|
||||
- "All tests pass"
|
||||
estimated_complexity: "medium"
|
||||
files_affected:
|
||||
- "tests/test_common/test_config.py"
|
||||
- "tests/test_web/test_app.py"
|
||||
|
||||
- id: "TASK-011"
|
||||
title: "Write tests for config JSON script block escaping"
|
||||
description: |
|
||||
Add tests in `tests/test_web/` to verify that the config JSON escaping prevents XSS breakout.
|
||||
|
||||
Tests to add:
|
||||
1. A config value containing `</script><script>alert(1)</script>` is escaped to `<\/script>...` in
|
||||
the rendered HTML.
|
||||
2. A config value without special characters renders unchanged.
|
||||
3. The escaped JSON is still valid and parseable by `json.loads()` (after un-escaping `<\/` back to `</`
|
||||
if needed, though `json.loads` handles `<\/` fine).
|
||||
|
||||
Test by calling the config JSON builder function directly or by checking the rendered template output.
|
||||
requirements:
|
||||
- "REQ-004"
|
||||
- "REQ-006"
|
||||
dependencies:
|
||||
- "TASK-005"
|
||||
suggested_role: "python"
|
||||
acceptance_criteria:
|
||||
- "Test confirms `</script>` in config values is escaped to `<\\/script>`"
|
||||
- "Test confirms normal config values are unaffected"
|
||||
- "Test confirms escaped JSON is still valid and parseable"
|
||||
- "All tests pass"
|
||||
estimated_complexity: "small"
|
||||
files_affected:
|
||||
- "tests/test_web/test_app.py"
|
||||
|
||||
- id: "TASK-012"
|
||||
title: "Update documentation for WEB_TRUSTED_PROXY_HOSTS setting"
|
||||
description: |
|
||||
Update project documentation to document the new `WEB_TRUSTED_PROXY_HOSTS` environment variable.
|
||||
|
||||
Files to update:
|
||||
|
||||
1. **README.md** — Add `WEB_TRUSTED_PROXY_HOSTS` to the environment variables table with description:
|
||||
"Comma-separated list of trusted proxy hosts for admin authentication headers. Default: `*` (all hosts).
|
||||
Recommended: set to your reverse proxy IP in production."
|
||||
|
||||
2. **AGENTS.md** — Add `WEB_TRUSTED_PROXY_HOSTS` to the Environment Variables section with the same description.
|
||||
|
||||
3. **PLAN.md** — If there is a configuration section, add the new variable there as well.
|
||||
|
||||
Ensure the documentation notes:
|
||||
- Default is `*` for backward compatibility
|
||||
- A startup warning is emitted when using the default with admin enabled
|
||||
- Operators should set this to their reverse proxy IP in production
|
||||
requirements:
|
||||
- "REQ-003"
|
||||
- "REQ-006"
|
||||
dependencies:
|
||||
- "TASK-003"
|
||||
- "TASK-004"
|
||||
suggested_role: "docs"
|
||||
acceptance_criteria:
|
||||
- "`WEB_TRUSTED_PROXY_HOSTS` is documented in README.md"
|
||||
- "`WEB_TRUSTED_PROXY_HOSTS` is documented in AGENTS.md"
|
||||
- "Documentation notes the default value, startup warning, and production recommendation"
|
||||
estimated_complexity: "small"
|
||||
files_affected:
|
||||
- "README.md"
|
||||
- "AGENTS.md"
|
||||
- "PLAN.md"
|
||||
81
.plans/2026/03/17/01-multibyte-support/changelog.md
Normal file
81
.plans/2026/03/17/01-multibyte-support/changelog.md
Normal file
@@ -0,0 +1,81 @@
|
||||
## TASK-001: Verify meshcore_py v2.3.0+ backwards compatibility
|
||||
**Status:** completed
|
||||
### Files Created
|
||||
_(none)_
|
||||
### Files Modified
|
||||
_(none)_
|
||||
### Notes
|
||||
Research-only task. meshcore_py v2.3.0 handles multibyte path hashes transparently at the protocol level. Path hash size is self-describing in the wire format (upper 2 bits of path length byte encode hash size). The interface receiver, sender, and device wrapper pass event payloads through without manipulation, so no code changes are needed. pyproject.toml dependency confirmed at meshcore>=2.3.0.
|
||||
---
|
||||
|
||||
## TASK-002: Update _normalize_hash_list to accept variable-length hex strings
|
||||
**Status:** completed
|
||||
### Files Created
|
||||
_(none)_
|
||||
### Files Modified
|
||||
- `src/meshcore_hub/collector/letsmesh_normalizer.py`
|
||||
### Notes
|
||||
Changed length validation from `if len(token) != 2` to `if len(token) < 2 or len(token) % 2 != 0`. Updated docstring to describe variable-length hex hash support. Existing hex validation and uppercase normalization unchanged. All 98 collector tests pass.
|
||||
---
|
||||
|
||||
## TASK-003: Update Pydantic schema descriptions for path_hashes fields
|
||||
**Status:** completed
|
||||
### Files Created
|
||||
_(none)_
|
||||
### Files Modified
|
||||
- `src/meshcore_hub/common/schemas/events.py`
|
||||
- `src/meshcore_hub/common/schemas/messages.py`
|
||||
- `src/meshcore_hub/common/models/trace_path.py`
|
||||
### Notes
|
||||
Updated TraceDataEvent.path_hashes, TracePathRead.path_hashes, and TracePath model docstring to reflect variable-length hex strings. No Pydantic validators needed changes - both schemas use Optional[list[str]] with no per-element length constraints.
|
||||
---
|
||||
|
||||
## TASK-004: Update SCHEMAS.md documentation for multibyte path hashes
|
||||
**Status:** completed
|
||||
### Files Created
|
||||
_(none)_
|
||||
### Files Modified
|
||||
- `SCHEMAS.md`
|
||||
### Notes
|
||||
Updated path_hashes field description from "2-character" to variable-length hex. Updated example to include mixed-length hashes ["4a", "b3fa", "02"]. Added firmware v1.14 compatibility note.
|
||||
---
|
||||
|
||||
## TASK-008: Verify web dashboard trace path display handles variable-length hashes
|
||||
**Status:** completed
|
||||
### Files Created
|
||||
_(none)_
|
||||
### Files Modified
|
||||
_(none)_
|
||||
### Notes
|
||||
Verification-only task. The web dashboard SPA has no trace path page and no JavaScript/CSS code referencing path_hash or pathHash. Trace path data is only served by the REST API which returns path_hashes as list[str] with no length constraints. No changes needed.
|
||||
---
|
||||
|
||||
## TASK-005: Write tests for multibyte path hash normalizer
|
||||
**Status:** completed
|
||||
### Files Created
|
||||
- `tests/test_collector/test_letsmesh_normalizer.py`
|
||||
### Files Modified
|
||||
- `tests/test_collector/test_subscriber.py`
|
||||
### Notes
|
||||
Created 12 unit tests for _normalize_hash_list covering all 7 required scenarios plus edge cases. Added 2 integration tests to test_subscriber.py verifying multibyte path hashes flow through the full collector pipeline. All 35 collector tests pass.
|
||||
---
|
||||
|
||||
## TASK-006: Write tests for database round-trip of multibyte path hashes
|
||||
**Status:** completed
|
||||
### Files Created
|
||||
_(none)_
|
||||
### Files Modified
|
||||
- `tests/test_common/test_models.py`
|
||||
### Notes
|
||||
Added 2 new test methods to TestTracePathModel: test_multibyte_path_hashes_round_trip and test_mixed_length_path_hashes_round_trip. Verified JSON column handles variable-length strings natively. All 10 model tests pass. No Alembic migration needed.
|
||||
---
|
||||
|
||||
## TASK-007: Write tests for API trace path responses with multibyte hashes
|
||||
**Status:** completed
|
||||
### Files Created
|
||||
_(none)_
|
||||
### Files Modified
|
||||
- `tests/test_api/test_trace_paths.py`
|
||||
### Notes
|
||||
Added TestMultibytePathHashes class with 2 tests: list endpoint with multibyte hashes and detail endpoint with mixed-length hashes. All 9 API trace path tests pass.
|
||||
---
|
||||
146
.plans/2026/03/17/01-multibyte-support/prd.md
Normal file
146
.plans/2026/03/17/01-multibyte-support/prd.md
Normal file
@@ -0,0 +1,146 @@
|
||||
# Product Requirements Document
|
||||
|
||||
> Source: `.plans/2026/03/17/01-multibyte-support/prompt.md`
|
||||
|
||||
## Project Overview
|
||||
|
||||
MeshCore Hub must be updated to support multibyte path hashes introduced in MeshCore firmware v1.14 and the meshcore_py v2.3.0 Python bindings. Path hashes — node identifiers embedded in trace and route data — were previously fixed at 1 byte (2 hex characters) per hop but can now be multiple bytes, allowing longer repeater IDs at the cost of reduced maximum hops. The update must maintain backwards compatibility with nodes running older single-byte firmware.
|
||||
|
||||
## Goals
|
||||
|
||||
- Support variable-length (multibyte) path hashes throughout the data pipeline: interface → MQTT → collector → database → API → web dashboard.
|
||||
- Maintain backwards compatibility so single-byte path hashes from older firmware nodes continue to work without modification.
|
||||
- Update documentation and schemas to accurately describe the new variable-length path hash format.
|
||||
|
||||
## Functional Requirements
|
||||
|
||||
### REQ-001: Accept Variable-Length Path Hashes in Collector
|
||||
|
||||
**Description:** The collector's event handlers and normalizer must accept path hash strings of any even length (not just 2-character strings). Path hashes arriving from both the meshcore_py interface and LetsMesh-compatible ingest must be processed correctly regardless of byte length.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
|
||||
- [ ] Path hashes with 2-character values (legacy single-byte) are accepted and stored correctly
|
||||
- [ ] Path hashes with 4+ character values (multibyte) are accepted and stored correctly
|
||||
- [ ] Mixed-length path hash arrays (e.g. `["4a", "b3fa", "02"]`) are accepted when the mesh contains nodes with different firmware versions
|
||||
- [ ] The LetsMesh normalizer handles multibyte `pathHashes` values from decoded payloads
|
||||
|
||||
### REQ-002: Update Pydantic Schema Validation for Path Hashes
|
||||
|
||||
**Description:** The `path_hashes` field in event and message Pydantic schemas currently describes values as "2-character node hash identifiers". The schema description and any validation constraints must be updated to permit variable-length hex strings.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
|
||||
- [ ] `TraceDataEvent.path_hashes` field description reflects variable-length hex strings
|
||||
- [ ] `MessageEventBase.path_hashes` field description reflects variable-length hex strings (if applicable)
|
||||
- [ ] No schema validation rejects path hash strings longer than 2 characters
|
||||
|
||||
### REQ-003: Verify Database Storage Compatibility
|
||||
|
||||
**Description:** The `path_hashes` column on the `trace_paths` table uses a JSON column type. Confirm that variable-length path hash strings are stored and retrieved correctly without requiring a schema migration.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
|
||||
- [ ] Multibyte path hash arrays are round-tripped correctly through SQLAlchemy JSON column (store and retrieve)
|
||||
- [ ] No Alembic migration is required (JSON column already supports arbitrary string lengths)
|
||||
|
||||
### REQ-004: Update API Responses for Variable-Length Path Hashes
|
||||
|
||||
**Description:** The trace paths API must return multibyte path hashes faithfully. API response schemas and any serialization logic must not truncate or assume a fixed length.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
|
||||
- [ ] `GET /trace-paths` returns multibyte path hash arrays as-is from the database
|
||||
- [ ] `GET /trace-paths/{id}` returns multibyte path hash arrays as-is from the database
|
||||
- [ ] API response examples in documentation reflect variable-length path hashes
|
||||
|
||||
### REQ-005: Update Web Dashboard Trace/Path Display
|
||||
|
||||
**Description:** If the web dashboard displays path hashes (e.g. in trace path views), the rendering must handle variable-length strings without layout breakage or truncation.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
|
||||
- [ ] Trace path views display multibyte path hashes correctly
|
||||
- [ ] No fixed-width formatting assumes 2-character hash strings
|
||||
|
||||
### REQ-006: Verify meshcore_py Library Compatibility
|
||||
|
||||
**Description:** Confirm that the meshcore_py v2.3.0+ library handles backwards compatibility with single-byte firmware nodes transparently, so that MeshCore Hub does not need to implement compatibility logic itself.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
|
||||
- [ ] meshcore_py v2.3.0+ is confirmed to handle mixed single-byte and multibyte path hashes at the protocol level
|
||||
- [ ] The interface receiver and sender components work with the updated library without code changes beyond the dependency version bump (or with minimal changes if the library API changed)
|
||||
|
||||
## Non-Functional Requirements
|
||||
|
||||
### REQ-007: Backwards Compatibility
|
||||
|
||||
**Category:** Reliability
|
||||
|
||||
**Description:** The system must continue to operate correctly when receiving events from nodes running older (single-byte) firmware. No data loss or processing errors may occur for legacy path hash formats.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
|
||||
- [ ] Existing test cases with 2-character path hashes continue to pass without modification
|
||||
- [ ] New test cases with multibyte path hashes pass alongside legacy test cases
|
||||
- [ ] No database migration is required that would break rollback to the previous version
|
||||
|
||||
### REQ-008: Documentation Accuracy
|
||||
|
||||
**Category:** Maintainability
|
||||
|
||||
**Description:** All documentation referencing path hash format must be updated to reflect the variable-length nature of multibyte path hashes.
|
||||
|
||||
**Acceptance Criteria:**
|
||||
|
||||
- [ ] `SCHEMAS.md` path hash descriptions updated from "2-character" to "variable-length hex string"
|
||||
- [ ] Code docstrings and field descriptions in models/schemas updated
|
||||
- [ ] Example payloads in documentation include at least one multibyte path hash example
|
||||
|
||||
## Technical Constraints and Assumptions
|
||||
|
||||
### Constraints
|
||||
|
||||
- Python 3.13+ (specified by project)
|
||||
- meshcore_py >= 2.3.0 (already set in `pyproject.toml`)
|
||||
- SQLite with JSON column for path hash storage (existing schema)
|
||||
- No breaking changes to the REST API response format
|
||||
|
||||
### Assumptions
|
||||
|
||||
- The meshcore_py library handles protocol-level backwards compatibility for multibyte path hashes, so MeshCore Hub only needs to ensure its data pipeline accepts variable-length strings
|
||||
- Path hashes are always valid hex strings (even number of characters)
|
||||
- The JSON column type in SQLite/SQLAlchemy does not impose length restrictions on individual array element strings
|
||||
- The `pyproject.toml` dependency has already been bumped to `meshcore>=2.3.0`
|
||||
|
||||
## Scope
|
||||
|
||||
### In Scope
|
||||
|
||||
- Updating Pydantic schema descriptions and validation for variable-length path hashes
|
||||
- Updating collector handlers and normalizer for multibyte path hashes
|
||||
- Verifying database storage compatibility (no migration expected)
|
||||
- Verifying API response compatibility
|
||||
- Updating web dashboard path hash display if applicable
|
||||
- Updating `SCHEMAS.md` and code documentation
|
||||
- Adding/updating tests for multibyte path hashes
|
||||
- Confirming meshcore_py library handles backwards compatibility
|
||||
|
||||
### Out of Scope
|
||||
|
||||
- MeshCore firmware changes or device-side configuration
|
||||
- Adding UI controls for selecting single-byte vs. multibyte mode
|
||||
- Performance optimization of path hash processing
|
||||
- Changes to MQTT topic structure or message format
|
||||
- LetsMesh ingest protocol changes (beyond accepting multibyte values that LetsMesh already provides)
|
||||
|
||||
## Suggested Tech Stack
|
||||
|
||||
| Layer | Technology | Rationale |
|
||||
|-------|-----------|-----------|
|
||||
| MeshCore bindings | meshcore_py >= 2.3.0 | Specified by prompt; provides multibyte path hash support |
|
||||
| Validation | Pydantic v2 | Existing stack — schema descriptions updated |
|
||||
| Database | SQLAlchemy 2.0 + SQLite JSON | Existing stack — no migration needed |
|
||||
| API | FastAPI | Existing stack — no changes to framework |
|
||||
| Testing | pytest + pytest-asyncio | Existing stack — new test cases for multibyte |
|
||||
17
.plans/2026/03/17/01-multibyte-support/prompt.md
Normal file
17
.plans/2026/03/17/01-multibyte-support/prompt.md
Normal file
@@ -0,0 +1,17 @@
|
||||
# Phase: 01-multibyte-support
|
||||
|
||||
## Overview
|
||||
|
||||
The latest MeshCore firmware (v1.14) has introduced multibyte support for multi-byte path hashes. The latest version of the MeshCore Python bindings (meshcore_py) has been updated to use this. This allows longer repeater IDs per hop, but reduces the maximum allowed hops. Nodes running older firmware only support 1-byte path hashes and will not receive messages if other nodes use multibyte path hashes.
|
||||
|
||||
## Goals
|
||||
|
||||
* Update Receiver/Sender component to use latest version of MeshCore Python bindings that support multibyte path hash handling.
|
||||
|
||||
## Requirements
|
||||
|
||||
* Must remain backwards compatible with previous version. Confirm whether this is handled by the Python library.
|
||||
|
||||
## References
|
||||
|
||||
* https://github.com/meshcore-dev/meshcore_py/releases/tag/v2.3.0
|
||||
@@ -0,0 +1,19 @@
|
||||
# Code review round 001
|
||||
# Phase: .plans/2026/03/17/01-multibyte-support
|
||||
# Scope: full
|
||||
# Generated by: /jp-codereview
|
||||
|
||||
issues: []
|
||||
|
||||
summary:
|
||||
total_issues: 0
|
||||
critical: 0
|
||||
major: 0
|
||||
minor: 0
|
||||
by_category:
|
||||
integration: 0
|
||||
architecture: 0
|
||||
security: 0
|
||||
duplication: 0
|
||||
error-handling: 0
|
||||
style: 0
|
||||
57
.plans/2026/03/17/01-multibyte-support/reviews/prd.md
Normal file
57
.plans/2026/03/17/01-multibyte-support/reviews/prd.md
Normal file
@@ -0,0 +1,57 @@
|
||||
# PRD Review
|
||||
|
||||
> Phase: `.plans/2026/03/17/01-multibyte-support`
|
||||
> PRD: `.plans/2026/03/17/01-multibyte-support/prd.md`
|
||||
> Prompt: `.plans/2026/03/17/01-multibyte-support/prompt.md`
|
||||
|
||||
## Verdict: PASS
|
||||
|
||||
The PRD comprehensively addresses the narrow scope of the original prompt. All prompt items are covered by specific requirements with testable acceptance criteria. The PRD appropriately expands the prompt's Receiver/Sender focus to cover the full data pipeline (collector, schemas, database, API, web), which is necessary for end-to-end multibyte support. No contradictions, feasibility concerns, or scope inconsistencies were found.
|
||||
|
||||
## Coverage Assessment
|
||||
|
||||
| Prompt Item | PRD Section | Covered? | Notes |
|
||||
|---|---|---|---|
|
||||
| Update Receiver/Sender to use latest meshcore_py with multibyte support | REQ-006 | Yes | Covered by library compatibility verification; receiver/sender work with updated bindings |
|
||||
| Must remain backwards compatible with previous version | REQ-007 | Yes | Explicit non-functional requirement with 3 testable acceptance criteria |
|
||||
| Confirm whether backwards compat is handled by the Python library | REQ-006 | Yes | First AC specifically calls for confirming library-level protocol compatibility |
|
||||
| Reference to meshcore_py v2.3.0 release | Constraints, Tech Stack | Yes | Noted in constraints and suggested tech stack table |
|
||||
|
||||
**Coverage summary:** 4 of 4 prompt items fully covered, 0 partially covered, 0 not covered.
|
||||
|
||||
## Requirement Evaluation
|
||||
|
||||
All requirements passed evaluation. Minor observations:
|
||||
|
||||
### REQ-006: Verify meshcore_py Library Compatibility
|
||||
|
||||
- **Implementability:** Pass
|
||||
- **Testability:** Pass -- though the first AC ("confirmed to handle...at the protocol level") is a verification/research task rather than an automated test, this is appropriate given the prompt explicitly asks to confirm library behavior
|
||||
- **Completeness:** Pass
|
||||
- **Consistency:** Pass
|
||||
|
||||
## Structural Issues
|
||||
|
||||
### Contradictions
|
||||
|
||||
None found.
|
||||
|
||||
### Ambiguities
|
||||
|
||||
None found. The PRD is appropriately specific for the scope of work.
|
||||
|
||||
### Missing Edge Cases
|
||||
|
||||
None significant. The PRD covers the key edge case of mixed-length path hash arrays from heterogeneous firmware networks (REQ-001 AC3).
|
||||
|
||||
### Feasibility Concerns
|
||||
|
||||
None. The changes are primarily documentation/description updates and verification tasks. The JSON column type inherently supports variable-length strings, and the meshcore_py dependency is already bumped.
|
||||
|
||||
### Scope Inconsistencies
|
||||
|
||||
None. The PRD's scope appropriately extends beyond the prompt's Receiver/Sender focus to cover downstream components (collector, API, web) that also handle path hashes. This is a necessary expansion, not scope creep.
|
||||
|
||||
## Action Items
|
||||
|
||||
No action items -- verdict is PASS.
|
||||
89
.plans/2026/03/17/01-multibyte-support/reviews/tasks.md
Normal file
89
.plans/2026/03/17/01-multibyte-support/reviews/tasks.md
Normal file
@@ -0,0 +1,89 @@
|
||||
# Task Review
|
||||
|
||||
> Phase: `.plans/2026/03/17/01-multibyte-support`
|
||||
> Tasks: `.plans/2026/03/17/01-multibyte-support/tasks.yaml`
|
||||
> PRD: `.plans/2026/03/17/01-multibyte-support/prd.md`
|
||||
|
||||
## Verdict: PASS
|
||||
|
||||
The task list is structurally sound, correctly ordered, and fully covers all 8 PRD requirements. The dependency graph is a valid DAG with no cycles or invalid references. No ordering issues were found — no task references files that should be produced by a task outside its dependency chain. All tasks have valid roles, complexity values, and complete fields. The task breakdown is appropriate for the narrow scope of this phase.
|
||||
|
||||
## Dependency Validation
|
||||
|
||||
### Reference Validity
|
||||
|
||||
All dependency references are valid. Every task ID in every `dependencies` list corresponds to an existing task in the inventory.
|
||||
|
||||
### DAG Validation
|
||||
|
||||
The dependency graph is a valid DAG with no cycles. Maximum dependency depth is 1 (two test tasks depend on one implementation task each).
|
||||
|
||||
### Orphan Tasks
|
||||
|
||||
The following tasks are never referenced as dependencies by other tasks:
|
||||
|
||||
- **TASK-001** (Verify meshcore_py compatibility) — terminal verification task, expected
|
||||
- **TASK-004** (Update SCHEMAS.md) — terminal documentation task, expected
|
||||
- **TASK-005** (Tests for normalizer) — terminal test task, expected
|
||||
- **TASK-006** (Tests for DB round-trip) — terminal test task, expected
|
||||
- **TASK-007** (Tests for API responses) — terminal test task, expected
|
||||
- **TASK-008** (Verify web dashboard) — terminal verification task, expected
|
||||
|
||||
All orphan tasks are leaf nodes (tests, docs, or verification tasks). No missing integration points.
|
||||
|
||||
## Ordering Check
|
||||
|
||||
No ordering issues detected. No task modifies a file that is also modified by another task outside its dependency chain. The `files_affected` sets across all tasks are disjoint except where proper dependency relationships exist.
|
||||
|
||||
## Coverage Check
|
||||
|
||||
### Uncovered Requirements
|
||||
|
||||
All PRD requirements are covered.
|
||||
|
||||
### Phantom References
|
||||
|
||||
No phantom references detected. Every requirement ID referenced in tasks exists in the PRD.
|
||||
|
||||
**Coverage summary:** 8 of 8 PRD requirements covered by tasks.
|
||||
|
||||
| Requirement | Covered By |
|
||||
|---|---|
|
||||
| REQ-001 | TASK-002, TASK-005 |
|
||||
| REQ-002 | TASK-003 |
|
||||
| REQ-003 | TASK-006 |
|
||||
| REQ-004 | TASK-007 |
|
||||
| REQ-005 | TASK-008 |
|
||||
| REQ-006 | TASK-001 |
|
||||
| REQ-007 | TASK-005, TASK-006, TASK-007 |
|
||||
| REQ-008 | TASK-004 |
|
||||
|
||||
## Scope Check
|
||||
|
||||
### Tasks Too Large
|
||||
|
||||
No tasks flagged as too large. All tasks are `small` complexity except TASK-005 (`medium`), which is appropriately scoped for a test suite covering 7 unit test scenarios plus an integration test.
|
||||
|
||||
### Tasks Too Vague
|
||||
|
||||
No tasks flagged as too vague. All tasks have detailed descriptions (well over 50 characters), multiple testable acceptance criteria, and specific file paths.
|
||||
|
||||
### Missing Test Tasks
|
||||
|
||||
- **TASK-001** (Verify meshcore_py compatibility) — no associated test task. This is a research/verification task that does not produce source code, so a test task is not applicable. (Warning only)
|
||||
- **TASK-004** (Update SCHEMAS.md) — no associated test task. This is a documentation-only task. (Warning only)
|
||||
- **TASK-008** (Verify web dashboard) — no associated test task. This is a verification task that may result in no code changes. (Warning only)
|
||||
|
||||
All implementation tasks that modify source code (TASK-002, TASK-003) have corresponding test tasks (TASK-005, TASK-006, TASK-007).
|
||||
|
||||
### Field Validation
|
||||
|
||||
All tasks have valid fields:
|
||||
- All `suggested_role` values are valid (`python`, `docs`, `frontend`)
|
||||
- All `estimated_complexity` values are valid (`small`, `medium`)
|
||||
- All tasks have at least one entry in `requirements`, `acceptance_criteria`, and `files_affected`
|
||||
- All task IDs follow the `TASK-NNN` format with sequential numbering
|
||||
|
||||
## Action Items
|
||||
|
||||
No action items — verdict is PASS.
|
||||
18
.plans/2026/03/17/01-multibyte-support/state.yaml
Normal file
18
.plans/2026/03/17/01-multibyte-support/state.yaml
Normal file
@@ -0,0 +1,18 @@
|
||||
status: completed
|
||||
phase_path: .plans/2026/03/17/01-multibyte-support
|
||||
branch: feature/multibyte-support
|
||||
current_phase: completed
|
||||
current_task: null
|
||||
fix_round: 0
|
||||
last_review_round: 1
|
||||
review_loop_exit_reason: success
|
||||
quality_gate: pass
|
||||
tasks:
|
||||
TASK-001: completed
|
||||
TASK-002: completed
|
||||
TASK-003: completed
|
||||
TASK-004: completed
|
||||
TASK-005: completed
|
||||
TASK-006: completed
|
||||
TASK-007: completed
|
||||
TASK-008: completed
|
||||
102
.plans/2026/03/17/01-multibyte-support/summary.md
Normal file
102
.plans/2026/03/17/01-multibyte-support/summary.md
Normal file
@@ -0,0 +1,102 @@
|
||||
# Phase Summary
|
||||
|
||||
> Phase: `.plans/2026/03/17/01-multibyte-support`
|
||||
> Generated by: `/jp-summary`
|
||||
|
||||
## Project Overview
|
||||
|
||||
MeshCore Hub was updated to support multibyte path hashes introduced in MeshCore firmware v1.14 and meshcore_py v2.3.0. Path hashes — node identifiers embedded in trace and route data — were previously fixed at 1 byte (2 hex characters) per hop but can now be multiple bytes. The update maintains backwards compatibility with nodes running older single-byte firmware.
|
||||
|
||||
### Goals
|
||||
|
||||
- Support variable-length (multibyte) path hashes throughout the data pipeline: interface → MQTT → collector → database → API → web dashboard.
|
||||
- Maintain backwards compatibility so single-byte path hashes from older firmware nodes continue to work without modification.
|
||||
- Update documentation and schemas to accurately describe the new variable-length path hash format.
|
||||
|
||||
## Task Execution
|
||||
|
||||
### Overview
|
||||
|
||||
| Metric | Value |
|
||||
|---|---|
|
||||
| Total tasks | 8 |
|
||||
| Completed | 8 |
|
||||
| Failed | 0 |
|
||||
| Blocked | 0 |
|
||||
| Skipped | 0 |
|
||||
|
||||
### Task Details
|
||||
|
||||
| ID | Title | Role | Complexity | Status |
|
||||
|---|---|---|---|---|
|
||||
| TASK-001 | Verify meshcore_py v2.3.0+ backwards compatibility | python | small | completed |
|
||||
| TASK-002 | Update _normalize_hash_list to accept variable-length hex strings | python | small | completed |
|
||||
| TASK-003 | Update Pydantic schema descriptions for path_hashes fields | python | small | completed |
|
||||
| TASK-004 | Update SCHEMAS.md documentation for multibyte path hashes | docs | small | completed |
|
||||
| TASK-005 | Write tests for multibyte path hash normalizer | python | medium | completed |
|
||||
| TASK-006 | Write tests for database round-trip of multibyte path hashes | python | small | completed |
|
||||
| TASK-007 | Write tests for API trace path responses with multibyte hashes | python | small | completed |
|
||||
| TASK-008 | Verify web dashboard trace path display handles variable-length hashes | frontend | small | completed |
|
||||
|
||||
### Requirement Coverage
|
||||
|
||||
| Metric | Value |
|
||||
|---|---|
|
||||
| Total PRD requirements | 8 |
|
||||
| Requirements covered by completed tasks | 8 |
|
||||
| Requirements with incomplete coverage | 0 |
|
||||
|
||||
## Files Created and Modified
|
||||
|
||||
### Created
|
||||
|
||||
- `tests/test_collector/test_letsmesh_normalizer.py`
|
||||
|
||||
### Modified
|
||||
|
||||
- `pyproject.toml`
|
||||
- `SCHEMAS.md`
|
||||
- `src/meshcore_hub/collector/letsmesh_normalizer.py`
|
||||
- `src/meshcore_hub/common/schemas/events.py`
|
||||
- `src/meshcore_hub/common/schemas/messages.py`
|
||||
- `src/meshcore_hub/common/models/trace_path.py`
|
||||
- `tests/test_collector/test_subscriber.py`
|
||||
- `tests/test_common/test_models.py`
|
||||
- `tests/test_api/test_trace_paths.py`
|
||||
|
||||
## Review Rounds
|
||||
|
||||
### Overview
|
||||
|
||||
| Metric | Value |
|
||||
|---|---|
|
||||
| Total review rounds | 1 |
|
||||
| Total issues found | 0 |
|
||||
| Issues fixed | 0 |
|
||||
| Issues deferred | 0 |
|
||||
| Issues remaining | 0 |
|
||||
| Regressions introduced | 0 |
|
||||
|
||||
### Round Details
|
||||
|
||||
#### Round 1 (scope: full)
|
||||
|
||||
- **Issues found:** 0 (0 CRITICAL, 0 MAJOR, 0 MINOR)
|
||||
- **Exit reason:** success (clean review, no fix rounds needed)
|
||||
|
||||
## Known Issues and Deferred Items
|
||||
|
||||
No known issues.
|
||||
|
||||
## Decisions
|
||||
|
||||
- **meshcore_py handles backwards compatibility transparently** -- Research (TASK-001) confirmed that meshcore_py v2.3.0 handles multibyte path hashes at the protocol level via self-describing wire format. No compatibility logic needed in MeshCore Hub's interface layer.
|
||||
- **No database migration required** -- The existing JSON column type on `trace_paths.path_hashes` stores variable-length string arrays natively. Round-trip tests confirmed no data loss.
|
||||
- **No web dashboard changes needed** -- The SPA has no trace path rendering page. Path hashes are only served via the REST API which uses `list[str]` with no length constraints.
|
||||
- **Normalizer validation approach** -- Changed from exact length check (`len == 2`) to even-length minimum-2 check (`len >= 2 and len % 2 == 0`), preserving existing hex validation and uppercase normalization.
|
||||
|
||||
## Suggested Next Steps
|
||||
|
||||
1. Push the branch and create a pull request for review.
|
||||
2. Perform manual integration testing with a MeshCore device running firmware v1.14+ to verify multibyte path hashes flow end-to-end.
|
||||
3. Verify that mixed-firmware networks (some nodes v1.14+, some older) produce correct mixed-length path hash arrays in the database.
|
||||
274
.plans/2026/03/17/01-multibyte-support/tasks.yaml
Normal file
274
.plans/2026/03/17/01-multibyte-support/tasks.yaml
Normal file
@@ -0,0 +1,274 @@
|
||||
# Task list generated from PRD: .plans/2026/03/17/01-multibyte-support/prd.md
|
||||
# Generated by: /jp-task-list
|
||||
|
||||
tasks:
|
||||
- id: "TASK-001"
|
||||
title: "Verify meshcore_py v2.3.0+ backwards compatibility"
|
||||
description: |
|
||||
Research and confirm that meshcore_py v2.3.0+ handles backwards compatibility
|
||||
with single-byte firmware nodes at the protocol level. Check the meshcore_py
|
||||
v2.3.0 release notes and source code to determine whether the library
|
||||
transparently handles mixed single-byte and multibyte path hashes, or whether
|
||||
MeshCore Hub needs to implement any compatibility logic.
|
||||
|
||||
The pyproject.toml dependency is already set to meshcore>=2.3.0. Verify the
|
||||
interface receiver (src/meshcore_hub/interface/receiver.py) and sender
|
||||
(src/meshcore_hub/interface/sender.py) components work with the updated library
|
||||
without code changes, or document any API changes that require updates.
|
||||
|
||||
Document findings as a comment block at the top of the PR description or in
|
||||
the phase changelog.
|
||||
requirements:
|
||||
- "REQ-006"
|
||||
dependencies: []
|
||||
suggested_role: "python"
|
||||
acceptance_criteria:
|
||||
- "meshcore_py v2.3.0+ backwards compatibility behaviour is documented"
|
||||
- "Any required interface code changes are identified (or confirmed unnecessary)"
|
||||
- "pyproject.toml dependency version is confirmed correct at >=2.3.0"
|
||||
estimated_complexity: "small"
|
||||
files_affected:
|
||||
- "pyproject.toml"
|
||||
|
||||
- id: "TASK-002"
|
||||
title: "Update _normalize_hash_list to accept variable-length hex strings"
|
||||
description: |
|
||||
The LetsMesh normalizer method `_normalize_hash_list` in
|
||||
src/meshcore_hub/collector/letsmesh_normalizer.py (line ~724) currently rejects
|
||||
any path hash string that is not exactly 2 characters long:
|
||||
|
||||
if len(token) != 2:
|
||||
continue
|
||||
|
||||
Update this method to accept variable-length hex strings (any even-length hex
|
||||
string of 2+ characters). The validation should:
|
||||
- Accept strings of length 2, 4, 6, etc. (even-length, minimum 2)
|
||||
- Reject odd-length strings and empty strings
|
||||
- Continue to validate that all characters are valid hexadecimal (0-9, A-F)
|
||||
- Continue to uppercase-normalize the hex strings
|
||||
|
||||
Also update the method's docstring from "Normalize a list of one-byte hash
|
||||
strings" to reflect variable-length support.
|
||||
requirements:
|
||||
- "REQ-001"
|
||||
dependencies: []
|
||||
suggested_role: "python"
|
||||
acceptance_criteria:
|
||||
- "_normalize_hash_list accepts 2-character hex strings (legacy single-byte)"
|
||||
- "_normalize_hash_list accepts 4+ character hex strings (multibyte)"
|
||||
- "_normalize_hash_list rejects odd-length strings"
|
||||
- "_normalize_hash_list rejects non-hex characters"
|
||||
- "_normalize_hash_list uppercases all hex strings"
|
||||
- "Method docstring updated to describe variable-length support"
|
||||
estimated_complexity: "small"
|
||||
files_affected:
|
||||
- "src/meshcore_hub/collector/letsmesh_normalizer.py"
|
||||
|
||||
- id: "TASK-003"
|
||||
done: true
|
||||
title: "Update Pydantic schema descriptions for path_hashes fields"
|
||||
description: |
|
||||
Update the `path_hashes` field description in Pydantic schemas to reflect
|
||||
variable-length hex strings instead of fixed 2-character strings.
|
||||
|
||||
Files and fields to update:
|
||||
|
||||
1. src/meshcore_hub/common/schemas/events.py - TraceDataEvent.path_hashes
|
||||
(line ~134): Change description from "Array of 2-character node hash
|
||||
identifiers" to "Array of hex-encoded node hash identifiers (variable
|
||||
length, e.g. '4a' for single-byte or 'b3fa' for multibyte)"
|
||||
|
||||
2. src/meshcore_hub/common/schemas/messages.py - MessageEventBase.path_hashes
|
||||
or TracePathRead.path_hashes (line ~157): Update description similarly
|
||||
if it references fixed-length hashes.
|
||||
|
||||
3. src/meshcore_hub/common/models/trace_path.py - TracePath.path_hashes
|
||||
docstring (line ~23): Change "JSON array of node hash identifiers" to
|
||||
"JSON array of hex-encoded node hash identifiers (variable length)"
|
||||
|
||||
Ensure no Pydantic validators or Field constraints reject strings longer
|
||||
than 2 characters. The current schemas use Optional[list[str]] with no
|
||||
per-element length validation, so no validator changes should be needed.
|
||||
requirements:
|
||||
- "REQ-002"
|
||||
dependencies: []
|
||||
suggested_role: "python"
|
||||
acceptance_criteria:
|
||||
- "TraceDataEvent.path_hashes description reflects variable-length hex strings"
|
||||
- "TracePathRead.path_hashes description reflects variable-length hex strings"
|
||||
- "TracePath model docstring updated for variable-length path hashes"
|
||||
- "No Pydantic validation rejects path hash strings longer than 2 characters"
|
||||
estimated_complexity: "small"
|
||||
files_affected:
|
||||
- "src/meshcore_hub/common/schemas/events.py"
|
||||
- "src/meshcore_hub/common/schemas/messages.py"
|
||||
- "src/meshcore_hub/common/models/trace_path.py"
|
||||
|
||||
- id: "TASK-004"
|
||||
title: "Update SCHEMAS.md documentation for multibyte path hashes"
|
||||
description: |
|
||||
Update SCHEMAS.md to reflect the new variable-length path hash format
|
||||
introduced in MeshCore firmware v1.14.
|
||||
|
||||
Changes needed:
|
||||
|
||||
1. Line ~228: Change "Array of 2-character node hash identifiers (ordered
|
||||
by hops)" to "Array of hex-encoded node hash identifiers, variable length
|
||||
(e.g. '4a' for single-byte, 'b3fa' for multibyte), ordered by hops"
|
||||
|
||||
2. Line ~239: Update the example path_hashes array to include at least one
|
||||
multibyte hash, e.g.:
|
||||
"path_hashes": ["4a", "b3fa", "02"]
|
||||
This demonstrates mixed single-byte and multibyte hashes in the same trace.
|
||||
|
||||
3. Add a brief note explaining that firmware v1.14+ supports multibyte path
|
||||
hashes and that older nodes use single-byte (2-character) hashes, so
|
||||
mixed-length arrays are expected in heterogeneous networks.
|
||||
requirements:
|
||||
- "REQ-008"
|
||||
dependencies: []
|
||||
suggested_role: "docs"
|
||||
acceptance_criteria:
|
||||
- "path_hashes field description updated from '2-character' to 'variable-length hex'"
|
||||
- "Example payload includes at least one multibyte path hash"
|
||||
- "Note about firmware version compatibility is present"
|
||||
estimated_complexity: "small"
|
||||
files_affected:
|
||||
- "SCHEMAS.md"
|
||||
|
||||
- id: "TASK-005"
|
||||
done: true
|
||||
title: "Write tests for multibyte path hash normalizer"
|
||||
description: |
|
||||
Add tests for the updated _normalize_hash_list method in the LetsMesh
|
||||
normalizer to verify it handles variable-length hex strings correctly.
|
||||
|
||||
Add test cases in tests/test_collector/ (either in an existing normalizer
|
||||
test file or a new test_letsmesh_normalizer.py if one doesn't exist):
|
||||
|
||||
1. Single-byte (2-char) hashes: ["4a", "b3", "fa"] -> accepted, uppercased
|
||||
2. Multibyte (4-char) hashes: ["4a2b", "b3fa"] -> accepted, uppercased
|
||||
3. Mixed-length hashes: ["4a", "b3fa", "02"] -> all accepted
|
||||
4. Odd-length strings: ["4a", "b3f", "02"] -> "b3f" filtered out
|
||||
5. Invalid hex characters: ["4a", "zz", "02"] -> "zz" filtered out
|
||||
6. Empty list: [] -> returns None
|
||||
7. Non-string items: [42, "4a"] -> 42 filtered out
|
||||
|
||||
Also add/update integration-level tests in tests/test_collector/test_subscriber.py
|
||||
to verify that multibyte path hashes flow through the full collector pipeline
|
||||
(subscriber -> handler -> database) correctly. The existing test cases at
|
||||
lines ~607 and ~662 use 2-character hashes; add a parallel test case with
|
||||
multibyte hashes.
|
||||
requirements:
|
||||
- "REQ-001"
|
||||
- "REQ-007"
|
||||
dependencies:
|
||||
- "TASK-002"
|
||||
suggested_role: "python"
|
||||
acceptance_criteria:
|
||||
- "Unit tests for _normalize_hash_list cover all 7 scenarios listed"
|
||||
- "Integration test verifies multibyte path hashes stored correctly in database"
|
||||
- "All existing 2-character path hash tests continue to pass"
|
||||
- "All new tests pass"
|
||||
estimated_complexity: "medium"
|
||||
files_affected:
|
||||
- "tests/test_collector/test_letsmesh_normalizer.py"
|
||||
- "tests/test_collector/test_subscriber.py"
|
||||
|
||||
- id: "TASK-006"
|
||||
title: "Write tests for database round-trip of multibyte path hashes"
|
||||
description: |
|
||||
Verify that the SQLAlchemy JSON column on the TracePath model correctly
|
||||
stores and retrieves variable-length path hash arrays without data loss
|
||||
or truncation.
|
||||
|
||||
Add test cases in tests/test_common/test_models.py (where existing
|
||||
TracePath tests are at line ~129):
|
||||
|
||||
1. Store and retrieve a TracePath with multibyte path_hashes:
|
||||
["4a2b", "b3fa", "02cd"] -> verify round-trip equality
|
||||
2. Store and retrieve a TracePath with mixed-length path_hashes:
|
||||
["4a", "b3fa", "02"] -> verify round-trip equality
|
||||
3. Verify existing test with 2-character hashes still passes
|
||||
|
||||
These tests confirm REQ-003 (no migration needed) and contribute to
|
||||
REQ-007 (backwards compatibility).
|
||||
requirements:
|
||||
- "REQ-003"
|
||||
- "REQ-007"
|
||||
dependencies:
|
||||
- "TASK-003"
|
||||
suggested_role: "python"
|
||||
acceptance_criteria:
|
||||
- "Test verifies multibyte path_hashes round-trip through JSON column correctly"
|
||||
- "Test verifies mixed-length path_hashes round-trip correctly"
|
||||
- "Existing 2-character path hash test continues to pass"
|
||||
- "No Alembic migration is created or required"
|
||||
estimated_complexity: "small"
|
||||
files_affected:
|
||||
- "tests/test_common/test_models.py"
|
||||
|
||||
- id: "TASK-007"
|
||||
title: "Write tests for API trace path responses with multibyte hashes"
|
||||
description: |
|
||||
Add test cases in tests/test_api/test_trace_paths.py to verify that the
|
||||
trace paths API returns multibyte path hashes faithfully.
|
||||
|
||||
The existing test fixtures in tests/test_api/conftest.py create
|
||||
sample_trace_path objects with path_hashes like ["abc123", "def456",
|
||||
"ghi789"] (line ~275). Note these are already 6-character strings, so
|
||||
the API serialization likely already works. Add explicit test cases:
|
||||
|
||||
1. Create a trace path with multibyte path_hashes (e.g. ["4a2b", "b3fa"])
|
||||
via the fixture, then GET /trace-paths and verify the response contains
|
||||
the exact same array.
|
||||
2. Create a trace path with mixed-length path_hashes (e.g. ["4a", "b3fa",
|
||||
"02"]), then GET /trace-paths/{id} and verify the response.
|
||||
3. Verify existing API tests with current path_hashes continue to pass.
|
||||
|
||||
These tests confirm REQ-004.
|
||||
requirements:
|
||||
- "REQ-004"
|
||||
- "REQ-007"
|
||||
dependencies:
|
||||
- "TASK-003"
|
||||
suggested_role: "python"
|
||||
acceptance_criteria:
|
||||
- "Test verifies GET /trace-paths returns multibyte path hashes correctly"
|
||||
- "Test verifies GET /trace-paths/{id} returns mixed-length path hashes correctly"
|
||||
- "Existing API trace path tests continue to pass"
|
||||
estimated_complexity: "small"
|
||||
files_affected:
|
||||
- "tests/test_api/test_trace_paths.py"
|
||||
- "tests/test_api/conftest.py"
|
||||
|
||||
- id: "TASK-008"
|
||||
done: true
|
||||
title: "Verify web dashboard trace path display handles variable-length hashes"
|
||||
description: |
|
||||
Verify that the web dashboard does not have any hardcoded assumptions about
|
||||
2-character path hash strings. A grep of src/meshcore_hub/web/static/js/spa/
|
||||
for "path_hash" and "trace" shows no direct references to path hashes in the
|
||||
SPA JavaScript code, meaning path hashes are likely rendered generically
|
||||
through the API data display.
|
||||
|
||||
Confirm this by:
|
||||
1. Checking all web template and JavaScript files that render trace path data
|
||||
2. Verifying no CSS or JS applies fixed-width formatting to path hash elements
|
||||
3. If any fixed-width or truncation logic exists, update it to handle
|
||||
variable-length strings
|
||||
|
||||
If no web code references path hashes directly (as initial grep suggests),
|
||||
document that the web dashboard requires no changes for multibyte support.
|
||||
This satisfies REQ-005.
|
||||
requirements:
|
||||
- "REQ-005"
|
||||
dependencies: []
|
||||
suggested_role: "frontend"
|
||||
acceptance_criteria:
|
||||
- "Web dashboard trace/path display verified to handle variable-length hashes"
|
||||
- "No fixed-width formatting assumes 2-character hash strings"
|
||||
- "Any necessary changes applied, or no-change finding documented"
|
||||
estimated_complexity: "small"
|
||||
files_affected:
|
||||
- "src/meshcore_hub/web/static/js/spa/pages/trace-paths.js"
|
||||
@@ -1,3 +1,6 @@
|
||||
default_language_version:
|
||||
python: python3
|
||||
|
||||
repos:
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v4.5.0
|
||||
@@ -14,7 +17,6 @@ repos:
|
||||
rev: 24.3.0
|
||||
hooks:
|
||||
- id: black
|
||||
language_version: python3.11
|
||||
args: ["--line-length=88"]
|
||||
|
||||
- repo: https://github.com/pycqa/flake8
|
||||
@@ -38,3 +40,4 @@ repos:
|
||||
- fastapi>=0.100.0
|
||||
- alembic>=1.7.0
|
||||
- types-paho-mqtt>=1.6.0
|
||||
- types-PyYAML>=6.0.0
|
||||
|
||||
@@ -1 +1 @@
|
||||
3.11
|
||||
3.14
|
||||
|
||||
402
AGENTS.md
402
AGENTS.md
@@ -5,20 +5,27 @@ This document provides context and guidelines for AI coding assistants working o
|
||||
## Agent Rules
|
||||
|
||||
* You MUST use Python (version in `.python-version` file)
|
||||
* You MUST activate a Python virtual environment in the `venv` directory or create one if it does not exist:
|
||||
- `ls ./venv` to check if it exists
|
||||
* You MUST activate a Python virtual environment in the `.venv` directory or create one if it does not exist:
|
||||
- `ls ./.venv` to check if it exists
|
||||
- `python -m venv .venv` to create it
|
||||
* You MUST always activate the virtual environment before running any commands
|
||||
- `source .venv/bin/activate`
|
||||
* You MUST install all project dependencies using `pip install -e ".[dev]"` command`
|
||||
* You MUST install `pre-commit` for quality checks
|
||||
* You MUST keep project documentation in sync with behavior/config/schema changes made in code (at minimum update relevant sections in `README.md`, `SCHEMAS.md`, `PLAN.md`, and/or `TASKS.md` when applicable)
|
||||
* Before commiting:
|
||||
- Run tests with `pytest` to ensure recent changes haven't broken anything
|
||||
- Run **targeted tests** for the components you changed, not the full suite:
|
||||
- `pytest tests/test_web/` for web-only changes (templates, static JS, web routes)
|
||||
- `pytest tests/test_api/` for API changes
|
||||
- `pytest tests/test_collector/` for collector changes
|
||||
- `pytest tests/test_interface/` for interface/sender/receiver changes
|
||||
- `pytest tests/test_common/` for common models/schemas/config changes
|
||||
- Only run the full `pytest` if changes span multiple components
|
||||
- Run `pre-commit run --all-files` to perform all quality checks
|
||||
|
||||
## Project Overview
|
||||
|
||||
MeshCore Hub is a Python 3.11+ monorepo for managing and orchestrating MeshCore mesh networks. It consists of five main components:
|
||||
MeshCore Hub is a Python 3.13+ monorepo for managing and orchestrating MeshCore mesh networks. It consists of five main components:
|
||||
|
||||
- **meshcore_interface**: Serial/USB interface to MeshCore companion nodes, publishes/subscribes to MQTT
|
||||
- **meshcore_collector**: Collects MeshCore events from MQTT and stores them in a database
|
||||
@@ -37,7 +44,7 @@ MeshCore Hub is a Python 3.11+ monorepo for managing and orchestrating MeshCore
|
||||
|
||||
| Category | Technology |
|
||||
|----------|------------|
|
||||
| Language | Python 3.11+ |
|
||||
| Language | Python 3.13+ |
|
||||
| Package Management | pip with pyproject.toml |
|
||||
| CLI Framework | Click |
|
||||
| Configuration | Pydantic Settings |
|
||||
@@ -46,7 +53,8 @@ MeshCore Hub is a Python 3.11+ monorepo for managing and orchestrating MeshCore
|
||||
| REST API | FastAPI |
|
||||
| MQTT Client | paho-mqtt |
|
||||
| MeshCore Interface | meshcore |
|
||||
| Templates | Jinja2 |
|
||||
| Templates | Jinja2 (server), lit-html (SPA) |
|
||||
| Frontend | ES Modules SPA with client-side routing |
|
||||
| CSS Framework | Tailwind CSS + DaisyUI |
|
||||
| Testing | pytest, pytest-asyncio |
|
||||
| Formatting | black |
|
||||
@@ -114,17 +122,15 @@ class NodeRead(BaseModel):
|
||||
### SQLAlchemy Models
|
||||
|
||||
```python
|
||||
from sqlalchemy import String, DateTime, ForeignKey
|
||||
from sqlalchemy import String, DateTime, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
from datetime import datetime
|
||||
from uuid import uuid4
|
||||
from typing import Optional
|
||||
|
||||
from meshcore_hub.common.models.base import Base
|
||||
from meshcore_hub.common.models.base import Base, TimestampMixin, UUIDMixin
|
||||
|
||||
class Node(Base):
|
||||
class Node(Base, UUIDMixin, TimestampMixin):
|
||||
__tablename__ = "nodes"
|
||||
|
||||
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=lambda: str(uuid4()))
|
||||
public_key: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
name: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||
adv_type: Mapped[str | None] = mapped_column(String(20), nullable=True)
|
||||
@@ -132,6 +138,18 @@ class Node(Base):
|
||||
|
||||
# Relationships
|
||||
tags: Mapped[list["NodeTag"]] = relationship(back_populates="node", cascade="all, delete-orphan")
|
||||
|
||||
|
||||
class Member(Base, UUIDMixin, TimestampMixin):
|
||||
"""Network member model - stores info about network operators."""
|
||||
__tablename__ = "members"
|
||||
|
||||
name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
callsign: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
|
||||
role: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
contact: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
public_key: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
```
|
||||
|
||||
### FastAPI Routes
|
||||
@@ -239,7 +257,12 @@ meshcore-hub/
|
||||
│ │ ├── mqtt.py # MQTT utilities
|
||||
│ │ ├── logging.py # Logging config
|
||||
│ │ ├── models/ # SQLAlchemy models
|
||||
│ │ │ ├── node.py # Node model
|
||||
│ │ │ ├── member.py # Network member model
|
||||
│ │ │ └── ...
|
||||
│ │ └── schemas/ # Pydantic schemas
|
||||
│ │ ├── members.py # Member API schemas
|
||||
│ │ └── ...
|
||||
│ ├── interface/
|
||||
│ │ ├── cli.py
|
||||
│ │ ├── device.py # MeshCore device wrapper
|
||||
@@ -247,9 +270,11 @@ meshcore-hub/
|
||||
│ │ ├── receiver.py # RECEIVER mode
|
||||
│ │ └── sender.py # SENDER mode
|
||||
│ ├── collector/
|
||||
│ │ ├── cli.py
|
||||
│ │ ├── cli.py # Collector CLI with seed commands
|
||||
│ │ ├── subscriber.py # MQTT subscriber
|
||||
│ │ ├── tag_import.py # Tag import from JSON
|
||||
│ │ ├── cleanup.py # Data retention/cleanup service
|
||||
│ │ ├── tag_import.py # Tag import from YAML
|
||||
│ │ ├── member_import.py # Member import from YAML
|
||||
│ │ ├── handlers/ # Event handlers
|
||||
│ │ └── webhook.py # Webhook dispatcher
|
||||
│ ├── api/
|
||||
@@ -257,14 +282,26 @@ meshcore-hub/
|
||||
│ │ ├── app.py # FastAPI app
|
||||
│ │ ├── auth.py # Authentication
|
||||
│ │ ├── dependencies.py
|
||||
│ │ ├── routes/ # API routes
|
||||
│ │ └── templates/ # Dashboard HTML
|
||||
│ │ ├── metrics.py # Prometheus metrics endpoint
|
||||
│ │ └── routes/ # API routes
|
||||
│ │ ├── members.py # Member CRUD endpoints
|
||||
│ │ └── ...
|
||||
│ └── web/
|
||||
│ ├── cli.py
|
||||
│ ├── app.py # FastAPI app
|
||||
│ ├── routes/ # Page routes
|
||||
│ ├── templates/ # Jinja2 templates
|
||||
│ └── static/ # CSS, JS
|
||||
│ ├── pages.py # Custom markdown page loader
|
||||
│ ├── templates/ # Jinja2 templates (spa.html shell)
|
||||
│ └── static/
|
||||
│ ├── css/app.css # Custom styles
|
||||
│ └── js/spa/ # SPA frontend (ES modules)
|
||||
│ ├── app.js # Entry point, route registration
|
||||
│ ├── router.js # Client-side History API router
|
||||
│ ├── api.js # API fetch helper
|
||||
│ ├── components.js # Shared UI components (lit-html)
|
||||
│ ├── icons.js # SVG icon functions (lit-html)
|
||||
│ └── pages/ # Page modules (lazy-loaded)
|
||||
│ ├── home.js, dashboard.js, nodes.js, ...
|
||||
│ └── admin/ # Admin page modules
|
||||
├── tests/
|
||||
│ ├── conftest.py
|
||||
│ ├── test_common/
|
||||
@@ -276,22 +313,27 @@ meshcore-hub/
|
||||
│ ├── env.py
|
||||
│ └── versions/
|
||||
├── etc/
|
||||
│ └── mosquitto.conf # MQTT broker configuration
|
||||
│ ├── mosquitto.conf # MQTT broker configuration
|
||||
│ ├── prometheus/ # Prometheus configuration
|
||||
│ │ ├── prometheus.yml # Scrape and alerting config
|
||||
│ │ └── alerts.yml # Alert rules
|
||||
│ └── alertmanager/ # Alertmanager configuration
|
||||
│ └── alertmanager.yml # Routing and receiver config
|
||||
├── example/
|
||||
│ └── data/
|
||||
│ ├── collector/
|
||||
│ │ └── tags.json # Example node tags data
|
||||
│ └── web/
|
||||
│ └── members.json # Example network members data
|
||||
│ ├── seed/ # Example seed data files
|
||||
│ │ ├── node_tags.yaml # Example node tags
|
||||
│ │ └── members.yaml # Example network members
|
||||
│ └── content/ # Example custom content
|
||||
│ ├── pages/ # Example custom pages
|
||||
│ └── media/ # Example media files
|
||||
├── seed/ # Seed data directory (SEED_HOME)
|
||||
│ ├── node_tags.yaml # Node tags for import
|
||||
│ └── members.yaml # Network members for import
|
||||
├── data/ # Runtime data (gitignored, DATA_HOME default)
|
||||
│ ├── collector/ # Collector data
|
||||
│ │ ├── meshcore.db # SQLite database
|
||||
│ │ └── tags.json # Node tags for import
|
||||
│ └── web/ # Web data
|
||||
│ └── members.json # Network members list
|
||||
│ └── collector/ # Collector data
|
||||
│ └── meshcore.db # SQLite database
|
||||
├── Dockerfile # Docker build configuration
|
||||
├── docker-compose.yml # Docker Compose services (gitignored)
|
||||
└── docker-compose.yml.example # Docker Compose template
|
||||
└── docker-compose.yml # Docker Compose services
|
||||
```
|
||||
|
||||
## MQTT Topic Structure
|
||||
@@ -324,6 +366,25 @@ Examples:
|
||||
- JSON columns for flexible data (path_hashes, parsed_data, etc.)
|
||||
- Foreign keys reference nodes by UUID, not public_key
|
||||
|
||||
## Standard Node Tags
|
||||
|
||||
Node tags are flexible key-value pairs that allow custom metadata to be attached to nodes. While tags are completely optional and freeform, the following standard tag keys are recommended for consistent use across the web dashboard:
|
||||
|
||||
| Tag Key | Description | Usage |
|
||||
|---------|-------------|-------|
|
||||
| `name` | Node display name | Used as the primary display name throughout the UI (overrides the advertised name) |
|
||||
| `description` | Short description | Displayed as supplementary text under the node name |
|
||||
| `member_id` | Member identifier reference | Links the node to a network member (matches `member_id` in Members table) |
|
||||
| `lat` | GPS latitude override | Overrides node-reported latitude for map display |
|
||||
| `lon` | GPS longitude override | Overrides node-reported longitude for map display |
|
||||
| `elevation` | GPS elevation override | Overrides node-reported elevation |
|
||||
| `role` | Node role/purpose | Used for website presentation and filtering (e.g., "gateway", "repeater", "sensor") |
|
||||
|
||||
**Important Notes:**
|
||||
- All tags are optional - nodes can function without any tags
|
||||
- Tag keys are case-sensitive
|
||||
- The `member_id` tag should reference a valid `member_id` from the Members table
|
||||
|
||||
## Testing Guidelines
|
||||
|
||||
### Unit Tests
|
||||
@@ -400,13 +461,121 @@ async def client(db_session):
|
||||
5. Add Alembic migration if schema changed
|
||||
6. Add tests in `tests/test_collector/`
|
||||
|
||||
### Adding a New SPA Page
|
||||
|
||||
The web dashboard is a Single Page Application. Pages are ES modules loaded by the client-side router.
|
||||
|
||||
1. Create a page module in `web/static/js/spa/pages/` (e.g., `my-page.js`)
|
||||
2. Export an `async function render(container, params, router)` that renders into `container` using `litRender(html\`...\`, container)`
|
||||
3. Register the route in `web/static/js/spa/app.js` with `router.addRoute('/my-page', pageHandler(pages.myPage))`
|
||||
4. Add the page title to `updatePageTitle()` in `app.js`
|
||||
5. Add a nav link in `web/templates/spa.html` (both mobile and desktop menus)
|
||||
|
||||
**Key patterns:**
|
||||
- Import `html`, `litRender`, `nothing` from `../components.js` (re-exports lit-html)
|
||||
- Use `apiGet()` from `../api.js` for API calls
|
||||
- For list pages with filters, use the `renderPage()` pattern: render the page header immediately, then re-render with the filter form + results after fetch (keeps the form out of the shell to avoid layout shift from data-dependent filter selects)
|
||||
- Old page content stays visible until data is ready (navbar spinner indicates loading)
|
||||
- Use `pageColors` from `components.js` for section-specific colors (reads CSS custom properties from `app.css`)
|
||||
- Return a cleanup function if the page creates resources (e.g., Leaflet maps, Chart.js instances)
|
||||
|
||||
### Internationalization (i18n)
|
||||
|
||||
The web dashboard supports internationalization via JSON translation files. The default language is English.
|
||||
|
||||
**Translation files location:** `src/meshcore_hub/web/static/locales/`
|
||||
|
||||
**Key files:**
|
||||
- `en.json` - English translations (reference implementation)
|
||||
- `languages.md` - Comprehensive translation reference guide for translators
|
||||
|
||||
**Using translations in JavaScript:**
|
||||
|
||||
Import the `t()` function from `components.js`:
|
||||
|
||||
```javascript
|
||||
import { t } from '../components.js';
|
||||
|
||||
// Simple translation
|
||||
const label = t('common.save'); // "Save"
|
||||
|
||||
// Translation with variable interpolation
|
||||
const title = t('common.add_entity', { entity: t('entities.node') }); // "Add Node"
|
||||
|
||||
// Composed patterns for consistency
|
||||
const emptyMsg = t('common.no_entity_found', { entity: t('entities.nodes').toLowerCase() }); // "No nodes found"
|
||||
```
|
||||
|
||||
**Translation architecture:**
|
||||
|
||||
1. **Entity-based composition:** Core entity names (`entities.*`) are referenced by composite patterns for consistency
|
||||
2. **Reusable patterns:** Common UI patterns (`common.*`) use `{{variable}}` interpolation for dynamic content
|
||||
3. **Separation of concerns:**
|
||||
- Keys without `_label` suffix = table headers (title case, no colon)
|
||||
- Keys with `_label` suffix = inline labels (sentence case, with colon)
|
||||
|
||||
**When adding/modifying translations:**
|
||||
|
||||
1. **Add new keys** to `en.json` following existing patterns:
|
||||
- Use composition when possible (reference `entities.*` in `common.*` patterns)
|
||||
- Group related keys by section (e.g., `admin_members.*`, `admin_node_tags.*`)
|
||||
- Use `{{variable}}` syntax for dynamic content
|
||||
|
||||
2. **Update `languages.md`** with:
|
||||
- Key name, English value, and usage context
|
||||
- Variable descriptions if using interpolation
|
||||
- Notes about HTML content or special formatting
|
||||
|
||||
3. **Add tests** in `tests/test_common/test_i18n.py`:
|
||||
- Test new interpolation patterns
|
||||
- Test required sections if adding new top-level sections
|
||||
- Test composed patterns with entity references
|
||||
|
||||
4. **Run i18n tests:**
|
||||
```bash
|
||||
pytest tests/test_common/test_i18n.py -v
|
||||
```
|
||||
|
||||
**Best practices:**
|
||||
|
||||
- **Avoid duplication:** Use `common.*` patterns instead of duplicating similar strings
|
||||
- **Compose with entities:** Reference `entities.*` keys in patterns rather than hardcoding entity names
|
||||
- **Preserve variables:** Keep `{{variable}}` placeholders unchanged when translating
|
||||
- **Test composition:** Verify patterns work with all entity types (singular/plural, lowercase/uppercase)
|
||||
- **Document context:** Always update `languages.md` so translators understand usage
|
||||
|
||||
**Example - adding a new entity and patterns:**
|
||||
|
||||
```javascript
|
||||
// 1. Add entity to en.json
|
||||
"entities": {
|
||||
"sensor": "Sensor"
|
||||
}
|
||||
|
||||
// 2. Use with existing common patterns
|
||||
t('common.add_entity', { entity: t('entities.sensor') }) // "Add Sensor"
|
||||
t('common.no_entity_found', { entity: t('entities.sensors').toLowerCase() }) // "No sensors found"
|
||||
|
||||
// 3. Update languages.md with context
|
||||
// 4. Add test to test_i18n.py
|
||||
```
|
||||
|
||||
**Translation loading:**
|
||||
|
||||
The i18n system (`src/meshcore_hub/common/i18n.py`) loads translations on startup:
|
||||
- Defaults to English (`en`)
|
||||
- Falls back to English for missing keys
|
||||
- Returns the key itself if translation not found
|
||||
|
||||
For full translation guidelines, see `src/meshcore_hub/web/static/locales/languages.md`.
|
||||
|
||||
### Adding a New Database Model
|
||||
|
||||
1. Create model in `common/models/`
|
||||
2. Export in `common/models/__init__.py`
|
||||
3. Create Alembic migration: `alembic revision --autogenerate -m "description"`
|
||||
3. Create Alembic migration: `meshcore-hub db revision --autogenerate -m "description"`
|
||||
4. Review and adjust migration file
|
||||
5. Test migration: `alembic upgrade head`
|
||||
5. Test migration: `meshcore-hub db upgrade`
|
||||
|
||||
### Running the Development Environment
|
||||
|
||||
@@ -428,7 +597,7 @@ pytest
|
||||
# Run specific component
|
||||
meshcore-hub api --reload
|
||||
meshcore-hub collector
|
||||
meshcore-hub interface --mode receiver --mock
|
||||
meshcore-hub interface receiver --mock
|
||||
```
|
||||
|
||||
## Environment Variables
|
||||
@@ -436,26 +605,86 @@ meshcore-hub interface --mode receiver --mock
|
||||
See [PLAN.md](PLAN.md#configuration-environment-variables) for complete list.
|
||||
|
||||
Key variables:
|
||||
- `DATA_HOME` - Base directory for all service data (default: `./data`)
|
||||
- `DATA_HOME` - Base directory for runtime data (default: `./data`)
|
||||
- `SEED_HOME` - Directory containing seed data files (default: `./seed`)
|
||||
- `CONTENT_HOME` - Directory containing custom content (pages, media) (default: `./content`)
|
||||
- `MQTT_HOST`, `MQTT_PORT`, `MQTT_PREFIX` - MQTT broker connection
|
||||
- `DATABASE_URL` - SQLAlchemy database URL (default: `sqlite:///{DATA_HOME}/collector/meshcore.db`)
|
||||
- `MQTT_TLS` - Enable TLS/SSL for MQTT (default: `false`)
|
||||
- `API_READ_KEY`, `API_ADMIN_KEY` - API authentication keys
|
||||
- `WEB_ADMIN_ENABLED` - Enable admin interface at /a/ (default: `false`, requires auth proxy)
|
||||
- `WEB_TRUSTED_PROXY_HOSTS` - Comma-separated list of trusted proxy hosts for admin authentication headers. Default: `*` (all hosts). Recommended: set to your reverse proxy IP in production. A startup warning is emitted when using the default `*` with admin enabled.
|
||||
- `WEB_THEME` - Default theme for the web dashboard (default: `dark`, options: `dark`, `light`). Users can override via the theme toggle in the navbar, which persists their preference in browser localStorage.
|
||||
- `WEB_AUTO_REFRESH_SECONDS` - Auto-refresh interval in seconds for list pages (default: `30`, `0` to disable)
|
||||
- `TZ` - Timezone for web dashboard date/time display (default: `UTC`, e.g., `America/New_York`, `Europe/London`)
|
||||
- `FEATURE_DASHBOARD`, `FEATURE_NODES`, `FEATURE_ADVERTISEMENTS`, `FEATURE_MESSAGES`, `FEATURE_MAP`, `FEATURE_MEMBERS`, `FEATURE_PAGES` - Feature flags to enable/disable specific web dashboard pages (default: all `true`). Dependencies: Dashboard auto-disables when all of Nodes/Advertisements/Messages are disabled. Map auto-disables when Nodes is disabled.
|
||||
- `METRICS_ENABLED` - Enable Prometheus metrics endpoint at /metrics (default: `true`)
|
||||
- `METRICS_CACHE_TTL` - Seconds to cache metrics output (default: `60`)
|
||||
- `LOG_LEVEL` - Logging verbosity
|
||||
|
||||
### Data Directory Structure
|
||||
The database defaults to `sqlite:///{DATA_HOME}/collector/meshcore.db` and does not typically need to be configured.
|
||||
|
||||
The `DATA_HOME` environment variable controls where all service data is stored:
|
||||
### Directory Structure
|
||||
|
||||
**Seed Data (`SEED_HOME`)** - Contains initial data files for database seeding:
|
||||
```
|
||||
${SEED_HOME}/
|
||||
├── node_tags.yaml # Node tags (keyed by public_key)
|
||||
└── members.yaml # Network members list
|
||||
```
|
||||
|
||||
**Custom Content (`CONTENT_HOME`)** - Contains custom pages and media for the web dashboard:
|
||||
```
|
||||
${CONTENT_HOME}/
|
||||
├── pages/ # Custom markdown pages
|
||||
│ ├── about.md # Example: About page (/pages/about)
|
||||
│ ├── faq.md # Example: FAQ page (/pages/faq)
|
||||
│ └── getting-started.md # Example: Getting Started (/pages/getting-started)
|
||||
└── media/ # Custom media files
|
||||
└── images/
|
||||
├── logo.svg # Full-color custom logo (default)
|
||||
└── logo-invert.svg # Monochrome custom logo (darkened in light mode)
|
||||
```
|
||||
|
||||
Pages use YAML frontmatter for metadata:
|
||||
```markdown
|
||||
---
|
||||
title: About Us # Browser tab title and nav link (not rendered on page)
|
||||
slug: about # URL path (default: filename without .md)
|
||||
menu_order: 10 # Nav sort order (default: 100, lower = earlier)
|
||||
---
|
||||
|
||||
# About Our Network
|
||||
|
||||
Markdown content here (include your own heading)...
|
||||
```
|
||||
|
||||
**Runtime Data (`DATA_HOME`)** - Contains runtime data (gitignored):
|
||||
```
|
||||
${DATA_HOME}/
|
||||
├── collector/
|
||||
│ ├── meshcore.db # SQLite database
|
||||
│ └── tags.json # Node tags for import
|
||||
└── web/
|
||||
└── members.json # Network members list
|
||||
└── collector/
|
||||
└── meshcore.db # SQLite database
|
||||
```
|
||||
|
||||
Services automatically create their subdirectories if they don't exist.
|
||||
|
||||
### Seeding
|
||||
|
||||
The database can be seeded with node tags and network members from YAML files in `SEED_HOME`:
|
||||
- `node_tags.yaml` - Node tag definitions (keyed by public_key)
|
||||
- `members.yaml` - Network member definitions
|
||||
|
||||
**Important:** Seeding is NOT automatic and must be run explicitly. This prevents seed files from overwriting user changes made via the admin UI.
|
||||
|
||||
```bash
|
||||
# Native CLI
|
||||
meshcore-hub collector seed
|
||||
|
||||
# With Docker Compose
|
||||
docker compose --profile seed up
|
||||
```
|
||||
|
||||
**Note:** Once the admin UI is enabled (`WEB_ADMIN_ENABLED=true`), tags should be managed through the web interface rather than seed files.
|
||||
|
||||
### Webhook Configuration
|
||||
|
||||
The collector supports forwarding events to external HTTP endpoints:
|
||||
@@ -472,6 +701,64 @@ The collector supports forwarding events to external HTTP endpoints:
|
||||
| `WEBHOOK_MAX_RETRIES` | Max retries on failure (default: 3) |
|
||||
| `WEBHOOK_RETRY_BACKOFF` | Exponential backoff multiplier (default: 2.0) |
|
||||
|
||||
### Data Retention / Cleanup Configuration
|
||||
|
||||
The collector supports automatic cleanup of old event data and inactive nodes:
|
||||
|
||||
**Event Data Cleanup:**
|
||||
|
||||
| Variable | Description |
|
||||
|----------|-------------|
|
||||
| `DATA_RETENTION_ENABLED` | Enable automatic event data cleanup (default: true) |
|
||||
| `DATA_RETENTION_DAYS` | Days to retain event data (default: 30) |
|
||||
| `DATA_RETENTION_INTERVAL_HOURS` | Hours between cleanup runs (default: 24) |
|
||||
|
||||
When enabled, the collector automatically deletes event data older than the retention period:
|
||||
- Advertisements
|
||||
- Messages (channel and direct)
|
||||
- Telemetry
|
||||
- Trace paths
|
||||
- Event logs
|
||||
|
||||
**Node Cleanup:**
|
||||
|
||||
| Variable | Description |
|
||||
|----------|-------------|
|
||||
| `NODE_CLEANUP_ENABLED` | Enable automatic cleanup of inactive nodes (default: true) |
|
||||
| `NODE_CLEANUP_DAYS` | Remove nodes not seen for this many days (default: 7) |
|
||||
|
||||
When enabled, the collector automatically removes nodes where:
|
||||
- `last_seen` is older than the configured number of days
|
||||
- Nodes with `last_seen=NULL` (never seen on network) are **NOT** removed
|
||||
- Nodes created via tag import that have never been seen on the mesh are preserved
|
||||
|
||||
**Note:** Both event data and node cleanup run on the same schedule (DATA_RETENTION_INTERVAL_HOURS).
|
||||
|
||||
**Contact Cleanup (Interface RECEIVER):**
|
||||
|
||||
The interface RECEIVER mode can automatically remove stale contacts from the MeshCore companion node's contact database. This prevents the companion node from resyncing old/dead contacts back to the collector, freeing up memory on the device (typically limited to ~100 contacts).
|
||||
|
||||
| Variable | Description |
|
||||
|----------|-------------|
|
||||
| `CONTACT_CLEANUP_ENABLED` | Enable automatic removal of stale contacts (default: true) |
|
||||
| `CONTACT_CLEANUP_DAYS` | Remove contacts not advertised for this many days (default: 7) |
|
||||
|
||||
When enabled, during each contact sync the receiver checks each contact's `last_advert` timestamp:
|
||||
- Contacts with `last_advert` older than `CONTACT_CLEANUP_DAYS` are removed from the device
|
||||
- Stale contacts are not published to MQTT (preventing collector database pollution)
|
||||
- Contacts without a `last_advert` timestamp are preserved (no removal without data)
|
||||
|
||||
This cleanup runs automatically whenever the receiver syncs contacts (on startup and after each advertisement event).
|
||||
|
||||
Manual cleanup can be triggered at any time with:
|
||||
```bash
|
||||
# Dry run to see what would be deleted
|
||||
meshcore-hub collector cleanup --retention-days 30 --dry-run
|
||||
|
||||
# Live cleanup
|
||||
meshcore-hub collector cleanup --retention-days 30
|
||||
```
|
||||
|
||||
Webhook payload structure:
|
||||
```json
|
||||
{
|
||||
@@ -486,9 +773,13 @@ Webhook payload structure:
|
||||
### Common Issues
|
||||
|
||||
1. **MQTT Connection Failed**: Check broker is running and `MQTT_HOST`/`MQTT_PORT` are correct
|
||||
2. **Database Migration Errors**: Ensure `DATABASE_URL` is correct, run `alembic upgrade head`
|
||||
2. **Database Migration Errors**: Ensure `DATA_HOME` is writable, run `meshcore-hub db upgrade`
|
||||
3. **Import Errors**: Ensure package is installed with `pip install -e .`
|
||||
4. **Type Errors**: Run `mypy src/` to check type annotations
|
||||
4. **Type Errors**: Run `pre-commit run --all-files` to check type annotations and other issues
|
||||
5. **NixOS greenlet errors**: On NixOS, the pre-built greenlet wheel may fail with `libstdc++.so.6` errors. Rebuild from source:
|
||||
```bash
|
||||
pip install --no-binary greenlet greenlet
|
||||
```
|
||||
|
||||
### Debugging
|
||||
|
||||
@@ -549,8 +840,23 @@ await mc.start_auto_message_fetching()
|
||||
|
||||
On startup, the receiver performs these initialization steps:
|
||||
1. Set device clock to current Unix timestamp
|
||||
2. Send a local (non-flood) advertisement
|
||||
3. Start automatic message fetching
|
||||
2. Optionally set the device name (if `MESHCORE_DEVICE_NAME` is configured)
|
||||
3. Send a flood advertisement (broadcasts device name to the mesh)
|
||||
4. Start automatic message fetching
|
||||
5. Sync the device's contact database
|
||||
|
||||
### Contact Sync Behavior
|
||||
|
||||
The receiver syncs the device's contact database in two scenarios:
|
||||
|
||||
1. **Startup**: Initial sync when receiver starts
|
||||
2. **Advertisement Events**: Automatic sync triggered whenever an advertisement is received from the mesh
|
||||
|
||||
Since advertisements are typically received every ~20 minutes, contact sync happens automatically without manual intervention. Each contact from the device is published individually to MQTT:
|
||||
- Topic: `{prefix}/{device_public_key}/event/contact`
|
||||
- Payload: `{public_key, adv_name, type}`
|
||||
|
||||
This ensures the collector's database stays current with all nodes discovered on the mesh network.
|
||||
|
||||
## References
|
||||
|
||||
|
||||
29
Dockerfile
29
Dockerfile
@@ -4,7 +4,7 @@
|
||||
# =============================================================================
|
||||
# Stage 1: Builder - Install dependencies and build package
|
||||
# =============================================================================
|
||||
FROM python:3.11-slim AS builder
|
||||
FROM python:3.14-slim AS builder
|
||||
|
||||
# Set environment variables
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
@@ -28,14 +28,18 @@ COPY src/ ./src/
|
||||
COPY alembic/ ./alembic/
|
||||
COPY alembic.ini ./
|
||||
|
||||
# Install the package
|
||||
RUN pip install --upgrade pip && \
|
||||
# Build argument for version (set via CI or manually)
|
||||
ARG BUILD_VERSION=dev
|
||||
|
||||
# Set version in _version.py and install the package
|
||||
RUN sed -i "s|__version__ = \"dev\"|__version__ = \"${BUILD_VERSION}\"|" src/meshcore_hub/_version.py && \
|
||||
pip install --upgrade pip && \
|
||||
pip install .
|
||||
|
||||
# =============================================================================
|
||||
# Stage 2: Runtime - Final production image
|
||||
# =============================================================================
|
||||
FROM python:3.11-slim AS runtime
|
||||
FROM python:3.14-slim AS runtime
|
||||
|
||||
# Labels
|
||||
LABEL org.opencontainers.image.title="MeshCore Hub" \
|
||||
@@ -61,9 +65,26 @@ ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
# For serial port access
|
||||
udev \
|
||||
# LetsMesh decoder runtime
|
||||
nodejs \
|
||||
npm \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& mkdir -p /data
|
||||
|
||||
# Install meshcore-decoder CLI.
|
||||
RUN mkdir -p /opt/letsmesh-decoder \
|
||||
&& cd /opt/letsmesh-decoder \
|
||||
&& npm init -y >/dev/null 2>&1 \
|
||||
&& npm install --omit=dev @michaelhart/meshcore-decoder@0.2.7 patch-package
|
||||
|
||||
# Apply maintained meshcore-decoder compatibility patch.
|
||||
COPY patches/@michaelhart+meshcore-decoder+0.2.7.patch /opt/letsmesh-decoder/patches/@michaelhart+meshcore-decoder+0.2.7.patch
|
||||
RUN cd /opt/letsmesh-decoder \
|
||||
&& npx patch-package --error-on-fail \
|
||||
&& npm uninstall patch-package \
|
||||
&& npm prune --omit=dev
|
||||
RUN ln -s /opt/letsmesh-decoder/node_modules/.bin/meshcore-decoder /usr/local/bin/meshcore-decoder
|
||||
|
||||
# Copy virtual environment from builder
|
||||
COPY --from=builder /opt/venv /opt/venv
|
||||
ENV PATH="/opt/venv/bin:$PATH"
|
||||
|
||||
15
PLAN.md
15
PLAN.md
@@ -481,6 +481,7 @@ ${DATA_HOME}/
|
||||
| INTERFACE_MODE | RECEIVER | RECEIVER or SENDER |
|
||||
| SERIAL_PORT | /dev/ttyUSB0 | Serial port path |
|
||||
| SERIAL_BAUD | 115200 | Baud rate |
|
||||
| MESHCORE_DEVICE_NAME | *(none)* | Device/node name set on startup |
|
||||
| MOCK_DEVICE | false | Use mock device |
|
||||
|
||||
### Collector
|
||||
@@ -488,6 +489,16 @@ ${DATA_HOME}/
|
||||
|----------|---------|-------------|
|
||||
| DATABASE_URL | sqlite:///{DATA_HOME}/collector/meshcore.db | SQLAlchemy URL |
|
||||
| TAGS_FILE | {DATA_HOME}/collector/tags.json | Path to tags JSON file |
|
||||
| COLLECTOR_INGEST_MODE | native | Ingest mode (`native` or `letsmesh_upload`) |
|
||||
| COLLECTOR_LETSMESH_DECODER_ENABLED | true | Enable external packet decoding in LetsMesh mode |
|
||||
|
||||
LetsMesh compatibility parity note:
|
||||
- `status` feed packets are stored as informational `letsmesh_status` events and do not create advertisement rows.
|
||||
- Advertisement rows in LetsMesh mode are created from decoded payload type `4` only.
|
||||
- Decoded payload type `11` is normalized to native `contact` updates.
|
||||
- Decoded payload type `9` is normalized to native `trace_data`.
|
||||
- Decoded payload type `8` is normalized to informational `path_updated`.
|
||||
- Decoded payload type `1` can map to native response-style events when decrypted structured content is available.
|
||||
|
||||
### API
|
||||
| Variable | Default | Description |
|
||||
@@ -505,6 +516,10 @@ ${DATA_HOME}/
|
||||
| WEB_PORT | 8080 | Web bind port |
|
||||
| API_BASE_URL | http://localhost:8000 | API endpoint |
|
||||
| API_KEY | | API key for queries |
|
||||
| WEB_TRUSTED_PROXY_HOSTS | * | Comma-separated list of trusted proxy hosts for admin authentication headers. Default: `*` (all hosts). Recommended: set to your reverse proxy IP in production. |
|
||||
| WEB_LOCALE | en | UI translation locale |
|
||||
| WEB_DATETIME_LOCALE | en-US | Date formatting locale for UI timestamps |
|
||||
| TZ | UTC | Timezone used for UI timestamp rendering |
|
||||
| NETWORK_DOMAIN | | Network domain |
|
||||
| NETWORK_NAME | MeshCore Network | Network name |
|
||||
| NETWORK_CITY | | City location |
|
||||
|
||||
692
README.md
692
README.md
@@ -1,6 +1,18 @@
|
||||
# MeshCore Hub
|
||||
|
||||
Python 3.11+ platform for managing and orchestrating MeshCore mesh networks.
|
||||
[](https://github.com/ipnet-mesh/meshcore-hub/actions/workflows/ci.yml)
|
||||
[](https://github.com/ipnet-mesh/meshcore-hub/actions/workflows/docker.yml)
|
||||
[](https://codecov.io/github/ipnet-mesh/meshcore-hub)
|
||||
[](https://www.buymeacoffee.com/jinglemansweep)
|
||||
|
||||
Python 3.13+ platform for managing and orchestrating MeshCore mesh networks.
|
||||
|
||||

|
||||
|
||||
> [!IMPORTANT]
|
||||
> **Help Translate MeshCore Hub** 🌍
|
||||
>
|
||||
> We need volunteers to translate the web dashboard! Currently only English is available. Check out the [Translation Guide](src/meshcore_hub/web/static/locales/languages.md) to contribute a language pack. Partial translations welcome!
|
||||
|
||||
## Overview
|
||||
|
||||
@@ -11,45 +23,49 @@ MeshCore Hub provides a complete solution for monitoring, collecting, and intera
|
||||
| **Interface** | Connects to MeshCore companion nodes via Serial/USB, bridges events to/from MQTT |
|
||||
| **Collector** | Subscribes to MQTT events and persists them to a database |
|
||||
| **API** | REST API for querying data and sending commands to the network |
|
||||
| **Web Dashboard** | User-friendly web interface for visualizing network status |
|
||||
| **Web Dashboard** | Single Page Application (SPA) for visualizing network status |
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
|
||||
│ MeshCore │ │ MeshCore │ │ MeshCore │
|
||||
│ Device 1 │ │ Device 2 │ │ Device 3 │
|
||||
└────────┬────────┘ └────────┬────────┘ └────────┬────────┘
|
||||
│ │ │
|
||||
│ Serial/USB │ Serial/USB │ Serial/USB
|
||||
│ │ │
|
||||
┌────────▼────────┐ ┌────────▼────────┐ ┌────────▼────────┐
|
||||
│ Interface │ │ Interface │ │ Interface │
|
||||
│ (RECEIVER) │ │ (RECEIVER) │ │ (SENDER) │
|
||||
└────────┬────────┘ └────────┬────────┘ └────────▲────────┘
|
||||
│ │ │
|
||||
│ Publish │ Publish │ Subscribe
|
||||
│ │ │
|
||||
└───────────┬───────────┴───────────────────────┘
|
||||
│
|
||||
┌──────▼──────┐
|
||||
│ MQTT │
|
||||
│ Broker │
|
||||
└──────┬──────┘
|
||||
│
|
||||
┌──────▼──────┐
|
||||
│ Collector │
|
||||
└──────┬──────┘
|
||||
│
|
||||
┌──────▼──────┐
|
||||
│ Database │
|
||||
└──────┬──────┘
|
||||
│
|
||||
┌───────────┴───────────┐
|
||||
│ │
|
||||
┌──────▼──────┐ ┌───────▼───────┐
|
||||
│ API │◄──────│ Web Dashboard │
|
||||
└─────────────┘ └───────────────┘
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph Devices["MeshCore Devices"]
|
||||
D1["Device 1"]
|
||||
D2["Device 2"]
|
||||
D3["Device 3"]
|
||||
end
|
||||
|
||||
subgraph Interfaces["Interface Layer"]
|
||||
I1["RECEIVER"]
|
||||
I2["RECEIVER"]
|
||||
I3["SENDER"]
|
||||
end
|
||||
|
||||
D1 -->|Serial| I1
|
||||
D2 -->|Serial| I2
|
||||
D3 -->|Serial| I3
|
||||
|
||||
I1 -->|Publish| MQTT
|
||||
I2 -->|Publish| MQTT
|
||||
MQTT -->|Subscribe| I3
|
||||
|
||||
MQTT["MQTT Broker"]
|
||||
|
||||
subgraph Backend["Backend Services"]
|
||||
Collector --> Database --> API
|
||||
end
|
||||
|
||||
MQTT --> Collector
|
||||
API --> Web["Web Dashboard"]
|
||||
|
||||
style Devices fill:none,stroke:#0288d1,stroke-width:2px
|
||||
style Interfaces fill:none,stroke:#f57c00,stroke-width:2px
|
||||
style Backend fill:none,stroke:#388e3c,stroke-width:2px
|
||||
style MQTT fill:none,stroke:#7b1fa2,stroke-width:3px
|
||||
style Collector fill:none,stroke:#388e3c,stroke-width:2px
|
||||
style Database fill:none,stroke:#c2185b,stroke-width:2px
|
||||
style API fill:none,stroke:#1976d2,stroke-width:2px
|
||||
style Web fill:none,stroke:#ffa000,stroke-width:2px
|
||||
```
|
||||
|
||||
## Features
|
||||
@@ -60,54 +76,144 @@ MeshCore Hub provides a complete solution for monitoring, collecting, and intera
|
||||
- **Command Dispatch**: Send messages and advertisements via the API
|
||||
- **Node Tagging**: Add custom metadata to nodes for organization
|
||||
- **Web Dashboard**: Visualize network status, node locations, and message history
|
||||
- **Internationalization**: Full i18n support with composable translation patterns
|
||||
- **Docker Ready**: Single image with all components, easy deployment
|
||||
|
||||
## Quick Start
|
||||
## Getting Started
|
||||
|
||||
### Using Docker Compose (Recommended)
|
||||
### Simple Self-Hosted Setup
|
||||
|
||||
Docker Compose supports **profiles** to selectively enable/disable components:
|
||||
The quickest way to get started is running the entire stack on a single machine with a connected MeshCore device.
|
||||
|
||||
| Profile | Services |
|
||||
|---------|----------|
|
||||
| `mqtt` | Eclipse Mosquitto MQTT broker |
|
||||
| `interface-receiver` | MeshCore device receiver (events to MQTT) |
|
||||
| `interface-sender` | MeshCore device sender (MQTT to device) |
|
||||
| `collector` | MQTT subscriber + database storage |
|
||||
| `api` | REST API server |
|
||||
| `web` | Web dashboard |
|
||||
| `mock` | All services with mock device (for testing) |
|
||||
| `all` | All production services |
|
||||
**Prerequisites:**
|
||||
1. Flash the [USB Companion firmware](https://meshcore.dev/) onto a compatible device (e.g., Heltec V3, T-Beam)
|
||||
2. Connect the device via USB to a machine that supports Docker or Python
|
||||
|
||||
**Steps:**
|
||||
```bash
|
||||
# Clone the repository
|
||||
git clone https://github.com/your-org/meshcore-hub.git
|
||||
cd meshcore-hub/docker
|
||||
# Create a directory, download the Docker Compose file and
|
||||
# example environment configuration file
|
||||
|
||||
mkdir meshcore-hub
|
||||
cd meshcore-hub
|
||||
wget https://raw.githubusercontent.com/ipnet-mesh/meshcore-hub/refs/heads/main/docker-compose.yml
|
||||
wget https://raw.githubusercontent.com/ipnet-mesh/meshcore-hub/refs/heads/main/.env.example
|
||||
|
||||
# Copy and configure environment
|
||||
cp .env.example .env
|
||||
# Edit .env with your settings (API keys, serial port, network info)
|
||||
# Edit .env: set SERIAL_PORT to your device (e.g., /dev/ttyUSB0 or /dev/ttyACM0)
|
||||
|
||||
# Option 1: Start all services with mock device (for testing)
|
||||
docker compose --profile mock up -d
|
||||
# Start the entire stack with local MQTT broker
|
||||
docker compose --profile mqtt --profile core --profile receiver up -d
|
||||
|
||||
# Option 2: Start specific services for production
|
||||
docker compose --profile mqtt --profile collector --profile api --profile web up -d
|
||||
# View the web dashboard
|
||||
open http://localhost:8080
|
||||
```
|
||||
|
||||
# Option 3: Start all production services (requires real MeshCore device)
|
||||
docker compose --profile all up -d
|
||||
This starts all services: MQTT broker, collector, API, web dashboard, and the interface receiver that bridges your MeshCore device to the system.
|
||||
|
||||
### Distributed Community Setup
|
||||
|
||||
For larger deployments, you can separate receiver nodes from the central infrastructure. This allows multiple community members to contribute receiver coverage while hosting the backend centrally.
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
subgraph Community["Community Members"]
|
||||
R1["Raspberry Pi + MeshCore"]
|
||||
R2["Raspberry Pi + MeshCore"]
|
||||
R3["Any Linux + MeshCore"]
|
||||
end
|
||||
|
||||
subgraph Server["Community VPS / Server"]
|
||||
MQTT["MQTT Broker"]
|
||||
Collector
|
||||
API
|
||||
Web["Web Dashboard (public)"]
|
||||
|
||||
MQTT --> Collector --> API
|
||||
API <--- Web
|
||||
end
|
||||
|
||||
R1 -->|MQTT port 1883| MQTT
|
||||
R2 -->|MQTT port 1883| MQTT
|
||||
R3 -->|MQTT port 1883| MQTT
|
||||
|
||||
style Community fill:none,stroke:#0288d1,stroke-width:2px
|
||||
style Server fill:none,stroke:#388e3c,stroke-width:2px
|
||||
style MQTT fill:none,stroke:#7b1fa2,stroke-width:3px
|
||||
style Collector fill:none,stroke:#388e3c,stroke-width:2px
|
||||
style API fill:none,stroke:#1976d2,stroke-width:2px
|
||||
style Web fill:none,stroke:#ffa000,stroke-width:2px
|
||||
```
|
||||
|
||||
**On each receiver node (Raspberry Pi, etc.):**
|
||||
```bash
|
||||
# Only run the receiver component
|
||||
# Configure .env with MQTT_HOST pointing to your central server
|
||||
MQTT_HOST=your-community-server.com
|
||||
SERIAL_PORT=/dev/ttyUSB0
|
||||
|
||||
docker compose --profile receiver up -d
|
||||
```
|
||||
|
||||
**On the central server (VPS/cloud):**
|
||||
```bash
|
||||
# Run the core infrastructure with local MQTT broker
|
||||
docker compose --profile mqtt --profile core up -d
|
||||
|
||||
# Or connect to an existing MQTT broker (set MQTT_HOST in .env)
|
||||
docker compose --profile core up -d
|
||||
```
|
||||
|
||||
This architecture allows:
|
||||
- Multiple receivers for better RF coverage across a geographic area
|
||||
- Centralized data storage and web interface
|
||||
- Community members to contribute coverage with minimal setup
|
||||
- The central server to be hosted anywhere with internet access
|
||||
|
||||
## Deployment
|
||||
|
||||
### Docker Compose Profiles
|
||||
|
||||
Docker Compose uses **profiles** to select which services to run:
|
||||
|
||||
| Profile | Services | Use Case |
|
||||
|---------|----------|----------|
|
||||
| `core` | db-migrate, collector, api, web | Central server infrastructure |
|
||||
| `receiver` | interface-receiver | Receiver node (events to MQTT) |
|
||||
| `sender` | interface-sender | Sender node (MQTT to device) |
|
||||
| `mqtt` | mosquitto broker | Local MQTT broker (optional) |
|
||||
| `mock` | interface-mock-receiver | Testing without hardware |
|
||||
| `migrate` | db-migrate | One-time database migration |
|
||||
| `seed` | seed | One-time seed data import |
|
||||
| `metrics` | prometheus, alertmanager | Prometheus metrics and alerting |
|
||||
|
||||
**Note:** Most deployments connect to an external MQTT broker. Add `--profile mqtt` only if you need a local broker.
|
||||
|
||||
```bash
|
||||
# Create database schema
|
||||
docker compose --profile migrate run --rm db-migrate
|
||||
|
||||
# Seed the database
|
||||
docker compose --profile seed run --rm seed
|
||||
|
||||
# Start core services with local MQTT broker
|
||||
docker compose --profile mqtt --profile core up -d
|
||||
|
||||
# Or connect to external MQTT (configure MQTT_HOST in .env)
|
||||
docker compose --profile core up -d
|
||||
|
||||
# Start just the receiver (connects to MQTT_HOST from .env)
|
||||
docker compose --profile receiver up -d
|
||||
|
||||
# View logs
|
||||
docker compose logs -f
|
||||
|
||||
# Run database migrations
|
||||
docker compose --profile migrate up
|
||||
|
||||
# Stop services
|
||||
docker compose --profile mock down
|
||||
docker compose down
|
||||
```
|
||||
|
||||
#### Serial Device Access
|
||||
### Serial Device Access
|
||||
|
||||
For production with real MeshCore devices, ensure the serial port is accessible:
|
||||
|
||||
@@ -123,13 +229,25 @@ SERIAL_PORT=/dev/ttyUSB0
|
||||
SERIAL_PORT_SENDER=/dev/ttyUSB1 # If using separate sender device
|
||||
```
|
||||
|
||||
**Tip:** If USB devices reconnect as different numeric IDs (e.g., `/dev/ttyUSB0` becomes `/dev/ttyUSB1`), use the stable `/dev/serial/by-id/` path instead:
|
||||
|
||||
```bash
|
||||
# List available devices by ID
|
||||
ls -la /dev/serial/by-id/
|
||||
|
||||
# Example output:
|
||||
# usb-Silicon_Labs_CP2102N_USB_to_UART_Bridge_abc123-if00-port0 -> ../../ttyUSB0
|
||||
|
||||
# Configure using the stable ID
|
||||
SERIAL_PORT=/dev/serial/by-id/usb-Silicon_Labs_CP2102N_USB_to_UART_Bridge_abc123-if00-port0
|
||||
```
|
||||
|
||||
### Manual Installation
|
||||
|
||||
```bash
|
||||
# Create virtual environment
|
||||
python -m venv .venv
|
||||
source .venv/bin/activate # Linux/macOS
|
||||
# .venv\Scripts\activate # Windows
|
||||
source .venv/bin/activate
|
||||
|
||||
# Install the package
|
||||
pip install -e ".[dev]"
|
||||
@@ -138,7 +256,7 @@ pip install -e ".[dev]"
|
||||
meshcore-hub db upgrade
|
||||
|
||||
# Start components (in separate terminals)
|
||||
meshcore-hub interface --mode receiver --port /dev/ttyUSB0
|
||||
meshcore-hub interface receiver --port /dev/ttyUSB0
|
||||
meshcore-hub collector
|
||||
meshcore-hub api
|
||||
meshcore-hub web
|
||||
@@ -153,28 +271,70 @@ All components are configured via environment variables. Create a `.env` file or
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `LOG_LEVEL` | `INFO` | Logging level (DEBUG, INFO, WARNING, ERROR) |
|
||||
| `DATA_HOME` | `./data` | Base directory for runtime data |
|
||||
| `SEED_HOME` | `./seed` | Directory containing seed data files |
|
||||
| `MQTT_HOST` | `localhost` | MQTT broker hostname |
|
||||
| `MQTT_PORT` | `1883` | MQTT broker port |
|
||||
| `MQTT_USERNAME` | *(none)* | MQTT username (optional) |
|
||||
| `MQTT_PASSWORD` | *(none)* | MQTT password (optional) |
|
||||
| `MQTT_PREFIX` | `meshcore` | Topic prefix for all MQTT messages |
|
||||
| `MQTT_TLS` | `false` | Enable TLS/SSL for MQTT connection |
|
||||
| `MQTT_TRANSPORT` | `tcp` | MQTT transport (`tcp` or `websockets`) |
|
||||
| `MQTT_WS_PATH` | `/mqtt` | MQTT WebSocket path (used when `MQTT_TRANSPORT=websockets`) |
|
||||
|
||||
### Interface Settings
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `INTERFACE_MODE` | `RECEIVER` | Operating mode (RECEIVER or SENDER) |
|
||||
| `SERIAL_PORT` | `/dev/ttyUSB0` | Serial port for MeshCore device |
|
||||
| `SERIAL_BAUD` | `115200` | Serial baud rate |
|
||||
| `MOCK_DEVICE` | `false` | Use mock device for testing |
|
||||
| `MESHCORE_DEVICE_NAME` | *(none)* | Device/node name set on startup (broadcast in advertisements) |
|
||||
| `NODE_ADDRESS` | *(none)* | Override for device public key (64-char hex string) |
|
||||
| `NODE_ADDRESS_SENDER` | *(none)* | Override for sender device public key |
|
||||
| `CONTACT_CLEANUP_ENABLED` | `true` | Enable automatic removal of stale contacts from companion node |
|
||||
| `CONTACT_CLEANUP_DAYS` | `7` | Remove contacts not advertised for this many days |
|
||||
|
||||
### Collector Settings
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `DATABASE_URL` | `sqlite:///./meshcore.db` | SQLAlchemy database URL |
|
||||
| `COLLECTOR_INGEST_MODE` | `native` | Ingest mode (`native` or `letsmesh_upload`) |
|
||||
| `COLLECTOR_LETSMESH_DECODER_ENABLED` | `true` | Enable external LetsMesh packet decoding |
|
||||
| `COLLECTOR_LETSMESH_DECODER_COMMAND` | `meshcore-decoder` | Decoder CLI command |
|
||||
| `COLLECTOR_LETSMESH_DECODER_KEYS` | *(none)* | Additional decoder channel keys (`label=hex`, `label:hex`, or `hex`) |
|
||||
| `COLLECTOR_LETSMESH_DECODER_TIMEOUT_SECONDS` | `2.0` | Timeout per decoder invocation |
|
||||
|
||||
#### Webhook Configuration
|
||||
#### LetsMesh Upload Compatibility Mode
|
||||
|
||||
The collector can forward events to external HTTP endpoints:
|
||||
When `COLLECTOR_INGEST_MODE=letsmesh_upload`, the collector subscribes to:
|
||||
|
||||
- `<prefix>/+/packets`
|
||||
- `<prefix>/+/status`
|
||||
- `<prefix>/+/internal`
|
||||
|
||||
Normalization behavior:
|
||||
|
||||
- `status` packets are stored as informational `letsmesh_status` events and are not mapped to `advertisement` rows.
|
||||
- Decoder payload type `4` is mapped to `advertisement` when node identity metadata is present.
|
||||
- Decoder payload type `11` (control discover response) is mapped to `contact`.
|
||||
- Decoder payload type `9` is mapped to `trace_data`.
|
||||
- Decoder payload type `8` is mapped to informational `path_updated` events.
|
||||
- Decoder payload type `1` can map to native response events (`telemetry_response`, `battery`, `path_updated`, `status_response`) when decrypted structured content is available.
|
||||
- `packet_type=5` packets are mapped to `channel_msg_recv`.
|
||||
- `packet_type=1`, `2`, and `7` packets are mapped to `contact_msg_recv` when decryptable text is available.
|
||||
- For channel packets, if a channel key is available, a channel label is attached (for example `Public` or `#test`) for UI display.
|
||||
- In the messages feed and dashboard channel sections, known channel indexes are preferred for labels (`17 -> Public`, `217 -> #test`) to avoid stale channel-name mismatches.
|
||||
- Additional channel names are loaded from `COLLECTOR_LETSMESH_DECODER_KEYS` when entries are provided as `label=hex` (for example `bot=<key>`).
|
||||
- Decoder-advertisement packets with location metadata update node GPS (`lat/lon`) for map display.
|
||||
- This keeps advertisement listings closer to native mode behavior (node advert traffic only, not observer status telemetry).
|
||||
- Packets without decryptable message text are kept as informational `letsmesh_packet` events and are not shown in the messages feed; when decode succeeds the decoded JSON is attached to those packet log events.
|
||||
- When decoder output includes a human sender (`payload.decoded.decrypted.sender`), message text is normalized to `Name: Message` before storage; receiver/observer names are never used as sender fallback.
|
||||
- The collector keeps built-in keys for `Public` and `#test`, and merges any additional keys from `COLLECTOR_LETSMESH_DECODER_KEYS`.
|
||||
- Docker runtime installs `@michaelhart/meshcore-decoder@0.2.7` and applies `patches/@michaelhart+meshcore-decoder+0.2.7.patch` via `patch-package` for Node compatibility.
|
||||
|
||||
### Webhooks
|
||||
|
||||
The collector can forward certain events to external HTTP endpoints:
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
@@ -183,7 +343,9 @@ The collector can forward events to external HTTP endpoints:
|
||||
| `WEBHOOK_MESSAGE_URL` | *(none)* | Webhook URL for all message events |
|
||||
| `WEBHOOK_MESSAGE_SECRET` | *(none)* | Secret for message webhook |
|
||||
| `WEBHOOK_CHANNEL_MESSAGE_URL` | *(none)* | Override URL for channel messages only |
|
||||
| `WEBHOOK_CHANNEL_MESSAGE_SECRET` | *(none)* | Secret for channel message webhook |
|
||||
| `WEBHOOK_DIRECT_MESSAGE_URL` | *(none)* | Override URL for direct messages only |
|
||||
| `WEBHOOK_DIRECT_MESSAGE_SECRET` | *(none)* | Secret for direct message webhook |
|
||||
| `WEBHOOK_TIMEOUT` | `10.0` | Request timeout in seconds |
|
||||
| `WEBHOOK_MAX_RETRIES` | `3` | Max retry attempts on failure |
|
||||
| `WEBHOOK_RETRY_BACKOFF` | `2.0` | Exponential backoff multiplier |
|
||||
@@ -197,6 +359,18 @@ Webhook payload format:
|
||||
}
|
||||
```
|
||||
|
||||
### Data Retention
|
||||
|
||||
The collector automatically cleans up old event data and inactive nodes:
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `DATA_RETENTION_ENABLED` | `true` | Enable automatic cleanup of old events |
|
||||
| `DATA_RETENTION_DAYS` | `30` | Days to retain event data |
|
||||
| `DATA_RETENTION_INTERVAL_HOURS` | `24` | Hours between cleanup runs |
|
||||
| `NODE_CLEANUP_ENABLED` | `true` | Enable removal of inactive nodes |
|
||||
| `NODE_CLEANUP_DAYS` | `7` | Remove nodes not seen for this many days |
|
||||
|
||||
### API Settings
|
||||
|
||||
| Variable | Default | Description |
|
||||
@@ -205,6 +379,8 @@ Webhook payload format:
|
||||
| `API_PORT` | `8000` | API port |
|
||||
| `API_READ_KEY` | *(none)* | Read-only API key |
|
||||
| `API_ADMIN_KEY` | *(none)* | Admin API key (required for commands) |
|
||||
| `METRICS_ENABLED` | `true` | Enable Prometheus metrics endpoint at `/metrics` |
|
||||
| `METRICS_CACHE_TTL` | `60` | Seconds to cache metrics output (reduces database load) |
|
||||
|
||||
### Web Dashboard Settings
|
||||
|
||||
@@ -213,134 +389,248 @@ Webhook payload format:
|
||||
| `WEB_HOST` | `0.0.0.0` | Web server bind address |
|
||||
| `WEB_PORT` | `8080` | Web server port |
|
||||
| `API_BASE_URL` | `http://localhost:8000` | API endpoint URL |
|
||||
| `API_KEY` | *(none)* | API key for web dashboard queries (optional) |
|
||||
| `WEB_THEME` | `dark` | Default theme (`dark` or `light`). Users can override via theme toggle in navbar. |
|
||||
| `WEB_LOCALE` | `en` | Locale/language for the web dashboard (e.g., `en`, `es`, `fr`) |
|
||||
| `WEB_DATETIME_LOCALE` | `en-US` | Locale used for date formatting in the web dashboard (e.g., `en-US` for MM/DD/YYYY, `en-GB` for DD/MM/YYYY). |
|
||||
| `WEB_AUTO_REFRESH_SECONDS` | `30` | Auto-refresh interval in seconds for list pages (0 to disable) |
|
||||
| `WEB_ADMIN_ENABLED` | `false` | Enable admin interface at /a/ (requires auth proxy: `X-Forwarded-User`/`X-Auth-Request-User` or forwarded `Authorization: Basic ...`) |
|
||||
| `WEB_TRUSTED_PROXY_HOSTS` | `*` | Comma-separated list of trusted proxy hosts for admin authentication headers. Default: `*` (all hosts). Recommended: set to your reverse proxy IP in production. A startup warning is emitted when using the default `*` with admin enabled. |
|
||||
| `TZ` | `UTC` | Timezone for displaying dates/times (e.g., `America/New_York`, `Europe/London`) |
|
||||
| `NETWORK_DOMAIN` | *(none)* | Network domain name (optional) |
|
||||
| `NETWORK_NAME` | `MeshCore Network` | Display name for the network |
|
||||
| `NETWORK_CITY` | *(none)* | City where network is located |
|
||||
| `NETWORK_COUNTRY` | *(none)* | Country code (ISO 3166-1 alpha-2) |
|
||||
| `NETWORK_LOCATION` | *(none)* | Center coordinates (lat,lon) |
|
||||
| `NETWORK_RADIO_CONFIG` | *(none)* | Radio config (comma-delimited: profile,freq,bw,sf,cr,power) |
|
||||
| `NETWORK_WELCOME_TEXT` | *(none)* | Custom welcome text for homepage |
|
||||
| `NETWORK_CONTACT_EMAIL` | *(none)* | Contact email address |
|
||||
| `NETWORK_CONTACT_DISCORD` | *(none)* | Discord server link |
|
||||
| `NETWORK_CONTACT_GITHUB` | *(none)* | GitHub repository URL |
|
||||
| `NETWORK_CONTACT_YOUTUBE` | *(none)* | YouTube channel URL |
|
||||
| `CONTENT_HOME` | `./content` | Directory containing custom content (pages/, media/) |
|
||||
|
||||
## CLI Reference
|
||||
Timezone handling note:
|
||||
- API timestamps that omit an explicit timezone suffix are treated as UTC before rendering in the configured `TZ`.
|
||||
|
||||
```bash
|
||||
# Show help
|
||||
meshcore-hub --help
|
||||
#### Nginx Proxy Manager (NPM) Admin Setup
|
||||
|
||||
# Interface component
|
||||
meshcore-hub interface --mode receiver --port /dev/ttyUSB0
|
||||
meshcore-hub interface --mode sender --mock # Use mock device
|
||||
Use two hostnames so the public map/site stays open while admin stays protected:
|
||||
|
||||
# Collector component
|
||||
meshcore-hub collector --database-url sqlite:///./data.db
|
||||
1. Public host: no Access List (normal users).
|
||||
2. Admin host: Access List enabled (operators only).
|
||||
|
||||
# Import node tags from JSON file
|
||||
meshcore-hub collector import-tags /path/to/tags.json
|
||||
Both proxy hosts should forward to the same web container:
|
||||
- Scheme: `http`
|
||||
- Forward Hostname/IP: your MeshCore Hub host
|
||||
- Forward Port: `18080` (or your mapped web port)
|
||||
- Websockets Support: `ON`
|
||||
- Block Common Exploits: `ON`
|
||||
|
||||
# API component
|
||||
meshcore-hub api --host 0.0.0.0 --port 8000
|
||||
Important:
|
||||
- Do not host this app under a subpath (for example `/meshcore`); proxy it at `/`.
|
||||
- `WEB_ADMIN_ENABLED` must be `true`.
|
||||
|
||||
# Web dashboard
|
||||
meshcore-hub web --port 8080 --network-name "My Network"
|
||||
In NPM, for the **admin host**, paste this in the `Advanced` field:
|
||||
|
||||
# Database management
|
||||
meshcore-hub db upgrade # Run migrations
|
||||
meshcore-hub db downgrade # Rollback one migration
|
||||
meshcore-hub db current # Show current revision
|
||||
```nginx
|
||||
# Forward authenticated identity for MeshCore Hub admin checks
|
||||
proxy_set_header Authorization $http_authorization;
|
||||
proxy_set_header X-Forwarded-User $remote_user;
|
||||
proxy_set_header X-Auth-Request-User $remote_user;
|
||||
proxy_set_header X-Forwarded-Email "";
|
||||
proxy_set_header X-Forwarded-Groups "";
|
||||
```
|
||||
|
||||
## Node Tags
|
||||
Then attach your NPM Access List (Basic auth users) to that admin host.
|
||||
|
||||
Verify auth forwarding:
|
||||
|
||||
```bash
|
||||
curl -s -u 'admin:password' "https://admin.example.com/config.js?t=$(date +%s)" \
|
||||
| grep -o '"is_authenticated":[^,]*'
|
||||
```
|
||||
|
||||
Expected:
|
||||
|
||||
```text
|
||||
"is_authenticated": true
|
||||
```
|
||||
|
||||
If it still shows `false`, check:
|
||||
1. You are using the admin hostname, not the public hostname.
|
||||
2. The Access List is attached to that admin host.
|
||||
3. The `Advanced` block above is present exactly.
|
||||
4. `WEB_ADMIN_ENABLED=true` is loaded in the running web container.
|
||||
|
||||
#### Feature Flags
|
||||
|
||||
Control which pages are visible in the web dashboard. Disabled features are fully hidden: removed from navigation, return 404 on their routes, and excluded from sitemap/robots.txt.
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `FEATURE_DASHBOARD` | `true` | Enable the `/dashboard` page |
|
||||
| `FEATURE_NODES` | `true` | Enable the `/nodes` pages (list, detail, short links) |
|
||||
| `FEATURE_ADVERTISEMENTS` | `true` | Enable the `/advertisements` page |
|
||||
| `FEATURE_MESSAGES` | `true` | Enable the `/messages` page |
|
||||
| `FEATURE_MAP` | `true` | Enable the `/map` page and `/map/data` endpoint |
|
||||
| `FEATURE_MEMBERS` | `true` | Enable the `/members` page |
|
||||
| `FEATURE_PAGES` | `true` | Enable custom markdown pages |
|
||||
|
||||
**Dependencies:** Dashboard auto-disables when all of Nodes/Advertisements/Messages are disabled. Map auto-disables when Nodes is disabled.
|
||||
|
||||
### Custom Content
|
||||
|
||||
The web dashboard supports custom content including markdown pages and media files. Content is organized in subdirectories:
|
||||
|
||||
Custom logo options:
|
||||
- `logo.svg` — full-color logo, displayed as-is in both themes (no automatic darkening)
|
||||
- `logo-invert.svg` — monochrome/two-tone logo, automatically darkened in light mode for visibility
|
||||
```
|
||||
content/
|
||||
├── pages/ # Custom markdown pages
|
||||
│ └── about.md
|
||||
└── media/ # Custom media files
|
||||
└── images/
|
||||
├── logo.svg # Full-color custom logo (default)
|
||||
└── logo-invert.svg # Monochrome custom logo (darkened in light mode)
|
||||
```
|
||||
|
||||
**Setup:**
|
||||
```bash
|
||||
# Create content directory structure
|
||||
mkdir -p content/pages content/media
|
||||
|
||||
# Create a custom page
|
||||
cat > content/pages/about.md << 'EOF'
|
||||
---
|
||||
title: About Us
|
||||
slug: about
|
||||
menu_order: 10
|
||||
---
|
||||
|
||||
# About Our Network
|
||||
|
||||
Welcome to our MeshCore mesh network!
|
||||
|
||||
## Getting Started
|
||||
|
||||
1. Get a compatible LoRa device
|
||||
2. Flash MeshCore firmware
|
||||
3. Configure your radio settings
|
||||
EOF
|
||||
```
|
||||
|
||||
**Frontmatter fields:**
|
||||
| Field | Default | Description |
|
||||
|-------|---------|-------------|
|
||||
| `title` | Filename titlecased | Browser tab title and navigation link text (not rendered on page) |
|
||||
| `slug` | Filename without `.md` | URL path (e.g., `about` → `/pages/about`) |
|
||||
| `menu_order` | `100` | Sort order in navigation (lower = earlier) |
|
||||
|
||||
The markdown content is rendered as-is, so include your own `# Heading` if desired.
|
||||
|
||||
Pages automatically appear in the navigation menu and sitemap. With Docker, mount the content directory:
|
||||
|
||||
```yaml
|
||||
# docker-compose.yml (already configured)
|
||||
volumes:
|
||||
- ${CONTENT_HOME:-./content}:/content:ro
|
||||
environment:
|
||||
- CONTENT_HOME=/content
|
||||
```
|
||||
|
||||
## Seed Data
|
||||
|
||||
The database can be seeded with node tags and network members from YAML files in the `SEED_HOME` directory (default: `./seed`).
|
||||
|
||||
#### Running the Seed Process
|
||||
|
||||
Seeding is a separate process and must be run explicitly:
|
||||
|
||||
```bash
|
||||
docker compose --profile seed up
|
||||
```
|
||||
|
||||
This imports data from the following files (if they exist):
|
||||
- `{SEED_HOME}/node_tags.yaml` - Node tag definitions
|
||||
- `{SEED_HOME}/members.yaml` - Network member definitions
|
||||
|
||||
#### Directory Structure
|
||||
|
||||
```
|
||||
seed/ # SEED_HOME (seed data files)
|
||||
├── node_tags.yaml # Node tags for import
|
||||
└── members.yaml # Network members for import
|
||||
|
||||
data/ # DATA_HOME (runtime data)
|
||||
└── collector/
|
||||
└── meshcore.db # SQLite database
|
||||
```
|
||||
|
||||
Example seed files are provided in `example/seed/`.
|
||||
|
||||
### Node Tags
|
||||
|
||||
Node tags allow you to attach custom metadata to nodes (e.g., location, role, owner). Tags are stored in the database and returned with node data via the API.
|
||||
|
||||
### Importing Tags from JSON
|
||||
#### Node Tags YAML Format
|
||||
|
||||
Tags can be bulk imported from a JSON file:
|
||||
Tags are keyed by public key in YAML format:
|
||||
|
||||
```bash
|
||||
# Native CLI
|
||||
meshcore-hub collector import-tags /path/to/tags.json
|
||||
```yaml
|
||||
# Each key is a 64-character hex public key
|
||||
0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef:
|
||||
name: Gateway Node
|
||||
description: Main network gateway
|
||||
role: gateway
|
||||
lat: 37.7749
|
||||
lon: -122.4194
|
||||
member_id: alice
|
||||
|
||||
# With Docker Compose
|
||||
docker compose --profile import-tags run --rm import-tags
|
||||
fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210:
|
||||
name: Oakland Repeater
|
||||
elevation: 150
|
||||
```
|
||||
|
||||
### Tags JSON Format
|
||||
Tag values can be:
|
||||
- **YAML primitives** (auto-detected type): strings, numbers, booleans
|
||||
- **Explicit type** (when you need to force a specific type):
|
||||
```yaml
|
||||
altitude:
|
||||
value: "150"
|
||||
type: number
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"tags": [
|
||||
{
|
||||
"public_key": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
|
||||
"key": "location",
|
||||
"value": "San Francisco, CA",
|
||||
"value_type": "string"
|
||||
},
|
||||
{
|
||||
"public_key": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
|
||||
"key": "altitude",
|
||||
"value": "150",
|
||||
"value_type": "number"
|
||||
}
|
||||
]
|
||||
}
|
||||
Supported types: `string`, `number`, `boolean`
|
||||
|
||||
### Network Members
|
||||
|
||||
Network members represent the people operating nodes in your network. Members can optionally be linked to nodes via their public key.
|
||||
|
||||
#### Members YAML Format
|
||||
|
||||
```yaml
|
||||
- member_id: walshie86
|
||||
name: Walshie
|
||||
callsign: Walshie86
|
||||
role: member
|
||||
description: IPNet Member
|
||||
- member_id: craig
|
||||
name: Craig
|
||||
callsign: M7XCN
|
||||
role: member
|
||||
description: IPNet Member
|
||||
```
|
||||
|
||||
| Field | Required | Description |
|
||||
|-------|----------|-------------|
|
||||
| `public_key` | Yes | 64-character hex public key of the node |
|
||||
| `key` | Yes | Tag name (max 100 characters) |
|
||||
| `value` | No | Tag value (stored as text) |
|
||||
| `value_type` | No | Type hint: `string`, `number`, `boolean`, or `coordinate` (default: `string`) |
|
||||
|
||||
### Import Options
|
||||
|
||||
```bash
|
||||
# Create nodes if they don't exist (default behavior)
|
||||
meshcore-hub collector import-tags tags.json
|
||||
|
||||
# Skip tags for nodes that don't exist
|
||||
meshcore-hub collector import-tags --no-create-nodes tags.json
|
||||
```
|
||||
|
||||
### Data Directory Structure
|
||||
|
||||
For Docker deployments, organize your data files:
|
||||
|
||||
```
|
||||
data/
|
||||
├── collector/
|
||||
│ └── tags.json # Node tags for import
|
||||
└── web/
|
||||
└── members.json # Network members list
|
||||
```
|
||||
|
||||
Example files are provided in `example/data/`.
|
||||
|
||||
### Managing Tags via API
|
||||
|
||||
Tags can also be managed via the REST API:
|
||||
|
||||
```bash
|
||||
# List tags for a node
|
||||
curl http://localhost:8000/api/v1/nodes/{public_key}/tags
|
||||
|
||||
# Create a tag (requires admin key)
|
||||
curl -X POST \
|
||||
-H "Authorization: Bearer <API_ADMIN_KEY>" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"key": "location", "value": "Building A"}' \
|
||||
http://localhost:8000/api/v1/nodes/{public_key}/tags
|
||||
|
||||
# Update a tag
|
||||
curl -X PUT \
|
||||
-H "Authorization: Bearer <API_ADMIN_KEY>" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"value": "Building B"}' \
|
||||
http://localhost:8000/api/v1/nodes/{public_key}/tags/location
|
||||
|
||||
# Delete a tag
|
||||
curl -X DELETE \
|
||||
-H "Authorization: Bearer <API_ADMIN_KEY>" \
|
||||
http://localhost:8000/api/v1/nodes/{public_key}/tags/location
|
||||
```
|
||||
| `member_id` | Yes | Unique identifier for the member |
|
||||
| `name` | Yes | Member's display name |
|
||||
| `callsign` | No | Amateur radio callsign |
|
||||
| `role` | No | Member's role in the network |
|
||||
| `description` | No | Additional description |
|
||||
| `contact` | No | Contact information |
|
||||
| `public_key` | No | Associated node public key (64-char hex) |
|
||||
|
||||
## API Documentation
|
||||
|
||||
@@ -354,6 +644,7 @@ Health check endpoints are also available:
|
||||
|
||||
- **Health**: http://localhost:8000/health
|
||||
- **Ready**: http://localhost:8000/health/ready (includes database check)
|
||||
- **Metrics**: http://localhost:8000/metrics (Prometheus format)
|
||||
|
||||
### Authentication
|
||||
|
||||
@@ -377,15 +668,21 @@ curl -X POST \
|
||||
|--------|----------|-------------|
|
||||
| GET | `/api/v1/nodes` | List all known nodes |
|
||||
| GET | `/api/v1/nodes/{public_key}` | Get node details |
|
||||
| GET | `/api/v1/nodes/prefix/{prefix}` | Get node by public key prefix |
|
||||
| GET | `/api/v1/nodes/{public_key}/tags` | Get node tags |
|
||||
| POST | `/api/v1/nodes/{public_key}/tags` | Create node tag |
|
||||
| GET | `/api/v1/messages` | List messages with filters |
|
||||
| GET | `/api/v1/advertisements` | List advertisements |
|
||||
| GET | `/api/v1/telemetry` | List telemetry data |
|
||||
| GET | `/api/v1/trace-paths` | List trace paths |
|
||||
| GET | `/api/v1/members` | List network members |
|
||||
| POST | `/api/v1/commands/send-message` | Send direct message |
|
||||
| POST | `/api/v1/commands/send-channel-message` | Send channel message |
|
||||
| GET | `/api/v1/stats` | Get network statistics |
|
||||
| POST | `/api/v1/commands/send-advertisement` | Send advertisement |
|
||||
| GET | `/api/v1/dashboard/stats` | Get network statistics |
|
||||
| GET | `/api/v1/dashboard/activity` | Get daily advertisement activity |
|
||||
| GET | `/api/v1/dashboard/message-activity` | Get daily message activity |
|
||||
| GET | `/api/v1/dashboard/node-count` | Get cumulative node count history |
|
||||
|
||||
## Development
|
||||
|
||||
@@ -393,7 +690,7 @@ curl -X POST \
|
||||
|
||||
```bash
|
||||
# Clone and setup
|
||||
git clone https://github.com/your-org/meshcore-hub.git
|
||||
git clone https://github.com/ipnet-mesh/meshcore-hub.git
|
||||
cd meshcore-hub
|
||||
python -m venv .venv
|
||||
source .venv/bin/activate
|
||||
@@ -422,14 +719,8 @@ pytest -k "test_list"
|
||||
### Code Quality
|
||||
|
||||
```bash
|
||||
# Format code
|
||||
black src/ tests/
|
||||
|
||||
# Lint
|
||||
flake8 src/ tests/
|
||||
|
||||
# Type check
|
||||
mypy src/
|
||||
# Run all code quality checks (formatting, linting, type checking)
|
||||
pre-commit run --all-files
|
||||
```
|
||||
|
||||
### Creating Database Migrations
|
||||
@@ -455,15 +746,30 @@ meshcore-hub/
|
||||
│ ├── collector/ # MQTT event collector
|
||||
│ ├── api/ # REST API
|
||||
│ └── web/ # Web dashboard
|
||||
│ ├── templates/ # Jinja2 templates (SPA shell)
|
||||
│ └── static/
|
||||
│ ├── js/spa/ # SPA frontend (ES modules, lit-html)
|
||||
│ └── locales/ # Translation files (en.json, languages.md)
|
||||
├── tests/ # Test suite
|
||||
├── alembic/ # Database migrations
|
||||
├── etc/ # Configuration files (mosquitto.conf)
|
||||
├── example/ # Example files for testing
|
||||
│ └── data/ # Example data files (members.json)
|
||||
├── data/ # Runtime data (gitignored)
|
||||
├── etc/ # Configuration files (MQTT, Prometheus, Alertmanager)
|
||||
├── example/ # Example files for reference
|
||||
│ ├── seed/ # Example seed data files
|
||||
│ │ ├── node_tags.yaml # Example node tags
|
||||
│ │ └── members.yaml # Example network members
|
||||
│ └── content/ # Example custom content
|
||||
│ ├── pages/ # Example custom pages
|
||||
│ │ └── join.md # Example join page
|
||||
│ └── media/ # Example media files
|
||||
│ └── images/ # Custom images
|
||||
├── seed/ # Seed data directory (SEED_HOME, copy from example/seed/)
|
||||
├── content/ # Custom content directory (CONTENT_HOME, optional)
|
||||
│ ├── pages/ # Custom markdown pages
|
||||
│ └── media/ # Custom media files
|
||||
│ └── images/ # Custom images (logo.svg/png/jpg/jpeg/webp replace default logo)
|
||||
├── data/ # Runtime data directory (DATA_HOME, created at runtime)
|
||||
├── Dockerfile # Docker build configuration
|
||||
├── docker-compose.yml # Docker Compose services (gitignored)
|
||||
├── docker-compose.yml.example # Docker Compose template
|
||||
├── docker-compose.yml # Docker Compose services
|
||||
├── PROMPT.md # Project specification
|
||||
├── SCHEMAS.md # Event schema documentation
|
||||
├── PLAN.md # Implementation plan
|
||||
@@ -484,14 +790,14 @@ meshcore-hub/
|
||||
1. Fork the repository
|
||||
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
|
||||
3. Make your changes
|
||||
4. Run tests and linting (`pytest && black . && flake8`)
|
||||
4. Run tests and quality checks (`pytest && pre-commit run --all-files`)
|
||||
5. Commit your changes (`git commit -m 'Add amazing feature'`)
|
||||
6. Push to the branch (`git push origin feature/amazing-feature`)
|
||||
7. Open a Pull Request
|
||||
|
||||
## License
|
||||
|
||||
See [LICENSE](LICENSE) for details.
|
||||
This project is licensed under the GNU General Public License v3.0 or later (GPL-3.0-or-later). See [LICENSE](LICENSE) for details.
|
||||
|
||||
## Acknowledgments
|
||||
|
||||
|
||||
47
SCHEMAS.md
47
SCHEMAS.md
@@ -45,15 +45,19 @@ Node advertisements announcing presence and metadata.
|
||||
"public_key": "string (64 hex chars)",
|
||||
"name": "string (optional)",
|
||||
"adv_type": "string (optional)",
|
||||
"flags": "integer (optional)"
|
||||
"flags": "integer (optional)",
|
||||
"lat": "number (optional)",
|
||||
"lon": "number (optional)"
|
||||
}
|
||||
```
|
||||
|
||||
**Field Descriptions**:
|
||||
- `public_key`: Node's full 64-character hexadecimal public key (required)
|
||||
- `name`: Node name/alias (e.g., "Gateway-01", "Alice")
|
||||
- `adv_type`: Node type - one of: `"chat"`, `"repeater"`, `"room"`, `"none"`
|
||||
- `adv_type`: Node type - common values: `"chat"`, `"repeater"`, `"room"`, `"companion"` (other values may appear from upstream feeds and are normalized by the collector when possible)
|
||||
- `flags`: Node capability/status flags (bitmask)
|
||||
- `lat`: GPS latitude when provided by decoder metadata
|
||||
- `lon`: GPS longitude when provided by decoder metadata
|
||||
|
||||
**Example**:
|
||||
```json
|
||||
@@ -61,7 +65,9 @@ Node advertisements announcing presence and metadata.
|
||||
"public_key": "4767c2897c256df8d85a5fa090574284bfd15b92d47359741b0abd5098ed30c4",
|
||||
"name": "Gateway-01",
|
||||
"adv_type": "repeater",
|
||||
"flags": 218
|
||||
"flags": 218,
|
||||
"lat": 42.470001,
|
||||
"lon": -71.330001
|
||||
}
|
||||
```
|
||||
|
||||
@@ -90,7 +96,7 @@ Direct/private messages between two nodes.
|
||||
```
|
||||
|
||||
**Field Descriptions**:
|
||||
- `pubkey_prefix`: First 12 characters of sender's public key
|
||||
- `pubkey_prefix`: First 12 characters of sender's public key (or source hash prefix in compatibility ingest modes)
|
||||
- `path_len`: Number of hops message traveled
|
||||
- `txt_type`: Message type indicator (0=plain, 2=signed, etc.)
|
||||
- `signature`: Message signature (8 hex chars) when `txt_type=2`
|
||||
@@ -128,7 +134,9 @@ Group/broadcast messages on specific channels.
|
||||
**Payload Schema**:
|
||||
```json
|
||||
{
|
||||
"channel_idx": "integer",
|
||||
"channel_idx": "integer (optional)",
|
||||
"channel_name": "string (optional)",
|
||||
"pubkey_prefix": "string (12 chars, optional)",
|
||||
"path_len": "integer (optional)",
|
||||
"txt_type": "integer (optional)",
|
||||
"signature": "string (optional)",
|
||||
@@ -139,7 +147,9 @@ Group/broadcast messages on specific channels.
|
||||
```
|
||||
|
||||
**Field Descriptions**:
|
||||
- `channel_idx`: Channel number (0-255)
|
||||
- `channel_idx`: Channel number (0-255) when available
|
||||
- `channel_name`: Channel display label (e.g., `"Public"`, `"#test"`) when available
|
||||
- `pubkey_prefix`: First 12 characters of sender's public key when available
|
||||
- `path_len`: Number of hops message traveled
|
||||
- `txt_type`: Message type indicator (0=plain, 2=signed, etc.)
|
||||
- `signature`: Message signature (8 hex chars) when `txt_type=2`
|
||||
@@ -166,6 +176,25 @@ Group/broadcast messages on specific channels.
|
||||
- Send only text: `$.data.text`
|
||||
- Send channel + text: `$.data.[channel_idx,text]`
|
||||
|
||||
**Compatibility ingest note**:
|
||||
- In LetsMesh upload compatibility mode, packet type `5` is normalized to `CHANNEL_MSG_RECV` and packet types `1`, `2`, and `7` are normalized to `CONTACT_MSG_RECV` when decryptable text is available.
|
||||
- LetsMesh packets without decryptable message text are treated as informational `letsmesh_packet` events instead of message events.
|
||||
- For UI labels, known channel indexes are mapped (`17 -> Public`, `217 -> #test`) and preferred over ambiguous/stale channel-name hints.
|
||||
- Additional channel labels can be provided through `COLLECTOR_LETSMESH_DECODER_KEYS` using `label=hex` entries.
|
||||
- When decoder output includes a human sender (`payload.decoded.decrypted.sender`), message text is normalized to `Name: Message`; sender identity remains unknown when only hash/prefix metadata is available.
|
||||
|
||||
**Compatibility ingest note (advertisements)**:
|
||||
- In LetsMesh upload compatibility mode, `status` feed payloads are persisted as informational `letsmesh_status` events and are not normalized to `ADVERTISEMENT`.
|
||||
- In LetsMesh upload compatibility mode, decoded payload type `4` is normalized to `ADVERTISEMENT` when node identity metadata is present.
|
||||
- Payload type `4` location metadata (`appData.location.latitude/longitude`) is mapped to node `lat/lon` for map rendering.
|
||||
- This keeps advertisement persistence aligned with native mode expectations (advertisement traffic only).
|
||||
|
||||
**Compatibility ingest note (non-message structured events)**:
|
||||
- Decoded payload type `9` is normalized to `TRACE_DATA` (`traceTag`, flags, auth, path hashes, and SNR values).
|
||||
- Decoded payload type `11` (`Control/NodeDiscoverResp`) is normalized to `contact` events for node upsert parity.
|
||||
- Decoded payload type `8` is normalized to informational `PATH_UPDATED` events (`hop_count` + path hashes).
|
||||
- Decoded payload type `1` can be normalized to `TELEMETRY_RESPONSE`, `BATTERY`, `PATH_UPDATED`, or `STATUS_RESPONSE` when decrypted response content is structured and parseable.
|
||||
|
||||
---
|
||||
|
||||
## Persisted Events (Non-Webhook)
|
||||
@@ -196,7 +225,7 @@ Network trace path results showing route and signal strength.
|
||||
- `path_len`: Length of the path
|
||||
- `flags`: Trace flags/options
|
||||
- `auth`: Authentication/validation data
|
||||
- `path_hashes`: Array of 2-character node hash identifiers (ordered by hops)
|
||||
- `path_hashes`: Array of hex-encoded node hash identifiers, variable length (e.g., `"4a"` for single-byte, `"b3fa"` for multibyte), ordered by hops
|
||||
- `snr_values`: Array of SNR values corresponding to each hop
|
||||
- `hop_count`: Total number of hops
|
||||
|
||||
@@ -207,12 +236,14 @@ Network trace path results showing route and signal strength.
|
||||
"path_len": 3,
|
||||
"flags": 0,
|
||||
"auth": 1,
|
||||
"path_hashes": ["4a", "b3", "fa"],
|
||||
"path_hashes": ["4a", "b3fa", "02"],
|
||||
"snr_values": [25.3, 18.7, 12.4],
|
||||
"hop_count": 3
|
||||
}
|
||||
```
|
||||
|
||||
**Note**: MeshCore firmware v1.14+ supports multibyte path hashes. Older nodes use single-byte (2-character) hashes. Mixed-length hash arrays are expected in heterogeneous networks where nodes run different firmware versions.
|
||||
|
||||
**Webhook Trigger**: No
|
||||
**REST API**: `GET /api/v1/trace-paths`
|
||||
|
||||
|
||||
3
TASKS.md
3
TASKS.md
@@ -753,6 +753,9 @@ This document tracks implementation progress for the MeshCore Hub project. Each
|
||||
### Decisions Made
|
||||
*(Record architectural decisions and answers to clarifying questions here)*
|
||||
|
||||
- [x] LetsMesh/native advertisement parity: in `letsmesh_upload` mode, observer `status` feed stays informational (`letsmesh_status`) and does not populate `advertisements`.
|
||||
- [x] LetsMesh advertisement persistence source: decoded packet payload type `4` maps to `advertisement`; payload type `11` maps to `contact` parity updates.
|
||||
- [x] LetsMesh native-event parity extensions: payload type `9` maps to `trace_data`, payload type `8` maps to informational `path_updated`, and payload type `1` can map to response-style native events when decryptable structured content exists.
|
||||
- [ ] Q1 (MQTT Broker):
|
||||
- [ ] Q2 (Database):
|
||||
- [ ] Q3 (Web Dashboard Separation):
|
||||
|
||||
114
alembic/versions/20241205_0001_002_member_nodes.py
Normal file
114
alembic/versions/20241205_0001_002_member_nodes.py
Normal file
@@ -0,0 +1,114 @@
|
||||
"""Add member_nodes association table
|
||||
|
||||
Revision ID: 002
|
||||
Revises: 001
|
||||
Create Date: 2024-12-05
|
||||
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "002"
|
||||
down_revision: Union[str, None] = "001"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# Create member_nodes table
|
||||
op.create_table(
|
||||
"member_nodes",
|
||||
sa.Column("id", sa.String(), nullable=False),
|
||||
sa.Column("member_id", sa.String(36), nullable=False),
|
||||
sa.Column("public_key", sa.String(64), nullable=False),
|
||||
sa.Column("node_role", sa.String(50), nullable=True),
|
||||
sa.Column(
|
||||
"created_at",
|
||||
sa.DateTime(timezone=True),
|
||||
server_default=sa.func.now(),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column(
|
||||
"updated_at",
|
||||
sa.DateTime(timezone=True),
|
||||
server_default=sa.func.now(),
|
||||
nullable=False,
|
||||
),
|
||||
sa.ForeignKeyConstraint(["member_id"], ["members.id"], ondelete="CASCADE"),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
op.create_index("ix_member_nodes_member_id", "member_nodes", ["member_id"])
|
||||
op.create_index("ix_member_nodes_public_key", "member_nodes", ["public_key"])
|
||||
op.create_index(
|
||||
"ix_member_nodes_member_public_key",
|
||||
"member_nodes",
|
||||
["member_id", "public_key"],
|
||||
)
|
||||
|
||||
# Migrate existing public_key data from members to member_nodes
|
||||
# Get all members with a public_key
|
||||
connection = op.get_bind()
|
||||
members_with_keys = connection.execute(
|
||||
sa.text("SELECT id, public_key FROM members WHERE public_key IS NOT NULL")
|
||||
).fetchall()
|
||||
|
||||
# Insert into member_nodes
|
||||
for member_id, public_key in members_with_keys:
|
||||
# Generate a UUID for the new row
|
||||
import uuid
|
||||
|
||||
node_id = str(uuid.uuid4())
|
||||
connection.execute(
|
||||
sa.text(
|
||||
"""
|
||||
INSERT INTO member_nodes (id, member_id, public_key, created_at, updated_at)
|
||||
VALUES (:id, :member_id, :public_key, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
|
||||
"""
|
||||
),
|
||||
{"id": node_id, "member_id": member_id, "public_key": public_key},
|
||||
)
|
||||
|
||||
# Drop the public_key column from members
|
||||
op.drop_index("ix_members_public_key", table_name="members")
|
||||
op.drop_column("members", "public_key")
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# Add public_key column back to members
|
||||
op.add_column(
|
||||
"members",
|
||||
sa.Column("public_key", sa.String(64), nullable=True),
|
||||
)
|
||||
op.create_index("ix_members_public_key", "members", ["public_key"])
|
||||
|
||||
# Migrate data back - take the first node for each member
|
||||
connection = op.get_bind()
|
||||
member_nodes = connection.execute(
|
||||
sa.text(
|
||||
"""
|
||||
SELECT DISTINCT member_id, public_key
|
||||
FROM member_nodes
|
||||
WHERE (member_id, created_at) IN (
|
||||
SELECT member_id, MIN(created_at)
|
||||
FROM member_nodes
|
||||
GROUP BY member_id
|
||||
)
|
||||
"""
|
||||
)
|
||||
).fetchall()
|
||||
|
||||
for member_id, public_key in member_nodes:
|
||||
connection.execute(
|
||||
sa.text(
|
||||
"UPDATE members SET public_key = :public_key WHERE id = :member_id"
|
||||
),
|
||||
{"public_key": public_key, "member_id": member_id},
|
||||
)
|
||||
|
||||
# Drop member_nodes table
|
||||
op.drop_table("member_nodes")
|
||||
67
alembic/versions/20241206_0001_003_add_event_hash.py
Normal file
67
alembic/versions/20241206_0001_003_add_event_hash.py
Normal file
@@ -0,0 +1,67 @@
|
||||
"""Add event_hash column to event tables for deduplication
|
||||
|
||||
Revision ID: 003
|
||||
Revises: 002
|
||||
Create Date: 2024-12-06
|
||||
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "003"
|
||||
down_revision: Union[str, None] = "002"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# Add event_hash column to messages table
|
||||
op.add_column(
|
||||
"messages",
|
||||
sa.Column("event_hash", sa.String(32), nullable=True),
|
||||
)
|
||||
op.create_index("ix_messages_event_hash", "messages", ["event_hash"])
|
||||
|
||||
# Add event_hash column to advertisements table
|
||||
op.add_column(
|
||||
"advertisements",
|
||||
sa.Column("event_hash", sa.String(32), nullable=True),
|
||||
)
|
||||
op.create_index("ix_advertisements_event_hash", "advertisements", ["event_hash"])
|
||||
|
||||
# Add event_hash column to trace_paths table
|
||||
op.add_column(
|
||||
"trace_paths",
|
||||
sa.Column("event_hash", sa.String(32), nullable=True),
|
||||
)
|
||||
op.create_index("ix_trace_paths_event_hash", "trace_paths", ["event_hash"])
|
||||
|
||||
# Add event_hash column to telemetry table
|
||||
op.add_column(
|
||||
"telemetry",
|
||||
sa.Column("event_hash", sa.String(32), nullable=True),
|
||||
)
|
||||
op.create_index("ix_telemetry_event_hash", "telemetry", ["event_hash"])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# Remove event_hash from telemetry
|
||||
op.drop_index("ix_telemetry_event_hash", table_name="telemetry")
|
||||
op.drop_column("telemetry", "event_hash")
|
||||
|
||||
# Remove event_hash from trace_paths
|
||||
op.drop_index("ix_trace_paths_event_hash", table_name="trace_paths")
|
||||
op.drop_column("trace_paths", "event_hash")
|
||||
|
||||
# Remove event_hash from advertisements
|
||||
op.drop_index("ix_advertisements_event_hash", table_name="advertisements")
|
||||
op.drop_column("advertisements", "event_hash")
|
||||
|
||||
# Remove event_hash from messages
|
||||
op.drop_index("ix_messages_event_hash", table_name="messages")
|
||||
op.drop_column("messages", "event_hash")
|
||||
63
alembic/versions/20241206_0002_004_event_receivers.py
Normal file
63
alembic/versions/20241206_0002_004_event_receivers.py
Normal file
@@ -0,0 +1,63 @@
|
||||
"""Add event_receivers junction table for multi-receiver tracking
|
||||
|
||||
Revision ID: 004
|
||||
Revises: 003
|
||||
Create Date: 2024-12-06
|
||||
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "004"
|
||||
down_revision: Union[str, None] = "003"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"event_receivers",
|
||||
sa.Column("id", sa.String(36), primary_key=True),
|
||||
sa.Column("event_type", sa.String(20), nullable=False),
|
||||
sa.Column("event_hash", sa.String(32), nullable=False),
|
||||
sa.Column(
|
||||
"receiver_node_id",
|
||||
sa.String(36),
|
||||
sa.ForeignKey("nodes.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column("snr", sa.Float, nullable=True),
|
||||
sa.Column("received_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.UniqueConstraint(
|
||||
"event_hash", "receiver_node_id", name="uq_event_receivers_hash_node"
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
"ix_event_receivers_event_hash",
|
||||
"event_receivers",
|
||||
["event_hash"],
|
||||
)
|
||||
op.create_index(
|
||||
"ix_event_receivers_receiver_node_id",
|
||||
"event_receivers",
|
||||
["receiver_node_id"],
|
||||
)
|
||||
op.create_index(
|
||||
"ix_event_receivers_type_hash",
|
||||
"event_receivers",
|
||||
["event_type", "event_hash"],
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index("ix_event_receivers_type_hash", table_name="event_receivers")
|
||||
op.drop_index("ix_event_receivers_receiver_node_id", table_name="event_receivers")
|
||||
op.drop_index("ix_event_receivers_event_hash", table_name="event_receivers")
|
||||
op.drop_table("event_receivers")
|
||||
126
alembic/versions/20241206_0003_005_unique_event_hash.py
Normal file
126
alembic/versions/20241206_0003_005_unique_event_hash.py
Normal file
@@ -0,0 +1,126 @@
|
||||
"""Make event_hash columns unique for race condition prevention
|
||||
|
||||
Revision ID: 005
|
||||
Revises: 004
|
||||
Create Date: 2024-12-06
|
||||
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
from sqlalchemy import inspect
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "005"
|
||||
down_revision: Union[str, None] = "004"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def _index_exists(table_name: str, index_name: str) -> bool:
|
||||
"""Check if an index exists on a table."""
|
||||
bind = op.get_bind()
|
||||
inspector = inspect(bind)
|
||||
indexes = inspector.get_indexes(table_name)
|
||||
return any(idx["name"] == index_name for idx in indexes)
|
||||
|
||||
|
||||
def _has_unique_on_column(table_name: str, column_name: str) -> bool:
|
||||
"""Check if a unique constraint or unique index exists on a column."""
|
||||
bind = op.get_bind()
|
||||
inspector = inspect(bind)
|
||||
# Check unique constraints
|
||||
uniques = inspector.get_unique_constraints(table_name)
|
||||
for uq in uniques:
|
||||
if column_name in uq.get("column_names", []):
|
||||
return True
|
||||
# Also check indexes (SQLite may create unique index instead of constraint)
|
||||
indexes = inspector.get_indexes(table_name)
|
||||
for idx in indexes:
|
||||
if idx.get("unique") and column_name in idx.get("column_names", []):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# Convert non-unique indexes to unique indexes for race condition prevention
|
||||
# Note: SQLite handles NULL values as unique (each NULL is distinct)
|
||||
# SQLite doesn't support ALTER TABLE ADD CONSTRAINT, so we use unique indexes
|
||||
|
||||
# Messages
|
||||
if _index_exists("messages", "ix_messages_event_hash"):
|
||||
op.drop_index("ix_messages_event_hash", table_name="messages")
|
||||
if not _has_unique_on_column("messages", "event_hash"):
|
||||
op.create_index(
|
||||
"ix_messages_event_hash_unique",
|
||||
"messages",
|
||||
["event_hash"],
|
||||
unique=True,
|
||||
)
|
||||
|
||||
# Advertisements
|
||||
if _index_exists("advertisements", "ix_advertisements_event_hash"):
|
||||
op.drop_index("ix_advertisements_event_hash", table_name="advertisements")
|
||||
if not _has_unique_on_column("advertisements", "event_hash"):
|
||||
op.create_index(
|
||||
"ix_advertisements_event_hash_unique",
|
||||
"advertisements",
|
||||
["event_hash"],
|
||||
unique=True,
|
||||
)
|
||||
|
||||
# Trace paths
|
||||
if _index_exists("trace_paths", "ix_trace_paths_event_hash"):
|
||||
op.drop_index("ix_trace_paths_event_hash", table_name="trace_paths")
|
||||
if not _has_unique_on_column("trace_paths", "event_hash"):
|
||||
op.create_index(
|
||||
"ix_trace_paths_event_hash_unique",
|
||||
"trace_paths",
|
||||
["event_hash"],
|
||||
unique=True,
|
||||
)
|
||||
|
||||
# Telemetry
|
||||
if _index_exists("telemetry", "ix_telemetry_event_hash"):
|
||||
op.drop_index("ix_telemetry_event_hash", table_name="telemetry")
|
||||
if not _has_unique_on_column("telemetry", "event_hash"):
|
||||
op.create_index(
|
||||
"ix_telemetry_event_hash_unique",
|
||||
"telemetry",
|
||||
["event_hash"],
|
||||
unique=True,
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# Restore non-unique indexes
|
||||
|
||||
# Telemetry
|
||||
if _index_exists("telemetry", "ix_telemetry_event_hash_unique"):
|
||||
op.drop_index("ix_telemetry_event_hash_unique", table_name="telemetry")
|
||||
if not _index_exists("telemetry", "ix_telemetry_event_hash"):
|
||||
op.create_index("ix_telemetry_event_hash", "telemetry", ["event_hash"])
|
||||
|
||||
# Trace paths
|
||||
if _index_exists("trace_paths", "ix_trace_paths_event_hash_unique"):
|
||||
op.drop_index("ix_trace_paths_event_hash_unique", table_name="trace_paths")
|
||||
if not _index_exists("trace_paths", "ix_trace_paths_event_hash"):
|
||||
op.create_index("ix_trace_paths_event_hash", "trace_paths", ["event_hash"])
|
||||
|
||||
# Advertisements
|
||||
if _index_exists("advertisements", "ix_advertisements_event_hash_unique"):
|
||||
op.drop_index(
|
||||
"ix_advertisements_event_hash_unique", table_name="advertisements"
|
||||
)
|
||||
if not _index_exists("advertisements", "ix_advertisements_event_hash"):
|
||||
op.create_index(
|
||||
"ix_advertisements_event_hash", "advertisements", ["event_hash"]
|
||||
)
|
||||
|
||||
# Messages
|
||||
if _index_exists("messages", "ix_messages_event_hash_unique"):
|
||||
op.drop_index("ix_messages_event_hash_unique", table_name="messages")
|
||||
if not _index_exists("messages", "ix_messages_event_hash"):
|
||||
op.create_index("ix_messages_event_hash", "messages", ["event_hash"])
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Make Node.last_seen nullable
|
||||
|
||||
Revision ID: 0b944542ccd8
|
||||
Revises: 005
|
||||
Create Date: 2025-12-08 00:07:49.891245+00:00
|
||||
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "0b944542ccd8"
|
||||
down_revision: Union[str, None] = "005"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
# Make Node.last_seen nullable since nodes from contact sync
|
||||
# haven't actually been "seen" on the mesh yet
|
||||
with op.batch_alter_table("nodes", schema=None) as batch_op:
|
||||
batch_op.alter_column("last_seen", existing_type=sa.DATETIME(), nullable=True)
|
||||
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
# Revert Node.last_seen to non-nullable
|
||||
# Note: This will fail if there are NULL values in last_seen
|
||||
with op.batch_alter_table("nodes", schema=None) as batch_op:
|
||||
batch_op.alter_column("last_seen", existing_type=sa.DATETIME(), nullable=False)
|
||||
|
||||
# ### end Alembic commands ###
|
||||
@@ -0,0 +1,111 @@
|
||||
"""Add member_id field to members table
|
||||
|
||||
Revision ID: 03b9b2451bd9
|
||||
Revises: 0b944542ccd8
|
||||
Create Date: 2025-12-08 14:34:30.337799+00:00
|
||||
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "03b9b2451bd9"
|
||||
down_revision: Union[str, None] = "0b944542ccd8"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table("advertisements", schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f("ix_advertisements_event_hash_unique"))
|
||||
batch_op.create_unique_constraint(
|
||||
"uq_advertisements_event_hash", ["event_hash"]
|
||||
)
|
||||
|
||||
with op.batch_alter_table("members", schema=None) as batch_op:
|
||||
# Add member_id as nullable first to handle existing data
|
||||
batch_op.add_column(
|
||||
sa.Column("member_id", sa.String(length=100), nullable=True)
|
||||
)
|
||||
|
||||
# Generate member_id for existing members based on their name
|
||||
# Convert name to lowercase and replace spaces with underscores
|
||||
connection = op.get_bind()
|
||||
connection.execute(
|
||||
sa.text(
|
||||
"UPDATE members SET member_id = LOWER(REPLACE(name, ' ', '_')) WHERE member_id IS NULL"
|
||||
)
|
||||
)
|
||||
|
||||
with op.batch_alter_table("members", schema=None) as batch_op:
|
||||
# Now make it non-nullable and add unique index
|
||||
batch_op.alter_column("member_id", nullable=False)
|
||||
batch_op.drop_index(batch_op.f("ix_members_name"))
|
||||
batch_op.create_index(
|
||||
batch_op.f("ix_members_member_id"), ["member_id"], unique=True
|
||||
)
|
||||
|
||||
with op.batch_alter_table("messages", schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f("ix_messages_event_hash_unique"))
|
||||
batch_op.create_unique_constraint("uq_messages_event_hash", ["event_hash"])
|
||||
|
||||
with op.batch_alter_table("nodes", schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f("ix_nodes_public_key"))
|
||||
batch_op.create_index(
|
||||
batch_op.f("ix_nodes_public_key"), ["public_key"], unique=True
|
||||
)
|
||||
|
||||
with op.batch_alter_table("telemetry", schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f("ix_telemetry_event_hash_unique"))
|
||||
batch_op.create_unique_constraint("uq_telemetry_event_hash", ["event_hash"])
|
||||
|
||||
with op.batch_alter_table("trace_paths", schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f("ix_trace_paths_event_hash_unique"))
|
||||
batch_op.create_unique_constraint("uq_trace_paths_event_hash", ["event_hash"])
|
||||
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table("trace_paths", schema=None) as batch_op:
|
||||
batch_op.drop_constraint("uq_trace_paths_event_hash", type_="unique")
|
||||
batch_op.create_index(
|
||||
batch_op.f("ix_trace_paths_event_hash_unique"), ["event_hash"], unique=1
|
||||
)
|
||||
|
||||
with op.batch_alter_table("telemetry", schema=None) as batch_op:
|
||||
batch_op.drop_constraint("uq_telemetry_event_hash", type_="unique")
|
||||
batch_op.create_index(
|
||||
batch_op.f("ix_telemetry_event_hash_unique"), ["event_hash"], unique=1
|
||||
)
|
||||
|
||||
with op.batch_alter_table("nodes", schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f("ix_nodes_public_key"))
|
||||
batch_op.create_index(
|
||||
batch_op.f("ix_nodes_public_key"), ["public_key"], unique=False
|
||||
)
|
||||
|
||||
with op.batch_alter_table("messages", schema=None) as batch_op:
|
||||
batch_op.drop_constraint("uq_messages_event_hash", type_="unique")
|
||||
batch_op.create_index(
|
||||
batch_op.f("ix_messages_event_hash_unique"), ["event_hash"], unique=1
|
||||
)
|
||||
|
||||
with op.batch_alter_table("members", schema=None) as batch_op:
|
||||
batch_op.drop_index(batch_op.f("ix_members_member_id"))
|
||||
batch_op.create_index(batch_op.f("ix_members_name"), ["name"], unique=False)
|
||||
batch_op.drop_column("member_id")
|
||||
|
||||
with op.batch_alter_table("advertisements", schema=None) as batch_op:
|
||||
batch_op.drop_constraint("uq_advertisements_event_hash", type_="unique")
|
||||
batch_op.create_index(
|
||||
batch_op.f("ix_advertisements_event_hash_unique"), ["event_hash"], unique=1
|
||||
)
|
||||
|
||||
# ### end Alembic commands ###
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Remove member_nodes table
|
||||
|
||||
Revision ID: aa1162502616
|
||||
Revises: 03b9b2451bd9
|
||||
Create Date: 2025-12-08 15:04:37.260923+00:00
|
||||
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "aa1162502616"
|
||||
down_revision: Union[str, None] = "03b9b2451bd9"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# Drop the member_nodes table
|
||||
# Nodes are now associated with members via a 'member_id' tag on the node
|
||||
op.drop_table("member_nodes")
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# Recreate the member_nodes table if needed for rollback
|
||||
op.create_table(
|
||||
"member_nodes",
|
||||
sa.Column("id", sa.String(length=36), nullable=False),
|
||||
sa.Column("member_id", sa.String(length=36), nullable=False),
|
||||
sa.Column("public_key", sa.String(length=64), nullable=False),
|
||||
sa.Column("node_role", sa.String(length=50), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["member_id"],
|
||||
["members.id"],
|
||||
name=op.f("fk_member_nodes_member_id_members"),
|
||||
ondelete="CASCADE",
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id", name=op.f("pk_member_nodes")),
|
||||
)
|
||||
op.create_index(
|
||||
op.f("ix_member_nodes_member_id"), "member_nodes", ["member_id"], unique=False
|
||||
)
|
||||
op.create_index(
|
||||
op.f("ix_member_nodes_public_key"), "member_nodes", ["public_key"], unique=False
|
||||
)
|
||||
op.create_index(
|
||||
"ix_member_nodes_member_public_key",
|
||||
"member_nodes",
|
||||
["member_id", "public_key"],
|
||||
unique=False,
|
||||
)
|
||||
@@ -0,0 +1,37 @@
|
||||
"""add lat lon columns to nodes
|
||||
|
||||
Revision ID: 4e2e787a1660
|
||||
Revises: aa1162502616
|
||||
Create Date: 2026-01-09 20:04:04.273741+00:00
|
||||
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "4e2e787a1660"
|
||||
down_revision: Union[str, None] = "aa1162502616"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table("nodes", schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column("lat", sa.Float(), nullable=True))
|
||||
batch_op.add_column(sa.Column("lon", sa.Float(), nullable=True))
|
||||
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
with op.batch_alter_table("nodes", schema=None) as batch_op:
|
||||
batch_op.drop_column("lon")
|
||||
batch_op.drop_column("lat")
|
||||
|
||||
# ### end Alembic commands ###
|
||||
@@ -1,10 +0,0 @@
|
||||
{
|
||||
"members": [
|
||||
{
|
||||
"name": "Louis",
|
||||
"callsign": "Louis",
|
||||
"role": "admin",
|
||||
"description": "IPNet Founder"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,613 +0,0 @@
|
||||
{
|
||||
"2337484665ced7e210007e9fd9db98ced0a24a6eab8b4cbe3a06b3a1cea33ca1": {
|
||||
"friendly_name": "IP2 Repeater 1",
|
||||
"node_id": "ip2-rep01.ipnt.uk",
|
||||
"member_id": "louis",
|
||||
"area": "IP2",
|
||||
"location": {
|
||||
"value": "52.0357627,1.132079",
|
||||
"type": "coordinate"
|
||||
},
|
||||
"location_description": "Fountains Road",
|
||||
"hardware": "Heltec V3",
|
||||
"antenna": "Paradar 8.5dBi Omni",
|
||||
"elevation": {
|
||||
"value": "31",
|
||||
"type": "number"
|
||||
},
|
||||
"show_on_map": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_public": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_online": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_testing": {
|
||||
"value": "false",
|
||||
"type": "boolean"
|
||||
},
|
||||
"mesh_role": "repeater"
|
||||
},
|
||||
"8cb01fff1afc099055af418ce5fc5e60384df9ff763c25dd7e6a5e0922e8df90": {
|
||||
"friendly_name": "IP2 Repeater 2",
|
||||
"node_id": "ip2-rep02.ipnt.uk",
|
||||
"member_id": "louis",
|
||||
"area": "IP2",
|
||||
"location": {
|
||||
"value": "52.0390682,1.1304141",
|
||||
"type": "coordinate"
|
||||
},
|
||||
"location_description": "Belstead Road",
|
||||
"hardware": "Heltec V3",
|
||||
"antenna": "McGill 6dBi Omni",
|
||||
"elevation": {
|
||||
"value": "44",
|
||||
"type": "number"
|
||||
},
|
||||
"show_on_map": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_public": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_online": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_testing": {
|
||||
"value": "false",
|
||||
"type": "boolean"
|
||||
},
|
||||
"mesh_role": "repeater"
|
||||
},
|
||||
"5b565df747913358e24d890b2227de9c35d09763746b6ec326c15ebbf9b8be3b": {
|
||||
"friendly_name": "IP2 Repeater 3",
|
||||
"node_id": "ip2-rep03.ipnt.uk",
|
||||
"member_id": "louis",
|
||||
"area": "IP2",
|
||||
"location": {
|
||||
"value": "52.046356,1.134661",
|
||||
"type": "coordinate"
|
||||
},
|
||||
"location_description": "Birkfield Drive",
|
||||
"hardware": "Heltec V3",
|
||||
"antenna": "Paradar 8.5dBi Omni",
|
||||
"elevation": {
|
||||
"value": "52",
|
||||
"type": "number"
|
||||
},
|
||||
"show_on_map": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_public": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_online": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_testing": {
|
||||
"value": "false",
|
||||
"type": "boolean"
|
||||
},
|
||||
"mesh_role": "repeater"
|
||||
},
|
||||
"780d0939f90b22d3bd7cbedcaf4e8d468a12c01886ab24b8cfa11eab2f5516c5": {
|
||||
"friendly_name": "IP2 Integration 1",
|
||||
"node_id": "ip2-int01.ipnt.uk",
|
||||
"member_id": "louis",
|
||||
"area": "IP2",
|
||||
"location": {
|
||||
"value": "52.0354539,1.1295338",
|
||||
"type": "coordinate"
|
||||
},
|
||||
"location_description": "Fountains Road",
|
||||
"hardware": "Heltec V3",
|
||||
"antenna": "Generic 5dBi Whip",
|
||||
"elevation": {
|
||||
"value": "25",
|
||||
"type": "number"
|
||||
},
|
||||
"show_on_map": {
|
||||
"value": "false",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_public": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_online": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_testing": {
|
||||
"value": "false",
|
||||
"type": "boolean"
|
||||
},
|
||||
"mesh_role": "integration"
|
||||
},
|
||||
"30121dc60362c633c457ffa18f49b3e1d6823402c33709f32d7df70612250b96": {
|
||||
"friendly_name": "MeshBot",
|
||||
"node_id": "bot.ipnt.uk",
|
||||
"member_id": "louis",
|
||||
"area": "IP2",
|
||||
"location": {
|
||||
"value": "52.0354539,1.1295338",
|
||||
"type": "coordinate"
|
||||
},
|
||||
"location_description": "Fountains Road",
|
||||
"hardware": "Heltec V3",
|
||||
"antenna": "Generic 5dBi Whip",
|
||||
"elevation": {
|
||||
"value": "25",
|
||||
"type": "number"
|
||||
},
|
||||
"show_on_map": {
|
||||
"value": "false",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_public": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_online": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_testing": {
|
||||
"value": "false",
|
||||
"type": "boolean"
|
||||
},
|
||||
"mesh_role": "integration"
|
||||
},
|
||||
"9135986b83815ada92883358435cc6528c7db60cb647f9b6547739a1ce5eb1c8": {
|
||||
"friendly_name": "IP3 Repeater 1",
|
||||
"node_id": "ip3-rep01.ipnt.uk",
|
||||
"member_id": "markab",
|
||||
"area": "IP3",
|
||||
"location": {
|
||||
"value": "52.045803,1.204416",
|
||||
"type": "coordinate"
|
||||
},
|
||||
"location_description": "Brokehall",
|
||||
"hardware": "Heltec V3",
|
||||
"antenna": "Paradar 8.5dBi Omni",
|
||||
"elevation": {
|
||||
"value": "42",
|
||||
"type": "number"
|
||||
},
|
||||
"show_on_map": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_public": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_online": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_testing": {
|
||||
"value": "false",
|
||||
"type": "boolean"
|
||||
},
|
||||
"mesh_role": "repeater"
|
||||
},
|
||||
"e334ec5475789d542ed9e692fbeef7444a371fcc05adcbda1f47ba6a3191b459": {
|
||||
"friendly_name": "IP3 Repeater 2",
|
||||
"node_id": "ip3-rep02.ipnt.uk",
|
||||
"member_id": "ccz",
|
||||
"area": "IP3",
|
||||
"location": {
|
||||
"value": "52.03297,1.17543",
|
||||
"type": "coordinate"
|
||||
},
|
||||
"location_description": "Morland Road Allotments",
|
||||
"hardware": "Heltec T114",
|
||||
"antenna": "Unknown",
|
||||
"elevation": {
|
||||
"value": "39",
|
||||
"type": "number"
|
||||
},
|
||||
"show_on_map": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_public": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_online": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_testing": {
|
||||
"value": "false",
|
||||
"type": "boolean"
|
||||
},
|
||||
"mesh_role": "repeater"
|
||||
},
|
||||
"cc15fb33e98f2e098a543f516f770dc3061a1a6b30f79b84780663bf68ae6b53": {
|
||||
"friendly_name": "IP3 Repeater 3",
|
||||
"node_id": "ip3-rep03.ipnt.uk",
|
||||
"member_id": "ccz",
|
||||
"area": "IP3",
|
||||
"location": {
|
||||
"value": "52.04499,1.18149",
|
||||
"type": "coordinate"
|
||||
},
|
||||
"location_description": "Hatfield Road",
|
||||
"hardware": "Heltec V3",
|
||||
"antenna": "Unknown",
|
||||
"elevation": {
|
||||
"value": "39",
|
||||
"type": "number"
|
||||
},
|
||||
"show_on_map": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_public": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_online": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_testing": {
|
||||
"value": "false",
|
||||
"type": "boolean"
|
||||
},
|
||||
"mesh_role": "repeater"
|
||||
},
|
||||
"22309435fbd9dd1f14870a1895dc854779f6b2af72b08542f6105d264a493ebe": {
|
||||
"friendly_name": "IP3 Integration 1",
|
||||
"node_id": "ip3-int01.ipnt.uk",
|
||||
"member_id": "markab",
|
||||
"area": "IP3",
|
||||
"location": {
|
||||
"value": "52.045773,1.212808",
|
||||
"type": "coordinate"
|
||||
},
|
||||
"location_description": "Brokehall",
|
||||
"hardware": "Heltec V3",
|
||||
"antenna": "Generic 3dBi Whip",
|
||||
"elevation": {
|
||||
"value": "37",
|
||||
"type": "number"
|
||||
},
|
||||
"show_on_map": {
|
||||
"value": "false",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_public": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_online": {
|
||||
"value": "false",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_testing": {
|
||||
"value": "false",
|
||||
"type": "boolean"
|
||||
},
|
||||
"mesh_role": "integration"
|
||||
},
|
||||
"2a4f89e766dfa1758e35a69962c1f6d352b206a5e3562a589155a3ebfe7fc2bb": {
|
||||
"friendly_name": "IP3 Repeater 4",
|
||||
"node_id": "ip3-rep04.ipnt.uk",
|
||||
"member_id": "markab",
|
||||
"area": "IP3",
|
||||
"location": {
|
||||
"value": "52.046383,1.174542",
|
||||
"type": "coordinate"
|
||||
},
|
||||
"location_description": "Holywells",
|
||||
"hardware": "Sensecap Solar",
|
||||
"antenna": "Paradar 6.5dbi Omni",
|
||||
"elevation": {
|
||||
"value": "21",
|
||||
"type": "number"
|
||||
},
|
||||
"show_on_map": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_public": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_online": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_testing": {
|
||||
"value": "false",
|
||||
"type": "boolean"
|
||||
},
|
||||
"mesh_role": "repeater"
|
||||
},
|
||||
"e790b73b2d6e377dd0f575c847f3ef42232f610eb9a19af57083fc4f647309ac": {
|
||||
"friendly_name": "IP3 Repeater 5",
|
||||
"node_id": "ip3-rep05.ipnt.uk",
|
||||
"member_id": "markab",
|
||||
"area": "IP3",
|
||||
"location": {
|
||||
"value": "52.05252,1.17034",
|
||||
"type": "coordinate"
|
||||
},
|
||||
"location_description": "Back Hamlet",
|
||||
"hardware": "Heltec T114",
|
||||
"antenna": "Paradar 6.5dBi Omni",
|
||||
"elevation": {
|
||||
"value": "38",
|
||||
"type": "number"
|
||||
},
|
||||
"show_on_map": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_public": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_online": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_testing": {
|
||||
"value": "false",
|
||||
"type": "boolean"
|
||||
},
|
||||
"mesh_role": "repeater"
|
||||
},
|
||||
"20ed75ffc0f9777951716bb3d308d7f041fd2ad32fe2e998e600d0361e1fe2ac": {
|
||||
"friendly_name": "IP3 Repeater 6",
|
||||
"node_id": "ip3-rep06.ipnt.uk",
|
||||
"member_id": "ccz",
|
||||
"area": "IP3",
|
||||
"location": {
|
||||
"value": "52.04893,1.18965",
|
||||
"type": "coordinate"
|
||||
},
|
||||
"location_description": "Dover Road",
|
||||
"hardware": "Unknown",
|
||||
"antenna": "Generic 5dBi Whip",
|
||||
"elevation": {
|
||||
"value": "38",
|
||||
"type": "number"
|
||||
},
|
||||
"show_on_map": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_public": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_online": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_testing": {
|
||||
"value": "false",
|
||||
"type": "boolean"
|
||||
},
|
||||
"mesh_role": "repeater"
|
||||
},
|
||||
"bd7b5ac75f660675b39f368e1dbb6d1dbcefd8bd7a170e21a942954f67c8bf52": {
|
||||
"friendly_name": "IP8 Repeater 1",
|
||||
"node_id": "rep01.ip8.ipnt.uk",
|
||||
"member_id": "walshie86",
|
||||
"area": "IP8",
|
||||
"location": {
|
||||
"value": "52.033684,1.118384",
|
||||
"type": "coordinate"
|
||||
},
|
||||
"location_description": "Grove Hill",
|
||||
"hardware": "Heltec V3",
|
||||
"antenna": "McGill 3dBi Omni",
|
||||
"elevation": {
|
||||
"value": "13",
|
||||
"type": "number"
|
||||
},
|
||||
"show_on_map": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_public": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_online": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_testing": {
|
||||
"value": "false",
|
||||
"type": "boolean"
|
||||
},
|
||||
"mesh_role": "repeater"
|
||||
},
|
||||
"9cf300c40112ea34d0a59858270948b27ab6cd87e840de338f3ca782c17537b2": {
|
||||
"friendly_name": "IP8 Repeater 2",
|
||||
"node_id": "rep02.ip8.ipnt.uk",
|
||||
"member_id": "walshie86",
|
||||
"area": "IP8",
|
||||
"location": {
|
||||
"value": "52.035648,1.073271",
|
||||
"type": "coordinate"
|
||||
},
|
||||
"location_description": "Washbrook",
|
||||
"hardware": "Sensecap Solar",
|
||||
"elevation": {
|
||||
"value": "13",
|
||||
"type": "number"
|
||||
},
|
||||
"show_on_map": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_public": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_online": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_testing": {
|
||||
"value": "false",
|
||||
"type": "boolean"
|
||||
},
|
||||
"mesh_role": "repeater"
|
||||
},
|
||||
"d3c20d962f7384c111fbafad6fbc1c1dc0e5c3ce802fb3ee11020e8d8207ed3a": {
|
||||
"friendly_name": "IP4 Repeater 1",
|
||||
"node_id": "ip4-rep01.ipnt.uk",
|
||||
"member_id": "markab",
|
||||
"area": "IP4",
|
||||
"location": {
|
||||
"value": "52.052445,1.156882",
|
||||
"type": "coordinate"
|
||||
},
|
||||
"location_description": "Wine Rack",
|
||||
"hardware": "Heltec T114",
|
||||
"antenna": "Generic 5dbi Whip",
|
||||
"elevation": {
|
||||
"value": "50",
|
||||
"type": "number"
|
||||
},
|
||||
"show_on_map": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_public": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_online": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_testing": {
|
||||
"value": "false",
|
||||
"type": "boolean"
|
||||
},
|
||||
"mesh_role": "repeater"
|
||||
},
|
||||
"b00ce9d218203e96d8557a4d59e06f5de59bbc4dcc4df9c870079d2cb8b5bd80": {
|
||||
"friendly_name": "IP4 Repeater 2",
|
||||
"node_id": "ip4-rep02.ipnt.uk",
|
||||
"member_id": "markab",
|
||||
"area": "IP4",
|
||||
"location": {
|
||||
"value": "52.06217,1.18332",
|
||||
"type": "coordinate"
|
||||
},
|
||||
"location_description": "Rushmere Road",
|
||||
"hardware": "Heltec V3",
|
||||
"antenna": "Paradar 5dbi Whip",
|
||||
"elevation": {
|
||||
"value": "35",
|
||||
"type": "number"
|
||||
},
|
||||
"show_on_map": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_public": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_online": {
|
||||
"value": "false",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_testing": {
|
||||
"value": "false",
|
||||
"type": "boolean"
|
||||
},
|
||||
"mesh_role": "repeater"
|
||||
},
|
||||
"8accb6d0189ccaffb745ba54793e7fe3edd515edb45554325d957e48c1b9f3b3": {
|
||||
"friendly_name": "IP4 Repeater 3",
|
||||
"node_id": "ip4-rep03.ipnt.uk",
|
||||
"member_id": "craig",
|
||||
"area": "IP4",
|
||||
"location": {
|
||||
"value": "52.058,1.165",
|
||||
"type": "coordinate"
|
||||
},
|
||||
"location_description": "IP4 Area",
|
||||
"hardware": "Heltec v3",
|
||||
"antenna": "Generic Whip",
|
||||
"elevation": {
|
||||
"value": "30",
|
||||
"type": "number"
|
||||
},
|
||||
"show_on_map": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_public": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_online": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_testing": {
|
||||
"value": "false",
|
||||
"type": "boolean"
|
||||
},
|
||||
"mesh_role": "repeater"
|
||||
},
|
||||
"69fb8431e7ab307513797544fab99ce53ce24c46ec2d3a11767fe70f2ca37b23": {
|
||||
"friendly_name": "IP3 Test Repeater 1",
|
||||
"node_id": "ip3-tst01.ipnt.uk",
|
||||
"member_id": "markab",
|
||||
"area": "IP3",
|
||||
"location": {
|
||||
"value": "52.041869,1.204789",
|
||||
"type": "coordinate"
|
||||
},
|
||||
"location_description": "Brokehall",
|
||||
"hardware": "Station G2",
|
||||
"antenna": "McGill 10dBi Panel",
|
||||
"elevation": {
|
||||
"value": "37",
|
||||
"type": "number"
|
||||
},
|
||||
"show_on_map": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_public": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_online": {
|
||||
"value": "false",
|
||||
"type": "boolean"
|
||||
},
|
||||
"is_testing": {
|
||||
"value": "true",
|
||||
"type": "boolean"
|
||||
},
|
||||
"mesh_role": "repeater"
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
services:
|
||||
api:
|
||||
networks:
|
||||
- default
|
||||
- pangolin
|
||||
|
||||
web:
|
||||
networks:
|
||||
- default
|
||||
- pangolin
|
||||
|
||||
networks:
|
||||
pangolin:
|
||||
external: true
|
||||
@@ -1,16 +1,20 @@
|
||||
services:
|
||||
# ==========================================================================
|
||||
# MQTT Broker - Eclipse Mosquitto
|
||||
# MQTT Broker - Eclipse Mosquitto (optional, use --profile mqtt)
|
||||
# Most users will connect to an external MQTT broker instead
|
||||
# ==========================================================================
|
||||
mqtt:
|
||||
image: eclipse-mosquitto:2
|
||||
container_name: meshcore-mqtt
|
||||
profiles:
|
||||
- all
|
||||
- mqtt
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "${MQTT_EXTERNAL_PORT:-1883}:1883"
|
||||
- "${MQTT_WS_PORT:-9001}:9001"
|
||||
volumes:
|
||||
- ./etc/mosquitto.conf:/mosquitto/config/mosquitto.conf:ro
|
||||
# - ./etc/mosquitto.conf:/mosquitto/config/mosquitto.conf:ro
|
||||
- mosquitto_data:/mosquitto/data
|
||||
- mosquitto_log:/mosquitto/log
|
||||
healthcheck:
|
||||
@@ -24,17 +28,15 @@ services:
|
||||
# Interface Receiver - MeshCore device to MQTT bridge (events)
|
||||
# ==========================================================================
|
||||
interface-receiver:
|
||||
image: ghcr.io/ipnet-mesh/meshcore-hub:main
|
||||
image: ghcr.io/ipnet-mesh/meshcore-hub:${IMAGE_VERSION:-latest}
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
container_name: meshcore-interface-receiver
|
||||
profiles:
|
||||
- interface-receiver
|
||||
- all
|
||||
- receiver
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
mqtt:
|
||||
condition: service_healthy
|
||||
devices:
|
||||
- "${SERIAL_PORT:-/dev/ttyUSB0}:${SERIAL_PORT:-/dev/ttyUSB0}"
|
||||
user: root # Required for device access
|
||||
@@ -45,6 +47,9 @@ services:
|
||||
- MQTT_USERNAME=${MQTT_USERNAME:-}
|
||||
- MQTT_PASSWORD=${MQTT_PASSWORD:-}
|
||||
- MQTT_PREFIX=${MQTT_PREFIX:-meshcore}
|
||||
- MQTT_TLS=${MQTT_TLS:-false}
|
||||
- MQTT_TRANSPORT=${MQTT_TRANSPORT:-tcp}
|
||||
- MQTT_WS_PATH=${MQTT_WS_PATH:-/mqtt}
|
||||
- SERIAL_PORT=${SERIAL_PORT:-/dev/ttyUSB0}
|
||||
- SERIAL_BAUD=${SERIAL_BAUD:-115200}
|
||||
- NODE_ADDRESS=${NODE_ADDRESS:-}
|
||||
@@ -60,17 +65,15 @@ services:
|
||||
# Interface Sender - MQTT to MeshCore device bridge (commands)
|
||||
# ==========================================================================
|
||||
interface-sender:
|
||||
image: ghcr.io/ipnet-mesh/meshcore-hub:main
|
||||
image: ghcr.io/ipnet-mesh/meshcore-hub:${IMAGE_VERSION:-latest}
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
container_name: meshcore-interface-sender
|
||||
profiles:
|
||||
- interface-sender
|
||||
- all
|
||||
- sender
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
mqtt:
|
||||
condition: service_healthy
|
||||
devices:
|
||||
- "${SERIAL_PORT_SENDER:-/dev/ttyUSB1}:${SERIAL_PORT_SENDER:-/dev/ttyUSB1}"
|
||||
user: root # Required for device access
|
||||
@@ -81,6 +84,9 @@ services:
|
||||
- MQTT_USERNAME=${MQTT_USERNAME:-}
|
||||
- MQTT_PASSWORD=${MQTT_PASSWORD:-}
|
||||
- MQTT_PREFIX=${MQTT_PREFIX:-meshcore}
|
||||
- MQTT_TLS=${MQTT_TLS:-false}
|
||||
- MQTT_TRANSPORT=${MQTT_TRANSPORT:-tcp}
|
||||
- MQTT_WS_PATH=${MQTT_WS_PATH:-/mqtt}
|
||||
- SERIAL_PORT=${SERIAL_PORT_SENDER:-/dev/ttyUSB1}
|
||||
- SERIAL_BAUD=${SERIAL_BAUD:-115200}
|
||||
- NODE_ADDRESS=${NODE_ADDRESS_SENDER:-}
|
||||
@@ -96,17 +102,15 @@ services:
|
||||
# Interface Mock Receiver - For testing without real devices
|
||||
# ==========================================================================
|
||||
interface-mock-receiver:
|
||||
image: ghcr.io/ipnet-mesh/meshcore-hub:main
|
||||
image: ghcr.io/ipnet-mesh/meshcore-hub:${IMAGE_VERSION:-latest}
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
container_name: meshcore-interface-mock-receiver
|
||||
profiles:
|
||||
- all
|
||||
- mock
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
mqtt:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
- LOG_LEVEL=${LOG_LEVEL:-INFO}
|
||||
- MQTT_HOST=${MQTT_HOST:-mqtt}
|
||||
@@ -114,6 +118,9 @@ services:
|
||||
- MQTT_USERNAME=${MQTT_USERNAME:-}
|
||||
- MQTT_PASSWORD=${MQTT_PASSWORD:-}
|
||||
- MQTT_PREFIX=${MQTT_PREFIX:-meshcore}
|
||||
- MQTT_TLS=${MQTT_TLS:-false}
|
||||
- MQTT_TRANSPORT=${MQTT_TRANSPORT:-tcp}
|
||||
- MQTT_WS_PATH=${MQTT_WS_PATH:-/mqtt}
|
||||
- MOCK_DEVICE=true
|
||||
- NODE_ADDRESS=${NODE_ADDRESS:-0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef}
|
||||
command: ["interface", "receiver", "--mock"]
|
||||
@@ -128,18 +135,21 @@ services:
|
||||
# Collector - MQTT subscriber and database storage
|
||||
# ==========================================================================
|
||||
collector:
|
||||
image: ghcr.io/ipnet-mesh/meshcore-hub:main
|
||||
image: ghcr.io/ipnet-mesh/meshcore-hub:${IMAGE_VERSION:-latest}
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
container_name: meshcore-collector
|
||||
profiles:
|
||||
- all
|
||||
- core
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
mqtt:
|
||||
condition: service_healthy
|
||||
db-migrate:
|
||||
condition: service_completed_successfully
|
||||
volumes:
|
||||
# Mount data directory (contains collector/meshcore.db)
|
||||
- ${DATA_HOME:-./data}:/data
|
||||
- hub_data:/data
|
||||
- ${SEED_HOME:-./seed}:/seed
|
||||
environment:
|
||||
- LOG_LEVEL=${LOG_LEVEL:-INFO}
|
||||
- MQTT_HOST=${MQTT_HOST:-mqtt}
|
||||
@@ -147,9 +157,16 @@ services:
|
||||
- MQTT_USERNAME=${MQTT_USERNAME:-}
|
||||
- MQTT_PASSWORD=${MQTT_PASSWORD:-}
|
||||
- MQTT_PREFIX=${MQTT_PREFIX:-meshcore}
|
||||
- MQTT_TLS=${MQTT_TLS:-false}
|
||||
- MQTT_TRANSPORT=${MQTT_TRANSPORT:-tcp}
|
||||
- MQTT_WS_PATH=${MQTT_WS_PATH:-/mqtt}
|
||||
- COLLECTOR_INGEST_MODE=${COLLECTOR_INGEST_MODE:-native}
|
||||
- COLLECTOR_LETSMESH_DECODER_ENABLED=${COLLECTOR_LETSMESH_DECODER_ENABLED:-true}
|
||||
- COLLECTOR_LETSMESH_DECODER_COMMAND=${COLLECTOR_LETSMESH_DECODER_COMMAND:-meshcore-decoder}
|
||||
- COLLECTOR_LETSMESH_DECODER_KEYS=${COLLECTOR_LETSMESH_DECODER_KEYS:-}
|
||||
- COLLECTOR_LETSMESH_DECODER_TIMEOUT_SECONDS=${COLLECTOR_LETSMESH_DECODER_TIMEOUT_SECONDS:-2.0}
|
||||
- DATA_HOME=/data
|
||||
# Explicitly unset to use DATA_HOME-based default path
|
||||
- DATABASE_URL=
|
||||
- SEED_HOME=/seed
|
||||
# Webhook configuration
|
||||
- WEBHOOK_ADVERTISEMENT_URL=${WEBHOOK_ADVERTISEMENT_URL:-}
|
||||
- WEBHOOK_ADVERTISEMENT_SECRET=${WEBHOOK_ADVERTISEMENT_SECRET:-}
|
||||
@@ -162,6 +179,12 @@ services:
|
||||
- WEBHOOK_TIMEOUT=${WEBHOOK_TIMEOUT:-10.0}
|
||||
- WEBHOOK_MAX_RETRIES=${WEBHOOK_MAX_RETRIES:-3}
|
||||
- WEBHOOK_RETRY_BACKOFF=${WEBHOOK_RETRY_BACKOFF:-2.0}
|
||||
# Data retention and cleanup configuration
|
||||
- DATA_RETENTION_ENABLED=${DATA_RETENTION_ENABLED:-true}
|
||||
- DATA_RETENTION_DAYS=${DATA_RETENTION_DAYS:-30}
|
||||
- DATA_RETENTION_INTERVAL_HOURS=${DATA_RETENTION_INTERVAL_HOURS:-24}
|
||||
- NODE_CLEANUP_ENABLED=${NODE_CLEANUP_ENABLED:-true}
|
||||
- NODE_CLEANUP_DAYS=${NODE_CLEANUP_DAYS:-7}
|
||||
command: ["collector"]
|
||||
healthcheck:
|
||||
test: ["CMD", "meshcore-hub", "health", "collector"]
|
||||
@@ -174,22 +197,24 @@ services:
|
||||
# API Server - REST API for querying data and sending commands
|
||||
# ==========================================================================
|
||||
api:
|
||||
image: ghcr.io/ipnet-mesh/meshcore-hub:main
|
||||
image: ghcr.io/ipnet-mesh/meshcore-hub:${IMAGE_VERSION:-latest}
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
container_name: meshcore-api
|
||||
profiles:
|
||||
- all
|
||||
- core
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
mqtt:
|
||||
condition: service_healthy
|
||||
db-migrate:
|
||||
condition: service_completed_successfully
|
||||
collector:
|
||||
condition: service_started
|
||||
ports:
|
||||
- "${API_PORT:-8000}:8000"
|
||||
volumes:
|
||||
# Mount data directory (uses collector/meshcore.db)
|
||||
- ${DATA_HOME:-./data}:/data
|
||||
- hub_data:/data
|
||||
environment:
|
||||
- LOG_LEVEL=${LOG_LEVEL:-INFO}
|
||||
- MQTT_HOST=${MQTT_HOST:-mqtt}
|
||||
@@ -197,13 +222,16 @@ services:
|
||||
- MQTT_USERNAME=${MQTT_USERNAME:-}
|
||||
- MQTT_PASSWORD=${MQTT_PASSWORD:-}
|
||||
- MQTT_PREFIX=${MQTT_PREFIX:-meshcore}
|
||||
- MQTT_TLS=${MQTT_TLS:-false}
|
||||
- MQTT_TRANSPORT=${MQTT_TRANSPORT:-tcp}
|
||||
- MQTT_WS_PATH=${MQTT_WS_PATH:-/mqtt}
|
||||
- DATA_HOME=/data
|
||||
# Explicitly unset to use DATA_HOME-based default path
|
||||
- DATABASE_URL=
|
||||
- API_HOST=0.0.0.0
|
||||
- API_PORT=8000
|
||||
- API_READ_KEY=${API_READ_KEY:-}
|
||||
- API_ADMIN_KEY=${API_ADMIN_KEY:-}
|
||||
- METRICS_ENABLED=${METRICS_ENABLED:-true}
|
||||
- METRICS_CACHE_TTL=${METRICS_CACHE_TTL:-60}
|
||||
command: ["api"]
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"]
|
||||
@@ -216,30 +244,54 @@ services:
|
||||
# Web Dashboard - Web interface for network visualization
|
||||
# ==========================================================================
|
||||
web:
|
||||
image: ghcr.io/ipnet-mesh/meshcore-hub:main
|
||||
image: ghcr.io/ipnet-mesh/meshcore-hub:${IMAGE_VERSION:-latest}
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
container_name: meshcore-web
|
||||
profiles:
|
||||
- all
|
||||
- core
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
api:
|
||||
condition: service_healthy
|
||||
ports:
|
||||
- "${WEB_PORT:-8080}:8080"
|
||||
volumes:
|
||||
- ${CONTENT_HOME:-./content}:/content:ro
|
||||
environment:
|
||||
- LOG_LEVEL=${LOG_LEVEL:-INFO}
|
||||
- API_BASE_URL=http://api:8000
|
||||
- API_KEY=${API_READ_KEY:-}
|
||||
# Use ADMIN key to allow write operations from admin interface
|
||||
# Falls back to READ key if ADMIN key is not set
|
||||
- API_KEY=${API_ADMIN_KEY:-${API_READ_KEY:-}}
|
||||
- WEB_HOST=0.0.0.0
|
||||
- WEB_PORT=8080
|
||||
- WEB_THEME=${WEB_THEME:-dark}
|
||||
- WEB_LOCALE=${WEB_LOCALE:-en}
|
||||
- WEB_DATETIME_LOCALE=${WEB_DATETIME_LOCALE:-en-US}
|
||||
- WEB_ADMIN_ENABLED=${WEB_ADMIN_ENABLED:-false}
|
||||
- NETWORK_NAME=${NETWORK_NAME:-MeshCore Network}
|
||||
- NETWORK_CITY=${NETWORK_CITY:-}
|
||||
- NETWORK_COUNTRY=${NETWORK_COUNTRY:-}
|
||||
- NETWORK_LOCATION=${NETWORK_LOCATION:-}
|
||||
- NETWORK_RADIO_CONFIG=${NETWORK_RADIO_CONFIG:-}
|
||||
- NETWORK_CONTACT_EMAIL=${NETWORK_CONTACT_EMAIL:-}
|
||||
- NETWORK_CONTACT_DISCORD=${NETWORK_CONTACT_DISCORD:-}
|
||||
- NETWORK_CONTACT_GITHUB=${NETWORK_CONTACT_GITHUB:-}
|
||||
- NETWORK_CONTACT_YOUTUBE=${NETWORK_CONTACT_YOUTUBE:-}
|
||||
- NETWORK_WELCOME_TEXT=${NETWORK_WELCOME_TEXT:-}
|
||||
- CONTENT_HOME=/content
|
||||
- TZ=${TZ:-UTC}
|
||||
- COLLECTOR_LETSMESH_DECODER_KEYS=${COLLECTOR_LETSMESH_DECODER_KEYS:-}
|
||||
# Feature flags (set to false to disable specific pages)
|
||||
- FEATURE_DASHBOARD=${FEATURE_DASHBOARD:-true}
|
||||
- FEATURE_NODES=${FEATURE_NODES:-true}
|
||||
- FEATURE_ADVERTISEMENTS=${FEATURE_ADVERTISEMENTS:-true}
|
||||
- FEATURE_MESSAGES=${FEATURE_MESSAGES:-true}
|
||||
- FEATURE_MAP=${FEATURE_MAP:-true}
|
||||
- FEATURE_MEMBERS=${FEATURE_MEMBERS:-true}
|
||||
- FEATURE_PAGES=${FEATURE_PAGES:-true}
|
||||
command: ["web"]
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8080/health')"]
|
||||
@@ -252,52 +304,100 @@ services:
|
||||
# Database Migrations - Run Alembic migrations
|
||||
# ==========================================================================
|
||||
db-migrate:
|
||||
image: ghcr.io/ipnet-mesh/meshcore-hub:main
|
||||
image: ghcr.io/ipnet-mesh/meshcore-hub:${IMAGE_VERSION:-latest}
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
container_name: meshcore-db-migrate
|
||||
profiles:
|
||||
- all
|
||||
- core
|
||||
- migrate
|
||||
restart: "no"
|
||||
volumes:
|
||||
# Mount data directory (uses collector/meshcore.db)
|
||||
- ${DATA_HOME:-./data}:/data
|
||||
- hub_data:/data
|
||||
environment:
|
||||
- DATA_HOME=/data
|
||||
# Explicitly unset to use DATA_HOME-based default path
|
||||
- DATABASE_URL=
|
||||
command: ["db", "upgrade"]
|
||||
|
||||
# ==========================================================================
|
||||
# Seed Data - Import node_tags.json and members.json from SEED_HOME
|
||||
# Seed Data - Import node_tags.yaml and members.yaml from SEED_HOME
|
||||
# NOTE: This is NOT run automatically. Use --profile seed to run explicitly.
|
||||
# Since tags are now managed via the admin UI, automatic seeding would
|
||||
# overwrite user changes.
|
||||
# ==========================================================================
|
||||
seed:
|
||||
image: ghcr.io/ipnet-mesh/meshcore-hub:main
|
||||
image: ghcr.io/ipnet-mesh/meshcore-hub:${IMAGE_VERSION:-latest}
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
container_name: meshcore-seed
|
||||
profiles:
|
||||
- seed
|
||||
restart: "no"
|
||||
volumes:
|
||||
# Mount data directory for database (read-write)
|
||||
- ${DATA_HOME:-./data}:/data
|
||||
# Mount seed directory for seed files (read-only)
|
||||
- hub_data:/data
|
||||
- ${SEED_HOME:-./seed}:/seed:ro
|
||||
environment:
|
||||
- DATA_HOME=/data
|
||||
- SEED_HOME=/seed
|
||||
- LOG_LEVEL=${LOG_LEVEL:-INFO}
|
||||
# Explicitly unset to use DATA_HOME-based default path
|
||||
- DATABASE_URL=
|
||||
# Imports both node_tags.json and members.json if they exist
|
||||
# Imports both node_tags.yaml and members.yaml if they exist
|
||||
command: ["collector", "seed"]
|
||||
|
||||
# ==========================================================================
|
||||
# Prometheus - Metrics collection and monitoring (optional, use --profile metrics)
|
||||
# ==========================================================================
|
||||
prometheus:
|
||||
image: prom/prometheus:latest
|
||||
container_name: meshcore-prometheus
|
||||
profiles:
|
||||
- all
|
||||
- metrics
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
api:
|
||||
condition: service_healthy
|
||||
ports:
|
||||
- "${PROMETHEUS_PORT:-9090}:9090"
|
||||
command:
|
||||
- '--config.file=/etc/prometheus/prometheus.yml'
|
||||
- '--storage.tsdb.retention.time=30d'
|
||||
volumes:
|
||||
- ./etc/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro
|
||||
- ./etc/prometheus/alerts.yml:/etc/prometheus/alerts.yml:ro
|
||||
- prometheus_data:/prometheus
|
||||
|
||||
# ==========================================================================
|
||||
# Alertmanager - Alert routing and notifications (optional, use --profile metrics)
|
||||
# ==========================================================================
|
||||
alertmanager:
|
||||
image: prom/alertmanager:latest
|
||||
container_name: meshcore-alertmanager
|
||||
profiles:
|
||||
- all
|
||||
- metrics
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "${ALERTMANAGER_PORT:-9093}:9093"
|
||||
volumes:
|
||||
- ./etc/alertmanager/alertmanager.yml:/etc/alertmanager/alertmanager.yml:ro
|
||||
- alertmanager_data:/alertmanager
|
||||
command:
|
||||
- '--config.file=/etc/alertmanager/alertmanager.yml'
|
||||
- '--storage.path=/alertmanager'
|
||||
|
||||
# ==========================================================================
|
||||
# Volumes
|
||||
# ==========================================================================
|
||||
volumes:
|
||||
hub_data:
|
||||
name: meshcore_hub_data
|
||||
mosquitto_data:
|
||||
name: meshcore_mosquitto_data
|
||||
mosquitto_log:
|
||||
name: meshcore_mosquitto_log
|
||||
prometheus_data:
|
||||
name: meshcore_prometheus_data
|
||||
alertmanager_data:
|
||||
name: meshcore_alertmanager_data
|
||||
|
||||
BIN
docs/images/web.png
Normal file
BIN
docs/images/web.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 238 KiB |
35
etc/alertmanager/alertmanager.yml
Normal file
35
etc/alertmanager/alertmanager.yml
Normal file
@@ -0,0 +1,35 @@
|
||||
# Alertmanager configuration for MeshCore Hub
|
||||
#
|
||||
# Default configuration routes all alerts to a "blackhole" receiver
|
||||
# (logs only, no external notifications).
|
||||
#
|
||||
# To receive notifications, configure a receiver below.
|
||||
# See: https://prometheus.io/docs/alerting/latest/configuration/
|
||||
#
|
||||
# Examples:
|
||||
#
|
||||
# Email:
|
||||
# receivers:
|
||||
# - name: 'email'
|
||||
# email_configs:
|
||||
# - to: 'admin@example.com'
|
||||
# from: 'alertmanager@example.com'
|
||||
# smarthost: 'smtp.example.com:587'
|
||||
# auth_username: 'alertmanager@example.com'
|
||||
# auth_password: 'password'
|
||||
#
|
||||
# Webhook (e.g. Slack incoming webhook, ntfy, Gotify):
|
||||
# receivers:
|
||||
# - name: 'webhook'
|
||||
# webhook_configs:
|
||||
# - url: 'https://example.com/webhook'
|
||||
|
||||
route:
|
||||
receiver: 'default'
|
||||
group_by: ['alertname']
|
||||
group_wait: 30s
|
||||
group_interval: 5m
|
||||
repeat_interval: 4h
|
||||
|
||||
receivers:
|
||||
- name: 'default'
|
||||
16
etc/prometheus/alerts.yml
Normal file
16
etc/prometheus/alerts.yml
Normal file
@@ -0,0 +1,16 @@
|
||||
# Prometheus alert rules for MeshCore Hub
|
||||
#
|
||||
# These rules are evaluated by Prometheus and fired alerts are sent
|
||||
# to Alertmanager for routing and notification.
|
||||
|
||||
groups:
|
||||
- name: meshcore
|
||||
rules:
|
||||
- alert: NodeNotSeen
|
||||
expr: time() - meshcore_node_last_seen_timestamp_seconds{role="infra"} > 48 * 3600
|
||||
for: 5m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "Node {{ $labels.node_name }} ({{ $labels.role }}) not seen for 48+ hours"
|
||||
description: "Node {{ $labels.public_key }} ({{ $labels.adv_type }}, role={{ $labels.role }}) last seen {{ $value | humanizeDuration }} ago."
|
||||
29
etc/prometheus/prometheus.yml
Normal file
29
etc/prometheus/prometheus.yml
Normal file
@@ -0,0 +1,29 @@
|
||||
# Prometheus scrape configuration for MeshCore Hub
|
||||
#
|
||||
# This file is used when running Prometheus via Docker Compose:
|
||||
# docker compose --profile core --profile metrics up -d
|
||||
#
|
||||
# The scrape interval matches the default metrics cache TTL (60s)
|
||||
# to avoid unnecessary database queries.
|
||||
|
||||
global:
|
||||
scrape_interval: 60s
|
||||
evaluation_interval: 60s
|
||||
|
||||
alerting:
|
||||
alertmanagers:
|
||||
- static_configs:
|
||||
- targets: ['alertmanager:9093']
|
||||
|
||||
rule_files:
|
||||
- 'alerts.yml'
|
||||
|
||||
scrape_configs:
|
||||
- job_name: 'meshcore-hub'
|
||||
metrics_path: '/metrics'
|
||||
# Uncomment basic_auth if API_READ_KEY is configured
|
||||
# basic_auth:
|
||||
# username: 'metrics'
|
||||
# password: '<API_READ_KEY>'
|
||||
static_configs:
|
||||
- targets: ['api:8000']
|
||||
61
example/content/media/images/logo-invert.svg
Normal file
61
example/content/media/images/logo-invert.svg
Normal file
@@ -0,0 +1,61 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
viewBox="0 0 115 100"
|
||||
width="115"
|
||||
height="100"
|
||||
version="1.1"
|
||||
id="svg4"
|
||||
sodipodi:docname="logo-dark.svg"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg">
|
||||
<defs
|
||||
id="defs4" />
|
||||
<sodipodi:namedview
|
||||
id="namedview4"
|
||||
pagecolor="#ffffff"
|
||||
bordercolor="#000000"
|
||||
borderopacity="0.25"
|
||||
inkscape:showpageshadow="2"
|
||||
inkscape:pageopacity="0.0"
|
||||
inkscape:pagecheckerboard="0"
|
||||
inkscape:deskcolor="#d1d1d1" />
|
||||
<!-- I letter - muted -->
|
||||
<rect
|
||||
x="0"
|
||||
y="0"
|
||||
width="25"
|
||||
height="100"
|
||||
rx="2"
|
||||
fill="#ffffff"
|
||||
opacity="0.5"
|
||||
id="rect1" />
|
||||
<!-- P vertical stem -->
|
||||
<rect
|
||||
x="35"
|
||||
y="0"
|
||||
width="25"
|
||||
height="100"
|
||||
rx="2"
|
||||
fill="#ffffff"
|
||||
id="rect2" />
|
||||
<!-- WiFi arcs: center at mid-stem (90, 60), sweeping from right up to top -->
|
||||
<g
|
||||
fill="none"
|
||||
stroke="#ffffff"
|
||||
stroke-width="10"
|
||||
stroke-linecap="round"
|
||||
id="g4"
|
||||
transform="translate(-30,-10)">
|
||||
<path
|
||||
d="M 110,65 A 20,20 0 0 0 90,45"
|
||||
id="path2" />
|
||||
<path
|
||||
d="M 125,65 A 35,35 0 0 0 90,30"
|
||||
id="path3" />
|
||||
<path
|
||||
d="M 140,65 A 50,50 0 0 0 90,15"
|
||||
id="path4" />
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.4 KiB |
87
example/content/pages/join.md
Normal file
87
example/content/pages/join.md
Normal file
@@ -0,0 +1,87 @@
|
||||
---
|
||||
title: Join
|
||||
slug: join
|
||||
menu_order: 10
|
||||
---
|
||||
|
||||
# Getting Started with MeshCore
|
||||
|
||||
MeshCore is an open-source off-grid LoRa mesh networking platform. This guide will help you get connected to the network.
|
||||
|
||||
For detailed documentation, see the [MeshCore FAQ](https://github.com/meshcore-dev/MeshCore/blob/main/docs/faq.md).
|
||||
|
||||
## Node Types
|
||||
|
||||
MeshCore devices operate in different modes:
|
||||
|
||||
| Mode | Description |
|
||||
|------|-------------|
|
||||
| **Companion** | Connects to your phone via Bluetooth. Use this for messaging and interacting with the network. |
|
||||
| **Repeater** | Standalone node that extends network coverage. Place these in elevated locations for best results. |
|
||||
| **Room Server** | Hosts chat rooms that persist messages for offline users. |
|
||||
|
||||
Most users start with a **Companion** node paired to their phone.
|
||||
|
||||
## Frequency Regulations
|
||||
|
||||
MeshCore uses LoRa radio, which operates on unlicensed ISM bands. You **must** use the correct frequency for your region:
|
||||
|
||||
| Region | Frequency | Notes |
|
||||
|--------|-----------|-------|
|
||||
| Europe (EU) | 868 MHz | EU868 band |
|
||||
| United Kingdom | 868 MHz | Same as EU |
|
||||
| North America | 915 MHz | US915 band |
|
||||
| Australia | 915 MHz | AU915 band |
|
||||
|
||||
Using the wrong frequency is illegal and may cause interference. Check your local regulations.
|
||||
|
||||
## Compatible Hardware
|
||||
|
||||
MeshCore runs on inexpensive low-power LoRa devices. Popular options include:
|
||||
|
||||
### Recommended Devices
|
||||
|
||||
| Device | Manufacturer | Features |
|
||||
|--------|--------------|----------|
|
||||
| [Heltec V3](https://heltec.org/project/wifi-lora-32-v3/) | Heltec | Budget-friendly, OLED display |
|
||||
| [T114](https://heltec.org/project/mesh-node-t114/) | Heltec | Compact, GPS, colour display |
|
||||
| [T1000-E](https://www.seeedstudio.com/SenseCAP-Card-Tracker-T1000-E-for-Meshtastic-p-5913.html) | Seeed Studio | Credit-card sized, GPS, weatherproof |
|
||||
| [T-Deck Plus](https://www.lilygo.cc/products/t-deck-plus) | LilyGO | Built-in keyboard, touchscreen, GPS |
|
||||
|
||||
Ensure you purchase the correct frequency variant (868MHz for EU/UK, 915MHz for US/AU).
|
||||
|
||||
### Where to Buy
|
||||
|
||||
- **Heltec**: [Official Store](https://heltec.org/) or AliExpress
|
||||
- **LilyGO**: [Official Store](https://lilygo.cc/) or AliExpress
|
||||
- **Seeed Studio**: [Official Store](https://www.seeedstudio.com/)
|
||||
- **Amazon**: Search for device name + "LoRa 868" (or 915 for US)
|
||||
|
||||
## Mobile Apps
|
||||
|
||||
Connect to your Companion node using the official MeshCore apps:
|
||||
|
||||
| Platform | App | Link |
|
||||
|----------|-----|------|
|
||||
| Android | MeshCore | [Google Play](https://play.google.com/store/apps/details?id=com.liamcottle.meshcore.android) |
|
||||
| iOS | MeshCore | [App Store](https://apps.apple.com/us/app/meshcore/id6742354151) |
|
||||
|
||||
The app connects via Bluetooth to your Companion node, allowing you to send messages, view the network, and configure your device.
|
||||
|
||||
## Flashing Firmware
|
||||
|
||||
1. Use the [MeshCore Web Flasher](https://flasher.meshcore.co.uk/) for easy browser-based flashing
|
||||
2. Select your device type and region (frequency)
|
||||
3. Connect via USB and flash
|
||||
|
||||
## Next Steps
|
||||
|
||||
Once your device is flashed and paired:
|
||||
|
||||
1. Open the MeshCore app on your phone
|
||||
2. Enable Bluetooth and pair with your device
|
||||
3. Set your node name in the app settings
|
||||
4. Configure your radio settings/profile for your region
|
||||
4. You should start seeing other nodes on the network
|
||||
|
||||
Welcome to the mesh!
|
||||
@@ -1,10 +0,0 @@
|
||||
{
|
||||
"members": [
|
||||
{
|
||||
"name": "Example Member",
|
||||
"callsign": "N0CALL",
|
||||
"role": "Network Operator",
|
||||
"description": "Example member entry"
|
||||
}
|
||||
]
|
||||
}
|
||||
14
example/seed/members.yaml
Normal file
14
example/seed/members.yaml
Normal file
@@ -0,0 +1,14 @@
|
||||
# Example members seed file
|
||||
# Note: Nodes are associated with members via a 'member_id' tag on the node.
|
||||
# Use node_tags.yaml to set member_id tags on nodes.
|
||||
members:
|
||||
- member_id: example_member
|
||||
name: Example Member
|
||||
callsign: N0CALL
|
||||
role: Network Operator
|
||||
description: Example network operator member
|
||||
- member_id: simple_member
|
||||
name: Simple Member
|
||||
callsign: N0CALL2
|
||||
role: Observer
|
||||
description: Example observer member
|
||||
@@ -1,16 +0,0 @@
|
||||
{
|
||||
"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef": {
|
||||
"friendly_name": "Gateway Node",
|
||||
"location": {"value": "37.7749,-122.4194", "type": "coordinate"},
|
||||
"lat": {"value": "37.7749", "type": "number"},
|
||||
"lon": {"value": "-122.4194", "type": "number"},
|
||||
"role": "gateway"
|
||||
},
|
||||
"fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210": {
|
||||
"friendly_name": "Oakland Repeater",
|
||||
"location": {"value": "37.8044,-122.2712", "type": "coordinate"},
|
||||
"lat": {"value": "37.8044", "type": "number"},
|
||||
"lon": {"value": "-122.2712", "type": "number"},
|
||||
"altitude": {"value": "150", "type": "number"}
|
||||
}
|
||||
}
|
||||
29
example/seed/node_tags.yaml
Normal file
29
example/seed/node_tags.yaml
Normal file
@@ -0,0 +1,29 @@
|
||||
# Example node tags seed file
|
||||
# Each key is a 64-character hex public key
|
||||
#
|
||||
# Tag values can be:
|
||||
# - YAML primitives (auto-detected type):
|
||||
# friendly_name: Gateway Node # string
|
||||
# elevation: 150 # number
|
||||
# is_online: true # boolean
|
||||
#
|
||||
# - Explicit type (when you need to force a specific type):
|
||||
# altitude:
|
||||
# value: "150"
|
||||
# type: number
|
||||
#
|
||||
# Supported types: string, number, boolean
|
||||
|
||||
0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef:
|
||||
friendly_name: Gateway Node
|
||||
role: gateway
|
||||
lat: 37.7749
|
||||
lon: -122.4194
|
||||
is_online: true
|
||||
|
||||
fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210:
|
||||
friendly_name: Oakland Repeater
|
||||
lat: 37.8044
|
||||
lon: -122.2712
|
||||
altitude: 150
|
||||
is_online: false
|
||||
58
patches/@michaelhart+meshcore-decoder+0.2.7.patch
Normal file
58
patches/@michaelhart+meshcore-decoder+0.2.7.patch
Normal file
@@ -0,0 +1,58 @@
|
||||
diff --git a/node_modules/@michaelhart/meshcore-decoder/dist/crypto/ed25519-verifier.js b/node_modules/@michaelhart/meshcore-decoder/dist/crypto/ed25519-verifier.js
|
||||
index d33ffd6..8d040d0 100644
|
||||
--- a/node_modules/@michaelhart/meshcore-decoder/dist/crypto/ed25519-verifier.js
|
||||
+++ b/node_modules/@michaelhart/meshcore-decoder/dist/crypto/ed25519-verifier.js
|
||||
@@ -36,7 +36,27 @@ var __importStar = (this && this.__importStar) || (function () {
|
||||
})();
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Ed25519SignatureVerifier = void 0;
|
||||
-const ed25519 = __importStar(require("@noble/ed25519"));
|
||||
+let _ed25519 = null;
|
||||
+async function getEd25519() {
|
||||
+ if (_ed25519) {
|
||||
+ return _ed25519;
|
||||
+ }
|
||||
+ const mod = await import("@noble/ed25519");
|
||||
+ _ed25519 = mod.default ? mod.default : mod;
|
||||
+ try {
|
||||
+ _ed25519.etc.sha512Async = sha512Hash;
|
||||
+ }
|
||||
+ catch (error) {
|
||||
+ console.debug("Could not set async SHA-512:", error);
|
||||
+ }
|
||||
+ try {
|
||||
+ _ed25519.etc.sha512Sync = sha512HashSync;
|
||||
+ }
|
||||
+ catch (error) {
|
||||
+ console.debug("Could not set up synchronous SHA-512:", error);
|
||||
+ }
|
||||
+ return _ed25519;
|
||||
+}
|
||||
const hex_1 = require("../utils/hex");
|
||||
const orlp_ed25519_wasm_1 = require("./orlp-ed25519-wasm");
|
||||
// Cross-platform SHA-512 implementation
|
||||
@@ -90,16 +110,6 @@ function sha512HashSync(data) {
|
||||
throw new Error('No SHA-512 implementation available for synchronous operation');
|
||||
}
|
||||
}
|
||||
-// Set up SHA-512 for @noble/ed25519
|
||||
-ed25519.etc.sha512Async = sha512Hash;
|
||||
-// Always set up sync version - @noble/ed25519 requires it
|
||||
-// It will throw in browser environments, which @noble/ed25519 can handle
|
||||
-try {
|
||||
- ed25519.etc.sha512Sync = sha512HashSync;
|
||||
-}
|
||||
-catch (error) {
|
||||
- console.debug('Could not set up synchronous SHA-512:', error);
|
||||
-}
|
||||
class Ed25519SignatureVerifier {
|
||||
/**
|
||||
* Verify an Ed25519 signature for MeshCore advertisement packets
|
||||
@@ -116,6 +126,7 @@ class Ed25519SignatureVerifier {
|
||||
// Construct the signed message according to MeshCore format
|
||||
const message = this.constructAdvertSignedMessage(publicKeyHex, timestamp, appData);
|
||||
// Verify the signature using noble-ed25519
|
||||
+ const ed25519 = await getEd25519();
|
||||
return await ed25519.verify(signature, message, publicKey);
|
||||
}
|
||||
catch (error) {
|
||||
@@ -4,22 +4,21 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "meshcore-hub"
|
||||
version = "0.1.0"
|
||||
version = "0.0.0"
|
||||
description = "Python monorepo for managing and orchestrating MeshCore mesh networks"
|
||||
readme = "README.md"
|
||||
license = {text = "MIT"}
|
||||
requires-python = ">=3.11"
|
||||
license = {text = "GPL-3.0-or-later"}
|
||||
requires-python = ">=3.13"
|
||||
authors = [
|
||||
{name = "MeshCore Hub Contributors"}
|
||||
]
|
||||
classifiers = [
|
||||
"Development Status :: 3 - Alpha",
|
||||
"Intended Audience :: Developers",
|
||||
"License :: OSI Approved :: MIT License",
|
||||
"License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
|
||||
"Operating System :: OS Independent",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
"Programming Language :: Python :: 3.13",
|
||||
"Topic :: Communications",
|
||||
"Topic :: System :: Networking",
|
||||
]
|
||||
@@ -38,7 +37,11 @@ dependencies = [
|
||||
"python-multipart>=0.0.6",
|
||||
"httpx>=0.25.0",
|
||||
"aiosqlite>=0.19.0",
|
||||
"meshcore>=2.2.0",
|
||||
"meshcore>=2.3.0",
|
||||
"pyyaml>=6.0.0",
|
||||
"python-frontmatter>=1.0.0",
|
||||
"markdown>=3.5.0",
|
||||
"prometheus-client>=0.20.0",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
@@ -50,7 +53,9 @@ dev = [
|
||||
"flake8>=6.1.0",
|
||||
"mypy>=1.5.0",
|
||||
"pre-commit>=3.4.0",
|
||||
"beautifulsoup4>=4.12.0",
|
||||
"types-paho-mqtt>=1.6.0",
|
||||
"types-PyYAML>=6.0.0",
|
||||
]
|
||||
postgres = [
|
||||
"asyncpg>=0.28.0",
|
||||
@@ -61,10 +66,10 @@ postgres = [
|
||||
meshcore-hub = "meshcore_hub.__main__:main"
|
||||
|
||||
[project.urls]
|
||||
Homepage = "https://github.com/meshcore-dev/meshcore-hub"
|
||||
Documentation = "https://github.com/meshcore-dev/meshcore-hub#readme"
|
||||
Repository = "https://github.com/meshcore-dev/meshcore-hub"
|
||||
Issues = "https://github.com/meshcore-dev/meshcore-hub/issues"
|
||||
Homepage = "https://github.com/ipnet-mesh/meshcore-hub"
|
||||
Documentation = "https://github.com/ipnet-mesh/meshcore-hub#readme"
|
||||
Repository = "https://github.com/ipnet-mesh/meshcore-hub"
|
||||
Issues = "https://github.com/ipnet-mesh/meshcore-hub/issues"
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
where = ["src"]
|
||||
@@ -76,7 +81,7 @@ meshcore_hub = ["py.typed"]
|
||||
|
||||
[tool.black]
|
||||
line-length = 88
|
||||
target-version = ["py311"]
|
||||
target-version = ["py312"]
|
||||
include = '\.pyi?$'
|
||||
extend-exclude = '''
|
||||
/(
|
||||
@@ -95,7 +100,7 @@ extend-exclude = '''
|
||||
'''
|
||||
|
||||
[tool.mypy]
|
||||
python_version = "3.11"
|
||||
python_version = "3.13"
|
||||
warn_return_any = true
|
||||
warn_unused_ignores = true
|
||||
disallow_untyped_defs = true
|
||||
@@ -110,6 +115,9 @@ module = [
|
||||
"uvicorn.*",
|
||||
"alembic.*",
|
||||
"meshcore.*",
|
||||
"frontmatter.*",
|
||||
"markdown.*",
|
||||
"prometheus_client.*",
|
||||
]
|
||||
ignore_missing_imports = true
|
||||
|
||||
|
||||
6
renovate.json
Normal file
6
renovate.json
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||
"extends": [
|
||||
"config:recommended"
|
||||
]
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
"""MeshCore Hub - Python monorepo for managing MeshCore mesh networks."""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
from meshcore_hub._version import __version__
|
||||
|
||||
__all__ = ["__version__"]
|
||||
|
||||
@@ -174,6 +174,40 @@ def db_history() -> None:
|
||||
command.history(alembic_cfg)
|
||||
|
||||
|
||||
@db.command("stamp")
|
||||
@click.option(
|
||||
"--revision",
|
||||
type=str,
|
||||
default="head",
|
||||
help="Target revision to stamp (default: head)",
|
||||
)
|
||||
@click.option(
|
||||
"--database-url",
|
||||
type=str,
|
||||
default=None,
|
||||
envvar="DATABASE_URL",
|
||||
help="Database connection URL",
|
||||
)
|
||||
def db_stamp(revision: str, database_url: str | None) -> None:
|
||||
"""Stamp database with revision without running migrations.
|
||||
|
||||
Use this to mark an existing database as up-to-date when the schema
|
||||
was created before Alembic migrations were introduced.
|
||||
"""
|
||||
import os
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
|
||||
click.echo(f"Stamping database with revision: {revision}")
|
||||
|
||||
alembic_cfg = Config("alembic.ini")
|
||||
if database_url:
|
||||
os.environ["DATABASE_URL"] = database_url
|
||||
|
||||
command.stamp(alembic_cfg, revision)
|
||||
click.echo("Database stamped successfully.")
|
||||
|
||||
|
||||
# Health check commands for Docker HEALTHCHECK
|
||||
@cli.group()
|
||||
def health() -> None:
|
||||
|
||||
8
src/meshcore_hub/_version.py
Normal file
8
src/meshcore_hub/_version.py
Normal file
@@ -0,0 +1,8 @@
|
||||
"""MeshCore Hub version information.
|
||||
|
||||
This file contains the version string for the package.
|
||||
It can be overridden at build time by setting BUILD_VERSION environment variable.
|
||||
"""
|
||||
|
||||
__version__ = "dev"
|
||||
__all__ = ["__version__"]
|
||||
@@ -32,10 +32,9 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
|
||||
# Get database URL from app state
|
||||
database_url = getattr(app.state, "database_url", "sqlite:///./meshcore.db")
|
||||
|
||||
# Initialize database
|
||||
# Initialize database (schema managed by Alembic migrations)
|
||||
logger.info(f"Initializing database: {database_url}")
|
||||
_db_manager = DatabaseManager(database_url)
|
||||
_db_manager.create_tables()
|
||||
|
||||
yield
|
||||
|
||||
@@ -52,8 +51,15 @@ def create_app(
|
||||
admin_key: str | None = None,
|
||||
mqtt_host: str = "localhost",
|
||||
mqtt_port: int = 1883,
|
||||
mqtt_username: str | None = None,
|
||||
mqtt_password: str | None = None,
|
||||
mqtt_prefix: str = "meshcore",
|
||||
mqtt_tls: bool = False,
|
||||
mqtt_transport: str = "tcp",
|
||||
mqtt_ws_path: str = "/mqtt",
|
||||
cors_origins: list[str] | None = None,
|
||||
metrics_enabled: bool = True,
|
||||
metrics_cache_ttl: int = 60,
|
||||
) -> FastAPI:
|
||||
"""Create and configure the FastAPI application.
|
||||
|
||||
@@ -63,8 +69,15 @@ def create_app(
|
||||
admin_key: Admin API key
|
||||
mqtt_host: MQTT broker host
|
||||
mqtt_port: MQTT broker port
|
||||
mqtt_username: MQTT username
|
||||
mqtt_password: MQTT password
|
||||
mqtt_prefix: MQTT topic prefix
|
||||
mqtt_tls: Enable TLS/SSL for MQTT connection
|
||||
mqtt_transport: MQTT transport protocol (tcp or websockets)
|
||||
mqtt_ws_path: WebSocket path (used when transport=websockets)
|
||||
cors_origins: Allowed CORS origins
|
||||
metrics_enabled: Enable Prometheus metrics endpoint at /metrics
|
||||
metrics_cache_ttl: Seconds to cache metrics output
|
||||
|
||||
Returns:
|
||||
Configured FastAPI application
|
||||
@@ -85,7 +98,13 @@ def create_app(
|
||||
app.state.admin_key = admin_key
|
||||
app.state.mqtt_host = mqtt_host
|
||||
app.state.mqtt_port = mqtt_port
|
||||
app.state.mqtt_username = mqtt_username
|
||||
app.state.mqtt_password = mqtt_password
|
||||
app.state.mqtt_prefix = mqtt_prefix
|
||||
app.state.mqtt_tls = mqtt_tls
|
||||
app.state.mqtt_transport = mqtt_transport
|
||||
app.state.mqtt_ws_path = mqtt_ws_path
|
||||
app.state.metrics_cache_ttl = metrics_cache_ttl
|
||||
|
||||
# Configure CORS
|
||||
if cors_origins is None:
|
||||
@@ -104,6 +123,12 @@ def create_app(
|
||||
|
||||
app.include_router(api_router, prefix="/api/v1")
|
||||
|
||||
# Include Prometheus metrics endpoint
|
||||
if metrics_enabled:
|
||||
from meshcore_hub.api.metrics import router as metrics_router
|
||||
|
||||
app.include_router(metrics_router)
|
||||
|
||||
# Health check endpoints
|
||||
@app.get("/health", tags=["Health"])
|
||||
async def health() -> dict:
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Authentication middleware for the API."""
|
||||
|
||||
import hmac
|
||||
import logging
|
||||
from typing import Annotated
|
||||
|
||||
@@ -79,7 +80,9 @@ async def require_read(
|
||||
)
|
||||
|
||||
# Check if token matches any key
|
||||
if token == read_key or token == admin_key:
|
||||
if (read_key and hmac.compare_digest(token, read_key)) or (
|
||||
admin_key and hmac.compare_digest(token, admin_key)
|
||||
):
|
||||
return token
|
||||
|
||||
raise HTTPException(
|
||||
@@ -124,7 +127,7 @@ async def require_admin(
|
||||
)
|
||||
|
||||
# Check if token matches admin key
|
||||
if token == admin_key:
|
||||
if hmac.compare_digest(token, admin_key):
|
||||
return token
|
||||
|
||||
raise HTTPException(
|
||||
|
||||
@@ -60,13 +60,48 @@ import click
|
||||
envvar="MQTT_PORT",
|
||||
help="MQTT broker port",
|
||||
)
|
||||
@click.option(
|
||||
"--mqtt-username",
|
||||
type=str,
|
||||
default=None,
|
||||
envvar="MQTT_USERNAME",
|
||||
help="MQTT username",
|
||||
)
|
||||
@click.option(
|
||||
"--mqtt-password",
|
||||
type=str,
|
||||
default=None,
|
||||
envvar="MQTT_PASSWORD",
|
||||
help="MQTT password",
|
||||
)
|
||||
@click.option(
|
||||
"--mqtt-prefix",
|
||||
type=str,
|
||||
default="meshcore",
|
||||
envvar="MQTT_TOPIC_PREFIX",
|
||||
envvar=["MQTT_PREFIX", "MQTT_TOPIC_PREFIX"],
|
||||
help="MQTT topic prefix",
|
||||
)
|
||||
@click.option(
|
||||
"--mqtt-tls",
|
||||
is_flag=True,
|
||||
default=False,
|
||||
envvar="MQTT_TLS",
|
||||
help="Enable TLS/SSL for MQTT connection",
|
||||
)
|
||||
@click.option(
|
||||
"--mqtt-transport",
|
||||
type=click.Choice(["tcp", "websockets"], case_sensitive=False),
|
||||
default="tcp",
|
||||
envvar="MQTT_TRANSPORT",
|
||||
help="MQTT transport protocol",
|
||||
)
|
||||
@click.option(
|
||||
"--mqtt-ws-path",
|
||||
type=str,
|
||||
default="/mqtt",
|
||||
envvar="MQTT_WS_PATH",
|
||||
help="MQTT WebSocket path (used when transport=websockets)",
|
||||
)
|
||||
@click.option(
|
||||
"--cors-origins",
|
||||
type=str,
|
||||
@@ -74,6 +109,19 @@ import click
|
||||
envvar="CORS_ORIGINS",
|
||||
help="Comma-separated list of allowed CORS origins",
|
||||
)
|
||||
@click.option(
|
||||
"--metrics-enabled/--no-metrics",
|
||||
default=True,
|
||||
envvar="METRICS_ENABLED",
|
||||
help="Enable Prometheus metrics endpoint at /metrics",
|
||||
)
|
||||
@click.option(
|
||||
"--metrics-cache-ttl",
|
||||
type=int,
|
||||
default=60,
|
||||
envvar="METRICS_CACHE_TTL",
|
||||
help="Seconds to cache metrics output (reduces database load)",
|
||||
)
|
||||
@click.option(
|
||||
"--reload",
|
||||
is_flag=True,
|
||||
@@ -91,8 +139,15 @@ def api(
|
||||
admin_key: str | None,
|
||||
mqtt_host: str,
|
||||
mqtt_port: int,
|
||||
mqtt_username: str | None,
|
||||
mqtt_password: str | None,
|
||||
mqtt_prefix: str,
|
||||
mqtt_tls: bool,
|
||||
mqtt_transport: str,
|
||||
mqtt_ws_path: str,
|
||||
cors_origins: str | None,
|
||||
metrics_enabled: bool,
|
||||
metrics_cache_ttl: int,
|
||||
reload: bool,
|
||||
) -> None:
|
||||
"""Run the REST API server.
|
||||
@@ -138,9 +193,12 @@ def api(
|
||||
click.echo(f"Data home: {effective_data_home}")
|
||||
click.echo(f"Database: {effective_db_url}")
|
||||
click.echo(f"MQTT: {mqtt_host}:{mqtt_port} (prefix: {mqtt_prefix})")
|
||||
click.echo(f"MQTT transport: {mqtt_transport} (ws_path: {mqtt_ws_path})")
|
||||
click.echo(f"Read key configured: {read_key is not None}")
|
||||
click.echo(f"Admin key configured: {admin_key is not None}")
|
||||
click.echo(f"CORS origins: {cors_origins or 'none'}")
|
||||
click.echo(f"Metrics enabled: {metrics_enabled}")
|
||||
click.echo(f"Metrics cache TTL: {metrics_cache_ttl}s")
|
||||
click.echo(f"Reload mode: {reload}")
|
||||
click.echo("=" * 50)
|
||||
|
||||
@@ -170,8 +228,15 @@ def api(
|
||||
admin_key=admin_key,
|
||||
mqtt_host=mqtt_host,
|
||||
mqtt_port=mqtt_port,
|
||||
mqtt_username=mqtt_username,
|
||||
mqtt_password=mqtt_password,
|
||||
mqtt_prefix=mqtt_prefix,
|
||||
mqtt_tls=mqtt_tls,
|
||||
mqtt_transport=mqtt_transport,
|
||||
mqtt_ws_path=mqtt_ws_path,
|
||||
cors_origins=origins_list,
|
||||
metrics_enabled=metrics_enabled,
|
||||
metrics_cache_ttl=metrics_cache_ttl,
|
||||
)
|
||||
|
||||
click.echo("\nStarting API server...")
|
||||
|
||||
@@ -56,15 +56,25 @@ def get_mqtt_client(request: Request) -> MQTTClient:
|
||||
"""
|
||||
mqtt_host = getattr(request.app.state, "mqtt_host", "localhost")
|
||||
mqtt_port = getattr(request.app.state, "mqtt_port", 1883)
|
||||
mqtt_username = getattr(request.app.state, "mqtt_username", None)
|
||||
mqtt_password = getattr(request.app.state, "mqtt_password", None)
|
||||
mqtt_prefix = getattr(request.app.state, "mqtt_prefix", "meshcore")
|
||||
mqtt_tls = getattr(request.app.state, "mqtt_tls", False)
|
||||
mqtt_transport = getattr(request.app.state, "mqtt_transport", "tcp")
|
||||
mqtt_ws_path = getattr(request.app.state, "mqtt_ws_path", "/mqtt")
|
||||
|
||||
# Use unique client ID to allow multiple API instances
|
||||
unique_id = uuid.uuid4().hex[:8]
|
||||
config = MQTTConfig(
|
||||
host=mqtt_host,
|
||||
port=mqtt_port,
|
||||
username=mqtt_username,
|
||||
password=mqtt_password,
|
||||
prefix=mqtt_prefix,
|
||||
client_id=f"meshcore-api-{unique_id}",
|
||||
tls=mqtt_tls,
|
||||
transport=mqtt_transport,
|
||||
ws_path=mqtt_ws_path,
|
||||
)
|
||||
|
||||
client = MQTTClient(config)
|
||||
|
||||
334
src/meshcore_hub/api/metrics.py
Normal file
334
src/meshcore_hub/api/metrics.py
Normal file
@@ -0,0 +1,334 @@
|
||||
"""Prometheus metrics endpoint for MeshCore Hub API."""
|
||||
|
||||
import base64
|
||||
import hmac
|
||||
import logging
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Request, Response
|
||||
from fastapi.responses import PlainTextResponse
|
||||
from prometheus_client import CollectorRegistry, Gauge, generate_latest
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from meshcore_hub.common.models import (
|
||||
Advertisement,
|
||||
EventLog,
|
||||
Member,
|
||||
Message,
|
||||
Node,
|
||||
NodeTag,
|
||||
Telemetry,
|
||||
TracePath,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# Module-level cache
|
||||
_cache: dict[str, Any] = {"output": b"", "expires_at": 0.0}
|
||||
|
||||
|
||||
def verify_basic_auth(request: Request) -> bool:
|
||||
"""Verify HTTP Basic Auth credentials for metrics endpoint.
|
||||
|
||||
Uses username 'metrics' and the API read key as password.
|
||||
Returns True if no read key is configured (public access).
|
||||
|
||||
Args:
|
||||
request: FastAPI request
|
||||
|
||||
Returns:
|
||||
True if authentication passes
|
||||
"""
|
||||
read_key = getattr(request.app.state, "read_key", None)
|
||||
|
||||
# No read key configured = public access
|
||||
if not read_key:
|
||||
return True
|
||||
|
||||
auth_header = request.headers.get("Authorization", "")
|
||||
if not auth_header.startswith("Basic "):
|
||||
return False
|
||||
|
||||
try:
|
||||
decoded = base64.b64decode(auth_header[6:]).decode("utf-8")
|
||||
username, password = decoded.split(":", 1)
|
||||
return hmac.compare_digest(username, "metrics") and hmac.compare_digest(
|
||||
password, read_key
|
||||
)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def collect_metrics(session: Any) -> bytes:
|
||||
"""Collect all metrics from the database and generate Prometheus output.
|
||||
|
||||
Creates a fresh CollectorRegistry per call to avoid global state issues.
|
||||
|
||||
Args:
|
||||
session: SQLAlchemy database session
|
||||
|
||||
Returns:
|
||||
Prometheus text exposition format as bytes
|
||||
"""
|
||||
from meshcore_hub import __version__
|
||||
|
||||
registry = CollectorRegistry()
|
||||
|
||||
# -- Info gauge --
|
||||
info_gauge = Gauge(
|
||||
"meshcore_info",
|
||||
"MeshCore Hub application info",
|
||||
["version"],
|
||||
registry=registry,
|
||||
)
|
||||
info_gauge.labels(version=__version__).set(1)
|
||||
|
||||
# -- Nodes total --
|
||||
nodes_total = Gauge(
|
||||
"meshcore_nodes_total",
|
||||
"Total number of nodes",
|
||||
registry=registry,
|
||||
)
|
||||
count = session.execute(select(func.count(Node.id))).scalar() or 0
|
||||
nodes_total.set(count)
|
||||
|
||||
# -- Nodes active by time window --
|
||||
nodes_active = Gauge(
|
||||
"meshcore_nodes_active",
|
||||
"Number of active nodes in time window",
|
||||
["window"],
|
||||
registry=registry,
|
||||
)
|
||||
for window, hours in [("1h", 1), ("24h", 24), ("7d", 168), ("30d", 720)]:
|
||||
cutoff = time.time() - (hours * 3600)
|
||||
from datetime import datetime, timezone
|
||||
|
||||
cutoff_dt = datetime.fromtimestamp(cutoff, tz=timezone.utc)
|
||||
count = (
|
||||
session.execute(
|
||||
select(func.count(Node.id)).where(Node.last_seen >= cutoff_dt)
|
||||
).scalar()
|
||||
or 0
|
||||
)
|
||||
nodes_active.labels(window=window).set(count)
|
||||
|
||||
# -- Nodes by type --
|
||||
nodes_by_type = Gauge(
|
||||
"meshcore_nodes_by_type",
|
||||
"Number of nodes by advertisement type",
|
||||
["adv_type"],
|
||||
registry=registry,
|
||||
)
|
||||
type_counts = session.execute(
|
||||
select(Node.adv_type, func.count(Node.id)).group_by(Node.adv_type)
|
||||
).all()
|
||||
for adv_type, count in type_counts:
|
||||
nodes_by_type.labels(adv_type=adv_type or "unknown").set(count)
|
||||
|
||||
# -- Nodes with location --
|
||||
nodes_with_location = Gauge(
|
||||
"meshcore_nodes_with_location",
|
||||
"Number of nodes with GPS coordinates",
|
||||
registry=registry,
|
||||
)
|
||||
count = (
|
||||
session.execute(
|
||||
select(func.count(Node.id)).where(
|
||||
Node.lat.isnot(None), Node.lon.isnot(None)
|
||||
)
|
||||
).scalar()
|
||||
or 0
|
||||
)
|
||||
nodes_with_location.set(count)
|
||||
|
||||
# -- Node last seen timestamp --
|
||||
node_last_seen = Gauge(
|
||||
"meshcore_node_last_seen_timestamp_seconds",
|
||||
"Unix timestamp of when the node was last seen",
|
||||
["public_key", "node_name", "adv_type", "role"],
|
||||
registry=registry,
|
||||
)
|
||||
role_subq = (
|
||||
select(NodeTag.node_id, NodeTag.value.label("role"))
|
||||
.where(NodeTag.key == "role")
|
||||
.subquery()
|
||||
)
|
||||
nodes_with_last_seen = session.execute(
|
||||
select(
|
||||
Node.public_key,
|
||||
Node.name,
|
||||
Node.adv_type,
|
||||
Node.last_seen,
|
||||
role_subq.c.role,
|
||||
)
|
||||
.outerjoin(role_subq, Node.id == role_subq.c.node_id)
|
||||
.where(Node.last_seen.isnot(None))
|
||||
).all()
|
||||
for public_key, name, adv_type, last_seen, role in nodes_with_last_seen:
|
||||
node_last_seen.labels(
|
||||
public_key=public_key,
|
||||
node_name=name or "",
|
||||
adv_type=adv_type or "unknown",
|
||||
role=role or "",
|
||||
).set(last_seen.timestamp())
|
||||
|
||||
# -- Messages total by type --
|
||||
messages_total = Gauge(
|
||||
"meshcore_messages_total",
|
||||
"Total number of messages by type",
|
||||
["type"],
|
||||
registry=registry,
|
||||
)
|
||||
msg_type_counts = session.execute(
|
||||
select(Message.message_type, func.count(Message.id)).group_by(
|
||||
Message.message_type
|
||||
)
|
||||
).all()
|
||||
for msg_type, count in msg_type_counts:
|
||||
messages_total.labels(type=msg_type).set(count)
|
||||
|
||||
# -- Messages received by type and window --
|
||||
messages_received = Gauge(
|
||||
"meshcore_messages_received",
|
||||
"Messages received in time window by type",
|
||||
["type", "window"],
|
||||
registry=registry,
|
||||
)
|
||||
for window, hours in [("1h", 1), ("24h", 24), ("7d", 168), ("30d", 720)]:
|
||||
cutoff = time.time() - (hours * 3600)
|
||||
cutoff_dt = datetime.fromtimestamp(cutoff, tz=timezone.utc)
|
||||
window_counts = session.execute(
|
||||
select(Message.message_type, func.count(Message.id))
|
||||
.where(Message.received_at >= cutoff_dt)
|
||||
.group_by(Message.message_type)
|
||||
).all()
|
||||
for msg_type, count in window_counts:
|
||||
messages_received.labels(type=msg_type, window=window).set(count)
|
||||
|
||||
# -- Advertisements total --
|
||||
advertisements_total = Gauge(
|
||||
"meshcore_advertisements_total",
|
||||
"Total number of advertisements",
|
||||
registry=registry,
|
||||
)
|
||||
count = session.execute(select(func.count(Advertisement.id))).scalar() or 0
|
||||
advertisements_total.set(count)
|
||||
|
||||
# -- Advertisements received by window --
|
||||
advertisements_received = Gauge(
|
||||
"meshcore_advertisements_received",
|
||||
"Advertisements received in time window",
|
||||
["window"],
|
||||
registry=registry,
|
||||
)
|
||||
for window, hours in [("1h", 1), ("24h", 24), ("7d", 168), ("30d", 720)]:
|
||||
cutoff = time.time() - (hours * 3600)
|
||||
cutoff_dt = datetime.fromtimestamp(cutoff, tz=timezone.utc)
|
||||
count = (
|
||||
session.execute(
|
||||
select(func.count(Advertisement.id)).where(
|
||||
Advertisement.received_at >= cutoff_dt
|
||||
)
|
||||
).scalar()
|
||||
or 0
|
||||
)
|
||||
advertisements_received.labels(window=window).set(count)
|
||||
|
||||
# -- Telemetry total --
|
||||
telemetry_total = Gauge(
|
||||
"meshcore_telemetry_total",
|
||||
"Total number of telemetry records",
|
||||
registry=registry,
|
||||
)
|
||||
count = session.execute(select(func.count(Telemetry.id))).scalar() or 0
|
||||
telemetry_total.set(count)
|
||||
|
||||
# -- Trace paths total --
|
||||
trace_paths_total = Gauge(
|
||||
"meshcore_trace_paths_total",
|
||||
"Total number of trace path records",
|
||||
registry=registry,
|
||||
)
|
||||
count = session.execute(select(func.count(TracePath.id))).scalar() or 0
|
||||
trace_paths_total.set(count)
|
||||
|
||||
# -- Events by type --
|
||||
events_total = Gauge(
|
||||
"meshcore_events_total",
|
||||
"Total events by type from event log",
|
||||
["event_type"],
|
||||
registry=registry,
|
||||
)
|
||||
event_counts = session.execute(
|
||||
select(EventLog.event_type, func.count(EventLog.id)).group_by(
|
||||
EventLog.event_type
|
||||
)
|
||||
).all()
|
||||
for event_type, count in event_counts:
|
||||
events_total.labels(event_type=event_type).set(count)
|
||||
|
||||
# -- Members total --
|
||||
members_total = Gauge(
|
||||
"meshcore_members_total",
|
||||
"Total number of network members",
|
||||
registry=registry,
|
||||
)
|
||||
count = session.execute(select(func.count(Member.id))).scalar() or 0
|
||||
members_total.set(count)
|
||||
|
||||
output: bytes = generate_latest(registry)
|
||||
return output
|
||||
|
||||
|
||||
@router.get("/metrics")
|
||||
async def metrics(request: Request) -> Response:
|
||||
"""Prometheus metrics endpoint.
|
||||
|
||||
Returns metrics in Prometheus text exposition format.
|
||||
Supports HTTP Basic Auth with username 'metrics' and API read key as password.
|
||||
Results are cached with a configurable TTL to reduce database load.
|
||||
"""
|
||||
# Check authentication
|
||||
if not verify_basic_auth(request):
|
||||
return PlainTextResponse(
|
||||
"Unauthorized",
|
||||
status_code=401,
|
||||
headers={"WWW-Authenticate": 'Basic realm="metrics"'},
|
||||
)
|
||||
|
||||
# Check cache
|
||||
cache_ttl = getattr(request.app.state, "metrics_cache_ttl", 60)
|
||||
now = time.time()
|
||||
|
||||
if _cache["output"] and now < _cache["expires_at"]:
|
||||
return Response(
|
||||
content=_cache["output"],
|
||||
media_type="text/plain; version=0.0.4; charset=utf-8",
|
||||
)
|
||||
|
||||
# Collect fresh metrics
|
||||
try:
|
||||
from meshcore_hub.api.app import get_db_manager
|
||||
|
||||
db_manager = get_db_manager()
|
||||
with db_manager.session_scope() as session:
|
||||
output = collect_metrics(session)
|
||||
|
||||
# Update cache
|
||||
_cache["output"] = output
|
||||
_cache["expires_at"] = now + cache_ttl
|
||||
|
||||
return Response(
|
||||
content=output,
|
||||
media_type="text/plain; version=0.0.4; charset=utf-8",
|
||||
)
|
||||
except Exception as e:
|
||||
logger.exception("Failed to collect metrics: %s", e)
|
||||
return PlainTextResponse(
|
||||
f"# Error collecting metrics: {e}\n",
|
||||
status_code=500,
|
||||
media_type="text/plain; version=0.0.4; charset=utf-8",
|
||||
)
|
||||
@@ -4,33 +4,168 @@ from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy import func, or_, select
|
||||
from sqlalchemy.orm import aliased, selectinload
|
||||
|
||||
from meshcore_hub.api.auth import RequireRead
|
||||
from meshcore_hub.api.dependencies import DbSession
|
||||
from meshcore_hub.common.models import Advertisement
|
||||
from meshcore_hub.common.schemas.messages import AdvertisementList, AdvertisementRead
|
||||
from meshcore_hub.common.models import Advertisement, EventReceiver, Node, NodeTag
|
||||
from meshcore_hub.common.schemas.messages import (
|
||||
AdvertisementList,
|
||||
AdvertisementRead,
|
||||
ReceiverInfo,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _get_tag_name(node: Optional[Node]) -> Optional[str]:
|
||||
"""Extract name tag from a node's tags."""
|
||||
if not node or not node.tags:
|
||||
return None
|
||||
for tag in node.tags:
|
||||
if tag.key == "name":
|
||||
return tag.value
|
||||
return None
|
||||
|
||||
|
||||
def _get_tag_description(node: Optional[Node]) -> Optional[str]:
|
||||
"""Extract description tag from a node's tags."""
|
||||
if not node or not node.tags:
|
||||
return None
|
||||
for tag in node.tags:
|
||||
if tag.key == "description":
|
||||
return tag.value
|
||||
return None
|
||||
|
||||
|
||||
def _fetch_receivers_for_events(
|
||||
session: DbSession,
|
||||
event_type: str,
|
||||
event_hashes: list[str],
|
||||
) -> dict[str, list[ReceiverInfo]]:
|
||||
"""Fetch receiver info for a list of events by their hashes."""
|
||||
if not event_hashes:
|
||||
return {}
|
||||
|
||||
query = (
|
||||
select(
|
||||
EventReceiver.event_hash,
|
||||
EventReceiver.snr,
|
||||
EventReceiver.received_at,
|
||||
Node.id.label("node_id"),
|
||||
Node.public_key,
|
||||
Node.name,
|
||||
)
|
||||
.join(Node, EventReceiver.receiver_node_id == Node.id)
|
||||
.where(EventReceiver.event_type == event_type)
|
||||
.where(EventReceiver.event_hash.in_(event_hashes))
|
||||
.order_by(EventReceiver.received_at)
|
||||
)
|
||||
|
||||
results = session.execute(query).all()
|
||||
receivers_by_hash: dict[str, list[ReceiverInfo]] = {}
|
||||
|
||||
node_ids = [r.node_id for r in results]
|
||||
tag_names: dict[str, str] = {}
|
||||
if node_ids:
|
||||
tag_query = (
|
||||
select(NodeTag.node_id, NodeTag.value)
|
||||
.where(NodeTag.node_id.in_(node_ids))
|
||||
.where(NodeTag.key == "name")
|
||||
)
|
||||
for node_id, value in session.execute(tag_query).all():
|
||||
tag_names[node_id] = value
|
||||
|
||||
for row in results:
|
||||
if row.event_hash not in receivers_by_hash:
|
||||
receivers_by_hash[row.event_hash] = []
|
||||
|
||||
receivers_by_hash[row.event_hash].append(
|
||||
ReceiverInfo(
|
||||
node_id=row.node_id,
|
||||
public_key=row.public_key,
|
||||
name=row.name,
|
||||
tag_name=tag_names.get(row.node_id),
|
||||
snr=row.snr,
|
||||
received_at=row.received_at,
|
||||
)
|
||||
)
|
||||
|
||||
return receivers_by_hash
|
||||
|
||||
|
||||
@router.get("", response_model=AdvertisementList)
|
||||
async def list_advertisements(
|
||||
_: RequireRead,
|
||||
session: DbSession,
|
||||
search: Optional[str] = Query(
|
||||
None, description="Search in name tag, node name, or public key"
|
||||
),
|
||||
public_key: Optional[str] = Query(None, description="Filter by public key"),
|
||||
received_by: Optional[str] = Query(
|
||||
None, description="Filter by receiver node public key"
|
||||
),
|
||||
member_id: Optional[str] = Query(
|
||||
None, description="Filter by member_id tag value of source node"
|
||||
),
|
||||
since: Optional[datetime] = Query(None, description="Start timestamp"),
|
||||
until: Optional[datetime] = Query(None, description="End timestamp"),
|
||||
limit: int = Query(50, ge=1, le=100, description="Page size"),
|
||||
offset: int = Query(0, ge=0, description="Page offset"),
|
||||
) -> AdvertisementList:
|
||||
"""List advertisements with filtering and pagination."""
|
||||
# Build query
|
||||
query = select(Advertisement)
|
||||
# Aliases for node joins
|
||||
ReceiverNode = aliased(Node)
|
||||
SourceNode = aliased(Node)
|
||||
|
||||
# Build query with both receiver and source node joins
|
||||
query = (
|
||||
select(
|
||||
Advertisement,
|
||||
ReceiverNode.public_key.label("receiver_pk"),
|
||||
ReceiverNode.name.label("receiver_name"),
|
||||
ReceiverNode.id.label("receiver_id"),
|
||||
SourceNode.name.label("source_name"),
|
||||
SourceNode.id.label("source_id"),
|
||||
SourceNode.adv_type.label("source_adv_type"),
|
||||
)
|
||||
.outerjoin(ReceiverNode, Advertisement.receiver_node_id == ReceiverNode.id)
|
||||
.outerjoin(SourceNode, Advertisement.node_id == SourceNode.id)
|
||||
)
|
||||
|
||||
if search:
|
||||
# Search in public key, advertisement name, node name, or name tag
|
||||
search_pattern = f"%{search}%"
|
||||
query = query.where(
|
||||
or_(
|
||||
Advertisement.public_key.ilike(search_pattern),
|
||||
Advertisement.name.ilike(search_pattern),
|
||||
SourceNode.name.ilike(search_pattern),
|
||||
SourceNode.id.in_(
|
||||
select(NodeTag.node_id).where(
|
||||
NodeTag.key == "name", NodeTag.value.ilike(search_pattern)
|
||||
)
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
if public_key:
|
||||
query = query.where(Advertisement.public_key == public_key)
|
||||
|
||||
if received_by:
|
||||
query = query.where(ReceiverNode.public_key == received_by)
|
||||
|
||||
if member_id:
|
||||
# Filter advertisements from nodes that have a member_id tag with the specified value
|
||||
query = query.where(
|
||||
SourceNode.id.in_(
|
||||
select(NodeTag.node_id).where(
|
||||
NodeTag.key == "member_id", NodeTag.value == member_id
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
if since:
|
||||
query = query.where(Advertisement.received_at >= since)
|
||||
|
||||
@@ -45,10 +180,59 @@ async def list_advertisements(
|
||||
query = query.order_by(Advertisement.received_at.desc()).offset(offset).limit(limit)
|
||||
|
||||
# Execute
|
||||
advertisements = session.execute(query).scalars().all()
|
||||
results = session.execute(query).all()
|
||||
|
||||
# Collect node IDs to fetch tags
|
||||
node_ids = set()
|
||||
for row in results:
|
||||
if row.receiver_id:
|
||||
node_ids.add(row.receiver_id)
|
||||
if row.source_id:
|
||||
node_ids.add(row.source_id)
|
||||
|
||||
# Fetch nodes with tags
|
||||
nodes_by_id: dict[str, Node] = {}
|
||||
if node_ids:
|
||||
nodes_query = (
|
||||
select(Node).where(Node.id.in_(node_ids)).options(selectinload(Node.tags))
|
||||
)
|
||||
nodes = session.execute(nodes_query).scalars().all()
|
||||
nodes_by_id = {n.id: n for n in nodes}
|
||||
|
||||
# Fetch all receivers for these advertisements
|
||||
event_hashes = [r[0].event_hash for r in results if r[0].event_hash]
|
||||
receivers_by_hash = _fetch_receivers_for_events(
|
||||
session, "advertisement", event_hashes
|
||||
)
|
||||
|
||||
# Build response with node details
|
||||
items = []
|
||||
for row in results:
|
||||
adv = row[0]
|
||||
receiver_node = nodes_by_id.get(row.receiver_id) if row.receiver_id else None
|
||||
source_node = nodes_by_id.get(row.source_id) if row.source_id else None
|
||||
|
||||
data = {
|
||||
"received_by": row.receiver_pk,
|
||||
"receiver_name": row.receiver_name,
|
||||
"receiver_tag_name": _get_tag_name(receiver_node),
|
||||
"public_key": adv.public_key,
|
||||
"name": adv.name,
|
||||
"node_name": row.source_name,
|
||||
"node_tag_name": _get_tag_name(source_node),
|
||||
"node_tag_description": _get_tag_description(source_node),
|
||||
"adv_type": adv.adv_type or row.source_adv_type,
|
||||
"flags": adv.flags,
|
||||
"received_at": adv.received_at,
|
||||
"created_at": adv.created_at,
|
||||
"receivers": (
|
||||
receivers_by_hash.get(adv.event_hash, []) if adv.event_hash else []
|
||||
),
|
||||
}
|
||||
items.append(AdvertisementRead(**data))
|
||||
|
||||
return AdvertisementList(
|
||||
items=[AdvertisementRead.model_validate(a) for a in advertisements],
|
||||
items=items,
|
||||
total=total,
|
||||
limit=limit,
|
||||
offset=offset,
|
||||
@@ -62,10 +246,68 @@ async def get_advertisement(
|
||||
advertisement_id: str,
|
||||
) -> AdvertisementRead:
|
||||
"""Get a single advertisement by ID."""
|
||||
query = select(Advertisement).where(Advertisement.id == advertisement_id)
|
||||
advertisement = session.execute(query).scalar_one_or_none()
|
||||
ReceiverNode = aliased(Node)
|
||||
SourceNode = aliased(Node)
|
||||
query = (
|
||||
select(
|
||||
Advertisement,
|
||||
ReceiverNode.public_key.label("receiver_pk"),
|
||||
ReceiverNode.name.label("receiver_name"),
|
||||
ReceiverNode.id.label("receiver_id"),
|
||||
SourceNode.name.label("source_name"),
|
||||
SourceNode.id.label("source_id"),
|
||||
SourceNode.adv_type.label("source_adv_type"),
|
||||
)
|
||||
.outerjoin(ReceiverNode, Advertisement.receiver_node_id == ReceiverNode.id)
|
||||
.outerjoin(SourceNode, Advertisement.node_id == SourceNode.id)
|
||||
.where(Advertisement.id == advertisement_id)
|
||||
)
|
||||
result = session.execute(query).one_or_none()
|
||||
|
||||
if not advertisement:
|
||||
if not result:
|
||||
raise HTTPException(status_code=404, detail="Advertisement not found")
|
||||
|
||||
return AdvertisementRead.model_validate(advertisement)
|
||||
adv = result[0]
|
||||
|
||||
# Fetch nodes with tags for friendly names
|
||||
node_ids = []
|
||||
if result.receiver_id:
|
||||
node_ids.append(result.receiver_id)
|
||||
if result.source_id:
|
||||
node_ids.append(result.source_id)
|
||||
|
||||
nodes_by_id: dict[str, Node] = {}
|
||||
if node_ids:
|
||||
nodes_query = (
|
||||
select(Node).where(Node.id.in_(node_ids)).options(selectinload(Node.tags))
|
||||
)
|
||||
nodes = session.execute(nodes_query).scalars().all()
|
||||
nodes_by_id = {n.id: n for n in nodes}
|
||||
|
||||
receiver_node = nodes_by_id.get(result.receiver_id) if result.receiver_id else None
|
||||
source_node = nodes_by_id.get(result.source_id) if result.source_id else None
|
||||
|
||||
# Fetch receivers for this advertisement
|
||||
receivers = []
|
||||
if adv.event_hash:
|
||||
receivers_by_hash = _fetch_receivers_for_events(
|
||||
session, "advertisement", [adv.event_hash]
|
||||
)
|
||||
receivers = receivers_by_hash.get(adv.event_hash, [])
|
||||
|
||||
data = {
|
||||
"received_by": result.receiver_pk,
|
||||
"receiver_name": result.receiver_name,
|
||||
"receiver_tag_name": _get_tag_name(receiver_node),
|
||||
"public_key": adv.public_key,
|
||||
"name": adv.name,
|
||||
"node_name": result.source_name,
|
||||
"node_tag_name": _get_tag_name(source_node),
|
||||
"node_tag_description": _get_tag_description(source_node),
|
||||
"adv_type": adv.adv_type or result.source_adv_type,
|
||||
"flags": adv.flags,
|
||||
"received_at": adv.received_at,
|
||||
"created_at": adv.created_at,
|
||||
"receivers": receivers,
|
||||
}
|
||||
return AdvertisementRead(**data)
|
||||
|
||||
@@ -2,14 +2,21 @@
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import HTMLResponse
|
||||
from fastapi import APIRouter
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from meshcore_hub.api.auth import RequireRead
|
||||
from meshcore_hub.api.dependencies import DbSession
|
||||
from meshcore_hub.common.models import Advertisement, Message, Node, NodeTag
|
||||
from meshcore_hub.common.schemas.messages import DashboardStats, RecentAdvertisement
|
||||
from meshcore_hub.common.schemas.messages import (
|
||||
ChannelMessage,
|
||||
DailyActivity,
|
||||
DailyActivityPoint,
|
||||
DashboardStats,
|
||||
MessageActivity,
|
||||
NodeCountHistory,
|
||||
RecentAdvertisement,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -23,6 +30,7 @@ async def get_stats(
|
||||
now = datetime.now(timezone.utc)
|
||||
today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
yesterday = now - timedelta(days=1)
|
||||
seven_days_ago = now - timedelta(days=7)
|
||||
|
||||
# Total nodes
|
||||
total_nodes = session.execute(select(func.count()).select_from(Node)).scalar() or 0
|
||||
@@ -65,6 +73,26 @@ async def get_stats(
|
||||
or 0
|
||||
)
|
||||
|
||||
# Advertisements in last 7 days
|
||||
advertisements_7d = (
|
||||
session.execute(
|
||||
select(func.count())
|
||||
.select_from(Advertisement)
|
||||
.where(Advertisement.received_at >= seven_days_ago)
|
||||
).scalar()
|
||||
or 0
|
||||
)
|
||||
|
||||
# Messages in last 7 days
|
||||
messages_7d = (
|
||||
session.execute(
|
||||
select(func.count())
|
||||
.select_from(Message)
|
||||
.where(Message.received_at >= seven_days_ago)
|
||||
).scalar()
|
||||
or 0
|
||||
)
|
||||
|
||||
# Recent advertisements (last 10)
|
||||
recent_ads = (
|
||||
session.execute(
|
||||
@@ -74,25 +102,38 @@ async def get_stats(
|
||||
.all()
|
||||
)
|
||||
|
||||
# Get friendly_name tags for the advertised nodes
|
||||
# Get node names, adv_types, and name tags for the advertised nodes
|
||||
ad_public_keys = [ad.public_key for ad in recent_ads]
|
||||
friendly_names: dict[str, str] = {}
|
||||
node_names: dict[str, str] = {}
|
||||
node_adv_types: dict[str, str] = {}
|
||||
tag_names: dict[str, str] = {}
|
||||
if ad_public_keys:
|
||||
friendly_name_query = (
|
||||
# Get node names and adv_types from Node table
|
||||
node_query = select(Node.public_key, Node.name, Node.adv_type).where(
|
||||
Node.public_key.in_(ad_public_keys)
|
||||
)
|
||||
for public_key, name, adv_type in session.execute(node_query).all():
|
||||
if name:
|
||||
node_names[public_key] = name
|
||||
if adv_type:
|
||||
node_adv_types[public_key] = adv_type
|
||||
|
||||
# Get name tags
|
||||
tag_name_query = (
|
||||
select(Node.public_key, NodeTag.value)
|
||||
.join(NodeTag, Node.id == NodeTag.node_id)
|
||||
.where(Node.public_key.in_(ad_public_keys))
|
||||
.where(NodeTag.key == "friendly_name")
|
||||
.where(NodeTag.key == "name")
|
||||
)
|
||||
for public_key, value in session.execute(friendly_name_query).all():
|
||||
friendly_names[public_key] = value
|
||||
for public_key, value in session.execute(tag_name_query).all():
|
||||
tag_names[public_key] = value
|
||||
|
||||
recent_advertisements = [
|
||||
RecentAdvertisement(
|
||||
public_key=ad.public_key,
|
||||
name=ad.name,
|
||||
friendly_name=friendly_names.get(ad.public_key),
|
||||
adv_type=ad.adv_type,
|
||||
name=ad.name or node_names.get(ad.public_key),
|
||||
tag_name=tag_names.get(ad.public_key),
|
||||
adv_type=ad.adv_type or node_adv_types.get(ad.public_key),
|
||||
received_at=ad.received_at,
|
||||
)
|
||||
for ad in recent_ads
|
||||
@@ -110,185 +151,213 @@ async def get_stats(
|
||||
int(channel): int(count) for channel, count in channel_results
|
||||
}
|
||||
|
||||
# Get latest 5 messages for each channel that has messages
|
||||
channel_messages: dict[int, list[ChannelMessage]] = {}
|
||||
for channel_idx, _ in channel_results:
|
||||
messages_query = (
|
||||
select(Message)
|
||||
.where(Message.message_type == "channel")
|
||||
.where(Message.channel_idx == channel_idx)
|
||||
.order_by(Message.received_at.desc())
|
||||
.limit(5)
|
||||
)
|
||||
channel_msgs = session.execute(messages_query).scalars().all()
|
||||
|
||||
# Look up sender names for these messages
|
||||
msg_prefixes = [m.pubkey_prefix for m in channel_msgs if m.pubkey_prefix]
|
||||
msg_sender_names: dict[str, str] = {}
|
||||
msg_tag_names: dict[str, str] = {}
|
||||
if msg_prefixes:
|
||||
for prefix in set(msg_prefixes):
|
||||
sender_node_query = select(Node.public_key, Node.name).where(
|
||||
Node.public_key.startswith(prefix)
|
||||
)
|
||||
for public_key, name in session.execute(sender_node_query).all():
|
||||
if name:
|
||||
msg_sender_names[public_key[:12]] = name
|
||||
|
||||
sender_tag_query = (
|
||||
select(Node.public_key, NodeTag.value)
|
||||
.join(NodeTag, Node.id == NodeTag.node_id)
|
||||
.where(Node.public_key.startswith(prefix))
|
||||
.where(NodeTag.key == "name")
|
||||
)
|
||||
for public_key, value in session.execute(sender_tag_query).all():
|
||||
msg_tag_names[public_key[:12]] = value
|
||||
|
||||
channel_messages[int(channel_idx)] = [
|
||||
ChannelMessage(
|
||||
text=m.text,
|
||||
sender_name=(
|
||||
msg_sender_names.get(m.pubkey_prefix) if m.pubkey_prefix else None
|
||||
),
|
||||
sender_tag_name=(
|
||||
msg_tag_names.get(m.pubkey_prefix) if m.pubkey_prefix else None
|
||||
),
|
||||
pubkey_prefix=m.pubkey_prefix,
|
||||
received_at=m.received_at,
|
||||
)
|
||||
for m in channel_msgs
|
||||
]
|
||||
|
||||
return DashboardStats(
|
||||
total_nodes=total_nodes,
|
||||
active_nodes=active_nodes,
|
||||
total_messages=total_messages,
|
||||
messages_today=messages_today,
|
||||
messages_7d=messages_7d,
|
||||
total_advertisements=total_advertisements,
|
||||
advertisements_24h=advertisements_24h,
|
||||
advertisements_7d=advertisements_7d,
|
||||
recent_advertisements=recent_advertisements,
|
||||
channel_message_counts=channel_message_counts,
|
||||
channel_messages=channel_messages,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/", response_class=HTMLResponse)
|
||||
async def dashboard(
|
||||
request: Request,
|
||||
@router.get("/activity", response_model=DailyActivity)
|
||||
async def get_activity(
|
||||
_: RequireRead,
|
||||
session: DbSession,
|
||||
) -> HTMLResponse:
|
||||
"""Simple HTML dashboard page."""
|
||||
days: int = 30,
|
||||
) -> DailyActivity:
|
||||
"""Get daily advertisement activity for the specified period.
|
||||
|
||||
Args:
|
||||
days: Number of days to include (default 30, max 90)
|
||||
|
||||
Returns:
|
||||
Daily advertisement counts for each day in the period (excluding today)
|
||||
"""
|
||||
# Limit to max 90 days
|
||||
days = min(days, 90)
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
yesterday = now - timedelta(days=1)
|
||||
# End at start of today (exclude today's incomplete data)
|
||||
end_date = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
start_date = end_date - timedelta(days=days)
|
||||
|
||||
# Get stats
|
||||
total_nodes = session.execute(select(func.count()).select_from(Node)).scalar() or 0
|
||||
# Query advertisement counts grouped by date
|
||||
# Use SQLite's date() function for grouping (returns string 'YYYY-MM-DD')
|
||||
date_expr = func.date(Advertisement.received_at)
|
||||
|
||||
active_nodes = (
|
||||
session.execute(
|
||||
select(func.count()).select_from(Node).where(Node.last_seen >= yesterday)
|
||||
).scalar()
|
||||
or 0
|
||||
query = (
|
||||
select(
|
||||
date_expr.label("date"),
|
||||
func.count().label("count"),
|
||||
)
|
||||
.where(Advertisement.received_at >= start_date)
|
||||
.where(Advertisement.received_at < end_date)
|
||||
.group_by(date_expr)
|
||||
.order_by(date_expr)
|
||||
)
|
||||
|
||||
total_messages = (
|
||||
session.execute(select(func.count()).select_from(Message)).scalar() or 0
|
||||
results = session.execute(query).all()
|
||||
|
||||
# Build a dict of date -> count from results (date is already a string)
|
||||
counts_by_date = {row.date: row.count for row in results}
|
||||
|
||||
# Generate all dates in the range, filling in zeros for missing days
|
||||
data = []
|
||||
for i in range(days):
|
||||
date = start_date + timedelta(days=i)
|
||||
date_str = date.strftime("%Y-%m-%d")
|
||||
count = counts_by_date.get(date_str, 0)
|
||||
data.append(DailyActivityPoint(date=date_str, count=count))
|
||||
|
||||
return DailyActivity(days=days, data=data)
|
||||
|
||||
|
||||
@router.get("/message-activity", response_model=MessageActivity)
|
||||
async def get_message_activity(
|
||||
_: RequireRead,
|
||||
session: DbSession,
|
||||
days: int = 30,
|
||||
) -> MessageActivity:
|
||||
"""Get daily message activity for the specified period.
|
||||
|
||||
Args:
|
||||
days: Number of days to include (default 30, max 90)
|
||||
|
||||
Returns:
|
||||
Daily message counts for each day in the period (excluding today)
|
||||
"""
|
||||
days = min(days, 90)
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
# End at start of today (exclude today's incomplete data)
|
||||
end_date = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
start_date = end_date - timedelta(days=days)
|
||||
|
||||
# Query message counts grouped by date
|
||||
date_expr = func.date(Message.received_at)
|
||||
|
||||
query = (
|
||||
select(
|
||||
date_expr.label("date"),
|
||||
func.count().label("count"),
|
||||
)
|
||||
.where(Message.received_at >= start_date)
|
||||
.where(Message.received_at < end_date)
|
||||
.group_by(date_expr)
|
||||
.order_by(date_expr)
|
||||
)
|
||||
|
||||
messages_today = (
|
||||
session.execute(
|
||||
select(func.count())
|
||||
.select_from(Message)
|
||||
.where(Message.received_at >= today_start)
|
||||
).scalar()
|
||||
or 0
|
||||
)
|
||||
results = session.execute(query).all()
|
||||
counts_by_date = {row.date: row.count for row in results}
|
||||
|
||||
# Get recent nodes
|
||||
recent_nodes = (
|
||||
session.execute(select(Node).order_by(Node.last_seen.desc()).limit(10))
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
# Generate all dates in the range, filling in zeros for missing days
|
||||
data = []
|
||||
for i in range(days):
|
||||
date = start_date + timedelta(days=i)
|
||||
date_str = date.strftime("%Y-%m-%d")
|
||||
count = counts_by_date.get(date_str, 0)
|
||||
data.append(DailyActivityPoint(date=date_str, count=count))
|
||||
|
||||
# Get recent messages
|
||||
recent_messages = (
|
||||
session.execute(select(Message).order_by(Message.received_at.desc()).limit(10))
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
return MessageActivity(days=days, data=data)
|
||||
|
||||
# Build HTML
|
||||
html = f"""
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>MeshCore Hub Dashboard</title>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta http-equiv="refresh" content="30">
|
||||
<style>
|
||||
body {{
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
margin: 0;
|
||||
padding: 20px;
|
||||
background: #f5f5f5;
|
||||
color: #333;
|
||||
}}
|
||||
h1 {{ color: #2c3e50; }}
|
||||
.container {{ max-width: 1200px; margin: 0 auto; }}
|
||||
.stats {{
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 20px;
|
||||
margin-bottom: 30px;
|
||||
}}
|
||||
.stat-card {{
|
||||
background: white;
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||
}}
|
||||
.stat-card h3 {{ margin: 0 0 10px 0; color: #666; font-size: 14px; }}
|
||||
.stat-card .value {{ font-size: 32px; font-weight: bold; color: #2c3e50; }}
|
||||
.section {{
|
||||
background: white;
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||
margin-bottom: 20px;
|
||||
}}
|
||||
table {{ width: 100%; border-collapse: collapse; }}
|
||||
th, td {{ padding: 10px; text-align: left; border-bottom: 1px solid #eee; }}
|
||||
th {{ background: #f8f9fa; font-weight: 600; }}
|
||||
.text-muted {{ color: #666; }}
|
||||
.truncate {{ max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h1>MeshCore Hub Dashboard</h1>
|
||||
<p class="text-muted">Last updated: {now.strftime('%Y-%m-%d %H:%M:%S UTC')}</p>
|
||||
|
||||
<div class="stats">
|
||||
<div class="stat-card">
|
||||
<h3>Total Nodes</h3>
|
||||
<div class="value">{total_nodes}</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<h3>Active Nodes (24h)</h3>
|
||||
<div class="value">{active_nodes}</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<h3>Total Messages</h3>
|
||||
<div class="value">{total_messages}</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<h3>Messages Today</h3>
|
||||
<div class="value">{messages_today}</div>
|
||||
</div>
|
||||
</div>
|
||||
@router.get("/node-count", response_model=NodeCountHistory)
|
||||
async def get_node_count_history(
|
||||
_: RequireRead,
|
||||
session: DbSession,
|
||||
days: int = 30,
|
||||
) -> NodeCountHistory:
|
||||
"""Get cumulative node count over time.
|
||||
|
||||
<div class="section">
|
||||
<h2>Recent Nodes</h2>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>Public Key</th>
|
||||
<th>Type</th>
|
||||
<th>Last Seen</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{"".join(f'''
|
||||
<tr>
|
||||
<td>{n.name or '-'}</td>
|
||||
<td class="truncate">{n.public_key[:16]}...</td>
|
||||
<td>{n.adv_type or '-'}</td>
|
||||
<td>{n.last_seen.strftime('%Y-%m-%d %H:%M') if n.last_seen else '-'}</td>
|
||||
</tr>
|
||||
''' for n in recent_nodes)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
For each day, shows the total number of nodes that existed by that date
|
||||
(based on their created_at timestamp).
|
||||
|
||||
<div class="section">
|
||||
<h2>Recent Messages</h2>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Type</th>
|
||||
<th>From/Channel</th>
|
||||
<th>Text</th>
|
||||
<th>Received</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{"".join(f'''
|
||||
<tr>
|
||||
<td>{m.message_type}</td>
|
||||
<td>{m.pubkey_prefix or f'Ch {m.channel_idx}' or '-'}</td>
|
||||
<td class="truncate">{m.text[:50]}{'...' if len(m.text) > 50 else ''}</td>
|
||||
<td>{m.received_at.strftime('%Y-%m-%d %H:%M') if m.received_at else '-'}</td>
|
||||
</tr>
|
||||
''' for m in recent_messages)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
return HTMLResponse(content=html)
|
||||
Args:
|
||||
days: Number of days to include (default 30, max 90)
|
||||
|
||||
Returns:
|
||||
Cumulative node count for each day in the period (excluding today)
|
||||
"""
|
||||
days = min(days, 90)
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
# End at start of today (exclude today's incomplete data)
|
||||
end_date = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
start_date = end_date - timedelta(days=days)
|
||||
|
||||
# Get all nodes with their creation dates
|
||||
# Count nodes created on or before each date
|
||||
data = []
|
||||
for i in range(days):
|
||||
date = start_date + timedelta(days=i)
|
||||
end_of_day = date.replace(hour=23, minute=59, second=59, microsecond=999999)
|
||||
date_str = date.strftime("%Y-%m-%d")
|
||||
|
||||
# Count nodes created on or before this date
|
||||
count = (
|
||||
session.execute(
|
||||
select(func.count())
|
||||
.select_from(Node)
|
||||
.where(Node.created_at <= end_of_day)
|
||||
).scalar()
|
||||
or 0
|
||||
)
|
||||
data.append(DailyActivityPoint(date=date_str, count=count))
|
||||
|
||||
return NodeCountHistory(days=days, data=data)
|
||||
|
||||
@@ -20,7 +20,7 @@ router = APIRouter()
|
||||
async def list_members(
|
||||
_: RequireRead,
|
||||
session: DbSession,
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
limit: int = Query(default=50, ge=1, le=500),
|
||||
offset: int = Query(default=0, ge=0),
|
||||
) -> MemberList:
|
||||
"""List all members with pagination."""
|
||||
@@ -28,9 +28,9 @@ async def list_members(
|
||||
count_query = select(func.count()).select_from(Member)
|
||||
total = session.execute(count_query).scalar() or 0
|
||||
|
||||
# Get members
|
||||
# Get members ordered by name
|
||||
query = select(Member).order_by(Member.name).limit(limit).offset(offset)
|
||||
members = session.execute(query).scalars().all()
|
||||
members = list(session.execute(query).scalars().all())
|
||||
|
||||
return MemberList(
|
||||
items=[MemberRead.model_validate(m) for m in members],
|
||||
@@ -63,17 +63,23 @@ async def create_member(
|
||||
member: MemberCreate,
|
||||
) -> MemberRead:
|
||||
"""Create a new member."""
|
||||
# Normalize public_key to lowercase if provided
|
||||
public_key = member.public_key.lower() if member.public_key else None
|
||||
# Check if member_id already exists
|
||||
query = select(Member).where(Member.member_id == member.member_id)
|
||||
existing = session.execute(query).scalar_one_or_none()
|
||||
if existing:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Member with member_id '{member.member_id}' already exists",
|
||||
)
|
||||
|
||||
# Create member
|
||||
new_member = Member(
|
||||
member_id=member.member_id,
|
||||
name=member.name,
|
||||
callsign=member.callsign,
|
||||
role=member.role,
|
||||
description=member.description,
|
||||
contact=member.contact,
|
||||
public_key=public_key,
|
||||
)
|
||||
session.add(new_member)
|
||||
session.commit()
|
||||
@@ -97,6 +103,18 @@ async def update_member(
|
||||
raise HTTPException(status_code=404, detail="Member not found")
|
||||
|
||||
# Update fields
|
||||
if member.member_id is not None:
|
||||
# Check if new member_id is already taken by another member
|
||||
check_query = select(Member).where(
|
||||
Member.member_id == member.member_id, Member.id != member_id
|
||||
)
|
||||
collision = session.execute(check_query).scalar_one_or_none()
|
||||
if collision:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Member with member_id '{member.member_id}' already exists",
|
||||
)
|
||||
existing.member_id = member.member_id
|
||||
if member.name is not None:
|
||||
existing.name = member.name
|
||||
if member.callsign is not None:
|
||||
@@ -107,8 +125,6 @@ async def update_member(
|
||||
existing.description = member.description
|
||||
if member.contact is not None:
|
||||
existing.contact = member.contact
|
||||
if member.public_key is not None:
|
||||
existing.public_key = member.public_key.lower()
|
||||
|
||||
session.commit()
|
||||
session.refresh(existing)
|
||||
|
||||
@@ -5,15 +5,95 @@ from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import aliased, selectinload
|
||||
|
||||
from meshcore_hub.api.auth import RequireRead
|
||||
from meshcore_hub.api.dependencies import DbSession
|
||||
from meshcore_hub.common.models import Message, Node, NodeTag
|
||||
from meshcore_hub.common.schemas.messages import MessageList, MessageRead
|
||||
from meshcore_hub.common.models import EventReceiver, Message, Node, NodeTag
|
||||
from meshcore_hub.common.schemas.messages import MessageList, MessageRead, ReceiverInfo
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _get_tag_name(node: Optional[Node]) -> Optional[str]:
|
||||
"""Extract name tag from a node's tags."""
|
||||
if not node or not node.tags:
|
||||
return None
|
||||
for tag in node.tags:
|
||||
if tag.key == "name":
|
||||
return tag.value
|
||||
return None
|
||||
|
||||
|
||||
def _fetch_receivers_for_events(
|
||||
session: DbSession,
|
||||
event_type: str,
|
||||
event_hashes: list[str],
|
||||
) -> dict[str, list[ReceiverInfo]]:
|
||||
"""Fetch receiver info for a list of events by their hashes.
|
||||
|
||||
Args:
|
||||
session: Database session
|
||||
event_type: Type of event ('message', 'advertisement', etc.)
|
||||
event_hashes: List of event hashes to fetch receivers for
|
||||
|
||||
Returns:
|
||||
Dict mapping event_hash to list of ReceiverInfo objects
|
||||
"""
|
||||
if not event_hashes:
|
||||
return {}
|
||||
|
||||
# Query event_receivers with receiver node info
|
||||
query = (
|
||||
select(
|
||||
EventReceiver.event_hash,
|
||||
EventReceiver.snr,
|
||||
EventReceiver.received_at,
|
||||
Node.id.label("node_id"),
|
||||
Node.public_key,
|
||||
Node.name,
|
||||
)
|
||||
.join(Node, EventReceiver.receiver_node_id == Node.id)
|
||||
.where(EventReceiver.event_type == event_type)
|
||||
.where(EventReceiver.event_hash.in_(event_hashes))
|
||||
.order_by(EventReceiver.received_at)
|
||||
)
|
||||
|
||||
results = session.execute(query).all()
|
||||
|
||||
# Group by event_hash
|
||||
receivers_by_hash: dict[str, list[ReceiverInfo]] = {}
|
||||
|
||||
# Get tag names for receiver nodes
|
||||
node_ids = [r.node_id for r in results]
|
||||
tag_names: dict[str, str] = {}
|
||||
if node_ids:
|
||||
tag_query = (
|
||||
select(NodeTag.node_id, NodeTag.value)
|
||||
.where(NodeTag.node_id.in_(node_ids))
|
||||
.where(NodeTag.key == "name")
|
||||
)
|
||||
for node_id, value in session.execute(tag_query).all():
|
||||
tag_names[node_id] = value
|
||||
|
||||
for row in results:
|
||||
if row.event_hash not in receivers_by_hash:
|
||||
receivers_by_hash[row.event_hash] = []
|
||||
|
||||
receivers_by_hash[row.event_hash].append(
|
||||
ReceiverInfo(
|
||||
node_id=row.node_id,
|
||||
public_key=row.public_key,
|
||||
name=row.name,
|
||||
tag_name=tag_names.get(row.node_id),
|
||||
snr=row.snr,
|
||||
received_at=row.received_at,
|
||||
)
|
||||
)
|
||||
|
||||
return receivers_by_hash
|
||||
|
||||
|
||||
@router.get("", response_model=MessageList)
|
||||
async def list_messages(
|
||||
_: RequireRead,
|
||||
@@ -21,6 +101,9 @@ async def list_messages(
|
||||
message_type: Optional[str] = Query(None, description="Filter by message type"),
|
||||
pubkey_prefix: Optional[str] = Query(None, description="Filter by sender prefix"),
|
||||
channel_idx: Optional[int] = Query(None, description="Filter by channel"),
|
||||
received_by: Optional[str] = Query(
|
||||
None, description="Filter by receiver node public key"
|
||||
),
|
||||
since: Optional[datetime] = Query(None, description="Start timestamp"),
|
||||
until: Optional[datetime] = Query(None, description="End timestamp"),
|
||||
search: Optional[str] = Query(None, description="Search in message text"),
|
||||
@@ -28,8 +111,16 @@ async def list_messages(
|
||||
offset: int = Query(0, ge=0, description="Page offset"),
|
||||
) -> MessageList:
|
||||
"""List messages with filtering and pagination."""
|
||||
# Build query
|
||||
query = select(Message)
|
||||
# Alias for receiver node join
|
||||
ReceiverNode = aliased(Node)
|
||||
|
||||
# Build query with receiver node join
|
||||
query = select(
|
||||
Message,
|
||||
ReceiverNode.public_key.label("receiver_pk"),
|
||||
ReceiverNode.name.label("receiver_name"),
|
||||
ReceiverNode.id.label("receiver_id"),
|
||||
).outerjoin(ReceiverNode, Message.receiver_node_id == ReceiverNode.id)
|
||||
|
||||
if message_type:
|
||||
query = query.where(Message.message_type == message_type)
|
||||
@@ -40,6 +131,9 @@ async def list_messages(
|
||||
if channel_idx is not None:
|
||||
query = query.where(Message.channel_idx == channel_idx)
|
||||
|
||||
if received_by:
|
||||
query = query.where(ReceiverNode.public_key == received_by)
|
||||
|
||||
if since:
|
||||
query = query.where(Message.received_at >= since)
|
||||
|
||||
@@ -57,34 +151,77 @@ async def list_messages(
|
||||
query = query.order_by(Message.received_at.desc()).offset(offset).limit(limit)
|
||||
|
||||
# Execute
|
||||
messages = session.execute(query).scalars().all()
|
||||
results = session.execute(query).all()
|
||||
|
||||
# Look up friendly_names for senders with pubkey_prefix
|
||||
pubkey_prefixes = [m.pubkey_prefix for m in messages if m.pubkey_prefix]
|
||||
friendly_names: dict[str, str] = {}
|
||||
# Look up sender names and tag names for senders with pubkey_prefix
|
||||
pubkey_prefixes = [r[0].pubkey_prefix for r in results if r[0].pubkey_prefix]
|
||||
sender_names: dict[str, str] = {}
|
||||
sender_tag_names: dict[str, str] = {}
|
||||
if pubkey_prefixes:
|
||||
# Find nodes whose public_key starts with any of these prefixes
|
||||
for prefix in set(pubkey_prefixes):
|
||||
friendly_name_query = (
|
||||
# Get node name
|
||||
node_query = select(Node.public_key, Node.name).where(
|
||||
Node.public_key.startswith(prefix)
|
||||
)
|
||||
for public_key, name in session.execute(node_query).all():
|
||||
if name:
|
||||
sender_names[public_key[:12]] = name
|
||||
|
||||
# Get name tag
|
||||
tag_name_query = (
|
||||
select(Node.public_key, NodeTag.value)
|
||||
.join(NodeTag, Node.id == NodeTag.node_id)
|
||||
.where(Node.public_key.startswith(prefix))
|
||||
.where(NodeTag.key == "friendly_name")
|
||||
.where(NodeTag.key == "name")
|
||||
)
|
||||
for public_key, value in session.execute(friendly_name_query).all():
|
||||
# Map the prefix to the friendly_name
|
||||
friendly_names[public_key[:12]] = value
|
||||
for public_key, value in session.execute(tag_name_query).all():
|
||||
sender_tag_names[public_key[:12]] = value
|
||||
|
||||
# Build response with friendly_names
|
||||
# Collect receiver node IDs to fetch tags
|
||||
receiver_ids = set()
|
||||
for row in results:
|
||||
if row.receiver_id:
|
||||
receiver_ids.add(row.receiver_id)
|
||||
|
||||
# Fetch receiver nodes with tags
|
||||
receivers_by_id: dict[str, Node] = {}
|
||||
if receiver_ids:
|
||||
receivers_query = (
|
||||
select(Node)
|
||||
.where(Node.id.in_(receiver_ids))
|
||||
.options(selectinload(Node.tags))
|
||||
)
|
||||
receivers = session.execute(receivers_query).scalars().all()
|
||||
receivers_by_id = {n.id: n for n in receivers}
|
||||
|
||||
# Fetch all receivers for these messages
|
||||
event_hashes = [r[0].event_hash for r in results if r[0].event_hash]
|
||||
receivers_by_hash = _fetch_receivers_for_events(session, "message", event_hashes)
|
||||
|
||||
# Build response with sender info and received_by
|
||||
items = []
|
||||
for m in messages:
|
||||
for row in results:
|
||||
m = row[0]
|
||||
receiver_pk = row.receiver_pk
|
||||
receiver_name = row.receiver_name
|
||||
receiver_node = (
|
||||
receivers_by_id.get(row.receiver_id) if row.receiver_id else None
|
||||
)
|
||||
|
||||
msg_dict = {
|
||||
"id": m.id,
|
||||
"receiver_node_id": m.receiver_node_id,
|
||||
"received_by": receiver_pk,
|
||||
"receiver_name": receiver_name,
|
||||
"receiver_tag_name": _get_tag_name(receiver_node),
|
||||
"message_type": m.message_type,
|
||||
"pubkey_prefix": m.pubkey_prefix,
|
||||
"sender_friendly_name": (
|
||||
friendly_names.get(m.pubkey_prefix) if m.pubkey_prefix else None
|
||||
"sender_name": (
|
||||
sender_names.get(m.pubkey_prefix) if m.pubkey_prefix else None
|
||||
),
|
||||
"sender_tag_name": (
|
||||
sender_tag_names.get(m.pubkey_prefix) if m.pubkey_prefix else None
|
||||
),
|
||||
"channel_idx": m.channel_idx,
|
||||
"text": m.text,
|
||||
@@ -95,6 +232,9 @@ async def list_messages(
|
||||
"sender_timestamp": m.sender_timestamp,
|
||||
"received_at": m.received_at,
|
||||
"created_at": m.created_at,
|
||||
"receivers": (
|
||||
receivers_by_hash.get(m.event_hash, []) if m.event_hash else []
|
||||
),
|
||||
}
|
||||
items.append(MessageRead(**msg_dict))
|
||||
|
||||
@@ -113,10 +253,42 @@ async def get_message(
|
||||
message_id: str,
|
||||
) -> MessageRead:
|
||||
"""Get a single message by ID."""
|
||||
query = select(Message).where(Message.id == message_id)
|
||||
message = session.execute(query).scalar_one_or_none()
|
||||
ReceiverNode = aliased(Node)
|
||||
query = (
|
||||
select(Message, ReceiverNode.public_key.label("receiver_pk"))
|
||||
.outerjoin(ReceiverNode, Message.receiver_node_id == ReceiverNode.id)
|
||||
.where(Message.id == message_id)
|
||||
)
|
||||
result = session.execute(query).one_or_none()
|
||||
|
||||
if not message:
|
||||
if not result:
|
||||
raise HTTPException(status_code=404, detail="Message not found")
|
||||
|
||||
return MessageRead.model_validate(message)
|
||||
message, receiver_pk = result
|
||||
|
||||
# Fetch receivers for this message
|
||||
receivers = []
|
||||
if message.event_hash:
|
||||
receivers_by_hash = _fetch_receivers_for_events(
|
||||
session, "message", [message.event_hash]
|
||||
)
|
||||
receivers = receivers_by_hash.get(message.event_hash, [])
|
||||
|
||||
data = {
|
||||
"id": message.id,
|
||||
"receiver_node_id": message.receiver_node_id,
|
||||
"received_by": receiver_pk,
|
||||
"message_type": message.message_type,
|
||||
"pubkey_prefix": message.pubkey_prefix,
|
||||
"channel_idx": message.channel_idx,
|
||||
"text": message.text,
|
||||
"path_len": message.path_len,
|
||||
"txt_type": message.txt_type,
|
||||
"signature": message.signature,
|
||||
"snr": message.snr,
|
||||
"sender_timestamp": message.sender_timestamp,
|
||||
"received_at": message.received_at,
|
||||
"created_at": message.created_at,
|
||||
"receivers": receivers,
|
||||
}
|
||||
return MessageRead(**data)
|
||||
|
||||
@@ -6,7 +6,13 @@ from sqlalchemy import select
|
||||
from meshcore_hub.api.auth import RequireAdmin, RequireRead
|
||||
from meshcore_hub.api.dependencies import DbSession
|
||||
from meshcore_hub.common.models import Node, NodeTag
|
||||
from meshcore_hub.common.schemas.nodes import NodeTagCreate, NodeTagRead, NodeTagUpdate
|
||||
from meshcore_hub.common.schemas.nodes import (
|
||||
NodeTagCreate,
|
||||
NodeTagMove,
|
||||
NodeTagRead,
|
||||
NodeTagsCopyResult,
|
||||
NodeTagUpdate,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -130,6 +136,131 @@ async def update_node_tag(
|
||||
return NodeTagRead.model_validate(node_tag)
|
||||
|
||||
|
||||
@router.put("/nodes/{public_key}/tags/{key}/move", response_model=NodeTagRead)
|
||||
async def move_node_tag(
|
||||
_: RequireAdmin,
|
||||
session: DbSession,
|
||||
public_key: str,
|
||||
key: str,
|
||||
data: NodeTagMove,
|
||||
) -> NodeTagRead:
|
||||
"""Move a node tag to a different node."""
|
||||
# Check if source and destination are the same
|
||||
if public_key == data.new_public_key:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Source and destination nodes are the same",
|
||||
)
|
||||
|
||||
# Find source node
|
||||
source_query = select(Node).where(Node.public_key == public_key)
|
||||
source_node = session.execute(source_query).scalar_one_or_none()
|
||||
|
||||
if not source_node:
|
||||
raise HTTPException(status_code=404, detail="Source node not found")
|
||||
|
||||
# Find tag
|
||||
tag_query = select(NodeTag).where(
|
||||
(NodeTag.node_id == source_node.id) & (NodeTag.key == key)
|
||||
)
|
||||
node_tag = session.execute(tag_query).scalar_one_or_none()
|
||||
|
||||
if not node_tag:
|
||||
raise HTTPException(status_code=404, detail="Tag not found")
|
||||
|
||||
# Find destination node
|
||||
dest_query = select(Node).where(Node.public_key == data.new_public_key)
|
||||
dest_node = session.execute(dest_query).scalar_one_or_none()
|
||||
|
||||
if not dest_node:
|
||||
raise HTTPException(status_code=404, detail="Destination node not found")
|
||||
|
||||
# Check if tag already exists on destination node
|
||||
conflict_query = select(NodeTag).where(
|
||||
(NodeTag.node_id == dest_node.id) & (NodeTag.key == key)
|
||||
)
|
||||
conflict = session.execute(conflict_query).scalar_one_or_none()
|
||||
|
||||
if conflict:
|
||||
raise HTTPException(
|
||||
status_code=409,
|
||||
detail=f"Tag '{key}' already exists on destination node",
|
||||
)
|
||||
|
||||
# Move tag to destination node
|
||||
node_tag.node_id = dest_node.id
|
||||
session.commit()
|
||||
session.refresh(node_tag)
|
||||
|
||||
return NodeTagRead.model_validate(node_tag)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/nodes/{public_key}/tags/copy-to/{dest_public_key}",
|
||||
response_model=NodeTagsCopyResult,
|
||||
)
|
||||
async def copy_all_tags(
|
||||
_: RequireAdmin,
|
||||
session: DbSession,
|
||||
public_key: str,
|
||||
dest_public_key: str,
|
||||
) -> NodeTagsCopyResult:
|
||||
"""Copy all tags from one node to another.
|
||||
|
||||
Tags that already exist on the destination node are skipped.
|
||||
"""
|
||||
# Check if source and destination are the same
|
||||
if public_key == dest_public_key:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Source and destination nodes are the same",
|
||||
)
|
||||
|
||||
# Find source node
|
||||
source_query = select(Node).where(Node.public_key == public_key)
|
||||
source_node = session.execute(source_query).scalar_one_or_none()
|
||||
|
||||
if not source_node:
|
||||
raise HTTPException(status_code=404, detail="Source node not found")
|
||||
|
||||
# Find destination node
|
||||
dest_query = select(Node).where(Node.public_key == dest_public_key)
|
||||
dest_node = session.execute(dest_query).scalar_one_or_none()
|
||||
|
||||
if not dest_node:
|
||||
raise HTTPException(status_code=404, detail="Destination node not found")
|
||||
|
||||
# Get existing tags on destination node
|
||||
existing_query = select(NodeTag.key).where(NodeTag.node_id == dest_node.id)
|
||||
existing_keys = set(session.execute(existing_query).scalars().all())
|
||||
|
||||
# Copy tags
|
||||
copied = 0
|
||||
skipped_keys = []
|
||||
|
||||
for tag in source_node.tags:
|
||||
if tag.key in existing_keys:
|
||||
skipped_keys.append(tag.key)
|
||||
continue
|
||||
|
||||
new_tag = NodeTag(
|
||||
node_id=dest_node.id,
|
||||
key=tag.key,
|
||||
value=tag.value,
|
||||
value_type=tag.value_type,
|
||||
)
|
||||
session.add(new_tag)
|
||||
copied += 1
|
||||
|
||||
session.commit()
|
||||
|
||||
return NodeTagsCopyResult(
|
||||
copied=copied,
|
||||
skipped=len(skipped_keys),
|
||||
skipped_keys=skipped_keys,
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/nodes/{public_key}/tags/{key}", status_code=204)
|
||||
async def delete_node_tag(
|
||||
_: RequireAdmin,
|
||||
@@ -156,3 +287,27 @@ async def delete_node_tag(
|
||||
|
||||
session.delete(node_tag)
|
||||
session.commit()
|
||||
|
||||
|
||||
@router.delete("/nodes/{public_key}/tags")
|
||||
async def delete_all_node_tags(
|
||||
_: RequireAdmin,
|
||||
session: DbSession,
|
||||
public_key: str,
|
||||
) -> dict:
|
||||
"""Delete all tags for a node."""
|
||||
# Find node
|
||||
node_query = select(Node).where(Node.public_key == public_key)
|
||||
node = session.execute(node_query).scalar_one_or_none()
|
||||
|
||||
if not node:
|
||||
raise HTTPException(status_code=404, detail="Node not found")
|
||||
|
||||
# Count and delete all tags
|
||||
count = len(node.tags)
|
||||
for tag in node.tags:
|
||||
session.delete(tag)
|
||||
|
||||
session.commit()
|
||||
|
||||
return {"deleted": count}
|
||||
|
||||
@@ -2,12 +2,13 @@
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
from sqlalchemy import func, select
|
||||
from fastapi import APIRouter, HTTPException, Path, Query
|
||||
from sqlalchemy import func, or_, select
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
from meshcore_hub.api.auth import RequireRead
|
||||
from meshcore_hub.api.dependencies import DbSession
|
||||
from meshcore_hub.common.models import Node
|
||||
from meshcore_hub.common.models import Node, NodeTag
|
||||
from meshcore_hub.common.schemas.nodes import NodeList, NodeRead
|
||||
|
||||
router = APIRouter()
|
||||
@@ -17,28 +18,95 @@ router = APIRouter()
|
||||
async def list_nodes(
|
||||
_: RequireRead,
|
||||
session: DbSession,
|
||||
search: Optional[str] = Query(None, description="Search in name or public key"),
|
||||
search: Optional[str] = Query(
|
||||
None, description="Search in name tag, node name, or public key"
|
||||
),
|
||||
adv_type: Optional[str] = Query(None, description="Filter by advertisement type"),
|
||||
limit: int = Query(50, ge=1, le=100, description="Page size"),
|
||||
member_id: Optional[str] = Query(None, description="Filter by member_id tag value"),
|
||||
role: Optional[str] = Query(None, description="Filter by role tag value"),
|
||||
limit: int = Query(50, ge=1, le=500, description="Page size"),
|
||||
offset: int = Query(0, ge=0, description="Page offset"),
|
||||
) -> NodeList:
|
||||
"""List all nodes with pagination and filtering."""
|
||||
# Build query
|
||||
query = select(Node)
|
||||
# Build base query with tags loaded
|
||||
query = select(Node).options(selectinload(Node.tags))
|
||||
|
||||
if search:
|
||||
# Search in public key, node name, or name tag
|
||||
# For name tag search, we need to join with NodeTag
|
||||
search_pattern = f"%{search}%"
|
||||
query = query.where(
|
||||
(Node.name.ilike(f"%{search}%")) | (Node.public_key.ilike(f"%{search}%"))
|
||||
or_(
|
||||
Node.public_key.ilike(search_pattern),
|
||||
Node.name.ilike(search_pattern),
|
||||
Node.id.in_(
|
||||
select(NodeTag.node_id).where(
|
||||
NodeTag.key == "name", NodeTag.value.ilike(search_pattern)
|
||||
)
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
if adv_type:
|
||||
query = query.where(Node.adv_type == adv_type)
|
||||
normalized_adv_type = adv_type.strip().lower()
|
||||
if normalized_adv_type == "repeater":
|
||||
query = query.where(
|
||||
or_(
|
||||
Node.adv_type == "repeater",
|
||||
Node.adv_type.ilike("%repeater%"),
|
||||
Node.adv_type.ilike("%relay%"),
|
||||
)
|
||||
)
|
||||
elif normalized_adv_type == "companion":
|
||||
query = query.where(
|
||||
or_(
|
||||
Node.adv_type == "companion",
|
||||
Node.adv_type.ilike("%companion%"),
|
||||
Node.adv_type.ilike("%observer%"),
|
||||
)
|
||||
)
|
||||
elif normalized_adv_type == "room":
|
||||
query = query.where(
|
||||
or_(
|
||||
Node.adv_type == "room",
|
||||
Node.adv_type.ilike("%room%"),
|
||||
)
|
||||
)
|
||||
elif normalized_adv_type == "chat":
|
||||
query = query.where(
|
||||
or_(
|
||||
Node.adv_type == "chat",
|
||||
Node.adv_type.ilike("%chat%"),
|
||||
)
|
||||
)
|
||||
else:
|
||||
query = query.where(Node.adv_type == adv_type)
|
||||
|
||||
if member_id:
|
||||
# Filter nodes that have a member_id tag with the specified value
|
||||
query = query.where(
|
||||
Node.id.in_(
|
||||
select(NodeTag.node_id).where(
|
||||
NodeTag.key == "member_id", NodeTag.value == member_id
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
if role:
|
||||
# Filter nodes that have a role tag with the specified value
|
||||
query = query.where(
|
||||
Node.id.in_(
|
||||
select(NodeTag.node_id).where(
|
||||
NodeTag.key == "role", NodeTag.value == role
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
# Get total count
|
||||
count_query = select(func.count()).select_from(query.subquery())
|
||||
total = session.execute(count_query).scalar() or 0
|
||||
|
||||
# Apply pagination
|
||||
# Apply pagination and ordering
|
||||
query = query.order_by(Node.last_seen.desc()).offset(offset).limit(limit)
|
||||
|
||||
# Execute
|
||||
@@ -52,14 +120,43 @@ async def list_nodes(
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{public_key}", response_model=NodeRead)
|
||||
async def get_node(
|
||||
@router.get("/prefix/{prefix}", response_model=NodeRead)
|
||||
async def get_node_by_prefix(
|
||||
_: RequireRead,
|
||||
session: DbSession,
|
||||
public_key: str,
|
||||
prefix: str = Path(description="Public key prefix to search for"),
|
||||
) -> NodeRead:
|
||||
"""Get a single node by public key."""
|
||||
query = select(Node).where(Node.public_key == public_key)
|
||||
"""Get a single node by public key prefix.
|
||||
|
||||
Returns the first node (alphabetically by public_key) that matches the prefix.
|
||||
"""
|
||||
query = (
|
||||
select(Node)
|
||||
.options(selectinload(Node.tags))
|
||||
.where(Node.public_key.startswith(prefix))
|
||||
.order_by(Node.public_key)
|
||||
.limit(1)
|
||||
)
|
||||
node = session.execute(query).scalar_one_or_none()
|
||||
|
||||
if not node:
|
||||
raise HTTPException(status_code=404, detail="Node not found")
|
||||
|
||||
return NodeRead.model_validate(node)
|
||||
|
||||
|
||||
@router.get("/{public_key}", response_model=NodeRead)
|
||||
async def get_node(
|
||||
_: RequireRead,
|
||||
session: DbSession,
|
||||
public_key: str = Path(description="Full 64-character public key"),
|
||||
) -> NodeRead:
|
||||
"""Get a single node by exact public key match."""
|
||||
query = (
|
||||
select(Node)
|
||||
.options(selectinload(Node.tags))
|
||||
.where(Node.public_key == public_key)
|
||||
)
|
||||
node = session.execute(query).scalar_one_or_none()
|
||||
|
||||
if not node:
|
||||
|
||||
@@ -5,10 +5,11 @@ from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import aliased
|
||||
|
||||
from meshcore_hub.api.auth import RequireRead
|
||||
from meshcore_hub.api.dependencies import DbSession
|
||||
from meshcore_hub.common.models import Telemetry
|
||||
from meshcore_hub.common.models import Node, Telemetry
|
||||
from meshcore_hub.common.schemas.messages import TelemetryList, TelemetryRead
|
||||
|
||||
router = APIRouter()
|
||||
@@ -19,18 +20,29 @@ async def list_telemetry(
|
||||
_: RequireRead,
|
||||
session: DbSession,
|
||||
node_public_key: Optional[str] = Query(None, description="Filter by node"),
|
||||
received_by: Optional[str] = Query(
|
||||
None, description="Filter by receiver node public key"
|
||||
),
|
||||
since: Optional[datetime] = Query(None, description="Start timestamp"),
|
||||
until: Optional[datetime] = Query(None, description="End timestamp"),
|
||||
limit: int = Query(50, ge=1, le=100, description="Page size"),
|
||||
offset: int = Query(0, ge=0, description="Page offset"),
|
||||
) -> TelemetryList:
|
||||
"""List telemetry records with filtering and pagination."""
|
||||
# Build query
|
||||
query = select(Telemetry)
|
||||
# Alias for receiver node join
|
||||
ReceiverNode = aliased(Node)
|
||||
|
||||
# Build query with receiver node join
|
||||
query = select(Telemetry, ReceiverNode.public_key.label("receiver_pk")).outerjoin(
|
||||
ReceiverNode, Telemetry.receiver_node_id == ReceiverNode.id
|
||||
)
|
||||
|
||||
if node_public_key:
|
||||
query = query.where(Telemetry.node_public_key == node_public_key)
|
||||
|
||||
if received_by:
|
||||
query = query.where(ReceiverNode.public_key == received_by)
|
||||
|
||||
if since:
|
||||
query = query.where(Telemetry.received_at >= since)
|
||||
|
||||
@@ -45,10 +57,25 @@ async def list_telemetry(
|
||||
query = query.order_by(Telemetry.received_at.desc()).offset(offset).limit(limit)
|
||||
|
||||
# Execute
|
||||
records = session.execute(query).scalars().all()
|
||||
results = session.execute(query).all()
|
||||
|
||||
# Build response with received_by
|
||||
items = []
|
||||
for tel, receiver_pk in results:
|
||||
data = {
|
||||
"id": tel.id,
|
||||
"receiver_node_id": tel.receiver_node_id,
|
||||
"received_by": receiver_pk,
|
||||
"node_id": tel.node_id,
|
||||
"node_public_key": tel.node_public_key,
|
||||
"parsed_data": tel.parsed_data,
|
||||
"received_at": tel.received_at,
|
||||
"created_at": tel.created_at,
|
||||
}
|
||||
items.append(TelemetryRead(**data))
|
||||
|
||||
return TelemetryList(
|
||||
items=[TelemetryRead.model_validate(t) for t in records],
|
||||
items=items,
|
||||
total=total,
|
||||
limit=limit,
|
||||
offset=offset,
|
||||
@@ -62,10 +89,26 @@ async def get_telemetry(
|
||||
telemetry_id: str,
|
||||
) -> TelemetryRead:
|
||||
"""Get a single telemetry record by ID."""
|
||||
query = select(Telemetry).where(Telemetry.id == telemetry_id)
|
||||
telemetry = session.execute(query).scalar_one_or_none()
|
||||
ReceiverNode = aliased(Node)
|
||||
query = (
|
||||
select(Telemetry, ReceiverNode.public_key.label("receiver_pk"))
|
||||
.outerjoin(ReceiverNode, Telemetry.receiver_node_id == ReceiverNode.id)
|
||||
.where(Telemetry.id == telemetry_id)
|
||||
)
|
||||
result = session.execute(query).one_or_none()
|
||||
|
||||
if not telemetry:
|
||||
if not result:
|
||||
raise HTTPException(status_code=404, detail="Telemetry record not found")
|
||||
|
||||
return TelemetryRead.model_validate(telemetry)
|
||||
tel, receiver_pk = result
|
||||
data = {
|
||||
"id": tel.id,
|
||||
"receiver_node_id": tel.receiver_node_id,
|
||||
"received_by": receiver_pk,
|
||||
"node_id": tel.node_id,
|
||||
"node_public_key": tel.node_public_key,
|
||||
"parsed_data": tel.parsed_data,
|
||||
"received_at": tel.received_at,
|
||||
"created_at": tel.created_at,
|
||||
}
|
||||
return TelemetryRead(**data)
|
||||
|
||||
@@ -5,10 +5,11 @@ from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import aliased
|
||||
|
||||
from meshcore_hub.api.auth import RequireRead
|
||||
from meshcore_hub.api.dependencies import DbSession
|
||||
from meshcore_hub.common.models import TracePath
|
||||
from meshcore_hub.common.models import Node, TracePath
|
||||
from meshcore_hub.common.schemas.messages import TracePathList, TracePathRead
|
||||
|
||||
router = APIRouter()
|
||||
@@ -18,14 +19,25 @@ router = APIRouter()
|
||||
async def list_trace_paths(
|
||||
_: RequireRead,
|
||||
session: DbSession,
|
||||
received_by: Optional[str] = Query(
|
||||
None, description="Filter by receiver node public key"
|
||||
),
|
||||
since: Optional[datetime] = Query(None, description="Start timestamp"),
|
||||
until: Optional[datetime] = Query(None, description="End timestamp"),
|
||||
limit: int = Query(50, ge=1, le=100, description="Page size"),
|
||||
offset: int = Query(0, ge=0, description="Page offset"),
|
||||
) -> TracePathList:
|
||||
"""List trace paths with filtering and pagination."""
|
||||
# Build query
|
||||
query = select(TracePath)
|
||||
# Alias for receiver node join
|
||||
ReceiverNode = aliased(Node)
|
||||
|
||||
# Build query with receiver node join
|
||||
query = select(TracePath, ReceiverNode.public_key.label("receiver_pk")).outerjoin(
|
||||
ReceiverNode, TracePath.receiver_node_id == ReceiverNode.id
|
||||
)
|
||||
|
||||
if received_by:
|
||||
query = query.where(ReceiverNode.public_key == received_by)
|
||||
|
||||
if since:
|
||||
query = query.where(TracePath.received_at >= since)
|
||||
@@ -41,10 +53,29 @@ async def list_trace_paths(
|
||||
query = query.order_by(TracePath.received_at.desc()).offset(offset).limit(limit)
|
||||
|
||||
# Execute
|
||||
trace_paths = session.execute(query).scalars().all()
|
||||
results = session.execute(query).all()
|
||||
|
||||
# Build response with received_by
|
||||
items = []
|
||||
for tp, receiver_pk in results:
|
||||
data = {
|
||||
"id": tp.id,
|
||||
"receiver_node_id": tp.receiver_node_id,
|
||||
"received_by": receiver_pk,
|
||||
"initiator_tag": tp.initiator_tag,
|
||||
"path_len": tp.path_len,
|
||||
"flags": tp.flags,
|
||||
"auth": tp.auth,
|
||||
"path_hashes": tp.path_hashes,
|
||||
"snr_values": tp.snr_values,
|
||||
"hop_count": tp.hop_count,
|
||||
"received_at": tp.received_at,
|
||||
"created_at": tp.created_at,
|
||||
}
|
||||
items.append(TracePathRead(**data))
|
||||
|
||||
return TracePathList(
|
||||
items=[TracePathRead.model_validate(t) for t in trace_paths],
|
||||
items=items,
|
||||
total=total,
|
||||
limit=limit,
|
||||
offset=offset,
|
||||
@@ -58,10 +89,30 @@ async def get_trace_path(
|
||||
trace_path_id: str,
|
||||
) -> TracePathRead:
|
||||
"""Get a single trace path by ID."""
|
||||
query = select(TracePath).where(TracePath.id == trace_path_id)
|
||||
trace_path = session.execute(query).scalar_one_or_none()
|
||||
ReceiverNode = aliased(Node)
|
||||
query = (
|
||||
select(TracePath, ReceiverNode.public_key.label("receiver_pk"))
|
||||
.outerjoin(ReceiverNode, TracePath.receiver_node_id == ReceiverNode.id)
|
||||
.where(TracePath.id == trace_path_id)
|
||||
)
|
||||
result = session.execute(query).one_or_none()
|
||||
|
||||
if not trace_path:
|
||||
if not result:
|
||||
raise HTTPException(status_code=404, detail="Trace path not found")
|
||||
|
||||
return TracePathRead.model_validate(trace_path)
|
||||
tp, receiver_pk = result
|
||||
data = {
|
||||
"id": tp.id,
|
||||
"receiver_node_id": tp.receiver_node_id,
|
||||
"received_by": receiver_pk,
|
||||
"initiator_tag": tp.initiator_tag,
|
||||
"path_len": tp.path_len,
|
||||
"flags": tp.flags,
|
||||
"auth": tp.auth,
|
||||
"path_hashes": tp.path_hashes,
|
||||
"snr_values": tp.snr_values,
|
||||
"hop_count": tp.hop_count,
|
||||
"received_at": tp.received_at,
|
||||
"created_at": tp.created_at,
|
||||
}
|
||||
return TracePathRead(**data)
|
||||
|
||||
225
src/meshcore_hub/collector/cleanup.py
Normal file
225
src/meshcore_hub/collector/cleanup.py
Normal file
@@ -0,0 +1,225 @@
|
||||
"""Data retention and cleanup service for MeshCore Hub.
|
||||
|
||||
This module provides functionality to delete old event data and inactive nodes
|
||||
based on configured retention policies.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import delete, func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from meshcore_hub.common.models import (
|
||||
Advertisement,
|
||||
EventLog,
|
||||
Message,
|
||||
Node,
|
||||
Telemetry,
|
||||
TracePath,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class CleanupStats:
|
||||
"""Statistics from a cleanup operation."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.advertisements_deleted: int = 0
|
||||
self.messages_deleted: int = 0
|
||||
self.telemetry_deleted: int = 0
|
||||
self.trace_paths_deleted: int = 0
|
||||
self.event_logs_deleted: int = 0
|
||||
self.nodes_deleted: int = 0
|
||||
self.total_deleted: int = 0
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return (
|
||||
f"CleanupStats(total={self.total_deleted}, "
|
||||
f"advertisements={self.advertisements_deleted}, "
|
||||
f"messages={self.messages_deleted}, "
|
||||
f"telemetry={self.telemetry_deleted}, "
|
||||
f"trace_paths={self.trace_paths_deleted}, "
|
||||
f"event_logs={self.event_logs_deleted}, "
|
||||
f"nodes={self.nodes_deleted})"
|
||||
)
|
||||
|
||||
|
||||
async def cleanup_old_data(
|
||||
db: AsyncSession,
|
||||
retention_days: int,
|
||||
dry_run: bool = False,
|
||||
) -> CleanupStats:
|
||||
"""Delete event data older than the retention period.
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
retention_days: Number of days to retain data
|
||||
dry_run: If True, only count records without deleting
|
||||
|
||||
Returns:
|
||||
CleanupStats object with deletion counts
|
||||
"""
|
||||
stats = CleanupStats()
|
||||
cutoff_date = datetime.now(timezone.utc) - timedelta(days=retention_days)
|
||||
|
||||
logger.info(
|
||||
"Starting data cleanup (dry_run=%s, retention_days=%d, cutoff=%s)",
|
||||
dry_run,
|
||||
retention_days,
|
||||
cutoff_date.isoformat(),
|
||||
)
|
||||
|
||||
# Clean up advertisements
|
||||
stats.advertisements_deleted = await _cleanup_table(
|
||||
db, Advertisement, cutoff_date, "advertisements", dry_run
|
||||
)
|
||||
|
||||
# Clean up messages
|
||||
stats.messages_deleted = await _cleanup_table(
|
||||
db, Message, cutoff_date, "messages", dry_run
|
||||
)
|
||||
|
||||
# Clean up telemetry
|
||||
stats.telemetry_deleted = await _cleanup_table(
|
||||
db, Telemetry, cutoff_date, "telemetry", dry_run
|
||||
)
|
||||
|
||||
# Clean up trace paths
|
||||
stats.trace_paths_deleted = await _cleanup_table(
|
||||
db, TracePath, cutoff_date, "trace_paths", dry_run
|
||||
)
|
||||
|
||||
# Clean up event logs
|
||||
stats.event_logs_deleted = await _cleanup_table(
|
||||
db, EventLog, cutoff_date, "event_logs", dry_run
|
||||
)
|
||||
|
||||
stats.total_deleted = (
|
||||
stats.advertisements_deleted
|
||||
+ stats.messages_deleted
|
||||
+ stats.telemetry_deleted
|
||||
+ stats.trace_paths_deleted
|
||||
+ stats.event_logs_deleted
|
||||
)
|
||||
|
||||
if not dry_run:
|
||||
await db.commit()
|
||||
logger.info("Cleanup completed: %s", stats)
|
||||
else:
|
||||
logger.info("Cleanup dry run completed: %s", stats)
|
||||
|
||||
return stats
|
||||
|
||||
|
||||
async def _cleanup_table(
|
||||
db: AsyncSession,
|
||||
model: type,
|
||||
cutoff_date: datetime,
|
||||
table_name: str,
|
||||
dry_run: bool,
|
||||
) -> int:
|
||||
"""Delete old records from a specific table.
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
model: SQLAlchemy model class
|
||||
cutoff_date: Delete records older than this date
|
||||
table_name: Name of table for logging
|
||||
dry_run: If True, only count without deleting
|
||||
|
||||
Returns:
|
||||
Number of records deleted (or would be deleted in dry_run)
|
||||
"""
|
||||
from sqlalchemy import select
|
||||
|
||||
if dry_run:
|
||||
# Count records that would be deleted
|
||||
stmt = (
|
||||
select(func.count())
|
||||
.select_from(model)
|
||||
.where(model.created_at < cutoff_date) # type: ignore[attr-defined]
|
||||
)
|
||||
result = await db.execute(stmt)
|
||||
count = result.scalar() or 0
|
||||
logger.debug(
|
||||
"[DRY RUN] Would delete %d records from %s older than %s",
|
||||
count,
|
||||
table_name,
|
||||
cutoff_date.isoformat(),
|
||||
)
|
||||
return count
|
||||
else:
|
||||
# Delete old records
|
||||
result = await db.execute(delete(model).where(model.created_at < cutoff_date)) # type: ignore[attr-defined]
|
||||
count = result.rowcount or 0 # type: ignore[attr-defined]
|
||||
logger.debug(
|
||||
"Deleted %d records from %s older than %s",
|
||||
count,
|
||||
table_name,
|
||||
cutoff_date.isoformat(),
|
||||
)
|
||||
return count
|
||||
|
||||
|
||||
async def cleanup_inactive_nodes(
|
||||
db: AsyncSession,
|
||||
inactivity_days: int,
|
||||
dry_run: bool = False,
|
||||
) -> int:
|
||||
"""Delete nodes that haven't been seen for the specified number of days.
|
||||
|
||||
Only deletes nodes where last_seen is older than the cutoff date.
|
||||
Nodes with last_seen=NULL are NOT deleted (never seen on network).
|
||||
|
||||
Args:
|
||||
db: Database session
|
||||
inactivity_days: Delete nodes not seen for this many days
|
||||
dry_run: If True, only count without deleting
|
||||
|
||||
Returns:
|
||||
Number of nodes deleted (or would be deleted in dry_run)
|
||||
"""
|
||||
cutoff_date = datetime.now(timezone.utc) - timedelta(days=inactivity_days)
|
||||
|
||||
logger.info(
|
||||
"Starting node cleanup (dry_run=%s, inactivity_days=%d, cutoff=%s)",
|
||||
dry_run,
|
||||
inactivity_days,
|
||||
cutoff_date.isoformat(),
|
||||
)
|
||||
|
||||
if dry_run:
|
||||
# Count nodes that would be deleted
|
||||
# Only count nodes with last_seen < cutoff (excludes NULL last_seen)
|
||||
stmt = (
|
||||
select(func.count())
|
||||
.select_from(Node)
|
||||
.where(Node.last_seen < cutoff_date)
|
||||
.where(Node.last_seen.isnot(None))
|
||||
)
|
||||
result = await db.execute(stmt)
|
||||
count = result.scalar() or 0
|
||||
logger.info(
|
||||
"[DRY RUN] Would delete %d nodes not seen since %s",
|
||||
count,
|
||||
cutoff_date.isoformat(),
|
||||
)
|
||||
return count
|
||||
else:
|
||||
# Delete inactive nodes
|
||||
# Only delete nodes with last_seen < cutoff (excludes NULL last_seen)
|
||||
result = await db.execute(
|
||||
delete(Node)
|
||||
.where(Node.last_seen < cutoff_date)
|
||||
.where(Node.last_seen.isnot(None))
|
||||
)
|
||||
await db.commit()
|
||||
count = result.rowcount or 0 # type: ignore[attr-defined]
|
||||
logger.info(
|
||||
"Deleted %d nodes not seen since %s",
|
||||
count,
|
||||
cutoff_date.isoformat(),
|
||||
)
|
||||
return count
|
||||
@@ -1,9 +1,14 @@
|
||||
"""CLI for the Collector component."""
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import click
|
||||
|
||||
from meshcore_hub.common.logging import configure_logging
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from meshcore_hub.common.database import DatabaseManager
|
||||
|
||||
|
||||
@click.group(invoke_without_command=True)
|
||||
@click.pass_context
|
||||
@@ -42,6 +47,38 @@ from meshcore_hub.common.logging import configure_logging
|
||||
envvar="MQTT_PREFIX",
|
||||
help="MQTT topic prefix",
|
||||
)
|
||||
@click.option(
|
||||
"--mqtt-tls",
|
||||
is_flag=True,
|
||||
default=False,
|
||||
envvar="MQTT_TLS",
|
||||
help="Enable TLS/SSL for MQTT connection",
|
||||
)
|
||||
@click.option(
|
||||
"--mqtt-transport",
|
||||
type=click.Choice(["tcp", "websockets"], case_sensitive=False),
|
||||
default="tcp",
|
||||
envvar="MQTT_TRANSPORT",
|
||||
help="MQTT transport protocol",
|
||||
)
|
||||
@click.option(
|
||||
"--mqtt-ws-path",
|
||||
type=str,
|
||||
default="/mqtt",
|
||||
envvar="MQTT_WS_PATH",
|
||||
help="MQTT WebSocket path (used when transport=websockets)",
|
||||
)
|
||||
@click.option(
|
||||
"--ingest-mode",
|
||||
"collector_ingest_mode",
|
||||
type=click.Choice(["native", "letsmesh_upload"], case_sensitive=False),
|
||||
default="native",
|
||||
envvar="COLLECTOR_INGEST_MODE",
|
||||
help=(
|
||||
"Collector ingest mode: native MeshCore events or LetsMesh upload "
|
||||
"(packets/status/internal)"
|
||||
),
|
||||
)
|
||||
@click.option(
|
||||
"--data-home",
|
||||
type=str,
|
||||
@@ -77,6 +114,10 @@ def collector(
|
||||
mqtt_username: str | None,
|
||||
mqtt_password: str | None,
|
||||
prefix: str,
|
||||
mqtt_tls: bool,
|
||||
mqtt_transport: str,
|
||||
mqtt_ws_path: str,
|
||||
collector_ingest_mode: str,
|
||||
data_home: str | None,
|
||||
seed_home: str | None,
|
||||
database_url: str | None,
|
||||
@@ -120,6 +161,10 @@ def collector(
|
||||
ctx.obj["mqtt_username"] = mqtt_username
|
||||
ctx.obj["mqtt_password"] = mqtt_password
|
||||
ctx.obj["prefix"] = prefix
|
||||
ctx.obj["mqtt_tls"] = mqtt_tls
|
||||
ctx.obj["mqtt_transport"] = mqtt_transport
|
||||
ctx.obj["mqtt_ws_path"] = mqtt_ws_path
|
||||
ctx.obj["collector_ingest_mode"] = collector_ingest_mode
|
||||
ctx.obj["data_home"] = data_home or settings.data_home
|
||||
ctx.obj["seed_home"] = settings.effective_seed_home
|
||||
ctx.obj["database_url"] = effective_db_url
|
||||
@@ -134,9 +179,14 @@ def collector(
|
||||
mqtt_username=mqtt_username,
|
||||
mqtt_password=mqtt_password,
|
||||
prefix=prefix,
|
||||
mqtt_tls=mqtt_tls,
|
||||
mqtt_transport=mqtt_transport,
|
||||
mqtt_ws_path=mqtt_ws_path,
|
||||
ingest_mode=collector_ingest_mode,
|
||||
database_url=effective_db_url,
|
||||
log_level=log_level,
|
||||
data_home=data_home or settings.data_home,
|
||||
seed_home=settings.effective_seed_home,
|
||||
)
|
||||
|
||||
|
||||
@@ -146,12 +196,20 @@ def _run_collector_service(
|
||||
mqtt_username: str | None,
|
||||
mqtt_password: str | None,
|
||||
prefix: str,
|
||||
mqtt_tls: bool,
|
||||
mqtt_transport: str,
|
||||
mqtt_ws_path: str,
|
||||
ingest_mode: str,
|
||||
database_url: str,
|
||||
log_level: str,
|
||||
data_home: str,
|
||||
seed_home: str,
|
||||
) -> None:
|
||||
"""Run the collector service.
|
||||
|
||||
Note: Seed data import should be done using the 'meshcore-hub collector seed'
|
||||
command or the dedicated seed container before starting the collector service.
|
||||
|
||||
Webhooks can be configured via environment variables:
|
||||
- WEBHOOK_ADVERTISEMENT_URL: Webhook for advertisement events
|
||||
- WEBHOOK_MESSAGE_URL: Webhook for all message events
|
||||
@@ -168,20 +226,25 @@ def _run_collector_service(
|
||||
|
||||
click.echo("Starting MeshCore Collector")
|
||||
click.echo(f"Data home: {data_home}")
|
||||
click.echo(f"Seed home: {seed_home}")
|
||||
click.echo(f"MQTT: {mqtt_host}:{mqtt_port} (prefix: {prefix})")
|
||||
click.echo(f"MQTT transport: {mqtt_transport} (ws_path: {mqtt_ws_path})")
|
||||
click.echo(f"Ingest mode: {ingest_mode}")
|
||||
click.echo(f"Database: {database_url}")
|
||||
|
||||
# Load webhook configuration from settings
|
||||
from meshcore_hub.common.config import get_collector_settings
|
||||
from meshcore_hub.collector.webhook import (
|
||||
WebhookDispatcher,
|
||||
create_webhooks_from_settings,
|
||||
)
|
||||
from meshcore_hub.collector.letsmesh_decoder import LetsMeshPacketDecoder
|
||||
from meshcore_hub.common.config import get_collector_settings
|
||||
|
||||
settings = get_collector_settings()
|
||||
webhooks = create_webhooks_from_settings(settings)
|
||||
webhook_dispatcher = WebhookDispatcher(webhooks) if webhooks else None
|
||||
|
||||
click.echo("")
|
||||
if webhook_dispatcher and webhook_dispatcher.webhooks:
|
||||
click.echo(f"Webhooks configured: {len(webhooks)}")
|
||||
for wh in webhooks:
|
||||
@@ -191,14 +254,69 @@ def _run_collector_service(
|
||||
|
||||
from meshcore_hub.collector.subscriber import run_collector
|
||||
|
||||
# Show cleanup configuration
|
||||
click.echo("")
|
||||
click.echo("Cleanup configuration:")
|
||||
if settings.data_retention_enabled:
|
||||
click.echo(
|
||||
f" Event data: Enabled (retention: {settings.data_retention_days} days)"
|
||||
)
|
||||
else:
|
||||
click.echo(" Event data: Disabled")
|
||||
|
||||
if settings.node_cleanup_enabled:
|
||||
click.echo(
|
||||
f" Inactive nodes: Enabled (inactivity: {settings.node_cleanup_days} days)"
|
||||
)
|
||||
else:
|
||||
click.echo(" Inactive nodes: Disabled")
|
||||
|
||||
if settings.data_retention_enabled or settings.node_cleanup_enabled:
|
||||
click.echo(f" Interval: {settings.data_retention_interval_hours} hours")
|
||||
|
||||
if ingest_mode.lower() == "letsmesh_upload":
|
||||
click.echo("")
|
||||
click.echo("LetsMesh decode configuration:")
|
||||
if settings.collector_letsmesh_decoder_enabled:
|
||||
builtin_keys = len(LetsMeshPacketDecoder.BUILTIN_CHANNEL_KEYS)
|
||||
env_keys = len(settings.collector_letsmesh_decoder_keys_list)
|
||||
click.echo(
|
||||
" Decoder: Enabled " f"({settings.collector_letsmesh_decoder_command})"
|
||||
)
|
||||
click.echo(f" Built-in keys: {builtin_keys}")
|
||||
click.echo(" Additional keys from .env: " f"{env_keys} configured")
|
||||
click.echo(
|
||||
" Timeout: "
|
||||
f"{settings.collector_letsmesh_decoder_timeout_seconds:.2f}s"
|
||||
)
|
||||
else:
|
||||
click.echo(" Decoder: Disabled")
|
||||
|
||||
click.echo("")
|
||||
click.echo("Starting MQTT subscriber...")
|
||||
run_collector(
|
||||
mqtt_host=mqtt_host,
|
||||
mqtt_port=mqtt_port,
|
||||
mqtt_username=mqtt_username,
|
||||
mqtt_password=mqtt_password,
|
||||
mqtt_prefix=prefix,
|
||||
mqtt_tls=mqtt_tls,
|
||||
mqtt_transport=mqtt_transport,
|
||||
mqtt_ws_path=mqtt_ws_path,
|
||||
ingest_mode=ingest_mode,
|
||||
database_url=database_url,
|
||||
webhook_dispatcher=webhook_dispatcher,
|
||||
cleanup_enabled=settings.data_retention_enabled,
|
||||
cleanup_retention_days=settings.data_retention_days,
|
||||
cleanup_interval_hours=settings.data_retention_interval_hours,
|
||||
node_cleanup_enabled=settings.node_cleanup_enabled,
|
||||
node_cleanup_days=settings.node_cleanup_days,
|
||||
letsmesh_decoder_enabled=settings.collector_letsmesh_decoder_enabled,
|
||||
letsmesh_decoder_command=settings.collector_letsmesh_decoder_command,
|
||||
letsmesh_decoder_channel_keys=settings.collector_letsmesh_decoder_keys_list,
|
||||
letsmesh_decoder_timeout_seconds=(
|
||||
settings.collector_letsmesh_decoder_timeout_seconds
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -215,9 +333,14 @@ def run_cmd(ctx: click.Context) -> None:
|
||||
mqtt_username=ctx.obj["mqtt_username"],
|
||||
mqtt_password=ctx.obj["mqtt_password"],
|
||||
prefix=ctx.obj["prefix"],
|
||||
mqtt_tls=ctx.obj["mqtt_tls"],
|
||||
mqtt_transport=ctx.obj["mqtt_transport"],
|
||||
mqtt_ws_path=ctx.obj["mqtt_ws_path"],
|
||||
ingest_mode=ctx.obj["collector_ingest_mode"],
|
||||
database_url=ctx.obj["database_url"],
|
||||
log_level=ctx.obj["log_level"],
|
||||
data_home=ctx.obj["data_home"],
|
||||
seed_home=ctx.obj["seed_home"],
|
||||
)
|
||||
|
||||
|
||||
@@ -236,17 +359,15 @@ def seed_cmd(
|
||||
"""Import seed data from SEED_HOME directory.
|
||||
|
||||
Looks for the following files in SEED_HOME:
|
||||
- node_tags.json: Node tag definitions (keyed by public_key)
|
||||
- members.json: Network member definitions
|
||||
- node_tags.yaml: Node tag definitions (keyed by public_key)
|
||||
- members.yaml: Network member definitions
|
||||
|
||||
Files that don't exist are skipped. This command is idempotent -
|
||||
existing records are updated, new records are created.
|
||||
|
||||
SEED_HOME defaults to {DATA_HOME}/collector but can be overridden
|
||||
SEED_HOME defaults to ./seed but can be overridden
|
||||
with the --seed-home option or SEED_HOME environment variable.
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
configure_logging(level=ctx.obj["log_level"])
|
||||
|
||||
seed_home = ctx.obj["seed_home"]
|
||||
@@ -254,50 +375,17 @@ def seed_cmd(
|
||||
click.echo(f"Database: {ctx.obj['database_url']}")
|
||||
|
||||
from meshcore_hub.common.database import DatabaseManager
|
||||
from meshcore_hub.collector.tag_import import import_tags
|
||||
from meshcore_hub.collector.member_import import import_members
|
||||
|
||||
# Initialize database
|
||||
# Initialize database (schema managed by Alembic migrations)
|
||||
db = DatabaseManager(ctx.obj["database_url"])
|
||||
db.create_tables()
|
||||
|
||||
# Track what was imported
|
||||
imported_any = False
|
||||
|
||||
# Import node tags if file exists
|
||||
node_tags_file = Path(seed_home) / "node_tags.json"
|
||||
if node_tags_file.exists():
|
||||
click.echo(f"\nImporting node tags from: {node_tags_file}")
|
||||
stats = import_tags(
|
||||
file_path=str(node_tags_file),
|
||||
db=db,
|
||||
create_nodes=not no_create_nodes,
|
||||
)
|
||||
click.echo(f" Tags: {stats['created']} created, {stats['updated']} updated")
|
||||
if stats["nodes_created"]:
|
||||
click.echo(f" Nodes created: {stats['nodes_created']}")
|
||||
if stats["errors"]:
|
||||
for error in stats["errors"]:
|
||||
click.echo(f" Error: {error}", err=True)
|
||||
imported_any = True
|
||||
else:
|
||||
click.echo(f"\nNo node_tags.json found in {seed_home}")
|
||||
|
||||
# Import members if file exists
|
||||
members_file = Path(seed_home) / "members.json"
|
||||
if members_file.exists():
|
||||
click.echo(f"\nImporting members from: {members_file}")
|
||||
stats = import_members(
|
||||
file_path=str(members_file),
|
||||
db=db,
|
||||
)
|
||||
click.echo(f" Members: {stats['created']} created, {stats['updated']} updated")
|
||||
if stats["errors"]:
|
||||
for error in stats["errors"]:
|
||||
click.echo(f" Error: {error}", err=True)
|
||||
imported_any = True
|
||||
else:
|
||||
click.echo(f"\nNo members.json found in {seed_home}")
|
||||
# Run seed import
|
||||
imported_any = _run_seed_import(
|
||||
seed_home=seed_home,
|
||||
db=db,
|
||||
create_nodes=not no_create_nodes,
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
if not imported_any:
|
||||
click.echo("\nNo seed files found. Nothing to import.")
|
||||
@@ -307,6 +395,79 @@ def seed_cmd(
|
||||
db.dispose()
|
||||
|
||||
|
||||
def _run_seed_import(
|
||||
seed_home: str,
|
||||
db: "DatabaseManager",
|
||||
create_nodes: bool = True,
|
||||
verbose: bool = False,
|
||||
) -> bool:
|
||||
"""Run seed import from SEED_HOME directory.
|
||||
|
||||
Args:
|
||||
seed_home: Path to seed home directory
|
||||
db: Database manager instance
|
||||
create_nodes: If True, create nodes that don't exist
|
||||
verbose: If True, output progress messages
|
||||
|
||||
Returns:
|
||||
True if any files were imported, False otherwise
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
from meshcore_hub.collector.member_import import import_members
|
||||
from meshcore_hub.collector.tag_import import import_tags
|
||||
|
||||
imported_any = False
|
||||
|
||||
# Import node tags if file exists
|
||||
node_tags_file = Path(seed_home) / "node_tags.yaml"
|
||||
if node_tags_file.exists():
|
||||
if verbose:
|
||||
click.echo(f"\nImporting node tags from: {node_tags_file}")
|
||||
stats = import_tags(
|
||||
file_path=str(node_tags_file),
|
||||
db=db,
|
||||
create_nodes=create_nodes,
|
||||
clear_existing=True,
|
||||
)
|
||||
if verbose:
|
||||
if stats["deleted"]:
|
||||
click.echo(f" Deleted {stats['deleted']} existing tags")
|
||||
click.echo(
|
||||
f" Tags: {stats['created']} created, {stats['updated']} updated"
|
||||
)
|
||||
if stats["nodes_created"]:
|
||||
click.echo(f" Nodes created: {stats['nodes_created']}")
|
||||
if stats["errors"]:
|
||||
for error in stats["errors"]:
|
||||
click.echo(f" Error: {error}", err=True)
|
||||
imported_any = True
|
||||
elif verbose:
|
||||
click.echo(f"\nNo node_tags.yaml found in {seed_home}")
|
||||
|
||||
# Import members if file exists
|
||||
members_file = Path(seed_home) / "members.yaml"
|
||||
if members_file.exists():
|
||||
if verbose:
|
||||
click.echo(f"\nImporting members from: {members_file}")
|
||||
stats = import_members(
|
||||
file_path=str(members_file),
|
||||
db=db,
|
||||
)
|
||||
if verbose:
|
||||
click.echo(
|
||||
f" Members: {stats['created']} created, {stats['updated']} updated"
|
||||
)
|
||||
if stats["errors"]:
|
||||
for error in stats["errors"]:
|
||||
click.echo(f" Error: {error}", err=True)
|
||||
imported_any = True
|
||||
elif verbose:
|
||||
click.echo(f"\nNo members.yaml found in {seed_home}")
|
||||
|
||||
return imported_any
|
||||
|
||||
|
||||
@collector.command("import-tags")
|
||||
@click.argument("file", type=click.Path(), required=False, default=None)
|
||||
@click.option(
|
||||
@@ -315,40 +476,48 @@ def seed_cmd(
|
||||
default=False,
|
||||
help="Skip tags for nodes that don't exist (default: create nodes)",
|
||||
)
|
||||
@click.option(
|
||||
"--clear-existing",
|
||||
is_flag=True,
|
||||
default=False,
|
||||
help="Delete all existing tags before importing",
|
||||
)
|
||||
@click.pass_context
|
||||
def import_tags_cmd(
|
||||
ctx: click.Context,
|
||||
file: str | None,
|
||||
no_create_nodes: bool,
|
||||
clear_existing: bool,
|
||||
) -> None:
|
||||
"""Import node tags from a JSON file.
|
||||
"""Import node tags from a YAML file.
|
||||
|
||||
Reads a JSON file containing tag definitions and upserts them
|
||||
into the database. Existing tags are updated, new tags are created.
|
||||
Reads a YAML file containing tag definitions and upserts them
|
||||
into the database. By default, existing tags are updated and new tags are created.
|
||||
Use --clear-existing to delete all tags before importing.
|
||||
|
||||
FILE is the path to the JSON file containing tags.
|
||||
If not provided, defaults to {SEED_HOME}/node_tags.json.
|
||||
FILE is the path to the YAML file containing tags.
|
||||
If not provided, defaults to {SEED_HOME}/node_tags.yaml.
|
||||
|
||||
Expected YAML format (keyed by public_key):
|
||||
|
||||
Expected JSON format (keyed by public_key):
|
||||
\b
|
||||
{
|
||||
"0123456789abcdef...": {
|
||||
"friendly_name": "My Node",
|
||||
"location": {"value": "52.0,1.0", "type": "coordinate"},
|
||||
"altitude": {"value": "150", "type": "number"}
|
||||
}
|
||||
}
|
||||
0123456789abcdef...:
|
||||
friendly_name: My Node
|
||||
altitude:
|
||||
value: "150"
|
||||
type: number
|
||||
active:
|
||||
value: "true"
|
||||
type: boolean
|
||||
|
||||
Shorthand is also supported (string values with default type):
|
||||
\b
|
||||
{
|
||||
"0123456789abcdef...": {
|
||||
"friendly_name": "My Node",
|
||||
"role": "gateway"
|
||||
}
|
||||
}
|
||||
|
||||
Supported types: string, number, boolean, coordinate
|
||||
\b
|
||||
0123456789abcdef...:
|
||||
friendly_name: My Node
|
||||
role: gateway
|
||||
|
||||
Supported types: string, number, boolean
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
@@ -362,7 +531,7 @@ def import_tags_cmd(
|
||||
if not Path(tags_file).exists():
|
||||
click.echo(f"Tags file not found: {tags_file}")
|
||||
if not file:
|
||||
click.echo("Specify a file path or create the default node_tags.json.")
|
||||
click.echo("Specify a file path or create the default node_tags.yaml.")
|
||||
return
|
||||
|
||||
click.echo(f"Importing tags from: {tags_file}")
|
||||
@@ -371,20 +540,22 @@ def import_tags_cmd(
|
||||
from meshcore_hub.common.database import DatabaseManager
|
||||
from meshcore_hub.collector.tag_import import import_tags
|
||||
|
||||
# Initialize database
|
||||
# Initialize database (schema managed by Alembic migrations)
|
||||
db = DatabaseManager(ctx.obj["database_url"])
|
||||
db.create_tables()
|
||||
|
||||
# Import tags
|
||||
stats = import_tags(
|
||||
file_path=tags_file,
|
||||
db=db,
|
||||
create_nodes=not no_create_nodes,
|
||||
clear_existing=clear_existing,
|
||||
)
|
||||
|
||||
# Report results
|
||||
click.echo("")
|
||||
click.echo("Import complete:")
|
||||
if stats["deleted"]:
|
||||
click.echo(f" Tags deleted: {stats['deleted']}")
|
||||
click.echo(f" Total tags in file: {stats['total']}")
|
||||
click.echo(f" Tags created: {stats['created']}")
|
||||
click.echo(f" Tags updated: {stats['updated']}")
|
||||
@@ -407,33 +578,29 @@ def import_members_cmd(
|
||||
ctx: click.Context,
|
||||
file: str | None,
|
||||
) -> None:
|
||||
"""Import network members from a JSON file.
|
||||
"""Import network members from a YAML file.
|
||||
|
||||
Reads a JSON file containing member definitions and upserts them
|
||||
Reads a YAML file containing member definitions and upserts them
|
||||
into the database. Existing members (matched by name) are updated,
|
||||
new members are created.
|
||||
|
||||
FILE is the path to the JSON file containing members.
|
||||
If not provided, defaults to {SEED_HOME}/members.json.
|
||||
FILE is the path to the YAML file containing members.
|
||||
If not provided, defaults to {SEED_HOME}/members.yaml.
|
||||
|
||||
Expected YAML format (list):
|
||||
|
||||
Expected JSON format (list):
|
||||
\b
|
||||
[
|
||||
{
|
||||
"name": "John Doe",
|
||||
"callsign": "N0CALL",
|
||||
"role": "Network Operator",
|
||||
"description": "Example member"
|
||||
}
|
||||
]
|
||||
- name: John Doe
|
||||
callsign: N0CALL
|
||||
role: Network Operator
|
||||
description: Example member
|
||||
|
||||
Or with "members" key:
|
||||
|
||||
\b
|
||||
{
|
||||
"members": [
|
||||
{"name": "John Doe", "callsign": "N0CALL", ...}
|
||||
]
|
||||
}
|
||||
members:
|
||||
- name: John Doe
|
||||
callsign: N0CALL
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
@@ -447,7 +614,7 @@ def import_members_cmd(
|
||||
if not Path(members_file).exists():
|
||||
click.echo(f"Members file not found: {members_file}")
|
||||
if not file:
|
||||
click.echo("Specify a file path or create the default members.json.")
|
||||
click.echo("Specify a file path or create the default members.yaml.")
|
||||
return
|
||||
|
||||
click.echo(f"Importing members from: {members_file}")
|
||||
@@ -456,9 +623,8 @@ def import_members_cmd(
|
||||
from meshcore_hub.common.database import DatabaseManager
|
||||
from meshcore_hub.collector.member_import import import_members
|
||||
|
||||
# Initialize database
|
||||
# Initialize database (schema managed by Alembic migrations)
|
||||
db = DatabaseManager(ctx.obj["database_url"])
|
||||
db.create_tables()
|
||||
|
||||
# Import members
|
||||
stats = import_members(
|
||||
@@ -480,3 +646,299 @@ def import_members_cmd(
|
||||
click.echo(f" - {error}", err=True)
|
||||
|
||||
db.dispose()
|
||||
|
||||
|
||||
@collector.command("cleanup")
|
||||
@click.option(
|
||||
"--retention-days",
|
||||
type=int,
|
||||
default=30,
|
||||
envvar="DATA_RETENTION_DAYS",
|
||||
help="Number of days to retain data (default: 30)",
|
||||
)
|
||||
@click.option(
|
||||
"--dry-run",
|
||||
is_flag=True,
|
||||
default=False,
|
||||
help="Show what would be deleted without deleting",
|
||||
)
|
||||
@click.pass_context
|
||||
def cleanup_cmd(
|
||||
ctx: click.Context,
|
||||
retention_days: int,
|
||||
dry_run: bool,
|
||||
) -> None:
|
||||
"""Manually run data cleanup to delete old events.
|
||||
|
||||
Deletes event data older than the retention period:
|
||||
- Advertisements
|
||||
- Messages (channel and direct)
|
||||
- Telemetry
|
||||
- Trace paths
|
||||
- Event logs
|
||||
|
||||
Node records are never deleted - only event data.
|
||||
|
||||
Use --dry-run to preview what would be deleted without
|
||||
actually deleting anything.
|
||||
"""
|
||||
import asyncio
|
||||
|
||||
configure_logging(level=ctx.obj["log_level"])
|
||||
|
||||
click.echo(f"Database: {ctx.obj['database_url']}")
|
||||
click.echo(f"Retention: {retention_days} days")
|
||||
click.echo(f"Mode: {'DRY RUN' if dry_run else 'LIVE'}")
|
||||
click.echo("")
|
||||
|
||||
if dry_run:
|
||||
click.echo("Running in dry-run mode - no data will be deleted.")
|
||||
else:
|
||||
click.echo("WARNING: This will permanently delete old event data!")
|
||||
if not click.confirm("Continue?"):
|
||||
click.echo("Aborted.")
|
||||
return
|
||||
|
||||
click.echo("")
|
||||
|
||||
from meshcore_hub.common.database import DatabaseManager
|
||||
from meshcore_hub.collector.cleanup import cleanup_old_data
|
||||
|
||||
# Initialize database
|
||||
db = DatabaseManager(ctx.obj["database_url"])
|
||||
|
||||
# Run cleanup
|
||||
async def run_cleanup() -> None:
|
||||
async with db.async_session() as session:
|
||||
stats = await cleanup_old_data(
|
||||
session,
|
||||
retention_days,
|
||||
dry_run=dry_run,
|
||||
)
|
||||
|
||||
click.echo("")
|
||||
click.echo("Cleanup results:")
|
||||
click.echo(f" Advertisements: {stats.advertisements_deleted}")
|
||||
click.echo(f" Messages: {stats.messages_deleted}")
|
||||
click.echo(f" Telemetry: {stats.telemetry_deleted}")
|
||||
click.echo(f" Trace paths: {stats.trace_paths_deleted}")
|
||||
click.echo(f" Event logs: {stats.event_logs_deleted}")
|
||||
click.echo(f" Total: {stats.total_deleted}")
|
||||
|
||||
if dry_run:
|
||||
click.echo("")
|
||||
click.echo("(Dry run - no data was actually deleted)")
|
||||
|
||||
asyncio.run(run_cleanup())
|
||||
db.dispose()
|
||||
click.echo("")
|
||||
click.echo("Cleanup complete." if not dry_run else "Dry run complete.")
|
||||
|
||||
|
||||
@collector.command("truncate")
|
||||
@click.option(
|
||||
"--members",
|
||||
is_flag=True,
|
||||
default=False,
|
||||
help="Truncate members table",
|
||||
)
|
||||
@click.option(
|
||||
"--nodes",
|
||||
is_flag=True,
|
||||
default=False,
|
||||
help="Truncate nodes table (also clears tags, advertisements, messages, telemetry, trace paths)",
|
||||
)
|
||||
@click.option(
|
||||
"--messages",
|
||||
is_flag=True,
|
||||
default=False,
|
||||
help="Truncate messages table",
|
||||
)
|
||||
@click.option(
|
||||
"--advertisements",
|
||||
is_flag=True,
|
||||
default=False,
|
||||
help="Truncate advertisements table",
|
||||
)
|
||||
@click.option(
|
||||
"--telemetry",
|
||||
is_flag=True,
|
||||
default=False,
|
||||
help="Truncate telemetry table",
|
||||
)
|
||||
@click.option(
|
||||
"--trace-paths",
|
||||
is_flag=True,
|
||||
default=False,
|
||||
help="Truncate trace_paths table",
|
||||
)
|
||||
@click.option(
|
||||
"--event-logs",
|
||||
is_flag=True,
|
||||
default=False,
|
||||
help="Truncate event_logs table",
|
||||
)
|
||||
@click.option(
|
||||
"--all",
|
||||
"truncate_all",
|
||||
is_flag=True,
|
||||
default=False,
|
||||
help="Truncate ALL tables (use with caution!)",
|
||||
)
|
||||
@click.option(
|
||||
"--yes",
|
||||
is_flag=True,
|
||||
default=False,
|
||||
help="Skip confirmation prompt",
|
||||
)
|
||||
@click.pass_context
|
||||
def truncate_cmd(
|
||||
ctx: click.Context,
|
||||
members: bool,
|
||||
nodes: bool,
|
||||
messages: bool,
|
||||
advertisements: bool,
|
||||
telemetry: bool,
|
||||
trace_paths: bool,
|
||||
event_logs: bool,
|
||||
truncate_all: bool,
|
||||
yes: bool,
|
||||
) -> None:
|
||||
"""Truncate (clear) data tables.
|
||||
|
||||
WARNING: This permanently deletes data! Use with caution.
|
||||
|
||||
Examples:
|
||||
# Clear members table
|
||||
meshcore-hub collector truncate --members
|
||||
|
||||
# Clear messages and advertisements
|
||||
meshcore-hub collector truncate --messages --advertisements
|
||||
|
||||
# Clear everything (requires confirmation)
|
||||
meshcore-hub collector truncate --all
|
||||
|
||||
Note: Clearing nodes also clears all related data (tags, advertisements,
|
||||
messages, telemetry, trace paths) due to foreign key constraints.
|
||||
"""
|
||||
configure_logging(level=ctx.obj["log_level"])
|
||||
|
||||
# Determine what to truncate
|
||||
if truncate_all:
|
||||
tables_to_clear = {
|
||||
"members": True,
|
||||
"nodes": True,
|
||||
"messages": True,
|
||||
"advertisements": True,
|
||||
"telemetry": True,
|
||||
"trace_paths": True,
|
||||
"event_logs": True,
|
||||
}
|
||||
else:
|
||||
tables_to_clear = {
|
||||
"members": members,
|
||||
"nodes": nodes,
|
||||
"messages": messages,
|
||||
"advertisements": advertisements,
|
||||
"telemetry": telemetry,
|
||||
"trace_paths": trace_paths,
|
||||
"event_logs": event_logs,
|
||||
}
|
||||
|
||||
# Check if any tables selected
|
||||
if not any(tables_to_clear.values()):
|
||||
click.echo("No tables specified. Use --help to see available options.")
|
||||
return
|
||||
|
||||
# Show what will be cleared
|
||||
click.echo("Database: " + ctx.obj["database_url"])
|
||||
click.echo("")
|
||||
click.echo("The following tables will be PERMANENTLY CLEARED:")
|
||||
for table, should_clear in tables_to_clear.items():
|
||||
if should_clear:
|
||||
click.echo(f" - {table}")
|
||||
|
||||
if tables_to_clear.get("nodes"):
|
||||
click.echo("")
|
||||
click.echo(
|
||||
"WARNING: Clearing nodes will also clear all related data due to foreign keys:"
|
||||
)
|
||||
click.echo(" - node_tags")
|
||||
click.echo(" - advertisements")
|
||||
click.echo(" - messages")
|
||||
click.echo(" - telemetry")
|
||||
click.echo(" - trace_paths")
|
||||
|
||||
click.echo("")
|
||||
|
||||
# Confirm
|
||||
if not yes:
|
||||
if not click.confirm(
|
||||
"Are you sure you want to permanently delete this data?", default=False
|
||||
):
|
||||
click.echo("Aborted.")
|
||||
return
|
||||
|
||||
from meshcore_hub.common.database import DatabaseManager
|
||||
from meshcore_hub.common.models import (
|
||||
Advertisement,
|
||||
EventLog,
|
||||
Member,
|
||||
Message,
|
||||
Node,
|
||||
NodeTag,
|
||||
Telemetry,
|
||||
TracePath,
|
||||
)
|
||||
from sqlalchemy import delete
|
||||
from sqlalchemy.engine import CursorResult
|
||||
|
||||
db = DatabaseManager(ctx.obj["database_url"])
|
||||
|
||||
with db.session_scope() as session:
|
||||
# Truncate in correct order to respect foreign keys
|
||||
cleared: list[str] = []
|
||||
|
||||
# Clear members (no dependencies)
|
||||
if tables_to_clear.get("members"):
|
||||
result: CursorResult = session.execute(delete(Member)) # type: ignore
|
||||
cleared.append(f"members: {result.rowcount} rows")
|
||||
|
||||
# Clear event-specific tables first (they depend on nodes)
|
||||
if tables_to_clear.get("messages"):
|
||||
result = session.execute(delete(Message)) # type: ignore
|
||||
cleared.append(f"messages: {result.rowcount} rows")
|
||||
|
||||
if tables_to_clear.get("advertisements"):
|
||||
result = session.execute(delete(Advertisement)) # type: ignore
|
||||
cleared.append(f"advertisements: {result.rowcount} rows")
|
||||
|
||||
if tables_to_clear.get("telemetry"):
|
||||
result = session.execute(delete(Telemetry)) # type: ignore
|
||||
cleared.append(f"telemetry: {result.rowcount} rows")
|
||||
|
||||
if tables_to_clear.get("trace_paths"):
|
||||
result = session.execute(delete(TracePath)) # type: ignore
|
||||
cleared.append(f"trace_paths: {result.rowcount} rows")
|
||||
|
||||
if tables_to_clear.get("event_logs"):
|
||||
result = session.execute(delete(EventLog)) # type: ignore
|
||||
cleared.append(f"event_logs: {result.rowcount} rows")
|
||||
|
||||
# Clear nodes last (this will cascade delete tags and any remaining events)
|
||||
if tables_to_clear.get("nodes"):
|
||||
# Delete tags first (they depend on nodes)
|
||||
tag_result: CursorResult = session.execute(delete(NodeTag)) # type: ignore
|
||||
cleared.append(f"node_tags: {tag_result.rowcount} rows (cascade)")
|
||||
|
||||
# Delete nodes (will cascade to remaining related tables)
|
||||
node_result: CursorResult = session.execute(delete(Node)) # type: ignore
|
||||
cleared.append(f"nodes: {node_result.rowcount} rows")
|
||||
|
||||
db.dispose()
|
||||
|
||||
click.echo("")
|
||||
click.echo("Truncate complete. Cleared:")
|
||||
for item in cleared:
|
||||
click.echo(f" - {item}")
|
||||
click.echo("")
|
||||
|
||||
@@ -19,7 +19,7 @@ def register_all_handlers(subscriber: "Subscriber") -> None:
|
||||
)
|
||||
from meshcore_hub.collector.handlers.trace import handle_trace_data
|
||||
from meshcore_hub.collector.handlers.telemetry import handle_telemetry
|
||||
from meshcore_hub.collector.handlers.contacts import handle_contacts
|
||||
from meshcore_hub.collector.handlers.contacts import handle_contact
|
||||
from meshcore_hub.collector.handlers.event_log import handle_event_log
|
||||
|
||||
# Persisted events with specific handlers
|
||||
@@ -28,7 +28,7 @@ def register_all_handlers(subscriber: "Subscriber") -> None:
|
||||
subscriber.register_handler("channel_msg_recv", handle_channel_message)
|
||||
subscriber.register_handler("trace_data", handle_trace_data)
|
||||
subscriber.register_handler("telemetry_response", handle_telemetry)
|
||||
subscriber.register_handler("contacts", handle_contacts)
|
||||
subscriber.register_handler("contact", handle_contact) # Individual contact events
|
||||
|
||||
# Informational events (logged only)
|
||||
subscriber.register_handler("send_confirmed", handle_event_log)
|
||||
|
||||
@@ -5,13 +5,29 @@ from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from meshcore_hub.common.database import DatabaseManager
|
||||
from meshcore_hub.common.models import Advertisement, Node
|
||||
from meshcore_hub.common.hash_utils import compute_advertisement_hash
|
||||
from meshcore_hub.common.models import Advertisement, Node, add_event_receiver
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _coerce_float(value: Any) -> float | None:
|
||||
"""Convert int/float/string values to float when possible."""
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, (int, float)):
|
||||
return float(value)
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
return float(value.strip())
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def handle_advertisement(
|
||||
public_key: str,
|
||||
event_type: str,
|
||||
@@ -38,10 +54,35 @@ def handle_advertisement(
|
||||
name = payload.get("name")
|
||||
adv_type = payload.get("adv_type")
|
||||
flags = payload.get("flags")
|
||||
lat = payload.get("lat")
|
||||
lon = payload.get("lon")
|
||||
|
||||
if lat is None:
|
||||
lat = payload.get("adv_lat")
|
||||
if lon is None:
|
||||
lon = payload.get("adv_lon")
|
||||
|
||||
location = payload.get("location")
|
||||
if isinstance(location, dict):
|
||||
if lat is None:
|
||||
lat = location.get("latitude")
|
||||
if lon is None:
|
||||
lon = location.get("longitude")
|
||||
lat = _coerce_float(lat)
|
||||
lon = _coerce_float(lon)
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
# Compute event hash for deduplication (30-second time bucket)
|
||||
event_hash = compute_advertisement_hash(
|
||||
public_key=adv_public_key,
|
||||
name=name,
|
||||
adv_type=adv_type,
|
||||
flags=flags,
|
||||
received_at=now,
|
||||
)
|
||||
|
||||
with db.session_scope() as session:
|
||||
# Find or create receiver node
|
||||
# Find or create receiver node first (needed for both new and duplicate events)
|
||||
receiver_node = None
|
||||
if public_key:
|
||||
receiver_query = select(Node).where(Node.public_key == public_key)
|
||||
@@ -55,6 +96,41 @@ def handle_advertisement(
|
||||
)
|
||||
session.add(receiver_node)
|
||||
session.flush()
|
||||
else:
|
||||
receiver_node.last_seen = now
|
||||
|
||||
# Check if advertisement with same hash already exists
|
||||
existing = session.execute(
|
||||
select(Advertisement.id).where(Advertisement.event_hash == event_hash)
|
||||
).scalar_one_or_none()
|
||||
|
||||
if existing:
|
||||
# Still update advertised node's last_seen even for duplicate advertisements
|
||||
node_query = select(Node).where(Node.public_key == adv_public_key)
|
||||
node = session.execute(node_query).scalar_one_or_none()
|
||||
if node:
|
||||
if lat is not None:
|
||||
node.lat = lat
|
||||
if lon is not None:
|
||||
node.lon = lon
|
||||
node.last_seen = now
|
||||
|
||||
# Add this receiver to the junction table
|
||||
if receiver_node:
|
||||
added = add_event_receiver(
|
||||
session=session,
|
||||
event_type="advertisement",
|
||||
event_hash=event_hash,
|
||||
receiver_node_id=receiver_node.id,
|
||||
snr=None, # Advertisements don't have SNR
|
||||
received_at=now,
|
||||
)
|
||||
if added:
|
||||
logger.debug(
|
||||
f"Added receiver {public_key[:12]}... to advertisement "
|
||||
f"(hash={event_hash[:8]}...)"
|
||||
)
|
||||
return
|
||||
|
||||
# Find or create advertised node
|
||||
node_query = select(Node).where(Node.public_key == adv_public_key)
|
||||
@@ -68,6 +144,10 @@ def handle_advertisement(
|
||||
node.adv_type = adv_type
|
||||
if flags is not None:
|
||||
node.flags = flags
|
||||
if lat is not None:
|
||||
node.lat = lat
|
||||
if lon is not None:
|
||||
node.lon = lon
|
||||
node.last_seen = now
|
||||
else:
|
||||
# Create new node
|
||||
@@ -78,6 +158,8 @@ def handle_advertisement(
|
||||
flags=flags,
|
||||
first_seen=now,
|
||||
last_seen=now,
|
||||
lat=lat,
|
||||
lon=lon,
|
||||
)
|
||||
session.add(node)
|
||||
session.flush()
|
||||
@@ -91,9 +173,43 @@ def handle_advertisement(
|
||||
adv_type=adv_type,
|
||||
flags=flags,
|
||||
received_at=now,
|
||||
event_hash=event_hash,
|
||||
)
|
||||
session.add(advertisement)
|
||||
|
||||
# Add first receiver to junction table
|
||||
if receiver_node:
|
||||
add_event_receiver(
|
||||
session=session,
|
||||
event_type="advertisement",
|
||||
event_hash=event_hash,
|
||||
receiver_node_id=receiver_node.id,
|
||||
snr=None,
|
||||
received_at=now,
|
||||
)
|
||||
|
||||
# Flush to check for duplicate constraint violation (race condition)
|
||||
try:
|
||||
session.flush()
|
||||
except IntegrityError:
|
||||
# Race condition: another request inserted the same event_hash
|
||||
session.rollback()
|
||||
logger.debug(
|
||||
f"Duplicate advertisement skipped (race condition, "
|
||||
f"hash={event_hash[:8]}...)"
|
||||
)
|
||||
# Re-add receiver to existing event in a new transaction
|
||||
if receiver_node:
|
||||
add_event_receiver(
|
||||
session=session,
|
||||
event_type="advertisement",
|
||||
event_hash=event_hash,
|
||||
receiver_node_id=receiver_node.id,
|
||||
snr=None,
|
||||
received_at=now,
|
||||
)
|
||||
return
|
||||
|
||||
logger.info(
|
||||
f"Stored advertisement from {name or adv_public_key[:12]!r} "
|
||||
f"(type={adv_type})"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Handler for contacts sync events."""
|
||||
"""Handler for contact sync events."""
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
@@ -11,65 +11,90 @@ from meshcore_hub.common.models import Node
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Map numeric node type to string representation
|
||||
NODE_TYPE_MAP = {
|
||||
0: "none",
|
||||
1: "chat",
|
||||
2: "repeater",
|
||||
3: "room",
|
||||
}
|
||||
|
||||
def handle_contacts(
|
||||
|
||||
def handle_contact(
|
||||
public_key: str,
|
||||
event_type: str,
|
||||
payload: dict[str, Any],
|
||||
db: DatabaseManager,
|
||||
) -> None:
|
||||
"""Handle a contacts sync event.
|
||||
"""Handle a single contact event.
|
||||
|
||||
Upserts all contacts in the contacts list.
|
||||
Upserts a contact into the nodes table.
|
||||
|
||||
Args:
|
||||
public_key: Receiver node's public key (from MQTT topic)
|
||||
event_type: Event type name
|
||||
payload: Contacts payload
|
||||
payload: Single contact object with fields:
|
||||
- public_key: Contact's public key
|
||||
- adv_name: Advertised name
|
||||
- type: Numeric node type (0=none, 1=chat, 2=repeater, 3=room)
|
||||
db: Database manager
|
||||
"""
|
||||
contacts = payload.get("contacts", [])
|
||||
if not contacts:
|
||||
logger.debug("Empty contacts list received")
|
||||
contact_key = payload.get("public_key")
|
||||
if not contact_key:
|
||||
logger.warning("Contact event missing public_key field")
|
||||
return
|
||||
|
||||
# Device uses 'adv_name' for the advertised name
|
||||
name = payload.get("adv_name") or payload.get("name")
|
||||
|
||||
# GPS coordinates (optional)
|
||||
lat = payload.get("adv_lat")
|
||||
lon = payload.get("adv_lon")
|
||||
|
||||
logger.info(f"Processing contact: {contact_key[:12]}... adv_name={name}")
|
||||
|
||||
# Device uses numeric 'type' field, convert to string
|
||||
raw_type = payload.get("type")
|
||||
if raw_type is not None:
|
||||
node_type: str | None = NODE_TYPE_MAP.get(raw_type, str(raw_type))
|
||||
else:
|
||||
node_type = payload.get("node_type")
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
created_count = 0
|
||||
updated_count = 0
|
||||
|
||||
with db.session_scope() as session:
|
||||
for contact in contacts:
|
||||
contact_key = contact.get("public_key")
|
||||
if not contact_key:
|
||||
continue
|
||||
# Find or create node
|
||||
node_query = select(Node).where(Node.public_key == contact_key)
|
||||
node = session.execute(node_query).scalar_one_or_none()
|
||||
|
||||
name = contact.get("name")
|
||||
node_type = contact.get("node_type")
|
||||
|
||||
# Find or create node
|
||||
node_query = select(Node).where(Node.public_key == contact_key)
|
||||
node = session.execute(node_query).scalar_one_or_none()
|
||||
|
||||
if node:
|
||||
# Update existing node
|
||||
if name and not node.name:
|
||||
node.name = name
|
||||
if node_type and not node.adv_type:
|
||||
node.adv_type = node_type
|
||||
node.last_seen = now
|
||||
updated_count += 1
|
||||
else:
|
||||
# Create new node
|
||||
node = Node(
|
||||
public_key=contact_key,
|
||||
name=name,
|
||||
adv_type=node_type,
|
||||
first_seen=now,
|
||||
last_seen=now,
|
||||
if node:
|
||||
# Update existing node - always update name if we have one
|
||||
if name and name != node.name:
|
||||
logger.info(
|
||||
f"Updating node {contact_key[:12]}... "
|
||||
f"name: {node.name!r} -> {name!r}"
|
||||
)
|
||||
session.add(node)
|
||||
created_count += 1
|
||||
|
||||
logger.info(
|
||||
f"Processed contacts sync: {created_count} new, {updated_count} updated"
|
||||
)
|
||||
node.name = name
|
||||
if node_type and not node.adv_type:
|
||||
node.adv_type = node_type
|
||||
# Update GPS coordinates if provided
|
||||
if lat is not None:
|
||||
node.lat = lat
|
||||
if lon is not None:
|
||||
node.lon = lon
|
||||
# Do NOT update last_seen for contact sync - only advertisement events
|
||||
# should update last_seen since that's when the node was actually seen
|
||||
else:
|
||||
# Create new node from contact database
|
||||
# Set last_seen=None since we haven't actually seen this node advertise yet
|
||||
node = Node(
|
||||
public_key=contact_key,
|
||||
name=name,
|
||||
adv_type=node_type,
|
||||
first_seen=now,
|
||||
last_seen=None, # Will be set when we receive an advertisement
|
||||
lat=lat,
|
||||
lon=lon,
|
||||
)
|
||||
session.add(node)
|
||||
logger.info(f"Created node from contact: {contact_key[:12]}... ({name})")
|
||||
|
||||
@@ -5,9 +5,11 @@ from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from meshcore_hub.common.database import DatabaseManager
|
||||
from meshcore_hub.common.models import Message, Node
|
||||
from meshcore_hub.common.hash_utils import compute_message_hash
|
||||
from meshcore_hub.common.models import Message, Node, add_event_receiver
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -68,7 +70,7 @@ def _handle_message(
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
# Extract fields based on message type
|
||||
pubkey_prefix = payload.get("pubkey_prefix") if message_type == "contact" else None
|
||||
pubkey_prefix = payload.get("pubkey_prefix")
|
||||
channel_idx = payload.get("channel_idx") if message_type == "channel" else None
|
||||
path_len = payload.get("path_len")
|
||||
txt_type = payload.get("txt_type")
|
||||
@@ -84,8 +86,17 @@ def _handle_message(
|
||||
except (ValueError, OSError):
|
||||
pass
|
||||
|
||||
# Compute event hash for deduplication
|
||||
event_hash = compute_message_hash(
|
||||
text=text,
|
||||
pubkey_prefix=pubkey_prefix,
|
||||
channel_idx=channel_idx,
|
||||
sender_timestamp=sender_timestamp,
|
||||
txt_type=txt_type,
|
||||
)
|
||||
|
||||
with db.session_scope() as session:
|
||||
# Find receiver node
|
||||
# Find or create receiver node first (needed for both new and duplicate events)
|
||||
receiver_node = None
|
||||
if public_key:
|
||||
receiver_query = select(Node).where(Node.public_key == public_key)
|
||||
@@ -102,6 +113,29 @@ def _handle_message(
|
||||
else:
|
||||
receiver_node.last_seen = now
|
||||
|
||||
# Check if message with same hash already exists
|
||||
existing = session.execute(
|
||||
select(Message.id).where(Message.event_hash == event_hash)
|
||||
).scalar_one_or_none()
|
||||
|
||||
if existing:
|
||||
# Event already exists - just add this receiver to the junction table
|
||||
if receiver_node:
|
||||
added = add_event_receiver(
|
||||
session=session,
|
||||
event_type="message",
|
||||
event_hash=event_hash,
|
||||
receiver_node_id=receiver_node.id,
|
||||
snr=snr,
|
||||
received_at=now,
|
||||
)
|
||||
if added:
|
||||
logger.debug(
|
||||
f"Added receiver {public_key[:12]}... to message "
|
||||
f"(hash={event_hash[:8]}...)"
|
||||
)
|
||||
return
|
||||
|
||||
# Create message record
|
||||
message = Message(
|
||||
receiver_node_id=receiver_node.id if receiver_node else None,
|
||||
@@ -115,9 +149,42 @@ def _handle_message(
|
||||
snr=snr,
|
||||
sender_timestamp=sender_timestamp,
|
||||
received_at=now,
|
||||
event_hash=event_hash,
|
||||
)
|
||||
session.add(message)
|
||||
|
||||
# Add first receiver to junction table
|
||||
if receiver_node:
|
||||
add_event_receiver(
|
||||
session=session,
|
||||
event_type="message",
|
||||
event_hash=event_hash,
|
||||
receiver_node_id=receiver_node.id,
|
||||
snr=snr,
|
||||
received_at=now,
|
||||
)
|
||||
|
||||
# Flush to check for duplicate constraint violation (race condition)
|
||||
try:
|
||||
session.flush()
|
||||
except IntegrityError:
|
||||
# Race condition: another request inserted the same event_hash
|
||||
session.rollback()
|
||||
logger.debug(
|
||||
f"Duplicate message skipped (race condition, hash={event_hash[:8]}...)"
|
||||
)
|
||||
# Re-add receiver to existing event in a new transaction
|
||||
if receiver_node:
|
||||
add_event_receiver(
|
||||
session=session,
|
||||
event_type="message",
|
||||
event_hash=event_hash,
|
||||
receiver_node_id=receiver_node.id,
|
||||
snr=snr,
|
||||
received_at=now,
|
||||
)
|
||||
return
|
||||
|
||||
if message_type == "contact":
|
||||
logger.info(
|
||||
f"Stored contact message from {pubkey_prefix!r}: "
|
||||
|
||||
@@ -5,9 +5,11 @@ from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from meshcore_hub.common.database import DatabaseManager
|
||||
from meshcore_hub.common.models import Node, Telemetry
|
||||
from meshcore_hub.common.hash_utils import compute_telemetry_hash
|
||||
from meshcore_hub.common.models import Node, Telemetry, add_event_receiver
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -49,8 +51,15 @@ def handle_telemetry(
|
||||
except ValueError:
|
||||
lpp_bytes = lpp_data.encode()
|
||||
|
||||
# Compute event hash for deduplication (30-second time bucket)
|
||||
event_hash = compute_telemetry_hash(
|
||||
node_public_key=node_public_key,
|
||||
parsed_data=parsed_data,
|
||||
received_at=now,
|
||||
)
|
||||
|
||||
with db.session_scope() as session:
|
||||
# Find receiver node
|
||||
# Find or create receiver node first (needed for both new and duplicate events)
|
||||
receiver_node = None
|
||||
if public_key:
|
||||
receiver_query = select(Node).where(Node.public_key == public_key)
|
||||
@@ -67,6 +76,29 @@ def handle_telemetry(
|
||||
else:
|
||||
receiver_node.last_seen = now
|
||||
|
||||
# Check if telemetry with same hash already exists
|
||||
existing = session.execute(
|
||||
select(Telemetry.id).where(Telemetry.event_hash == event_hash)
|
||||
).scalar_one_or_none()
|
||||
|
||||
if existing:
|
||||
# Event already exists - just add this receiver to the junction table
|
||||
if receiver_node:
|
||||
added = add_event_receiver(
|
||||
session=session,
|
||||
event_type="telemetry",
|
||||
event_hash=event_hash,
|
||||
receiver_node_id=receiver_node.id,
|
||||
snr=None,
|
||||
received_at=now,
|
||||
)
|
||||
if added:
|
||||
logger.debug(
|
||||
f"Added receiver {public_key[:12]}... to telemetry "
|
||||
f"(node={node_public_key[:12]}...)"
|
||||
)
|
||||
return
|
||||
|
||||
# Find or create reporting node
|
||||
reporting_node = None
|
||||
if node_public_key:
|
||||
@@ -92,9 +124,43 @@ def handle_telemetry(
|
||||
lpp_data=lpp_bytes,
|
||||
parsed_data=parsed_data,
|
||||
received_at=now,
|
||||
event_hash=event_hash,
|
||||
)
|
||||
session.add(telemetry)
|
||||
|
||||
# Add first receiver to junction table
|
||||
if receiver_node:
|
||||
add_event_receiver(
|
||||
session=session,
|
||||
event_type="telemetry",
|
||||
event_hash=event_hash,
|
||||
receiver_node_id=receiver_node.id,
|
||||
snr=None,
|
||||
received_at=now,
|
||||
)
|
||||
|
||||
# Flush to check for duplicate constraint violation (race condition)
|
||||
try:
|
||||
session.flush()
|
||||
except IntegrityError:
|
||||
# Race condition: another request inserted the same event_hash
|
||||
session.rollback()
|
||||
logger.debug(
|
||||
f"Duplicate telemetry skipped (race condition, "
|
||||
f"node={node_public_key[:12]}...)"
|
||||
)
|
||||
# Re-add receiver to existing event in a new transaction
|
||||
if receiver_node:
|
||||
add_event_receiver(
|
||||
session=session,
|
||||
event_type="telemetry",
|
||||
event_hash=event_hash,
|
||||
receiver_node_id=receiver_node.id,
|
||||
snr=None,
|
||||
received_at=now,
|
||||
)
|
||||
return
|
||||
|
||||
# Log telemetry values
|
||||
if parsed_data:
|
||||
values = ", ".join(f"{k}={v}" for k, v in parsed_data.items())
|
||||
|
||||
@@ -5,9 +5,11 @@ from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from meshcore_hub.common.database import DatabaseManager
|
||||
from meshcore_hub.common.models import Node, TracePath
|
||||
from meshcore_hub.common.hash_utils import compute_trace_hash
|
||||
from meshcore_hub.common.models import Node, TracePath, add_event_receiver
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -40,8 +42,11 @@ def handle_trace_data(
|
||||
snr_values = payload.get("snr_values")
|
||||
hop_count = payload.get("hop_count")
|
||||
|
||||
# Compute event hash for deduplication (initiator_tag is unique per trace)
|
||||
event_hash = compute_trace_hash(initiator_tag=initiator_tag)
|
||||
|
||||
with db.session_scope() as session:
|
||||
# Find receiver node
|
||||
# Find or create receiver node first (needed for both new and duplicate events)
|
||||
receiver_node = None
|
||||
if public_key:
|
||||
receiver_query = select(Node).where(Node.public_key == public_key)
|
||||
@@ -58,6 +63,29 @@ def handle_trace_data(
|
||||
else:
|
||||
receiver_node.last_seen = now
|
||||
|
||||
# Check if trace with same hash already exists
|
||||
existing = session.execute(
|
||||
select(TracePath.id).where(TracePath.event_hash == event_hash)
|
||||
).scalar_one_or_none()
|
||||
|
||||
if existing:
|
||||
# Event already exists - just add this receiver to the junction table
|
||||
if receiver_node:
|
||||
added = add_event_receiver(
|
||||
session=session,
|
||||
event_type="trace",
|
||||
event_hash=event_hash,
|
||||
receiver_node_id=receiver_node.id,
|
||||
snr=None, # Trace events don't have a single SNR value
|
||||
received_at=now,
|
||||
)
|
||||
if added:
|
||||
logger.debug(
|
||||
f"Added receiver {public_key[:12]}... to trace "
|
||||
f"(tag={initiator_tag})"
|
||||
)
|
||||
return
|
||||
|
||||
# Create trace path record
|
||||
trace_path = TracePath(
|
||||
receiver_node_id=receiver_node.id if receiver_node else None,
|
||||
@@ -69,7 +97,40 @@ def handle_trace_data(
|
||||
snr_values=snr_values,
|
||||
hop_count=hop_count,
|
||||
received_at=now,
|
||||
event_hash=event_hash,
|
||||
)
|
||||
session.add(trace_path)
|
||||
|
||||
# Add first receiver to junction table
|
||||
if receiver_node:
|
||||
add_event_receiver(
|
||||
session=session,
|
||||
event_type="trace",
|
||||
event_hash=event_hash,
|
||||
receiver_node_id=receiver_node.id,
|
||||
snr=None,
|
||||
received_at=now,
|
||||
)
|
||||
|
||||
# Flush to check for duplicate constraint violation (race condition)
|
||||
try:
|
||||
session.flush()
|
||||
except IntegrityError:
|
||||
# Race condition: another request inserted the same event_hash
|
||||
session.rollback()
|
||||
logger.debug(
|
||||
f"Duplicate trace skipped (race condition, tag={initiator_tag})"
|
||||
)
|
||||
# Re-add receiver to existing event in a new transaction
|
||||
if receiver_node:
|
||||
add_event_receiver(
|
||||
session=session,
|
||||
event_type="trace",
|
||||
event_hash=event_hash,
|
||||
receiver_node_id=receiver_node.id,
|
||||
snr=None,
|
||||
received_at=now,
|
||||
)
|
||||
return
|
||||
|
||||
logger.info(f"Stored trace data: tag={initiator_tag}, hops={hop_count}")
|
||||
|
||||
275
src/meshcore_hub/collector/letsmesh_decoder.py
Normal file
275
src/meshcore_hub/collector/letsmesh_decoder.py
Normal file
@@ -0,0 +1,275 @@
|
||||
"""LetsMesh packet decoder integration.
|
||||
|
||||
Provides an optional bridge to the external `meshcore-decoder` CLI so the
|
||||
collector can turn LetsMesh upload `raw` packet hex into decoded message data.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import shlex
|
||||
import shutil
|
||||
import string
|
||||
import subprocess
|
||||
from typing import Any, NamedTuple
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class LetsMeshPacketDecoder:
|
||||
"""Decode LetsMesh packet payloads with `meshcore-decoder` CLI."""
|
||||
|
||||
class ChannelKey(NamedTuple):
|
||||
"""Channel key metadata for decryption and channel labeling."""
|
||||
|
||||
label: str | None
|
||||
key_hex: str
|
||||
channel_hash: str
|
||||
|
||||
# Built-in keys required by your deployment.
|
||||
# - Public channel
|
||||
# - #test channel
|
||||
BUILTIN_CHANNEL_KEYS: tuple[tuple[str, str], ...] = (
|
||||
("Public", "8B3387E9C5CDEA6AC9E5EDBAA115CD72"),
|
||||
("test", "9CD8FCF22A47333B591D96A2B848B73F"),
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
enabled: bool = True,
|
||||
command: str = "meshcore-decoder",
|
||||
channel_keys: list[str] | None = None,
|
||||
timeout_seconds: float = 2.0,
|
||||
) -> None:
|
||||
self._enabled = enabled
|
||||
self._command_tokens = shlex.split(command.strip()) if command.strip() else []
|
||||
self._channel_key_infos = self._normalize_channel_keys(channel_keys or [])
|
||||
self._channel_keys = [info.key_hex for info in self._channel_key_infos]
|
||||
self._channel_names_by_hash = {
|
||||
info.channel_hash: info.label
|
||||
for info in self._channel_key_infos
|
||||
if info.label
|
||||
}
|
||||
self._decode_cache: dict[str, dict[str, Any] | None] = {}
|
||||
self._decode_cache_maxsize = 2048
|
||||
self._timeout_seconds = timeout_seconds
|
||||
self._checked_command = False
|
||||
self._command_available = False
|
||||
self._warned_unavailable = False
|
||||
|
||||
@classmethod
|
||||
def _normalize_channel_keys(cls, values: list[str]) -> list[ChannelKey]:
|
||||
"""Normalize key list (labels + key + channel hash, deduplicated)."""
|
||||
normalized: list[LetsMeshPacketDecoder.ChannelKey] = []
|
||||
seen_keys: set[str] = set()
|
||||
|
||||
for label, key in cls.BUILTIN_CHANNEL_KEYS:
|
||||
entry = cls._normalize_channel_entry(f"{label}={key}")
|
||||
if not entry:
|
||||
continue
|
||||
if entry.key_hex in seen_keys:
|
||||
continue
|
||||
normalized.append(entry)
|
||||
seen_keys.add(entry.key_hex)
|
||||
|
||||
for value in values:
|
||||
entry = cls._normalize_channel_entry(value)
|
||||
if not entry:
|
||||
continue
|
||||
if entry.key_hex in seen_keys:
|
||||
continue
|
||||
normalized.append(entry)
|
||||
seen_keys.add(entry.key_hex)
|
||||
|
||||
return normalized
|
||||
|
||||
@classmethod
|
||||
def _normalize_channel_entry(cls, value: str | None) -> ChannelKey | None:
|
||||
"""Normalize one key entry (`label=hex`, `label:hex`, or `hex`)."""
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
candidate = value.strip()
|
||||
if not candidate:
|
||||
return None
|
||||
|
||||
label: str | None = None
|
||||
key_candidate = candidate
|
||||
for separator in ("=", ":"):
|
||||
if separator not in candidate:
|
||||
continue
|
||||
left, right = candidate.split(separator, 1)
|
||||
right = right.strip()
|
||||
right = right.removeprefix("0x").removeprefix("0X").strip()
|
||||
if right and cls._is_hex(right):
|
||||
label = left.strip().lstrip("#")
|
||||
key_candidate = right
|
||||
break
|
||||
|
||||
key_candidate = key_candidate.strip()
|
||||
key_candidate = key_candidate.removeprefix("0x").removeprefix("0X").strip()
|
||||
if not key_candidate or not cls._is_hex(key_candidate):
|
||||
return None
|
||||
|
||||
key_hex = key_candidate.upper()
|
||||
channel_hash = cls._compute_channel_hash(key_hex)
|
||||
normalized_label = label.strip() if label and label.strip() else None
|
||||
return cls.ChannelKey(
|
||||
label=normalized_label,
|
||||
key_hex=key_hex,
|
||||
channel_hash=channel_hash,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _is_hex(value: str) -> bool:
|
||||
"""Return True if string contains only hex digits."""
|
||||
return bool(value) and all(char in string.hexdigits for char in value)
|
||||
|
||||
@staticmethod
|
||||
def _compute_channel_hash(key_hex: str) -> str:
|
||||
"""Compute channel hash (first byte of SHA-256 of channel key)."""
|
||||
return hashlib.sha256(bytes.fromhex(key_hex)).digest()[:1].hex().upper()
|
||||
|
||||
def channel_name_from_decoded(
|
||||
self,
|
||||
decoded_packet: dict[str, Any] | None,
|
||||
) -> str | None:
|
||||
"""Resolve channel label from decoded payload channel hash."""
|
||||
if not isinstance(decoded_packet, dict):
|
||||
return None
|
||||
|
||||
payload = decoded_packet.get("payload")
|
||||
if not isinstance(payload, dict):
|
||||
return None
|
||||
|
||||
decoded = payload.get("decoded")
|
||||
if not isinstance(decoded, dict):
|
||||
return None
|
||||
|
||||
channel_hash = decoded.get("channelHash")
|
||||
if not isinstance(channel_hash, str):
|
||||
return None
|
||||
|
||||
return self._channel_names_by_hash.get(channel_hash.upper())
|
||||
|
||||
def channel_labels_by_index(self) -> dict[int, str]:
|
||||
"""Return channel labels keyed by numeric channel index (0-255)."""
|
||||
labels: dict[int, str] = {}
|
||||
for info in self._channel_key_infos:
|
||||
if not info.label:
|
||||
continue
|
||||
|
||||
label = info.label.strip()
|
||||
if not label:
|
||||
continue
|
||||
|
||||
if label.lower() == "public":
|
||||
normalized_label = "Public"
|
||||
else:
|
||||
normalized_label = label if label.startswith("#") else f"#{label}"
|
||||
|
||||
channel_idx = int(info.channel_hash, 16)
|
||||
labels.setdefault(channel_idx, normalized_label)
|
||||
|
||||
return labels
|
||||
|
||||
def decode_payload(self, payload: dict[str, Any]) -> dict[str, Any] | None:
|
||||
"""Decode packet payload `raw` hex and return decoded JSON if available."""
|
||||
raw_hex = payload.get("raw")
|
||||
if not isinstance(raw_hex, str):
|
||||
return None
|
||||
clean_hex = raw_hex.strip()
|
||||
if not clean_hex:
|
||||
return None
|
||||
if not self._is_hex(clean_hex):
|
||||
logger.debug("LetsMesh decoder skipped non-hex raw payload")
|
||||
return None
|
||||
cached = self._decode_cache.get(clean_hex)
|
||||
if clean_hex in self._decode_cache:
|
||||
return cached
|
||||
|
||||
decoded = self._decode_raw(clean_hex)
|
||||
self._decode_cache[clean_hex] = decoded
|
||||
if len(self._decode_cache) > self._decode_cache_maxsize:
|
||||
# Drop oldest cached payload (insertion-order dict).
|
||||
self._decode_cache.pop(next(iter(self._decode_cache)))
|
||||
return decoded
|
||||
|
||||
def _decode_raw(self, raw_hex: str) -> dict[str, Any] | None:
|
||||
"""Decode raw packet hex with decoder CLI (cached per packet hex)."""
|
||||
if not self._enabled:
|
||||
return None
|
||||
if not self._is_command_available():
|
||||
return None
|
||||
|
||||
command = [*self._command_tokens, "decode", raw_hex, "--json"]
|
||||
if self._channel_keys:
|
||||
command.append("--key")
|
||||
command.extend(self._channel_keys)
|
||||
|
||||
try:
|
||||
result = subprocess.run(
|
||||
command,
|
||||
check=False,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=self._timeout_seconds,
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
logger.debug(
|
||||
"LetsMesh decoder timed out after %.2fs",
|
||||
self._timeout_seconds,
|
||||
)
|
||||
return None
|
||||
except OSError as exc:
|
||||
logger.debug("LetsMesh decoder failed to execute: %s", exc)
|
||||
return None
|
||||
|
||||
if result.returncode != 0:
|
||||
stderr = result.stderr.strip() if result.stderr else ""
|
||||
logger.debug(
|
||||
"LetsMesh decoder exited with code %s%s",
|
||||
result.returncode,
|
||||
f": {stderr}" if stderr else "",
|
||||
)
|
||||
return None
|
||||
|
||||
output = result.stdout.strip()
|
||||
if not output:
|
||||
return None
|
||||
|
||||
try:
|
||||
decoded = json.loads(output)
|
||||
except json.JSONDecodeError:
|
||||
logger.debug("LetsMesh decoder returned non-JSON output")
|
||||
return None
|
||||
|
||||
return decoded if isinstance(decoded, dict) else None
|
||||
|
||||
def _is_command_available(self) -> bool:
|
||||
"""Check decoder command availability once."""
|
||||
if self._checked_command:
|
||||
return self._command_available
|
||||
|
||||
self._checked_command = True
|
||||
if not self._command_tokens:
|
||||
self._command_available = False
|
||||
else:
|
||||
command = self._command_tokens[0]
|
||||
if "/" in command:
|
||||
self._command_available = shutil.which(command) is not None
|
||||
else:
|
||||
self._command_available = shutil.which(command) is not None
|
||||
|
||||
if not self._command_available and not self._warned_unavailable:
|
||||
self._warned_unavailable = True
|
||||
command_text = " ".join(self._command_tokens) or "<empty>"
|
||||
logger.warning(
|
||||
"LetsMesh decoder command not found (%s). "
|
||||
"Messages will remain encrypted placeholders until decoder is installed.",
|
||||
command_text,
|
||||
)
|
||||
|
||||
return self._command_available
|
||||
1081
src/meshcore_hub/collector/letsmesh_normalizer.py
Normal file
1081
src/meshcore_hub/collector/letsmesh_normalizer.py
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,11 +1,11 @@
|
||||
"""Import members from JSON file."""
|
||||
"""Import members from YAML file."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
import yaml
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import select
|
||||
|
||||
from meshcore_hub.common.database import DatabaseManager
|
||||
@@ -15,47 +15,46 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class MemberData(BaseModel):
|
||||
"""Schema for a member entry in the import file."""
|
||||
"""Schema for a member entry in the import file.
|
||||
|
||||
Note: Nodes are associated with members via a 'member_id' tag on the node,
|
||||
not through this schema.
|
||||
"""
|
||||
|
||||
member_id: str = Field(..., min_length=1, max_length=100)
|
||||
name: str = Field(..., min_length=1, max_length=255)
|
||||
callsign: Optional[str] = Field(default=None, max_length=20)
|
||||
role: Optional[str] = Field(default=None, max_length=100)
|
||||
description: Optional[str] = Field(default=None)
|
||||
contact: Optional[str] = Field(default=None, max_length=255)
|
||||
public_key: Optional[str] = Field(default=None)
|
||||
|
||||
@field_validator("public_key")
|
||||
@classmethod
|
||||
def validate_public_key(cls, v: Optional[str]) -> Optional[str]:
|
||||
"""Validate and normalize public key if provided."""
|
||||
if v is None:
|
||||
return None
|
||||
if len(v) != 64:
|
||||
raise ValueError(f"public_key must be 64 characters, got {len(v)}")
|
||||
if not all(c in "0123456789abcdefABCDEF" for c in v):
|
||||
raise ValueError("public_key must be a valid hex string")
|
||||
return v.lower()
|
||||
|
||||
|
||||
def load_members_file(file_path: str | Path) -> list[dict[str, Any]]:
|
||||
"""Load and validate members from a JSON file.
|
||||
"""Load and validate members from a YAML file.
|
||||
|
||||
Supports two formats:
|
||||
1. List of member objects:
|
||||
[{"name": "Member 1", ...}, {"name": "Member 2", ...}]
|
||||
|
||||
- member_id: member1
|
||||
name: Member 1
|
||||
callsign: M1
|
||||
|
||||
2. Object with "members" key:
|
||||
{"members": [{"name": "Member 1", ...}, ...]}
|
||||
|
||||
members:
|
||||
- member_id: member1
|
||||
name: Member 1
|
||||
callsign: M1
|
||||
|
||||
Args:
|
||||
file_path: Path to the members JSON file
|
||||
file_path: Path to the members YAML file
|
||||
|
||||
Returns:
|
||||
List of validated member dictionaries
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If file does not exist
|
||||
json.JSONDecodeError: If file is not valid JSON
|
||||
yaml.YAMLError: If file is not valid YAML
|
||||
ValueError: If file content is invalid
|
||||
"""
|
||||
path = Path(file_path)
|
||||
@@ -63,7 +62,7 @@ def load_members_file(file_path: str | Path) -> list[dict[str, Any]]:
|
||||
raise FileNotFoundError(f"Members file not found: {file_path}")
|
||||
|
||||
with open(path, "r") as f:
|
||||
data = json.load(f)
|
||||
data = yaml.safe_load(f)
|
||||
|
||||
# Handle both formats
|
||||
if isinstance(data, list):
|
||||
@@ -73,15 +72,15 @@ def load_members_file(file_path: str | Path) -> list[dict[str, Any]]:
|
||||
if not isinstance(members_list, list):
|
||||
raise ValueError("'members' key must contain a list")
|
||||
else:
|
||||
raise ValueError(
|
||||
"Members file must be a list or an object with 'members' key"
|
||||
)
|
||||
raise ValueError("Members file must be a list or a mapping with 'members' key")
|
||||
|
||||
# Validate each member
|
||||
validated: list[dict[str, Any]] = []
|
||||
for i, member in enumerate(members_list):
|
||||
if not isinstance(member, dict):
|
||||
raise ValueError(f"Member at index {i} must be an object")
|
||||
if "member_id" not in member:
|
||||
raise ValueError(f"Member at index {i} must have a 'member_id' field")
|
||||
if "name" not in member:
|
||||
raise ValueError(f"Member at index {i} must have a 'name' field")
|
||||
|
||||
@@ -99,13 +98,16 @@ def import_members(
|
||||
file_path: str | Path,
|
||||
db: DatabaseManager,
|
||||
) -> dict[str, Any]:
|
||||
"""Import members from a JSON file into the database.
|
||||
"""Import members from a YAML file into the database.
|
||||
|
||||
Performs upsert operations based on name - existing members are updated,
|
||||
Performs upsert operations based on member_id - existing members are updated,
|
||||
new members are created.
|
||||
|
||||
Note: Nodes are associated with members via a 'member_id' tag on the node.
|
||||
This import does not manage node associations.
|
||||
|
||||
Args:
|
||||
file_path: Path to the members JSON file
|
||||
file_path: Path to the members YAML file
|
||||
db: Database manager instance
|
||||
|
||||
Returns:
|
||||
@@ -134,14 +136,17 @@ def import_members(
|
||||
with db.session_scope() as session:
|
||||
for member_data in members_data:
|
||||
try:
|
||||
member_id = member_data["member_id"]
|
||||
name = member_data["name"]
|
||||
|
||||
# Find existing member by name
|
||||
query = select(Member).where(Member.name == name)
|
||||
# Find existing member by member_id
|
||||
query = select(Member).where(Member.member_id == member_id)
|
||||
existing = session.execute(query).scalar_one_or_none()
|
||||
|
||||
if existing:
|
||||
# Update existing member
|
||||
if member_data.get("name") is not None:
|
||||
existing.name = member_data["name"]
|
||||
if member_data.get("callsign") is not None:
|
||||
existing.callsign = member_data["callsign"]
|
||||
if member_data.get("role") is not None:
|
||||
@@ -150,27 +155,26 @@ def import_members(
|
||||
existing.description = member_data["description"]
|
||||
if member_data.get("contact") is not None:
|
||||
existing.contact = member_data["contact"]
|
||||
if member_data.get("public_key") is not None:
|
||||
existing.public_key = member_data["public_key"]
|
||||
|
||||
stats["updated"] += 1
|
||||
logger.debug(f"Updated member: {name}")
|
||||
logger.debug(f"Updated member: {member_id} ({name})")
|
||||
else:
|
||||
# Create new member
|
||||
new_member = Member(
|
||||
member_id=member_id,
|
||||
name=name,
|
||||
callsign=member_data.get("callsign"),
|
||||
role=member_data.get("role"),
|
||||
description=member_data.get("description"),
|
||||
contact=member_data.get("contact"),
|
||||
public_key=member_data.get("public_key"),
|
||||
)
|
||||
session.add(new_member)
|
||||
|
||||
stats["created"] += 1
|
||||
logger.debug(f"Created member: {name}")
|
||||
logger.debug(f"Created member: {member_id} ({name})")
|
||||
|
||||
except Exception as e:
|
||||
error_msg = f"Error processing member '{member_data.get('name', 'unknown')}': {e}"
|
||||
error_msg = f"Error processing member '{member_data.get('member_id', 'unknown')}' ({member_data.get('name', 'unknown')}): {e}"
|
||||
stats["errors"].append(error_msg)
|
||||
logger.error(error_msg)
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ The subscriber:
|
||||
3. Routes events to appropriate handlers
|
||||
4. Persists data to database
|
||||
5. Dispatches events to configured webhooks
|
||||
6. Performs scheduled data cleanup if enabled
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
@@ -14,11 +15,14 @@ import signal
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Callable, Optional, TYPE_CHECKING
|
||||
|
||||
from meshcore_hub.common.database import DatabaseManager
|
||||
from meshcore_hub.common.health import HealthReporter
|
||||
from meshcore_hub.common.mqtt import MQTTClient, MQTTConfig
|
||||
from meshcore_hub.collector.letsmesh_decoder import LetsMeshPacketDecoder
|
||||
from meshcore_hub.collector.letsmesh_normalizer import LetsMeshNormalizer
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from meshcore_hub.collector.webhook import WebhookDispatcher
|
||||
@@ -30,14 +34,27 @@ logger = logging.getLogger(__name__)
|
||||
EventHandler = Callable[[str, str, dict[str, Any], DatabaseManager], None]
|
||||
|
||||
|
||||
class Subscriber:
|
||||
class Subscriber(LetsMeshNormalizer):
|
||||
"""MQTT Subscriber for collecting and storing MeshCore events."""
|
||||
|
||||
INGEST_MODE_NATIVE = "native"
|
||||
INGEST_MODE_LETSMESH_UPLOAD = "letsmesh_upload"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
mqtt_client: MQTTClient,
|
||||
db_manager: DatabaseManager,
|
||||
webhook_dispatcher: Optional["WebhookDispatcher"] = None,
|
||||
cleanup_enabled: bool = False,
|
||||
cleanup_retention_days: int = 30,
|
||||
cleanup_interval_hours: int = 24,
|
||||
node_cleanup_enabled: bool = False,
|
||||
node_cleanup_days: int = 90,
|
||||
ingest_mode: str = INGEST_MODE_NATIVE,
|
||||
letsmesh_decoder_enabled: bool = True,
|
||||
letsmesh_decoder_command: str = "meshcore-decoder",
|
||||
letsmesh_decoder_channel_keys: list[str] | None = None,
|
||||
letsmesh_decoder_timeout_seconds: float = 2.0,
|
||||
):
|
||||
"""Initialize subscriber.
|
||||
|
||||
@@ -45,6 +62,16 @@ class Subscriber:
|
||||
mqtt_client: MQTT client instance
|
||||
db_manager: Database manager instance
|
||||
webhook_dispatcher: Optional webhook dispatcher for event forwarding
|
||||
cleanup_enabled: Enable automatic event data cleanup
|
||||
cleanup_retention_days: Number of days to retain event data
|
||||
cleanup_interval_hours: Hours between cleanup runs
|
||||
node_cleanup_enabled: Enable automatic cleanup of inactive nodes
|
||||
node_cleanup_days: Remove nodes not seen for this many days
|
||||
ingest_mode: Ingest mode ('native' or 'letsmesh_upload')
|
||||
letsmesh_decoder_enabled: Enable external LetsMesh packet decoder
|
||||
letsmesh_decoder_command: Decoder CLI command
|
||||
letsmesh_decoder_channel_keys: Optional channel keys for decrypting group text
|
||||
letsmesh_decoder_timeout_seconds: Decoder CLI timeout
|
||||
"""
|
||||
self.mqtt = mqtt_client
|
||||
self.db = db_manager
|
||||
@@ -59,6 +86,26 @@ class Subscriber:
|
||||
self._webhook_queue: list[tuple[str, dict[str, Any], str]] = []
|
||||
self._webhook_lock = threading.Lock()
|
||||
self._webhook_thread: Optional[threading.Thread] = None
|
||||
# Data cleanup
|
||||
self._cleanup_enabled = cleanup_enabled
|
||||
self._cleanup_retention_days = cleanup_retention_days
|
||||
self._cleanup_interval_hours = cleanup_interval_hours
|
||||
self._node_cleanup_enabled = node_cleanup_enabled
|
||||
self._node_cleanup_days = node_cleanup_days
|
||||
self._cleanup_thread: Optional[threading.Thread] = None
|
||||
self._last_cleanup: Optional[datetime] = None
|
||||
self._ingest_mode = ingest_mode.lower()
|
||||
if self._ingest_mode not in {
|
||||
self.INGEST_MODE_NATIVE,
|
||||
self.INGEST_MODE_LETSMESH_UPLOAD,
|
||||
}:
|
||||
raise ValueError(f"Unsupported collector ingest mode: {ingest_mode}")
|
||||
self._letsmesh_decoder = LetsMeshPacketDecoder(
|
||||
enabled=letsmesh_decoder_enabled,
|
||||
command=letsmesh_decoder_command,
|
||||
channel_keys=letsmesh_decoder_channel_keys,
|
||||
timeout_seconds=letsmesh_decoder_timeout_seconds,
|
||||
)
|
||||
|
||||
@property
|
||||
def is_healthy(self) -> bool:
|
||||
@@ -105,14 +152,34 @@ class Subscriber:
|
||||
pattern: Subscription pattern
|
||||
payload: Message payload
|
||||
"""
|
||||
# Parse event from topic
|
||||
parsed = self.mqtt.topic_builder.parse_event_topic(topic)
|
||||
parsed: tuple[str, str, dict[str, Any]] | None
|
||||
if self._ingest_mode == self.INGEST_MODE_LETSMESH_UPLOAD:
|
||||
parsed = self._normalize_letsmesh_event(topic, payload)
|
||||
else:
|
||||
parsed_event = self.mqtt.topic_builder.parse_event_topic(topic)
|
||||
parsed = (
|
||||
(parsed_event[0], parsed_event[1], payload) if parsed_event else None
|
||||
)
|
||||
|
||||
if not parsed:
|
||||
logger.warning(f"Could not parse event topic: {topic}")
|
||||
logger.warning(
|
||||
"Could not parse topic for ingest mode %s: %s",
|
||||
self._ingest_mode,
|
||||
topic,
|
||||
)
|
||||
return
|
||||
|
||||
public_key, event_type = parsed
|
||||
logger.debug(f"Received event: {event_type} from {public_key[:12]}...")
|
||||
public_key, event_type, normalized_payload = parsed
|
||||
logger.debug("Received event: %s from %s...", event_type, public_key[:12])
|
||||
self._dispatch_event(public_key, event_type, normalized_payload)
|
||||
|
||||
def _dispatch_event(
|
||||
self,
|
||||
public_key: str,
|
||||
event_type: str,
|
||||
payload: dict[str, Any],
|
||||
) -> None:
|
||||
"""Route a normalized event to the appropriate handler."""
|
||||
|
||||
# Find and call handler
|
||||
handler = self._handlers.get(event_type)
|
||||
@@ -202,18 +269,129 @@ class Subscriber:
|
||||
if self._webhook_thread.is_alive():
|
||||
logger.warning("Webhook processor thread did not stop cleanly")
|
||||
|
||||
def _start_cleanup_scheduler(self) -> None:
|
||||
"""Start background thread for periodic data cleanup."""
|
||||
if not self._cleanup_enabled and not self._node_cleanup_enabled:
|
||||
logger.info("Data cleanup and node cleanup are both disabled")
|
||||
return
|
||||
|
||||
logger.info(
|
||||
"Starting cleanup scheduler (interval_hours=%d)",
|
||||
self._cleanup_interval_hours,
|
||||
)
|
||||
if self._cleanup_enabled:
|
||||
logger.info(
|
||||
" Event data cleanup: ENABLED (retention_days=%d)",
|
||||
self._cleanup_retention_days,
|
||||
)
|
||||
else:
|
||||
logger.info(" Event data cleanup: DISABLED")
|
||||
|
||||
if self._node_cleanup_enabled:
|
||||
logger.info(
|
||||
" Node cleanup: ENABLED (inactivity_days=%d)", self._node_cleanup_days
|
||||
)
|
||||
else:
|
||||
logger.info(" Node cleanup: DISABLED")
|
||||
|
||||
def run_cleanup_loop() -> None:
|
||||
"""Run async cleanup tasks in background thread."""
|
||||
loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(loop)
|
||||
|
||||
try:
|
||||
while self._running:
|
||||
# Check if cleanup is due
|
||||
now = datetime.now(timezone.utc)
|
||||
should_run = False
|
||||
|
||||
if self._last_cleanup is None:
|
||||
# First run
|
||||
should_run = True
|
||||
else:
|
||||
# Check if interval has passed
|
||||
hours_since_last = (
|
||||
now - self._last_cleanup
|
||||
).total_seconds() / 3600
|
||||
should_run = hours_since_last >= self._cleanup_interval_hours
|
||||
|
||||
if should_run:
|
||||
try:
|
||||
logger.info("Starting scheduled cleanup")
|
||||
from meshcore_hub.collector.cleanup import (
|
||||
cleanup_old_data,
|
||||
cleanup_inactive_nodes,
|
||||
)
|
||||
|
||||
# Get async session and run cleanup
|
||||
async def run_cleanup() -> None:
|
||||
async with self.db.async_session() as session:
|
||||
# Run event data cleanup if enabled
|
||||
if self._cleanup_enabled:
|
||||
stats = await cleanup_old_data(
|
||||
session,
|
||||
self._cleanup_retention_days,
|
||||
dry_run=False,
|
||||
)
|
||||
logger.info(
|
||||
"Event cleanup completed: %s", stats
|
||||
)
|
||||
|
||||
# Run node cleanup if enabled
|
||||
if self._node_cleanup_enabled:
|
||||
nodes_deleted = await cleanup_inactive_nodes(
|
||||
session,
|
||||
self._node_cleanup_days,
|
||||
dry_run=False,
|
||||
)
|
||||
logger.info(
|
||||
"Node cleanup completed: %d nodes deleted",
|
||||
nodes_deleted,
|
||||
)
|
||||
|
||||
loop.run_until_complete(run_cleanup())
|
||||
self._last_cleanup = now
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Cleanup error: {e}", exc_info=True)
|
||||
|
||||
# Sleep for 1 hour before next check
|
||||
for _ in range(3600):
|
||||
if not self._running:
|
||||
break
|
||||
time.sleep(1)
|
||||
|
||||
finally:
|
||||
loop.close()
|
||||
logger.info("Cleanup scheduler stopped")
|
||||
|
||||
self._cleanup_thread = threading.Thread(
|
||||
target=run_cleanup_loop, daemon=True, name="cleanup-scheduler"
|
||||
)
|
||||
self._cleanup_thread.start()
|
||||
|
||||
def _stop_cleanup_scheduler(self) -> None:
|
||||
"""Stop the cleanup scheduler thread."""
|
||||
if self._cleanup_thread and self._cleanup_thread.is_alive():
|
||||
# Thread will exit when self._running becomes False
|
||||
self._cleanup_thread.join(timeout=5.0)
|
||||
if self._cleanup_thread.is_alive():
|
||||
logger.warning("Cleanup scheduler thread did not stop cleanly")
|
||||
|
||||
def start(self) -> None:
|
||||
"""Start the subscriber."""
|
||||
logger.info("Starting collector subscriber")
|
||||
|
||||
# Create database tables if needed
|
||||
# Verify database connection (schema managed by Alembic migrations)
|
||||
try:
|
||||
self.db.create_tables()
|
||||
# Test connection by getting a session
|
||||
session = self.db.get_session()
|
||||
session.close()
|
||||
self._db_connected = True
|
||||
logger.info("Database initialized")
|
||||
logger.info("Database connection verified")
|
||||
except Exception as e:
|
||||
self._db_connected = False
|
||||
logger.error(f"Failed to initialize database: {e}")
|
||||
logger.error(f"Failed to connect to database: {e}")
|
||||
raise
|
||||
|
||||
# Connect to MQTT broker
|
||||
@@ -227,16 +405,29 @@ class Subscriber:
|
||||
logger.error(f"Failed to connect to MQTT broker: {e}")
|
||||
raise
|
||||
|
||||
# Subscribe to all event topics
|
||||
event_topic = self.mqtt.topic_builder.all_events_topic()
|
||||
self.mqtt.subscribe(event_topic, self._handle_mqtt_message)
|
||||
logger.info(f"Subscribed to event topic: {event_topic}")
|
||||
# Subscribe to topics based on ingest mode
|
||||
if self._ingest_mode == self.INGEST_MODE_LETSMESH_UPLOAD:
|
||||
letsmesh_topics = [
|
||||
f"{self.mqtt.topic_builder.prefix}/+/packets",
|
||||
f"{self.mqtt.topic_builder.prefix}/+/status",
|
||||
f"{self.mqtt.topic_builder.prefix}/+/internal",
|
||||
]
|
||||
for letsmesh_topic in letsmesh_topics:
|
||||
self.mqtt.subscribe(letsmesh_topic, self._handle_mqtt_message)
|
||||
logger.info(f"Subscribed to LetsMesh upload topic: {letsmesh_topic}")
|
||||
else:
|
||||
event_topic = self.mqtt.topic_builder.all_events_topic()
|
||||
self.mqtt.subscribe(event_topic, self._handle_mqtt_message)
|
||||
logger.info(f"Subscribed to event topic: {event_topic}")
|
||||
|
||||
self._running = True
|
||||
|
||||
# Start webhook processor if configured
|
||||
self._start_webhook_processor()
|
||||
|
||||
# Start cleanup scheduler if configured
|
||||
self._start_cleanup_scheduler()
|
||||
|
||||
# Start health reporter for Docker health checks
|
||||
self._health_reporter = HealthReporter(
|
||||
component="collector",
|
||||
@@ -269,6 +460,9 @@ class Subscriber:
|
||||
self._running = False
|
||||
self._shutdown_event.set()
|
||||
|
||||
# Stop cleanup scheduler
|
||||
self._stop_cleanup_scheduler()
|
||||
|
||||
# Stop webhook processor
|
||||
self._stop_webhook_processor()
|
||||
|
||||
@@ -291,8 +485,21 @@ def create_subscriber(
|
||||
mqtt_username: Optional[str] = None,
|
||||
mqtt_password: Optional[str] = None,
|
||||
mqtt_prefix: str = "meshcore",
|
||||
mqtt_tls: bool = False,
|
||||
mqtt_transport: str = "tcp",
|
||||
mqtt_ws_path: str = "/mqtt",
|
||||
ingest_mode: str = "native",
|
||||
database_url: str = "sqlite:///./meshcore.db",
|
||||
webhook_dispatcher: Optional["WebhookDispatcher"] = None,
|
||||
cleanup_enabled: bool = False,
|
||||
cleanup_retention_days: int = 30,
|
||||
cleanup_interval_hours: int = 24,
|
||||
node_cleanup_enabled: bool = False,
|
||||
node_cleanup_days: int = 90,
|
||||
letsmesh_decoder_enabled: bool = True,
|
||||
letsmesh_decoder_command: str = "meshcore-decoder",
|
||||
letsmesh_decoder_channel_keys: list[str] | None = None,
|
||||
letsmesh_decoder_timeout_seconds: float = 2.0,
|
||||
) -> Subscriber:
|
||||
"""Create a configured subscriber instance.
|
||||
|
||||
@@ -302,8 +509,21 @@ def create_subscriber(
|
||||
mqtt_username: MQTT username
|
||||
mqtt_password: MQTT password
|
||||
mqtt_prefix: MQTT topic prefix
|
||||
mqtt_tls: Enable TLS/SSL for MQTT connection
|
||||
mqtt_transport: MQTT transport protocol (tcp or websockets)
|
||||
mqtt_ws_path: WebSocket path (used when transport=websockets)
|
||||
ingest_mode: Ingest mode ('native' or 'letsmesh_upload')
|
||||
database_url: Database connection URL
|
||||
webhook_dispatcher: Optional webhook dispatcher for event forwarding
|
||||
cleanup_enabled: Enable automatic event data cleanup
|
||||
cleanup_retention_days: Number of days to retain event data
|
||||
cleanup_interval_hours: Hours between cleanup runs
|
||||
node_cleanup_enabled: Enable automatic cleanup of inactive nodes
|
||||
node_cleanup_days: Remove nodes not seen for this many days
|
||||
letsmesh_decoder_enabled: Enable external LetsMesh packet decoder
|
||||
letsmesh_decoder_command: Decoder CLI command
|
||||
letsmesh_decoder_channel_keys: Optional channel keys for decrypting group text
|
||||
letsmesh_decoder_timeout_seconds: Decoder CLI timeout
|
||||
|
||||
Returns:
|
||||
Configured Subscriber instance
|
||||
@@ -317,6 +537,9 @@ def create_subscriber(
|
||||
password=mqtt_password,
|
||||
prefix=mqtt_prefix,
|
||||
client_id=f"meshcore-collector-{unique_id}",
|
||||
tls=mqtt_tls,
|
||||
transport=mqtt_transport,
|
||||
ws_path=mqtt_ws_path,
|
||||
)
|
||||
mqtt_client = MQTTClient(mqtt_config)
|
||||
|
||||
@@ -324,7 +547,21 @@ def create_subscriber(
|
||||
db_manager = DatabaseManager(database_url)
|
||||
|
||||
# Create subscriber
|
||||
subscriber = Subscriber(mqtt_client, db_manager, webhook_dispatcher)
|
||||
subscriber = Subscriber(
|
||||
mqtt_client,
|
||||
db_manager,
|
||||
webhook_dispatcher,
|
||||
cleanup_enabled=cleanup_enabled,
|
||||
cleanup_retention_days=cleanup_retention_days,
|
||||
cleanup_interval_hours=cleanup_interval_hours,
|
||||
node_cleanup_enabled=node_cleanup_enabled,
|
||||
node_cleanup_days=node_cleanup_days,
|
||||
ingest_mode=ingest_mode,
|
||||
letsmesh_decoder_enabled=letsmesh_decoder_enabled,
|
||||
letsmesh_decoder_command=letsmesh_decoder_command,
|
||||
letsmesh_decoder_channel_keys=letsmesh_decoder_channel_keys,
|
||||
letsmesh_decoder_timeout_seconds=letsmesh_decoder_timeout_seconds,
|
||||
)
|
||||
|
||||
# Register handlers
|
||||
from meshcore_hub.collector.handlers import register_all_handlers
|
||||
@@ -340,8 +577,21 @@ def run_collector(
|
||||
mqtt_username: Optional[str] = None,
|
||||
mqtt_password: Optional[str] = None,
|
||||
mqtt_prefix: str = "meshcore",
|
||||
mqtt_tls: bool = False,
|
||||
mqtt_transport: str = "tcp",
|
||||
mqtt_ws_path: str = "/mqtt",
|
||||
ingest_mode: str = "native",
|
||||
database_url: str = "sqlite:///./meshcore.db",
|
||||
webhook_dispatcher: Optional["WebhookDispatcher"] = None,
|
||||
cleanup_enabled: bool = False,
|
||||
cleanup_retention_days: int = 30,
|
||||
cleanup_interval_hours: int = 24,
|
||||
node_cleanup_enabled: bool = False,
|
||||
node_cleanup_days: int = 90,
|
||||
letsmesh_decoder_enabled: bool = True,
|
||||
letsmesh_decoder_command: str = "meshcore-decoder",
|
||||
letsmesh_decoder_channel_keys: list[str] | None = None,
|
||||
letsmesh_decoder_timeout_seconds: float = 2.0,
|
||||
) -> None:
|
||||
"""Run the collector (blocking).
|
||||
|
||||
@@ -351,8 +601,21 @@ def run_collector(
|
||||
mqtt_username: MQTT username
|
||||
mqtt_password: MQTT password
|
||||
mqtt_prefix: MQTT topic prefix
|
||||
mqtt_tls: Enable TLS/SSL for MQTT connection
|
||||
mqtt_transport: MQTT transport protocol (tcp or websockets)
|
||||
mqtt_ws_path: WebSocket path (used when transport=websockets)
|
||||
ingest_mode: Ingest mode ('native' or 'letsmesh_upload')
|
||||
database_url: Database connection URL
|
||||
webhook_dispatcher: Optional webhook dispatcher for event forwarding
|
||||
cleanup_enabled: Enable automatic event data cleanup
|
||||
cleanup_retention_days: Number of days to retain event data
|
||||
cleanup_interval_hours: Hours between cleanup runs
|
||||
node_cleanup_enabled: Enable automatic cleanup of inactive nodes
|
||||
node_cleanup_days: Remove nodes not seen for this many days
|
||||
letsmesh_decoder_enabled: Enable external LetsMesh packet decoder
|
||||
letsmesh_decoder_command: Decoder CLI command
|
||||
letsmesh_decoder_channel_keys: Optional channel keys for decrypting group text
|
||||
letsmesh_decoder_timeout_seconds: Decoder CLI timeout
|
||||
"""
|
||||
subscriber = create_subscriber(
|
||||
mqtt_host=mqtt_host,
|
||||
@@ -360,8 +623,21 @@ def run_collector(
|
||||
mqtt_username=mqtt_username,
|
||||
mqtt_password=mqtt_password,
|
||||
mqtt_prefix=mqtt_prefix,
|
||||
mqtt_tls=mqtt_tls,
|
||||
mqtt_transport=mqtt_transport,
|
||||
mqtt_ws_path=mqtt_ws_path,
|
||||
ingest_mode=ingest_mode,
|
||||
database_url=database_url,
|
||||
webhook_dispatcher=webhook_dispatcher,
|
||||
cleanup_enabled=cleanup_enabled,
|
||||
cleanup_retention_days=cleanup_retention_days,
|
||||
cleanup_interval_hours=cleanup_interval_hours,
|
||||
node_cleanup_enabled=node_cleanup_enabled,
|
||||
node_cleanup_days=node_cleanup_days,
|
||||
letsmesh_decoder_enabled=letsmesh_decoder_enabled,
|
||||
letsmesh_decoder_command=letsmesh_decoder_command,
|
||||
letsmesh_decoder_channel_keys=letsmesh_decoder_channel_keys,
|
||||
letsmesh_decoder_timeout_seconds=letsmesh_decoder_timeout_seconds,
|
||||
)
|
||||
|
||||
# Set up signal handlers
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
"""Import node tags from JSON file."""
|
||||
"""Import node tags from YAML file."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import yaml
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy import delete, func, select
|
||||
|
||||
from meshcore_hub.common.database import DatabaseManager
|
||||
from meshcore_hub.common.models import Node, NodeTag
|
||||
@@ -19,7 +19,7 @@ class TagValue(BaseModel):
|
||||
"""Schema for a tag value with type."""
|
||||
|
||||
value: str | None = None
|
||||
type: str = Field(default="string", pattern=r"^(string|number|boolean|coordinate)$")
|
||||
type: str = Field(default="string", pattern=r"^(string|number|boolean)$")
|
||||
|
||||
|
||||
class NodeTags(BaseModel):
|
||||
@@ -64,33 +64,33 @@ def validate_public_key(public_key: str) -> str:
|
||||
|
||||
|
||||
def load_tags_file(file_path: str | Path) -> dict[str, dict[str, Any]]:
|
||||
"""Load and validate tags from a JSON file.
|
||||
"""Load and validate tags from a YAML file.
|
||||
|
||||
New format - dictionary keyed by public_key:
|
||||
{
|
||||
"0123456789abcdef...": {
|
||||
"friendly_name": "My Node",
|
||||
"location": {"value": "52.0,1.0", "type": "coordinate"},
|
||||
"altitude": {"value": "150", "type": "number"}
|
||||
}
|
||||
}
|
||||
YAML format - dictionary keyed by public_key:
|
||||
|
||||
0123456789abcdef...:
|
||||
friendly_name: My Node
|
||||
location:
|
||||
value: "52.0,1.0"
|
||||
type: coordinate
|
||||
altitude:
|
||||
value: "150"
|
||||
type: number
|
||||
|
||||
Shorthand is allowed - string values are auto-converted:
|
||||
{
|
||||
"0123456789abcdef...": {
|
||||
"friendly_name": "My Node"
|
||||
}
|
||||
}
|
||||
|
||||
0123456789abcdef...:
|
||||
friendly_name: My Node
|
||||
|
||||
Args:
|
||||
file_path: Path to the tags JSON file
|
||||
file_path: Path to the tags YAML file
|
||||
|
||||
Returns:
|
||||
Dictionary mapping public_key to tag dictionary
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If file does not exist
|
||||
json.JSONDecodeError: If file is not valid JSON
|
||||
yaml.YAMLError: If file is not valid YAML
|
||||
ValueError: If file content is invalid
|
||||
"""
|
||||
path = Path(file_path)
|
||||
@@ -98,10 +98,10 @@ def load_tags_file(file_path: str | Path) -> dict[str, dict[str, Any]]:
|
||||
raise FileNotFoundError(f"Tags file not found: {file_path}")
|
||||
|
||||
with open(path, "r") as f:
|
||||
data = json.load(f)
|
||||
data = yaml.safe_load(f)
|
||||
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("Tags file must contain a JSON object")
|
||||
raise ValueError("Tags file must contain a YAML mapping")
|
||||
|
||||
# Validate each entry
|
||||
validated: dict[str, dict[str, Any]] = {}
|
||||
@@ -117,12 +117,24 @@ def load_tags_file(file_path: str | Path) -> dict[str, dict[str, Any]]:
|
||||
for tag_key, tag_value in tags.items():
|
||||
if isinstance(tag_value, dict):
|
||||
# Full format with value and type
|
||||
raw_value = tag_value.get("value")
|
||||
# Convert value to string if it's not None
|
||||
str_value = str(raw_value) if raw_value is not None else None
|
||||
validated_tags[tag_key] = {
|
||||
"value": tag_value.get("value"),
|
||||
"value": str_value,
|
||||
"type": tag_value.get("type", "string"),
|
||||
}
|
||||
elif isinstance(tag_value, bool):
|
||||
# YAML boolean - must check before int since bool is subclass of int
|
||||
validated_tags[tag_key] = {
|
||||
"value": str(tag_value).lower(),
|
||||
"type": "boolean",
|
||||
}
|
||||
elif isinstance(tag_value, (int, float)):
|
||||
# YAML number (int or float)
|
||||
validated_tags[tag_key] = {"value": str(tag_value), "type": "number"}
|
||||
elif isinstance(tag_value, str):
|
||||
# Shorthand: just a string value
|
||||
# String value
|
||||
validated_tags[tag_key] = {"value": tag_value, "type": "string"}
|
||||
elif tag_value is None:
|
||||
validated_tags[tag_key] = {"value": None, "type": "string"}
|
||||
@@ -139,16 +151,19 @@ def import_tags(
|
||||
file_path: str | Path,
|
||||
db: DatabaseManager,
|
||||
create_nodes: bool = True,
|
||||
clear_existing: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""Import tags from a JSON file into the database.
|
||||
"""Import tags from a YAML file into the database.
|
||||
|
||||
Performs upsert operations - existing tags are updated, new tags are created.
|
||||
Optionally clears all existing tags before import.
|
||||
|
||||
Args:
|
||||
file_path: Path to the tags JSON file
|
||||
file_path: Path to the tags YAML file
|
||||
db: Database manager instance
|
||||
create_nodes: If True, create nodes that don't exist. If False, skip tags
|
||||
for non-existent nodes.
|
||||
clear_existing: If True, delete all existing tags before importing.
|
||||
|
||||
Returns:
|
||||
Dictionary with import statistics:
|
||||
@@ -157,6 +172,7 @@ def import_tags(
|
||||
- updated: Number of existing tags updated
|
||||
- skipped: Number of tags skipped (node not found and create_nodes=False)
|
||||
- nodes_created: Number of new nodes created
|
||||
- deleted: Number of existing tags deleted (if clear_existing=True)
|
||||
- errors: List of error messages
|
||||
"""
|
||||
stats: dict[str, Any] = {
|
||||
@@ -165,6 +181,7 @@ def import_tags(
|
||||
"updated": 0,
|
||||
"skipped": 0,
|
||||
"nodes_created": 0,
|
||||
"deleted": 0,
|
||||
"errors": [],
|
||||
}
|
||||
|
||||
@@ -182,6 +199,15 @@ def import_tags(
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
with db.session_scope() as session:
|
||||
# Clear all existing tags if requested
|
||||
if clear_existing:
|
||||
delete_count = (
|
||||
session.execute(select(func.count()).select_from(NodeTag)).scalar() or 0
|
||||
)
|
||||
session.execute(delete(NodeTag))
|
||||
stats["deleted"] = delete_count
|
||||
logger.info(f"Deleted {delete_count} existing tags")
|
||||
|
||||
# Cache nodes by public_key to reduce queries
|
||||
node_cache: dict[str, Node] = {}
|
||||
|
||||
@@ -198,7 +224,8 @@ def import_tags(
|
||||
node = Node(
|
||||
public_key=public_key,
|
||||
first_seen=now,
|
||||
last_seen=now,
|
||||
# last_seen is intentionally left unset (None)
|
||||
# It will be set when the node is actually seen via events
|
||||
)
|
||||
session.add(node)
|
||||
session.flush()
|
||||
@@ -219,24 +246,8 @@ def import_tags(
|
||||
tag_value = tag_data.get("value")
|
||||
tag_type = tag_data.get("type", "string")
|
||||
|
||||
# Find or create tag
|
||||
tag_query = select(NodeTag).where(
|
||||
NodeTag.node_id == node.id,
|
||||
NodeTag.key == tag_key,
|
||||
)
|
||||
existing_tag = session.execute(tag_query).scalar_one_or_none()
|
||||
|
||||
if existing_tag:
|
||||
# Update existing tag
|
||||
existing_tag.value = tag_value
|
||||
existing_tag.value_type = tag_type
|
||||
stats["updated"] += 1
|
||||
logger.debug(
|
||||
f"Updated tag {tag_key}={tag_value} "
|
||||
f"for {public_key[:12]}..."
|
||||
)
|
||||
else:
|
||||
# Create new tag
|
||||
if clear_existing:
|
||||
# When clearing, always create new tags
|
||||
new_tag = NodeTag(
|
||||
node_id=node.id,
|
||||
key=tag_key,
|
||||
@@ -249,6 +260,39 @@ def import_tags(
|
||||
f"Created tag {tag_key}={tag_value} "
|
||||
f"for {public_key[:12]}..."
|
||||
)
|
||||
else:
|
||||
# Find or create tag
|
||||
tag_query = select(NodeTag).where(
|
||||
NodeTag.node_id == node.id,
|
||||
NodeTag.key == tag_key,
|
||||
)
|
||||
existing_tag = session.execute(
|
||||
tag_query
|
||||
).scalar_one_or_none()
|
||||
|
||||
if existing_tag:
|
||||
# Update existing tag
|
||||
existing_tag.value = tag_value
|
||||
existing_tag.value_type = tag_type
|
||||
stats["updated"] += 1
|
||||
logger.debug(
|
||||
f"Updated tag {tag_key}={tag_value} "
|
||||
f"for {public_key[:12]}..."
|
||||
)
|
||||
else:
|
||||
# Create new tag
|
||||
new_tag = NodeTag(
|
||||
node_id=node.id,
|
||||
key=tag_key,
|
||||
value=tag_value,
|
||||
value_type=tag_type,
|
||||
)
|
||||
session.add(new_tag)
|
||||
stats["created"] += 1
|
||||
logger.debug(
|
||||
f"Created tag {tag_key}={tag_value} "
|
||||
f"for {public_key[:12]}..."
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
error_msg = f"Error processing tag {tag_key} for {public_key[:12]}...: {e}"
|
||||
|
||||
@@ -404,7 +404,7 @@ _dispatch_callback: Optional[Callable[[str, dict[str, Any], Optional[str]], None
|
||||
|
||||
|
||||
def set_dispatch_callback(
|
||||
callback: Optional[Callable[[str, dict[str, Any], Optional[str]], None]]
|
||||
callback: Optional[Callable[[str, dict[str, Any], Optional[str]], None]],
|
||||
) -> None:
|
||||
"""Set a callback for synchronous webhook dispatch.
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Pydantic Settings for MeshCore Hub configuration."""
|
||||
|
||||
from enum import Enum
|
||||
import re
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import Field, field_validator
|
||||
@@ -24,6 +25,20 @@ class InterfaceMode(str, Enum):
|
||||
SENDER = "SENDER"
|
||||
|
||||
|
||||
class MQTTTransport(str, Enum):
|
||||
"""MQTT transport type."""
|
||||
|
||||
TCP = "tcp"
|
||||
WEBSOCKETS = "websockets"
|
||||
|
||||
|
||||
class CollectorIngestMode(str, Enum):
|
||||
"""Collector MQTT ingest mode."""
|
||||
|
||||
NATIVE = "native"
|
||||
LETSMESH_UPLOAD = "letsmesh_upload"
|
||||
|
||||
|
||||
class CommonSettings(BaseSettings):
|
||||
"""Common settings shared by all components."""
|
||||
|
||||
@@ -52,6 +67,17 @@ class CommonSettings(BaseSettings):
|
||||
default=None, description="MQTT password (optional)"
|
||||
)
|
||||
mqtt_prefix: str = Field(default="meshcore", description="MQTT topic prefix")
|
||||
mqtt_tls: bool = Field(
|
||||
default=False, description="Enable TLS/SSL for MQTT connection"
|
||||
)
|
||||
mqtt_transport: MQTTTransport = Field(
|
||||
default=MQTTTransport.TCP,
|
||||
description="MQTT transport protocol (tcp or websockets)",
|
||||
)
|
||||
mqtt_ws_path: str = Field(
|
||||
default="/mqtt",
|
||||
description="WebSocket path for MQTT transport (used when MQTT_TRANSPORT=websockets)",
|
||||
)
|
||||
|
||||
|
||||
class InterfaceSettings(CommonSettings):
|
||||
@@ -70,6 +96,22 @@ class InterfaceSettings(CommonSettings):
|
||||
# Mock device
|
||||
mock_device: bool = Field(default=False, description="Use mock device for testing")
|
||||
|
||||
# Device name
|
||||
meshcore_device_name: Optional[str] = Field(
|
||||
default=None, description="Device/node name (optional)"
|
||||
)
|
||||
|
||||
# Contact cleanup settings
|
||||
contact_cleanup_enabled: bool = Field(
|
||||
default=True,
|
||||
description="Enable automatic removal of stale contacts from companion node",
|
||||
)
|
||||
contact_cleanup_days: int = Field(
|
||||
default=7,
|
||||
description="Remove contacts not advertised for this many days",
|
||||
ge=1,
|
||||
)
|
||||
|
||||
|
||||
class CollectorSettings(CommonSettings):
|
||||
"""Settings for the Collector component."""
|
||||
@@ -80,7 +122,7 @@ class CollectorSettings(CommonSettings):
|
||||
description="SQLAlchemy database URL (default: sqlite:///{data_home}/collector/meshcore.db)",
|
||||
)
|
||||
|
||||
# Seed home directory - contains initial data files (node_tags.json, members.json)
|
||||
# Seed home directory - contains initial data files (node_tags.yaml, members.yaml)
|
||||
seed_home: str = Field(
|
||||
default="./seed",
|
||||
description="Directory containing seed data files (default: ./seed)",
|
||||
@@ -121,6 +163,65 @@ class CollectorSettings(CommonSettings):
|
||||
default=2.0, description="Retry backoff multiplier"
|
||||
)
|
||||
|
||||
# Data retention / cleanup settings
|
||||
data_retention_enabled: bool = Field(
|
||||
default=True, description="Enable automatic event data cleanup"
|
||||
)
|
||||
data_retention_days: int = Field(
|
||||
default=30, description="Number of days to retain event data", ge=1
|
||||
)
|
||||
data_retention_interval_hours: int = Field(
|
||||
default=24,
|
||||
description="Hours between automatic cleanup runs (applies to both events and nodes)",
|
||||
ge=1,
|
||||
)
|
||||
|
||||
# Node cleanup settings
|
||||
node_cleanup_enabled: bool = Field(
|
||||
default=True, description="Enable automatic cleanup of inactive nodes"
|
||||
)
|
||||
node_cleanup_days: int = Field(
|
||||
default=7,
|
||||
description="Remove nodes not seen for this many days (last_seen)",
|
||||
ge=1,
|
||||
)
|
||||
collector_ingest_mode: CollectorIngestMode = Field(
|
||||
default=CollectorIngestMode.NATIVE,
|
||||
description=(
|
||||
"Collector MQTT ingest mode. "
|
||||
"'native' expects <prefix>/<pubkey>/event/<event_name>. "
|
||||
"'letsmesh_upload' expects LetsMesh observer uploads on "
|
||||
"<prefix>/<pubkey>/(packets|status|internal)."
|
||||
),
|
||||
)
|
||||
collector_letsmesh_decoder_enabled: bool = Field(
|
||||
default=True,
|
||||
description=(
|
||||
"Enable external LetsMesh packet decoding via meshcore-decoder. "
|
||||
"Only applies when COLLECTOR_INGEST_MODE=letsmesh_upload."
|
||||
),
|
||||
)
|
||||
collector_letsmesh_decoder_command: str = Field(
|
||||
default="meshcore-decoder",
|
||||
description=(
|
||||
"Command used to run LetsMesh packet decoder CLI "
|
||||
"(for example: meshcore-decoder, /usr/local/bin/meshcore-decoder, "
|
||||
"or 'npx meshcore-decoder')."
|
||||
),
|
||||
)
|
||||
collector_letsmesh_decoder_keys: Optional[str] = Field(
|
||||
default=None,
|
||||
description=(
|
||||
"Optional channel secret keys for LetsMesh message decryption. "
|
||||
"Provide as comma/space separated hex values."
|
||||
),
|
||||
)
|
||||
collector_letsmesh_decoder_timeout_seconds: float = Field(
|
||||
default=2.0,
|
||||
description="Timeout in seconds for each decoder invocation.",
|
||||
ge=0.1,
|
||||
)
|
||||
|
||||
@property
|
||||
def collector_data_dir(self) -> str:
|
||||
"""Get the collector data directory path."""
|
||||
@@ -147,17 +248,28 @@ class CollectorSettings(CommonSettings):
|
||||
|
||||
@property
|
||||
def node_tags_file(self) -> str:
|
||||
"""Get the path to node_tags.json in seed_home."""
|
||||
"""Get the path to node_tags.yaml in seed_home."""
|
||||
from pathlib import Path
|
||||
|
||||
return str(Path(self.effective_seed_home) / "node_tags.json")
|
||||
return str(Path(self.effective_seed_home) / "node_tags.yaml")
|
||||
|
||||
@property
|
||||
def members_file(self) -> str:
|
||||
"""Get the path to members.json in seed_home."""
|
||||
"""Get the path to members.yaml in seed_home."""
|
||||
from pathlib import Path
|
||||
|
||||
return str(Path(self.effective_seed_home) / "members.json")
|
||||
return str(Path(self.effective_seed_home) / "members.yaml")
|
||||
|
||||
@property
|
||||
def collector_letsmesh_decoder_keys_list(self) -> list[str]:
|
||||
"""Parse configured LetsMesh decoder keys into a normalized list."""
|
||||
if not self.collector_letsmesh_decoder_keys:
|
||||
return []
|
||||
return [
|
||||
part.strip()
|
||||
for part in re.split(r"[,\s]+", self.collector_letsmesh_decoder_keys)
|
||||
if part.strip()
|
||||
]
|
||||
|
||||
@field_validator("database_url")
|
||||
@classmethod
|
||||
@@ -211,6 +323,47 @@ class WebSettings(CommonSettings):
|
||||
web_host: str = Field(default="0.0.0.0", description="Web server host")
|
||||
web_port: int = Field(default=8080, description="Web server port")
|
||||
|
||||
# Timezone for date/time display (uses standard TZ environment variable)
|
||||
tz: str = Field(default="UTC", description="Timezone for displaying dates/times")
|
||||
|
||||
# Theme (dark or light, default dark)
|
||||
web_theme: str = Field(
|
||||
default="dark",
|
||||
description="Default theme for the web dashboard (dark or light)",
|
||||
)
|
||||
|
||||
# Locale / language (default: English)
|
||||
web_locale: str = Field(
|
||||
default="en",
|
||||
description="Locale/language for the web dashboard (e.g. 'en')",
|
||||
)
|
||||
web_datetime_locale: str = Field(
|
||||
default="en-US",
|
||||
description=(
|
||||
"Locale used for date/time formatting in the web dashboard "
|
||||
"(e.g. 'en-US', 'en-GB')."
|
||||
),
|
||||
)
|
||||
|
||||
# Auto-refresh interval for list pages
|
||||
web_auto_refresh_seconds: int = Field(
|
||||
default=30,
|
||||
description="Auto-refresh interval in seconds for list pages (0 to disable)",
|
||||
ge=0,
|
||||
)
|
||||
|
||||
# Trusted proxy hosts for X-Forwarded-For header processing
|
||||
web_trusted_proxy_hosts: str = Field(
|
||||
default="*",
|
||||
description="Comma-separated list of trusted proxy hosts or '*' for all",
|
||||
)
|
||||
|
||||
# Admin interface (disabled by default for security)
|
||||
web_admin_enabled: bool = Field(
|
||||
default=False,
|
||||
description="Enable admin interface at /a/ (requires OAuth2Proxy in front)",
|
||||
)
|
||||
|
||||
# API connection
|
||||
api_base_url: str = Field(
|
||||
default="http://localhost:8000",
|
||||
@@ -231,9 +384,6 @@ class WebSettings(CommonSettings):
|
||||
network_country: Optional[str] = Field(
|
||||
default=None, description="Network country (ISO 3166-1 alpha-2)"
|
||||
)
|
||||
network_location: Optional[str] = Field(
|
||||
default=None, description="Network location (lat,lon)"
|
||||
)
|
||||
network_radio_config: Optional[str] = Field(
|
||||
default=None, description="Radio configuration details"
|
||||
)
|
||||
@@ -243,6 +393,82 @@ class WebSettings(CommonSettings):
|
||||
network_contact_discord: Optional[str] = Field(
|
||||
default=None, description="Discord server link"
|
||||
)
|
||||
network_contact_github: Optional[str] = Field(
|
||||
default=None, description="GitHub repository URL"
|
||||
)
|
||||
network_contact_youtube: Optional[str] = Field(
|
||||
default=None, description="YouTube channel URL"
|
||||
)
|
||||
network_welcome_text: Optional[str] = Field(
|
||||
default=None, description="Welcome text for homepage"
|
||||
)
|
||||
|
||||
# Feature flags (control which pages are visible in the web dashboard)
|
||||
feature_dashboard: bool = Field(
|
||||
default=True, description="Enable the /dashboard page"
|
||||
)
|
||||
feature_nodes: bool = Field(default=True, description="Enable the /nodes pages")
|
||||
feature_advertisements: bool = Field(
|
||||
default=True, description="Enable the /advertisements page"
|
||||
)
|
||||
feature_messages: bool = Field(
|
||||
default=True, description="Enable the /messages page"
|
||||
)
|
||||
feature_map: bool = Field(
|
||||
default=True, description="Enable the /map page and /map/data endpoint"
|
||||
)
|
||||
feature_members: bool = Field(default=True, description="Enable the /members page")
|
||||
feature_pages: bool = Field(
|
||||
default=True, description="Enable custom markdown pages"
|
||||
)
|
||||
|
||||
# Content directory (contains pages/ and media/ subdirectories)
|
||||
content_home: Optional[str] = Field(
|
||||
default=None,
|
||||
description="Directory containing custom content (pages/, media/) (default: ./content)",
|
||||
)
|
||||
|
||||
@property
|
||||
def features(self) -> dict[str, bool]:
|
||||
"""Get feature flags as a dictionary.
|
||||
|
||||
Automatic dependencies:
|
||||
- Dashboard requires at least one of nodes/advertisements/messages.
|
||||
- Map requires nodes (map displays node locations).
|
||||
"""
|
||||
has_dashboard_content = (
|
||||
self.feature_nodes or self.feature_advertisements or self.feature_messages
|
||||
)
|
||||
return {
|
||||
"dashboard": self.feature_dashboard and has_dashboard_content,
|
||||
"nodes": self.feature_nodes,
|
||||
"advertisements": self.feature_advertisements,
|
||||
"messages": self.feature_messages,
|
||||
"map": self.feature_map and self.feature_nodes,
|
||||
"members": self.feature_members,
|
||||
"pages": self.feature_pages,
|
||||
}
|
||||
|
||||
@property
|
||||
def effective_content_home(self) -> str:
|
||||
"""Get the effective content home directory."""
|
||||
from pathlib import Path
|
||||
|
||||
return str(Path(self.content_home or "./content"))
|
||||
|
||||
@property
|
||||
def effective_pages_home(self) -> str:
|
||||
"""Get the effective pages directory (content_home/pages)."""
|
||||
from pathlib import Path
|
||||
|
||||
return str(Path(self.effective_content_home) / "pages")
|
||||
|
||||
@property
|
||||
def effective_media_home(self) -> str:
|
||||
"""Get the effective media directory (content_home/media)."""
|
||||
from pathlib import Path
|
||||
|
||||
return str(Path(self.effective_content_home) / "media")
|
||||
|
||||
@property
|
||||
def web_data_dir(self) -> str:
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
"""Database connection and session management."""
|
||||
|
||||
from contextlib import contextmanager
|
||||
from typing import Generator
|
||||
from contextlib import asynccontextmanager, contextmanager
|
||||
from typing import AsyncGenerator, Generator
|
||||
|
||||
from sqlalchemy import create_engine, event
|
||||
from sqlalchemy.engine import Engine
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from meshcore_hub.common.models.base import Base
|
||||
@@ -97,9 +98,29 @@ class DatabaseManager:
|
||||
echo: Enable SQL query logging
|
||||
"""
|
||||
self.database_url = database_url
|
||||
|
||||
# Ensure parent directory exists for SQLite databases
|
||||
if database_url.startswith("sqlite:///"):
|
||||
from pathlib import Path
|
||||
|
||||
# Extract path from sqlite:///path/to/db.sqlite
|
||||
db_path = Path(database_url.replace("sqlite:///", ""))
|
||||
db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
self.engine = create_database_engine(database_url, echo=echo)
|
||||
self.session_factory = create_session_factory(self.engine)
|
||||
|
||||
# Create async engine for async operations
|
||||
async_url = database_url.replace("sqlite://", "sqlite+aiosqlite://")
|
||||
self.async_engine = create_async_engine(async_url, echo=echo)
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker
|
||||
|
||||
self.async_session_factory = async_sessionmaker(
|
||||
self.async_engine,
|
||||
class_=AsyncSession,
|
||||
expire_on_commit=False,
|
||||
)
|
||||
|
||||
def create_tables(self) -> None:
|
||||
"""Create all database tables."""
|
||||
create_tables(self.engine)
|
||||
@@ -138,6 +159,21 @@ class DatabaseManager:
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
@asynccontextmanager
|
||||
async def async_session(self) -> AsyncGenerator[AsyncSession, None]:
|
||||
"""Provide an async session context manager.
|
||||
|
||||
Yields:
|
||||
AsyncSession instance
|
||||
|
||||
Example:
|
||||
async with db.async_session() as session:
|
||||
result = await session.execute(select(Node))
|
||||
await session.commit()
|
||||
"""
|
||||
async with self.async_session_factory() as session:
|
||||
yield session
|
||||
|
||||
def dispose(self) -> None:
|
||||
"""Dispose of the database engine and connection pool."""
|
||||
self.engine.dispose()
|
||||
|
||||
142
src/meshcore_hub/common/hash_utils.py
Normal file
142
src/meshcore_hub/common/hash_utils.py
Normal file
@@ -0,0 +1,142 @@
|
||||
"""Event hash utilities for deduplication.
|
||||
|
||||
This module provides functions to compute deterministic hashes for events,
|
||||
allowing deduplication when multiple receiver nodes report the same event.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
|
||||
def compute_message_hash(
|
||||
text: str,
|
||||
pubkey_prefix: Optional[str] = None,
|
||||
channel_idx: Optional[int] = None,
|
||||
sender_timestamp: Optional[datetime] = None,
|
||||
txt_type: Optional[int] = None,
|
||||
) -> str:
|
||||
"""Compute a deterministic hash for a message.
|
||||
|
||||
The hash is computed from fields that uniquely identify a message's content
|
||||
and sender, excluding receiver-specific data.
|
||||
|
||||
Args:
|
||||
text: Message content
|
||||
pubkey_prefix: Sender's public key prefix (12 chars)
|
||||
channel_idx: Channel index for channel messages
|
||||
sender_timestamp: Sender's timestamp
|
||||
txt_type: Message type indicator
|
||||
|
||||
Returns:
|
||||
32-character hex hash string
|
||||
"""
|
||||
# Build a canonical string from the relevant fields
|
||||
parts = [
|
||||
text or "",
|
||||
pubkey_prefix or "",
|
||||
str(channel_idx) if channel_idx is not None else "",
|
||||
sender_timestamp.isoformat() if sender_timestamp else "",
|
||||
str(txt_type) if txt_type is not None else "",
|
||||
]
|
||||
canonical = "|".join(parts)
|
||||
return hashlib.md5(canonical.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def compute_advertisement_hash(
|
||||
public_key: str,
|
||||
name: Optional[str] = None,
|
||||
adv_type: Optional[str] = None,
|
||||
flags: Optional[int] = None,
|
||||
received_at: Optional[datetime] = None,
|
||||
bucket_seconds: int = 120,
|
||||
) -> str:
|
||||
"""Compute a deterministic hash for an advertisement.
|
||||
|
||||
Advertisements are bucketed by time since the same node may advertise
|
||||
periodically and we want to deduplicate within a time window.
|
||||
|
||||
Args:
|
||||
public_key: Advertised node's public key
|
||||
name: Advertised name
|
||||
adv_type: Node type
|
||||
flags: Capability flags
|
||||
received_at: When received (used for time bucketing)
|
||||
bucket_seconds: Time bucket size in seconds (default 30)
|
||||
|
||||
Returns:
|
||||
32-character hex hash string
|
||||
"""
|
||||
# Bucket the time to allow deduplication within a window
|
||||
time_bucket = ""
|
||||
if received_at:
|
||||
# Round down to nearest bucket
|
||||
epoch = int(received_at.timestamp())
|
||||
bucket_epoch = (epoch // bucket_seconds) * bucket_seconds
|
||||
time_bucket = str(bucket_epoch)
|
||||
|
||||
parts = [
|
||||
public_key,
|
||||
name or "",
|
||||
adv_type or "",
|
||||
str(flags) if flags is not None else "",
|
||||
time_bucket,
|
||||
]
|
||||
canonical = "|".join(parts)
|
||||
return hashlib.md5(canonical.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def compute_trace_hash(initiator_tag: int) -> str:
|
||||
"""Compute a deterministic hash for a trace path.
|
||||
|
||||
Trace paths have a unique initiator_tag that serves as the identifier.
|
||||
|
||||
Args:
|
||||
initiator_tag: Unique trace identifier
|
||||
|
||||
Returns:
|
||||
32-character hex hash string
|
||||
"""
|
||||
return hashlib.md5(str(initiator_tag).encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def compute_telemetry_hash(
|
||||
node_public_key: str,
|
||||
parsed_data: Optional[dict] = None,
|
||||
received_at: Optional[datetime] = None,
|
||||
bucket_seconds: int = 120,
|
||||
) -> str:
|
||||
"""Compute a deterministic hash for a telemetry record.
|
||||
|
||||
Telemetry is bucketed by time since nodes report periodically.
|
||||
|
||||
Args:
|
||||
node_public_key: Reporting node's public key
|
||||
parsed_data: Decoded sensor readings
|
||||
received_at: When received (used for time bucketing)
|
||||
bucket_seconds: Time bucket size in seconds (default 30)
|
||||
|
||||
Returns:
|
||||
32-character hex hash string
|
||||
"""
|
||||
# Bucket the time
|
||||
time_bucket = ""
|
||||
if received_at:
|
||||
epoch = int(received_at.timestamp())
|
||||
bucket_epoch = (epoch // bucket_seconds) * bucket_seconds
|
||||
time_bucket = str(bucket_epoch)
|
||||
|
||||
# Serialize parsed_data deterministically
|
||||
data_str = ""
|
||||
if parsed_data:
|
||||
# Sort keys for deterministic serialization
|
||||
sorted_items = sorted(parsed_data.items())
|
||||
data_str = str(sorted_items)
|
||||
|
||||
parts = [
|
||||
node_public_key,
|
||||
data_str,
|
||||
time_bucket,
|
||||
]
|
||||
canonical = "|".join(parts)
|
||||
return hashlib.md5(canonical.encode("utf-8")).hexdigest()
|
||||
81
src/meshcore_hub/common/i18n.py
Normal file
81
src/meshcore_hub/common/i18n.py
Normal file
@@ -0,0 +1,81 @@
|
||||
"""Lightweight i18n support for MeshCore Hub.
|
||||
|
||||
Loads JSON translation files and provides a ``t()`` lookup function
|
||||
that is shared between the Python (Jinja2) and JavaScript (SPA) sides.
|
||||
The same ``en.json`` file is served as a static asset for the client and
|
||||
read from disk for server-side template rendering.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_translations: dict[str, Any] = {}
|
||||
_locale: str = "en"
|
||||
|
||||
# Directory where locale JSON files live (web/static/locales/)
|
||||
LOCALES_DIR = Path(__file__).parent.parent / "web" / "static" / "locales"
|
||||
|
||||
|
||||
def load_locale(locale: str = "en", locales_dir: Path | None = None) -> None:
|
||||
"""Load a locale's translation file into memory.
|
||||
|
||||
Args:
|
||||
locale: Language code (e.g. ``"en"``).
|
||||
locales_dir: Override directory containing ``<locale>.json`` files.
|
||||
"""
|
||||
global _translations, _locale
|
||||
directory = locales_dir or LOCALES_DIR
|
||||
path = directory / f"{locale}.json"
|
||||
if not path.exists():
|
||||
logger.warning("Locale file not found: %s – falling back to 'en'", path)
|
||||
path = directory / "en.json"
|
||||
if path.exists():
|
||||
_translations = json.loads(path.read_text(encoding="utf-8"))
|
||||
_locale = locale
|
||||
logger.info("Loaded locale '%s' from %s", locale, path)
|
||||
else:
|
||||
logger.error("No locale files found in %s", directory)
|
||||
|
||||
|
||||
def _resolve(key: str) -> Any:
|
||||
"""Walk a dot-separated key through the nested translation dict."""
|
||||
value: Any = _translations
|
||||
for part in key.split("."):
|
||||
if isinstance(value, dict):
|
||||
value = value.get(part)
|
||||
else:
|
||||
return None
|
||||
return value
|
||||
|
||||
|
||||
def t(key: str, **kwargs: Any) -> str:
|
||||
"""Translate a key with optional interpolation.
|
||||
|
||||
Supports ``{{var}}`` placeholders in translation strings.
|
||||
|
||||
Args:
|
||||
key: Dot-separated translation key (e.g. ``"nav.home"``).
|
||||
**kwargs: Interpolation values.
|
||||
|
||||
Returns:
|
||||
Translated string, or the key itself as fallback.
|
||||
"""
|
||||
val = _resolve(key)
|
||||
|
||||
if not isinstance(val, str):
|
||||
return key
|
||||
|
||||
# Interpolation: replace {{var}} placeholders
|
||||
for k, v in kwargs.items():
|
||||
val = val.replace("{{" + k + "}}", str(v))
|
||||
|
||||
return val
|
||||
|
||||
|
||||
def get_locale() -> str:
|
||||
"""Return the currently loaded locale code."""
|
||||
return _locale
|
||||
@@ -9,6 +9,7 @@ from meshcore_hub.common.models.trace_path import TracePath
|
||||
from meshcore_hub.common.models.telemetry import Telemetry
|
||||
from meshcore_hub.common.models.event_log import EventLog
|
||||
from meshcore_hub.common.models.member import Member
|
||||
from meshcore_hub.common.models.event_receiver import EventReceiver, add_event_receiver
|
||||
|
||||
__all__ = [
|
||||
"Base",
|
||||
@@ -21,4 +22,6 @@ __all__ = [
|
||||
"Telemetry",
|
||||
"EventLog",
|
||||
"Member",
|
||||
"EventReceiver",
|
||||
"add_event_receiver",
|
||||
]
|
||||
|
||||
@@ -58,6 +58,11 @@ class Advertisement(Base, UUIDMixin, TimestampMixin):
|
||||
default=utc_now,
|
||||
nullable=False,
|
||||
)
|
||||
event_hash: Mapped[Optional[str]] = mapped_column(
|
||||
String(32),
|
||||
nullable=True,
|
||||
unique=True,
|
||||
)
|
||||
|
||||
__table_args__ = (Index("ix_advertisements_received_at", "received_at"),)
|
||||
|
||||
|
||||
127
src/meshcore_hub/common/models/event_receiver.py
Normal file
127
src/meshcore_hub/common/models/event_receiver.py
Normal file
@@ -0,0 +1,127 @@
|
||||
"""EventReceiver model for tracking which nodes received each event."""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import TYPE_CHECKING, Optional
|
||||
from uuid import uuid4
|
||||
|
||||
from sqlalchemy import DateTime, Float, ForeignKey, Index, String, UniqueConstraint
|
||||
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
|
||||
from sqlalchemy.orm import Mapped, Session, mapped_column, relationship
|
||||
|
||||
from meshcore_hub.common.models.base import Base, TimestampMixin, UUIDMixin, utc_now
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from meshcore_hub.common.models.node import Node
|
||||
|
||||
|
||||
class EventReceiver(Base, UUIDMixin, TimestampMixin):
|
||||
"""Junction model tracking which receivers observed each event.
|
||||
|
||||
This table enables multi-receiver tracking for deduplicated events.
|
||||
When multiple receiver nodes observe the same mesh event, each receiver
|
||||
gets an entry in this table linked by the event_hash.
|
||||
|
||||
Attributes:
|
||||
id: UUID primary key
|
||||
event_type: Type of event ('message', 'advertisement', 'trace', 'telemetry')
|
||||
event_hash: Hash identifying the unique event (links to event tables)
|
||||
receiver_node_id: FK to the node that received this event
|
||||
snr: Signal-to-noise ratio at this receiver (if available)
|
||||
received_at: When this specific receiver saw the event
|
||||
created_at: Record creation timestamp
|
||||
updated_at: Record update timestamp
|
||||
"""
|
||||
|
||||
__tablename__ = "event_receivers"
|
||||
|
||||
event_type: Mapped[str] = mapped_column(
|
||||
String(20),
|
||||
nullable=False,
|
||||
)
|
||||
event_hash: Mapped[str] = mapped_column(
|
||||
String(32),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
receiver_node_id: Mapped[str] = mapped_column(
|
||||
String(36),
|
||||
ForeignKey("nodes.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
snr: Mapped[Optional[float]] = mapped_column(
|
||||
Float,
|
||||
nullable=True,
|
||||
)
|
||||
received_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True),
|
||||
default=utc_now,
|
||||
nullable=False,
|
||||
)
|
||||
|
||||
# Relationship to receiver node
|
||||
receiver_node: Mapped["Node"] = relationship(
|
||||
"Node",
|
||||
foreign_keys=[receiver_node_id],
|
||||
)
|
||||
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
"event_hash", "receiver_node_id", name="uq_event_receivers_hash_node"
|
||||
),
|
||||
Index("ix_event_receivers_type_hash", "event_type", "event_hash"),
|
||||
)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return (
|
||||
f"<EventReceiver(type={self.event_type}, "
|
||||
f"hash={self.event_hash[:8]}..., "
|
||||
f"node={self.receiver_node_id[:8]}...)>"
|
||||
)
|
||||
|
||||
|
||||
def add_event_receiver(
|
||||
session: Session,
|
||||
event_type: str,
|
||||
event_hash: str,
|
||||
receiver_node_id: str,
|
||||
snr: Optional[float] = None,
|
||||
received_at: Optional[datetime] = None,
|
||||
) -> bool:
|
||||
"""Add a receiver to an event, handling duplicates gracefully.
|
||||
|
||||
Uses INSERT OR IGNORE to handle the unique constraint on (event_hash, receiver_node_id).
|
||||
|
||||
Args:
|
||||
session: SQLAlchemy session
|
||||
event_type: Type of event ('message', 'advertisement', 'trace', 'telemetry')
|
||||
event_hash: Hash identifying the unique event
|
||||
receiver_node_id: UUID of the receiver node
|
||||
snr: Signal-to-noise ratio at this receiver (optional)
|
||||
received_at: When this receiver saw the event (defaults to now)
|
||||
|
||||
Returns:
|
||||
True if a new receiver entry was added, False if it already existed.
|
||||
"""
|
||||
from datetime import timezone
|
||||
|
||||
now = received_at or datetime.now(timezone.utc)
|
||||
|
||||
stmt = (
|
||||
sqlite_insert(EventReceiver)
|
||||
.values(
|
||||
id=str(uuid4()),
|
||||
event_type=event_type,
|
||||
event_hash=event_hash,
|
||||
receiver_node_id=receiver_node_id,
|
||||
snr=snr,
|
||||
received_at=now,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
.on_conflict_do_nothing(index_elements=["event_hash", "receiver_node_id"])
|
||||
)
|
||||
result = session.execute(stmt)
|
||||
# CursorResult has rowcount attribute
|
||||
rowcount = getattr(result, "rowcount", 0)
|
||||
return bool(rowcount and rowcount > 0)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user