19 Commits
Author SHA1 Message Date
Worph b1179a6f94 virtual paths fall back to parsedTitle when a file has no title or originalTitle (claims model)
Build and Push Docker Image / build (push) Successful in 2m15s
2026-10-25 19:25:17 +00:00
Manielle e03b6b1fd4 CI accepts four-part tags (v1.2.3.1) for fixes
Build and Push Docker Image / build (push) Successful in 1m56s
2026-10-25 14:21:58 +01:00
Worph 4dcac7f690 gitea workflow: push to IPCR's direct host (Cloudflare 100 MB cap)
Build and Push Docker Image / build (push) Successful in 2m15s
2026-10-13 09:58:06 +00:00
Worph 9825b4317b gitea workflow: publish to IPCR (metadec.eth) instead of ghcr
Build and Push Docker Image / build (push) Failing after 1m49s
2026-10-12 18:30:17 +00:00
Worph 33847b1440 meshdisco.ts: beacon v2 scan (probe + classify) mirrored from meta-sort; LeaderClient.scan passthrough
Build and Push Docker Image / build (push) Failing after 14s
2026-10-04 17:19:28 +00:00
Worph b425318d21 beacon v2 discovery: meshdisco.ts on 239.255.99.1:9099, core located by metamesh.core cap, /api/neighbors ?cap=, nav lists services only
Build and Push Docker Image / build (push) Failing after 13s
2026-10-04 11:51:08 +00:00
Worph 58a7474721 README: sync with current code 2026-10-03 11:51:56 +00:00
Worph a0ffcd11b3 fix CI 2026-09-14 13:10:22 +02:00
Worph af495c4ad4 bugfix meshdisco
Build and Push Docker Image / build (push) Failing after 14s
2026-09-14 11:55:17 +02:00
Worph daf464261d replace file discovery by udp discovery
Build and Push Docker Image / build (push) Failing after 13s
2026-09-14 11:25:03 +02:00
Worph 2c485d5616 change service discovery 2026-09-13 19:49:11 +02:00
Worph d35a64a744 align with metadata standard
Build and Push Docker Image / build (push) Failing after 15s
2026-09-13 15:57:12 +02:00
Worph 9061c7a37d gitattributes 2026-07-14 16:08:49 +02:00
Pierre b100b3a77c improve doc + bugfix 2026-05-25 23:47:48 +02:00
Pierre 8e50b85e08 bugfix 2026-05-24 17:43:31 +02:00
Pierre a03aa35169 adaptation related to meta-core api changes 2026-05-24 17:26:13 +02:00
Pierre 797cf98afd ignore file 2026-04-28 12:20:57 +02:00
Pierre 0f034d9e95 remove pycache
Build and Push Docker Image / build (push) Failing after 13s
2026-04-26 15:27:49 +02:00
Pierre 9e6c3859c0 add proper auth 2026-04-26 15:26:46 +02:00
31 changed files with 2501 additions and 1015 deletions
+6
View File
@@ -0,0 +1,6 @@
# FIX CRLF always when developer has not set
# Linux/Mac: git config --global core.autocrlf input
# Windows: git config --global core.autocrlf true
# Auto detect text files and perform LF normalization
* text=auto
* eol=lf
+98
View File
@@ -0,0 +1,98 @@
# Gitea twin of .github/workflows/docker-publish.yml. Gitea runs only .gitea/workflows/ once this
# folder exists, and GitHub never reads it.
#
# Publishes to IPCR on watch.nsl.sh instead of ghcr.io:
# push ipcr-push-85-17-246-67.nip.io/metadec.eth/<repo>:<tag> docker login as metadec.eth with the
# IPCR_PUSH_TOKEN secret (the metadec.eth namespace token from the IPCR dashboard)
# pull ipcr-watch.nsl.sh/ipns/metadec.eth/metadec.eth/<repo>:<tag> anonymous
# The push goes to ipcr-push-85-17-246-67.nip.io, the box's own address, not ipcr-push-watch.nsl.sh: Cloudflare fronts
# *.watch.nsl.sh and refuses any request over 100 MB (413), which a large image layer is.
# That host's certificate is signed by the box's private Mesh Router CA, given to buildkit from
# the IPCR_CA_PEM repo variable. docker login would make the job's Docker daemon check the
# certificate without that CA, so the login is written straight into ~/.docker/config.json.
# The runner's job image (node:22-bookworm) has no docker CLI, so the static one is
# installed first; buildx installs itself. No `type=gha` cache: the runner has none.
name: Build and Push Docker Image
on:
push:
branches:
- main
tags:
- 'v*'
workflow_dispatch:
inputs:
tag:
description: 'Tag for the image (optional, defaults to sha)'
required: false
type: string
meta_core_version:
description: 'meta-core version to use (default: latest)'
required: false
type: string
default: 'latest'
env:
REGISTRY: ipcr-push-85-17-246-67.nip.io
IPCR_PULL: ipcr-watch.nsl.sh/ipns/metadec.eth
IMAGE_NAME: metadec.eth/${{ github.event.repository.name }}
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install Docker CLI
run: curl -fsSL https://download.docker.com/linux/static/stable/x86_64/docker-28.5.1.tgz | tar -xz -C /usr/local/bin --strip-components=1 docker/docker
- name: Trust the Mesh Router CA
run: printf '%s\n' "$IPCR_CA_PEM" > /tmp/ipcr-ca.pem
env:
IPCR_CA_PEM: ${{ vars.IPCR_CA_PEM }}
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
with:
version: latest
buildkitd-config-inline: |
[registry."${{ env.REGISTRY }}"]
ca = ["/tmp/ipcr-ca.pem"]
- name: Log in to IPCR
env:
IPCR_PUSH_TOKEN: ${{ secrets.IPCR_PUSH_TOKEN }}
run: |
mkdir -p ~/.docker
printf '{"auths":{"%s":{"auth":"%s"}}}\n' "$REGISTRY" "$(printf 'metadec.eth:%s' "$IPCR_PUSH_TOKEN" | base64 -w0)" > ~/.docker/config.json
- name: Extract metadata (tags, labels)
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=semver,pattern={{version}}
# A fix to release 1.2.3 is tagged v1.2.3.1: four numbers are not semver, so
# the pattern above makes no tag for it; this one does (image tag 1.2.3.1).
type=match,pattern=v(\d+\.\d+\.\d+\.\d+),group=1
type=semver,pattern={{major}}.{{minor}}
type=sha,prefix=
type=raw,value=latest,enable={{is_default_branch}}
type=raw,value=${{ inputs.tag }},enable=${{ inputs.tag != '' }}
- name: Build and push Docker image
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
build-args: |
META_CORE_IMAGE=${{ env.IPCR_PULL }}/metadec.eth/meta-core:${{ inputs.meta_core_version || 'latest' }}
+3
View File
@@ -50,6 +50,9 @@ jobs:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: | tags: |
type=semver,pattern={{version}} type=semver,pattern={{version}}
# A fix to release 1.2.3 is tagged v1.2.3.1: four numbers are not semver, so
# the pattern above makes no tag for it; this one does (image tag 1.2.3.1).
type=match,pattern=v(\d+\.\d+\.\d+\.\d+),group=1
type=semver,pattern={{major}}.{{minor}} type=semver,pattern={{major}}.{{minor}}
type=sha,prefix= type=sha,prefix=
type=raw,value=latest,enable={{is_default_branch}} type=raw,value=latest,enable={{is_default_branch}}
+1
View File
@@ -25,3 +25,4 @@ logs/
# Runtime data # Runtime data
data/ data/
docker/__pycache__/
+8 -5
View File
@@ -39,19 +39,21 @@ COPY packages/meta-fuse-core/src/ ./src/
RUN npm run build RUN npm run build
# Stage 3: Build FUSE Driver # Stage 3: Build FUSE Driver
FROM rust:1.86-bookworm AS fuse-builder FROM rust:1.89-bookworm AS fuse-builder
WORKDIR /build WORKDIR /build
# Install FUSE development libraries # Install FUSE development libraries
RUN apt-get update && apt-get install -y libfuse3-dev pkg-config RUN apt-get update && apt-get install -y libfuse3-dev pkg-config
# Copy Rust project # Copy Rust project (Cargo.lock included: without it cargo re-resolves every
COPY packages/meta-fuse-driver/Cargo.toml ./ # dep to the newest compatible version at build time, which drags in crates
# whose MSRV is above this image's rustc and breaks the build out of nowhere)
COPY packages/meta-fuse-driver/Cargo.toml packages/meta-fuse-driver/Cargo.lock ./
COPY packages/meta-fuse-driver/src/ ./src/ COPY packages/meta-fuse-driver/src/ ./src/
# Build release binary # Build release binary (--locked: fail loudly instead of silently re-resolving)
RUN cargo build --release RUN cargo build --release --locked
# Stage 4: Runtime # Stage 4: Runtime
FROM ubuntu:22.04 FROM ubuntu:22.04
@@ -121,6 +123,7 @@ RUN chmod +x /usr/local/bin/meta-core
COPY docker/nginx.conf /etc/nginx/nginx.conf COPY docker/nginx.conf /etc/nginx/nginx.conf
COPY docker/supervisord.conf /etc/supervisor/conf.d/supervisord.conf COPY docker/supervisord.conf /etc/supervisor/conf.d/supervisord.conf
COPY docker/wsgidav.yaml /app/docker/ COPY docker/wsgidav.yaml /app/docker/
COPY docker/webdav_token_controller.py /app/docker/
COPY docker/welcome.html /app/welcome/ COPY docker/welcome.html /app/welcome/
COPY docker/start-fuse-driver.sh /app/docker/ COPY docker/start-fuse-driver.sh /app/docker/
RUN chmod 644 /app/welcome/welcome.html && \ RUN chmod 644 /app/welcome/welcome.html && \
+232 -355
View File
@@ -6,12 +6,12 @@ Standalone virtual filesystem service that exposes metadata-organized content vi
Meta-Fuse is a read-only process in the MetaMesh ecosystem that: Meta-Fuse is a read-only process in the MetaMesh ecosystem that:
1. **Connects to shared KV storage** - Reads metadata from Redis/compatible KV database managed by meta-sort 1. **Locates meta-core over UDP** - beacon v2 multicast advertise (`239.255.99.1:9099`); no shared volume, no `REDIS_URL`
2. **Mounts virtual filesystem** - Rust-based FUSE driver creates an organized view of media files 2. **Reads metadata through meta-core's HTTP API** - `/meta/{hash}*` reads + SSE live updates on `/api/events/meta` (no direct Redis access)
3. **Serves WebDAV** - Network-accessible file sharing for Windows/Mac/Linux clients 3. **Mounts virtual filesystem** - Rust-based FUSE driver creates an organized view of media files
4. **Zero file duplication** - All content points to original files via WebDAV or direct volume access 4. **Serves WebDAV** - Network-accessible, read-only file sharing for Windows/Mac/Linux clients, authenticated with per-device tokens
5. **Leader-aware KV access** - Discovers and connects to the active KV database via lock file 5. **Zero file duplication** - File bytes are read from meta-core's WebDAV (`http://<meta-core host>/webdav`), which also covers SMB/rclone mounts; no `/files` mount required
6. **WebDAV file access** - Can read files from meta-sort's WebDAV server (supports SMB/rclone mounts) 6. **Configurable renaming rules** - Virtual paths are computed from metadata by editable rules (dashboard rules editor)
## Architecture ## Architecture
@@ -20,29 +20,27 @@ Meta-Fuse is a read-only process in the MetaMesh ecosystem that:
│ MetaMesh Ecosystem │ │ MetaMesh Ecosystem │
├─────────────────────────────────────────────────────────────────────────────┤ ├─────────────────────────────────────────────────────────────────────────────┤
│ │ │ │
│ DATA Volume (Shared) KV Database (Leader Election) │ │ meta-core (owns Redis) │
│ ┌────────────────────┐ ┌────────────────────────────┐ │ │ ┌──────────────────────────────────────────────┐ │
│ │ /data/watch/ │ │ Redis/Compatible DB │ │ │ │ UDP announce (beacon v2, /urls) │ │
│ │ /data/output/ │◄──────┐│ - metadata storage │ │ │ │ HTTP API: /meta/{hash}*, /api/events/meta │ │
│ │ /mnt/remote/ │ ││ - file paths & attributes │ │ │ │ WebDAV: /webdav (file bytes, /files/...) │ │
│ └────────────────────┘ │└────────────────────────────┘ │ │ └──────────────────────────────────────────────┘ │
│ ▲ │ ▲ │ │ ▲ metadata (HTTP + SSE) ▲ file bytes (WebDAV Range) │
│ │ │ │ reads │ │ ┌────────┴────────────────────────────────┴───────────────────┐ │
│ │ │ │ │
│ ┌────────┴───────────────────┴─────────────┴──────────────────┐ │
│ │ META-FUSE │ │ │ │ META-FUSE │ │
│ │ ┌─────────────────────────────────────────────────────────┐│ │ │ │ ┌─────────────────────────────────────────────────────────┐│ │
│ │ │ KV Client Wrapper ││ │ │ │ │ Storage client (KVManager / LeaderClient) ││ │
│ │ │ - Reads lock file for leader discovery ││ │ │ │ │ - Locates meta-core via UDP (or META_CORE_URL pin) ││ │
│ │ │ - Connects to active KV database ││ │ │ │ │ - Reads metadata over HTTP, events over SSE ││ │
│ │ │ - Reconnect loop for failure handling ││ │ │ │ │ - Reconnects when a different meta-core announces ││ │
│ │ └─────────────────────────────────────────────────────────┘│ │ │ │ └─────────────────────────────────────────────────────────┘│ │
│ │ │ │ │ │ │ │ │ │
│ │ ┌─────────────┴─────────────┐ │ │ │ │ ┌─────────────┴─────────────┐ │ │
│ │ ▼ ▼ │ │ │ │ ▼ ▼ │ │
│ │ ┌───────────────────────┐ ┌─────────────────────────┐ │ │ │ │ ┌───────────────────────┐ ┌─────────────────────────┐ │ │
│ │ │ FUSE API Server │ │ WebDAV Server │ │ │ │ │ │ FUSE API Server │ │ WebDAV Server │ │ │
│ │ │ (Node.js/Fastify) │ │ (WsgiDAV) │ │ │ │ │ │ (Node.js/Fastify) │ │ (WsgiDAV, token auth)│ │ │
│ │ │ Port 3000 │ │ Port 8080 │ │ │ │ │ │ Port 3000 │ │ Port 8080 │ │ │
│ │ └───────────┬───────────┘ └───────────┬─────────────┘ │ │ │ │ └───────────┬───────────┘ └───────────┬─────────────┘ │ │
│ │ │ │ │ │ │ │ │ │ │ │
@@ -56,10 +54,11 @@ Meta-Fuse is a read-only process in the MetaMesh ecosystem that:
│ │ │ │ │ │
│ ▼ │ │ ▼ │
│ ┌─────────────────────────┐ │ │ ┌─────────────────────────┐ │
│ │ nginx Reverse Proxy │ │ │ │ nginx (port 80) │ │
│ │ / → UI │ │ │ │ / → UI │ │
│ │ /webdav → WebDAV │ │ │ │ /webdav → WebDAV │ │
│ │ /api/fuse → API │ │ │ │ /api/ → API │ │
│ │ /health → API │ │
│ └─────────────────────────┘ │ │ └─────────────────────────┘ │
│ │ │ │ │ │
└────────────────────────────┼────────────────────────────────────────────────┘ └────────────────────────────┼────────────────────────────────────────────────┘
@@ -68,6 +67,8 @@ Meta-Fuse is a read-only process in the MetaMesh ecosystem that:
(Windows/Mac/Linux) (Windows/Mac/Linux)
``` ```
In the dev stack and the CasaOS store app (`packages/MetaAppStore`, app `MetaFuse`) the backend runs as `metafuse-app` behind an OIDC perimeter container `metafuse` (`nginx-hash-lock` in dev, `appshield` in the store app); in the store app Caddy routes `/health` and `/webdav*` straight to the backend, so WebDAV is authenticated by WebDAV tokens instead. See the meta-root [authentication architecture](../../docs/project-architecture/authentication.md).
### Service Role in MetaMesh ### Service Role in MetaMesh
``` ```
@@ -75,54 +76,45 @@ Meta-Fuse is a read-only process in the MetaMesh ecosystem that:
│ SERVICE ROLES │ │ SERVICE ROLES │
├────────────────────────────────────────────────────────────────────────────┤ ├────────────────────────────────────────────────────────────────────────────┤
│ │ │ │
│ [1] meta-sort (PROCESS-WRITE) │ │ [1] meta-core (STORE) │
│ └─► Writes metadata to KV, manages remote mounts │ │ └─► Owns Redis, metadata HTTP API, event streams, WebDAV over /files │
│ │ │ │
│ [2] meta-fuse (PROCESS-READ) ◄── YOU ARE HERE │ │ [2] meta-sort (PROCESS-WRITE) │
│ └─► Reads metadata from KV, exposes virtual filesystem │ │ └─► Watches folders, writes metadata through meta-core │
│ │ │ │
│ [3] meta-stremio (PROCESS-READ) │ │ [3] meta-fuse (PROCESS-READ) ◄── YOU ARE HERE │
│ └─► Reads metadata from KV, streams media content │ │ └─► Reads metadata from meta-core, exposes virtual filesystem │
│ │ │ │
│ [4] meta-orbit (SHARING-READ-WRITE) │ │ [4] meta-stremio (PROCESS-READ) │
│ └─► P2P metadata sync across network │ │ └─► Reads metadata, streams media content │
│ │ │ │
└────────────────────────────────────────────────────────────────────────────┘ └────────────────────────────────────────────────────────────────────────────┘
``` ```
### KV Leader Election ### Locating meta-core (beacon v2)
All services in MetaMesh use leader discovery via meta-core's lock file and HTTP API: meta-core announces itself on UDP multicast `239.255.99.1:9099`, carrying its `/urls` payload. meta-fuse listens (and announces itself on the same group, so it shows up in every neighbour's nav menu):
``` ```
/meta-core/locks/ /urls payload (JSON):
├── kv-leader.lock # flock-based leader election
└── kv-leader.info # Leader API URL (plain text)
Lock Info File Format (plain text):
http://meta-core:9000
/urls API Response (JSON):
{ {
"hostname": "meta-core-dev", "hostname": "metacore-app",
"baseUrl": "http://localhost:8083", "baseUrl": "https://metacore-dev.localhost:8083",
"apiUrl": "http://meta-core:9000", "apiUrl": "http://<meta-core ip>:9000",
"redisUrl": "redis://meta-core:6379", "redisUrl": "", # always empty since the api-mediated-access lockdown
"webdavUrl": "http://localhost:8083/webdav", "webdavUrl": "https://metacore-dev.localhost:8083/webdav",
"webdavUrlInternal": "http://meta-core:9000/webdav", "webdavUrlInternal": "http://<meta-core ip>:9000/webdav"
"isLeader": true
} }
Leader Discovery Flow: Discovery flow:
1. meta-core acquires flock on kv-leader.lock 1. meta-core advertises `metamesh.core` with its /urls payload (`data.urls`)
2. Winner (leader) spawns Redis, writes API URL to kv-leader.info 2. meta-fuse picks it up (or uses META_CORE_URL and GET {url}/urls when pinned)
3. meta-fuse reads kv-leader.info to find API URL 3. meta-fuse reads metadata from apiUrl (/meta/{hash}*) and streams apiUrl/api/events/meta
4. meta-fuse calls /urls API to get Redis URL and other endpoints 4. File bytes are fetched from http://<hostname>/webdav
5. meta-fuse connects to Redis as read-only client 5. An announce carrying a different apiUrl triggers a reconnect
6. On leader failure, flock auto-releases, new leader elected
``` ```
**Note**: meta-fuse never becomes leader - it reads the lock file and calls the /urls API to discover the active Redis endpoint managed by meta-core. **Note**: meta-fuse never owns storage. If meta-core still publishes a non-empty `redisUrl`, meta-fuse refuses to start (set `ALLOW_LEGACY_REDIS_URL=1` to downgrade that to a warning). Protocol spec: [beacon-v2.md](../../docs/project-architecture/beacon-v2.md).
## Core Features ## Core Features
@@ -132,21 +124,21 @@ Leader Discovery Flow:
- **Path-to-inode mapping**: Translates filesystem paths to FUSE inode numbers - **Path-to-inode mapping**: Translates filesystem paths to FUSE inode numbers
- **Attribute caching**: 1-second TTL for file attributes - **Attribute caching**: 1-second TTL for file attributes
- **Directory caching**: 30-second TTL for directory listings - **Directory caching**: 30-second TTL for directory listings
- **Error resilience**: Virtual ERROR.txt shown when backend unavailable - **Error resilience**: Virtual `ERROR.txt` shown after 3 consecutive API failures
- **WebDAV reads**: The driver issues HTTP Range requests against the `webdavUrl` returned by `/api/fuse/read`
### WebDAV Server ### WebDAV Server
- **Network file sharing**: Mount as network drive on any OS - **Network file sharing**: Mount as network drive on any OS
- **Read-only access**: Prevents accidental modifications - **Read-only access**: Prevents accidental modifications
- **Basic authentication**: Username/password protection - **Per-device tokens**: Minted/revoked from the dashboard (`/api/webdav-tokens`); the token (`mfwd_…`) is the basic-auth password, any non-empty username is accepted. Only sha256 hashes are stored (`$CONFIG_DIR/webdav-tokens.json`); revocation is immediate
- **Directory browsing**: Web-based file browser - **Directory browsing**: Web-based file browser
### KV Client Wrapper ### Renaming Rules
- **Leader discovery**: Reads lock file to find active database - Stored in `$CONFIG_DIR/renaming-rules.json` (timestamped backups on update)
- **Auto-reconnect**: Handles leader failover gracefully - Template variables + conditions; preview and validate via the API before saving
- **Connection pooling**: Efficient database connections - Only the metadata properties the rules reference are fetched (`RulesPropertyExtractor`)
- **Read-only operations**: No writes to KV database
## Package Structure ## Package Structure
@@ -155,16 +147,16 @@ meta-fuse/
├── packages/ ├── packages/
│ ├── meta-fuse-core/ # Core service (@meta-fuse/core) │ ├── meta-fuse-core/ # Core service (@meta-fuse/core)
│ │ ├── src/ │ │ ├── src/
│ │ │ ├── api/ # Fastify REST API (APIServer) │ │ │ ├── api/APIServer.ts # Fastify REST API
│ │ │ │ └── APIServer.ts │ │ │ ├── config/ConfigStorage.ts # Renaming-rules persistence
│ │ │ ├── config/ # Configuration management │ │ │ ├── discovery/meshdisco.ts # beacon v2 (mirrored, see scripts/check-mirrors.sh)
│ │ │ │ └── ConfigStorage.ts │ │ │ ├── kv/ # Storage client (read-only)
│ │ │ ├── kv/ # KV client wrapper (FOLLOWER mode only)
│ │ │ │ ├── IKVClient.ts # Read-only interface │ │ │ │ ├── IKVClient.ts # Read-only interface
│ │ │ │ ├── KVManager.ts # Leader discovery, connection management │ │ │ │ ├── KVManager.ts # meta-core location, connection management
│ │ │ │ ├── LeaderClient.ts # Lock file reading + /urls API │ │ │ │ ├── LeaderClient.ts # Adapter over MetaCoreLocator (UDP / META_CORE_URL pin)
│ │ │ │ ├── RedisClient.ts # Redis connection with Streams support │ │ │ │ ├── MetaCoreApiClient.ts # HTTP reads: /meta, /meta/{hash}, /meta/{hash}/{prop}
│ │ │ │ └── ServiceDiscovery.ts # Service discovery client │ │ │ │ ├── SSEEventClient.ts # SSE consumer for /api/events/meta
│ │ │ │ └── RedisClient.ts # Storage facade (HTTP-only mode when redisUrl is empty)
│ │ │ ├── vfs/ # Virtual filesystem logic │ │ │ ├── vfs/ # Virtual filesystem logic
│ │ │ │ ├── VirtualFileSystem.ts # In-memory VFS representation │ │ │ │ ├── VirtualFileSystem.ts # In-memory VFS representation
│ │ │ │ ├── StreamingStateBuilder.ts # Event-driven state management │ │ │ │ ├── StreamingStateBuilder.ts # Event-driven state management
@@ -172,146 +164,123 @@ meta-fuse/
│ │ │ │ ├── MetaDataToFolderStruct.ts # Folder organization │ │ │ │ ├── MetaDataToFolderStruct.ts # Folder organization
│ │ │ │ ├── RenamingRule.ts # Virtual path rules │ │ │ │ ├── RenamingRule.ts # Virtual path rules
│ │ │ │ ├── defaults/ # Default renaming rules │ │ │ │ ├── defaults/ # Default renaming rules
│ │ │ │ ├── template/ # Template engine components │ │ │ │ ├── template/ # TemplateEngine, ConditionEvaluator
│ │ │ │ │ ├── TemplateEngine.ts # Variable interpolation │ │ │ │ └── types/ # RenamingRuleTypes.ts
│ │ │ │ │ └── ConditionEvaluator.ts # Rule condition evaluation │ │ │ ├── webdav/TokenStore.ts # Per-device WebDAV tokens
│ │ │ │ └── types/ # TypeScript type definitions
│ │ │ │ └── RenamingRuleTypes.ts
│ │ │ └── index.ts # Entry point │ │ │ └── index.ts # Entry point
│ │ ├── package.json │ │ ├── package.json
│ │ └── tsconfig.json │ │ └── tsconfig.json
│ │ │ │
│ ├── meta-fuse-driver/ # Rust FUSE driver │ ├── meta-fuse-driver/ # Rust FUSE driver (fuser)
│ │ ├── src/ │ │ ├── src/
│ │ │ ├── main.rs # Entry point │ │ │ ├── main.rs # Entry point, FUSE ops, inode mapping
│ │ │ ├── api_client.rs # HTTP client to API server │ │ │ └── api_client.rs # HTTP client to API server
│ │ │ └── inode_mapper.rs # Path-to-inode mapping │ │ ├── Cargo.toml
│ │ └── Cargo.toml │ │ └── Cargo.lock
│ │ │ │
│ └── meta-fuse-ui/ # Monitoring dashboard (optional) │ └── meta-fuse-ui/ # Dashboard (Vite + React): stats, rules editor, WebDAV tokens
│ ├── src/
│ └── package.json
│ │
├── docs/ # Architecture documentation ├── docs/ # Architecture documentation
│ ├── vfs-rebuild-architecture.md
│ ├── streaming-architecture.md
│ └── api-reference.md
│
├── docker/ ├── docker/
│ ├── nginx.conf # Reverse proxy config │ ├── nginx.conf # Reverse proxy config
│ ├── wsgidav.yaml # WebDAV server config │ ├── wsgidav.yaml # WebDAV server config
│ ├── webdav_token_controller.py # WsgiDAV DomainController (token auth)
│ ├── supervisord.conf # Process management │ ├── supervisord.conf # Process management
│ └── entrypoint.sh # Service orchestration │ ├── start-fuse-driver.sh # Waits for the API, then mounts
│ └── welcome.html
│ │
├── Dockerfile ├── Dockerfile
├── docker-compose.yml ├── docker-compose.yml # Legacy standalone example (see note below)
├── package.json # Workspace root ├── package.json # Workspace root
├── pnpm-workspace.yaml └── pnpm-workspace.yaml
└── README.md
``` ```
### Key Components (meta-fuse-core) ### Key Components (meta-fuse-core)
| Component | File | Purpose | | Component | File | Purpose |
|-----------|------|---------| |-----------|------|---------|
| Entry Point | `src/index.ts` | Initializes KV manager, VFS, API server, stream consumer | | Entry Point | `src/index.ts` | Initializes KV manager, VFS, SSE consumer, API server |
| API Server | `src/api/APIServer.ts` | Fastify REST API for FUSE operations and rules management | | API Server | `src/api/APIServer.ts` | Fastify REST API for FUSE operations, rules, tokens, neighbours |
| KV Manager | `src/kv/KVManager.ts` | **FOLLOWER-only**: leader discovery, Redis connection, reconnection loop | | KV Manager | `src/kv/KVManager.ts` | Never owns storage: locates meta-core, builds the client, reconnects |
| Leader Client | `src/kv/LeaderClient.ts` | Reads `/meta-core/locks/kv-leader.info`, calls `/urls` API | | Leader Client | `src/kv/LeaderClient.ts` | Locates meta-core over UDP (name is legacy: no election involved) |
| Redis Client | `src/kv/RedisClient.ts` | Wrapper around ioredis with Redis Streams support | | meta-core API Client | `src/kv/MetaCoreApiClient.ts` | `/meta/{hash}/{prop}`, `/meta/{hash}`, `/meta` reads |
| Service Discovery | `src/kv/ServiceDiscovery.ts` | Discovers all MetaMesh services via service files | | SSE Event Client | `src/kv/SSEEventClient.ts` | Consumes `/api/events/meta` (replays from `0-0` every start) |
| KV Interface | `src/kv/IKVClient.ts` | Read-only interface (get, scan, subscribe) |
| Virtual FS | `src/vfs/VirtualFileSystem.ts` | In-memory VFS representation with caching | | Virtual FS | `src/vfs/VirtualFileSystem.ts` | In-memory VFS representation with caching |
| Streaming State Builder | `src/vfs/StreamingStateBuilder.ts` | Processes `meta:events` stream, builds VFS state incrementally | | Streaming State Builder | `src/vfs/StreamingStateBuilder.ts` | Turns `meta:events` into VFS state incrementally |
| Rules Property Extractor | `src/vfs/RulesPropertyExtractor.ts` | Extracts VFS-relevant properties from renaming rules | | Rules Property Extractor | `src/vfs/RulesPropertyExtractor.ts` | Extracts VFS-relevant properties from renaming rules |
| Folder Organizer | `src/vfs/MetaDataToFolderStruct.ts` | Converts flat metadata to organized folder structure | | Folder Organizer | `src/vfs/MetaDataToFolderStruct.ts` | Converts flat metadata to organized folder structure |
| Renaming Rules | `src/vfs/RenamingRule.ts` | Rules for virtual path organization |
| Template Engine | `src/vfs/template/TemplateEngine.ts` | Variable interpolation for renaming templates | | Template Engine | `src/vfs/template/TemplateEngine.ts` | Variable interpolation for renaming templates |
| Condition Evaluator | `src/vfs/template/ConditionEvaluator.ts` | Evaluates rule conditions against file metadata | | Condition Evaluator | `src/vfs/template/ConditionEvaluator.ts` | Evaluates rule conditions against file metadata |
| Token Store | `src/webdav/TokenStore.ts` | Mints/lists/revokes WebDAV tokens |
**Note**: Unlike meta-sort, meta-fuse's KVManager is simplified:
- **Never spawns Redis** (always FOLLOWER)
- **Only reads metadata** (read-only interface)
- **Discovers leader** via lock file at `/meta-core/locks/kv-leader.info`
- **Calls `/urls` API** to get Redis URL, WebDAV URL, and other endpoints
- **Uses streaming mode** - processes `meta:events` stream for real-time updates
## Configuration ## Configuration
### Environment Variables ### Environment Variables
```bash ```bash
# Volume Paths # meta-core location
META_CORE_PATH=/meta-core # Infrastructure volume (locks, services) META_CORE_URL= # Pin meta-core's API URL; UDP discovery never overrides it
FILES_VOLUME=/files # Shared media volume ENABLE_UDP_DISCOVERY=true # false/0 disables meta-discovery
ALLOW_LEGACY_REDIS_URL= # 1 = warn instead of fail if meta-core publishes redisUrl
# KV Connection # Announce / nav menu
REDIS_URL= # Direct Redis URL (optional, skips discovery) BASE_URL= # External (Caddy) URL
REDIS_PREFIX=meta-sort: # Key prefix in Redis PUBLIC_URL= # Wins over BASE_URL (debug-direct port, no Caddy)
# Paths
FILES_VOLUME=/files # Prefix for the relative filePath of each record
CONFIG_DIR=/meta-fuse/config # renaming-rules.json, webdav-tokens.json
# API Server # API Server
API_PORT=3000 # API server port API_PORT=3000 # API server port
API_HOST=0.0.0.0 # API bind address API_HOST=0.0.0.0 # API bind address
VFS_REFRESH_INTERVAL=30000 # VFS cache refresh interval (ms)
# FUSE Driver # VFS attributes (core)
FUSE_MOUNT_POINT=/mnt/virtual # Virtual filesystem mount
FUSE_API_URL=http://localhost:3000 # API server URL
FUSE_FILE_MODE=644 # File permissions (octal) FUSE_FILE_MODE=644 # File permissions (octal)
FUSE_DIR_MODE=755 # Directory permissions (octal) FUSE_DIR_MODE=755 # Directory permissions (octal)
FUSE_ALLOW_OTHER=true # Allow other users PUID=1000 # File owner uid (core + driver)
PGID=1000 # File owner gid (core + driver)
# User/Group # FUSE driver (args: <mountpoint> [api-url] [uid] [gid])
PUID=1000 # User ID for files FUSE_API_URL=http://localhost:3000 # Used when api-url arg is omitted
PGID=1000 # Group ID for files FUSE_FILE_PERM / FUSE_DIR_PERM # Driver-side permission overrides
# Mount always uses allow_other (needs user_allow_other in /etc/fuse.conf)
# WebDAV (serving files to clients) # WsgiDAV
WEBDAV_PORT=8080 # WebDAV server port TOKEN_STORE_PATH=/meta-fuse/config/webdav-tokens.json
WEBDAV_USERNAME=metamesh # WebDAV username
WEBDAV_PASSWORD=metamesh # WebDAV password
WEBDAV_READONLY=true # Read-only mode
# meta-core WebDAV Access (reading files from meta-core)
META_CORE_WEBDAV_URL=http://meta-core/webdav # URL to access files via meta-core's WebDAV
# Enables access to SMB/rclone mounts
``` ```
### Docker Compose ### Docker Compose
```yaml The CasaOS store app (`packages/MetaAppStore/Apps/MetaFuse/docker-compose.yml`) is the reference deployment. Trimmed:
version: '3.8'
```yaml
services: services:
meta-fuse: metafuse-app:
build: . image: ghcr.io/worph/meta-fuse:<version>
container_name: meta-fuse
restart: unless-stopped
privileged: true # Required for FUSE privileged: true # Required for FUSE
cap_add: cap_add: [SYS_ADMIN, DAC_READ_SEARCH, DAC_OVERRIDE]
- SYS_ADMIN
devices: devices:
- /dev/fuse - /dev/fuse:/dev/fuse
ports: security_opt:
- "80:80" # nginx (WebDAV, API) - apparmor:unconfined
expose:
- 80 # nginx (UI, API, WebDAV)
volumes: volumes:
# Infrastructure volume (read-only for followers) # No /meta-core mount (UDP discovery), no /files mount (WebDAV via meta-core)
- ${META_CORE_PATH:-./data/meta-core}:/meta-core:ro - ${DATA_ROOT:-/DATA}/MetaFuse/Library:/mnt/virtual:shared # FUSE mount output
# Shared media volume (read-only) - ${DATA_ROOT:-/DATA}/AppData/metafuse/config:/meta-fuse/config:rw
- ${FILES_PATH:-./data/files}:/files:ro
# FUSE mount output (if exposing to host)
- /mnt/metamesh:/mnt/virtual:rw,shared
environment: environment:
- META_CORE_PATH=/meta-core - CONFIG_DIR=/meta-fuse/config
- FILES_VOLUME=/files - BASE_URL=https://metafuse-$APP_DOMAIN
- FUSE_MOUNT_POINT=/mnt/virtual networks: [pcs] # must share a multicast-capable network with meta-core
- REDIS_PREFIX=meta-sort:
# Optional: Read files via meta-core WebDAV (enables SMB/rclone mount access)
- META_CORE_WEBDAV_URL=http://meta-core/webdav
``` ```
The repo-root `docker-compose.yml` predates meta-core (it sets `REDIS_URL` and mounts `/data`) and is not representative.
## API Endpoints ## API Endpoints
### FUSE API (Port 3000) ### FUSE API (Port 3000, proxied by nginx under `/api/` and `/health`)
| Method | Endpoint | Description | | Method | Endpoint | Description |
|--------|----------|-------------| |--------|----------|-------------|
@@ -324,35 +293,34 @@ services:
| POST | `/api/fuse/readdir` | List directory contents | | POST | `/api/fuse/readdir` | List directory contents |
| POST | `/api/fuse/getattr` | Get file/directory attributes | | POST | `/api/fuse/getattr` | Get file/directory attributes |
| POST | `/api/fuse/exists` | Check path existence | | POST | `/api/fuse/exists` | Check path existence |
| POST | `/api/fuse/read` | Read file content (returns source path or WebDAV URL) | | POST | `/api/fuse/read` | Resolve file content (source path / WebDAV URL) |
| POST | `/api/fuse/metadata` | Get full metadata for a path | | POST | `/api/fuse/metadata` | Get full metadata for a path |
| GET | `/api/fuse/files` | List all virtual files | | GET | `/api/fuse/files` | List all virtual files |
| GET | `/api/fuse/directories` | List all virtual directories | | GET | `/api/fuse/directories` | List all virtual directories |
| POST | `/api/fuse/refresh` | Trigger VFS refresh | | POST | `/api/fuse/refresh` | Trigger VFS refresh (replays the event stream) |
| **Renaming Rules** | | **Renaming Rules** |
| GET | `/api/fuse/rules` | Get current renaming rules configuration | | GET | `/api/fuse/rules` | Get current renaming rules configuration |
| PUT | `/api/fuse/rules` | Update renaming rules configuration | | PUT | `/api/fuse/rules` | Update renaming rules configuration |
| POST | `/api/fuse/rules/preview` | Preview how files would be renamed | | POST | `/api/fuse/rules/preview` | Preview how files would be renamed |
| POST | `/api/fuse/rules/validate` | Validate a single rule | | POST | `/api/fuse/rules/validate` | Validate a single rule |
| GET | `/api/fuse/rules/variables` | Get list of available template variables | | GET | `/api/fuse/rules/variables` | Get list of available template variables |
| **WebDAV Tokens** |
| GET | `/api/webdav-tokens` | List tokens (hashes/prefixes only) |
| POST | `/api/webdav-tokens` | Create a token (`{ "label": "..." }`); plaintext returned once |
| DELETE | `/api/webdav-tokens/:id` | Revoke a token |
| **Service Discovery** | | **Service Discovery** |
| GET | `/api/services` | List all discovered MetaMesh services | | GET | `/api/neighbors` | Services heard over beacon v2 (nav menu) |
### Example Responses ### Example Responses
**GET /api/fuse/stats** **GET /api/fuse/stats**
```json ```json
{ {
"totalFiles": 1523, "fileCount": 1523,
"totalDirectories": 48, "directoryCount": 48,
"totalSize": 1847392847362, "totalSize": 1847392847362,
"categories": { "lastRefresh": "2026-01-15T10:30:00.000Z",
"Movies": 523, "redisConnected": true
"TV": 412,
"Anime": 588
},
"kvConnection": "connected",
"fuseMount": "mounted"
} }
``` ```
@@ -363,12 +331,7 @@ services:
// Response // Response
{ {
"entries": [ "entries": ["Action", "Comedy", "Drama", "Sci-Fi"]
"Action",
"Comedy",
"Drama",
"Sci-Fi"
]
} }
``` ```
@@ -377,66 +340,54 @@ services:
// Request // Request
{ "path": "/Movies/Action/Movie.mkv" } { "path": "/Movies/Action/Movie.mkv" }
// Response // Response (mode includes the file-type bits; times are epoch seconds)
{ {
"size": 4831838208, "size": 4831838208,
"mode": "file", "mode": 33188,
"permissions": 644, "mtime": 1705314600,
"atime": "2024-01-15T10:30:00Z", "atime": 1705314600,
"mtime": "2024-01-15T10:30:00Z", "ctime": 1705314600,
"ctime": "2024-01-15T10:30:00Z", "nlink": 1,
"sourcePath": "/data/watch/downloads/Movie.2024.1080p.mkv" "uid": 1000,
"gid": 1000
} }
``` ```
## Usage ## Usage
### Docker (Recommended) ### Docker
```bash ```bash
# Start meta-fuse service # Build the image (bundles UI, backend, FUSE driver, WsgiDAV, nginx)
docker-compose up -d docker build -t meta-fuse .
# View logs # Check health (through nginx on port 80)
docker logs -f meta-fuse curl http://localhost/health
# Check health
curl http://localhost/api/fuse/health
``` ```
### Mount WebDAV (Windows) Images are published to `ghcr.io/worph/meta-fuse` by `.github/workflows/docker-publish.yml`. In the meta-root dev stack the service is `metafuse-app` (`https://metafuse-dev.localhost:8181` via Caddy, debug-direct `http://localhost:18181`); rebuild it with `dev/scripts/reload-meta-fuse.sh`.
### Mount WebDAV
Create a token in the dashboard (WebDAV tokens panel) first; use it as the password. The username can be anything non-empty.
```powershell ```powershell
# Map network drive # Windows
net use Z: http://localhost/webdav /user:metamesh metamesh net use Z: https://<metafuse host>/webdav /user:me mfwd_xxxxxxxx
# Access files
dir Z:\Movies dir Z:\Movies
``` ```
### Mount WebDAV (Linux)
```bash ```bash
# Install davfs2 # Linux (davfs2)
sudo apt-get install davfs2 sudo apt-get install davfs2
# Create mount point
mkdir -p ~/meta-fuse mkdir -p ~/meta-fuse
sudo mount -t davfs https://<metafuse host>/webdav ~/meta-fuse
# Mount # Credentials: any username / your mfwd_ token
sudo mount -t davfs http://localhost/webdav ~/meta-fuse
# Enter credentials: metamesh / metamesh
# Access files
ls ~/meta-fuse/Movies ls ~/meta-fuse/Movies
``` ```
### Mount WebDAV (macOS)
```bash ```bash
# Using Finder: Go → Connect to Server # macOS: Finder → Go → Connect to Server → https://<metafuse host>/webdav
# Enter: http://localhost/webdav
# Credentials: metamesh / metamesh
``` ```
## Development ## Development
@@ -444,39 +395,30 @@ ls ~/meta-fuse/Movies
### Prerequisites ### Prerequisites
- Node.js 21.6.2+ - Node.js 21.6.2+
- pnpm 10.19.0+ - pnpm
- Rust 1.90+ (for FUSE driver) - Rust 1.89+ (for FUSE driver; the Dockerfile builds with `rust:1.89-bookworm`)
- Docker & Docker Compose - Docker & Docker Compose
### Local Development ### Local Development
```bash ```bash
# Install dependencies
pnpm install pnpm install
pnpm run build # all packages
# Build all packages pnpm run dev # tsc --watch (core) + vite (ui), in parallel
pnpm run build pnpm run test # @meta-fuse/core (mocha)
# Start development mode
pnpm run dev
# Run tests
pnpm run test
# Lint
pnpm run lint pnpm run lint
``` ```
Inside the meta-root, prefer the dev stack's in-container build (`dev/scripts/reload-meta-fuse.sh`) — see the meta-root [CLAUDE.md](../../CLAUDE.md).
### Building FUSE Driver ### Building FUSE Driver
```bash ```bash
cd packages/meta-fuse-driver cd packages/meta-fuse-driver
cargo build --release cargo build --release --locked
# Run driver # Run driver: <mountpoint> [api-url] [uid] [gid]
./target/release/meta-fuse-driver \ ./target/release/meta-fuse-driver /mnt/virtual http://localhost:3000
--mount-point /mnt/virtual \
--api-url http://localhost:3000
``` ```
### Project Scripts ### Project Scripts
@@ -485,9 +427,9 @@ cargo build --release
|---------|-------------| |---------|-------------|
| `pnpm run build` | Build all packages | | `pnpm run build` | Build all packages |
| `pnpm run dev` | Development mode with hot reload | | `pnpm run dev` | Development mode with hot reload |
| `pnpm run start:core` | Start core service | | `pnpm run start` / `start:core` | Start core service |
| `pnpm run start:driver` | Start FUSE driver | | `pnpm run start:ui` | Start UI dev server |
| `pnpm run test` | Run all tests | | `pnpm run test` | Run core tests |
| `pnpm run lint` | Lint all packages | | `pnpm run lint` | Lint all packages |
## How It Works ## How It Works
@@ -498,86 +440,56 @@ cargo build --release
1. Client opens /mnt/virtual/Movies/Action/Movie.mkv 1. Client opens /mnt/virtual/Movies/Action/Movie.mkv
│ │
▼ ▼
2. FUSE driver receives read request 2. FUSE driver receives the request
- Converts path to inode - Converts path to inode
- Calls API: POST /api/fuse/getattr - Calls API: POST /api/fuse/getattr, then /api/fuse/read
│ │
▼ ▼
3. API server queries KV database 3. API server resolves the path from its in-memory VFS
- Looks up metadata by virtual path - Returns a webdavUrl on meta-core's WebDAV for the source file
- Returns sourcePath pointing to actual file
│ │
▼ ▼
4. FUSE driver reads from sourcePath 4. FUSE driver reads byte ranges from that URL (HTTP Range)
- /data/watch/downloads/Movie.2024.1080p.mkv
│ │
▼ ▼
5. Content streamed to client 5. Content streamed to client
- No file duplication - No file duplication
- Direct read from original location - Bytes come from the original location via meta-core
``` ```
### KV Data Structure ### Metadata Access
meta-fuse reads metadata stored by meta-sort using flat Redis keys: meta-fuse never talks to Redis. It reads records through meta-core's HTTP API:
``` ```
# File metadata stored by meta-sort (flat key format) GET /meta → { hashIds: [...] } enumerate records
file:{hashId}/title → "Inception" GET /meta/{hash} → { metadata: {...} } full flat record
file:{hashId}/year → "2010" GET /meta/{hash}/{prop} → text/plain value one property (e.g. titles/eng)
file:{hashId}/filePath → "media1/Movies/Inception (2010)/Inception.mkv"
file:{hashId}/size → 4831838208
file:{hashId}/video/codec → "h265"
file:{hashId}/titles/eng → "Inception"
# File index for enumeration # VFS paths are computed from metadata by the renaming rules, e.g.
file:__index__ → SET of all hashIds
# VFS paths are computed dynamically from metadata
# meta-fuse builds virtual paths like:
# /Movies/Inception (2010)/Inception.mkv # /Movies/Inception (2010)/Inception.mkv
# → resolves to sourcePath: /files/media1/Movies/Inception (2010)/Inception.mkv # → filePath "media1/Movies/Inception (2010)/Inception.mkv" (relative to FILES_VOLUME)
``` ```
**Key Format**: `file:{hashId}/{property}` where: Field names and value formats: meta-root [METADATA_KEYS.md](../../METADATA_KEYS.md). File paths are **relative to FILES_VOLUME** (`/files`).
- `hashId` is the midhash256 content identifier
- `property` can be flat (e.g., `title`) or nested (e.g., `titles/eng`)
**Note**: File paths in Redis are **relative to FILES_VOLUME** (`/files`). meta-fuse prepends the FILES_VOLUME path when resolving actual file locations. ### Real-Time Updates via SSE
### Real-Time Updates via Redis Streams meta-fuse consumes meta-core's `meta:events` stream through SSE at `GET {apiUrl}/api/events/meta`. Each event is a property change:
meta-fuse uses the `meta:events` Redis Stream for real-time metadata updates. The streaming architecture provides:
- **Reliable delivery** - Messages persist until consumed
- **Replay capability** - Can rebuild state from stream position 0
- **Memory efficiency** - Only VFS-relevant properties are fetched
```typescript ```typescript
// Stream message format (meta:events) // SSE event → StreamMessage
interface StreamMessage { {
id: string; // Stream entry ID (e.g., "1703808000000-0") id: string; // Stream entry ID (e.g., "1703808000000-0")
type: 'set' | 'del'; // Operation type type: 'set' | 'del'; // SSE event name
key: string; // Redis key (e.g., "file:abc123/title") key: string; // e.g. "file:abc123/title"
ts: string; // Timestamp
} }
``` ```
**Startup Sequence**: **Startup Sequence**:
1. **Streaming Bootstrap**: Replay `meta:events` stream from position 0 1. **Bootstrap**: VFS state is held only in memory, so every start replays from cursor `0-0` (the cursor is deliberately not persisted; a `gap` event resumes from the oldest retained entry)
2. **Build State**: Process each event, fetch only VFS-relevant properties 2. **Build State**: Parse `file:{hashId}/{property}`, skip properties the rules don't use, fetch the rest
3. **Go Live**: Continue consuming new events from last processed position 3. **Go Live**: Keep consuming new events; a file appears in the VFS once it has a `filePath`
**Event Processing Pipeline**:
1. Parse key to extract `hashId` and `property`
2. Check if property is VFS-relevant (based on renaming rules)
3. If relevant, fetch property value from Redis
4. Update internal state and notify VFS
5. When file has `filePath`, it appears in VFS
This streaming architecture enables:
- Sub-second startup (no HGETALL/SCAN)
- Memory-efficient state (~500 bytes/file)
- Real-time VFS updates as files are processed
--- ---
@@ -586,65 +498,42 @@ This streaming architecture enables:
### FUSE Mount Not Working ### FUSE Mount Not Working
```bash ```bash
# Check if FUSE is available ls -la /dev/fuse # FUSE available?
ls -la /dev/fuse mount | grep virtual # mounted?
curl http://localhost/api/fuse/health
# Verify mount # Driver logs (inside the container)
mount | grep virtual tail -f /var/log/supervisor/fuse-driver.log /var/log/supervisor/fuse-driver_error.log
# Check API health
curl http://localhost:3000/api/fuse/health
# View driver logs
journalctl -u meta-fuse-driver -f
``` ```
### KV Connection Failed ### meta-core Not Found
```bash ```bash
# Check lock file exists # Who this service hears over UDP
cat /meta-core/locks/kv-leader.info curl http://localhost/api/neighbors
# Check /urls API # meta-core's own view + URLs
curl -k https://dev.localhost:8083/api/urls curl -k https://metacore-dev.localhost:8083/api/neighbors
curl -k https://metacore-dev.localhost:8083/api/urls
# Verify redis is running (on leader) # meta-fuse logs
docker exec meta-core-dev redis-cli ping docker logs metafuse-app | grep -E "LeaderClient|KVManager|SSE"
# Check meta-fuse logs
docker logs meta-fuse | grep "KV"
``` ```
If multicast can't cross your network, pin it with `META_CORE_URL`.
### WebDAV Not Accessible ### WebDAV Not Accessible
```bash ```bash
# Check WebDAV health curl -u me:mfwd_xxxxxxxx http://localhost/webdav/ # 401 = bad/revoked token
curl -u metamesh:metamesh http://localhost/webdav/ docker exec metafuse-app tail /var/log/supervisor/wsgidav_error.log
# Verify nginx is proxying
curl -I http://localhost/webdav
# Check WsgiDAV logs
docker logs meta-fuse | grep "wsgidav"
``` ```
### Files Not Appearing ### Files Not Appearing
```bash ```bash
# Check Redis has file data (flat key format) curl http://localhost/api/fuse/stats
docker exec meta-core-dev redis-cli keys "file:*" | head -20 docker logs metafuse-app | grep "State builder"
curl -k https://metacore-dev.localhost:8083/api/stats # does meta-core have records?
# Check file index
docker exec meta-core-dev redis-cli scard "file:__index__"
# Verify source files exist
ls -la /files/watch/
# Check API stats
curl http://localhost:3000/api/fuse/stats
# Check streaming state builder stats
docker logs meta-fuse-dev | grep "State builder"
``` ```
## Technology Stack ## Technology Stack
@@ -654,44 +543,32 @@ docker logs meta-fuse-dev | grep "State builder"
| Core Service | Node.js + TypeScript | API server, VFS logic | | Core Service | Node.js + TypeScript | API server, VFS logic |
| HTTP Framework | Fastify 5.x | REST API | | HTTP Framework | Fastify 5.x | REST API |
| FUSE Driver | Rust + fuser | Filesystem interface | | FUSE Driver | Rust + fuser | Filesystem interface |
| WebDAV | WsgiDAV (Python) | Network file sharing | | WebDAV | WsgiDAV (Python) + token DomainController | Network file sharing |
| KV Database | Redis (via ioredis) | Metadata storage | | Metadata | meta-core HTTP API + SSE | Reads and live updates |
| Discovery | beacon v2 (UDP multicast) | Locating meta-core and neighbours |
| Reverse Proxy | nginx | Request routing | | Reverse Proxy | nginx | Request routing |
| Containerization | Docker | Deployment | | Containerization | Docker + supervisord | Deployment |
## Integration with MetaMesh ## Integration with MetaMesh
Meta-Fuse is designed to work seamlessly with other MetaMesh services: - **meta-core**: Source of metadata (HTTP/SSE) and file bytes (WebDAV)
- **meta-sort**: Produces the metadata meta-fuse organizes
- **meta-sort**: Provides metadata in KV database - **meta-stremio**: Reads the same metadata for streaming
- **meta-stremio**: Can stream files exposed by meta-fuse
- **meta-orbit**: Syncs metadata across P2P network
### Connecting to meta-sort
Ensure meta-sort is running and has processed files:
```bash ```bash
# Check meta-sort processing status # Is meta-sort producing records?
curl -k https://dev.localhost:8180/api/processing/status curl -k https://metasort-dev.localhost:8180/api/processing/status
curl -k https://metacore-dev.localhost:8083/api/stats
# Verify Redis has metadata (via meta-core)
docker exec meta-core-dev redis-cli scard "file:__index__"
# Check meta:events stream has events
docker exec meta-core-dev redis-cli xlen "meta:events"
``` ```
Meta-fuse will automatically discover the KV database through the shared lock file at `/meta-core/locks/kv-leader.info`.
## Documentation ## Documentation
For detailed architecture documentation, see the `docs/` directory: - [VFS Rebuild Architecture](docs/vfs-rebuild-architecture.md) - How VFS state is built from the event stream
- [VFS Rebuild Architecture](docs/vfs-rebuild-architecture.md) - How VFS state is built from Redis Streams
- [Streaming Architecture](docs/streaming-architecture.md) - Event processing pipeline details - [Streaming Architecture](docs/streaming-architecture.md) - Event processing pipeline details
- [API Reference](docs/api-reference.md) - Complete REST API documentation - [API Reference](docs/api-reference.md) - REST API documentation
(These predate the HTTP/SSE migration in places; the code is authoritative.)
## License ## License
MIT License - See [LICENSE](LICENSE) for details. MIT (see `package.json`).
+3
View File
@@ -72,3 +72,6 @@ autorestart=true
stdout_logfile=/var/log/supervisor/wsgidav.log stdout_logfile=/var/log/supervisor/wsgidav.log
stderr_logfile=/var/log/supervisor/wsgidav_error.log stderr_logfile=/var/log/supervisor/wsgidav_error.log
startsecs=5 startsecs=5
environment=
PYTHONPATH="/app/docker",
TOKEN_STORE_PATH="/meta-fuse/config/webdav-tokens.json"
+71
View File
@@ -0,0 +1,71 @@
"""
WsgiDAV custom DomainController for meta-fuse WebDAV access tokens.
Reads `${TOKEN_STORE_PATH}` (a JSON file written by meta-fuse's TokenStore.ts)
fresh on every basic-auth request — no caching, so token revocation from the
dashboard takes effect on the next request.
Username is ignored: the WebDAV password IS the token. We accept any
non-empty username so generic clients (Finder, Plex, davfs2) that demand both
fields keep working.
"""
import hashlib
import json
import os
from typing import Any
from wsgidav.dc.base_dc import BaseDomainController
# Match the prefix produced by TokenStore.ts.
TOKEN_PREFIX = "mfwd_"
TOKEN_STORE_DEFAULT = "/meta-fuse/config/webdav-tokens.json"
class WebdavTokenController(BaseDomainController):
"""
Auth provider backed by meta-fuse's per-device token store.
WsgiDAV calls `basic_auth_user(realm, user_name, password, environ)` for
every request that requires auth. We hash the candidate password with
sha256 and check it against the persisted records.
"""
def __init__(self, wsgidav_app: Any, config: dict) -> None:
super().__init__(wsgidav_app, config)
self._store_path = os.environ.get("TOKEN_STORE_PATH", TOKEN_STORE_DEFAULT)
# --- BaseDomainController contract --------------------------------------
def get_domain_realm(self, path_info: str, environ: dict) -> str:
# Single realm — all paths require the same token.
return "metafuse-webdav"
def require_authentication(self, realm: str, environ: dict) -> bool:
return True
def supports_http_digest_auth(self) -> bool:
# Tokens are not stored in plaintext, so we cannot answer digest
# challenges — clients must use basic auth (over TLS).
return False
def basic_auth_user(
self, realm: str, user_name: str, password: str, environ: dict
) -> bool:
if not password or not password.startswith(TOKEN_PREFIX):
return False
try:
with open(self._store_path, "r", encoding="utf-8") as fh:
store = json.load(fh)
except FileNotFoundError:
return False
except (OSError, json.JSONDecodeError):
# Treat unreadable store as "no valid tokens" — fail closed.
return False
candidate = hashlib.sha256(password.encode("utf-8")).hexdigest()
for token in store.get("tokens", []):
if token.get("hash") == candidate:
return True
return False
+8 -16
View File
@@ -3,17 +3,14 @@
host: 0.0.0.0 host: 0.0.0.0
port: 8080 port: 8080
# Simple user authentication # Authentication is delegated to a custom DomainController that validates the
simple_dc: # basic-auth password against meta-fuse's per-device token store. Any
user_mapping: # non-empty username is accepted; the password IS the token (`mfwd_*`).
"/": http_authenticator:
metamesh: domain_controller: webdav_token_controller.WebdavTokenController
password: metamesh accept_basic: true
roles: ["editor"] accept_digest: false
"/webdav": default_to_digest: false
metamesh:
password: metamesh
roles: ["editor"]
# Mount the virtual filesystem # Mount the virtual filesystem
provider_mapping: provider_mapping:
@@ -31,11 +28,6 @@ server: cheroot
server_args: server_args:
numthreads: 10 numthreads: 10
# Authentication settings
accept_basic: true
accept_digest: false
default_to_digest: false
# HTTP configuration # HTTP configuration
add_header_MS_Author_Via: false add_header_MS_Author_Via: false
+7 -7
View File
@@ -535,29 +535,29 @@ List all discovered MetaMesh services.
"services": [ "services": [
{ {
"name": "meta-sort", "name": "meta-sort",
"url": "http://meta-sort-dev", "url": "http://metasort-app",
"api": "http://meta-sort-dev/api", "api": "http://metasort-app/api",
"status": "healthy", "status": "healthy",
"role": "writer" "role": "writer"
}, },
{ {
"name": "meta-fuse", "name": "meta-fuse",
"url": "http://meta-fuse-dev", "url": "http://metafuse-app",
"api": "http://meta-fuse-dev/api", "api": "http://metafuse-app/api",
"status": "healthy", "status": "healthy",
"role": "reader" "role": "reader"
}, },
{ {
"name": "meta-stremio", "name": "meta-stremio",
"url": "http://meta-stremio-dev", "url": "http://metastremio-app",
"api": "http://meta-stremio-dev/api", "api": "http://metastremio-app/api",
"status": "healthy", "status": "healthy",
"role": "reader" "role": "reader"
} }
], ],
"current": "meta-fuse", "current": "meta-fuse",
"leader": { "leader": {
"hostname": "meta-core-dev", "hostname": "metacore-app",
"baseUrl": "http://localhost:8083", "baseUrl": "http://localhost:8083",
"apiUrl": "http://meta-core:9000", "apiUrl": "http://meta-core:9000",
"redisUrl": "redis://meta-core:6379", "redisUrl": "redis://meta-core:6379",
+1 -1
View File
@@ -350,7 +350,7 @@ The `onFileComplete` callback is called when:
``` ```
[meta-fuse] Starting meta-fuse... [meta-fuse] Starting meta-fuse...
[KVManager] Waiting for leader... [KVManager] Waiting for leader...
[LeaderClient] Leader found: meta-core-dev at redis://meta-core:6379 [LeaderClient] Leader found: metacore-app at redis://meta-core:6379
[meta-fuse] KV Manager ready, initializing VFS with streaming bootstrap... [meta-fuse] KV Manager ready, initializing VFS with streaming bootstrap...
[StreamingStateBuilder] Initialized with 12 VFS-relevant properties [StreamingStateBuilder] Initialized with 12 VFS-relevant properties
[meta-fuse] Replaying meta:events stream from position 0... [meta-fuse] Replaying meta:events stream from position 0...
+60 -25
View File
@@ -13,6 +13,7 @@ import type { RenamingConfig, RenamingRule, PreviewResponse } from '../vfs/types
import { TEMPLATE_VARIABLES } from '../vfs/types/RenamingRuleTypes.js'; import { TEMPLATE_VARIABLES } from '../vfs/types/RenamingRuleTypes.js';
import { TemplateEngine } from '../vfs/template/TemplateEngine.js'; import { TemplateEngine } from '../vfs/template/TemplateEngine.js';
import { ConditionEvaluator } from '../vfs/template/ConditionEvaluator.js'; import { ConditionEvaluator } from '../vfs/template/ConditionEvaluator.js';
import { TokenStore } from '../webdav/TokenStore.js';
const logger = new Logger({ name: 'APIServer' }); const logger = new Logger({ name: 'APIServer' });
@@ -30,6 +31,7 @@ export class APIServer {
private vfs: VirtualFileSystem; private vfs: VirtualFileSystem;
private kvManager: KVManager | null = null; private kvManager: KVManager | null = null;
private config: Required<APIServerConfig>; private config: Required<APIServerConfig>;
private tokenStore: TokenStore;
constructor(vfs: VirtualFileSystem, config: APIServerConfig = {}, kvManager?: KVManager) { constructor(vfs: VirtualFileSystem, config: APIServerConfig = {}, kvManager?: KVManager) {
this.vfs = vfs; this.vfs = vfs;
@@ -38,6 +40,10 @@ export class APIServer {
port: config.port ?? parseInt(process.env.API_PORT ?? '3000', 10), port: config.port ?? parseInt(process.env.API_PORT ?? '3000', 10),
host: config.host ?? process.env.API_HOST ?? '0.0.0.0', host: config.host ?? process.env.API_HOST ?? '0.0.0.0',
}; };
// CONFIG_DIR is the same dir ConfigStorage uses for renaming rules.
this.tokenStore = new TokenStore({
configDir: process.env.CONFIG_DIR ?? '/meta-fuse/config',
});
this.app = Fastify({ this.app = Fastify({
logger: false, logger: false,
@@ -85,42 +91,71 @@ export class APIServer {
this.app.post('/api/fuse/rules/validate', this.handleValidateRule.bind(this)); this.app.post('/api/fuse/rules/validate', this.handleValidateRule.bind(this));
this.app.get('/api/fuse/rules/variables', this.handleGetVariables.bind(this)); this.app.get('/api/fuse/rules/variables', this.handleGetVariables.bind(this));
// Service discovery — proxies to meta-core's /api/services, resolving the // beacon v2: neighbours heard over UDP, from this service's own
// current leader's URL via LeaderClient (no hardcoded hostname). // map — no meta-core needed, so the nav renders even when the core is down.
this.app.get('/api/services', this.handleServices.bind(this)); this.app.get('/api/neighbors', this.handleNeighbors.bind(this));
// WebDAV access tokens (per-device basic-auth passwords for /webdav).
this.app.get('/api/webdav-tokens', this.handleListTokens.bind(this));
this.app.post('/api/webdav-tokens', this.handleCreateToken.bind(this));
this.app.delete('/api/webdav-tokens/:id', this.handleRevokeToken.bind(this));
}
private async handleListTokens(_req: FastifyRequest, reply: FastifyReply): Promise<void> {
reply.send({ tokens: this.tokenStore.list() });
}
private async handleCreateToken(
req: FastifyRequest<{ Body: { label?: string } }>,
reply: FastifyReply
): Promise<void> {
const label = (req.body?.label ?? '').toString();
if (label.length > 200) {
reply.status(400).send({ error: 'label too long (max 200 chars)' });
return;
}
const { plaintext, view } = this.tokenStore.create(label);
// The plaintext is included exactly once in this response — the dashboard
// surfaces it to the user and then discards it. Subsequent GETs do not
// include it.
reply.status(201).send({ ...view, token: plaintext });
}
private async handleRevokeToken(
req: FastifyRequest<{ Params: { id: string } }>,
reply: FastifyReply
): Promise<void> {
const ok = this.tokenStore.revoke(req.params.id);
if (!ok) {
reply.status(404).send({ error: 'token not found' });
return;
}
reply.status(204).send();
} }
/** /**
* Proxy handler that forwards /api/services to meta-core's canonical * beacon v2 neighbours, served from this service's own UDP map.
* registry endpoint using LeaderClient for discovery. * `services` is an alias kept while older dashboard builds are around.
*/ */
private async handleServices(_req: FastifyRequest, reply: FastifyReply): Promise<void> { private async handleNeighbors(request: FastifyRequest, reply: FastifyReply): Promise<void> {
try {
const leaderClient = this.kvManager?.getLeaderClient(); const leaderClient = this.kvManager?.getLeaderClient();
if (!leaderClient) { if (!leaderClient) {
reply.status(503).send({ error: 'KVManager not initialized' }); void reply.send({ current: 'meta-fuse', enabled: false, count: 0, neighbors: [] });
return; return;
} }
const apiUrl = await leaderClient.getApiUrl(); const q = (request.query ?? {}) as { all?: string; cap?: string };
if (!apiUrl) { const neighbors = leaderClient.getNeighbors({ all: !!q.all, cap: q.cap || undefined });
reply.status(503).send({ error: 'Leader not available yet' }); void reply.send({
return; current: 'meta-fuse',
} enabled: true,
const response = await fetch(`${apiUrl}/api/services`, { count: neighbors.length,
signal: AbortSignal.timeout(5000), neighbors,
services: neighbors,
self: leaderClient.self(),
}); });
if (!response.ok) {
reply.status(response.status).send({
error: `Upstream ${apiUrl} returned ${response.status}`,
});
return;
}
reply.send(await response.json());
} catch (err: any) {
reply.status(502).send({ error: err?.message ?? String(err) });
}
} }
/** /**
* Start the server * Start the server
*/ */
@@ -0,0 +1,666 @@
/**
* Beacon v2 — local resource advertise / discover over UDP multicast
* (239.255.99.1:9099).
*
* Every node advertises resources tagged with capability strings
* (`metamesh.core`, `metamesh.service/meta-sort`, `metamesh.transport/nzb@1`)
* and keeps a live view of everyone else's. This service uses it to locate
* meta-core (the `metamesh.core` resource carries its /urls block) and to feed
* the nav menu (`metamesh.service/*`), with no shared volume.
*
* The normative spec is docs/project-architecture/beacon-v2.md.
*
* ⚠ MIRRORED FILE. Byte-identical copies live in meta-sort-core, meta-fuse-core
* and meta-dup-core. They cannot share a package: meta-fuse-core and
* meta-dup-core do not depend on @metazla/meta-interface at all, and each
* submodule is its own Docker build context, so a workspace dep resolves
* outside the build. Edit one copy → edit all three, and
* `scripts/check-mirrors.sh` will tell you if you forgot.
*/
import dgram from 'dgram';
import { hostname, networkInterfaces } from 'os';
export const PROTO = 'beacon';
export const VERSION = 2;
export const DEFAULT_GROUP = '239.255.99.1';
export const DEFAULT_PORT = 9099;
export const DEFAULT_INTERVAL_MS = 10_000;
/** A node unheard for interval × this is dropped (evaluated at read time). */
export const LIVENESS_FACTOR = 3;
/** Senders stay under this so nothing fragments. */
export const MAX_DATAGRAM = 1400;
export const TYPE_PROBE = 'probe';
export const TYPE_ADVERTISE = 'advertise';
export const TYPE_BYE = 'bye';
export const CAP_CORE = 'metamesh.core';
export const CAP_SERVICE_PREFIX = 'metamesh.service/';
export const CAP_ANY_SERVICE = 'metamesh.service/*';
/** Mirrors meta-core's GET /urls response minus redisUrl (retired). */
export interface MeshUrls {
hostname: string;
baseUrl: string;
apiUrl: string;
webdavUrl: string;
webdavUrlInternal: string;
}
export interface BeaconNodeInfo {
name: string;
instance: string;
version?: string;
/** 'starting' | 'running'; absent reads as running. */
status?: string;
}
export interface BeaconResource {
id: string;
caps: string[];
/** Well-known: http, ui, manifest, mcp. A '/…' value is relative to http. */
endpoints?: Record<string, string>;
rev?: string;
/** The one consumer instance this resource belongs to. */
binds?: string;
data?: Record<string, unknown>;
}
export interface BeaconMessage {
proto: string;
v: number;
type: string;
node?: BeaconNodeInfo;
resources?: BeaconResource[];
from?: string;
want?: string[];
}
/** A node as served by /api/neighbors. */
export interface MeshNeighbor extends BeaconNodeInfo {
resources: BeaconResource[];
/** Every resource's caps, flattened. */
caps: string[];
/** The metamesh.service/* resource's endpoints.ui (v1-compatible field). */
baseUrl?: string;
/** Source address taken from the packet, never from the payload. */
addr: string;
/** Unix seconds. */
lastSeen: number;
}
export interface MeshNodeConfig {
name: string;
instance?: string;
version?: string;
group?: string;
port?: number;
intervalMs?: number;
enabled?: boolean;
/** Rebuilt on every advertise so the payload never goes stale. */
payload?: () => { status?: string; resources: BeaconResource[] };
}
/** How a discovered resource relates to this consumer (Scan card). */
export type ScanState = 'configured' | 'addable' | 'bound-elsewhere';
export interface ScanCandidate {
instance: string;
name: string;
version?: string;
resourceId: string;
caps: string[];
/** endpoints.http — what the consumer would register. */
url: string;
binds?: string;
state: ScanState;
/** The list entry that already holds this URL (state `configured`). */
configuredAs?: string;
/** A list-safe name to register it under. */
suggestedName: string;
}
/** Same JSON as meta-feeder-sdk `beacon::ScanReport`. */
export interface ScanReport {
cap: string;
self: string;
durationMs: number;
summary: { nodes: number; capable: number; configured: number; boundElsewhere: number; addable: number };
candidates: ScanCandidate[];
}
/** Lower-case, `[a-z0-9._-]` only — accepted by every consumer's name rules. */
export function suggestedName(instance: string): string {
const s = instance.trim().toLowerCase().replace(/[^a-z0-9._-]/g, '-');
return s || 'plugin';
}
const normUrl = (u: string) => u.trim().replace(/\/+$/, '');
/**
* Classify every resource matching `pattern` against the consumer's
* `(name, url)` list. Mirrors meta-feeder-sdk `beacon::classify`.
*/
export function classifyScan(
pattern: string,
self: string,
neighbors: MeshNeighbor[],
configured: Array<[string, string]>,
): ScanReport {
const summary = { nodes: neighbors.length, capable: 0, configured: 0, boundElsewhere: 0, addable: 0 };
const candidates: ScanCandidate[] = [];
for (const n of neighbors) {
for (const r of n.resources) {
if (!resourceMatches(r, pattern)) continue;
const http = resourceEndpoint(r, 'http');
if (!http) continue; // nothing a consumer could register
const url = normUrl(http);
summary.capable++;
const hit = configured.find(([, u]) => normUrl(u) === url);
let state: ScanState;
if (hit) { state = 'configured'; summary.configured++; }
else if (r.binds && r.binds !== self) { state = 'bound-elsewhere'; summary.boundElsewhere++; }
else { state = 'addable'; summary.addable++; }
candidates.push({
instance: n.instance,
name: n.name,
...(n.version ? { version: n.version } : {}),
resourceId: r.id,
caps: r.caps ?? [],
url,
...(r.binds ? { binds: r.binds } : {}),
state,
...(hit ? { configuredAs: hit[0] } : {}),
suggestedName: suggestedName(n.instance),
});
}
}
const rank: Record<ScanState, number> = { addable: 0, configured: 1, 'bound-elsewhere': 2 };
candidates.sort((a, b) => rank[a.state] - rank[b.state] || a.instance.localeCompare(b.instance));
return { cap: pattern, self, durationMs: 0, summary, candidates };
}
/**
* Does capability `cap` satisfy `pattern`? `*` matches everything; an `@N` on
* the pattern must equal the cap's contract (none ignores it); `x/*` matches
* any variant of `x`; otherwise the bases must be equal.
*/
export function capMatches(pattern: string, cap: string): boolean {
if (pattern === '*') return true;
const split = (s: string): [string, string | null] => {
const i = s.lastIndexOf('@');
return i >= 0 ? [s.slice(0, i), s.slice(i + 1)] : [s, null];
};
const [pbase, pc] = split(pattern);
const [cbase, cc] = split(cap);
if (pc !== null && cc !== pc) return false;
if (pbase.endsWith('/*')) {
const prefix = pbase.slice(0, -2);
if (!cbase.startsWith(prefix)) return false;
const rest = cbase.slice(prefix.length);
return rest.startsWith('/') && rest.length > 1;
}
return pbase === cbase;
}
export function resourceMatches(r: BeaconResource, pattern: string): boolean {
return (r.caps ?? []).some((c) => capMatches(pattern, c));
}
/** The named endpoint as an absolute URL ('/…' joins onto endpoints.http). */
export function resourceEndpoint(r: BeaconResource, name: string): string | undefined {
const v = r.endpoints?.[name];
if (!v) return undefined;
if (!v.startsWith('/')) return v;
const base = r.endpoints?.http;
return base ? base.replace(/\/+$/, '') + v : undefined;
}
/**
* Decode a datagram; null for anything that is not a well-formed beacon v2
* message (beacon v1, meta-discovery v1, other versions, junk).
*/
export function parseMessage(buf: Buffer): BeaconMessage | null {
let m: BeaconMessage;
try {
m = JSON.parse(buf.toString('utf8')) as BeaconMessage;
} catch {
return null;
}
if (!m || m.proto !== PROTO || m.v !== VERSION) return null;
if (m.type === TYPE_PROBE) return m;
if (m.type === TYPE_ADVERTISE || m.type === TYPE_BYE) {
if (!m.node?.name || !m.node?.instance) return null;
return m;
}
return null;
}
/** IPv4 addresses of every up, non-internal interface. */
function localInterfaceAddresses(): string[] {
const out: string[] = [];
const nets = networkInterfaces();
for (const name of Object.keys(nets)) {
for (const ni of nets[name] ?? []) {
// Node has flip-flopped between 'IPv4' and 4 for `family`.
const isV4 = (ni as { family: string | number }).family === 'IPv4' ||
(ni as { family: string | number }).family === 4;
if (isV4 && !ni.internal && ni.address) out.push(ni.address);
}
}
return out;
}
/** First non-internal IPv4 address, or the hostname. Matches the Go helper. */
export function localIPv4(): string {
return localInterfaceAddresses()[0] ?? hostname();
}
function envNum(key: string): number | undefined {
const n = Number(process.env[key]);
return Number.isFinite(n) && n > 0 ? n : undefined;
}
interface Seen {
node: BeaconNodeInfo;
resources: BeaconResource[];
addr: string;
lastSeen: number; // ms
}
function toNeighbor(s: Seen): MeshNeighbor {
const caps: string[] = [];
let baseUrl: string | undefined;
for (const r of s.resources) {
for (const c of r.caps ?? []) if (!caps.includes(c)) caps.push(c);
if (!baseUrl && resourceMatches(r, CAP_ANY_SERVICE)) baseUrl = resourceEndpoint(r, 'ui');
}
return {
...s.node,
resources: s.resources,
caps,
...(baseUrl ? { baseUrl } : {}),
addr: s.addr,
lastSeen: s.lastSeen / 1000,
};
}
/**
* One beacon v2 participant: advertises its resources, answers probes, and
* keeps a TTL map of every other node.
*/
export class MeshNode {
private cfg: Required<Omit<MeshNodeConfig, 'payload'>> & Pick<MeshNodeConfig, 'payload'>;
private socket: dgram.Socket | null = null;
private timer: NodeJS.Timeout | null = null;
private nodes = new Map<string, Seen>();
private ifaceAddrs: string[] = [];
private listeners: ((n: MeshNeighbor) => void)[] = [];
private started = false;
constructor(config: MeshNodeConfig) {
this.cfg = {
name: config.name,
instance: config.instance ?? hostname(),
version: config.version ?? '',
group: config.group ?? process.env.BEACON_GROUP ?? DEFAULT_GROUP,
port: config.port ?? envNum('BEACON_PORT') ?? DEFAULT_PORT,
intervalMs: config.intervalMs ?? envNum('BEACON_INTERVAL_MS') ?? DEFAULT_INTERVAL_MS,
enabled: config.enabled ?? true,
payload: config.payload,
};
}
async start(): Promise<void> {
if (this.started || !this.cfg.enabled) {
if (!this.cfg.enabled) console.log('[beacon] Disabled by configuration');
return;
}
this.started = true;
await new Promise<void>((resolve) => {
// reuseAddr sets SO_REUSEADDR (+ SO_REUSEPORT on Linux for udp4),
// so several listeners can share 9099 on one host.
const socket = dgram.createSocket({ type: 'udp4', reuseAddr: true });
this.socket = socket;
socket.on('message', (buf, rinfo) => this.onMessage(buf, rinfo));
socket.on('error', (err) => {
// Never fatal: a host that blocks multicast must degrade, not
// take the service down.
console.error('[beacon] Socket error:', err.message);
});
socket.bind(this.cfg.port, '0.0.0.0', () => {
try {
socket.setMulticastTTL(1); // link-local only
} catch (e) {
console.warn('[beacon] Could not set multicast TTL:', e);
}
// Join on EVERY interface. A container on two docker networks
// that joins only the default route silently sees one network.
this.ifaceAddrs = localInterfaceAddresses();
let joined = 0;
for (const addr of this.ifaceAddrs) {
try {
socket.addMembership(this.cfg.group, addr);
joined++;
} catch (e) {
console.warn(`[beacon] Join ${this.cfg.group} on ${addr} failed:`, e);
}
}
console.log(
`[beacon] Listening on ${this.cfg.group}:${this.cfg.port} as ` +
`${this.cfg.name}/${this.cfg.instance} (joined ${joined} of ${this.ifaceAddrs.length} interfaces)`
);
resolve();
});
});
this.advertise();
this.probe();
this.timer = setInterval(() => this.advertise(), this.cfg.intervalMs);
// Don't hold the event loop open on shutdown.
this.timer.unref?.();
}
async stop(): Promise<void> {
if (!this.started) return;
this.started = false;
if (this.timer) { clearInterval(this.timer); this.timer = null; }
// Bye, so neighbours drop us immediately rather than waiting out the
// staleness window.
this.multicast({ proto: PROTO, v: VERSION, type: TYPE_BYE, node: this.nodeInfo() });
await new Promise<void>((resolve) => {
if (!this.socket) return resolve();
try { this.socket.close(() => resolve()); } catch { resolve(); }
});
this.socket = null;
this.listeners = [];
}
/**
* Multicast a probe. Every node owning a resource matching one of `want`
* (every node, when empty) replies immediately.
*/
probe(want: string[] = []): void {
const msg: BeaconMessage = { proto: PROTO, v: VERSION, type: TYPE_PROBE, from: this.cfg.instance };
if (want.length) msg.want = want;
this.multicast(msg);
}
/** Every live node, sorted by (name, instance). */
getNeighbors(): MeshNeighbor[] {
const cutoff = Date.now() - this.cfg.intervalMs * LIVENESS_FACTOR;
const out: MeshNeighbor[] = [];
for (const [key, s] of this.nodes) {
if (s.lastSeen < cutoff) { this.nodes.delete(key); continue; }
out.push(toNeighbor(s));
}
return out.sort((a, b) => a.name.localeCompare(b.name) || a.instance.localeCompare(b.instance));
}
/** One row per node name, most recently seen instance wins. */
getNeighborsByName(): MeshNeighbor[] {
const best = new Map<string, MeshNeighbor>();
for (const nb of this.getNeighbors()) {
const cur = best.get(nb.name);
if (!cur || nb.lastSeen > cur.lastSeen) best.set(nb.name, nb);
}
return [...best.values()].sort((a, b) => a.name.localeCompare(b.name));
}
/**
* The Scan card: probe everyone, wait `waitMs` for the replies, then
* classify what matches `pattern` against `configured` ([name, url]).
*/
async scan(pattern: string, configured: Array<[string, string]>, waitMs = 1500): Promise<ScanReport> {
const started = Date.now();
this.probe();
await new Promise((r) => setTimeout(r, waitMs));
const report = classifyScan(pattern, this.cfg.instance, this.getNeighbors(), configured);
report.durationMs = Date.now() - started;
return report;
}
/** This node as a row, so a UI can render itself without waiting. */
self(): MeshNeighbor {
const { status, resources } = this.payload();
return toNeighbor({ node: this.nodeInfo(status), resources, addr: '', lastSeen: Date.now() });
}
/** Fires for every advertise received (after the self-echo filter). */
onAdvertise(cb: (n: MeshNeighbor) => void): void {
this.listeners.push(cb);
}
private payload(): { status?: string; resources: BeaconResource[] } {
return this.cfg.payload ? this.cfg.payload() : { resources: [] };
}
private nodeInfo(status?: string): BeaconNodeInfo {
const n: BeaconNodeInfo = { name: this.cfg.name, instance: this.cfg.instance };
if (this.cfg.version) n.version = this.cfg.version;
if (status) n.status = status;
return n;
}
private advertiseMsg(): BeaconMessage {
const { status, resources } = this.payload();
return { proto: PROTO, v: VERSION, type: TYPE_ADVERTISE, node: this.nodeInfo(status), resources };
}
private onMessage(buf: Buffer, rinfo: dgram.RemoteInfo): void {
const msg = parseMessage(buf);
if (!msg) return; // v1 or foreign traffic on the shared group
if (msg.type === TYPE_PROBE) {
if (msg.from === this.cfg.instance) return;
const ad = this.advertiseMsg();
const want = msg.want ?? [];
const wanted = want.length === 0 ||
(ad.resources ?? []).some((r) => want.some((p) => resourceMatches(r, p)));
if (wanted) this.replyTo(ad, rinfo);
return;
}
const node = msg.node!;
if (node.instance === this.cfg.instance) return; // our own echo
if (msg.type === TYPE_BYE) { this.nodes.delete(node.instance); return; }
const seen: Seen = { node, resources: msg.resources ?? [], addr: rinfo.address, lastSeen: Date.now() };
this.nodes.set(node.instance, seen);
const nb = toNeighbor(seen);
for (const cb of this.listeners) {
try { cb(nb); } catch (e) { console.error('[beacon] Listener threw:', e); }
}
}
private encode(msg: BeaconMessage): Buffer {
const body = Buffer.from(JSON.stringify(msg));
if (body.length > MAX_DATAGRAM) {
console.warn(`[beacon] ${body.length}-byte datagram exceeds the fragmentation-safe ${MAX_DATAGRAM}`);
}
return body;
}
private advertise(): void {
this.multicast(this.advertiseMsg());
}
private replyTo(msg: BeaconMessage, rinfo: dgram.RemoteInfo): void {
try {
this.socket?.send(this.encode(msg), rinfo.port, rinfo.address);
} catch (e) {
console.warn('[beacon] Reply failed:', e);
}
}
/** Writes once per interface — the default route alone reaches one network. */
private multicast(msg: BeaconMessage): void {
const socket = this.socket;
if (!socket) return;
const body = this.encode(msg);
for (const addr of this.ifaceAddrs) {
try {
socket.setMulticastInterface(addr);
socket.send(body, this.cfg.port, this.cfg.group);
} catch (e) {
console.warn(`[beacon] Send on ${addr} failed:`, e);
}
}
}
}
export interface MetaCoreLocatorConfig {
/** This service's name, for its own advertise. */
serviceName: string;
/** Browser-facing URL for the nav menu. */
baseUrl?: string;
version?: string;
/**
* Explicit meta-core API URL. When set this ALWAYS wins and the wire is
* never consulted for core selection — see the spec's "the
* metamesh.core pin". This is what stops a client box from latching onto a
* gateway box's core when both are reachable on a shared network.
*/
metaCoreUrl?: string;
group?: string;
port?: number;
intervalMs?: number;
enabled?: boolean;
}
/**
* Locates meta-core over beacon v2 (the first `metamesh.core` resource that
* carries `data.urls`), and advertises this service as
* `metamesh.service/<serviceName>`.
*/
export class MetaCoreLocator {
private node: MeshNode;
private cfg: MetaCoreLocatorConfig;
private current: MeshUrls | null = null;
private changeCallbacks: (() => void)[] = [];
constructor(config: MetaCoreLocatorConfig) {
this.cfg = config;
this.node = new MeshNode({
name: config.serviceName,
version: config.version,
group: config.group,
port: config.port,
intervalMs: config.intervalMs,
enabled: config.enabled,
payload: () => ({
resources: [{
id: 'service',
caps: [CAP_SERVICE_PREFIX + config.serviceName],
endpoints: { ui: config.baseUrl ?? `http://${localIPv4()}` },
}],
}),
});
this.node.onAdvertise((nb) => {
if (this.cfg.metaCoreUrl) return; // pinned: the wire cannot move us
const core = nb.resources.find((r) => resourceMatches(r, CAP_CORE));
const urls = core?.data?.urls as MeshUrls | undefined;
if (!urls?.apiUrl) return;
const prev = this.current;
if (!prev) {
this.current = urls;
console.log(`[beacon] meta-core discovered at ${urls.apiUrl} (${nb.addr})`);
this.notifyChange();
return;
}
if (prev.apiUrl === urls.apiUrl) {
this.current = urls; // refresh the rest of the fields
return;
}
// A second, different core is advertising. Do not flap between
// them — keep the first and say so loudly, because on a PCS box
// this means a client container can see the gateway's core.
console.warn(
`[beacon] Ignoring a second meta-core at ${urls.apiUrl} (${nb.addr}); ` +
`staying with ${prev.apiUrl}. Set META_CORE_URL to pin this explicitly.`
);
});
}
async start(): Promise<void> {
if (this.cfg.metaCoreUrl) {
console.log(`[beacon] meta-core pinned to ${this.cfg.metaCoreUrl}; discovery is advisory`);
}
await this.node.start();
}
async stop(): Promise<void> {
await this.node.stop();
this.changeCallbacks = [];
}
/** The pin if set, else whatever discovery elected. */
getApiUrl(): string | null {
if (this.cfg.metaCoreUrl) return this.cfg.metaCoreUrl;
return this.current?.apiUrl ?? null;
}
/** Full URLs block. null when pinned and /urls has not been fetched yet. */
getUrls(): MeshUrls | null {
return this.current;
}
/**
* Block until meta-core is located. Probes immediately and re-probes every
* 500ms — the same loop shape as the old LeaderClient.waitForLeader, so the
* 30s boot timeout semantics are preserved exactly.
*/
async waitForCore(timeoutMs = 30_000): Promise<string> {
const deadline = Date.now() + timeoutMs;
let logged = false;
while (Date.now() < deadline) {
const url = this.getApiUrl();
if (url) return url;
if (!logged) { console.log('[beacon] Waiting for meta-core...'); logged = true; }
this.node.probe([CAP_CORE]);
await new Promise((r) => setTimeout(r, 500));
}
throw new Error(`[beacon] No meta-core found within ${timeoutMs}ms`);
}
/** Fires when the elected core's apiUrl changes. Replaces the fs.watch. */
onChange(cb: () => void): void {
this.changeCallbacks.push(cb);
}
/**
* Neighbours for /api/neighbors: one row per name (or every instance with
* `all`), optionally only nodes with a resource matching `cap`.
*/
getNeighbors(opts: { all?: boolean; cap?: string } = {}): MeshNeighbor[] {
const list = opts.all ? this.node.getNeighbors() : this.node.getNeighborsByName();
const cap = opts.cap;
return cap ? list.filter((n) => n.resources.some((r) => resourceMatches(r, cap))) : list;
}
self(): MeshNeighbor {
return this.node.self();
}
/** The Scan card — see {@link MeshNode.scan}. */
scan(pattern: string, configured: Array<[string, string]>, waitMs = 1500): Promise<ScanReport> {
return this.node.scan(pattern, configured, waitMs);
}
probe(want: string[] = []): void {
this.node.probe(want);
}
private notifyChange(): void {
for (const cb of this.changeCallbacks) {
try { cb(); } catch (e) { console.error('[beacon] Change callback threw:', e); }
}
}
}
+51 -27
View File
@@ -11,6 +11,7 @@ import 'dotenv/config';
import { Logger } from 'tslog'; import { Logger } from 'tslog';
import { KVManager } from './kv/KVManager.js'; import { KVManager } from './kv/KVManager.js';
import { RedisClient, StreamMessage } from './kv/RedisClient.js'; import { RedisClient, StreamMessage } from './kv/RedisClient.js';
import { SSEEventClient, type SSEEvent } from './kv/SSEEventClient.js';
import { VirtualFileSystem } from './vfs/VirtualFileSystem.js'; import { VirtualFileSystem } from './vfs/VirtualFileSystem.js';
import { StreamingStateBuilder } from './vfs/StreamingStateBuilder.js'; import { StreamingStateBuilder } from './vfs/StreamingStateBuilder.js';
import { APIServer } from './api/APIServer.js'; import { APIServer } from './api/APIServer.js';
@@ -69,6 +70,9 @@ async function main(): Promise<void> {
serviceName: 'meta-fuse', serviceName: 'meta-fuse',
apiPort: config.apiPort, apiPort: config.apiPort,
baseUrl: config.baseUrl, baseUrl: config.baseUrl,
// Pin: when META_CORE_URL is set, UDP discovery never overrides it.
// See docs/project-architecture/service-discovery.md.
metaCoreUrl: process.env.META_CORE_URL,
redisPrefix: config.redisPrefix, redisPrefix: config.redisPrefix,
}); });
@@ -76,13 +80,16 @@ async function main(): Promise<void> {
let vfs: VirtualFileSystem | null = null; let vfs: VirtualFileSystem | null = null;
let stateBuilder: StreamingStateBuilder | null = null; let stateBuilder: StreamingStateBuilder | null = null;
let apiServer: APIServer | null = null; let apiServer: APIServer | null = null;
let sseClient: SSEEventClient | null = null;
// Graceful shutdown // Graceful shutdown
const shutdown = async (signal: string): Promise<void> => { const shutdown = async (signal: string): Promise<void> => {
logger.info(`Received ${signal}, shutting down...`); logger.info(`Received ${signal}, shutting down...`);
try { try {
// Stop stream consumer first // Stop SSE consumer first
if (sseClient) await sseClient.stop();
// Stop legacy stream consumer if it ever ran
if (redisClient) { if (redisClient) {
redisClient.stopStreamConsumer(); redisClient.stopStreamConsumer();
} }
@@ -155,35 +162,52 @@ async function main(): Promise<void> {
// This enables vfs.refresh() to replay the event stream // This enables vfs.refresh() to replay the event stream
vfs.setStreamingStateBuilder(stateBuilder); vfs.setStreamingStateBuilder(stateBuilder);
// Bootstrap: Replay meta:events stream from position 0 // Bootstrap + live stream via SSE on /api/events/meta.
// This rebuilds state from all historical events //
logger.info(`Replaying ${EVENTS_STREAM} stream from position 0 (streaming bootstrap)...`); // We persist the cursor; on a clean restart we resume from where
const bootstrapStart = Date.now(); // we left off. On a `gap` event (cursor trimmed out of retention)
// we fall back to replaying from the oldest available entry,
const lastId = await redisClient.replayStream( // which is good enough to rebuild VFS state because every property
EVENTS_STREAM, // change has been republished into the stream by meta-core.
'0', const apiUrl = leaderInfo?.apiUrl;
async (message: StreamMessage) => { if (!apiUrl) {
throw new Error('meta-core apiUrl not available from leader info; cannot start SSE consumer');
}
logger.info(`Starting SSE consumer for /api/events/meta (apiUrl=${apiUrl})...`);
sseClient = new SSEEventClient({
url: `${apiUrl.replace(/\/+$/, '')}/api/events/meta`,
// Deliberately NOT persisting the cursor. meta-fuse holds
// VFS state purely in memory, so each restart needs to
// rebuild from a full event replay. Setting cursorPath to
// null + initialCursor to "0-0" forces the gap-handling
// path which resumes from the oldest available stream
// entry — i.e. effectively a full bootstrap.
cursorPath: null,
logTag: '[meta-fuse SSE]',
initialCursor: '0-0',
onEvent: async (e: SSEEvent) => {
// Translate SSE event back into the StreamMessage shape
// StreamingStateBuilder expects.
const message: StreamMessage = {
id: e.id,
type: e.event as any,
key: e.data?.key,
path: e.data?.path,
size: e.data?.size,
midhash256: e.data?.midhash256,
oldPath: e.data?.oldPath,
watcherId: e.data?.watcherId,
timestamp: e.data?.timestamp ?? e.data?.ts,
} as StreamMessage;
await handleStreamingEvent(message, stateBuilder!); await handleStreamingEvent(message, stateBuilder!);
}, },
100 // Batch size onGap: (payload) => {
); logger.warn(`SSE cursor ${payload.requested} trimmed; resuming from ${payload.resumeFrom}`);
const bootstrapTime = Date.now() - bootstrapStart;
const stats = vfs.getStats();
logger.info(`Streaming bootstrap complete: ${stats.fileCount} files in ${bootstrapTime}ms`);
// Start live stream consumer from where replay left off
logger.info(`Starting live stream consumer from ${lastId}...`);
redisClient.startSimpleStreamConsumer(
EVENTS_STREAM,
lastId,
async (message: StreamMessage) => {
await handleStreamingEvent(message, stateBuilder!);
}, },
5000 // 5 second block timeout });
).catch(error => { // Fire-and-forget; start() returns when stop() fires.
logger.error('Stream consumer error:', error); sseClient.start().catch((error) => {
logger.error('SSE consumer terminated:', error);
}); });
// Initialize API server (with kvManager for service discovery) // Initialize API server (with kvManager for service discovery)
+1 -1
View File
@@ -58,7 +58,7 @@ export interface IKVClient {
} }
/** /**
* Leader lock file content format (kv-leader.info) * meta-core's identity and URL set (from its UDP announce, or /urls)
* Written by meta-core leader, read by other services * Written by meta-core leader, read by other services
*/ */
export interface LeaderLockInfo { export interface LeaderLockInfo {
+27 -26
View File
@@ -2,7 +2,7 @@
* KV Manager for meta-fuse (FOLLOWER-only) * KV Manager for meta-fuse (FOLLOWER-only)
* *
* Simplified KV manager that: * Simplified KV manager that:
* 1. Discovers the leader via LeaderClient (reads kv-leader.info) * 1. Locates meta-core via LeaderClient (UDP announce, beacon v2)
* 2. Creates Redis client connection * 2. Creates Redis client connection
* 3. Handles reconnection on leader failure * 3. Handles reconnection on leader failure
* *
@@ -13,7 +13,6 @@
import { hostname } from 'os'; import { hostname } from 'os';
import { Logger } from 'tslog'; import { Logger } from 'tslog';
import { LeaderClient } from './LeaderClient.js'; import { LeaderClient } from './LeaderClient.js';
import { ServiceRegistration } from './ServiceRegistration.js';
import { RedisClient } from './RedisClient.js'; import { RedisClient } from './RedisClient.js';
import type { LeaderLockInfo } from './IKVClient.js'; import type { LeaderLockInfo } from './IKVClient.js';
@@ -48,7 +47,6 @@ interface KVManagerConfig {
export class KVManager { export class KVManager {
private config: Required<KVManagerConfig>; private config: Required<KVManagerConfig>;
private leaderClient: LeaderClient | null = null; private leaderClient: LeaderClient | null = null;
private serviceRegistration: ServiceRegistration | null = null;
private redisClient: RedisClient | null = null; private redisClient: RedisClient | null = null;
private isStarted = false; private isStarted = false;
private isShuttingDown = false; private isShuttingDown = false;
@@ -80,14 +78,15 @@ export class KVManager {
logger.info(`Starting KVManager for ${this.config.serviceName}...`); logger.info(`Starting KVManager for ${this.config.serviceName}...`);
// Initialize and start service registration for heartbeat // No separate service registration step any more: the LeaderClient's
const apiUrl = this.config.baseUrl || `http://${hostname()}:${this.config.apiPort}`; // discovery node announces this service on the same UDP group it
this.serviceRegistration = new ServiceRegistration({ // listens on, so being discoverable and discovering are one thing.
metaCorePath: this.config.metaCorePath, // Browser-facing URL for the nav menu, in the order the spec requires:
serviceName: this.config.serviceName, // PUBLIC_URL (reachable when there is no Caddy perimeter in front — a
apiUrl // debug-direct port) -> BASE_URL (the Caddy URL) -> container host.
}); // Announcing a Caddy URL on a stack with no Caddy running is what puts
await this.serviceRegistration.start(); // dead links in every neighbour's menu.
const apiUrl = process.env.PUBLIC_URL || this.config.baseUrl || `http://${hostname()}:${this.config.apiPort}`;
// If direct Redis URL provided, skip leader discovery // If direct Redis URL provided, skip leader discovery
if (this.config.redisUrl) { if (this.config.redisUrl) {
@@ -99,8 +98,9 @@ export class KVManager {
// Use leader client // Use leader client
this.leaderClient = new LeaderClient({ this.leaderClient = new LeaderClient({
metaCorePath: this.config.metaCorePath, metaCoreUrl: this.config.metaCoreUrl || undefined,
metaCoreUrl: this.config.metaCoreUrl || undefined serviceName: this.config.serviceName,
baseUrl: apiUrl,
}); });
// Set up leader change callback // Set up leader change callback
@@ -113,7 +113,7 @@ export class KVManager {
try { try {
const leaderInfo = await this.leaderClient.waitForLeader(30000); const leaderInfo = await this.leaderClient.waitForLeader(30000);
logger.info(`Connecting to Redis at ${leaderInfo.redisUrl}...`); logger.info(`Connecting to Redis at ${leaderInfo.redisUrl}...`);
await this.connectToRedis(leaderInfo.redisUrl); await this.connectToRedis(leaderInfo.redisUrl, leaderInfo.apiUrl);
} catch (error: any) { } catch (error: any) {
logger.error(`Failed to connect to leader: ${error.message}`); logger.error(`Failed to connect to leader: ${error.message}`);
throw error; throw error;
@@ -141,7 +141,7 @@ export class KVManager {
try { try {
const leaderInfo = await this.leaderClient.waitForLeader(30000); const leaderInfo = await this.leaderClient.waitForLeader(30000);
logger.info(`Reconnecting to Redis at ${leaderInfo.redisUrl}...`); logger.info(`Reconnecting to Redis at ${leaderInfo.redisUrl}...`);
await this.connectToRedis(leaderInfo.redisUrl); await this.connectToRedis(leaderInfo.redisUrl, leaderInfo.apiUrl);
} catch (error: any) { } catch (error: any) {
logger.error(`Failed to reconnect: ${error.message}`); logger.error(`Failed to reconnect: ${error.message}`);
} }
@@ -163,10 +163,6 @@ export class KVManager {
} }
// Stop service registration (if it was started) // Stop service registration (if it was started)
if (this.serviceRegistration) {
await this.serviceRegistration.stop();
this.serviceRegistration = null;
}
// Disconnect Redis // Disconnect Redis
await this.disconnectRedis(); await this.disconnectRedis();
@@ -178,20 +174,28 @@ export class KVManager {
/** /**
* Connect to Redis * Connect to Redis
*/ */
private async connectToRedis(url: string): Promise<void> { private async connectToRedis(url: string, apiUrl?: string): Promise<void> {
try { try {
// Disconnect existing client if any // Disconnect existing client if any
await this.disconnectRedis(); await this.disconnectRedis();
// Create new client // Create new client. When apiUrl is supplied, reads route
// through meta-core HTTP (api-mediated-access PR C).
// When url is also empty, the client is HTTP-only and never
// opens a Redis socket (post-PR D state).
this.redisClient = new RedisClient({ this.redisClient = new RedisClient({
url, url, // may be '' in PR D world
prefix: this.config.redisPrefix, prefix: this.config.redisPrefix,
filesVolume: this.config.filesPath filesVolume: this.config.filesPath,
metaCoreApiUrl: apiUrl,
}); });
await this.redisClient.connect(); await this.redisClient.connect();
if (url) {
logger.info('Connected to Redis'); logger.info('Connected to Redis');
} else {
logger.info('Storage client ready (HTTP-only mode, no Redis)');
}
// Notify ready // Notify ready
this.notifyReady(); this.notifyReady();
@@ -343,9 +347,6 @@ export class KVManager {
/** /**
* Get service registration instance * Get service registration instance
*/ */
getServiceRegistration(): ServiceRegistration | null {
return this.serviceRegistration;
}
/** /**
* Get configured paths * Get configured paths
+140 -149
View File
@@ -1,29 +1,49 @@
/** /**
* LeaderClient - Client for reading leader info from meta-core * LeaderClient - locates meta-core and exposes its URLs.
* *
* This replaces the old LeaderDiscovery.ts by delegating leader election * Since UDP discovery (meta-discovery v1, now beacon v2) this is a thin adapter
* to meta-core (Go sidecar) and just reading the results. * over MetaCoreLocator
* (../discovery/meshdisco.js): meta-core is found by UDP announce instead of by
* reading /meta-core/locks/kv-leader.info, which means this service no longer
* needs the /meta-core volume mounted at all.
* *
* Features: * The public surface is deliberately unchanged so KVManager and its callers did
* - Reads kv-leader.info file for leader URLs * not have to move: getLeaderInfo / getUrls / getApiUrl / getWebdavUrl*,
* - Calls meta-core /urls API for current leader URLs * waitForLeader (same 30s default), startWatching / onChange (the fs.watch on
* - Watches for leader changes via file system watcher * the lock dir became "an announce arrived carrying a different apiUrl").
*
* Precedence is the pin: when metaCoreUrl (META_CORE_URL) is set it always
* wins and the wire is never consulted for core selection. See
* docs/project-architecture/service-discovery.md.
*
* The name "leader" is legacy: meta-core's flock election is vestigial, and
* redisUrl has been empty since the api-mediated-access lockdown.
*/ */
import { promises as fs } from 'fs';
import { watch, FSWatcher } from 'fs';
import { dirname } from 'path';
import { Logger } from 'tslog'; import { Logger } from 'tslog';
import { MetaCoreLocator, type MeshNeighbor, type ScanReport } from '../discovery/meshdisco.js';
import type { LeaderLockInfo } from './IKVClient.js'; import type { LeaderLockInfo } from './IKVClient.js';
const logger = new Logger({ name: 'LeaderClient' }); const logger = new Logger({ name: 'LeaderClient' });
export interface LeaderClientConfig { export interface LeaderClientConfig {
/** Path to META_CORE_VOLUME (e.g., /meta-core) */ /**
metaCorePath: string; * @deprecated Unused since meta-discovery v1. Kept so existing callers
* compile unchanged; nothing reads the volume any more.
*/
metaCorePath?: string;
/** meta-core API URL (e.g., http://meta-core:9000 or http://localhost:9000) */ /** meta-core API URL. When set, discovery never overrides it. */
metaCoreUrl?: string; metaCoreUrl?: string;
/** This service's name, used for its own announce. */
serviceName?: string;
/** Browser-facing URL announced for the nav menu. */
baseUrl?: string;
/** Service version, display only. */
version?: string;
} }
export interface URLsResponse { export interface URLsResponse {
@@ -38,57 +58,75 @@ export interface URLsResponse {
export class LeaderClient { export class LeaderClient {
private config: LeaderClientConfig; private config: LeaderClientConfig;
private infoFilePath: string; private locator: MetaCoreLocator;
private leaderInfo: LeaderLockInfo | null = null; private leaderInfo: LeaderLockInfo | null = null;
private watcher: FSWatcher | null = null;
private onChangeCallbacks: (() => void)[] = []; private onChangeCallbacks: (() => void)[] = [];
private started = false;
// URL caching // Only used on the pinned path, where URLs still come from GET /urls.
// A discovered core carries them in the announce itself.
private cachedUrls: URLsResponse | null = null; private cachedUrls: URLsResponse | null = null;
private urlsCacheTime: number = 0; private urlsCacheTime: number = 0;
private readonly urlsCacheTTL: number = 5000; // 5 seconds private readonly urlsCacheTTL: number = 5000;
constructor(config: LeaderClientConfig) { constructor(config: LeaderClientConfig) {
this.config = config; this.config = config;
this.infoFilePath = `${config.metaCorePath}/locks/kv-leader.info`; this.locator = new MetaCoreLocator({
serviceName: config.serviceName ?? 'meta-fuse',
baseUrl: config.baseUrl,
version: config.version,
metaCoreUrl: config.metaCoreUrl,
enabled: process.env.ENABLE_UDP_DISCOVERY !== 'false' &&
process.env.ENABLE_UDP_DISCOVERY !== '0',
});
this.locator.onChange(() => {
this.cachedUrls = null;
this.urlsCacheTime = 0;
this.notifyChange();
});
}
private async ensureStarted(): Promise<void> {
if (this.started) return;
this.started = true;
await this.locator.start();
} }
/** /**
* Read API URL from file (plain text format) * Guard against a rollback reintroducing direct Redis exposure.
* api-mediated-access PR D removed redisUrl; ALLOW_LEGACY_REDIS_URL=1
* downgrades this to a warning during a deliberate temporary rollback.
*/ */
private async getApiUrlFromFile(): Promise<string | null> { private assertNoRedisUrl(redisUrl: string | undefined): void {
try { if (!redisUrl) return;
const content = await fs.readFile(this.infoFilePath, 'utf-8'); const msg =
return content.trim() || null; 'meta-core still publishes redisUrl; direct Redis access was retired ' +
} catch (error: any) { 'by the api-mediated-access lockdown. Verify meta-core version.';
logger.error(`Failed to read API URL from file: ${error.message}`); if (process.env.ALLOW_LEGACY_REDIS_URL === '1') {
return null; logger.warn('WARNING: ' + msg);
} else {
throw new Error(msg);
} }
} }
/**
* Fetch URLs from meta-core /urls API with caching
*/
private async fetchUrls(apiUrl: string): Promise<URLsResponse | null> { private async fetchUrls(apiUrl: string): Promise<URLsResponse | null> {
// Check cache
const now = Date.now(); const now = Date.now();
if (this.cachedUrls && (now - this.urlsCacheTime) < this.urlsCacheTTL) { if (this.cachedUrls && (now - this.urlsCacheTime) < this.urlsCacheTTL) {
return this.cachedUrls; return this.cachedUrls;
} }
try { try {
const response = await fetch(`${apiUrl}/urls`, { const response = await fetch(`${apiUrl}/urls`, {
method: 'GET', method: 'GET',
headers: { 'Accept': 'application/json' }, headers: { 'Accept': 'application/json' },
signal: AbortSignal.timeout(5000) signal: AbortSignal.timeout(5000)
}); });
if (!response.ok) { if (!response.ok) {
logger.error(`Failed to fetch URLs: ${response.status} ${response.statusText}`); logger.error(`Failed to fetch URLs: ${response.status} ${response.statusText}`);
return null; return null;
} }
const parsed = await response.json() as URLsResponse;
this.cachedUrls = await response.json() as URLsResponse; this.assertNoRedisUrl(parsed.redisUrl);
this.cachedUrls = parsed;
this.urlsCacheTime = now; this.urlsCacheTime = now;
return this.cachedUrls; return this.cachedUrls;
} catch (error: any) { } catch (error: any) {
@@ -98,23 +136,37 @@ export class LeaderClient {
} }
/** /**
* Read leader info from file and /urls API * Resolve meta-core's URLs — straight from the announce when discovered
* (no HTTP hop needed), or over HTTP when pinned.
*/ */
async getUrls(): Promise<URLsResponse | null> {
await this.ensureStarted();
const wire = this.locator.getUrls();
if (wire && !this.config.metaCoreUrl) {
return {
hostname: wire.hostname,
baseUrl: wire.baseUrl,
apiUrl: wire.apiUrl,
redisUrl: '',
webdavUrl: wire.webdavUrl,
webdavUrlInternal: wire.webdavUrlInternal,
isLeader: true,
};
}
const apiUrl = this.locator.getApiUrl();
if (!apiUrl) {
logger.error('No meta-core API URL available');
return null;
}
return this.fetchUrls(apiUrl);
}
async getLeaderInfo(): Promise<LeaderLockInfo | null> { async getLeaderInfo(): Promise<LeaderLockInfo | null> {
try { try {
// Read API URL from file (plain text) const urls = await this.getUrls();
const apiUrl = await this.getApiUrlFromFile(); if (!urls) return null;
if (!apiUrl) {
return null;
}
// Fetch full info from /urls API
const urls = await this.fetchUrls(apiUrl);
if (!urls) {
return null;
}
// Convert URLsResponse to LeaderLockInfo
this.leaderInfo = { this.leaderInfo = {
hostname: urls.hostname, hostname: urls.hostname,
baseUrl: urls.baseUrl, baseUrl: urls.baseUrl,
@@ -123,7 +175,7 @@ export class LeaderClient {
webdavUrl: urls.webdavUrl, webdavUrl: urls.webdavUrl,
webdavUrlInternal: urls.webdavUrlInternal, webdavUrlInternal: urls.webdavUrlInternal,
timestamp: Date.now(), timestamp: Date.now(),
pid: 0 // Unknown for remote leader pid: 0
}; };
return this.leaderInfo; return this.leaderInfo;
} catch (error: any) { } catch (error: any) {
@@ -132,138 +184,64 @@ export class LeaderClient {
} }
} }
/**
* Get Redis URL from leader info
*/
async getRedisUrl(): Promise<string | null> { async getRedisUrl(): Promise<string | null> {
const info = await this.getLeaderInfo(); return (await this.getLeaderInfo())?.redisUrl ?? null;
return info?.redisUrl ?? null;
} }
/**
* Get WebDAV URL from leader info (external, via nginx/HTTPS)
*/
async getWebdavUrl(): Promise<string | null> { async getWebdavUrl(): Promise<string | null> {
const info = await this.getLeaderInfo(); return (await this.getLeaderInfo())?.webdavUrl ?? null;
return info?.webdavUrl ?? null;
} }
/** /** Internal WebDAV URL — use for container-to-container access. */
* Get internal WebDAV URL from leader info (direct to port 9000)
* Use this for container-to-container communication
*/
async getWebdavUrlInternal(): Promise<string | null> { async getWebdavUrlInternal(): Promise<string | null> {
const info = await this.getLeaderInfo(); return (await this.getLeaderInfo())?.webdavUrlInternal ?? null;
return info?.webdavUrlInternal ?? null;
} }
/**
* Get meta-core API URL from leader info
*/
async getApiUrl(): Promise<string | null> { async getApiUrl(): Promise<string | null> {
const info = await this.getLeaderInfo(); return (await this.getLeaderInfo())?.apiUrl ?? null;
return info?.apiUrl ?? null;
} }
/** /**
* Call meta-core /urls API to get current URLs * Block until meta-core is reachable. Probes immediately then every 500ms,
* Useful for getting URLs when you don't want to read the file directly * matching the previous file-polling loop's timing exactly.
*/
async getUrls(): Promise<URLsResponse | null> {
// First try using configured metaCoreUrl
let apiUrl: string | null = this.config.metaCoreUrl ?? null;
// Fall back to reading from file
if (!apiUrl) {
apiUrl = await this.getApiUrlFromFile();
}
if (!apiUrl) {
logger.error('No meta-core API URL available');
return null;
}
return this.fetchUrls(apiUrl);
}
/**
* Wait for leader info to be available
*/ */
async waitForLeader(timeoutMs: number = 30000): Promise<LeaderLockInfo> { async waitForLeader(timeoutMs: number = 30000): Promise<LeaderLockInfo> {
const startTime = Date.now(); await this.ensureStarted();
const pollInterval = 500; const deadline = Date.now() + timeoutMs;
while (Date.now() - startTime < timeoutMs) { await this.locator.waitForCore(timeoutMs);
while (Date.now() < deadline) {
const info = await this.getLeaderInfo(); const info = await this.getLeaderInfo();
if (info) { if (info) {
logger.info(`Leader found: ${info.hostname} at ${info.redisUrl}`); logger.info(`meta-core found: ${info.hostname} at ${info.apiUrl}`);
return info; return info;
} }
logger.debug('Waiting for meta-core...');
logger.debug('Waiting for leader...'); await new Promise(resolve => setTimeout(resolve, 500));
await new Promise(resolve => setTimeout(resolve, pollInterval));
} }
throw new Error(`No meta-core found within ${timeoutMs}ms`);
throw new Error(`No leader found within ${timeoutMs}ms`);
} }
/** /**
* Start watching for leader changes * Previously an fs.watch on the lock directory. Discovery is always
* listening, so this only has to make sure the node is running.
*/ */
startWatching(): void { startWatching(): void {
if (this.watcher) { void this.ensureStarted();
return; // Already watching
} }
const lockDir = dirname(this.infoFilePath);
try {
this.watcher = watch(lockDir, (eventType, filename) => {
if (filename === 'kv-leader.info') {
logger.debug(`Lock file ${eventType}, invalidating cache...`);
// Invalidate cache to force fresh API call
this.cachedUrls = null;
this.urlsCacheTime = 0;
this.getLeaderInfo().then(() => {
this.notifyChange();
}).catch((err) => logger.error(`Error reloading leader info: ${err.message}`));
}
});
this.watcher.on('error', (error: any) => {
logger.warn(`File watcher error: ${error.message}`);
});
logger.info(`Watching for leader changes in ${lockDir}`);
} catch (error: any) {
logger.error(`Failed to start watching: ${error.message}`);
}
}
/**
* Stop watching for leader changes
*/
stopWatching(): void { stopWatching(): void {
if (this.watcher) { // No-op: the locator keeps listening until close().
this.watcher.close();
this.watcher = null;
logger.debug('Stopped watching for leader changes');
}
} }
/**
* Register callback for leader changes
*/
onChange(callback: () => void): this { onChange(callback: () => void): this {
this.onChangeCallbacks.push(callback); this.onChangeCallbacks.push(callback);
return this; return this;
} }
/**
* Notify all change callbacks
*/
private notifyChange(): void { private notifyChange(): void {
logger.debug('meta-core changed, invalidating cache...');
for (const callback of this.onChangeCallbacks) { for (const callback of this.onChangeCallbacks) {
try { try {
callback(); callback();
@@ -273,18 +251,31 @@ export class LeaderClient {
} }
} }
/**
* Get cached leader info (without re-reading file)
*/
getCachedLeaderInfo(): LeaderLockInfo | null { getCachedLeaderInfo(): LeaderLockInfo | null {
return this.leaderInfo; return this.leaderInfo;
} }
/** /**
* Clean up resources * Neighbours for /api/neighbors: one row per name (every instance with
* `all`), optionally only nodes with a capability matching `cap`.
*/ */
getNeighbors(opts: { all?: boolean; cap?: string } = {}): MeshNeighbor[] {
return this.locator.getNeighbors(opts);
}
/** This service's own row, so the menu can show itself. */
self(): MeshNeighbor {
return this.locator.self();
}
/** Beacon v2 Scan card: probe, wait, classify `pattern` against `configured`. */
scan(pattern: string, configured: Array<[string, string]>, waitMs = 1500): Promise<ScanReport> {
return this.locator.scan(pattern, configured, waitMs);
}
close(): void { close(): void {
this.stopWatching();
this.onChangeCallbacks = []; this.onChangeCallbacks = [];
void this.locator.stop();
this.started = false;
} }
} }
@@ -0,0 +1,121 @@
/**
* MetaCoreApiClient — HTTP read client against meta-core for meta-fuse.
*
* meta-fuse needs to read file metadata (property GETs, full-record fetch,
* hashId enumeration) as it builds the VFS. After the api-mediated-access
* lockdown lands these go through meta-core's /meta/{hash} family instead
* of direct Redis reads.
*
* Only the methods meta-fuse actually calls are implemented. See
* meta-core docs/api-mediated-access.md for the full surface.
*/
export interface MetaCoreApiClientConfig {
apiUrl: string;
timeoutMs?: number;
}
export class MetaCoreApiClient {
private apiUrl: string;
private timeoutMs: number;
constructor(config: MetaCoreApiClientConfig) {
this.apiUrl = config.apiUrl.replace(/\/+$/, '');
this.timeoutMs = config.timeoutMs ?? 30000;
}
/**
* GET /meta/{hash}/{prop}. Returns the raw string value or null on 404.
* meta-core sends text/plain for property reads.
*/
async getProperty(hashId: string, property: string): Promise<string | null> {
const path = `/meta/${encodeURIComponent(hashId)}/${this.encodePropertyPath(property)}`;
const url = `${this.apiUrl}${path}`;
const response = await fetch(url, {
method: 'GET',
signal: AbortSignal.timeout(this.timeoutMs),
headers: { Accept: 'text/plain' },
});
if (response.status === 404) return null;
if (!response.ok) {
throw new Error(`[MetaCoreApiClient] GET ${path} → ${response.status} ${response.statusText}`);
}
const text = await response.text();
return text === '' ? null : text;
}
/**
* GET /meta/{hash}. Returns the flat property map or null on 404.
*/
async getMetadataFlat(hashId: string): Promise<Record<string, string> | null> {
const path = `/meta/${encodeURIComponent(hashId)}`;
const body = await this.fetchJsonAllowing404('GET', path);
if (body === null) return null;
const flat = (body as any)?.metadata;
if (!flat || typeof flat !== 'object') return null;
return flat as Record<string, string>;
}
/**
* GET /meta. Enumerates every known hashId.
*/
async getAllHashIds(): Promise<string[]> {
const body = await this.fetchJson('GET', '/meta');
const ids = (body as any)?.hashIds;
return Array.isArray(ids) ? ids : [];
}
/**
* GET /health on meta-core. Used as the connectivity probe.
*/
async health(): Promise<boolean> {
try {
const response = await fetch(`${this.apiUrl}/health`, {
method: 'GET',
signal: AbortSignal.timeout(Math.min(this.timeoutMs, 5000)),
headers: { Accept: 'application/json' },
});
return response.ok;
} catch {
return false;
}
}
private encodePropertyPath(property: string): string {
return property
.split('/')
.map(segment => encodeURIComponent(segment))
.join('/');
}
private async fetchJson(method: string, path: string): Promise<unknown> {
const url = `${this.apiUrl}${path}`;
const response = await fetch(url, {
method,
signal: AbortSignal.timeout(this.timeoutMs),
headers: { Accept: 'application/json' },
});
if (!response.ok) {
throw new Error(`[MetaCoreApiClient] ${method} ${path} → ${response.status} ${response.statusText}`);
}
const text = await response.text();
if (!text) return null;
try { return JSON.parse(text); } catch { return text; }
}
private async fetchJsonAllowing404(method: string, path: string): Promise<unknown> {
const url = `${this.apiUrl}${path}`;
const response = await fetch(url, {
method,
signal: AbortSignal.timeout(this.timeoutMs),
headers: { Accept: 'application/json' },
});
if (response.status === 404) return null;
if (!response.ok) {
throw new Error(`[MetaCoreApiClient] ${method} ${path} → ${response.status} ${response.statusText}`);
}
const text = await response.text();
if (!text) return null;
try { return JSON.parse(text); } catch { return text; }
}
}
+57 -13
View File
@@ -12,6 +12,7 @@ import { Redis } from 'ioredis';
import { Logger } from 'tslog'; import { Logger } from 'tslog';
import * as os from 'os'; import * as os from 'os';
import type { IKVClient, KeyValuePair } from './IKVClient.js'; import type { IKVClient, KeyValuePair } from './IKVClient.js';
import { MetaCoreApiClient } from './MetaCoreApiClient.js';
const logger = new Logger({ name: 'RedisClient' }); const logger = new Logger({ name: 'RedisClient' });
@@ -74,7 +75,6 @@ export interface FileMetadata {
// Title information (for folder organization) // Title information (for folder organization)
title?: string; title?: string;
titles?: { eng?: string; [key: string]: string | undefined };
originalTitle?: string; originalTitle?: string;
fileName?: string; fileName?: string;
@@ -104,15 +104,27 @@ export interface RedisClientConfig {
prefix?: string; prefix?: string;
filesVolume?: string; filesVolume?: string;
reconnectInterval?: number; reconnectInterval?: number;
/**
* meta-core HTTP API base URL. When set, read methods (getProperty,
* getProperties, getMetadataFlat, getAllHashIds, health) route through
* the /meta/{hash} HTTP family instead of touching Redis directly.
*
* This is the meta-fuse half of the api-mediated-access lockdown (see
* meta-core docs/api-mediated-access.md). Reads stay on Redis when
* left unset so tests / one-off scripts still work.
*/
metaCoreApiUrl?: string;
} }
export class RedisClient implements Partial<IKVClient> { export class RedisClient implements Partial<IKVClient> {
private client: Redis | null = null; private client: Redis | null = null;
private subscriber: Redis | null = null; private subscriber: Redis | null = null;
private config: Required<RedisClientConfig>; private config: Required<Omit<RedisClientConfig, 'metaCoreApiUrl'>> & Pick<RedisClientConfig, 'metaCoreApiUrl'>;
private isConnected = false; private isConnected = false;
private reconnectTimer: NodeJS.Timeout | null = null; private reconnectTimer: NodeJS.Timeout | null = null;
private subscriptions: Map<string, (message: string) => void> = new Map(); private subscriptions: Map<string, (message: string) => void> = new Map();
private apiClient: MetaCoreApiClient | null = null;
// Stream consumer state // Stream consumer state
private streamConsumerRunning = false; private streamConsumerRunning = false;
@@ -125,20 +137,33 @@ export class RedisClient implements Partial<IKVClient> {
prefix: config.prefix ?? process.env.REDIS_PREFIX ?? '', prefix: config.prefix ?? process.env.REDIS_PREFIX ?? '',
filesVolume: config.filesVolume ?? process.env.FILES_VOLUME ?? '/files', filesVolume: config.filesVolume ?? process.env.FILES_VOLUME ?? '/files',
reconnectInterval: config.reconnectInterval ?? 5000, reconnectInterval: config.reconnectInterval ?? 5000,
metaCoreApiUrl: config.metaCoreApiUrl,
}; };
if (this.config.metaCoreApiUrl) {
this.apiClient = new MetaCoreApiClient({ apiUrl: this.config.metaCoreApiUrl });
logger.info(`Reads routed through meta-core API at ${this.config.metaCoreApiUrl}`);
}
// Unique consumer name for this instance // Unique consumer name for this instance
this.consumerName = `${os.hostname()}-${process.pid}`; this.consumerName = `${os.hostname()}-${process.pid}`;
} }
/** /**
* Connect to Redis * Connect to Redis. In HTTP-only mode (no URL + apiClient set) this is
* a no-op — reads route through MetaCoreApiClient and stream
* consumption is owned by SSEEventClient at the index.ts layer.
*/ */
async connect(): Promise<void> { async connect(): Promise<void> {
if (this.client && this.isConnected) { if (this.client && this.isConnected) {
return; return;
} }
if (this.apiClient && !this.config.url) {
logger.info('HTTP-only mode — no direct Redis connection');
return;
}
try { try {
this.client = new Redis(this.config.url, { this.client = new Redis(this.config.url, {
retryStrategy: (times: number) => { retryStrategy: (times: number) => {
@@ -236,9 +261,18 @@ export class RedisClient implements Partial<IKVClient> {
} }
/** /**
* Check if connected * Check if the metadata backend is reachable.
*
* In HTTP-only mode (api-mediated-access PR D) there's no Redis socket;
* reachability is signalled by having an apiClient configured. The
* health badge is keyed off this; reporting `false` there would make
* the UI permanently show "Disconnected" even though the service is
* working fine over HTTP.
*/ */
get connected(): boolean { get connected(): boolean {
if (this.apiClient && !this.config.url) {
return true;
}
return this.isConnected; return this.isConnected;
} }
@@ -255,6 +289,15 @@ export class RedisClient implements Partial<IKVClient> {
* @returns The property value or null if not found * @returns The property value or null if not found
*/ */
async getProperty(hashId: string, property: string): Promise<string | null> { async getProperty(hashId: string, property: string): Promise<string | null> {
if (this.apiClient) {
try {
return await this.apiClient.getProperty(hashId, property);
} catch (error: any) {
logger.error(`HTTP getProperty failed for ${hashId}/${property}:`, error.message);
return null;
}
}
if (!this.client || !this.isConnected) { if (!this.client || !this.isConnected) {
return null; return null;
} }
@@ -579,12 +622,6 @@ export class RedisClient implements Partial<IKVClient> {
mtime = isNaN(parsed) ? parseFloat(data.mtime) : parsed; mtime = isNaN(parsed) ? parseFloat(data.mtime) : parsed;
} }
// Parse titles - can be nested object or simple string
let titles: { eng?: string; [key: string]: string | undefined } | undefined;
if (data['titles/eng']) {
titles = { eng: data['titles/eng'] };
}
// Parse season/episode (can be 0 for specials) // Parse season/episode (can be 0 for specials)
const season = data.season !== undefined ? parseInt(data.season, 10) : undefined; const season = data.season !== undefined ? parseInt(data.season, 10) : undefined;
const episode = data.episode !== undefined ? parseInt(data.episode, 10) : undefined; const episode = data.episode !== undefined ? parseInt(data.episode, 10) : undefined;
@@ -603,12 +640,19 @@ export class RedisClient implements Partial<IKVClient> {
mtime, mtime,
ctime: data.ctime ? parseFloat(data.ctime) : mtime, ctime: data.ctime ? parseFloat(data.ctime) : mtime,
// Identification // Identification.
hashId: hashId ?? data.cid_midhash256 ?? data.hashId, //
// `hashId` is always supplied by the caller — every `parseMetadata`
// call site derives it from the Redis key (`file:<hashId>/…`), so the
// fallbacks below it were already unreachable. The two that used to sit
// here (`data.cid_midhash256`, then `data.hashId`) were also the wrong
// shape: `cid_*` fields no longer exist on records, and meta-core
// rejects them at the write boundary. Kept as a single defensive `??`
// rather than a chain of dead ones. See METADATA_KEYS.md §14.13.
hashId: hashId ?? data.hashId,
// Title information // Title information
title: data.title, title: data.title,
titles,
originalTitle: data.originalTitle, originalTitle: data.originalTitle,
fileName: data.fileName, fileName: data.fileName,
@@ -0,0 +1,229 @@
/**
* SSEEventClient — HTTP Server-Sent Events client for meta-core event streams.
*
* Replaces direct Redis Streams consumption. See the same-named module in
* meta-sort for the design rationale (meta-core docs/api-mediated-access.md).
*/
import { promises as fs } from 'fs';
import { dirname } from 'path';
export interface SSEEvent {
id: string;
event: string;
data: any;
}
export interface SSEClientOptions {
url: string;
cursorPath: string | null;
onEvent: (e: SSEEvent) => Promise<void> | void;
onGap?: (payload: { requested: string; resumeFrom: string; reason: string }) => Promise<void> | void;
logTag?: string;
reconnectBaseMs?: number;
reconnectMaxMs?: number;
flushIntervalMs?: number;
/** When set, sent as Last-Event-ID on the *first* connect (e.g. to
* force replay from a specific point). After the first event the
* persisted cursor takes over. */
initialCursor?: string;
}
export class SSEEventClient {
private readonly opts: Required<Omit<SSEClientOptions, 'onGap' | 'initialCursor'>> & Pick<SSEClientOptions, 'onGap' | 'initialCursor'>;
private cursor: string = '';
private cursorDirty = false;
private abort: AbortController | null = null;
private flushTimer: NodeJS.Timeout | null = null;
private stopped = false;
private backoff = 0;
private firstConnect = true;
constructor(options: SSEClientOptions) {
this.opts = {
url: options.url,
cursorPath: options.cursorPath,
onEvent: options.onEvent,
onGap: options.onGap,
logTag: options.logTag ?? '[SSE]',
reconnectBaseMs: options.reconnectBaseMs ?? 500,
reconnectMaxMs: options.reconnectMaxMs ?? 30_000,
flushIntervalMs: options.flushIntervalMs ?? 2000,
initialCursor: options.initialCursor,
};
this.backoff = this.opts.reconnectBaseMs;
}
async start(): Promise<void> {
await this.loadCursor();
if (!this.cursor && this.opts.initialCursor) {
this.cursor = this.opts.initialCursor;
}
this.startFlushTimer();
await this.runLoop();
}
async stop(): Promise<void> {
this.stopped = true;
if (this.abort) {
this.abort.abort();
this.abort = null;
}
if (this.flushTimer) {
clearInterval(this.flushTimer);
this.flushTimer = null;
}
await this.flushCursor();
}
getCursor(): string {
return this.cursor;
}
private async loadCursor(): Promise<void> {
if (!this.opts.cursorPath) return;
try {
const data = await fs.readFile(this.opts.cursorPath, 'utf-8');
const trimmed = data.trim();
if (trimmed) {
this.cursor = trimmed;
console.log(`${this.opts.logTag} Resuming from cursor ${this.cursor}`);
}
} catch (err: any) {
if (err.code !== 'ENOENT') {
console.warn(`${this.opts.logTag} Could not read cursor file ${this.opts.cursorPath}: ${err.message}`);
}
}
}
private startFlushTimer(): void {
this.flushTimer = setInterval(() => {
if (this.cursorDirty) {
this.flushCursor().catch(err =>
console.warn(`${this.opts.logTag} Cursor flush failed: ${err.message}`)
);
}
}, this.opts.flushIntervalMs);
}
private async flushCursor(): Promise<void> {
if (!this.opts.cursorPath || !this.cursorDirty) return;
this.cursorDirty = false;
try {
await fs.mkdir(dirname(this.opts.cursorPath), { recursive: true });
await fs.writeFile(this.opts.cursorPath, this.cursor, 'utf-8');
} catch (err: any) {
this.cursorDirty = true;
throw err;
}
}
private async runLoop(): Promise<void> {
while (!this.stopped) {
try {
await this.connect();
this.backoff = this.opts.reconnectBaseMs;
} catch (err: any) {
if (this.stopped) return;
console.warn(`${this.opts.logTag} Stream error, reconnecting in ${this.backoff}ms: ${err?.message ?? err}`);
await this.sleep(this.backoff);
this.backoff = Math.min(this.backoff * 2, this.opts.reconnectMaxMs);
}
}
}
private async connect(): Promise<void> {
this.abort = new AbortController();
const headers: Record<string, string> = {
Accept: 'text/event-stream',
'Cache-Control': 'no-cache',
};
if (this.cursor) {
headers['Last-Event-ID'] = this.cursor;
}
this.firstConnect = false;
const response = await fetch(this.opts.url, {
method: 'GET',
headers,
signal: this.abort.signal,
});
if (!response.ok) throw new Error(`HTTP ${response.status} ${response.statusText}`);
if (!response.body) throw new Error('Response has no body');
const reader = response.body.getReader();
const decoder = new TextDecoder('utf-8');
let buffer = '';
try {
while (!this.stopped) {
const { value, done } = await reader.read();
if (done) return;
buffer += decoder.decode(value, { stream: true });
let idx: number;
while ((idx = buffer.indexOf('\n\n')) !== -1) {
const rawChunk = buffer.slice(0, idx);
buffer = buffer.slice(idx + 2);
await this.handleChunk(rawChunk);
}
}
} finally {
try { reader.releaseLock(); } catch { /* nothing useful */ }
}
}
private async handleChunk(chunk: string): Promise<void> {
let id = '';
let event = '';
const dataLines: string[] = [];
for (const rawLine of chunk.split('\n')) {
if (!rawLine || rawLine.startsWith(':')) continue;
const colon = rawLine.indexOf(':');
if (colon === -1) continue;
const field = rawLine.slice(0, colon);
let value = rawLine.slice(colon + 1);
if (value.startsWith(' ')) value = value.slice(1);
switch (field) {
case 'id': id = value; break;
case 'event': event = value; break;
case 'data': dataLines.push(value); break;
}
}
if (dataLines.length === 0) return;
let data: any;
try {
data = JSON.parse(dataLines.join('\n'));
} catch (err: any) {
console.warn(`${this.opts.logTag} Skipping unparseable event ${id || '(no id)'}: ${err.message}`);
return;
}
const ev: SSEEvent = { id, event: event || 'message', data };
if (ev.event === 'gap') {
if (this.opts.onGap) {
await this.opts.onGap(ev.data);
} else {
console.warn(`${this.opts.logTag} Gap event (cursor ${ev.data?.requested} trimmed): resumed from ${ev.data?.resumeFrom}`);
}
if (typeof ev.data?.resumeFrom === 'string' && ev.data.resumeFrom) {
this.cursor = ev.data.resumeFrom;
this.cursorDirty = true;
}
return;
}
try {
await this.opts.onEvent(ev);
} catch (err: any) {
console.error(`${this.opts.logTag} onEvent handler failed for ${ev.id}: ${err?.stack ?? err}`);
}
if (ev.id) {
this.cursor = ev.id;
this.cursorDirty = true;
}
}
private sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
@@ -1,211 +0,0 @@
/**
* Service Registration using shared filesystem
*
* Each service registers itself in /meta-core/services/{service-name}-{hostname}.json
* with its base URL, status, and heartbeat timestamp.
*
* Service discovery is centralized in meta-core - this class only handles registration.
* For service discovery, use the /api/services endpoint (proxied to meta-core via nginx).
*
* Each service must call start() to register itself and begin heartbeat updates.
* meta-core runs a cleanup process that removes services with stale heartbeats.
*/
import { promises as fs } from 'fs';
import { hostname } from 'os';
import { Logger } from 'tslog';
import type { ServiceInfo } from './IKVClient.js';
const logger = new Logger({ name: 'ServiceRegistration' });
interface ServiceRegistrationConfig {
/** Path to META_CORE_VOLUME (e.g., /meta-core) */
metaCorePath: string;
/** Service name */
serviceName: string;
/** Base URL for the service */
apiUrl: string;
/** Heartbeat interval in ms (default: 30000) */
heartbeatInterval?: number;
/** Stale threshold in ms (default: 60000) */
staleThreshold?: number;
}
export class ServiceRegistration {
private config: ServiceRegistrationConfig;
private servicesDir: string;
private serviceFilePath: string;
private heartbeatTimer: NodeJS.Timeout | null = null;
private isShuttingDown = false;
private isStarted = false;
private currentHostname: string;
constructor(config: ServiceRegistrationConfig) {
this.config = {
heartbeatInterval: 30000,
staleThreshold: 60000,
...config
};
this.currentHostname = hostname();
this.servicesDir = `${this.config.metaCorePath}/services`;
// Use hostname-based file naming
this.serviceFilePath = `${this.servicesDir}/${this.config.serviceName}-${this.currentHostname}.json`;
}
/**
* Ensure services directory exists
*/
private async ensureServicesDir(): Promise<void> {
await fs.mkdir(this.servicesDir, { recursive: true });
}
/**
* Build service info for this service
*/
private buildServiceInfo(status: ServiceInfo['status']): ServiceInfo {
return {
name: this.config.serviceName,
hostname: this.currentHostname,
baseUrl: this.config.apiUrl,
status,
lastHeartbeat: new Date().toISOString()
};
}
/**
* Register this service by writing service info to the shared filesystem.
* meta-core's cleanup process monitors these files and removes stale entries.
*/
async register(): Promise<void> {
await this.ensureServicesDir();
const info = this.buildServiceInfo('running');
await fs.writeFile(this.serviceFilePath, JSON.stringify(info, null, 2));
logger.info(`Registered ${this.config.serviceName}-${this.currentHostname}`);
}
/**
* Update service status
*/
async updateStatus(status: ServiceInfo['status']): Promise<void> {
try {
const content = await fs.readFile(this.serviceFilePath, 'utf-8');
const info = JSON.parse(content) as ServiceInfo;
info.status = status;
info.lastHeartbeat = new Date().toISOString();
await fs.writeFile(this.serviceFilePath, JSON.stringify(info, null, 2));
} catch (error) {
logger.error('Failed to update status:', error);
}
}
/**
* Send heartbeat (update lastHeartbeat timestamp)
*/
async heartbeat(): Promise<void> {
try {
const content = await fs.readFile(this.serviceFilePath, 'utf-8');
const info = JSON.parse(content) as ServiceInfo;
info.lastHeartbeat = new Date().toISOString();
await fs.writeFile(this.serviceFilePath, JSON.stringify(info, null, 2));
} catch (error: any) {
// If file was deleted, re-register
if (error.code === 'ENOENT') {
await this.register();
} else {
logger.error('Heartbeat failed:', error);
}
}
}
/**
* Start heartbeat loop
*/
startHeartbeat(): void {
this.heartbeatTimer = setInterval(async () => {
if (this.isShuttingDown) return;
await this.heartbeat();
}, this.config.heartbeatInterval);
}
/**
* Stop heartbeat loop
*/
stopHeartbeat(): void {
if (this.heartbeatTimer) {
clearInterval(this.heartbeatTimer);
this.heartbeatTimer = null;
}
}
/**
* Unregister this service (on shutdown)
*/
async unregister(): Promise<void> {
this.isShuttingDown = true;
this.stopHeartbeat();
try {
// Remove the service file
await fs.unlink(this.serviceFilePath);
logger.info(`Unregistered ${this.config.serviceName}-${this.currentHostname}`);
} catch (error: any) {
if (error.code !== 'ENOENT') {
logger.error('Failed to unregister:', error);
}
}
}
// ========================================================================
// Lifecycle
// ========================================================================
/**
* Full startup sequence: register service and start heartbeat loop.
*/
async start(): Promise<void> {
if (this.isStarted) return;
await this.register();
this.startHeartbeat();
this.isStarted = true;
logger.info(`Started ${this.config.serviceName} at ${this.config.apiUrl}`);
}
/**
* Full shutdown sequence
*/
async stop(): Promise<void> {
if (!this.isStarted) return;
await this.unregister();
this.isStarted = false;
}
// ========================================================================
// Getters
// ========================================================================
getServiceFilePath(): string {
return this.serviceFilePath;
}
getServicesDir(): string {
return this.servicesDir;
}
getIsStarted(): boolean {
return this.isStarted;
}
}
@@ -13,7 +13,6 @@
*/ */
export interface MediaMeta { export interface MediaMeta {
// Title information // Title information
titles?: { eng?: string; [key: string]: string | undefined };
originalTitle?: string; originalTitle?: string;
title?: string; title?: string;
@@ -62,7 +61,9 @@ export function renamingRule(metadata: Partial<MediaMeta>, filepath?: string): s
} }
// Get title - try various fields // Get title - try various fields
const title = metadata.titles?.eng || metadata.originalTitle; // The display name — never the `titles/*` name set (METADATA_KEYS.md §3).
// `parsedTitle` is filename-parser's guess (claims model, D12): last resort.
const title = metadata.title || metadata.originalTitle || (metadata as { parsedTitle?: string }).parsedTitle;
if (!title) { if (!title) {
if (metadata.fileType !== 'torrent') { if (metadata.fileType !== 'torrent') {
// Don't warn for torrent files because they don't always have a title // Don't warn for torrent files because they don't always have a title
@@ -174,12 +174,6 @@ export class VirtualFileSystem implements VFSUpdateCallback {
mtime = isNaN(parsed) ? parseFloat(props.mtime) : parsed; mtime = isNaN(parsed) ? parseFloat(props.mtime) : parsed;
} }
// Parse titles - can be from nested paths like 'titles/eng'
let titles: { eng?: string; [key: string]: string | undefined } | undefined;
if (props['titles/eng']) {
titles = { eng: props['titles/eng'] };
}
// Parse season/episode // Parse season/episode
const season = props.season !== undefined ? parseInt(props.season, 10) : undefined; const season = props.season !== undefined ? parseInt(props.season, 10) : undefined;
const episode = props.episode !== undefined ? parseInt(props.episode, 10) : undefined; const episode = props.episode !== undefined ? parseInt(props.episode, 10) : undefined;
@@ -212,7 +206,6 @@ export class VirtualFileSystem implements VFSUpdateCallback {
ctime: props.ctime ? parseFloat(props.ctime) : mtime, ctime: props.ctime ? parseFloat(props.ctime) : mtime,
hashId, hashId,
title: props.title, title: props.title,
titles,
originalTitle: props.originalTitle, originalTitle: props.originalTitle,
fileName, fileName,
season, season,
@@ -443,6 +436,7 @@ export class VirtualFileSystem implements VFSUpdateCallback {
* Compute virtual path for a file using template rules * Compute virtual path for a file using template rules
*/ */
private computeVirtualPath(metadata: FileMetadata, sourcePath: string): string { private computeVirtualPath(metadata: FileMetadata, sourcePath: string): string {
metadata = withParsedTitleFallback(metadata);
if (!this.rulesConfig) { if (!this.rulesConfig) {
// Fallback to old behavior // Fallback to old behavior
return this.metaDataToFolderStruct.generateSingleVirtualPath(sourcePath, metadata); return this.metaDataToFolderStruct.generateSingleVirtualPath(sourcePath, metadata);
@@ -1112,6 +1106,7 @@ export class VirtualFileSystem implements VFSUpdateCallback {
rules: RenamingRule[], rules: RenamingRule[],
defaultRule?: RenamingRule defaultRule?: RenamingRule
): string { ): string {
metadata = withParsedTitleFallback(metadata);
// Sort rules by priority (descending) // Sort rules by priority (descending)
const sortedRules = [...rules] const sortedRules = [...rules]
.filter(r => r.enabled) .filter(r => r.enabled)
@@ -1311,3 +1306,15 @@ export class VirtualFileSystem implements VFSUpdateCallback {
this.onFileComplete(hashId, metadata); this.onFileComplete(hashId, metadata);
} }
} }
/**
* filename-parser's guessed title lives under `parsedTitle` since the claims
* model (it no longer writes `originalTitle`, which tmdb also writes). The
* rules and templates fall back `title` → `originalTitle`; fill a missing
* `originalTitle` from `parsedTitle` on a copy so a file with only a parsed
* title still gets a path. The record itself is never changed.
*/
function withParsedTitleFallback<T extends { originalTitle?: unknown; parsedTitle?: unknown }>(metadata: T): T {
if (metadata.originalTitle || !metadata.parsedTitle) return metadata;
return { ...metadata, originalTitle: metadata.parsedTitle };
}
@@ -7,7 +7,7 @@
* Old behavior: * Old behavior:
* - Only processes video, subtitle, torrent files * - Only processes video, subtitle, torrent files
* - Requires extension * - Requires extension
* - Title from titles.eng || originalTitle * - Title from title || originalTitle
* - Files without title/extension are hidden (not in Unsorted) * - Files without title/extension are hidden (not in Unsorted)
*/ */
@@ -21,7 +21,7 @@ export type ConditionOperator =
*/ */
export interface Condition { export interface Condition {
type: ConditionOperator; type: ConditionOperator;
field: string; // Metadata field path, e.g., "titles.eng", "season", "fileType" field: string; // Metadata field path, e.g., "title", "season", "fileType"
value?: string | number | boolean; // Required for EQUALS, NOT_EQUALS, CONTAINS, MATCHES value?: string | number | boolean; // Required for EQUALS, NOT_EQUALS, CONTAINS, MATCHES
} }
@@ -83,7 +83,7 @@ export interface PreviewResponse {
*/ */
export interface TemplateVariable { export interface TemplateVariable {
name: string; // Display name name: string; // Display name
path: string; // Field path (e.g., "titles.eng") path: string; // Field path (e.g., "title")
type: 'string' | 'number' | 'boolean'; type: 'string' | 'number' | 'boolean';
description: string; description: string;
example?: string; example?: string;
@@ -93,7 +93,6 @@ export interface TemplateVariable {
* List of all available template variables * List of all available template variables
*/ */
export const TEMPLATE_VARIABLES: TemplateVariable[] = [ export const TEMPLATE_VARIABLES: TemplateVariable[] = [
{ name: 'English Title', path: 'titles.eng', type: 'string', description: 'English title from metadata', example: 'Breaking Bad' },
{ name: 'Original Title', path: 'originalTitle', type: 'string', description: 'Original/native title', example: 'Breaking Bad' }, { name: 'Original Title', path: 'originalTitle', type: 'string', description: 'Original/native title', example: 'Breaking Bad' },
{ name: 'Title', path: 'title', type: 'string', description: 'Simple title field', example: 'Breaking Bad' }, { name: 'Title', path: 'title', type: 'string', description: 'Simple title field', example: 'Breaking Bad' },
{ name: 'Season', path: 'season', type: 'number', description: 'Season number', example: '1' }, { name: 'Season', path: 'season', type: 'number', description: 'Season number', example: '1' },
@@ -0,0 +1,138 @@
/**
* TokenStore — Per-device WebDAV access tokens.
*
* Tokens are minted from the OIDC-protected dashboard and used as the
* basic-auth password by WebDAV clients (Plex, Finder, etc.). The plaintext
* is shown to the user once at creation time; only sha256 hashes are
* persisted. The matching WsgiDAV DomainController
* (`docker/webdav_token_controller.py`) reads the same JSON file fresh on
* every auth request, so revocation is immediate.
*
* Tokens identify a *device*, not an OIDC user — multi-user support requires
* hash-lock to forward an X-Forwarded-User header (not currently the case),
* at which point a `userId` field can be added to the record.
*/
import * as crypto from 'crypto';
import * as fs from 'fs';
import * as path from 'path';
import { Logger } from 'tslog';
const logger = new Logger({ name: 'TokenStore' });
/** Length of the random portion (in hex chars) of a generated token. */
const TOKEN_RANDOM_HEX_LEN = 32; // 16 bytes => 128 bits of entropy
/** Public prefix marker so support can grep logs for stray tokens. */
const TOKEN_PREFIX = 'mfwd_';
/** Number of hex chars (after the prefix) we surface in the dashboard list. */
const VISIBLE_PREFIX_LEN = 4;
export interface WebdavTokenRecord {
id: string;
label: string;
hash: string; // sha256(plaintext)
prefix: string; // first VISIBLE_PREFIX_LEN chars of the random portion
createdAt: string; // ISO 8601
}
/** Public view shown in the dashboard list — no plaintext, no hash. */
export interface WebdavTokenView {
id: string;
label: string;
prefix: string;
createdAt: string;
}
interface TokenFile {
tokens: WebdavTokenRecord[];
}
export interface TokenStoreOptions {
configDir: string;
}
export class TokenStore {
private readonly file: string;
private readonly configDir: string;
constructor(opts: TokenStoreOptions) {
this.configDir = opts.configDir;
this.file = path.join(this.configDir, 'webdav-tokens.json');
this.ensureConfigDir();
}
private ensureConfigDir(): void {
if (!fs.existsSync(this.configDir)) {
fs.mkdirSync(this.configDir, { recursive: true });
}
}
private read(): TokenFile {
if (!fs.existsSync(this.file)) return { tokens: [] };
try {
const raw = fs.readFileSync(this.file, 'utf-8');
const parsed = JSON.parse(raw) as TokenFile;
if (!Array.isArray(parsed.tokens)) return { tokens: [] };
return parsed;
} catch (err) {
logger.warn(`Token store ${this.file} unreadable, treating as empty:`, err);
return { tokens: [] };
}
}
/**
* Atomic write — write to a sibling tmp file and rename. WsgiDAV's
* controller reads this file on every auth request, so a partial write
* would briefly fail authentication.
*/
private write(file: TokenFile): void {
const tmp = `${this.file}.tmp`;
fs.writeFileSync(tmp, JSON.stringify(file, null, 2), 'utf-8');
fs.renameSync(tmp, this.file);
}
/** Public list — no plaintext, no hash. */
list(): WebdavTokenView[] {
return this.read().tokens.map(({ id, label, prefix, createdAt }) => ({
id, label, prefix, createdAt,
}));
}
/**
* Mint a new token. Returns the plaintext exactly once — the caller is
* responsible for surfacing it to the user and forgetting it.
*/
create(label: string): { plaintext: string; view: WebdavTokenView } {
const random = crypto.randomBytes(TOKEN_RANDOM_HEX_LEN / 2).toString('hex');
const plaintext = `${TOKEN_PREFIX}${random}`;
const id = crypto.randomBytes(8).toString('hex');
const record: WebdavTokenRecord = {
id,
label: label.trim() || 'Unnamed token',
hash: crypto.createHash('sha256').update(plaintext).digest('hex'),
prefix: random.slice(0, VISIBLE_PREFIX_LEN),
createdAt: new Date().toISOString(),
};
const file = this.read();
file.tokens.push(record);
this.write(file);
logger.info(`Minted WebDAV token id=${id} label=${JSON.stringify(record.label)}`);
return {
plaintext,
view: { id, label: record.label, prefix: record.prefix, createdAt: record.createdAt },
};
}
/** Delete by id. Returns true if a record was removed. */
revoke(id: string): boolean {
const file = this.read();
const idx = file.tokens.findIndex(t => t.id === id);
if (idx < 0) return false;
file.tokens.splice(idx, 1);
this.write(file);
logger.info(`Revoked WebDAV token id=${id}`);
return true;
}
}
+13
View File
@@ -1,6 +1,7 @@
import { useState, useEffect, useCallback } from 'react'; import { useState, useEffect, useCallback } from 'react';
import { RulesEditor } from './components/RulesEditor'; import { RulesEditor } from './components/RulesEditor';
import ServiceNav from './components/ServiceNav'; import ServiceNav from './components/ServiceNav';
import { WebdavTokens } from './components/WebdavTokens';
interface Stats { interface Stats {
fileCount: number; fileCount: number;
@@ -39,6 +40,7 @@ function App() {
const [refreshing, setRefreshing] = useState(false); const [refreshing, setRefreshing] = useState(false);
const [showRules, setShowRules] = useState(false); const [showRules, setShowRules] = useState(false);
const [showSetup, setShowSetup] = useState(false); const [showSetup, setShowSetup] = useState(false);
const [showTokens, setShowTokens] = useState(false);
const fetchData = useCallback(async () => { const fetchData = useCallback(async () => {
try { try {
@@ -223,6 +225,17 @@ function App() {
<RulesEditor onSave={fetchData} /> <RulesEditor onSave={fetchData} />
)} )}
</div> </div>
<div className="subsection">
<div
className="section-header-collapsible"
onClick={() => setShowTokens(!showTokens)}
>
<h3 className="subsection-title">WebDAV Access Tokens</h3>
<span className="collapse-icon">{showTokens ? '-' : '+'}</span>
</div>
{showTokens && <WebdavTokens />}
</div>
</div> </div>
<div className="section"> <div className="section">
@@ -16,7 +16,7 @@ interface RulesEditorProps {
// Available metadata fields for conditions // Available metadata fields for conditions
const AVAILABLE_FIELDS = [ const AVAILABLE_FIELDS = [
{ value: 'fileType', label: 'File Type', type: 'string' }, { value: 'fileType', label: 'File Type', type: 'string' },
{ value: 'titles.eng', label: 'English Title', type: 'string' }, { value: 'title', label: 'Title', type: 'string' },
{ value: 'originalTitle', label: 'Original Title', type: 'string' }, { value: 'originalTitle', label: 'Original Title', type: 'string' },
{ value: 'season', label: 'Season', type: 'number' }, { value: 'season', label: 'Season', type: 'number' },
{ value: 'episode', label: 'Episode', type: 'number' }, { value: 'episode', label: 'Episode', type: 'number' },
@@ -53,7 +53,7 @@ function createEmptyRule(): RenamingRule {
function createEmptyCondition(): Condition { function createEmptyCondition(): Condition {
return { return {
type: 'EXISTS', type: 'EXISTS',
field: 'titles.eng', field: 'title',
}; };
} }
@@ -197,7 +197,7 @@ function TemplateEditor({ template, onChange, variables }: TemplateEditorProps)
<textarea <textarea
value={template} value={template}
onChange={e => onChange(e.target.value)} onChange={e => onChange(e.target.value)}
placeholder="e.g., Movies/{titles.eng|originalTitle}{movieYear? ({movieYear})}/{fileName}.{extension}" placeholder="e.g., Movies/{title|originalTitle}{movieYear? ({movieYear})}/{fileName}.{extension}"
rows={3} rows={3}
className="template-input" className="template-input"
/> />
@@ -1,164 +1,53 @@
import { useState, useEffect } from 'react'; import { useEffect } from 'react';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore -- plain ES module, no .d.ts; imported for its side effect
// of defining the custom element.
import '../meta-service-menu.js';
interface ServiceInfo { /**
name: string; * ServiceNav — the neighbouring meta-* services, as a burger menu.
hostname: string; *
baseUrl: string; * Since meta-discovery v1 this is a thin wrapper around <meta-service-menu>,
status: string; * a framework-free custom element shared by every meta-* UI (see
lastHeartbeat: string; * scripts/check-mirrors.sh). The old implementation was ~165 lines of React
} * that existed in four near-identical copies and polled meta-core's
* /api/services; the element polls this service's own /api/neighbors instead,
* so the nav still renders when meta-core is down.
*
* The element lives in shadow DOM and cannot see this app's CSS variables, so
* the four --mm-nav-* tokens below map our palette onto it.
*/
interface ServicesResponse { declare global {
services: ServiceInfo[]; // eslint-disable-next-line @typescript-eslint/no-namespace
current: string; namespace JSX {
} interface IntrinsicElements {
'meta-service-menu': React.DetailedHTMLProps<
const serviceIcons: Record<string, string> = { React.HTMLAttributes<HTMLElement>,
'meta-sort': '📁', HTMLElement
'meta-fuse': '🗂️', > & { current?: string; endpoint?: string; label?: string };
'meta-stremio': '🎬', }
'meta-core': '⚙️', }
'meta-dup': '🔍',
'meta-orbit': '🌐',
'default': '📦'
};
function formatServiceName(name: string): string {
return name.split('-').map(word =>
word.charAt(0).toUpperCase() + word.slice(1)
).join(' ');
} }
function ServiceNav() { function ServiceNav() {
const [services, setServices] = useState<ServiceInfo[]>([]);
const [loading, setLoading] = useState(true);
const currentService = 'meta-fuse';
useEffect(() => { useEffect(() => {
const fetchServices = async () => { // Import above is for the side effect of defining the element; this
try { // keeps bundlers from tree-shaking it away in production builds.
const response = await fetch('/api/services');
if (response.ok) {
const data: ServicesResponse = await response.json();
setServices(data.services || []);
}
} catch (error) {
console.error('Failed to fetch services:', error);
} finally {
setLoading(false);
}
};
fetchServices();
const interval = setInterval(fetchServices, 30000);
return () => clearInterval(interval);
}, []); }, []);
if (loading) return null;
const sortedServices = [...services].sort((a, b) => a.name.localeCompare(b.name));
if (sortedServices.length === 0) return null;
return ( return (
<nav className="services-nav"> <>
<span className="services-nav-label">Services:</span> <meta-service-menu current="meta-fuse" />
<div className="services-nav-items">
{sortedServices.map(service => {
const icon = serviceIcons[service.name] || serviceIcons.default;
const isActive = service.name === currentService;
return (
<a
key={service.name}
href={isActive ? '#' : service.baseUrl}
className={`service-link${isActive ? ' active' : ''}`}
onClick={(e) => {
e.preventDefault();
if (!isActive) {
window.location.href = service.baseUrl;
}
}}
>
<span className="service-icon">{icon}</span>
<span>{formatServiceName(service.name)}</span>
<span className="service-status"></span>
</a>
);
})}
</div>
<style>{` <style>{`
.services-nav { meta-service-menu {
background: var(--bg-secondary, #12121a); --mm-nav-fg: var(--text-primary, #e0e0e0);
border-radius: 12px; --mm-nav-bg: var(--bg-tertiary, var(--bg-secondary, #1a1a2e));
padding: 0.5rem; --mm-nav-border: var(--border-color, rgba(255,255,255,0.14));
margin-bottom: 1.5rem; --mm-nav-accent: var(--accent-primary, #4ecdc4);
display: flex;
align-items: center;
gap: 0.5rem;
flex-wrap: wrap;
border: 1px solid var(--border-color, #2a2a3a);
}
.services-nav-label {
color: var(--text-secondary, #a0a0a0);
font-size: 0.85rem;
padding: 0.5rem 0.75rem;
white-space: nowrap;
}
.services-nav-items {
display: flex;
gap: 0.5rem;
flex-wrap: wrap;
}
.service-link {
display: inline-flex;
align-items: center;
gap: 0.4rem;
padding: 0.5rem 1rem;
border-radius: 8px;
text-decoration: none;
font-size: 0.9rem;
font-weight: 500;
transition: all 0.2s;
color: var(--text-primary, #e0e0e0);
background: var(--bg-tertiary, #1a1a2a);
border: 1px solid var(--border-color, #2a2a3a);
}
.service-link:hover {
background: var(--border-color, #2a2a3a);
border-color: rgba(78, 205, 196, 0.5);
text-decoration: none;
}
.service-link.active {
background: linear-gradient(135deg, rgba(78, 205, 196, 0.2), rgba(68, 160, 141, 0.2));
border-color: rgba(78, 205, 196, 0.5);
}
.service-link .service-icon {
font-size: 1.1rem;
}
.service-link .service-status {
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--accent-primary, #4ecdc4);
margin-left: 0.25rem;
}
@media (max-width: 600px) {
.services-nav {
flex-direction: column;
align-items: flex-start;
}
} }
`}</style> `}</style>
</nav> </>
); );
} }
@@ -0,0 +1,177 @@
import { useCallback, useEffect, useState } from 'react';
interface TokenView {
id: string;
label: string;
prefix: string;
createdAt: string;
}
interface CreatedToken extends TokenView {
token: string; // plaintext, surfaced only once
}
function formatDate(iso: string): string {
try {
return new Date(iso).toLocaleString();
} catch {
return iso;
}
}
export function WebdavTokens() {
const [tokens, setTokens] = useState<TokenView[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [newLabel, setNewLabel] = useState('');
const [creating, setCreating] = useState(false);
const [justCreated, setJustCreated] = useState<CreatedToken | null>(null);
const [copied, setCopied] = useState(false);
const refresh = useCallback(async () => {
try {
const res = await fetch('/api/webdav-tokens');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
setTokens(data.tokens ?? []);
setError(null);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
refresh();
}, [refresh]);
const create = async () => {
setCreating(true);
try {
const res = await fetch('/api/webdav-tokens', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ label: newLabel }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const created: CreatedToken = await res.json();
setJustCreated(created);
setNewLabel('');
setCopied(false);
await refresh();
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setCreating(false);
}
};
const revoke = async (id: string, label: string) => {
if (!confirm(`Revoke token "${label}"? Devices using it will lose WebDAV access immediately.`)) return;
try {
const res = await fetch(`/api/webdav-tokens/${id}`, { method: 'DELETE' });
if (!res.ok && res.status !== 204) throw new Error(`HTTP ${res.status}`);
await refresh();
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
}
};
const copyToken = async () => {
if (!justCreated) return;
try {
await navigator.clipboard.writeText(justCreated.token);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch {
// Clipboard API may be unavailable on http; fall back silently.
}
};
if (loading) return <div className="loading">Loading tokens…</div>;
return (
<div className="webdav-tokens">
<p className="info-note">
Generate one token per device and paste it as the basic-auth password
when you add the WebDAV mount in Plex / Finder / Windows Explorer / etc.
Any username works — the password is what authenticates. Revoke a
token to cut off that single device without affecting the others.
</p>
{error && <div className="error">{error}</div>}
{justCreated && (
<div className="info-box" style={{ borderColor: '#10b981' }}>
<h4>New token — copy it now</h4>
<p className="info-note">
This is the only time the full token will be shown. After you close
this banner only the prefix will appear in the list.
</p>
<div className="command-box" style={{ display: 'flex', gap: '0.5rem', alignItems: 'center' }}>
<code style={{ flex: 1, wordBreak: 'break-all' }}>{justCreated.token}</code>
<button onClick={copyToken} className="refresh-btn">
{copied ? 'Copied!' : 'Copy'}
</button>
</div>
<button
onClick={() => setJustCreated(null)}
className="refresh-btn"
style={{ marginTop: '0.5rem' }}
>
Dismiss
</button>
</div>
)}
<div className="card" style={{ marginTop: '1rem' }}>
<div className="card-header">
<span className="card-title">Generate token</span>
</div>
<div style={{ display: 'flex', gap: '0.5rem', marginTop: '0.5rem' }}>
<input
type="text"
value={newLabel}
onChange={(e) => setNewLabel(e.target.value)}
placeholder="Label (e.g. 'Plex on living-room TV')"
maxLength={200}
style={{ flex: 1, padding: '0.5rem' }}
onKeyDown={(e) => { if (e.key === 'Enter' && !creating) create(); }}
/>
<button onClick={create} disabled={creating} className="refresh-btn">
{creating ? 'Generating…' : 'Generate'}
</button>
</div>
</div>
<div className="file-list" style={{ marginTop: '1rem' }}>
{tokens.length === 0 ? (
<div className="file-item">
<span className="file-name" style={{ color: '#64748b' }}>
No tokens yet — generate one to enable WebDAV access.
</span>
</div>
) : (
tokens.map((t) => (
<div key={t.id} className="file-item" style={{ justifyContent: 'space-between' }}>
<div>
<span className="file-name"><strong>{t.label}</strong></span>
<div className="info-note">
<code>mfwd_{t.prefix}…</code> · created {formatDate(t.createdAt)}
</div>
</div>
<button
onClick={() => revoke(t.id, t.label)}
className="refresh-btn"
style={{ background: '#ef4444', color: 'white' }}
>
Revoke
</button>
</div>
))
)}
</div>
</div>
);
}
@@ -0,0 +1,308 @@
/**
* <meta-service-menu> — the neighbouring meta-* services, as a burger menu.
*
* Replaces the eight divergent "services bar" implementations (four copies of
* a React `ServiceNav.tsx`, two mirrored `services.js`, two bespoke inline
* ones) with a single framework-free custom element. It drops into the React
* dashboards as a plain tag — no React dependency — and into the vanilla UIs
* as an ES module.
*
* Data comes from the host service's own `GET /api/neighbors`, same-origin.
* Never cross-origin: the dev stack's self-signed certs and the OIDC redirects
* make a fetch to a neighbour a dead end. Links are plain navigations.
*
* ⚠ MIRRORED FILE. Byte-identical copies live in every meta-* UI tree; see
* `scripts/check-mirrors.sh`. Edit one → edit all.
*
* Shadow DOM is not optional here. The eight UIs use four incompatible token
* vocabularies, and two of them define *different colours under the same
* names* (`--bg-secondary` is #12121a in meta-sort, #16213e in meta-core,
* #161b22 in meta-dup). meta-search and meta-share are also the only
* light-mode-capable UIs, so a hardcoded dark palette would break them.
* The element therefore styles itself from four tokens with dark defaults:
*
* --mm-nav-fg, --mm-nav-bg, --mm-nav-border, --mm-nav-accent
*
* Each host maps its own variables onto those, e.g.
* meta-service-menu { --mm-nav-bg: var(--bg-secondary); }
*
* Attributes:
* current name of the host service, so it can be marked and not linked
* endpoint override the default "/api/neighbors"
* label button tooltip (default "Services")
*
* Property:
* rewriteUrl optional (name, url, neighbour) => url, for hosts that must
* translate internal hostnames into browser-reachable ones
* (meta-gateway does this for its dev/prod split).
*/
const ICONS = {
"meta-core": "⚙️",
"meta-sort": "📁",
"meta-fuse": "🗂️",
"meta-stremio": "🎬",
"meta-dup": "🔍",
"meta-search": "🔎",
"meta-share": "🔗",
"meta-gateway": "🌉",
"meta-watch": "📺",
"meta-listen": "🎧",
"meta-read": "📖",
};
const DEFAULT_ICON = "📦";
const POLL_MS = 30000;
function titleCase(name) {
return String(name || "")
.split("-")
.map((w) => w.charAt(0).toUpperCase() + w.slice(1))
.join(" ");
}
const TEMPLATE = `
<style>
:host {
--_fg: var(--mm-nav-fg, #e8eaed);
--_bg: var(--mm-nav-bg, #1a1a2e);
--_border: var(--mm-nav-border, rgba(255, 255, 255, 0.14));
--_accent: var(--mm-nav-accent, #4ecdc4);
position: relative;
display: inline-block;
font-family: inherit;
font-size: 14px;
line-height: 1.4;
}
button.trigger {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.4rem;
width: 2.1rem;
height: 2.1rem;
padding: 0;
cursor: pointer;
color: var(--_fg);
background: transparent;
border: 1px solid var(--_border);
border-radius: 8px;
font: inherit;
transition: border-color 0.15s, background 0.15s;
}
button.trigger:hover { border-color: var(--_accent); }
button.trigger:focus-visible {
outline: 2px solid var(--_accent);
outline-offset: 2px;
}
button.trigger[aria-expanded="true"] { border-color: var(--_accent); }
.bars { display: block; width: 15px; }
.bars span {
display: block;
height: 2px;
margin: 3px 0;
border-radius: 2px;
background: currentColor;
}
.panel {
position: absolute;
top: calc(100% + 6px);
right: 0;
z-index: 1000;
min-width: 13rem;
max-height: 70vh;
overflow-y: auto;
padding: 0.3rem;
background: var(--_bg);
border: 1px solid var(--_border);
border-radius: 10px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.35);
}
.panel[hidden] { display: none; }
a.item, .item {
display: flex;
align-items: center;
gap: 0.55rem;
padding: 0.45rem 0.6rem;
border-radius: 6px;
color: var(--_fg);
text-decoration: none;
white-space: nowrap;
}
a.item:hover { background: color-mix(in srgb, var(--_accent) 18%, transparent); }
.item.active { color: var(--_accent); font-weight: 600; cursor: default; }
.item.dead { opacity: 0.55; cursor: not-allowed; }
.icon { font-size: 1rem; line-height: 1; }
.dot {
width: 6px;
height: 6px;
margin-left: auto;
border-radius: 50%;
background: var(--_accent);
}
.empty {
padding: 0.6rem;
opacity: 0.7;
font-size: 0.85em;
white-space: nowrap;
}
/* Respect a host that opts out of motion. */
@media (prefers-reduced-motion: reduce) {
button.trigger { transition: none; }
}
</style>
<button class="trigger" type="button" aria-haspopup="menu" aria-expanded="false">
<span class="bars" aria-hidden="true"><span></span><span></span><span></span></span>
</button>
<div class="panel" role="menu" hidden></div>
`;
class MetaServiceMenu extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.shadowRoot.innerHTML = TEMPLATE;
this._btn = this.shadowRoot.querySelector("button.trigger");
this._panel = this.shadowRoot.querySelector(".panel");
this._neighbors = [];
this._timer = null;
this._open = false;
this._onDocClick = (e) => {
if (!this._open) return;
if (e.composedPath().includes(this)) return;
this._setOpen(false);
};
this._onKey = (e) => {
if (e.key === "Escape" && this._open) {
this._setOpen(false);
this._btn.focus();
}
};
}
connectedCallback() {
this._btn.title = this.getAttribute("label") || "Services";
this._btn.setAttribute("aria-label", this._btn.title);
this._btn.addEventListener("click", () => this._setOpen(!this._open));
document.addEventListener("click", this._onDocClick);
document.addEventListener("keydown", this._onKey);
this.refresh();
this._timer = setInterval(() => this.refresh(), POLL_MS);
}
disconnectedCallback() {
if (this._timer) clearInterval(this._timer);
this._timer = null;
document.removeEventListener("click", this._onDocClick);
document.removeEventListener("keydown", this._onKey);
}
get endpoint() {
return this.getAttribute("endpoint") || "/api/neighbors";
}
get current() {
return this.getAttribute("current") || "";
}
async refresh() {
try {
const res = await fetch(this.endpoint, {
headers: { Accept: "application/json" },
});
if (!res.ok) throw new Error(String(res.status));
const data = await res.json();
// `services` is the legacy alias some backends still emit.
this._neighbors = data.neighbors || data.services || [];
} catch {
// Silent: the menu is navigation, not a health indicator. Keep whatever
// we last had rather than blanking the list on one failed poll.
}
this._render();
}
_setOpen(open) {
this._open = open;
this._panel.hidden = !open;
this._btn.setAttribute("aria-expanded", String(open));
if (open) this.refresh();
}
_render() {
const panel = this._panel;
panel.textContent = "";
const seen = new Set();
const rows = [];
for (const n of this._neighbors) {
const name = n.name || "";
if (!name || seen.has(name)) continue;
// Beacon v2 neighbours include plugins; the nav lists services only.
// (A row without `caps` comes from a pre-v2 backend — keep it.)
const isService = (c) => String(c).startsWith("metamesh.service/");
if (Array.isArray(n.caps) && !n.caps.some(isService)) continue;
seen.add(name);
rows.push(n);
}
// Always show the host itself, even before its own echo comes back.
if (this.current && !seen.has(this.current)) {
rows.push({ name: this.current, baseUrl: "" });
}
rows.sort((a, b) => String(a.name).localeCompare(String(b.name)));
if (rows.length === 0) {
const empty = document.createElement("div");
empty.className = "empty";
empty.textContent = "No services found";
panel.appendChild(empty);
return;
}
for (const n of rows) {
const isActive = n.name === this.current;
let url = n.baseUrl || "";
if (typeof this.rewriteUrl === "function") {
try {
url = this.rewriteUrl(n.name, url, n) || "";
} catch {
/* a bad hook must not blank the menu */
}
}
// A neighbour with no reachable URL is shown but not linked — better
// than a link that goes nowhere.
const el = document.createElement(isActive || !url ? "span" : "a");
el.className =
"item" + (isActive ? " active" : "") + (!isActive && !url ? " dead" : "");
if (el.tagName === "A") {
el.href = url;
el.setAttribute("role", "menuitem");
}
if (!isActive && !url) el.title = "No reachable URL advertised";
const icon = document.createElement("span");
icon.className = "icon";
icon.textContent = ICONS[n.name] || DEFAULT_ICON;
const label = document.createElement("span");
label.textContent = titleCase(n.name);
el.append(icon, label);
// Beacon v2 omits `status` when running.
if ((n.status || "running") === "running" || isActive) {
const dot = document.createElement("span");
dot.className = "dot";
dot.title = n.status || "running";
el.appendChild(dot);
}
panel.appendChild(el);
}
}
}
if (!customElements.get("meta-service-menu")) {
customElements.define("meta-service-menu", MetaServiceMenu);
}
export default MetaServiceMenu;