Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b0edfb5f97 | ||
|
|
c03c7a6bdb | ||
|
|
89ffd3b7d4 | ||
|
|
c81dcaf0b5 | ||
|
|
dc564baf87 | ||
|
|
fa4826ee2e | ||
|
|
33f576c92a | ||
|
|
b4528a099a | ||
|
|
9280e23e83 | ||
|
|
f5cafa77b2 | ||
|
|
af51bbf943 | ||
|
|
985b000c24 | ||
|
|
021991b00d | ||
|
|
862f73d26d | ||
|
|
b855adb822 | ||
|
|
9bf2e623f9 | ||
|
|
7bdb54f9a7 |
@@ -0,0 +1,100 @@
|
|||||||
|
# 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
|
||||||
|
with:
|
||||||
|
submodules: recursive # For plugins
|
||||||
|
|
||||||
|
- 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' }}
|
||||||
@@ -52,6 +52,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}}
|
||||||
|
|||||||
@@ -3,17 +3,18 @@
|
|||||||
File-watcher and metadata-extraction service for the MetaMesh ecosystem.
|
File-watcher and metadata-extraction service for the MetaMesh ecosystem.
|
||||||
meta-sort consumes file events from meta-core (over SSE), drives metadata
|
meta-sort consumes file events from meta-core (over SSE), drives metadata
|
||||||
through a streaming pipeline + container plugins, and writes results back
|
through a streaming pipeline + container plugins, and writes results back
|
||||||
to Redis through meta-core's API. It exposes a Fastify REST API and serves
|
to Redis through meta-core's HTTP API. It exposes a Fastify REST API and
|
||||||
the `/files` volume over WebDAV so that other services and plugin
|
reads media exclusively over **meta-core's WebDAV** — it mounts neither
|
||||||
containers can read media without mounting the same volume.
|
`/meta-core` nor `/files`.
|
||||||
|
|
||||||
> **Service role:** meta-sort is **Redis-consuming**, not Redis-managing.
|
> **Service role:** meta-sort is **Redis-consuming**, not Redis-managing.
|
||||||
> It does not run leader election, it does not spawn Redis, and it does
|
> It does not run leader election, it does not spawn Redis, and it has
|
||||||
> not own `kv-leader.lock`. Those responsibilities belong to **meta-core**
|
> no direct Redis connection: every read and write goes through
|
||||||
> (a separate Go service). meta-sort reads
|
> **meta-core** (a separate Go service) over HTTP. meta-sort locates
|
||||||
> `/meta-core/locks/kv-leader.info` via `LeaderClient` to discover the
|
> meta-core over UDP multicast (**beacon v2**,
|
||||||
> Redis URL, API URL, and WebDAV URLs, and registers its own URLs into
|
> `239.255.99.1:9099`) — meta-core's announce carries its API and WebDAV
|
||||||
> `/meta-core/services/<hostname>.json`.
|
> URLs — and announces itself on the same group so sibling dashboards can
|
||||||
|
> list it. `META_CORE_URL` pins meta-core and disables wire selection.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -29,14 +30,18 @@ What this service does:
|
|||||||
3. **Manages container plugins**: spawns plugin containers via the Docker
|
3. **Manages container plugins**: spawns plugin containers via the Docker
|
||||||
socket, exposes a callback endpoint, lets plugins write metadata back
|
socket, exposes a callback endpoint, lets plugins write metadata back
|
||||||
into Redis via the meta-core-compatible `/meta/*` API on this service.
|
into Redis via the meta-core-compatible `/meta/*` API on this service.
|
||||||
4. **Serves files over WebDAV** at `/webdav/*` so container plugins and
|
4. **Computes file identity**: `midhash256` in the light phase, full-file
|
||||||
sibling services (meta-fuse, meta-stremio) can read media without
|
digests (sha1, sha256, md5, sha3, crc32, btih v2) in the background
|
||||||
needing the underlying bind/SMB/rclone mounts.
|
phase. Digests are persisted only as the bare-CID key-set
|
||||||
|
(`cids/<cid>`), never as per-algorithm `cid_*` fields
|
||||||
|
(`src/config/TargetHash.ts`, `src/kv/MetaCoreApiWriter.ts`).
|
||||||
|
|
||||||
What this service does **not** do (anymore):
|
What this service does **not** do (anymore):
|
||||||
|
|
||||||
- It does not run leader election.
|
- It does not run leader election.
|
||||||
- It does not spawn or supervise Redis.
|
- It does not spawn or supervise Redis, nor talk to it directly.
|
||||||
|
- It does not serve WebDAV — files are read from meta-core's WebDAV, and
|
||||||
|
plugin containers get that same URL (`WEBDAV_URL`).
|
||||||
- It does not watch the filesystem directly (chokidar lives in meta-core).
|
- It does not watch the filesystem directly (chokidar lives in meta-core).
|
||||||
- It does not manage remote mounts (mounts are now in meta-core / rclone-smb).
|
- It does not manage remote mounts (mounts are now in meta-core / rclone-smb).
|
||||||
- It does not have an in-process plugin runtime — all plugins are
|
- It does not have an in-process plugin runtime — all plugins are
|
||||||
@@ -48,43 +53,46 @@ What this service does **not** do (anymore):
|
|||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
### Two-volume layout
|
### Volumes
|
||||||
|
|
||||||
meta-sort consumes two host-side volumes via standard bind mounts:
|
meta-sort needs **no shared volume**. Media lives on meta-core's
|
||||||
|
`FILES_VOLUME` and is read over meta-core's WebDAV; file paths stored in
|
||||||
|
Redis are **relative to `/files`**, which keeps storage portable across
|
||||||
|
hosts. The only mounts are its own cache (`/data/cache`), the Docker
|
||||||
|
socket (for plugin containers) and `plugins.yml`.
|
||||||
|
|
||||||
| Volume | Container path | Owner | Purpose |
|
### Locating meta-core (beacon v2)
|
||||||
|--------|----------------|-------|---------|
|
|
||||||
| `META_CORE_VOLUME` | `/meta-core` | meta-core writes, all services read | Leader-info file, Redis data, service registry, SSE cursor |
|
|
||||||
| `FILES_VOLUME` | `/files` | meta-sort serves over WebDAV | Watched media, plugin output, dynamic mounts |
|
|
||||||
|
|
||||||
File paths stored in Redis are **relative to `/files`**, which makes the
|
|
||||||
storage portable across hosts. See the root `CLAUDE.md` for the
|
|
||||||
authoritative volume layout description.
|
|
||||||
|
|
||||||
### Leader discovery (read-only)
|
|
||||||
|
|
||||||
```
|
```
|
||||||
meta-core (separate container)
|
meta-core (separate container)
|
||||||
├── runs Redis
|
├── runs Redis, the file watcher, and the WebDAV server for /files
|
||||||
├── runs file watcher (chokidar) and publishes file:events
|
├── HTTP API: /urls, /api/events/files (SSE), /meta/*, ...
|
||||||
├── runs HTTP API on /api/urls, /api/events/files, /meta/*, /api/services, ...
|
└── advertises metamesh.core on 239.255.99.1:9099 (UDP multicast),
|
||||||
└── writes /meta-core/locks/kv-leader.info
|
carrying its /urls payload (apiUrl, webdavUrl, webdavUrlInternal)
|
||||||
│
|
│
|
||||||
▼
|
▼
|
||||||
meta-sort (this service)
|
meta-sort (this service)
|
||||||
├── LeaderClient reads kv-leader.info → Redis URL, API URL,
|
├── LeaderClient → MetaCoreLocator (src/discovery/meshdisco.ts)
|
||||||
│ WebDAV URLs, etc.
|
│ picks up the core announce (or GET {META_CORE_URL}/urls
|
||||||
├── KVManager creates RedisKVClient (writes are routed
|
│ when pinned) and announces meta-sort on the same group
|
||||||
│ through meta-core's HTTP API for the api-mediated-access
|
├── KVManager builds an HTTP-only RedisKVClient against
|
||||||
│ model)
|
│ meta-core's API and configures the WebDAV client
|
||||||
├── ServiceRegistration writes
|
├── GET /api/neighbors serves the UDP neighbour map (nav menu)
|
||||||
│ /meta-core/services/meta-sort-<hostname>.json
|
|
||||||
└── FileEventConsumer subscribes to
|
└── FileEventConsumer subscribes to
|
||||||
${apiUrl}/api/events/files (SSE)
|
${apiUrl}/api/events/files (SSE)
|
||||||
```
|
```
|
||||||
|
|
||||||
Source: `packages/meta-sort-core/src/kv/{KVManager,LeaderClient,RedisClient,ServiceRegistration}.ts`,
|
Source: `packages/meta-sort-core/src/discovery/meshdisco.ts`,
|
||||||
|
`packages/meta-sort-core/src/kv/{KVManager,LeaderClient,RedisClient,MetaCoreApiWriter}.ts`,
|
||||||
`packages/meta-sort-core/src/events/{FileEventConsumer,SSEEventClient}.ts`.
|
`packages/meta-sort-core/src/events/{FileEventConsumer,SSEEventClient}.ts`.
|
||||||
|
The protocol spec is `docs/project-architecture/beacon-v2.md` in
|
||||||
|
the meta-root. The `meshdisco.ts` port is mirrored across services and
|
||||||
|
guarded by the meta-root's `scripts/check-mirrors.sh` — change it there in
|
||||||
|
lockstep.
|
||||||
|
|
||||||
|
The SSE cursor is persisted to `/meta-core/cursors/meta-sort-files.cursor`
|
||||||
|
(`FileEventConsumer.ts` default); since `/meta-core` is no longer mounted,
|
||||||
|
that path is container-local and does not survive a container recreate.
|
||||||
|
|
||||||
### Processing pipeline
|
### Processing pipeline
|
||||||
|
|
||||||
@@ -119,7 +127,9 @@ them via the Docker socket and a callback endpoint:
|
|||||||
- **Built-in plugins** (each is a separate git submodule under
|
- **Built-in plugins** (each is a separate git submodule under
|
||||||
`packages/plugins/metamesh-plugin-*` at the repo root): `file-info`,
|
`packages/plugins/metamesh-plugin-*` at the repo root): `file-info`,
|
||||||
`ffmpeg`, `filename-parser`, `jellyfin-nfo`, `tmdb`, `anime-detector`,
|
`ffmpeg`, `filename-parser`, `jellyfin-nfo`, `tmdb`, `anime-detector`,
|
||||||
`language`, `subtitle`, `subtitle-extractor`, `torrent`, `fullhash`.
|
`language`, `subtitle`, `subtitle-extractor`, `still-extractor`,
|
||||||
|
`opensubtitle`, `torrent`, `fullhash`. Which ones actually run is
|
||||||
|
decided by `plugins.yml` — the image ships none.
|
||||||
- **Dispatch:** `ContainerPluginScheduler.dispatchAllPlugins(hashId,
|
- **Dispatch:** `ContainerPluginScheduler.dispatchAllPlugins(hashId,
|
||||||
filePath, metaFlat)` — fire-and-forget. The scheduler keeps its own
|
filePath, metaFlat)` — fire-and-forget. The scheduler keeps its own
|
||||||
fast / background queues based on each plugin manifest's
|
fast / background queues based on each plugin manifest's
|
||||||
@@ -128,8 +138,10 @@ them via the Docker socket and a callback endpoint:
|
|||||||
`/api/plugins/callback`, and they can read/write Redis metadata
|
`/api/plugins/callback`, and they can read/write Redis metadata
|
||||||
through the meta-core-compatible `/meta/:hash` routes that meta-sort
|
through the meta-core-compatible `/meta/:hash` routes that meta-sort
|
||||||
also exposes (so plugins only need one HTTP target).
|
also exposes (so plugins only need one HTTP target).
|
||||||
- **Plugins access files** by hitting meta-sort's WebDAV
|
- **Plugins access files** over meta-core's WebDAV: each plugin
|
||||||
(`http://metasort-app/webdav/...` inside the docker network).
|
container is started with `WEBDAV_URL` (meta-core's
|
||||||
|
`webdavUrlInternal`), `META_CORE_URL` (= `CONTAINER_META_CORE_URL`),
|
||||||
|
`CALLBACK_URL` and `PLUGIN_ID` (`ContainerManager.ts`).
|
||||||
|
|
||||||
For the plugin HTTP contract, see
|
For the plugin HTTP contract, see
|
||||||
[`docs/containerized-plugin-architecture.md`](docs/containerized-plugin-architecture.md)
|
[`docs/containerized-plugin-architecture.md`](docs/containerized-plugin-architecture.md)
|
||||||
@@ -143,15 +155,16 @@ and [`docs/plugin-task-queue-architecture.md`](docs/plugin-task-queue-architectu
|
|||||||
|
|
||||||
| Variable | Default | Description |
|
| Variable | Default | Description |
|
||||||
|----------|---------|-------------|
|
|----------|---------|-------------|
|
||||||
| `META_CORE_PATH` | `/meta-core` | Mount of META_CORE_VOLUME. Required — startup fails fast if absent. |
|
| `META_CORE_URL` | — | Pins meta-core's API URL; UDP discovery then never overrides it. |
|
||||||
| `FILES_PATH` | `/files` | Mount of FILES_VOLUME. |
|
| `ENABLE_UDP_DISCOVERY` | on | `false`/`0` disables the beacon v2 announce/listen. |
|
||||||
|
| `ALLOW_LEGACY_REDIS_URL` | — | `1` downgrades the "meta-core still publishes `redisUrl`" startup error to a warning. |
|
||||||
|
| `FILES_PATH` | `/files` | Virtual root that relative paths resolve under (on meta-core's WebDAV). |
|
||||||
| `CACHE_FOLDER_PATH` | `/data/cache` | Local cache root. |
|
| `CACHE_FOLDER_PATH` | `/data/cache` | Local cache root. |
|
||||||
| `SERVICE_NAME` | `meta-sort` | Identifier used for service registration. |
|
| `SERVICE_NAME` | `meta-sort` | Name announced on the discovery group. |
|
||||||
| `SERVICE_VERSION` | `1.0.0` | Recorded in the service registry. |
|
|
||||||
| `FUSE_API_PORT` | `3000` | HTTP API port (legacy name; this is the Fastify API). |
|
| `FUSE_API_PORT` | `3000` | HTTP API port (legacy name; this is the Fastify API). |
|
||||||
| `FUSE_API_HOST` | `0.0.0.0` | API bind host. |
|
| `FUSE_API_HOST` | `0.0.0.0` | API bind host. |
|
||||||
| `BASE_URL` | — | External base URL recorded in service registration. |
|
| `PUBLIC_URL` | — | Browser-facing URL announced for neighbours' nav menus. Wins over `BASE_URL` (use it for a debug-direct port when no Caddy is in front). |
|
||||||
| `ADVERTISE_HOST` | — | Hostname to advertise to other services. Falls back to auto-detected IP. |
|
| `BASE_URL` | — | Perimeter URL announced when `PUBLIC_URL` is unset; falls back to `http://<hostname>:<FUSE_API_PORT>`. |
|
||||||
| `MAX_WORKER_THREADS` | `os.cpus().length` | If set, overrides all pipeline concurrencies to `(M*2, M, M)`. |
|
| `MAX_WORKER_THREADS` | `os.cpus().length` | If set, overrides all pipeline concurrencies to `(M*2, M, M)`. |
|
||||||
| `FAST_QUEUE_CONCURRENCY` | `32` | Container-plugin fast queue concurrency (see plugin-task-queue-architecture.md). |
|
| `FAST_QUEUE_CONCURRENCY` | `32` | Container-plugin fast queue concurrency (see plugin-task-queue-architecture.md). |
|
||||||
| `FILE_LIGHT_SLOTS` | `16` | Max files concurrently in the light phase. |
|
| `FILE_LIGHT_SLOTS` | `16` | Max files concurrently in the light phase. |
|
||||||
@@ -160,16 +173,22 @@ and [`docs/plugin-task-queue-architecture.md`](docs/plugin-task-queue-architectu
|
|||||||
| `CONTAINER_PLUGINS_CONFIG` | `/app/plugins.yml` | Path to plugin manifest YAML. If missing, container plugins are skipped. |
|
| `CONTAINER_PLUGINS_CONFIG` | `/app/plugins.yml` | Path to plugin manifest YAML. If missing, container plugins are skipped. |
|
||||||
| `DOCKER_SOCKET_PATH` | `/var/run/docker.sock` | Docker socket for container management. |
|
| `DOCKER_SOCKET_PATH` | `/var/run/docker.sock` | Docker socket for container management. |
|
||||||
| `CONTAINER_CALLBACK_URL` | `http://meta-sort:8180` | URL plugins POST callbacks to. |
|
| `CONTAINER_CALLBACK_URL` | `http://meta-sort:8180` | URL plugins POST callbacks to. |
|
||||||
| `CONTAINER_META_CORE_URL` | `http://meta-sort` | URL plugins use for meta-core-compatible `/meta/*` routes (served by meta-sort itself for now). |
|
| `CONTAINER_META_CORE_URL` | `http://meta-sort` | URL plugins use for meta-core-compatible `/meta/*` routes (served by meta-sort itself). The default host doesn't resolve on current stacks — dev sets `http://metasort-app` (port 80 dev nginx proxies `/meta/`), the store app `http://metasort-app:3000` (the stock nginx has no `/meta/` location). |
|
||||||
| `CONTAINER_NETWORK` | `meta-network` | Docker network to attach plugin containers to. |
|
| `CONTAINER_NETWORK` | `meta-network` | Docker network to attach plugin containers to. |
|
||||||
| `PLUGIN_STACK_NAME` | — | Docker Compose project label so plugin containers group together in Docker Desktop. |
|
| `PLUGIN_STACK_NAME` | — | Docker Compose project label so plugin containers group together in Docker Desktop. |
|
||||||
| `PLUGIN_CACHE_HOST_PATH` | — | Host path bind-mounted into each plugin for persistent caches. |
|
| `PLUGIN_CACHE_HOST_PATH` | — | Host path bind-mounted into each plugin for persistent caches. |
|
||||||
|
|
||||||
Source of truth: `packages/meta-sort-core/src/config/EnvConfig.ts`.
|
Source of truth: `packages/meta-sort-core/src/config/EnvConfig.ts` (plus
|
||||||
|
`PUBLIC_URL` in `kv/KVManager.ts` and `ENABLE_UDP_DISCOVERY` /
|
||||||
|
`ALLOW_LEGACY_REDIS_URL` in `kv/LeaderClient.ts`). `META_CORE_PATH`,
|
||||||
|
`REDIS_URL`, `ADVERTISE_HOST` and `SERVICE_VERSION` are still parsed by
|
||||||
|
`EnvConfig.ts` but nothing acts on them any more. The discovery group
|
||||||
|
defaults to the protocol endpoint (`239.255.99.1:9099`, 10 s interval);
|
||||||
|
`BEACON_GROUP` / `BEACON_PORT` / `BEACON_INTERVAL_MS` override it.
|
||||||
|
|
||||||
The Redis URL and WebDAV URLs are **not** configured via environment
|
The WebDAV URLs are **not** configured via environment variables —
|
||||||
variables — meta-sort discovers them from `kv-leader.info` (or its
|
meta-sort takes them from meta-core's announce (or `GET /urls` when
|
||||||
in-memory equivalent fetched through meta-core's `/api/urls`).
|
pinned).
|
||||||
|
|
||||||
### Concurrency defaults
|
### Concurrency defaults
|
||||||
|
|
||||||
@@ -239,7 +258,9 @@ Defined in `packages/meta-sort-core/src/api/UnifiedAPIServer.ts`.
|
|||||||
| `POST /api/plugins/callback` | Container plugin task-complete callback (used by plugins, not humans). |
|
| `POST /api/plugins/callback` | Container plugin task-complete callback (used by plugins, not humans). |
|
||||||
| `GET /api/plugins/containers` | Container-plugin status (health, instances, queue depths). |
|
| `GET /api/plugins/containers` | Container-plugin status (health, instances, queue depths). |
|
||||||
| `GET /api/plugins/containers/:pluginId/manifest` | Plugin manifest. |
|
| `GET /api/plugins/containers/:pluginId/manifest` | Plugin manifest. |
|
||||||
|
| `GET /api/plugins/containers/:pluginId/logs` | Container logs (`?instance=`, `?tail=`). |
|
||||||
| `POST /api/plugins/containers/:pluginId/restart` | Restart instances. |
|
| `POST /api/plugins/containers/:pluginId/restart` | Restart instances. |
|
||||||
|
| `POST /api/plugins/containers/:pluginId/stop` / `start` | Stop / start instances. |
|
||||||
| `POST /api/plugins/containers/restart-all` | Restart all. |
|
| `POST /api/plugins/containers/restart-all` | Restart all. |
|
||||||
| `POST /api/plugins/containers` | Add a new plugin (image, instances, resources, config, defaultQueue). |
|
| `POST /api/plugins/containers` | Add a new plugin (image, instances, resources, config, defaultQueue). |
|
||||||
| `PUT /api/plugins/containers/:pluginId` | Update plugin spec. |
|
| `PUT /api/plugins/containers/:pluginId` | Update plugin spec. |
|
||||||
@@ -249,9 +270,8 @@ Defined in `packages/meta-sort-core/src/api/UnifiedAPIServer.ts`.
|
|||||||
|
|
||||||
| Endpoint | Description |
|
| Endpoint | Description |
|
||||||
|----------|-------------|
|
|----------|-------------|
|
||||||
| `GET /api/file/download?path=...` | Download a file via the configured WebDAV backend. |
|
| `GET /api/file/download?path=...` | Download a file via meta-core's WebDAV. |
|
||||||
| `POST /file/cid` | Compute the CID (midhash256) for a path (`{ path }`). |
|
| `POST /file/cid` | Compute the CID (midhash256) for a path (`{ path }`). |
|
||||||
| `GET /webdav/*` (and `PUT`, `DELETE`, `MKCOL`, `PROPFIND`) | WebDAV view of `/files`. Unauthenticated. |
|
|
||||||
|
|
||||||
### meta-core-compatible KV (for container plugins)
|
### meta-core-compatible KV (for container plugins)
|
||||||
|
|
||||||
@@ -272,8 +292,8 @@ single host. They are only registered when the KV client is up.
|
|||||||
| Endpoint | Description |
|
| Endpoint | Description |
|
||||||
|----------|-------------|
|
|----------|-------------|
|
||||||
| `GET /api/metrics` | Performance metrics. |
|
| `GET /api/metrics` | Performance metrics. |
|
||||||
| `GET /api/stats` | Redis stats summary (only when KV is up). |
|
| `GET /api/stats` | File count + total size from meta-core's `/api/files/tuples` summary, cached stale-while-revalidate. |
|
||||||
| `GET /api/services` | Proxy to meta-core's `/api/services` via the LeaderClient. |
|
| `GET /api/neighbors` | beacon v2 neighbour map (nav menu). Served locally — works while meta-core is down. Replaces the removed `/api/services`. |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -286,6 +306,18 @@ single host. They are only registered when the KV client is up.
|
|||||||
- Debug-direct backend (no auth, no TLS): `http://localhost:18180`
|
- Debug-direct backend (no auth, no TLS): `http://localhost:18180`
|
||||||
- Container name (backend): `metasort-app`
|
- Container name (backend): `metasort-app`
|
||||||
- Container name (hash-lock proxy): `metasort`
|
- Container name (hash-lock proxy): `metasort`
|
||||||
|
- CasaOS store app: `MetaSort` in the meta-root's `packages/MetaAppStore`
|
||||||
|
(`ghcr.io/worph/meta-sort`, fronted by an `appshield` perimeter).
|
||||||
|
|
||||||
|
### Docker image
|
||||||
|
|
||||||
|
The repo `Dockerfile` (published to `ghcr.io/worph/meta-sort` by
|
||||||
|
`.github/workflows/docker-publish.yml`) is an all-in-one image: nginx on
|
||||||
|
`:80` → Fastify on `:3000`, rclone, and a bundled `meta-core` binary
|
||||||
|
copied from `ghcr.io/worph/meta-core` and started by
|
||||||
|
`docker/supervisord.conf`. Deployments run meta-core as its own app, so
|
||||||
|
both the dev stack and the store app mount their own supervisord/nginx
|
||||||
|
configs that drop the bundled meta-core.
|
||||||
|
|
||||||
### Logs
|
### Logs
|
||||||
|
|
||||||
@@ -310,7 +342,8 @@ cd dev
|
|||||||
### Running tests
|
### Running tests
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker exec meta-test-runner /app/test/test.sh sort
|
docker exec meta-test-runner /app/test/test.sh sort # E2E (meta-root dev stack)
|
||||||
|
pnpm test # unit tests (@meta-sort/core, mocha)
|
||||||
```
|
```
|
||||||
|
|
||||||
See the root `CLAUDE.md` "Running Tests" section for the full matrix.
|
See the root `CLAUDE.md` "Running Tests" section for the full matrix.
|
||||||
@@ -336,9 +369,10 @@ packages/meta-sort/
|
|||||||
│ │ │ ├── api/ # UnifiedAPIServer.ts (Fastify)
|
│ │ │ ├── api/ # UnifiedAPIServer.ts (Fastify)
|
||||||
│ │ │ ├── config/ # EnvConfig.ts, SupportedFileTypes.ts
|
│ │ │ ├── config/ # EnvConfig.ts, SupportedFileTypes.ts
|
||||||
│ │ │ ├── container-plugins/# ContainerManager, ContainerPluginScheduler, ...
|
│ │ │ ├── container-plugins/# ContainerManager, ContainerPluginScheduler, ...
|
||||||
|
│ │ │ ├── discovery/ # meshdisco.ts (beacon v2, mirrored port)
|
||||||
│ │ │ ├── events/ # FileEventConsumer, SSEEventClient
|
│ │ │ ├── events/ # FileEventConsumer, SSEEventClient
|
||||||
│ │ │ ├── jellyfin/ # Jellyfin / NFO output helpers
|
│ │ │ ├── jellyfin/ # Jellyfin / NFO output helpers
|
||||||
│ │ │ ├── kv/ # KVManager, LeaderClient, RedisClient
|
│ │ │ ├── kv/ # KVManager, LeaderClient, RedisClient, MetaCoreApiWriter
|
||||||
│ │ │ ├── logic/ # StreamingPipeline, state managers, fileProcessor
|
│ │ │ ├── logic/ # StreamingPipeline, state managers, fileProcessor
|
||||||
│ │ │ ├── metrics/ # PerformanceMetrics
|
│ │ │ ├── metrics/ # PerformanceMetrics
|
||||||
│ │ │ ├── plugin-engine/ # Vestigial in-process types + TaskScheduler glue
|
│ │ │ ├── plugin-engine/ # Vestigial in-process types + TaskScheduler glue
|
||||||
@@ -350,27 +384,28 @@ packages/meta-sort/
|
|||||||
│ ├── meta-sort-ui/ # @meta-sort/ui - React dashboard (Vite)
|
│ ├── meta-sort-ui/ # @meta-sort/ui - React dashboard (Vite)
|
||||||
│ ├── meta-sort-editor/ # Metadata editor UI (Vite)
|
│ ├── meta-sort-editor/ # Metadata editor UI (Vite)
|
||||||
│ ├── async-utils/ # @worph/async-utils - MultiQueue, etc.
|
│ ├── async-utils/ # @worph/async-utils - MultiQueue, etc.
|
||||||
│ └── shared/ # Symlinks to filename-tool, meta-hash, meta-interface
|
│ └── shared/ # Vendored copies of filename-tool, meta-hash, meta-interface
|
||||||
├── pnpm-workspace.yaml
|
├── pnpm-workspace.yaml
|
||||||
└── pnpm-lock.yaml
|
└── pnpm-lock.yaml
|
||||||
```
|
```
|
||||||
|
|
||||||
> Built-in container plugins **do not live here.** They live at the
|
> Built-in container plugins **do not live here.** They live at the
|
||||||
> repo root as separate submodules:
|
> repo root as separate submodules:
|
||||||
> `packages/plugins/metamesh-plugin-{file-info,ffmpeg,filename-parser,jellyfin-nfo,tmdb,anime-detector,language,subtitle,subtitle-extractor,torrent,fullhash}`.
|
> `packages/plugins/metamesh-plugin-{file-info,ffmpeg,filename-parser,jellyfin-nfo,tmdb,anime-detector,language,subtitle,subtitle-extractor,still-extractor,opensubtitle,torrent,fullhash}`.
|
||||||
|
|
||||||
### Key components
|
### Key components
|
||||||
|
|
||||||
| Component | File | Purpose |
|
| Component | File | Purpose |
|
||||||
|-----------|------|---------|
|
|-----------|------|---------|
|
||||||
| Entry point | `src/index.ts` | Wires KVManager → API server → plugin manager → ContainerManager → StreamingPipeline → FileEventConsumer. |
|
| Entry point | `src/index.ts` | Wires KVManager → API server → plugin manager → ContainerManager → StreamingPipeline → FileEventConsumer. |
|
||||||
|
| Discovery | `src/discovery/meshdisco.ts` | beacon v2 node + `MetaCoreLocator`. |
|
||||||
| Streaming pipeline | `src/logic/pipeline/StreamingPipeline.ts` | 3-queue (validation / fast / background) orchestrator. |
|
| Streaming pipeline | `src/logic/pipeline/StreamingPipeline.ts` | 3-queue (validation / fast / background) orchestrator. |
|
||||||
| State manager | `src/logic/UnifiedProcessingStateManager.ts` | Tracks `discovered → lightProcessing → hashProcessing → done`. |
|
| State manager | `src/logic/UnifiedProcessingStateManager.ts` | Tracks `discovered → lightProcessing → hashProcessing → done`. |
|
||||||
| File processor | `src/logic/WatchedFileProcessor.ts` | Light + hash phase implementation. |
|
| File processor | `src/logic/WatchedFileProcessor.ts` | Light + hash phase implementation. |
|
||||||
| SSE consumer | `src/events/FileEventConsumer.ts` | Translates meta-core events into pipeline calls. |
|
| SSE consumer | `src/events/FileEventConsumer.ts` | Translates meta-core events into pipeline calls. |
|
||||||
| SSE transport | `src/events/SSEEventClient.ts` | Long-lived HTTP SSE with cursor persistence. |
|
| SSE transport | `src/events/SSEEventClient.ts` | Long-lived HTTP SSE with cursor persistence. |
|
||||||
| KV manager | `src/kv/KVManager.ts` | Bootstraps RedisKVClient + ServiceRegistration from LeaderClient. |
|
| KV manager | `src/kv/KVManager.ts` | Bootstraps the HTTP-only RedisKVClient + WebDAV client from LeaderClient. |
|
||||||
| Leader client | `src/kv/LeaderClient.ts` | Reads `/meta-core/locks/kv-leader.info`, fetches `/api/urls`. |
|
| Leader client | `src/kv/LeaderClient.ts` | Legacy name: thin adapter over `MetaCoreLocator` (UDP), or `GET /urls` when `META_CORE_URL` is pinned. |
|
||||||
| Container manager | `src/container-plugins/ContainerManager.ts` | Docker socket orchestration. |
|
| Container manager | `src/container-plugins/ContainerManager.ts` | Docker socket orchestration. |
|
||||||
| Container scheduler | `src/container-plugins/ContainerPluginScheduler.ts` | Plugin fast/background queues + callbacks. |
|
| Container scheduler | `src/container-plugins/ContainerPluginScheduler.ts` | Plugin fast/background queues + callbacks. |
|
||||||
| API server | `src/api/UnifiedAPIServer.ts` | Fastify REST + WebDAV-facing meta routes. |
|
| API server | `src/api/UnifiedAPIServer.ts` | Fastify REST + WebDAV-facing meta routes. |
|
||||||
@@ -393,8 +428,9 @@ Repo-level docs of interest:
|
|||||||
- Root `CLAUDE.md` — authoritative ground truth on the dev stack, ports,
|
- Root `CLAUDE.md` — authoritative ground truth on the dev stack, ports,
|
||||||
containers, and operational commands.
|
containers, and operational commands.
|
||||||
- `/METADATA_KEYS.md` — schema for the `/file/{cid}` Redis hash.
|
- `/METADATA_KEYS.md` — schema for the `/file/{cid}` Redis hash.
|
||||||
- `packages/meta-core/docs/` — leader election and Redis storage owner.
|
- `packages/meta-core/docs/` — Redis storage owner, api-mediated access.
|
||||||
|
- `docs/project-architecture/beacon-v2.md` — beacon v2 spec.
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
MIT — see LICENSE.
|
MIT (see `package.json`).
|
||||||
|
|||||||
@@ -44,6 +44,19 @@ http {
|
|||||||
try_files $uri $uri/ /index.html;
|
try_files $uri $uri/ /index.html;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Signed claims relay (plugins -> meta-sort -> meta-core). Exact match so
|
||||||
|
# a large claim batch is not cut at nginx's 1 MB default (the API takes
|
||||||
|
# up to 16 MB); reads of /api/meta/{cid}/claims use the /api/ block.
|
||||||
|
location = /api/claims {
|
||||||
|
client_max_body_size 16m;
|
||||||
|
proxy_pass http://api;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
# API routes
|
# API routes
|
||||||
location /api/ {
|
location /api/ {
|
||||||
proxy_pass http://api;
|
proxy_pass http://api;
|
||||||
|
|||||||
@@ -1,5 +1,10 @@
|
|||||||
{
|
{
|
||||||
"spec": ["dist/api/api.test.js", "dist/kv/*.test.js"],
|
"spec": [
|
||||||
|
"dist/api/api.test.js",
|
||||||
|
"dist/kv/*.test.js",
|
||||||
|
"dist/container-plugins/*.test.js",
|
||||||
|
"dist/discovery/*.test.js"
|
||||||
|
],
|
||||||
"timeout": 30000,
|
"timeout": 30000,
|
||||||
"exit": true
|
"exit": true
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,8 +11,9 @@ import { performanceMetrics } from '../metrics/PerformanceMetrics.js';
|
|||||||
import { UnifiedProcessingStateManager } from '../logic/UnifiedProcessingStateManager.js';
|
import { UnifiedProcessingStateManager } from '../logic/UnifiedProcessingStateManager.js';
|
||||||
import type { IKVClient } from '../kv/IKVClient.js';
|
import type { IKVClient } from '../kv/IKVClient.js';
|
||||||
import type { KVManager } from '../kv/KVManager.js';
|
import type { KVManager } from '../kv/KVManager.js';
|
||||||
import type { ExtendedProcessingSnapshot, IKVClientWithPubSub } from '../types/ExtendedInterfaces.js';
|
import type { ExtendedProcessingSnapshot } from '../types/ExtendedInterfaces.js';
|
||||||
import { getErrorMessage } from '../types/ExtendedInterfaces.js';
|
import { getErrorMessage, hasFileTuples } from '../types/ExtendedInterfaces.js';
|
||||||
|
import type { IKVClientWithFileTuples } from '../types/ExtendedInterfaces.js';
|
||||||
import { config } from '../config/EnvConfig.js';
|
import { config } from '../config/EnvConfig.js';
|
||||||
import * as webdav from '../webdav/WebdavClient.js';
|
import * as webdav from '../webdav/WebdavClient.js';
|
||||||
import type { PluginManager } from '../plugin-engine/PluginManager.js';
|
import type { PluginManager } from '../plugin-engine/PluginManager.js';
|
||||||
@@ -29,6 +30,45 @@ export interface UnifiedAPIServerConfig {
|
|||||||
enableCors?: boolean;
|
enableCors?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** File totals served by /api/stats. Null when meta-core cannot supply them. */
|
||||||
|
interface FileStats {
|
||||||
|
fileCount: number | null;
|
||||||
|
totalSize: number | null;
|
||||||
|
source: 'meta-core' | 'unavailable';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Metadata reads in flight at once while a recompute builds its task list. */
|
||||||
|
const RECOMPUTE_READ_CONCURRENCY = 8;
|
||||||
|
|
||||||
|
/** Run `worker` over `items` with at most `limit` calls in flight. */
|
||||||
|
async function forEachWithConcurrency<T>(
|
||||||
|
items: readonly T[],
|
||||||
|
limit: number,
|
||||||
|
worker: (item: T) => Promise<void>
|
||||||
|
): Promise<void> {
|
||||||
|
let next = 0;
|
||||||
|
const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {
|
||||||
|
while (next < items.length) {
|
||||||
|
const item = items[next++];
|
||||||
|
await worker(item);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
await Promise.all(runners);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Flatten nested metadata into the `a/b/c` keys the task scheduler expects. */
|
||||||
|
function flattenMetadata(obj: Record<string, unknown>, out: Record<string, string> = {}, prefix = ''): Record<string, string> {
|
||||||
|
for (const [key, value] of Object.entries(obj)) {
|
||||||
|
const fullKey = prefix ? `${prefix}/${key}` : key;
|
||||||
|
if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
|
||||||
|
flattenMetadata(value as Record<string, unknown>, out, fullKey);
|
||||||
|
} else if (value !== undefined && value !== null) {
|
||||||
|
out[fullKey] = String(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
export class UnifiedAPIServer {
|
export class UnifiedAPIServer {
|
||||||
private app: FastifyInstance;
|
private app: FastifyInstance;
|
||||||
private unifiedStateManager: UnifiedProcessingStateManager | null = null;
|
private unifiedStateManager: UnifiedProcessingStateManager | null = null;
|
||||||
@@ -44,9 +84,15 @@ export class UnifiedAPIServer {
|
|||||||
private containerPluginScheduler: ContainerPluginScheduler | null = null;
|
private containerPluginScheduler: ContainerPluginScheduler | null = null;
|
||||||
private streamingPipeline: StreamingPipeline | null = null;
|
private streamingPipeline: StreamingPipeline | null = null;
|
||||||
|
|
||||||
// Cache for total file size (avoid running du on every request)
|
// /api/stats file totals: stale-while-revalidate, one refresh at a time.
|
||||||
private totalSizeCache: { value: number; timestamp: number } | null = null;
|
// Never walk hashIds for these — on a shared meta-core that is every gateway
|
||||||
private static TOTAL_SIZE_CACHE_TTL_MS = 30000; // 30 seconds
|
// record too (82k on watch.nsl.sh), and a sweep per poll stacked unbounded.
|
||||||
|
private fileStats: { value: FileStats; fetchedAt: number } | null = null;
|
||||||
|
private fileStatsInFlight: Promise<FileStats> | null = null;
|
||||||
|
private static FILE_STATS_TTL_MS = 30000; // 30 seconds
|
||||||
|
|
||||||
|
// Plugins whose recompute is currently being queued (single-flight per plugin)
|
||||||
|
private recomputeInFlight = new Set<string>();
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
config: UnifiedAPIServerConfig = {},
|
config: UnifiedAPIServerConfig = {},
|
||||||
@@ -97,48 +143,46 @@ export class UnifiedAPIServer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get total size of processed files from Redis sizeByte field (cached)
|
* File count + total size of the files meta-core holds on disk, for the
|
||||||
* This is "eventually correct" - accumulates as files are processed by the file-info plugin
|
* monitor's "Total Size" card: one summary call to meta-core's
|
||||||
|
* GET /api/files/tuples (batched server-side), cached for FILE_STATS_TTL_MS.
|
||||||
|
*
|
||||||
|
* Stale-while-revalidate with a single in-flight refresh — a poll never waits
|
||||||
|
* on meta-core once a value exists, and concurrent polls share one request.
|
||||||
*/
|
*/
|
||||||
private async getTotalFileSizeFromRedis(): Promise<number> {
|
private async getFileStats(): Promise<FileStats> {
|
||||||
// Check cache
|
const cached = this.fileStats;
|
||||||
const now = Date.now();
|
if (cached && Date.now() - cached.fetchedAt < UnifiedAPIServer.FILE_STATS_TTL_MS) {
|
||||||
if (this.totalSizeCache && (now - this.totalSizeCache.timestamp) < UnifiedAPIServer.TOTAL_SIZE_CACHE_TTL_MS) {
|
return cached.value;
|
||||||
return this.totalSizeCache.value;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sum sizeByte from all file entries in Redis
|
if (!this.fileStatsInFlight) {
|
||||||
let totalSize = 0;
|
this.fileStatsInFlight = this.fetchFileStats()
|
||||||
|
.catch((error: unknown): FileStats => {
|
||||||
if (!this.kvClient) {
|
console.warn('[API] /api/stats: meta-core file totals unavailable:', getErrorMessage(error));
|
||||||
return 0;
|
return cached?.value ?? { fileCount: null, totalSize: null, source: 'unavailable' };
|
||||||
|
})
|
||||||
|
.then((value) => {
|
||||||
|
this.fileStats = { value, fetchedAt: Date.now() };
|
||||||
|
return value;
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
this.fileStatsInFlight = null;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
return cached ? cached.value : this.fileStatsInFlight;
|
||||||
// Get all file hash IDs
|
}
|
||||||
const hashIds = await this.kvClient.getAllHashIds();
|
|
||||||
|
|
||||||
// Sum up sizeByte values (batch process for efficiency)
|
private async fetchFileStats(): Promise<FileStats> {
|
||||||
for (const hashId of hashIds) {
|
if (!this.kvClient || !hasFileTuples(this.kvClient)) {
|
||||||
try {
|
return { fileCount: null, totalSize: null, source: 'unavailable' };
|
||||||
const sizeByte = await this.kvClient.getMetadata(hashId, 'sizeByte');
|
|
||||||
if (sizeByte !== null && sizeByte !== undefined) {
|
|
||||||
const size = typeof sizeByte === 'number' ? sizeByte : parseInt(String(sizeByte), 10);
|
|
||||||
if (!isNaN(size) && size > 0) {
|
|
||||||
totalSize += size;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// Skip entries without sizeByte
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.warn('[API] Failed to calculate total size from Redis:', error);
|
|
||||||
}
|
}
|
||||||
|
const summary = await this.kvClient.getFileTuples({ summary: true });
|
||||||
// Update cache
|
if (!summary) {
|
||||||
this.totalSizeCache = { value: totalSize, timestamp: now };
|
return { fileCount: null, totalSize: null, source: 'unavailable' };
|
||||||
return totalSize;
|
}
|
||||||
|
return { fileCount: summary.count, totalSize: summary.totalSize, source: 'meta-core' };
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -193,7 +237,7 @@ export class UnifiedAPIServer {
|
|||||||
this.setupStatsRoutes();
|
this.setupStatsRoutes();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Service discovery — proxies to meta-core's /api/services using the
|
// Service discovery — beacon v2 neighbour list, served from the
|
||||||
// LeaderClient to resolve meta-core's current URL dynamically.
|
// LeaderClient to resolve meta-core's current URL dynamically.
|
||||||
this.setupServiceDiscoveryRoutes();
|
this.setupServiceDiscoveryRoutes();
|
||||||
|
|
||||||
@@ -524,53 +568,17 @@ export class UnifiedAPIServer {
|
|||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Setup Stats API routes (Redis stats for monitor UI)
|
* Setup Stats API routes (file totals for the monitor UI)
|
||||||
*/
|
*/
|
||||||
private setupStatsRoutes(): void {
|
private setupStatsRoutes(): void {
|
||||||
if (!this.kvClient) {
|
if (!this.kvClient) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get Redis/KV stats (for monitor UI)
|
// At most one meta-core call per FILE_STATS_TTL_MS however often the
|
||||||
this.app.get('/api/stats', async (request, reply) => {
|
// monitor polls — see getFileStats.
|
||||||
try {
|
this.app.get('/api/stats', async () => {
|
||||||
const hashIds = await this.kvClient!.getAllHashIds();
|
return this.getFileStats();
|
||||||
const redis = (this.kvClient as IKVClientWithPubSub).getRedisClient?.() as { info: (section: string) => Promise<string> } | undefined;
|
|
||||||
|
|
||||||
let memoryUsage = 'N/A';
|
|
||||||
let memoryUsageBytes = 0;
|
|
||||||
if (redis) {
|
|
||||||
try {
|
|
||||||
const info = await redis.info('memory');
|
|
||||||
const match = info.match(/used_memory_human:(\S+)/);
|
|
||||||
const bytesMatch = info.match(/used_memory:(\d+)/);
|
|
||||||
if (match) {
|
|
||||||
memoryUsage = match[1];
|
|
||||||
}
|
|
||||||
if (bytesMatch) {
|
|
||||||
memoryUsageBytes = parseInt(bytesMatch[1], 10);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// Ignore memory info errors
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get total size from Redis sizeByte (eventually correct as files are processed)
|
|
||||||
const totalSize = await this.getTotalFileSizeFromRedis();
|
|
||||||
|
|
||||||
return {
|
|
||||||
fileCount: hashIds.length,
|
|
||||||
keyCount: hashIds.length,
|
|
||||||
totalSize,
|
|
||||||
memoryUsage,
|
|
||||||
memoryUsageBytes
|
|
||||||
};
|
|
||||||
} catch (error: any) {
|
|
||||||
return reply.status(500).send({
|
|
||||||
error: 'Failed to get stats',
|
|
||||||
details: error.message
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -584,33 +592,31 @@ export class UnifiedAPIServer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Service discovery — proxies to meta-core's /api/services, resolving the
|
* Service discovery — beacon v2 (docs/project-architecture/beacon-v2.md).
|
||||||
* current leader's URL via LeaderClient (no hardcoded hostname).
|
* Served from this service's own beacon view; no meta-core round trip, so
|
||||||
|
* the nav survives a core outage.
|
||||||
*/
|
*/
|
||||||
private setupServiceDiscoveryRoutes(): void {
|
private setupServiceDiscoveryRoutes(): void {
|
||||||
this.app.get('/api/services', async (_request, reply) => {
|
// beacon v2: neighbours heard over UDP, served from this service's own
|
||||||
try {
|
// view. Unlike /api/services below it needs no meta-core, so the nav still
|
||||||
const leaderClient = this.kvManager?.getLeaderClient();
|
// renders when the core is down. `?all=1` returns every instance,
|
||||||
if (!leaderClient) {
|
// `?cap=<pattern>` filters by capability. `services` is kept as an alias
|
||||||
return reply.status(503).send({ error: 'KVManager not initialized' });
|
// while any older dashboard build is still in circulation.
|
||||||
}
|
this.app.get('/api/neighbors', async (request, reply) => {
|
||||||
const apiUrl = await leaderClient.getApiUrl();
|
const leaderClient = this.kvManager?.getLeaderClient();
|
||||||
if (!apiUrl) {
|
if (!leaderClient) {
|
||||||
return reply.status(503).send({ error: 'Leader not available yet' });
|
return reply.send({ current: 'meta-sort', enabled: false, count: 0, neighbors: [] });
|
||||||
}
|
|
||||||
const response = await fetch(`${apiUrl}/api/services`, {
|
|
||||||
signal: AbortSignal.timeout(5000),
|
|
||||||
});
|
|
||||||
if (!response.ok) {
|
|
||||||
return reply.status(response.status).send({
|
|
||||||
error: `Upstream ${apiUrl} returned ${response.status}`,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
const body = await response.json();
|
|
||||||
return reply.send(body);
|
|
||||||
} catch (err) {
|
|
||||||
return reply.status(502).send({ error: getErrorMessage(err) });
|
|
||||||
}
|
}
|
||||||
|
const q = (request.query ?? {}) as { all?: string; cap?: string };
|
||||||
|
const neighbors = leaderClient.getNeighbors({ all: !!q.all, cap: q.cap || undefined });
|
||||||
|
return reply.send({
|
||||||
|
current: 'meta-sort',
|
||||||
|
enabled: true,
|
||||||
|
count: neighbors.length,
|
||||||
|
neighbors,
|
||||||
|
services: neighbors,
|
||||||
|
self: leaderClient.self(),
|
||||||
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -886,38 +892,43 @@ export class UnifiedAPIServer {
|
|||||||
return reply.status(400).send({ error: `Plugin '${pluginId}' is not active` });
|
return reply.status(400).send({ error: `Plugin '${pluginId}' is not active` });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!hasFileTuples(this.kvClient)) {
|
||||||
|
return reply.status(501).send({ error: 'Recompute needs meta-core GET /api/files/tuples' });
|
||||||
|
}
|
||||||
|
const kvClient = this.kvClient as IKVClientWithFileTuples;
|
||||||
|
|
||||||
|
if (this.recomputeInFlight.has(pluginId)) {
|
||||||
|
return reply.status(409).send({ error: `Recompute for plugin '${pluginId}' is already being queued` });
|
||||||
|
}
|
||||||
|
|
||||||
|
this.recomputeInFlight.add(pluginId);
|
||||||
try {
|
try {
|
||||||
// Get all files from KV
|
// Only file-backed records can be recomputed, and meta-core lists exactly
|
||||||
const hashIds = await this.kvClient.getAllHashIds();
|
// those in one batched call. Walking getAllHashIds() instead reads every
|
||||||
console.log(`[Recompute] Starting recompute for plugin '${pluginId}' on ${hashIds.length} files`);
|
// gateway record too (82k on watch.nsl.sh) to keep a few thousand.
|
||||||
|
const tuples = await kvClient.getFileTuples();
|
||||||
|
if (!tuples || !tuples.files) {
|
||||||
|
return reply.status(501).send({
|
||||||
|
error: 'Recompute needs meta-core GET /api/files/tuples',
|
||||||
|
details: 'meta-core did not return a file list'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const candidates = tuples.files;
|
||||||
|
console.log(`[Recompute] Starting recompute for plugin '${pluginId}' on ${candidates.length} files`);
|
||||||
|
|
||||||
// Prepare file data with metadata for TaskScheduler
|
// Prepare file data with metadata for TaskScheduler
|
||||||
const files: Array<{ filePath: string; fileHash: string; kvData?: Record<string, string> }> = [];
|
const files: Array<{ filePath: string; fileHash: string; kvData?: Record<string, string> }> = [];
|
||||||
|
await forEachWithConcurrency(candidates, RECOMPUTE_READ_CONCURRENCY, async (tuple) => {
|
||||||
for (const hashId of hashIds) {
|
const metadata = await kvClient.getMetadataFlat(tuple.hashId);
|
||||||
const metadata = await this.kvClient.getMetadataFlat(hashId);
|
if (!metadata) {
|
||||||
if (metadata && metadata.filePath) {
|
return;
|
||||||
// Convert nested metadata to flat key-value pairs for KVStore
|
|
||||||
const kvData: Record<string, string> = {};
|
|
||||||
const flattenObj = (obj: any, prefix = '') => {
|
|
||||||
for (const [key, value] of Object.entries(obj)) {
|
|
||||||
const fullKey = prefix ? `${prefix}/${key}` : key;
|
|
||||||
if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
|
|
||||||
flattenObj(value, fullKey);
|
|
||||||
} else if (value !== undefined && value !== null) {
|
|
||||||
kvData[fullKey] = String(value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
flattenObj(metadata);
|
|
||||||
|
|
||||||
files.push({
|
|
||||||
fileHash: hashId,
|
|
||||||
filePath: metadata.filePath,
|
|
||||||
kvData
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
files.push({
|
||||||
|
fileHash: tuple.hashId,
|
||||||
|
filePath: metadata.filePath || tuple.filePath,
|
||||||
|
kvData: flattenMetadata(metadata)
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
// Create and enqueue tasks with forceRecompute option
|
// Create and enqueue tasks with forceRecompute option
|
||||||
const tasks = taskScheduler.createTasksForPluginOnFiles(
|
const tasks = taskScheduler.createTasksForPluginOnFiles(
|
||||||
@@ -935,7 +946,7 @@ export class UnifiedAPIServer {
|
|||||||
status: 'ok',
|
status: 'ok',
|
||||||
message: `Recompute triggered for plugin '${pluginId}'`,
|
message: `Recompute triggered for plugin '${pluginId}'`,
|
||||||
filesQueued: tasks.length,
|
filesQueued: tasks.length,
|
||||||
totalFiles: hashIds.length
|
totalFiles: candidates.length
|
||||||
};
|
};
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
console.error(`[Recompute] Error triggering recompute for plugin '${pluginId}':`, error);
|
console.error(`[Recompute] Error triggering recompute for plugin '${pluginId}':`, error);
|
||||||
@@ -943,6 +954,8 @@ export class UnifiedAPIServer {
|
|||||||
error: 'Failed to trigger recompute',
|
error: 'Failed to trigger recompute',
|
||||||
details: error.message
|
details: error.message
|
||||||
});
|
});
|
||||||
|
} finally {
|
||||||
|
this.recomputeInFlight.delete(pluginId);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -1014,7 +1027,9 @@ export class UnifiedAPIServer {
|
|||||||
instanceCount: p.instances,
|
instanceCount: p.instances,
|
||||||
healthyCount: p.healthyInstances,
|
healthyCount: p.healthyInstances,
|
||||||
enabled: p.enabled,
|
enabled: p.enabled,
|
||||||
image: p.image
|
image: p.image,
|
||||||
|
kind: p.kind,
|
||||||
|
url: p.url
|
||||||
})),
|
})),
|
||||||
queue: queueStatus || null
|
queue: queueStatus || null
|
||||||
};
|
};
|
||||||
@@ -1027,6 +1042,67 @@ export class UnifiedAPIServer {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Beacon v2 Scan card: enrichment plugins advertising on the network
|
||||||
|
// (metamesh.enrich/<id>), classified against what this meta-sort runs.
|
||||||
|
this.app.post('/api/plugins/discover', async (_request, reply) => {
|
||||||
|
const leaderClient = this.kvManager?.getLeaderClient();
|
||||||
|
const empty = {
|
||||||
|
cap: 'metamesh.enrich/*', disabled: true,
|
||||||
|
summary: { nodes: 0, capable: 0, configured: 0, boundElsewhere: 0, addable: 0 },
|
||||||
|
candidates: [],
|
||||||
|
};
|
||||||
|
if (!leaderClient) return reply.send(empty);
|
||||||
|
const status = this.containerManager?.getStatus();
|
||||||
|
const configured: Array<[string, string]> = (status?.plugins ?? [])
|
||||||
|
.filter((p) => p.url)
|
||||||
|
.map((p) => [p.pluginId, p.url as string]);
|
||||||
|
const report = await leaderClient.scan('metamesh.enrich/*', configured, 1500);
|
||||||
|
// Same plugin id already loaded under another URL (e.g. our own spawned
|
||||||
|
// container of it): adding it would clash, so it counts as configured.
|
||||||
|
const loaded = new Set((status?.plugins ?? []).map((p) => p.pluginId));
|
||||||
|
for (const c of report.candidates) {
|
||||||
|
if (c.state !== 'addable') continue;
|
||||||
|
const id = c.caps.map((cap) => cap.match(/^metamesh\.enrich\/([^@]+)/)?.[1]).find((x) => x && loaded.has(x));
|
||||||
|
if (id) {
|
||||||
|
c.state = 'configured';
|
||||||
|
c.configuredAs = id;
|
||||||
|
report.summary.addable--;
|
||||||
|
report.summary.configured++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return reply.send(report);
|
||||||
|
});
|
||||||
|
|
||||||
|
// External plugin (one meta-sort did not spawn) — the Scan card's Add.
|
||||||
|
this.app.post<{ Body: { url?: string; name?: string } }>('/api/plugins/external', async (request, reply) => {
|
||||||
|
if (!this.containerManager) {
|
||||||
|
return reply.status(503).send({ error: 'Container manager not initialized' });
|
||||||
|
}
|
||||||
|
const url = request.body?.url;
|
||||||
|
if (!url) return reply.status(400).send({ error: 'url is required' });
|
||||||
|
try {
|
||||||
|
const entry = await this.containerManager.addExternalPlugin(url, request.body?.name);
|
||||||
|
// Bring it into the processing pipeline (same as /api/plugins/rescan).
|
||||||
|
await this.getPluginManager?.()?.loadContainerPlugins();
|
||||||
|
return { success: true, plugin: entry };
|
||||||
|
} catch (error: any) {
|
||||||
|
return reply.status(400).send({ error: error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this.app.delete<{ Params: { pluginId: string } }>('/api/plugins/external/:pluginId', async (request, reply) => {
|
||||||
|
if (!this.containerManager) {
|
||||||
|
return reply.status(503).send({ error: 'Container manager not initialized' });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await this.containerManager.removeExternalPlugin(request.params.pluginId);
|
||||||
|
await this.getPluginManager?.()?.loadContainerPlugins();
|
||||||
|
return { success: true };
|
||||||
|
} catch (error: any) {
|
||||||
|
return reply.status(400).send({ error: error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// Get container plugin manifest
|
// Get container plugin manifest
|
||||||
this.app.get<{
|
this.app.get<{
|
||||||
Params: { pluginId: string }
|
Params: { pluginId: string }
|
||||||
@@ -1171,6 +1247,9 @@ export class UnifiedAPIServer {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
await this.containerManager.removePlugin(pluginId);
|
await this.containerManager.removePlugin(pluginId);
|
||||||
|
// Drop it from the processing pipeline too (else it lingers in
|
||||||
|
// /api/plugins until the next rescan or restart).
|
||||||
|
await this.getPluginManager?.()?.loadContainerPlugins();
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
message: `Plugin '${pluginId}' removed successfully`
|
message: `Plugin '${pluginId}' removed successfully`
|
||||||
@@ -1242,9 +1321,8 @@ export class UnifiedAPIServer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Setup meta-core compatible API routes
|
* Setup meta-core compatible API routes for container plugins: merged reads
|
||||||
* These routes allow container plugins to write metadata directly to Redis
|
* (`GET /meta/...`) and the signed-claims relay (`POST /api/claims`).
|
||||||
* Matches the meta-core Go sidecar API for compatibility
|
|
||||||
*/
|
*/
|
||||||
private setupMetaCoreRoutes(): void {
|
private setupMetaCoreRoutes(): void {
|
||||||
if (!this.kvClient) {
|
if (!this.kvClient) {
|
||||||
@@ -1299,125 +1377,43 @@ export class UnifiedAPIServer {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// PUT /meta/{hash}/{key} - Set single property
|
// Writes: plugins post signed MMUR2 claims; meta-sort relays them to
|
||||||
this.app.put<{
|
// meta-core untouched (never re-signs — the plugin is the signer). See
|
||||||
Params: { hash: string; '*': string };
|
// docs/implementation/metacore-claims-model.md §15.
|
||||||
Body: { value: string }
|
this.app.post<{ Body: unknown }>('/api/claims', { bodyLimit: 16 * 1024 * 1024 }, async (request, reply) => {
|
||||||
}>('/meta/:hash/*', async (request, reply) => {
|
if (!this.kvClient!.relayClaims) {
|
||||||
const { hash } = request.params;
|
return reply.status(503).send({ error: 'meta-core API not configured' });
|
||||||
const key = request.params['*'];
|
|
||||||
const { value } = request.body || {};
|
|
||||||
|
|
||||||
if (!key) {
|
|
||||||
return reply.status(400).send({ error: 'Missing key' });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (value === undefined) {
|
|
||||||
return reply.status(400).send({ error: 'Missing value in body' });
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Get existing metadata and merge
|
const { status, body } = await this.kvClient!.relayClaims(request.body);
|
||||||
const existing = await this.kvClient!.getMetadataFlat(hash) || {};
|
return reply.status(status).send(body);
|
||||||
existing[key] = String(value);
|
|
||||||
await this.kvClient!.setMetadataFlat(hash, existing);
|
|
||||||
|
|
||||||
return { status: 'ok' };
|
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
return reply.status(500).send({
|
return reply.status(502).send({ error: 'Failed to relay claims to meta-core', details: error.message });
|
||||||
error: 'Failed to set property',
|
|
||||||
details: error.message
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// DELETE /meta/{hash}/{key} - Delete single property
|
// Claims read relay: plugins read their own csv-set vote before appending.
|
||||||
this.app.delete<{
|
this.app.get<{ Params: { cid: string } }>('/api/meta/:cid/claims', async (request, reply) => {
|
||||||
Params: { hash: string; '*': string }
|
if (!this.kvClient!.fetchClaims) {
|
||||||
}>('/meta/:hash/*', async (request, reply) => {
|
return reply.status(503).send({ error: 'meta-core API not configured' });
|
||||||
const { hash } = request.params;
|
|
||||||
const key = request.params['*'];
|
|
||||||
|
|
||||||
if (!key) {
|
|
||||||
return reply.status(400).send({ error: 'Missing key' });
|
|
||||||
}
|
}
|
||||||
|
const q = request.url.indexOf('?');
|
||||||
try {
|
try {
|
||||||
const existing = await this.kvClient!.getMetadataFlat(hash);
|
const { status, body } = await this.kvClient!.fetchClaims(request.params.cid, q >= 0 ? request.url.slice(q) : '');
|
||||||
if (!existing) {
|
return reply.status(status).send(body);
|
||||||
return { status: 'ok' }; // Nothing to delete
|
|
||||||
}
|
|
||||||
|
|
||||||
delete existing[key];
|
|
||||||
await this.kvClient!.setMetadataFlat(hash, existing);
|
|
||||||
|
|
||||||
return { status: 'ok' };
|
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
return reply.status(500).send({
|
return reply.status(502).send({ error: 'Failed to read claims from meta-core', details: error.message });
|
||||||
error: 'Failed to delete property',
|
|
||||||
details: error.message
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// PATCH /meta/{hash} - Merge metadata (partial update)
|
// The unsigned write verbs are gone (meta-core v2.0.0 refuses unsigned
|
||||||
this.app.patch<{
|
// writes); answer like meta-core does so an old plugin build fails loudly.
|
||||||
Params: { hash: string };
|
const gone = async (_request: unknown, reply: any) =>
|
||||||
Body: Record<string, string>
|
reply.status(410).send({ error: 'gone', use: 'POST /api/claims' });
|
||||||
}>('/meta/:hash', async (request, reply) => {
|
this.app.put('/meta/:hash/*', gone);
|
||||||
const { hash } = request.params;
|
this.app.delete('/meta/:hash/*', gone);
|
||||||
const newMetadata = request.body;
|
this.app.patch('/meta/:hash', gone);
|
||||||
|
this.app.post('/meta/:hash/_add/:key', gone);
|
||||||
if (!newMetadata || typeof newMetadata !== 'object') {
|
|
||||||
return reply.status(400).send({ error: 'Body must be an object with key-value pairs' });
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Get existing metadata and merge
|
|
||||||
const existing = await this.kvClient!.getMetadataFlat(hash) || {};
|
|
||||||
const merged = { ...existing, ...newMetadata };
|
|
||||||
await this.kvClient!.setMetadataFlat(hash, merged);
|
|
||||||
|
|
||||||
return { status: 'ok' };
|
|
||||||
} catch (error: any) {
|
|
||||||
return reply.status(500).send({
|
|
||||||
error: 'Failed to merge metadata',
|
|
||||||
details: error.message
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// POST /meta/{hash}/_add/{key} - Add value to a set field (comma-separated)
|
|
||||||
this.app.post<{
|
|
||||||
Params: { hash: string; key: string };
|
|
||||||
Body: { value: string }
|
|
||||||
}>('/meta/:hash/_add/:key', async (request, reply) => {
|
|
||||||
const { hash, key } = request.params;
|
|
||||||
const { value } = request.body || {};
|
|
||||||
|
|
||||||
if (!value) {
|
|
||||||
return reply.status(400).send({ error: 'Missing value in body' });
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const existing = await this.kvClient!.getMetadataFlat(hash) || {};
|
|
||||||
const currentValue = existing[key] || '';
|
|
||||||
|
|
||||||
// Parse existing as comma-separated set
|
|
||||||
const values = new Set(currentValue ? currentValue.split(',').map(v => v.trim()) : []);
|
|
||||||
values.add(String(value));
|
|
||||||
|
|
||||||
existing[key] = Array.from(values).join(',');
|
|
||||||
await this.kvClient!.setMetadataFlat(hash, existing);
|
|
||||||
|
|
||||||
return { status: 'ok' };
|
|
||||||
} catch (error: any) {
|
|
||||||
return reply.status(500).send({
|
|
||||||
error: 'Failed to add to set',
|
|
||||||
details: error.message
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Health check for meta-core compatibility
|
// Health check for meta-core compatibility
|
||||||
this.app.get('/meta-health', async () => {
|
this.app.get('/meta-health', async () => {
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
import { expect } from 'chai';
|
import { expect } from 'chai';
|
||||||
import { UnifiedAPIServer } from './UnifiedAPIServer.js';
|
import { UnifiedAPIServer } from './UnifiedAPIServer.js';
|
||||||
import { UnifiedProcessingStateManager } from '../logic/UnifiedProcessingStateManager.js';
|
import { UnifiedProcessingStateManager } from '../logic/UnifiedProcessingStateManager.js';
|
||||||
|
import { performanceMetrics } from '../metrics/PerformanceMetrics.js';
|
||||||
import type { IKVClient } from '../kv/IKVClient.js';
|
import type { IKVClient } from '../kv/IKVClient.js';
|
||||||
import type { FastifyInstance } from 'fastify';
|
import type { FastifyInstance } from 'fastify';
|
||||||
|
|
||||||
@@ -23,6 +24,25 @@ class MockKVClient implements IKVClient {
|
|||||||
private data: Map<string, Map<string, any>> = new Map();
|
private data: Map<string, Map<string, any>> = new Map();
|
||||||
private rawStore: Map<string, string> = new Map();
|
private rawStore: Map<string, string> = new Map();
|
||||||
|
|
||||||
|
// Stand-in for meta-core's GET /api/files/tuples. null = a meta-core that
|
||||||
|
// predates the endpoint.
|
||||||
|
fileTuples: Array<{ hashId: string; filePath: string; sizeByte: number; mtimeNano: number }> | null = null;
|
||||||
|
fileTuplesDelayMs = 0;
|
||||||
|
calls = { getFileTuples: 0, getAllHashIds: 0, getMetadataFlat: 0 };
|
||||||
|
|
||||||
|
async getFileTuples(opts: { summary?: boolean } = {}) {
|
||||||
|
this.calls.getFileTuples++;
|
||||||
|
if (this.fileTuplesDelayMs) {
|
||||||
|
await new Promise(resolve => setTimeout(resolve, this.fileTuplesDelayMs));
|
||||||
|
}
|
||||||
|
if (!this.fileTuples) return null;
|
||||||
|
const files = this.fileTuples;
|
||||||
|
const totalSize = files.reduce((sum, f) => sum + f.sizeByte, 0);
|
||||||
|
return opts.summary
|
||||||
|
? { count: files.length, totalSize }
|
||||||
|
: { count: files.length, totalSize, files };
|
||||||
|
}
|
||||||
|
|
||||||
// Basic operations
|
// Basic operations
|
||||||
async set(key: string, value: any): Promise<void> {
|
async set(key: string, value: any): Promise<void> {
|
||||||
this.rawStore.set(key, JSON.stringify(value));
|
this.rawStore.set(key, JSON.stringify(value));
|
||||||
@@ -99,6 +119,7 @@ class MockKVClient implements IKVClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async getMetadataFlat(hashId: string): Promise<any | null> {
|
async getMetadataFlat(hashId: string): Promise<any | null> {
|
||||||
|
this.calls.getMetadataFlat++;
|
||||||
const entry = this.data.get(hashId);
|
const entry = this.data.get(hashId);
|
||||||
if (!entry) return null;
|
if (!entry) return null;
|
||||||
return Object.fromEntries(entry);
|
return Object.fromEntries(entry);
|
||||||
@@ -117,6 +138,23 @@ class MockKVClient implements IKVClient {
|
|||||||
this.data.get(hashId)!.set(property, value);
|
this.data.get(hashId)!.set(property, value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Bodies relayed to meta-core's POST /api/claims, in order. */
|
||||||
|
relayed: unknown[] = [];
|
||||||
|
|
||||||
|
/** `cid + search` of every claims read relayed to meta-core. */
|
||||||
|
claimReads: string[] = [];
|
||||||
|
|
||||||
|
async fetchClaims(cid: string, search: string): Promise<{ status: number; body: unknown }> {
|
||||||
|
this.claimReads.push(cid + search);
|
||||||
|
return { status: 200, body: { claims: [] } };
|
||||||
|
}
|
||||||
|
|
||||||
|
async relayClaims(body: unknown): Promise<{ status: number; body: unknown }> {
|
||||||
|
this.relayed.push(body);
|
||||||
|
const claims = Array.isArray(body) ? body : [];
|
||||||
|
return { status: 200, body: claims.map(() => ({ status: 'accepted' })) };
|
||||||
|
}
|
||||||
|
|
||||||
async deleteMetadataFlat(hashId: string): Promise<number> {
|
async deleteMetadataFlat(hashId: string): Promise<number> {
|
||||||
const entry = this.data.get(hashId);
|
const entry = this.data.get(hashId);
|
||||||
const count = entry?.size ?? 0;
|
const count = entry?.size ?? 0;
|
||||||
@@ -125,6 +163,7 @@ class MockKVClient implements IKVClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async getAllHashIds(): Promise<string[]> {
|
async getAllHashIds(): Promise<string[]> {
|
||||||
|
this.calls.getAllHashIds++;
|
||||||
return Array.from(this.data.keys());
|
return Array.from(this.data.keys());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -641,72 +680,38 @@ describe('UnifiedAPIServer', function() {
|
|||||||
expect(body).to.have.property('value', 'movie');
|
expect(body).to.have.property('value', 'movie');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('PUT /meta/:hash/:key sets property value', async function() {
|
it('unsigned write verbs answer 410 with a pointer to POST /api/claims', async function() {
|
||||||
const response = await app.inject({
|
const attempts = [
|
||||||
method: 'PUT',
|
{ method: 'PUT' as const, url: '/meta/testhash001/metaCustomField', payload: { value: 'x' } },
|
||||||
url: '/meta/testhash001/metaCustomField',
|
{ method: 'PATCH' as const, url: '/meta/testhash001', payload: { patchedField: 'x' } },
|
||||||
payload: { value: 'metaCustomValue' }
|
{ method: 'DELETE' as const, url: '/meta/testhash001/fileName' },
|
||||||
});
|
{ method: 'POST' as const, url: '/meta/testhash001/_add/genres', payload: { value: 'Drama' } },
|
||||||
|
];
|
||||||
expect(response.statusCode).to.equal(200);
|
for (const a of attempts) {
|
||||||
|
const response = await app.inject(a);
|
||||||
// Verify the update
|
expect(response.statusCode, `${a.method} ${a.url}`).to.equal(410);
|
||||||
const verify = await app.inject({
|
expect(JSON.parse(response.payload)).to.deep.equal({ error: 'gone', use: 'POST /api/claims' });
|
||||||
method: 'GET',
|
}
|
||||||
url: '/meta/testhash001/metaCustomField'
|
// Nothing was written behind the 410s.
|
||||||
});
|
const verify = await app.inject({ method: 'GET', url: '/meta/testhash001/fileName' });
|
||||||
const body = JSON.parse(verify.payload);
|
expect(JSON.parse(verify.payload)).to.have.property('value', 'Test Movie.mp4');
|
||||||
expect(body).to.have.property('value', 'metaCustomValue');
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('PATCH /meta/:hash merges metadata', async function() {
|
it('GET /api/meta/:cid/claims relays the read to meta-core with its query', async function() {
|
||||||
const response = await app.inject({
|
const response = await app.inject({ method: 'GET', url: '/api/meta/bafycid/claims?key=genres' });
|
||||||
method: 'PATCH',
|
|
||||||
url: '/meta/testhash001',
|
|
||||||
payload: {
|
|
||||||
patchedField: 'patchedValue',
|
|
||||||
anotherField: '123'
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(response.statusCode).to.equal(200);
|
expect(response.statusCode).to.equal(200);
|
||||||
const body = JSON.parse(response.payload);
|
expect(JSON.parse(response.payload)).to.deep.equal({ claims: [] });
|
||||||
expect(body).to.have.property('status', 'ok');
|
expect(mockKV.claimReads.at(-1)).to.equal('bafycid?key=genres');
|
||||||
|
|
||||||
// Verify the merge
|
|
||||||
const verify = await app.inject({
|
|
||||||
method: 'GET',
|
|
||||||
url: '/meta/testhash001'
|
|
||||||
});
|
|
||||||
const verifyBody = JSON.parse(verify.payload);
|
|
||||||
expect(verifyBody.metadata).to.have.property('patchedField', 'patchedValue');
|
|
||||||
expect(verifyBody.metadata).to.have.property('fileName', 'Test Movie.mp4'); // Original preserved
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('DELETE /meta/:hash/:key removes property', async function() {
|
it('POST /api/claims relays the signed batch to meta-core untouched', async function() {
|
||||||
// First set a property
|
const batch = [{ cid: 'bafy', uid: 'zQ3s', key: 'title', value: 'A', ts: 1, sig: 'c2ln' }];
|
||||||
await app.inject({
|
const response = await app.inject({ method: 'POST', url: '/api/claims', payload: batch });
|
||||||
method: 'PUT',
|
|
||||||
url: '/meta/testhash001/toDeleteMeta',
|
|
||||||
payload: { value: 'deleteMe' }
|
|
||||||
});
|
|
||||||
|
|
||||||
// Verify property was set
|
|
||||||
const beforeDelete = await app.inject({
|
|
||||||
method: 'GET',
|
|
||||||
url: '/meta/testhash001/toDeleteMeta'
|
|
||||||
});
|
|
||||||
expect(beforeDelete.statusCode).to.equal(200);
|
|
||||||
|
|
||||||
// Then delete it
|
|
||||||
const response = await app.inject({
|
|
||||||
method: 'DELETE',
|
|
||||||
url: '/meta/testhash001/toDeleteMeta'
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(response.statusCode).to.equal(200);
|
expect(response.statusCode).to.equal(200);
|
||||||
const body = JSON.parse(response.payload);
|
expect(JSON.parse(response.payload)).to.deep.equal([{ status: 'accepted' }]);
|
||||||
expect(body).to.have.property('status', 'ok');
|
expect(mockKV.relayed.at(-1)).to.deep.equal(batch);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -736,3 +741,157 @@ describe('UnifiedAPIServer', function() {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// File totals + recompute against meta-core's GET /api/files/tuples
|
||||||
|
// =============================================================================
|
||||||
|
//
|
||||||
|
// Each test builds its own server: /api/stats caches for 30 s and recompute is
|
||||||
|
// single-flight, so shared state between tests would hide both behaviours.
|
||||||
|
|
||||||
|
describe('UnifiedAPIServer file totals and recompute', function() {
|
||||||
|
const tuple = (hashId: string, sizeByte: number) =>
|
||||||
|
({ hashId, filePath: `/files/watch/${hashId}.mkv`, sizeByte, mtimeNano: 1 });
|
||||||
|
|
||||||
|
let app: FastifyInstance;
|
||||||
|
let kv: MockKVClient;
|
||||||
|
let queued: Array<{ pluginId: string; fileHash: string }>;
|
||||||
|
|
||||||
|
beforeEach(async function() {
|
||||||
|
kv = new MockKVClient();
|
||||||
|
queued = [];
|
||||||
|
const pluginManager = { getPlugins: () => [{ id: 'ffmpeg', active: true }] };
|
||||||
|
const taskScheduler = {
|
||||||
|
createTasksForPluginOnFiles: (pluginId: string, files: Array<{ fileHash: string }>) =>
|
||||||
|
files.map(f => ({ pluginId, fileHash: f.fileHash })),
|
||||||
|
enqueueTasks: (tasks: Array<{ pluginId: string; fileHash: string }>) => { queued.push(...tasks); },
|
||||||
|
};
|
||||||
|
const server = new UnifiedAPIServer(
|
||||||
|
{ port: 0, host: 'localhost', enableCors: false },
|
||||||
|
new MockProcessingStateManager() as any,
|
||||||
|
kv as any,
|
||||||
|
4,
|
||||||
|
16,
|
||||||
|
() => ({ fast: { pending: 0, running: 0 }, background: { pending: 0, running: 0 } }),
|
||||||
|
undefined,
|
||||||
|
() => pluginManager as any,
|
||||||
|
() => taskScheduler as any
|
||||||
|
);
|
||||||
|
app = server.getApp();
|
||||||
|
await app.ready();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(async function() {
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('GET /api/stats sums meta-core file tuples without walking hash ids', async function() {
|
||||||
|
kv.fileTuples = [tuple('a', 100), tuple('b', 250)];
|
||||||
|
|
||||||
|
const response = await app.inject({ method: 'GET', url: '/api/stats' });
|
||||||
|
|
||||||
|
expect(response.statusCode).to.equal(200);
|
||||||
|
expect(JSON.parse(response.payload)).to.deep.equal({ fileCount: 2, totalSize: 350, source: 'meta-core' });
|
||||||
|
expect(kv.calls.getAllHashIds).to.equal(0);
|
||||||
|
expect(kv.calls.getMetadataFlat).to.equal(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('GET /api/stats degrades to nulls on a meta-core without the endpoint', async function() {
|
||||||
|
kv.fileTuples = null;
|
||||||
|
|
||||||
|
const response = await app.inject({ method: 'GET', url: '/api/stats' });
|
||||||
|
|
||||||
|
expect(response.statusCode).to.equal(200);
|
||||||
|
expect(JSON.parse(response.payload)).to.deep.equal({ fileCount: null, totalSize: null, source: 'unavailable' });
|
||||||
|
expect(kv.calls.getAllHashIds).to.equal(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('GET /api/stats shares one meta-core call between concurrent polls', async function() {
|
||||||
|
kv.fileTuples = [tuple('a', 100)];
|
||||||
|
kv.fileTuplesDelayMs = 50;
|
||||||
|
|
||||||
|
const responses = await Promise.all(
|
||||||
|
Array.from({ length: 10 }, () => app.inject({ method: 'GET', url: '/api/stats' }))
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const response of responses) {
|
||||||
|
expect(response.statusCode).to.equal(200);
|
||||||
|
expect(JSON.parse(response.payload).totalSize).to.equal(100);
|
||||||
|
}
|
||||||
|
expect(kv.calls.getFileTuples).to.equal(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('POST recompute returns 501 on a meta-core without the endpoint', async function() {
|
||||||
|
kv.fileTuples = null;
|
||||||
|
|
||||||
|
const response = await app.inject({ method: 'POST', url: '/api/plugins/ffmpeg/recompute' });
|
||||||
|
|
||||||
|
expect(response.statusCode).to.equal(501);
|
||||||
|
expect(kv.calls.getAllHashIds).to.equal(0);
|
||||||
|
expect(queued).to.have.length(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('POST recompute queues only file-backed records', async function() {
|
||||||
|
kv.seedData('a', { filePath: '/files/watch/a.mkv', fileType: 'video' });
|
||||||
|
kv.seedData('b', { filePath: '/files/watch/b.mkv', fileType: 'video' });
|
||||||
|
kv.seedData('gateway-record', { title: 'Not a file' });
|
||||||
|
kv.fileTuples = [tuple('a', 100), tuple('b', 250)];
|
||||||
|
|
||||||
|
const response = await app.inject({ method: 'POST', url: '/api/plugins/ffmpeg/recompute' });
|
||||||
|
|
||||||
|
expect(response.statusCode).to.equal(200);
|
||||||
|
const body = JSON.parse(response.payload);
|
||||||
|
expect(body.filesQueued).to.equal(2);
|
||||||
|
expect(body.totalFiles).to.equal(2);
|
||||||
|
expect(queued.map(q => q.fileHash).sort()).to.deep.equal(['a', 'b']);
|
||||||
|
expect(kv.calls.getMetadataFlat).to.equal(2);
|
||||||
|
expect(kv.calls.getAllHashIds).to.equal(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('POST recompute refuses a second run for the same plugin while one is queuing', async function() {
|
||||||
|
kv.seedData('a', { filePath: '/files/watch/a.mkv' });
|
||||||
|
kv.fileTuples = [tuple('a', 100)];
|
||||||
|
kv.fileTuplesDelayMs = 50;
|
||||||
|
|
||||||
|
const [first, second] = await Promise.all([
|
||||||
|
app.inject({ method: 'POST', url: '/api/plugins/ffmpeg/recompute' }),
|
||||||
|
app.inject({ method: 'POST', url: '/api/plugins/ffmpeg/recompute' }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect([first.statusCode, second.statusCode].sort()).to.deep.equal([200, 409]);
|
||||||
|
expect(queued).to.have.length(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// =============================================================================
|
||||||
|
// File-level processing metric
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
describe('UnifiedProcessingStateManager file metric', function() {
|
||||||
|
// Files announced over SSE go straight to light processing; they are never
|
||||||
|
// marked discovered, which is the path that used to leave "Processed" at 0.
|
||||||
|
const runFile = (manager: UnifiedProcessingStateManager, filePath: string, error?: string) => {
|
||||||
|
manager.startLightProcessing(filePath);
|
||||||
|
manager.completeLightProcessing(filePath, 'bagacbabaeexamplehash');
|
||||||
|
manager.startHashProcessing(filePath);
|
||||||
|
manager.completeHashProcessing(filePath, 'bagacbabaeexamplehash', undefined, error);
|
||||||
|
};
|
||||||
|
|
||||||
|
it('counts a file as processed when its hash phase completes cleanly', function() {
|
||||||
|
const manager = new UnifiedProcessingStateManager();
|
||||||
|
const before = performanceMetrics.getMetrics().totalFilesProcessed;
|
||||||
|
|
||||||
|
runFile(manager, '/files/watch/metric-ok.mkv');
|
||||||
|
|
||||||
|
expect(performanceMetrics.getMetrics().totalFilesProcessed).to.equal(before + 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not count a file whose hash phase failed', function() {
|
||||||
|
const manager = new UnifiedProcessingStateManager();
|
||||||
|
const before = performanceMetrics.getMetrics().totalFilesProcessed;
|
||||||
|
|
||||||
|
runFile(manager, '/files/watch/metric-failed.mkv', 'plugin failed');
|
||||||
|
|
||||||
|
expect(performanceMetrics.getMetrics().totalFilesProcessed).to.equal(before);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -89,6 +89,13 @@ interface EnvConfig {
|
|||||||
/** Path to container plugins config file (default: '/app/plugins.yml') */
|
/** Path to container plugins config file (default: '/app/plugins.yml') */
|
||||||
CONTAINER_PLUGINS_CONFIG: string;
|
CONTAINER_PLUGINS_CONFIG: string;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* External plugins added by URL from the Plugins page's beacon Scan card
|
||||||
|
* (default: '<CACHE_FOLDER_PATH>/state/external-plugins.json'). Kept apart
|
||||||
|
* from plugins.yml, which the store app mounts read-only.
|
||||||
|
*/
|
||||||
|
EXTERNAL_PLUGINS_PATH: string;
|
||||||
|
|
||||||
/** Docker socket path (default: '/var/run/docker.sock') */
|
/** Docker socket path (default: '/var/run/docker.sock') */
|
||||||
DOCKER_SOCKET_PATH: string;
|
DOCKER_SOCKET_PATH: string;
|
||||||
|
|
||||||
@@ -112,6 +119,16 @@ interface EnvConfig {
|
|||||||
*/
|
*/
|
||||||
PLUGIN_CACHE_HOST_PATH?: string;
|
PLUGIN_CACHE_HOST_PATH?: string;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Where meta-sort keeps one signing key per container plugin
|
||||||
|
* (`<dir>/<pluginId>.key`, 0600), injected as `METAMESH_SIGNING_KEY`.
|
||||||
|
* Default: `<dirname(METAMESH_SIGNING_KEY_FILE)>/plugins` — next to
|
||||||
|
* meta-sort's own key, so one backed-up `keys/` dir holds every identity
|
||||||
|
* (store/dev bind it at /keys). Falls back to
|
||||||
|
* `<CACHE_FOLDER_PATH>/state/keys/plugins` when no key file is configured.
|
||||||
|
*/
|
||||||
|
METASORT_PLUGIN_KEYS_DIR: string;
|
||||||
|
|
||||||
// NOTE: Plugin output files are written via WebDAV (WEBDAV_URL/plugin/<pluginId>/)
|
// NOTE: Plugin output files are written via WebDAV (WEBDAV_URL/plugin/<pluginId>/)
|
||||||
// No PLUGIN_OUTPUT_HOST_PATH needed - plugins use HTTP PUT to write files
|
// No PLUGIN_OUTPUT_HOST_PATH needed - plugins use HTTP PUT to write files
|
||||||
|
|
||||||
@@ -156,12 +173,18 @@ export const config: EnvConfig = {
|
|||||||
|
|
||||||
// Container Plugins Configuration
|
// Container Plugins Configuration
|
||||||
CONTAINER_PLUGINS_CONFIG: process.env.CONTAINER_PLUGINS_CONFIG || '/app/plugins.yml',
|
CONTAINER_PLUGINS_CONFIG: process.env.CONTAINER_PLUGINS_CONFIG || '/app/plugins.yml',
|
||||||
|
EXTERNAL_PLUGINS_PATH: process.env.EXTERNAL_PLUGINS_PATH
|
||||||
|
|| `${process.env.CACHE_FOLDER_PATH || '/data/cache'}/state/external-plugins.json`,
|
||||||
DOCKER_SOCKET_PATH: process.env.DOCKER_SOCKET_PATH || '/var/run/docker.sock',
|
DOCKER_SOCKET_PATH: process.env.DOCKER_SOCKET_PATH || '/var/run/docker.sock',
|
||||||
CONTAINER_CALLBACK_URL: process.env.CONTAINER_CALLBACK_URL || 'http://meta-sort:8180',
|
CONTAINER_CALLBACK_URL: process.env.CONTAINER_CALLBACK_URL || 'http://meta-sort:8180',
|
||||||
CONTAINER_META_CORE_URL: process.env.CONTAINER_META_CORE_URL || 'http://meta-sort',
|
CONTAINER_META_CORE_URL: process.env.CONTAINER_META_CORE_URL || 'http://meta-sort',
|
||||||
CONTAINER_NETWORK: process.env.CONTAINER_NETWORK || 'meta-network',
|
CONTAINER_NETWORK: process.env.CONTAINER_NETWORK || 'meta-network',
|
||||||
PLUGIN_STACK_NAME: process.env.PLUGIN_STACK_NAME,
|
PLUGIN_STACK_NAME: process.env.PLUGIN_STACK_NAME,
|
||||||
PLUGIN_CACHE_HOST_PATH: process.env.PLUGIN_CACHE_HOST_PATH,
|
PLUGIN_CACHE_HOST_PATH: process.env.PLUGIN_CACHE_HOST_PATH,
|
||||||
|
METASORT_PLUGIN_KEYS_DIR: process.env.METASORT_PLUGIN_KEYS_DIR
|
||||||
|
|| (process.env.METAMESH_SIGNING_KEY_FILE
|
||||||
|
? `${process.env.METAMESH_SIGNING_KEY_FILE.replace(/\/[^/]*$/, '') || '/'}/plugins`
|
||||||
|
: `${process.env.CACHE_FOLDER_PATH || '/data/cache'}/state/keys/plugins`),
|
||||||
|
|
||||||
// Event Subscriber Configuration
|
// Event Subscriber Configuration
|
||||||
META_CORE_URL: process.env.META_CORE_URL,
|
META_CORE_URL: process.env.META_CORE_URL,
|
||||||
|
|||||||
@@ -26,7 +26,8 @@ export function renamingRule(metamesh: Local, filepath?: string): string | null
|
|||||||
throw new Error(`No extension found for file: ${filepath}`);
|
throw new Error(`No extension found for file: ${filepath}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const title = metamesh?.titles?.eng || metamesh.originalTitle;
|
// The display name — never the `titles/*` name set, which has no preferred member (METADATA_KEYS.md §3).
|
||||||
|
const title = metamesh.title || metamesh.originalTitle;
|
||||||
if (!title) {
|
if (!title) {
|
||||||
if (metamesh.fileType !== "torrent") {
|
if (metamesh.fileType !== "torrent") {
|
||||||
//don't warn for torrent files because they don't always have a title (eg representing a folder of files)
|
//don't warn for torrent files because they don't always have a title (eg representing a folder of files)
|
||||||
|
|||||||
@@ -25,6 +25,10 @@ import type {
|
|||||||
PluginConfigureResponse,
|
PluginConfigureResponse,
|
||||||
} from './types.js';
|
} from './types.js';
|
||||||
import { config } from '../config/EnvConfig.js';
|
import { config } from '../config/EnvConfig.js';
|
||||||
|
import { existsSync } from 'fs';
|
||||||
|
import { hostname } from 'os';
|
||||||
|
import { randomBytes } from 'crypto';
|
||||||
|
import { ExternalPluginStore, type ExternalPluginEntry } from './ExternalPluginStore.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Service info structure from meta-core service discovery
|
* Service info structure from meta-core service discovery
|
||||||
@@ -96,6 +100,11 @@ export class ContainerManager extends EventEmitter {
|
|||||||
private stackName?: string;
|
private stackName?: string;
|
||||||
private callbackUrl: string;
|
private callbackUrl: string;
|
||||||
private metaCoreUrl: string;
|
private metaCoreUrl: string;
|
||||||
|
/** External plugins (added by URL); see ExternalPluginStore. */
|
||||||
|
private externalStore: ExternalPluginStore;
|
||||||
|
private externalEntries: ExternalPluginEntry[] = [];
|
||||||
|
/** False when Docker is unreachable: only external plugins run then. */
|
||||||
|
private dockerAvailable = false;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private configPath: string = config.CONTAINER_PLUGINS_CONFIG,
|
private configPath: string = config.CONTAINER_PLUGINS_CONFIG,
|
||||||
@@ -116,6 +125,12 @@ export class ContainerManager extends EventEmitter {
|
|||||||
|
|
||||||
// Configure stack name for Docker Desktop grouping
|
// Configure stack name for Docker Desktop grouping
|
||||||
this.stackName = config.PLUGIN_STACK_NAME;
|
this.stackName = config.PLUGIN_STACK_NAME;
|
||||||
|
this.externalStore = new ExternalPluginStore(config.EXTERNAL_PLUGINS_PATH);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Swap the external-plugin store (tests). */
|
||||||
|
setExternalStore(store: ExternalPluginStore): void {
|
||||||
|
this.externalStore = store;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -142,53 +157,18 @@ export class ContainerManager extends EventEmitter {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fall back to service discovery for any missing URLs
|
// Anything still missing is a configuration problem, not something to
|
||||||
const serviceFile = join(config.META_CORE_PATH, 'services', 'meta-sort.json');
|
// guess at. The old fallback here read
|
||||||
|
// `${META_CORE_PATH}/services/meta-sort.json` — a filename that stopped
|
||||||
try {
|
// existing when registration files became hostname-suffixed, using a
|
||||||
const content = await fs.readFile(serviceFile, 'utf-8');
|
// schema (`.api` / `.endpoints`) that no longer matched either. It had
|
||||||
const serviceInfo: ServiceInfo = JSON.parse(content);
|
// been falling into its own catch block for a long time, and the
|
||||||
|
// volume it read is gone since meta-discovery v1.
|
||||||
// Extract URLs from service info
|
if (!this.callbackUrl) {
|
||||||
const api = serviceInfo.api;
|
console.warn('[ContainerManager] No callback URL — set CONTAINER_CALLBACK_URL');
|
||||||
const endpoints = serviceInfo.endpoints || {};
|
}
|
||||||
|
if (!this.webdavUrl) {
|
||||||
// Use service discovery for callback URL if not set
|
console.warn('[ContainerManager] No WebDAV URL — meta-core did not supply one');
|
||||||
if (!this.callbackUrl) {
|
|
||||||
if (endpoints.callback) {
|
|
||||||
this.callbackUrl = endpoints.callback;
|
|
||||||
console.log(`[ContainerManager] Discovered callback URL: ${this.callbackUrl}`);
|
|
||||||
} else if (api) {
|
|
||||||
// Fallback: construct from api base
|
|
||||||
this.callbackUrl = `${api}/api/plugins/callback`;
|
|
||||||
console.log(`[ContainerManager] Constructed callback URL: ${this.callbackUrl}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Use service discovery for WebDAV URL if not set (fallback)
|
|
||||||
if (!this.webdavUrl) {
|
|
||||||
if (endpoints.webdav) {
|
|
||||||
this.webdavUrl = endpoints.webdav;
|
|
||||||
console.log(`[ContainerManager] Discovered WebDAV URL: ${this.webdavUrl}`);
|
|
||||||
} else if (api) {
|
|
||||||
// Fallback: construct from api base
|
|
||||||
this.webdavUrl = `${api}/webdav`;
|
|
||||||
console.log(`[ContainerManager] Constructed WebDAV URL: ${this.webdavUrl}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (endpoints.health) {
|
|
||||||
// Extract meta-core URL from health endpoint
|
|
||||||
const healthUrl = new URL(endpoints.health);
|
|
||||||
this.metaCoreUrl = `${healthUrl.protocol}//${healthUrl.host}`;
|
|
||||||
console.log(`[ContainerManager] Discovered meta-core URL: ${this.metaCoreUrl}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('[ContainerManager] Service discovery successful');
|
|
||||||
} catch (error) {
|
|
||||||
console.warn(`[ContainerManager] Service discovery failed: ${error}`);
|
|
||||||
console.log(`[ContainerManager] Using callback URL: ${this.callbackUrl}`);
|
|
||||||
console.log(`[ContainerManager] Using WebDAV URL: ${this.webdavUrl || 'not set'}`);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -218,22 +198,41 @@ export class ContainerManager extends EventEmitter {
|
|||||||
console.warn(' Plugins will not have access to files.');
|
console.warn(' Plugins will not have access to files.');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Initialize Docker client
|
// Docker is needed only for the plugins we spawn. Without it (no
|
||||||
await this.dockerClient.initialize();
|
// socket, permission denied) external plugins still run.
|
||||||
|
try {
|
||||||
|
await this.dockerClient.initialize();
|
||||||
|
await this.dockerClient.ensureNetwork(this.network);
|
||||||
|
this.dockerAvailable = true;
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('[ContainerManager] Docker unavailable — only external plugins will run:', error);
|
||||||
|
}
|
||||||
|
|
||||||
// Ensure network exists
|
// Load configuration. A missing or broken plugins.yml means "no
|
||||||
await this.dockerClient.ensureNetwork(this.network);
|
// spawned plugins", not "no plugin manager": external plugins can
|
||||||
|
// still be added from the UI.
|
||||||
// Load configuration
|
if (existsSync(this.configPath)) {
|
||||||
this.pluginsConfig = await loadConfig(this.configPath);
|
try {
|
||||||
|
this.pluginsConfig = await loadConfig(this.configPath);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`[ContainerManager] Ignoring ${this.configPath}:`, error);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.log(`[ContainerManager] No ${this.configPath}; no spawned plugins`);
|
||||||
|
}
|
||||||
|
if (!this.pluginsConfig) {
|
||||||
|
this.pluginsConfig = { version: '1.0', plugins: {} };
|
||||||
|
}
|
||||||
|
|
||||||
// Get enabled plugins
|
// Get enabled plugins
|
||||||
const enabledPlugins = getEnabledPlugins(this.pluginsConfig);
|
const enabledPlugins = this.dockerAvailable ? getEnabledPlugins(this.pluginsConfig) : [];
|
||||||
|
|
||||||
console.log(`[ContainerManager] Found ${enabledPlugins.length} enabled plugins`);
|
console.log(`[ContainerManager] Found ${enabledPlugins.length} enabled plugins`);
|
||||||
|
|
||||||
// Clean up any stale containers from previous runs
|
if (this.dockerAvailable) {
|
||||||
await this.cleanupStaleContainers();
|
// Clean up any stale containers from previous runs
|
||||||
|
await this.cleanupStaleContainers();
|
||||||
|
}
|
||||||
|
|
||||||
// Spawn containers for each enabled plugin
|
// Spawn containers for each enabled plugin
|
||||||
for (const { id, config: pluginConfig } of enabledPlugins) {
|
for (const { id, config: pluginConfig } of enabledPlugins) {
|
||||||
@@ -248,6 +247,21 @@ export class ContainerManager extends EventEmitter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// External plugins (added by URL). One unreachable at boot is
|
||||||
|
// registered anyway and picked up by the health loop when it appears.
|
||||||
|
this.externalEntries = await this.externalStore.load();
|
||||||
|
for (const entry of this.externalEntries.filter((e) => e.enabled)) {
|
||||||
|
if (this.instances.has(entry.pluginId)) {
|
||||||
|
console.warn(
|
||||||
|
`[ContainerManager] External plugin '${entry.pluginId}' (${entry.url}) skipped: ` +
|
||||||
|
'a spawned plugin already has that id'
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
this.attachExternal(entry);
|
||||||
|
}
|
||||||
|
console.log(`[ContainerManager] ${this.externalEntries.length} external plugin(s) configured`);
|
||||||
|
|
||||||
this.initialized = true;
|
this.initialized = true;
|
||||||
this.emit('manager:initialized', { pluginCount: enabledPlugins.length });
|
this.emit('manager:initialized', { pluginCount: enabledPlugins.length });
|
||||||
|
|
||||||
@@ -363,6 +377,32 @@ export class ContainerManager extends EventEmitter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The plugin's signing key (64 hex chars), minted on first spawn and kept
|
||||||
|
* at `<METASORT_PLUGIN_KEYS_DIR>/<pluginId>.key` (0600). Containers are
|
||||||
|
* recreated on every spawn and store installs give them no volume, so the
|
||||||
|
* key lives with meta-sort and is injected as `METAMESH_SIGNING_KEY`: one
|
||||||
|
* stable uid per plugin id (docs/implementation/metacore-claims-model.md
|
||||||
|
* §15). Losing the file means a new uid and orphaned votes — back it up.
|
||||||
|
*/
|
||||||
|
private async pluginSigningKey(pluginId: string): Promise<string> {
|
||||||
|
const dir = config.METASORT_PLUGIN_KEYS_DIR;
|
||||||
|
const file = join(dir, `${pluginId.replace(/[^A-Za-z0-9._-]/g, '_')}.key`);
|
||||||
|
if (!existsSync(file)) {
|
||||||
|
await fs.mkdir(dir, { recursive: true, mode: 0o700 });
|
||||||
|
await fs.writeFile(file, randomBytes(32).toString('hex') + '\n', { mode: 0o600, flag: 'wx' })
|
||||||
|
.catch((error: NodeJS.ErrnoException) => {
|
||||||
|
if (error.code !== 'EEXIST') throw error; // another instance minted it first
|
||||||
|
});
|
||||||
|
console.log(`[ContainerManager] Minted signing key for plugin '${pluginId}' at ${file}`);
|
||||||
|
}
|
||||||
|
const key = (await fs.readFile(file, 'utf8')).trim();
|
||||||
|
if (!/^[0-9a-fA-F]{64}$/.test(key)) {
|
||||||
|
throw new Error(`[ContainerManager] signing key ${file} is not 64 hex characters`);
|
||||||
|
}
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Spawn a single container instance
|
* Spawn a single container instance
|
||||||
*/
|
*/
|
||||||
@@ -432,6 +472,8 @@ export class ContainerManager extends EventEmitter {
|
|||||||
console.warn(`[ContainerManager] WARNING: WebDAV not configured. Plugin '${pluginId}' won't have access to files. Ensure meta-core is running and accessible.`);
|
console.warn(`[ContainerManager] WARNING: WebDAV not configured. Plugin '${pluginId}' won't have access to files. Ensure meta-core is running and accessible.`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const signingKey = await this.pluginSigningKey(pluginId);
|
||||||
|
|
||||||
// Create container
|
// Create container
|
||||||
const containerId = await this.dockerClient.createContainer({
|
const containerId = await this.dockerClient.createContainer({
|
||||||
image: pluginConfig.image,
|
image: pluginConfig.image,
|
||||||
@@ -450,6 +492,16 @@ export class ContainerManager extends EventEmitter {
|
|||||||
CALLBACK_URL: this.callbackUrl,
|
CALLBACK_URL: this.callbackUrl,
|
||||||
WEBDAV_URL: this.webdavUrl || '',
|
WEBDAV_URL: this.webdavUrl || '',
|
||||||
FILES_PATH: '/files', // Virtual path - files accessed via WebDAV
|
FILES_PATH: '/files', // Virtual path - files accessed via WebDAV
|
||||||
|
// Beacon v2: advertise the URL we reach it on (so a Scan shows it
|
||||||
|
// as configured), and only to this meta-sort (another one's
|
||||||
|
// Scan shows it as bound elsewhere, never addable).
|
||||||
|
BEACON_ADVERTISE_URL: `http://${containerName}:8080`,
|
||||||
|
BEACON_BINDS: hostname(),
|
||||||
|
// Docker's own HOSTNAME is the container id; advertise a name
|
||||||
|
// an operator can read in the Scan card.
|
||||||
|
HOSTNAME: containerName,
|
||||||
|
// The plugin signs its claims as itself (one uid per plugin id).
|
||||||
|
METAMESH_SIGNING_KEY: signingKey,
|
||||||
},
|
},
|
||||||
// Docker Desktop grouping
|
// Docker Desktop grouping
|
||||||
stackName: this.stackName,
|
stackName: this.stackName,
|
||||||
@@ -462,6 +514,7 @@ export class ContainerManager extends EventEmitter {
|
|||||||
// Create instance record
|
// Create instance record
|
||||||
const instance: ContainerPluginInstance = {
|
const instance: ContainerPluginInstance = {
|
||||||
pluginId,
|
pluginId,
|
||||||
|
kind: 'container',
|
||||||
containerId,
|
containerId,
|
||||||
containerName,
|
containerName,
|
||||||
baseUrl: `http://${containerName}:8080`,
|
baseUrl: `http://${containerName}:8080`,
|
||||||
@@ -480,6 +533,12 @@ export class ContainerManager extends EventEmitter {
|
|||||||
* Stop a container instance
|
* Stop a container instance
|
||||||
*/
|
*/
|
||||||
private async stopInstance(instance: ContainerPluginInstance): Promise<void> {
|
private async stopInstance(instance: ContainerPluginInstance): Promise<void> {
|
||||||
|
if (instance.kind === 'external') {
|
||||||
|
// Not ours to stop: just stop using it.
|
||||||
|
instance.status = 'stopped';
|
||||||
|
this.emit('plugin:stopped', { pluginId: instance.pluginId, instanceIndex: instance.instanceIndex });
|
||||||
|
return;
|
||||||
|
}
|
||||||
console.log(`[ContainerManager] Stopping ${instance.containerName}...`);
|
console.log(`[ContainerManager] Stopping ${instance.containerName}...`);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -525,6 +584,11 @@ export class ContainerManager extends EventEmitter {
|
|||||||
if (healthy) {
|
if (healthy) {
|
||||||
instance.status = 'healthy';
|
instance.status = 'healthy';
|
||||||
instance.lastHealthCheck = Date.now();
|
instance.lastHealthCheck = Date.now();
|
||||||
|
// An external plugin unreachable at boot has no manifest
|
||||||
|
// yet; the scheduler needs one.
|
||||||
|
if (!instance.manifest) {
|
||||||
|
instance.manifest = await this.fetchManifest(instance).catch(() => undefined);
|
||||||
|
}
|
||||||
|
|
||||||
if (previousStatus !== 'healthy') {
|
if (previousStatus !== 'healthy') {
|
||||||
this.emit('plugin:healthy', { pluginId, instance });
|
this.emit('plugin:healthy', { pluginId, instance });
|
||||||
@@ -644,9 +708,12 @@ export class ContainerManager extends EventEmitter {
|
|||||||
throw new Error(`Failed to configure plugin: ${response.status}`);
|
throw new Error(`Failed to configure plugin: ${response.status}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Two contracts in the wild: `{ success: true }` and the TS plugins'
|
||||||
|
// `{ status: 'ok' }`. Before both were accepted every configure of a
|
||||||
|
// TS plugin "failed" (silently, behind a try/warn).
|
||||||
const data = (await response.json()) as PluginConfigureResponse;
|
const data = (await response.json()) as PluginConfigureResponse;
|
||||||
if (!data.success) {
|
if (!data.success && data.status !== 'ok') {
|
||||||
throw new Error(`Plugin configuration failed: ${data.error}`);
|
throw new Error(`Plugin configuration failed: ${data.error ?? JSON.stringify(data)}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -713,11 +780,14 @@ export class ContainerManager extends EventEmitter {
|
|||||||
for (const [pluginId, instances] of this.instances) {
|
for (const [pluginId, instances] of this.instances) {
|
||||||
const pluginConfig = this.pluginsConfig?.plugins[pluginId];
|
const pluginConfig = this.pluginsConfig?.plugins[pluginId];
|
||||||
const healthyCount = instances.filter((i) => i.status === 'healthy').length;
|
const healthyCount = instances.filter((i) => i.status === 'healthy').length;
|
||||||
|
const external = instances[0]?.kind === 'external';
|
||||||
|
|
||||||
plugins.push({
|
plugins.push({
|
||||||
pluginId,
|
pluginId,
|
||||||
enabled: pluginConfig?.enabled !== false,
|
enabled: pluginConfig?.enabled !== false,
|
||||||
image: pluginConfig?.image || 'unknown',
|
image: external ? instances[0].baseUrl : pluginConfig?.image || 'unknown',
|
||||||
|
kind: external ? 'external' : 'container',
|
||||||
|
url: instances[0]?.baseUrl,
|
||||||
instances: instances.length,
|
instances: instances.length,
|
||||||
healthyInstances: healthyCount,
|
healthyInstances: healthyCount,
|
||||||
manifest: instances[0]?.manifest,
|
manifest: instances[0]?.manifest,
|
||||||
@@ -752,6 +822,16 @@ export class ContainerManager extends EventEmitter {
|
|||||||
const instances = this.instances.get(pluginId);
|
const instances = this.instances.get(pluginId);
|
||||||
const pluginConfig = this.pluginsConfig?.plugins[pluginId];
|
const pluginConfig = this.pluginsConfig?.plugins[pluginId];
|
||||||
|
|
||||||
|
if (instances?.[0]?.kind === 'external') {
|
||||||
|
// Nothing to respawn: re-probe it and refresh its manifest.
|
||||||
|
for (const instance of instances) {
|
||||||
|
const healthy = await this.checkHealth(instance);
|
||||||
|
instance.status = healthy ? 'healthy' : 'unhealthy';
|
||||||
|
if (healthy) instance.manifest = await this.fetchManifest(instance).catch(() => instance.manifest);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (!instances || !pluginConfig) {
|
if (!instances || !pluginConfig) {
|
||||||
throw new Error(`Plugin '${pluginId}' not found`);
|
throw new Error(`Plugin '${pluginId}' not found`);
|
||||||
}
|
}
|
||||||
@@ -814,6 +894,93 @@ export class ContainerManager extends EventEmitter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The external plugins, as persisted. */
|
||||||
|
getExternalPlugins(): ExternalPluginEntry[] {
|
||||||
|
return [...this.externalEntries];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register an external plugin (one meta-sort did not spawn) by URL — what
|
||||||
|
* the beacon Scan card's Add does. Its manifest id becomes its plugin id,
|
||||||
|
* so it must be reachable now and its id must not clash with a loaded one.
|
||||||
|
*/
|
||||||
|
async addExternalPlugin(rawUrl: string, name?: string): Promise<ExternalPluginEntry> {
|
||||||
|
const url = rawUrl.trim().replace(/\/+$/, '');
|
||||||
|
if (!/^https?:\/\//.test(url)) {
|
||||||
|
throw new Error('url must start with http:// or https://');
|
||||||
|
}
|
||||||
|
for (const list of this.instances.values()) {
|
||||||
|
const holder = list.find((i) => i.baseUrl.replace(/\/+$/, '') === url);
|
||||||
|
if (holder) throw new Error(`${url} is already registered as '${holder.pluginId}'`);
|
||||||
|
}
|
||||||
|
const probe: ContainerPluginInstance = {
|
||||||
|
pluginId: '?', kind: 'external', containerId: '', containerName: url, baseUrl: url,
|
||||||
|
instanceIndex: 0, status: 'starting', tasksProcessed: 0, tasksFailed: 0,
|
||||||
|
};
|
||||||
|
let manifest: ContainerPluginManifest;
|
||||||
|
try {
|
||||||
|
manifest = await this.fetchManifest(probe);
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`could not read ${url}/manifest: ${error instanceof Error ? error.message : error}`);
|
||||||
|
}
|
||||||
|
const pluginId = manifest?.id;
|
||||||
|
if (!pluginId || !/^[a-z][a-z0-9-]*$/.test(pluginId)) {
|
||||||
|
throw new Error(`${url}/manifest has no usable plugin id`);
|
||||||
|
}
|
||||||
|
if (this.instances.has(pluginId)) {
|
||||||
|
throw new Error(`a plugin with id '${pluginId}' is already loaded`);
|
||||||
|
}
|
||||||
|
const entry: ExternalPluginEntry = {
|
||||||
|
pluginId, url, enabled: true, name: name?.trim() || undefined, addedAt: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
this.externalEntries = [...this.externalEntries.filter((e) => e.pluginId !== pluginId), entry];
|
||||||
|
await this.externalStore.save(this.externalEntries);
|
||||||
|
this.attachExternal(entry, manifest);
|
||||||
|
console.log(`[ContainerManager] External plugin '${pluginId}' added (${url})`);
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Forget an external plugin. Throws if `pluginId` is not one. */
|
||||||
|
async removeExternalPlugin(pluginId: string): Promise<void> {
|
||||||
|
const known = this.externalEntries.some((e) => e.pluginId === pluginId);
|
||||||
|
const instances = this.instances.get(pluginId);
|
||||||
|
if (!known && !(instances?.[0]?.kind === 'external')) {
|
||||||
|
throw new Error(`'${pluginId}' is not an external plugin`);
|
||||||
|
}
|
||||||
|
if (instances?.[0]?.kind === 'external') {
|
||||||
|
const interval = this.healthCheckIntervals.get(pluginId);
|
||||||
|
if (interval) {
|
||||||
|
clearInterval(interval);
|
||||||
|
this.healthCheckIntervals.delete(pluginId);
|
||||||
|
}
|
||||||
|
for (const instance of instances) await this.stopInstance(instance);
|
||||||
|
this.instances.delete(pluginId);
|
||||||
|
this.roundRobinCounters.delete(pluginId);
|
||||||
|
}
|
||||||
|
this.externalEntries = this.externalEntries.filter((e) => e.pluginId !== pluginId);
|
||||||
|
await this.externalStore.save(this.externalEntries);
|
||||||
|
console.log(`[ContainerManager] External plugin '${pluginId}' removed`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One instance pointing at `entry.url`, kept alive by the health loop. */
|
||||||
|
private attachExternal(entry: ExternalPluginEntry, manifest?: ContainerPluginManifest): void {
|
||||||
|
const instance: ContainerPluginInstance = {
|
||||||
|
pluginId: entry.pluginId,
|
||||||
|
kind: 'external',
|
||||||
|
containerId: '',
|
||||||
|
// The scheduler reports completions by this name; the URL is unique.
|
||||||
|
containerName: entry.url,
|
||||||
|
baseUrl: entry.url,
|
||||||
|
instanceIndex: 0,
|
||||||
|
status: 'starting',
|
||||||
|
manifest,
|
||||||
|
tasksProcessed: 0,
|
||||||
|
tasksFailed: 0,
|
||||||
|
};
|
||||||
|
this.instances.set(entry.pluginId, [instance]);
|
||||||
|
this.startHealthCheck(entry.pluginId);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Add a new plugin dynamically
|
* Add a new plugin dynamically
|
||||||
*/
|
*/
|
||||||
@@ -873,6 +1040,11 @@ export class ContainerManager extends EventEmitter {
|
|||||||
console.log(`[ContainerManager] Removing plugin '${pluginId}'...`);
|
console.log(`[ContainerManager] Removing plugin '${pluginId}'...`);
|
||||||
|
|
||||||
const instances = this.instances.get(pluginId);
|
const instances = this.instances.get(pluginId);
|
||||||
|
// An external plugin is forgotten (and un-persisted), never stopped.
|
||||||
|
if (instances?.[0]?.kind === 'external' || this.externalEntries.some((e) => e.pluginId === pluginId)) {
|
||||||
|
await this.removeExternalPlugin(pluginId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (instances) {
|
if (instances) {
|
||||||
// Stop health check
|
// Stop health check
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
/**
|
||||||
|
* External plugins — enrichment plugins meta-sort did NOT spawn, reached by
|
||||||
|
* URL (typically a MetaPlugin* store app found with the Plugins page's beacon
|
||||||
|
* Scan card). Persisted as JSON next to the cache, because the store app
|
||||||
|
* mounts plugins.yml read-only.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { promises as fs } from 'fs';
|
||||||
|
import { dirname } from 'path';
|
||||||
|
|
||||||
|
export interface ExternalPluginEntry {
|
||||||
|
/** The plugin's manifest id — its identity in the pipeline. */
|
||||||
|
pluginId: string;
|
||||||
|
/** Base URL of the plugin's HTTP contract (/manifest, /health, /process). */
|
||||||
|
url: string;
|
||||||
|
enabled: boolean;
|
||||||
|
/** Name it was added under (the advertising instance), display only. */
|
||||||
|
name?: string;
|
||||||
|
addedAt?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ExternalPluginStore {
|
||||||
|
constructor(private readonly path: string) {}
|
||||||
|
|
||||||
|
/** The persisted list; empty when the file is missing or unreadable. */
|
||||||
|
async load(): Promise<ExternalPluginEntry[]> {
|
||||||
|
let raw: string;
|
||||||
|
try {
|
||||||
|
raw = await fs.readFile(this.path, 'utf-8');
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(raw);
|
||||||
|
const list = Array.isArray(parsed?.plugins) ? parsed.plugins : [];
|
||||||
|
return list.filter(
|
||||||
|
(e: Partial<ExternalPluginEntry>) => typeof e?.pluginId === 'string' && typeof e?.url === 'string'
|
||||||
|
).map((e: ExternalPluginEntry) => ({ ...e, enabled: e.enabled !== false }));
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`[ExternalPluginStore] ${this.path} is not valid JSON; ignoring it:`, error);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Atomic write: a crash mid-save leaves the previous file intact. */
|
||||||
|
async save(entries: ExternalPluginEntry[]): Promise<void> {
|
||||||
|
await fs.mkdir(dirname(this.path), { recursive: true });
|
||||||
|
const tmp = `${this.path}.tmp`;
|
||||||
|
await fs.writeFile(tmp, JSON.stringify({ plugins: entries }, null, 2), 'utf-8');
|
||||||
|
await fs.rename(tmp, this.path);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import { strict as assert } from 'assert';
|
||||||
|
import { createServer, type Server } from 'http';
|
||||||
|
import { mkdtempSync, readFileSync } from 'fs';
|
||||||
|
import { tmpdir } from 'os';
|
||||||
|
import { join } from 'path';
|
||||||
|
import { ContainerManager } from './ContainerManager.js';
|
||||||
|
import { ExternalPluginStore } from './ExternalPluginStore.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* External plugins are the meta-sort side of the beacon Scan card's Add: a
|
||||||
|
* plugin meta-sort did not spawn, reached by URL, identified by its manifest
|
||||||
|
* id, persisted outside the read-only plugins.yml.
|
||||||
|
*/
|
||||||
|
describe('external plugins', () => {
|
||||||
|
let server: Server;
|
||||||
|
let url: string;
|
||||||
|
|
||||||
|
before(async () => {
|
||||||
|
server = createServer((req, res) => {
|
||||||
|
res.setHeader('Content-Type', 'application/json');
|
||||||
|
if (req.url === '/manifest') {
|
||||||
|
res.end(JSON.stringify({ id: 'language', name: 'Language', version: '1.0.2', defaultQueue: 'fast' }));
|
||||||
|
} else if (req.url === '/health') {
|
||||||
|
res.end(JSON.stringify({ status: 'healthy', ready: true, version: '1.0.2' }));
|
||||||
|
} else {
|
||||||
|
res.statusCode = 404;
|
||||||
|
res.end('{}');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()));
|
||||||
|
const addr = server.address();
|
||||||
|
url = `http://127.0.0.1:${typeof addr === 'object' && addr ? addr.port : 0}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
after(() => server.close());
|
||||||
|
|
||||||
|
function manager(path: string): ContainerManager {
|
||||||
|
const m = new ContainerManager('/nonexistent/plugins.yml', 'none', '/files', 'http://cb', 'http://core');
|
||||||
|
m.setExternalStore(new ExternalPluginStore(path));
|
||||||
|
return m;
|
||||||
|
}
|
||||||
|
|
||||||
|
it('adds by URL under the manifest id, persists, and refuses duplicates', async () => {
|
||||||
|
const path = join(mkdtempSync(join(tmpdir(), 'ext-')), 'state', 'external-plugins.json');
|
||||||
|
const m = manager(path);
|
||||||
|
const entry = await m.addExternalPlugin(`${url}/`, 'metapluginlanguage-plugin');
|
||||||
|
assert.equal(entry.pluginId, 'language');
|
||||||
|
assert.equal(entry.url, url, 'trailing slash normalised');
|
||||||
|
|
||||||
|
const saved = JSON.parse(readFileSync(path, 'utf-8'));
|
||||||
|
assert.equal(saved.plugins[0].pluginId, 'language');
|
||||||
|
|
||||||
|
await assert.rejects(m.addExternalPlugin(url), /already registered/);
|
||||||
|
const status = m.getStatus().plugins.find((p) => p.pluginId === 'language');
|
||||||
|
assert.equal(status?.kind, 'external');
|
||||||
|
assert.equal(status?.url, url);
|
||||||
|
|
||||||
|
await m.removeExternalPlugin('language');
|
||||||
|
assert.equal(m.getStatus().plugins.length, 0);
|
||||||
|
assert.deepEqual(JSON.parse(readFileSync(path, 'utf-8')).plugins, []);
|
||||||
|
await assert.rejects(m.removeExternalPlugin('language'), /not an external plugin/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects a URL whose manifest cannot be read', async () => {
|
||||||
|
const m = manager(join(mkdtempSync(join(tmpdir(), 'ext-')), 'x.json'));
|
||||||
|
await assert.rejects(m.addExternalPlugin('http://127.0.0.1:9/'), /could not read/);
|
||||||
|
await assert.rejects(m.addExternalPlugin('ftp://x'), /http/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a missing or corrupt store reads as empty', async () => {
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), 'ext-'));
|
||||||
|
assert.deepEqual(await new ExternalPluginStore(join(dir, 'missing.json')).load(), []);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -164,7 +164,12 @@ export type ContainerInstanceStatus = 'starting' | 'healthy' | 'unhealthy' | 'st
|
|||||||
export interface ContainerPluginInstance {
|
export interface ContainerPluginInstance {
|
||||||
/** Plugin ID */
|
/** Plugin ID */
|
||||||
pluginId: string;
|
pluginId: string;
|
||||||
/** Docker container ID */
|
/**
|
||||||
|
* `container` = spawned by meta-sort from plugins.yml; `external` = added by
|
||||||
|
* URL (beacon Scan card), not ours to start or stop. Absent = container.
|
||||||
|
*/
|
||||||
|
kind?: 'container' | 'external';
|
||||||
|
/** Docker container ID ('' for an external plugin) */
|
||||||
containerId: string;
|
containerId: string;
|
||||||
/** Container name (e.g., 'meta-plugin-ffmpeg-0') */
|
/** Container name (e.g., 'meta-plugin-ffmpeg-0') */
|
||||||
containerName: string;
|
containerName: string;
|
||||||
@@ -211,7 +216,9 @@ export interface PluginConfigureRequest {
|
|||||||
* Configure response from POST /configure
|
* Configure response from POST /configure
|
||||||
*/
|
*/
|
||||||
export interface PluginConfigureResponse {
|
export interface PluginConfigureResponse {
|
||||||
success: boolean;
|
/** Older contract. The TS plugins answer `{ status: 'ok' }` instead. */
|
||||||
|
success?: boolean;
|
||||||
|
status?: string;
|
||||||
error?: string;
|
error?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -315,7 +322,11 @@ export interface ContainerManagerStatus {
|
|||||||
plugins: Array<{
|
plugins: Array<{
|
||||||
pluginId: string;
|
pluginId: string;
|
||||||
enabled: boolean;
|
enabled: boolean;
|
||||||
|
/** Docker image, or the plugin URL for an external plugin. */
|
||||||
image: string;
|
image: string;
|
||||||
|
kind: 'container' | 'external';
|
||||||
|
/** Base URL of the first instance. */
|
||||||
|
url?: string;
|
||||||
instances: number;
|
instances: number;
|
||||||
healthyInstances: number;
|
healthyInstances: number;
|
||||||
manifest?: ContainerPluginManifest;
|
manifest?: ContainerPluginManifest;
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { strict as assert } from 'assert';
|
||||||
|
import { capMatches, classifyScan, suggestedName, type MeshNeighbor } from './meshdisco.js';
|
||||||
|
|
||||||
|
/** Mirrors meta-feeder-sdk `beacon::scan` tests: same rules, same JSON. */
|
||||||
|
describe('beacon v2 scan classification', () => {
|
||||||
|
const node = (instance: string, cap: string, http?: string, binds?: string): MeshNeighbor => ({
|
||||||
|
name: 'plugin', instance, caps: [cap], addr: '10.0.0.1', lastSeen: 0,
|
||||||
|
resources: [{ id: 'x', caps: [cap], ...(http ? { endpoints: { http } } : {}), ...(binds ? { binds } : {}) }],
|
||||||
|
});
|
||||||
|
|
||||||
|
it('classifies configured, addable and bound-elsewhere', () => {
|
||||||
|
const r = classifyScan('metamesh.enrich/*', 'metasort-app', [
|
||||||
|
node('meta-plugin-language-0', 'metamesh.enrich/language', 'http://meta-plugin-language-0:8080/', 'metasort-app'),
|
||||||
|
node('metapluginffmpeg-plugin', 'metamesh.enrich/ffmpeg', 'http://metapluginffmpeg-plugin:8080'),
|
||||||
|
node('other-sort-plugin', 'metamesh.enrich/tmdb', 'http://x:8080', 'other-metasort'),
|
||||||
|
node('no-endpoint', 'metamesh.enrich/tmdb'),
|
||||||
|
node('a-service', 'metamesh.service/meta-core', 'http://core'),
|
||||||
|
], [['language', 'http://meta-plugin-language-0:8080']]);
|
||||||
|
assert.deepEqual(r.summary, { nodes: 5, capable: 3, configured: 1, boundElsewhere: 1, addable: 1 });
|
||||||
|
assert.equal(r.candidates[0].instance, 'metapluginffmpeg-plugin');
|
||||||
|
assert.equal(r.candidates[1].configuredAs, 'language');
|
||||||
|
assert.equal(r.candidates[2].state, 'bound-elsewhere');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('caps and names', () => {
|
||||||
|
assert.ok(capMatches('metamesh.enrich/*', 'metamesh.enrich/language@1'));
|
||||||
|
assert.ok(!capMatches('metamesh.enrich/*', 'metamesh.enrichx/a'));
|
||||||
|
assert.equal(suggestedName('MetaPlugin Language'), 'metaplugin-language');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
import {config} from "./config/EnvConfig.js";
|
import {config} from "./config/EnvConfig.js";
|
||||||
|
|
||||||
import os from 'os';
|
import os from 'os';
|
||||||
import {existsSync} from 'fs';
|
|
||||||
import {WatchedFileProcessor} from "./logic/WatchedFileProcessor.js";
|
import {WatchedFileProcessor} from "./logic/WatchedFileProcessor.js";
|
||||||
import {UnifiedAPIServer} from "./api/UnifiedAPIServer.js";
|
import {UnifiedAPIServer} from "./api/UnifiedAPIServer.js";
|
||||||
import {StreamingPipeline} from "./logic/pipeline/StreamingPipeline.js";
|
import {StreamingPipeline} from "./logic/pipeline/StreamingPipeline.js";
|
||||||
@@ -125,22 +124,18 @@ process.on('SIGINT', async () => {
|
|||||||
// Start initial discovery and processing (streaming pipeline)
|
// Start initial discovery and processing (streaming pipeline)
|
||||||
(async () => {
|
(async () => {
|
||||||
try {
|
try {
|
||||||
// Validate META_CORE_PATH is configured (required for leader discovery)
|
// meta-core is located over UDP (beacon v2) — no /meta-core
|
||||||
if (!config.META_CORE_PATH) {
|
// volume required. META_CORE_URL, when set, pins it and discovery
|
||||||
console.error('[Startup] ERROR: META_CORE_PATH is required. Set META_CORE_PATH environment variable.');
|
// never overrides; see docs/project-architecture/service-discovery.md.
|
||||||
console.error('[Startup] Example: META_CORE_PATH=/meta-core');
|
{
|
||||||
process.exit(1);
|
console.log('[Startup] Initializing KV Manager (meta-core discovery)...');
|
||||||
}
|
|
||||||
|
|
||||||
// Initialize KV Manager (Redis via leader discovery)
|
|
||||||
if (config.META_CORE_PATH) {
|
|
||||||
console.log('[Startup] Initializing KV Manager (leader discovery)...');
|
|
||||||
kvManager = new KVManager({
|
kvManager = new KVManager({
|
||||||
metaCorePath: config.META_CORE_PATH,
|
metaCorePath: config.META_CORE_PATH,
|
||||||
filesPath: config.FILES_PATH,
|
filesPath: config.FILES_PATH,
|
||||||
serviceName: config.SERVICE_NAME,
|
serviceName: config.SERVICE_NAME,
|
||||||
apiPort: config.FUSE_API_PORT,
|
apiPort: config.FUSE_API_PORT,
|
||||||
baseUrl: config.BASE_URL,
|
baseUrl: config.BASE_URL,
|
||||||
|
metaCoreUrl: config.META_CORE_URL,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Wait for KV to be ready
|
// Wait for KV to be ready
|
||||||
@@ -172,8 +167,11 @@ process.on('SIGINT', async () => {
|
|||||||
const pluginManager = await initializePluginManager();
|
const pluginManager = await initializePluginManager();
|
||||||
console.log('[Startup] Plugin manager initialized');
|
console.log('[Startup] Plugin manager initialized');
|
||||||
|
|
||||||
// Initialize container plugins if config file exists
|
// Container plugins: the ones spawned from plugins.yml AND the external
|
||||||
if (existsSync(config.CONTAINER_PLUGINS_CONFIG)) {
|
// ones added by URL (beacon Scan card). Always initialised — with no
|
||||||
|
// plugins.yml and no Docker it still serves the external ones, and the
|
||||||
|
// Plugins page can add the first one.
|
||||||
|
{
|
||||||
console.log('[Startup] Initializing container plugins...');
|
console.log('[Startup] Initializing container plugins...');
|
||||||
try {
|
try {
|
||||||
// Get webdavUrlInternal from meta-core via LeaderClient (for container-to-container access)
|
// Get webdavUrlInternal from meta-core via LeaderClient (for container-to-container access)
|
||||||
@@ -219,8 +217,6 @@ process.on('SIGINT', async () => {
|
|||||||
console.error('[Startup] Failed to initialize container plugins:', error);
|
console.error('[Startup] Failed to initialize container plugins:', error);
|
||||||
console.log('[Startup] Continuing without container plugins...');
|
console.log('[Startup] Continuing without container plugins...');
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
console.log(`[Startup] Container plugins config not found at ${config.CONTAINER_PLUGINS_CONFIG}, skipping`);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Initialize hash index cache (loads existing hashes from disk)
|
// Initialize hash index cache (loads existing hashes from disk)
|
||||||
|
|||||||
@@ -102,10 +102,24 @@ export interface IKVClient {
|
|||||||
setMetadataProperty(hashId: string, property: string, value: string): Promise<void>;
|
setMetadataProperty(hashId: string, property: string, value: string): Promise<void>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Delete all metadata for a file
|
* Delete all metadata for a file. A no-op against meta-core v2.0.0+
|
||||||
|
* (claims model: records outlive files).
|
||||||
*/
|
*/
|
||||||
deleteMetadataFlat(hashId: string): Promise<number>;
|
deleteMetadataFlat(hashId: string): Promise<number>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Forward an already-signed claim batch to meta-core's `POST /api/claims`
|
||||||
|
* untouched (the relay plugins write through). Optional: only the
|
||||||
|
* meta-core-backed client implements it.
|
||||||
|
*/
|
||||||
|
relayClaims?(body: unknown): Promise<{ status: number; body: unknown }>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Forward `GET /api/meta/{cid}/claims` (+ query string) to meta-core
|
||||||
|
* verbatim. Optional, like relayClaims.
|
||||||
|
*/
|
||||||
|
fetchClaims?(cid: string, search: string): Promise<{ status: number; body: unknown }>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get all unique hash IDs (files) stored in KV
|
* Get all unique hash IDs (files) stored in KV
|
||||||
*/
|
*/
|
||||||
@@ -139,7 +153,7 @@ export interface KVClientConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 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 {
|
||||||
|
|||||||
@@ -2,13 +2,12 @@
|
|||||||
* KV Manager - Unified manager for KV storage and service discovery
|
* KV Manager - Unified manager for KV storage and service discovery
|
||||||
*
|
*
|
||||||
* This is the main entry point for the KV subsystem. It:
|
* This is the main entry point for the KV subsystem. It:
|
||||||
* 1. Uses LeaderClient to read leader info from meta-core
|
* 1. Uses LeaderClient to locate meta-core over UDP (beacon v2)
|
||||||
* 2. Creates and manages the KV client (Redis)
|
* 2. Creates and manages the KV client (Redis)
|
||||||
* 3. Handles service discovery registration
|
|
||||||
* 4. Manages reconnection on leader changes
|
* 4. Manages reconnection on leader changes
|
||||||
*
|
*
|
||||||
* Note: Leader election is now handled by meta-core (Go sidecar).
|
* Note: there is no leader election. meta-core announces itself on the
|
||||||
* This service only reads the leader info and connects to Redis.
|
* discovery group; this service listens and connects to its HTTP API.
|
||||||
*
|
*
|
||||||
* Usage:
|
* Usage:
|
||||||
* ```typescript
|
* ```typescript
|
||||||
@@ -28,7 +27,6 @@
|
|||||||
|
|
||||||
import { hostname } from 'os';
|
import { hostname } from 'os';
|
||||||
import { LeaderClient } from './LeaderClient.js';
|
import { LeaderClient } from './LeaderClient.js';
|
||||||
import { ServiceRegistration } from './ServiceRegistration.js';
|
|
||||||
import { RedisKVClient } from './RedisClient.js';
|
import { RedisKVClient } from './RedisClient.js';
|
||||||
import type { IKVClient, LeaderLockInfo } from './IKVClient.js';
|
import type { IKVClient, LeaderLockInfo } from './IKVClient.js';
|
||||||
import { configure as configureWebdav } from '../webdav/WebdavClient.js';
|
import { configure as configureWebdav } from '../webdav/WebdavClient.js';
|
||||||
@@ -59,7 +57,6 @@ interface KVManagerConfig {
|
|||||||
export class KVManager {
|
export class KVManager {
|
||||||
private config: KVManagerConfig;
|
private config: KVManagerConfig;
|
||||||
private leaderClient: LeaderClient | null = null;
|
private leaderClient: LeaderClient | null = null;
|
||||||
private serviceRegistration: ServiceRegistration | null = null;
|
|
||||||
private kvClient: IKVClient | null = null;
|
private kvClient: IKVClient | null = null;
|
||||||
private isStarted = false;
|
private isStarted = false;
|
||||||
private isShuttingDown = false;
|
private isShuttingDown = false;
|
||||||
@@ -112,8 +109,14 @@ export class KVManager {
|
|||||||
|
|
||||||
// Initialize leader client
|
// Initialize leader client
|
||||||
this.leaderClient = new LeaderClient({
|
this.leaderClient = new LeaderClient({
|
||||||
metaCorePath: this.config.metaCorePath,
|
metaCoreUrl: this.config.metaCoreUrl,
|
||||||
metaCoreUrl: this.config.metaCoreUrl
|
serviceName: this.config.serviceName,
|
||||||
|
// Browser-facing URL for the nav menu, in the order the spec requires:
|
||||||
|
// PUBLIC_URL (reachable when there is no Caddy perimeter in front — a
|
||||||
|
// debug-direct port) -> BASE_URL (the Caddy URL) -> container host.
|
||||||
|
// Announcing a Caddy URL on a stack with no Caddy running is what puts
|
||||||
|
// dead links in every neighbour's menu.
|
||||||
|
baseUrl: process.env.PUBLIC_URL || this.config.baseUrl || `http://${hostname()}:${this.config.apiPort}`,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Watch for leader changes
|
// Watch for leader changes
|
||||||
@@ -149,15 +152,9 @@ export class KVManager {
|
|||||||
// Start watching for leader changes
|
// Start watching for leader changes
|
||||||
this.leaderClient.startWatching();
|
this.leaderClient.startWatching();
|
||||||
|
|
||||||
// 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,
|
|
||||||
serviceName: this.config.serviceName,
|
|
||||||
version: '1.0.0',
|
|
||||||
apiUrl
|
|
||||||
});
|
|
||||||
await this.serviceRegistration.start();
|
|
||||||
|
|
||||||
this.isStarted = true;
|
this.isStarted = true;
|
||||||
this.notifyReady();
|
this.notifyReady();
|
||||||
@@ -224,10 +221,6 @@ export class KVManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Service registration stop (if it was started)
|
// Service registration stop (if it was started)
|
||||||
if (this.serviceRegistration) {
|
|
||||||
await this.serviceRegistration.stop();
|
|
||||||
this.serviceRegistration = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.isStarted = false;
|
this.isStarted = false;
|
||||||
console.log('[KVManager] Stopped');
|
console.log('[KVManager] Stopped');
|
||||||
@@ -324,9 +317,6 @@ export class KVManager {
|
|||||||
/**
|
/**
|
||||||
* Get service registration instance
|
* Get service registration instance
|
||||||
*/
|
*/
|
||||||
getServiceRegistration(): ServiceRegistration | null {
|
|
||||||
return this.serviceRegistration;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check if the KV store is healthy
|
* Check if the KV store is healthy
|
||||||
|
|||||||
@@ -1,26 +1,49 @@
|
|||||||
/**
|
/**
|
||||||
* LeaderClient - Client for reading leader info from meta-core
|
* LeaderClient - locates meta-core and exposes its URLs.
|
||||||
*
|
*
|
||||||
* This replaces the old LeaderElection.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:
|
||||||
* - Calls meta-core /urls API for current leader URLs
|
* - getLeaderInfo() / getUrls() / getApiUrl() / getWebdavUrl*()
|
||||||
* - Watches for leader changes via file system watcher
|
* - waitForLeader(timeoutMs) — same 30s default, same "poll until it answers"
|
||||||
|
* - startWatching() / onChange() — the fs.watch on the lock dir became "an
|
||||||
|
* announce arrived carrying a different apiUrl", feeding the same callback.
|
||||||
|
*
|
||||||
|
* 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 — the Go
|
||||||
|
* binary only ever runs as leader — and redisUrl has been empty since the
|
||||||
|
* api-mediated-access lockdown; everything routes over HTTP.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { promises as fs } from 'fs';
|
import { MetaCoreLocator, type MeshNeighbor, type ScanReport } from '../discovery/meshdisco.js';
|
||||||
import { watch, FSWatcher } from 'fs';
|
|
||||||
import { dirname } from 'path';
|
|
||||||
import type { LeaderLockInfo } from './IKVClient.js';
|
import type { LeaderLockInfo } from './IKVClient.js';
|
||||||
|
|
||||||
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 {
|
||||||
@@ -35,76 +58,79 @@ 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
|
// URL caching — only used on the pinned path, where the URLs still come
|
||||||
|
// from an HTTP GET /urls. A discovered core carries them in the announce.
|
||||||
private cachedUrls: URLsResponse | null = null;
|
private cachedUrls: URLsResponse | null = null;
|
||||||
private urlsCacheTime: number = 0;
|
private urlsCacheTime = 0;
|
||||||
private readonly urlsCacheTTL: number = 5000; // 5 seconds
|
private readonly urlsCacheTTL = 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-sort',
|
||||||
|
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();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Idempotent; safe to call from any entry point. */
|
||||||
|
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 that reintroduces direct Redis exposure.
|
||||||
|
* api-mediated-access PR D removed redisUrl; if it comes back, fail loudly
|
||||||
|
* so it can't go unnoticed. ALLOW_LEGACY_REDIS_URL=1 downgrades to a warn.
|
||||||
*/
|
*/
|
||||||
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;
|
'[LeaderClient] meta-core still publishes redisUrl; direct Redis access ' +
|
||||||
} catch (error) {
|
'was retired by the api-mediated-access lockdown. Verify meta-core version.';
|
||||||
console.error('[LeaderClient] Failed to read API URL from file:', error);
|
if (process.env.ALLOW_LEGACY_REDIS_URL === '1') {
|
||||||
return null;
|
console.warn('WARNING: ' + msg);
|
||||||
|
} else {
|
||||||
|
throw new Error(msg);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** HTTP GET {apiUrl}/urls — still needed when meta-core is pinned. */
|
||||||
* 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) {
|
||||||
console.error('[LeaderClient] Failed to fetch URLs:', response.status, response.statusText);
|
console.error('[LeaderClient] Failed to fetch URLs:', response.status, response.statusText);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
const parsed = (await response.json()) as URLsResponse;
|
||||||
const parsed = await response.json() as URLsResponse;
|
this.assertNoRedisUrl(parsed.redisUrl);
|
||||||
// api-mediated-access PR D: redisUrl is no longer published by
|
|
||||||
// meta-core. If it shows up, an older build snuck back in —
|
|
||||||
// fail loudly so the rollback can't go unnoticed. Set
|
|
||||||
// ALLOW_LEGACY_REDIS_URL=1 to downgrade to a warning during a
|
|
||||||
// deliberate temporary rollback.
|
|
||||||
if (parsed.redisUrl) {
|
|
||||||
const msg =
|
|
||||||
'[LeaderClient] meta-core still publishes redisUrl; ' +
|
|
||||||
'direct Redis access was retired by the api-mediated-access ' +
|
|
||||||
'lockdown. Verify meta-core version.';
|
|
||||||
if (process.env.ALLOW_LEGACY_REDIS_URL === '1') {
|
|
||||||
console.warn('WARNING: ' + msg);
|
|
||||||
} else {
|
|
||||||
throw new Error(msg);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
this.cachedUrls = parsed;
|
this.cachedUrls = parsed;
|
||||||
this.urlsCacheTime = now;
|
this.urlsCacheTime = now;
|
||||||
return this.cachedUrls;
|
return parsed;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('[LeaderClient] Error calling /urls API:', error);
|
console.error('[LeaderClient] Error calling /urls API:', error);
|
||||||
return null;
|
return null;
|
||||||
@@ -112,23 +138,37 @@ export class LeaderClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Read leader info from file and /urls API
|
* Resolve meta-core's URLs — from the announce when discovered (no HTTP
|
||||||
|
* hop needed, the payload already carries them), 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) {
|
||||||
|
console.error('[LeaderClient] 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,
|
||||||
@@ -137,7 +177,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) {
|
} catch (error) {
|
||||||
@@ -146,134 +186,67 @@ 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 = this.config.metaCoreUrl;
|
|
||||||
|
|
||||||
// Fall back to reading from file
|
|
||||||
if (!apiUrl) {
|
|
||||||
apiUrl = await this.getApiUrlFromFile();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!apiUrl) {
|
|
||||||
console.error('[LeaderClient] 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) {
|
// Locate the core (pin returns instantly; discovery probes).
|
||||||
|
await this.locator.waitForCore(timeoutMs);
|
||||||
|
|
||||||
|
// Then wait for a usable URLs payload — on the pinned path this is the
|
||||||
|
// first successful GET /urls, so meta-core still has to be up.
|
||||||
|
while (Date.now() < deadline) {
|
||||||
const info = await this.getLeaderInfo();
|
const info = await this.getLeaderInfo();
|
||||||
if (info) {
|
if (info) {
|
||||||
console.log(`[LeaderClient] Leader found: ${info.hostname} at ${info.redisUrl}`);
|
console.log(`[LeaderClient] meta-core found: ${info.hostname} at ${info.apiUrl}`);
|
||||||
return info;
|
return info;
|
||||||
}
|
}
|
||||||
|
console.log('[LeaderClient] Waiting for meta-core...');
|
||||||
console.log('[LeaderClient] 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') {
|
|
||||||
console.log('[LeaderClient] Leader info changed, invalidating cache...');
|
|
||||||
// Invalidate cache to force fresh API call
|
|
||||||
this.cachedUrls = null;
|
|
||||||
this.urlsCacheTime = 0;
|
|
||||||
|
|
||||||
this.getLeaderInfo().then(() => {
|
|
||||||
this.notifyChange();
|
|
||||||
}).catch(console.error);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log(`[LeaderClient] Watching for leader changes in ${lockDir}`);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('[LeaderClient] Failed to start watching:', error);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 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;
|
|
||||||
console.log('[LeaderClient] 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 {
|
||||||
|
console.log('[LeaderClient] meta-core changed, invalidating cache...');
|
||||||
for (const callback of this.onChangeCallbacks) {
|
for (const callback of this.onChangeCallbacks) {
|
||||||
try {
|
try {
|
||||||
callback();
|
callback();
|
||||||
@@ -283,18 +256,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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,23 +1,47 @@
|
|||||||
/**
|
/**
|
||||||
* MetaCoreApiWriter — HTTP writer for metadata, replacing direct Redis writes.
|
* MetaCoreApiWriter — meta-sort's HTTP client for meta-core.
|
||||||
*
|
*
|
||||||
* meta-core owns the Redis schema (UUID-rooted, reverse-indexed by CID). Any
|
* Since meta-core v2.0.0 (claims model) every metadata write is a vote signed
|
||||||
* service writing directly to Redis risks drifting the schema; the lockdown
|
* by meta-sort's own key (`METAMESH_SIGNING_KEY_FILE`) and posted to
|
||||||
* plan (docs/api-mediated-access.md in meta-core) routes every write through
|
* `POST /api/claims` (docs/implementation/metacore-claims-model.md). Signing
|
||||||
* meta-core's HTTP /meta/{hash} family.
|
* lives in `meta-core-client.ts`, mirrored from the plugins.
|
||||||
*
|
*
|
||||||
* This writer covers the three operations meta-sort actually performs in
|
* - setMetadataFlat → one signed claim per field (one batch)
|
||||||
* production:
|
* - setMetadataProperty → one signed claim
|
||||||
* - setMetadataFlat → PATCH /meta/{hash} (merge semantics)
|
* - deleteMetadataFlat → no-op: records describe content and outlive the
|
||||||
* - setMetadataProperty → PUT /meta/{hash}/{key}
|
* file (§13 G3); there is no record delete any more
|
||||||
* - deleteMetadataFlat → DELETE /meta/{hash}
|
* - relayClaims → pass-through of plugins' signed claims (relay,
|
||||||
|
* never re-signed)
|
||||||
*
|
*
|
||||||
* Reads and stream consumption stay on Redis in PR B; PR C migrates those.
|
* `filePath` and `mtimeNano` are meta-core's file-watcher facts (`local_file`,
|
||||||
|
* unsigned and box-local) — meta-sort never claims them.
|
||||||
*/
|
*/
|
||||||
import {
|
import {
|
||||||
buildRecordFields,
|
buildRecordFields,
|
||||||
buildFilePrefix,
|
buildFilePrefix,
|
||||||
} from './MetadataUtils.js';
|
} from './MetadataUtils.js';
|
||||||
|
import { MetaCoreClient } from './meta-core-client.js';
|
||||||
|
|
||||||
|
/** Watcher facts meta-core keeps in `local_file`; never written as claims. */
|
||||||
|
const LOCAL_FILE_FIELDS = ['filePath', 'mtimeNano'];
|
||||||
|
|
||||||
|
/** One file-backed root as listed by meta-core's GET /api/files/tuples. */
|
||||||
|
export interface FileTuple {
|
||||||
|
hashId: string;
|
||||||
|
filePath: string;
|
||||||
|
sizeByte: number;
|
||||||
|
mtimeNano: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GET /api/files/tuples body. `files` is present unless the summary form was
|
||||||
|
* asked for.
|
||||||
|
*/
|
||||||
|
export interface FileTuplesResult {
|
||||||
|
count: number;
|
||||||
|
totalSize: number;
|
||||||
|
files?: FileTuple[];
|
||||||
|
}
|
||||||
|
|
||||||
export interface MetaCoreApiWriterConfig {
|
export interface MetaCoreApiWriterConfig {
|
||||||
/** Base URL for meta-core's HTTP API (e.g. http://metacore-app:9000) */
|
/** Base URL for meta-core's HTTP API (e.g. http://metacore-app:9000) */
|
||||||
@@ -30,18 +54,19 @@ export interface MetaCoreApiWriterConfig {
|
|||||||
export class MetaCoreApiWriter {
|
export class MetaCoreApiWriter {
|
||||||
private apiUrl: string;
|
private apiUrl: string;
|
||||||
private timeoutMs: number;
|
private timeoutMs: number;
|
||||||
|
private claims: MetaCoreClient;
|
||||||
|
|
||||||
constructor(config: MetaCoreApiWriterConfig) {
|
constructor(config: MetaCoreApiWriterConfig) {
|
||||||
// Trim trailing slash so we can join paths predictably.
|
// Trim trailing slash so we can join paths predictably.
|
||||||
this.apiUrl = config.apiUrl.replace(/\/+$/, '');
|
this.apiUrl = config.apiUrl.replace(/\/+$/, '');
|
||||||
this.timeoutMs = config.timeoutMs ?? 30000;
|
this.timeoutMs = config.timeoutMs ?? 30000;
|
||||||
|
this.claims = new MetaCoreClient(this.apiUrl);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* PATCH /meta/{hash}.
|
* One signed claim per field, posted as a single batch. `hashId` is the
|
||||||
*
|
* content cid (meta-sort keys records by midhash256), which is what a claim
|
||||||
* meta-core's PATCH calls MergeMetadataFlat — merge semantics, matches
|
* names. Throws when meta-core refuses the batch.
|
||||||
* what setMetadataFlat used to do via Redis pipeline of SETs.
|
|
||||||
*/
|
*/
|
||||||
async setMetadataFlat(
|
async setMetadataFlat(
|
||||||
hashId: string,
|
hashId: string,
|
||||||
@@ -50,47 +75,63 @@ export class MetaCoreApiWriter {
|
|||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
// `buildRecordFields` is the single write-shape boundary, shared with the
|
// `buildRecordFields` is the single write-shape boundary, shared with the
|
||||||
// direct-Redis path in RedisClient. It emits the `cids/<cid>` key-set and
|
// direct-Redis path in RedisClient. It emits the `cids/<cid>` key-set and
|
||||||
// never a per-algorithm `cid_*` field — which meta-core would now reject
|
// never a per-algorithm `cid_*` field.
|
||||||
// with a 400 anyway.
|
const flat = buildRecordFields(metadata, [...excludeFields, ...LOCAL_FILE_FIELDS]);
|
||||||
const flat = buildRecordFields(metadata, excludeFields);
|
|
||||||
if (Object.keys(flat).length === 0) return;
|
if (Object.keys(flat).length === 0) return;
|
||||||
|
|
||||||
await this.fetchJson('PATCH', `/meta/${encodeURIComponent(hashId)}`, flat);
|
const ok = await this.claims.mergeMetadata(hashId, flat);
|
||||||
|
if (!ok) throw new Error(`[MetaCoreApiWriter] claims for ${hashId} were not accepted`);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** One signed claim. Throws when meta-core refuses it. */
|
||||||
* PUT /meta/{hash}/{key}.
|
|
||||||
*
|
|
||||||
* meta-core accepts either JSON {"value":"..."} or plain text; we use
|
|
||||||
* the JSON form to avoid ambiguity with values that happen to look like
|
|
||||||
* JSON themselves.
|
|
||||||
*/
|
|
||||||
async setMetadataProperty(hashId: string, property: string, value: string): Promise<void> {
|
async setMetadataProperty(hashId: string, property: string, value: string): Promise<void> {
|
||||||
await this.fetchJson(
|
if (LOCAL_FILE_FIELDS.includes(property)) return;
|
||||||
'PUT',
|
const ok = await this.claims.setProperty(hashId, property, value);
|
||||||
`/meta/${encodeURIComponent(hashId)}/${this.encodePropertyPath(property)}`,
|
if (!ok) throw new Error(`[MetaCoreApiWriter] claim ${hashId}/${property} was not accepted`);
|
||||||
{ value }
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* DELETE /meta/{hash}.
|
* No-op since the claims model: a record describes content, and votes about
|
||||||
*
|
* content stay true when one copy of the file disappears. meta-core's
|
||||||
* Removes every property and unregisters the hashId from file:__index__.
|
* watcher drops the file's `local_file` row on its own (§13 G3).
|
||||||
*/
|
*/
|
||||||
async deleteMetadataFlat(hashId: string): Promise<number> {
|
async deleteMetadataFlat(_hashId: string): Promise<number> {
|
||||||
const body = await this.fetchJson(
|
|
||||||
'DELETE',
|
|
||||||
`/meta/${encodeURIComponent(hashId)}`,
|
|
||||||
null
|
|
||||||
);
|
|
||||||
// meta-core's response is {success, hashId, deleted: N}.
|
|
||||||
if (body && typeof body === 'object' && typeof (body as any).deleted === 'number') {
|
|
||||||
return (body as any).deleted;
|
|
||||||
}
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Forward `GET /api/meta/{cid}/claims[?query]` to meta-core verbatim (plugins
|
||||||
|
* read their own csv-set vote through it before appending).
|
||||||
|
*/
|
||||||
|
async fetchClaims(cid: string, search: string): Promise<{ status: number; body: unknown }> {
|
||||||
|
const response = await fetch(`${this.apiUrl}/api/meta/${encodeURIComponent(cid)}/claims${search}`, {
|
||||||
|
method: 'GET',
|
||||||
|
signal: AbortSignal.timeout(this.timeoutMs),
|
||||||
|
headers: { Accept: 'application/json' },
|
||||||
|
});
|
||||||
|
const text = await response.text();
|
||||||
|
let parsed: unknown = text;
|
||||||
|
try { parsed = text ? JSON.parse(text) : null; } catch { /* keep raw text */ }
|
||||||
|
return { status: response.status, body: parsed };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Forward an already-signed claim batch to meta-core untouched (the relay
|
||||||
|
* plugins write through). Returns meta-core's status and body verbatim.
|
||||||
|
*/
|
||||||
|
async relayClaims(body: unknown): Promise<{ status: number; body: unknown }> {
|
||||||
|
const response = await fetch(`${this.apiUrl}/api/claims`, {
|
||||||
|
method: 'POST',
|
||||||
|
signal: AbortSignal.timeout(this.timeoutMs),
|
||||||
|
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
const text = await response.text();
|
||||||
|
let parsed: unknown = text;
|
||||||
|
try { parsed = text ? JSON.parse(text) : null; } catch { /* keep raw text */ }
|
||||||
|
return { status: response.status, body: parsed };
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* GET /meta/{hash}. Returns the flat metadata map (or null if absent).
|
* GET /meta/{hash}. Returns the flat metadata map (or null if absent).
|
||||||
*/
|
*/
|
||||||
@@ -139,6 +180,27 @@ export class MetaCoreApiWriter {
|
|||||||
return Array.isArray(ids) ? ids : [];
|
return Array.isArray(ids) ? ids : [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GET /api/files/tuples. meta-core's FILE-BACKED roots (records carrying
|
||||||
|
* filePath, sizeByte and mtimeNano) with sizes, read server-side in batched
|
||||||
|
* MGETs — the cheap alternative to walking getAllHashIds(), which on a
|
||||||
|
* shared meta-core is every gateway record too. `summary` omits the rows.
|
||||||
|
*
|
||||||
|
* Returns null when meta-core predates the endpoint (404, or a body that is
|
||||||
|
* not the expected JSON).
|
||||||
|
*/
|
||||||
|
async getFileTuples(opts: { summary?: boolean } = {}): Promise<FileTuplesResult | null> {
|
||||||
|
const path = opts.summary ? '/api/files/tuples?summary=1' : '/api/files/tuples';
|
||||||
|
const body = await this.fetchJsonAllowing404('GET', path);
|
||||||
|
if (!body || typeof body !== 'object') return null;
|
||||||
|
const b = body as { count?: unknown; totalSize?: unknown; files?: unknown };
|
||||||
|
return {
|
||||||
|
count: Number(b.count) || 0,
|
||||||
|
totalSize: Number(b.totalSize) || 0,
|
||||||
|
files: Array.isArray(b.files) ? (b.files as FileTuple[]) : undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* GET /health on meta-core. Used as a write-path health probe.
|
* GET /health on meta-core. Used as a write-path health probe.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ import {
|
|||||||
buildFilePrefix,
|
buildFilePrefix,
|
||||||
buildPropertyKey,
|
buildPropertyKey,
|
||||||
} from './MetadataUtils.js';
|
} from './MetadataUtils.js';
|
||||||
import { MetaCoreApiWriter } from './MetaCoreApiWriter.js';
|
import { MetaCoreApiWriter, type FileTuplesResult } from './MetaCoreApiWriter.js';
|
||||||
|
|
||||||
// ESM/CJS interop for ioredis
|
// ESM/CJS interop for ioredis
|
||||||
const Redis = (IORedis as any).default ?? IORedis;
|
const Redis = (IORedis as any).default ?? IORedis;
|
||||||
@@ -102,7 +102,22 @@ export class RedisKVClient implements IKVClient {
|
|||||||
// automatic connect. Any caller that tries to use the Redis
|
// automatic connect. Any caller that tries to use the Redis
|
||||||
// path (e.g. unmigrated stream code) will fail loudly rather
|
// path (e.g. unmigrated stream code) will fail loudly rather
|
||||||
// than silently misbehaving.
|
// than silently misbehaving.
|
||||||
this.redis = new Redis({ host: '127.0.0.1', port: 0, lazyConnect: true, enableOfflineQueue: false });
|
this.redis = new Redis({
|
||||||
|
host: '127.0.0.1',
|
||||||
|
port: 0,
|
||||||
|
lazyConnect: true,
|
||||||
|
enableOfflineQueue: false,
|
||||||
|
// Never reconnect. A stub that retries turns one stray call into
|
||||||
|
// an endless "Unhandled error event: ECONNREFUSED" loop.
|
||||||
|
retryStrategy: () => null,
|
||||||
|
maxRetriesPerRequest: 0,
|
||||||
|
});
|
||||||
|
let stubWarned = false;
|
||||||
|
this.redis.on('error', (err: Error) => {
|
||||||
|
if (stubWarned) return;
|
||||||
|
stubWarned = true;
|
||||||
|
console.warn(`[Redis] HTTP-only stub was used and refused (${err.message}) — a caller still reaches for direct Redis`);
|
||||||
|
});
|
||||||
this.isConnected = false;
|
this.isConnected = false;
|
||||||
console.log('[Redis] HTTP-only mode — no direct Redis connection');
|
console.log('[Redis] HTTP-only mode — no direct Redis connection');
|
||||||
return;
|
return;
|
||||||
@@ -438,6 +453,22 @@ export class RedisKVClient implements IKVClient {
|
|||||||
await this.redis.sadd(this.buildKey('file:__index__'), hashId);
|
await this.redis.sadd(this.buildKey('file:__index__'), hashId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Pass `GET /api/meta/{cid}/claims` through to meta-core (plugin relay). */
|
||||||
|
async fetchClaims(cid: string, search: string): Promise<{ status: number; body: unknown }> {
|
||||||
|
if (!this.writer) {
|
||||||
|
return { status: 503, body: { error: 'meta-core API not configured' } };
|
||||||
|
}
|
||||||
|
return this.writer.fetchClaims(cid, search);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pass a signed claim batch through to meta-core (plugin relay). */
|
||||||
|
async relayClaims(body: unknown): Promise<{ status: number; body: unknown }> {
|
||||||
|
if (!this.writer) {
|
||||||
|
return { status: 503, body: { error: 'meta-core API not configured' } };
|
||||||
|
}
|
||||||
|
return this.writer.relayClaims(body);
|
||||||
|
}
|
||||||
|
|
||||||
async deleteMetadataFlat(hashId: string): Promise<number> {
|
async deleteMetadataFlat(hashId: string): Promise<number> {
|
||||||
if (this.writer) {
|
if (this.writer) {
|
||||||
return this.writer.deleteMetadataFlat(hashId);
|
return this.writer.deleteMetadataFlat(hashId);
|
||||||
@@ -474,6 +505,15 @@ export class RedisKVClient implements IKVClient {
|
|||||||
return await this.redis.smembers(indexKey);
|
return await this.redis.smembers(indexKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* File-backed roots from meta-core (GET /api/files/tuples). Only the HTTP
|
||||||
|
* writer can serve this; direct-Redis mode returns null so callers take
|
||||||
|
* their degraded path instead of sweeping every record.
|
||||||
|
*/
|
||||||
|
async getFileTuples(opts: { summary?: boolean } = {}): Promise<FileTuplesResult | null> {
|
||||||
|
return this.writer ? this.writer.getFileTuples(opts) : null;
|
||||||
|
}
|
||||||
|
|
||||||
// ========================================================================
|
// ========================================================================
|
||||||
// Pub/Sub Operations
|
// Pub/Sub Operations
|
||||||
// ========================================================================
|
// ========================================================================
|
||||||
|
|||||||
@@ -1,199 +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 type { ServiceInfo } from './IKVClient.js';
|
|
||||||
import { isNodeError } from '../types/ExtendedInterfaces.js';
|
|
||||||
|
|
||||||
interface ServiceRegistrationConfig {
|
|
||||||
/** Path to META_CORE_VOLUME (e.g., /meta-core) */
|
|
||||||
metaCorePath: string;
|
|
||||||
|
|
||||||
/** Service name */
|
|
||||||
serviceName: string;
|
|
||||||
|
|
||||||
/** Service version (optional, not used in simplified format) */
|
|
||||||
version?: 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 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));
|
|
||||||
|
|
||||||
console.log(`[ServiceRegistration] 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) {
|
|
||||||
console.error('[ServiceRegistration] 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) {
|
|
||||||
// If file was deleted, re-register
|
|
||||||
if (isNodeError(error) && error.code === 'ENOENT') {
|
|
||||||
await this.register();
|
|
||||||
} else {
|
|
||||||
console.error('[ServiceRegistration] 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);
|
|
||||||
console.log(`[ServiceRegistration] Unregistered ${this.config.serviceName}-${this.currentHostname}`);
|
|
||||||
} catch (error) {
|
|
||||||
if (!isNodeError(error) || error.code !== 'ENOENT') {
|
|
||||||
console.error('[ServiceRegistration] Failed to unregister:', error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ========================================================================
|
|
||||||
// Lifecycle
|
|
||||||
// ========================================================================
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Full startup sequence: register service and start heartbeat loop.
|
|
||||||
*/
|
|
||||||
async start(): Promise<void> {
|
|
||||||
await this.register();
|
|
||||||
this.startHeartbeat();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Full shutdown sequence
|
|
||||||
*/
|
|
||||||
async stop(): Promise<void> {
|
|
||||||
await this.unregister();
|
|
||||||
}
|
|
||||||
|
|
||||||
// ========================================================================
|
|
||||||
// Getters
|
|
||||||
// ========================================================================
|
|
||||||
|
|
||||||
getServiceFilePath(): string {
|
|
||||||
return this.serviceFilePath;
|
|
||||||
}
|
|
||||||
|
|
||||||
getServicesDir(): string {
|
|
||||||
return this.servicesDir;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -5,7 +5,8 @@
|
|||||||
* - IKVClient interface for KV storage abstraction
|
* - IKVClient interface for KV storage abstraction
|
||||||
* - RedisKVClient for Redis-based storage
|
* - RedisKVClient for Redis-based storage
|
||||||
* - LeaderClient for reading leader info from meta-core
|
* - LeaderClient for reading leader info from meta-core
|
||||||
* - ServiceRegistration for service registration (discovery is centralized in meta-core)
|
* Services announce and discover over UDP (beacon v2); there is no
|
||||||
|
* separate registration step, so no ServiceRegistration export.
|
||||||
* - KVManager for unified management of all components
|
* - KVManager for unified management of all components
|
||||||
* - MetadataUtils for flattening/reconstructing nested metadata
|
* - MetadataUtils for flattening/reconstructing nested metadata
|
||||||
*/
|
*/
|
||||||
@@ -13,6 +14,5 @@
|
|||||||
export * from './IKVClient.js';
|
export * from './IKVClient.js';
|
||||||
export * from './RedisClient.js';
|
export * from './RedisClient.js';
|
||||||
export * from './LeaderClient.js';
|
export * from './LeaderClient.js';
|
||||||
export * from './ServiceRegistration.js';
|
|
||||||
export * from './KVManager.js';
|
export * from './KVManager.js';
|
||||||
export * from './MetadataUtils.js';
|
export * from './MetadataUtils.js';
|
||||||
|
|||||||
@@ -0,0 +1,380 @@
|
|||||||
|
/**
|
||||||
|
* meta-core client: signed claim writes (MMUR2) + plain reads.
|
||||||
|
*
|
||||||
|
* MIRRORED byte-for-byte across every `metamesh-plugin-*` TypeScript plugin and
|
||||||
|
* meta-sort-core (`src/kv/meta-core-client.ts`) — guarded by
|
||||||
|
* `scripts/check-mirrors.sh`. Edit one copy, then copy it everywhere.
|
||||||
|
*
|
||||||
|
* Every write is a vote signed by THIS container's key
|
||||||
|
* (docs/implementation/metacore-claims-model.md §3, §9):
|
||||||
|
*
|
||||||
|
* bytes_to_sign = "MMUR2\n" || canonical CBOR [cid, uid, key, value, ts]
|
||||||
|
* sig = ECDSA-secp256k1(SHA-256(bytes)), compact r||s, low-S
|
||||||
|
*
|
||||||
|
* and is posted to `POST {baseUrl}/api/claims` — meta-core directly, or
|
||||||
|
* meta-sort's pass-through relay when the plugin runs under meta-sort. The
|
||||||
|
* encoding is pinned by meta-core's `internal/claim/testdata/claim-vectors.json`
|
||||||
|
* (vendored as `test/claim-vectors.json`).
|
||||||
|
*
|
||||||
|
* Key: `METAMESH_SIGNING_KEY` (64 hex chars) or `METAMESH_SIGNING_KEY_FILE`
|
||||||
|
* (read; generated and written 0600 if missing). With neither, writes are
|
||||||
|
* refused (logged, return false) — no silent throwaway identities.
|
||||||
|
*
|
||||||
|
* Fails gracefully if meta-core is unavailable: logs and returns, never throws.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import * as crypto from 'crypto';
|
||||||
|
import * as fs from 'fs';
|
||||||
|
import * as path from 'path';
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- encoding --
|
||||||
|
|
||||||
|
const DOMAIN = Buffer.from('MMUR2\n', 'utf8');
|
||||||
|
const B58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
|
||||||
|
const N = BigInt('0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141');
|
||||||
|
const HALF_N = N >> 1n;
|
||||||
|
|
||||||
|
/** A claim value: text (public), bytes (private envelope) or null (retraction). */
|
||||||
|
export type ClaimValue = string | Uint8Array | null;
|
||||||
|
|
||||||
|
export interface SignedClaim {
|
||||||
|
cid: string;
|
||||||
|
uid: string;
|
||||||
|
key: string;
|
||||||
|
value: ClaimValue;
|
||||||
|
ts: number;
|
||||||
|
sig: Uint8Array;
|
||||||
|
}
|
||||||
|
|
||||||
|
function head(major: number, n: number | bigint): Buffer {
|
||||||
|
const m = major << 5;
|
||||||
|
const v = BigInt(n);
|
||||||
|
if (v < 24n) return Buffer.from([m | Number(v)]);
|
||||||
|
if (v <= 0xffn) return Buffer.from([m | 24, Number(v)]);
|
||||||
|
if (v <= 0xffffn) {
|
||||||
|
const b = Buffer.alloc(3);
|
||||||
|
b[0] = m | 25;
|
||||||
|
b.writeUInt16BE(Number(v), 1);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
if (v <= 0xffffffffn) {
|
||||||
|
const b = Buffer.alloc(5);
|
||||||
|
b[0] = m | 26;
|
||||||
|
b.writeUInt32BE(Number(v), 1);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
const b = Buffer.alloc(9);
|
||||||
|
b[0] = m | 27;
|
||||||
|
b.writeBigUInt64BE(v, 1);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
function text(s: string): Buffer {
|
||||||
|
const raw = Buffer.from(s, 'utf8');
|
||||||
|
return Buffer.concat([head(3, raw.length), raw]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The exact bytes an MMUR2 signature covers. */
|
||||||
|
export function signedBytes(cid: string, uid: string, key: string, value: ClaimValue, ts: number): Buffer {
|
||||||
|
let v: Buffer;
|
||||||
|
if (value === null) v = Buffer.from([0xf6]);
|
||||||
|
else if (typeof value === 'string') v = text(value);
|
||||||
|
else v = Buffer.concat([head(2, value.length), Buffer.from(value)]);
|
||||||
|
return Buffer.concat([DOMAIN, head(4, 5), text(cid), text(uid), text(key), v, head(0, ts)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function base58Encode(bytes: Uint8Array): string {
|
||||||
|
let n = BigInt('0x' + (Buffer.from(bytes).toString('hex') || '0'));
|
||||||
|
let out = '';
|
||||||
|
while (n > 0n) {
|
||||||
|
out = B58[Number(n % 58n)] + out;
|
||||||
|
n /= 58n;
|
||||||
|
}
|
||||||
|
for (const b of bytes) {
|
||||||
|
if (b !== 0) break;
|
||||||
|
out = '1' + out;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function base58Decode(s: string): Buffer {
|
||||||
|
let n = 0n;
|
||||||
|
for (const ch of s) {
|
||||||
|
const i = B58.indexOf(ch);
|
||||||
|
if (i < 0) throw new Error(`invalid base58 character ${ch}`);
|
||||||
|
n = n * 58n + BigInt(i);
|
||||||
|
}
|
||||||
|
let hex = n === 0n ? '' : n.toString(16);
|
||||||
|
if (hex.length % 2) hex = '0' + hex;
|
||||||
|
let zeros = 0;
|
||||||
|
while (zeros < s.length && s[zeros] === '1') zeros++;
|
||||||
|
return Buffer.concat([Buffer.alloc(zeros), Buffer.from(hex, 'hex')]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function b64url(b: Buffer): string {
|
||||||
|
return b.toString('base64url');
|
||||||
|
}
|
||||||
|
|
||||||
|
function publicKeyFromCompressed(compressed: Buffer): crypto.KeyObject {
|
||||||
|
const full = crypto.ECDH.convertKey(compressed, 'secp256k1', undefined, undefined, 'uncompressed') as Buffer;
|
||||||
|
return crypto.createPublicKey({
|
||||||
|
key: { kty: 'EC', crv: 'secp256k1', x: b64url(full.subarray(1, 33)), y: b64url(full.subarray(33, 65)) },
|
||||||
|
format: 'jwk',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Rewrite a compact signature to its low-S form (MMUR2 refuses high-S). */
|
||||||
|
function lowS(sig: Buffer): Buffer {
|
||||||
|
const s = BigInt('0x' + sig.subarray(32).toString('hex'));
|
||||||
|
if (s <= HALF_N) return sig;
|
||||||
|
const fixed = Buffer.from((N - s).toString(16).padStart(64, '0'), 'hex');
|
||||||
|
return Buffer.concat([sig.subarray(0, 32), fixed]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True when the claim's signature is a valid low-S signature by its uid. */
|
||||||
|
export function verifyClaim(c: SignedClaim): boolean {
|
||||||
|
try {
|
||||||
|
const sig = Buffer.from(c.sig);
|
||||||
|
if (sig.length !== 64) return false;
|
||||||
|
if (BigInt('0x' + sig.subarray(32).toString('hex')) > HALF_N) return false;
|
||||||
|
if (!c.uid.startsWith('z')) return false;
|
||||||
|
const pub = base58Decode(c.uid.slice(1));
|
||||||
|
if (pub.length !== 33) return false;
|
||||||
|
return crypto.verify(
|
||||||
|
'sha256',
|
||||||
|
signedBytes(c.cid, c.uid, c.key, c.value, c.ts),
|
||||||
|
{ key: publicKeyFromCompressed(pub), dsaEncoding: 'ieee-p1363' },
|
||||||
|
sig,
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------- signer --
|
||||||
|
|
||||||
|
export class ClaimSigner {
|
||||||
|
readonly uid: string;
|
||||||
|
private readonly key: crypto.KeyObject;
|
||||||
|
private lastTs = 0;
|
||||||
|
|
||||||
|
constructor(privateKeyHex: string) {
|
||||||
|
const hex = privateKeyHex.trim().replace(/^0x/i, '');
|
||||||
|
if (!/^[0-9a-fA-F]{64}$/.test(hex)) throw new Error('signing key must be 64 hex characters');
|
||||||
|
const d = Buffer.from(hex, 'hex');
|
||||||
|
const ecdh = crypto.createECDH('secp256k1');
|
||||||
|
ecdh.setPrivateKey(d);
|
||||||
|
const full = ecdh.getPublicKey(null, 'uncompressed');
|
||||||
|
this.uid = 'z' + base58Encode(ecdh.getPublicKey(null, 'compressed'));
|
||||||
|
this.key = crypto.createPrivateKey({
|
||||||
|
key: {
|
||||||
|
kty: 'EC', crv: 'secp256k1', d: b64url(d),
|
||||||
|
x: b64url(full.subarray(1, 33)), y: b64url(full.subarray(33, 65)),
|
||||||
|
},
|
||||||
|
format: 'jwk',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Milliseconds, strictly increasing within this process (ts is the version). */
|
||||||
|
nextTs(): number {
|
||||||
|
this.lastTs = Math.max(Date.now(), this.lastTs + 1);
|
||||||
|
return this.lastTs;
|
||||||
|
}
|
||||||
|
|
||||||
|
sign(cid: string, key: string, value: ClaimValue, ts: number = this.nextTs()): SignedClaim {
|
||||||
|
const raw = crypto.sign('sha256', signedBytes(cid, this.uid, key, value, ts), {
|
||||||
|
key: this.key,
|
||||||
|
dsaEncoding: 'ieee-p1363',
|
||||||
|
});
|
||||||
|
return { cid, uid: this.uid, key, value, ts, sig: lowS(raw) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let cachedSigner: ClaimSigner | null | undefined;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The process signer from the environment, or null when no key is configured.
|
||||||
|
* Read lazily on first write; `resetSignerForTests()` forgets it.
|
||||||
|
*/
|
||||||
|
export function loadSigner(): ClaimSigner | null {
|
||||||
|
if (cachedSigner !== undefined) return cachedSigner;
|
||||||
|
const inline = process.env.METAMESH_SIGNING_KEY;
|
||||||
|
const file = process.env.METAMESH_SIGNING_KEY_FILE;
|
||||||
|
try {
|
||||||
|
if (inline) {
|
||||||
|
cachedSigner = new ClaimSigner(inline);
|
||||||
|
} else if (file) {
|
||||||
|
if (!fs.existsSync(file)) {
|
||||||
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||||
|
fs.writeFileSync(file, crypto.randomBytes(32).toString('hex') + '\n', { mode: 0o600 });
|
||||||
|
}
|
||||||
|
cachedSigner = new ClaimSigner(fs.readFileSync(file, 'utf8'));
|
||||||
|
} else {
|
||||||
|
cachedSigner = null;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.warn(`[MetaCoreClient] Signing key unusable: ${error instanceof Error ? error.message : String(error)}`);
|
||||||
|
cachedSigner = null;
|
||||||
|
}
|
||||||
|
if (cachedSigner) console.log(`[MetaCoreClient] Signing claims as ${cachedSigner.uid}`);
|
||||||
|
else console.warn('[MetaCoreClient] No METAMESH_SIGNING_KEY / METAMESH_SIGNING_KEY_FILE — metadata writes are refused');
|
||||||
|
return cachedSigner;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resetSignerForTests(): void {
|
||||||
|
cachedSigner = undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The §3.4 JSON form. */
|
||||||
|
export function claimToJSON(c: SignedClaim): Record<string, unknown> {
|
||||||
|
let value: unknown = null;
|
||||||
|
if (typeof c.value === 'string') value = c.value;
|
||||||
|
else if (c.value) value = { b64: Buffer.from(c.value).toString('base64') };
|
||||||
|
return { cid: c.cid, uid: c.uid, key: c.key, value, ts: c.ts, sig: Buffer.from(c.sig).toString('base64') };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------------------------------- client --
|
||||||
|
|
||||||
|
export class MetaCoreClient {
|
||||||
|
constructor(private baseUrl: string) {}
|
||||||
|
|
||||||
|
private async safeFetch(url: string, options: RequestInit): Promise<Response | null> {
|
||||||
|
try {
|
||||||
|
return await fetch(url, { ...options, signal: AbortSignal.timeout(10000) });
|
||||||
|
} catch (error) {
|
||||||
|
console.warn(`[MetaCoreClient] Warning: meta-core unavailable at ${this.baseUrl}: ${error instanceof Error ? error.message : String(error)}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sign and post claims about `cid`. True when every claim was accepted (or
|
||||||
|
* was already stored: `unchanged` / `stale` are not failures).
|
||||||
|
*/
|
||||||
|
async writeClaims(cid: string, values: Array<[string, ClaimValue]>): Promise<boolean> {
|
||||||
|
if (values.length === 0) return true;
|
||||||
|
const signer = loadSigner();
|
||||||
|
if (!signer) return false;
|
||||||
|
const claims = values.map(([key, value]) => claimToJSON(signer.sign(cid, key, value)));
|
||||||
|
const response = await this.safeFetch(`${this.baseUrl}/api/claims`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(claims),
|
||||||
|
});
|
||||||
|
if (!response) return false;
|
||||||
|
if (!response.ok) {
|
||||||
|
console.warn(`[MetaCoreClient] Claims for ${cid} rejected: ${response.status}`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const statuses = await response.json().catch(() => null) as Array<{ status?: string; reason?: string }> | null;
|
||||||
|
const bad = (statuses ?? []).filter((s) => s.status === 'bad_signature' || s.status === 'bad_request');
|
||||||
|
if (bad.length > 0) {
|
||||||
|
console.warn(`[MetaCoreClient] ${bad.length} claim(s) for ${cid} refused: ${bad[0].status} ${bad[0].reason ?? ''}`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One text claim. */
|
||||||
|
async setProperty(hashId: string, key: string, value: string): Promise<boolean> {
|
||||||
|
return this.writeClaims(hashId, [[key, String(value)]]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One text claim per entry, in a single batch. */
|
||||||
|
async mergeMetadata(hashId: string, metadata: Record<string, string>): Promise<boolean> {
|
||||||
|
return this.writeClaims(hashId, Object.entries(metadata).map(([k, v]) => [k, String(v)]));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retract this signer's own vote for `key`. Other signers' votes for the
|
||||||
|
* same key are untouched (there are no negative votes).
|
||||||
|
*/
|
||||||
|
async deleteProperty(hashId: string, key: string): Promise<boolean> {
|
||||||
|
return this.writeClaims(hashId, [[key, null]]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Append a member to a legacy csv-set field (`genres`, `studio`, `tags`,
|
||||||
|
* `announceList`, …) — the comma-joined shape readers still parse (the
|
||||||
|
* METADATA_KEYS §14.12 key-set migration is out of scope for phase 1).
|
||||||
|
*
|
||||||
|
* Under claims a signer owns only its OWN vote, so this reads this
|
||||||
|
* signer's current claim for (cid, key) from
|
||||||
|
* `GET /api/meta/{cid}/claims?key=<key>` (other signers' claims are
|
||||||
|
* ignored), adds the member if absent and signs the new full value as one
|
||||||
|
* text claim. Members are kept raw (no escaping), same as the old
|
||||||
|
* meta-sort `_add` proxy. A member already present writes nothing.
|
||||||
|
*/
|
||||||
|
async addToSet(hashId: string, key: string, value: string): Promise<boolean> {
|
||||||
|
const member = String(value);
|
||||||
|
if (!member) return true;
|
||||||
|
const signer = loadSigner();
|
||||||
|
if (!signer) return false;
|
||||||
|
const current = await this.ownClaimValue(hashId, key, signer.uid);
|
||||||
|
if (current === undefined) return false; // could not read: never clobber our own set
|
||||||
|
const members = current ? current.split(',').map((v) => v.trim()).filter(Boolean) : [];
|
||||||
|
if (members.includes(member)) return true;
|
||||||
|
return this.writeClaims(hashId, [[key, [...members, member].join(',')]]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This signer's newest text claim for (cid, key): the value, `null` when it
|
||||||
|
* has none, `undefined` when the claims could not be read.
|
||||||
|
*/
|
||||||
|
private async ownClaimValue(cid: string, key: string, uid: string): Promise<string | null | undefined> {
|
||||||
|
const url = `${this.baseUrl}/api/meta/${encodeURIComponent(cid)}/claims?key=${encodeURIComponent(key)}`;
|
||||||
|
const response = await this.safeFetch(url, { method: 'GET' });
|
||||||
|
if (!response) return undefined;
|
||||||
|
if (response.status === 404) return null;
|
||||||
|
if (!response.ok) {
|
||||||
|
console.warn(`[MetaCoreClient] Failed to read claims for ${cid}/${key}: ${response.status}`);
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
const body = await response.json().catch(() => null) as unknown;
|
||||||
|
const list = (Array.isArray(body) ? body : (body as { claims?: unknown })?.claims) as
|
||||||
|
Array<{ uid?: string; key?: string; value?: unknown; ts?: number }> | undefined;
|
||||||
|
let best: { value: string; ts: number } | null = null;
|
||||||
|
for (const c of Array.isArray(list) ? list : []) {
|
||||||
|
if (c.uid !== uid || c.key !== key || typeof c.value !== 'string') continue;
|
||||||
|
const ts = Number(c.ts) || 0;
|
||||||
|
if (!best || ts > best.ts) best = { value: c.value, ts };
|
||||||
|
}
|
||||||
|
return best ? best.value : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async getProperty(hashId: string, key: string): Promise<string | null> {
|
||||||
|
const response = await this.safeFetch(`${this.baseUrl}/meta/${hashId}/${key}`, { method: 'GET' });
|
||||||
|
if (!response || !response.ok) return null;
|
||||||
|
const data = await response.json() as { value?: unknown };
|
||||||
|
return data.value === undefined || data.value === null ? null : String(data.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whole merged record, in whatever form the endpoint serves (meta-sort's
|
||||||
|
* /meta is nested, meta-core's is flat) — callers flatten. `null` when the
|
||||||
|
* call itself failed, `{}` when the record does not exist.
|
||||||
|
*/
|
||||||
|
async getMetadata(hashId: string): Promise<Record<string, unknown> | null> {
|
||||||
|
const response = await this.safeFetch(`${this.baseUrl}/meta/${hashId}`, { method: 'GET' });
|
||||||
|
if (!response) return null;
|
||||||
|
if (response.status === 404) return {};
|
||||||
|
if (!response.ok) return null;
|
||||||
|
const data = await response.json() as { metadata?: Record<string, unknown> };
|
||||||
|
return data.metadata ?? {};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compute the CID of a file under FILES_PATH via meta-core's `POST /file/cid`.
|
||||||
|
* @param filePath - path relative to FILES_PATH (e.g. "poster/Movie (2024)_poster.jpg")
|
||||||
|
*/
|
||||||
|
async computeFileCID(filePath: string): Promise<string | null> {
|
||||||
|
const response = await this.safeFetch(`${this.baseUrl}/file/cid`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ path: filePath }),
|
||||||
|
});
|
||||||
|
if (!response || !response.ok) return null;
|
||||||
|
const data = await response.json().catch(() => null) as { cid?: string } | null;
|
||||||
|
return data?.cid ?? null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -85,13 +85,10 @@ export class JellyfinFormatHandler implements IMetadataFormatHandler {
|
|||||||
if (metadata.originalTitle) jellyfinFields.originalTitle = metadata.originalTitle;
|
if (metadata.originalTitle) jellyfinFields.originalTitle = metadata.originalTitle;
|
||||||
if (metadata.movieYear) jellyfinFields.year = metadata.movieYear;
|
if (metadata.movieYear) jellyfinFields.year = metadata.movieYear;
|
||||||
|
|
||||||
// Titles (first title or original title)
|
// Title: the display name. `titles/*` is an unordered name set with no
|
||||||
if (metadata.titles) {
|
// preferred member, so it is never the NFO title (METADATA_KEYS.md §3).
|
||||||
const titleEntries = Object.entries(metadata.titles);
|
const title = metadata.title || metadata.originalTitle;
|
||||||
if (titleEntries.length > 0) {
|
if (title) jellyfinFields.title = title;
|
||||||
jellyfinFields.title = titleEntries[0][1];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// IDs
|
// IDs
|
||||||
if (metadata.imdbid) jellyfinFields.imdbid = metadata.imdbid;
|
if (metadata.imdbid) jellyfinFields.imdbid = metadata.imdbid;
|
||||||
|
|||||||
@@ -195,6 +195,16 @@ export class UnifiedProcessingStateManager {
|
|||||||
performanceMetrics.recordHashProcessing(hashProcessingTime);
|
performanceMetrics.recordHashProcessing(hashProcessingTime);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// File-level metric, one per file that finished cleanly. Nothing recorded
|
||||||
|
// it before, so the monitor's "Processed" tile stayed at 0. Files announced
|
||||||
|
// over SSE are never marked discovered, so fall back to the light phase.
|
||||||
|
if (!error) {
|
||||||
|
const fileTime = totalProcessingTime
|
||||||
|
?? (hashState?.lightProcessingStartedAt !== undefined ? now - hashState.lightProcessingStartedAt : hashProcessingTime)
|
||||||
|
?? 0;
|
||||||
|
performanceMetrics.recordFileProcessing(filePath, fileTime);
|
||||||
|
}
|
||||||
|
|
||||||
const doneState: UnifiedFileState = {
|
const doneState: UnifiedFileState = {
|
||||||
filePath,
|
filePath,
|
||||||
state: 'done',
|
state: 'done',
|
||||||
|
|||||||
@@ -631,20 +631,11 @@ export class FileProcessorPiscina implements FileAnalyzerInterface{
|
|||||||
const metadata = this.database.get(filePath);
|
const metadata = this.database.get(filePath);
|
||||||
this.database.delete(filePath);
|
this.database.delete(filePath);
|
||||||
|
|
||||||
// Delete from KV if configured (using nested key architecture)
|
// Nothing to delete in meta-core: since the claims model a record
|
||||||
if (this.kvClient && metadata) {
|
// describes content and its votes outlive this copy of the file.
|
||||||
try {
|
// meta-core's own watcher drops the file's `local_file` row.
|
||||||
const hashId = metadata.hashId;
|
if (metadata?.hashId) {
|
||||||
|
console.log(`File removed: ${filePath} (/file/${metadata.hashId} kept — records outlive files)`);
|
||||||
// Delete all properties for this file using nested key architecture
|
|
||||||
if (hashId) {
|
|
||||||
const deletedCount = await this.kvClient.deleteMetadataFlat(hashId);
|
|
||||||
console.log(`Metadata deleted from KV: /file/${hashId} (${deletedCount} keys)`);
|
|
||||||
}
|
|
||||||
} catch (metaError) {
|
|
||||||
// Log error but don't fail the entire process
|
|
||||||
console.error(`Failed to delete metadata from KV:`, metaError);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -220,6 +220,17 @@ export class PluginManager extends EventEmitter {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Forget container-backed plugins that are gone (an external plugin
|
||||||
|
// removed from the Plugins page); they have no local dir.
|
||||||
|
const present = new Set(status.plugins.map((p) => p.pluginId));
|
||||||
|
for (const [id, loaded] of this.loadedPlugins) {
|
||||||
|
if (loaded.pluginDir === '' && !present.has(id)) {
|
||||||
|
this.loadedPlugins.delete(id);
|
||||||
|
this.manifests.delete(id);
|
||||||
|
this.activePluginIds.delete(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Load state for plugin active status
|
// Load state for plugin active status
|
||||||
const state = await this.loadState();
|
const state = await this.loadState();
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
|
|
||||||
import type { HashMeta } from '@metazla/meta-interface';
|
import type { HashMeta } from '@metazla/meta-interface';
|
||||||
import type { IKVClient } from '../kv/IKVClient.js';
|
import type { IKVClient } from '../kv/IKVClient.js';
|
||||||
|
import type { FileTuplesResult } from '../kv/MetaCoreApiWriter.js';
|
||||||
import type { FileAnalyzerInterface } from '../logic/fileProcessor/FileAnalyzerInterface.js';
|
import type { FileAnalyzerInterface } from '../logic/fileProcessor/FileAnalyzerInterface.js';
|
||||||
import type { ContainerTask } from '../container-plugins/types.js';
|
import type { ContainerTask } from '../container-plugins/types.js';
|
||||||
import type { UnifiedProcessingSnapshot } from '../logic/UnifiedProcessingStateManager.js';
|
import type { UnifiedProcessingSnapshot } from '../logic/UnifiedProcessingStateManager.js';
|
||||||
@@ -41,6 +42,21 @@ export function hasPublish(client: IKVClient): client is IKVClientWithPubSub {
|
|||||||
return typeof (client as IKVClientWithPubSub).publish === 'function';
|
return typeof (client as IKVClientWithPubSub).publish === 'function';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* IKVClient that can list meta-core's file-backed roots in one call
|
||||||
|
* (GET /api/files/tuples). Resolves null when meta-core predates the endpoint.
|
||||||
|
*/
|
||||||
|
export interface IKVClientWithFileTuples extends IKVClient {
|
||||||
|
getFileTuples(opts?: { summary?: boolean }): Promise<FileTuplesResult | null>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Type guard to check if a KVClient can list file-backed roots
|
||||||
|
*/
|
||||||
|
export function hasFileTuples(client: IKVClient): client is IKVClientWithFileTuples {
|
||||||
|
return typeof (client as IKVClientWithFileTuples).getFileTuples === 'function';
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* IKVClient with Redis Streams capabilities
|
* IKVClient with Redis Streams capabilities
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ export interface FileMetadata {
|
|||||||
|
|
||||||
// Filename parsing
|
// Filename parsing
|
||||||
title?: string;
|
title?: string;
|
||||||
titles?: string[];
|
titles?: Record<string, Record<string, true | string>>; // key-set: lang3 → {name: "true"}
|
||||||
originaltitle?: string;
|
originaltitle?: string;
|
||||||
showtitle?: string;
|
showtitle?: string;
|
||||||
season?: number;
|
season?: number;
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import { useEffect, useRef } from 'react';
|
||||||
|
import '../meta-beacon-scan.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The Plugins page's beacon v2 Scan card: enrichment plugins advertising on
|
||||||
|
* the network (`metamesh.enrich/<id>`, typically MetaPlugin* store apps), with
|
||||||
|
* an Add per new one. A thin wrapper around the framework-free
|
||||||
|
* <meta-beacon-scan> element shared with meta-share and meta-gateway; the
|
||||||
|
* --mm-scan-* tokens map this dashboard's palette onto it.
|
||||||
|
*
|
||||||
|
* Add registers the plugin as an EXTERNAL plugin (POST /api/plugins/external):
|
||||||
|
* meta-sort calls it by URL and never starts or stops it.
|
||||||
|
*/
|
||||||
|
|
||||||
|
declare global {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-namespace
|
||||||
|
namespace JSX {
|
||||||
|
interface IntrinsicElements {
|
||||||
|
'meta-beacon-scan': React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement> & {
|
||||||
|
'scan-endpoint'?: string;
|
||||||
|
'add-endpoint'?: string;
|
||||||
|
'add-extra'?: string;
|
||||||
|
label?: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const TOKENS = {
|
||||||
|
display: 'block',
|
||||||
|
'--mm-scan-fg': 'var(--text-primary)',
|
||||||
|
'--mm-scan-bg': 'var(--bg-secondary)',
|
||||||
|
'--mm-scan-border': 'var(--border-color)',
|
||||||
|
'--mm-scan-accent': 'var(--accent-primary)',
|
||||||
|
'--mm-scan-err': 'var(--accent-secondary)',
|
||||||
|
} as React.CSSProperties;
|
||||||
|
|
||||||
|
function BeaconScanCard({ onAdded }: { onAdded: () => void }) {
|
||||||
|
const ref = useRef<HTMLElement>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const el = ref.current;
|
||||||
|
if (!el) return;
|
||||||
|
const handler = () => onAdded();
|
||||||
|
el.addEventListener('beacon-added', handler);
|
||||||
|
return () => el.removeEventListener('beacon-added', handler);
|
||||||
|
}, [onAdded]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<meta-beacon-scan
|
||||||
|
ref={ref}
|
||||||
|
style={TOKENS}
|
||||||
|
scan-endpoint="/api/plugins/discover"
|
||||||
|
add-endpoint="/api/plugins/external"
|
||||||
|
label="enrichment plugins"
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default BeaconScanCard;
|
||||||
@@ -1,165 +1,54 @@
|
|||||||
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[]>([]);
|
useEffect(() => {
|
||||||
const [loading, setLoading] = useState(true);
|
// Import above is for the side effect of defining the element; this
|
||||||
const currentService = 'meta-sort';
|
// keeps bundlers from tree-shaking it away in production builds.
|
||||||
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
return (
|
||||||
const fetchServices = async () => {
|
<>
|
||||||
try {
|
<meta-service-menu current="meta-sort" />
|
||||||
const response = await fetch('/api/services');
|
<style>{`
|
||||||
if (response.ok) {
|
meta-service-menu {
|
||||||
const data: ServicesResponse = await response.json();
|
--mm-nav-fg: var(--text-primary, #e0e0e0);
|
||||||
setServices(data.services || []);
|
--mm-nav-bg: var(--bg-tertiary, var(--bg-secondary, #1a1a2e));
|
||||||
}
|
--mm-nav-border: var(--border-color, rgba(255,255,255,0.14));
|
||||||
} catch (error) {
|
--mm-nav-accent: var(--accent-primary, #4ecdc4);
|
||||||
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 (
|
|
||||||
<nav className="services-nav">
|
|
||||||
<span className="services-nav-label">Services:</span>
|
|
||||||
<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;
|
|
||||||
}
|
}
|
||||||
}}
|
`}</style>
|
||||||
>
|
</>
|
||||||
<span className="service-icon">{icon}</span>
|
);
|
||||||
<span>{formatServiceName(service.name)}</span>
|
|
||||||
<span className="service-status"></span>
|
|
||||||
</a>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<style>{`
|
|
||||||
.services-nav {
|
|
||||||
background: var(--bg-secondary);
|
|
||||||
border-radius: 12px;
|
|
||||||
padding: 0.5rem;
|
|
||||||
margin-bottom: 1.5rem;
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 0.5rem;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
border: 1px solid var(--border-color);
|
|
||||||
}
|
|
||||||
|
|
||||||
.services-nav-label {
|
|
||||||
color: var(--text-secondary);
|
|
||||||
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);
|
|
||||||
background: var(--bg-tertiary);
|
|
||||||
border: 1px solid var(--border-color);
|
|
||||||
}
|
|
||||||
|
|
||||||
.service-link:hover {
|
|
||||||
background: var(--border-color);
|
|
||||||
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);
|
|
||||||
margin-left: 0.25rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 600px) {
|
|
||||||
.services-nav {
|
|
||||||
flex-direction: column;
|
|
||||||
align-items: flex-start;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
`}</style>
|
|
||||||
</nav>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export default ServiceNav;
|
export default ServiceNav;
|
||||||
|
|||||||
@@ -0,0 +1,277 @@
|
|||||||
|
/**
|
||||||
|
* <meta-beacon-scan> — "what plugins are on the network?", as a card.
|
||||||
|
*
|
||||||
|
* The Scan button POSTs to the host's own discover endpoint, which probes the
|
||||||
|
* beacon v2 group (239.255.99.1:9099), waits for the replies, and classifies
|
||||||
|
* every resource matching the host's capability (transport plugins for
|
||||||
|
* meta-share, feeders for meta-gateway, enrichment plugins for meta-sort):
|
||||||
|
*
|
||||||
|
* 10 nodes on the network · 3 transport plugins · 3 already configured
|
||||||
|
*
|
||||||
|
* Each `addable` row gets an Add button that POSTs {name, url} to the host's
|
||||||
|
* existing add endpoint. Response shape: meta-feeder-sdk `beacon::ScanReport`
|
||||||
|
* (docs/project-architecture/beacon-v2.md).
|
||||||
|
*
|
||||||
|
* ⚠ MIRRORED FILE. Byte-identical copies live in meta-share, meta-gateway and
|
||||||
|
* meta-sort-ui; see `scripts/check-mirrors.sh`. Edit one → edit all.
|
||||||
|
*
|
||||||
|
* Shadow DOM for the same reason as <meta-service-menu>: the three hosts use
|
||||||
|
* incompatible token vocabularies. Style it from the host with
|
||||||
|
* --mm-scan-fg, --mm-scan-bg, --mm-scan-border, --mm-scan-accent,
|
||||||
|
* --mm-scan-ok, --mm-scan-err
|
||||||
|
*
|
||||||
|
* Attributes:
|
||||||
|
* scan-endpoint POST → ScanReport (required)
|
||||||
|
* add-endpoint POST {name, url, ...add-extra} (required)
|
||||||
|
* add-extra JSON object merged into the add body (optional)
|
||||||
|
* label what the host calls a capable resource, plural
|
||||||
|
* (default "plugins")
|
||||||
|
*
|
||||||
|
* Events (bubbling, composed):
|
||||||
|
* beacon-added detail = { candidate, response }, after a successful Add
|
||||||
|
*/
|
||||||
|
|
||||||
|
const STATE_TEXT = {
|
||||||
|
addable: "new",
|
||||||
|
configured: "configured",
|
||||||
|
"bound-elsewhere": "bound elsewhere",
|
||||||
|
};
|
||||||
|
|
||||||
|
const TEMPLATE = `
|
||||||
|
<style>
|
||||||
|
:host {
|
||||||
|
--_fg: var(--mm-scan-fg, #e8eaed);
|
||||||
|
--_bg: var(--mm-scan-bg, transparent);
|
||||||
|
--_border: var(--mm-scan-border, rgba(255, 255, 255, 0.14));
|
||||||
|
--_accent: var(--mm-scan-accent, #4ecdc4);
|
||||||
|
--_ok: var(--mm-scan-ok, #3fb950);
|
||||||
|
--_err: var(--mm-scan-err, #f85149);
|
||||||
|
display: block;
|
||||||
|
color: var(--_fg);
|
||||||
|
font-family: inherit;
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 1.4;
|
||||||
|
}
|
||||||
|
.card {
|
||||||
|
background: var(--_bg);
|
||||||
|
border: 1px solid var(--_border);
|
||||||
|
border-radius: 10px;
|
||||||
|
padding: 0.9rem 1rem;
|
||||||
|
}
|
||||||
|
.head { display: flex; align-items: center; gap: 0.75rem; flex-wrap: wrap; }
|
||||||
|
.title { font-weight: 600; }
|
||||||
|
.hint { opacity: 0.7; font-size: 0.85em; }
|
||||||
|
.spacer { flex: 1; }
|
||||||
|
button {
|
||||||
|
font: inherit;
|
||||||
|
font-size: 0.85em;
|
||||||
|
cursor: pointer;
|
||||||
|
color: var(--_fg);
|
||||||
|
background: transparent;
|
||||||
|
border: 1px solid var(--_border);
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 0.3rem 0.8rem;
|
||||||
|
}
|
||||||
|
button:hover:not(:disabled) { border-color: var(--_accent); color: var(--_accent); }
|
||||||
|
button:disabled { opacity: 0.5; cursor: progress; }
|
||||||
|
button.add { border-color: var(--_accent); color: var(--_accent); }
|
||||||
|
.summary { margin-top: 0.6rem; font-size: 0.9em; }
|
||||||
|
.summary b { color: var(--_accent); }
|
||||||
|
.error { margin-top: 0.6rem; color: var(--_err); font-size: 0.85em; }
|
||||||
|
ul { list-style: none; margin: 0.6rem 0 0; padding: 0; }
|
||||||
|
li {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(0, 1fr) auto;
|
||||||
|
gap: 0.2rem 0.75rem;
|
||||||
|
align-items: center;
|
||||||
|
padding: 0.5rem 0;
|
||||||
|
border-top: 1px solid var(--_border);
|
||||||
|
}
|
||||||
|
.who { display: flex; gap: 0.5rem; align-items: baseline; flex-wrap: wrap; min-width: 0; }
|
||||||
|
.name { font-weight: 600; }
|
||||||
|
.muted { opacity: 0.65; font-size: 0.85em; }
|
||||||
|
code { font-size: 0.8em; opacity: 0.8; overflow-wrap: anywhere; }
|
||||||
|
.chips { display: inline-flex; gap: 0.3rem; flex-wrap: wrap; }
|
||||||
|
.chip {
|
||||||
|
font-size: 0.72em;
|
||||||
|
padding: 0 0.4rem;
|
||||||
|
border-radius: 3px;
|
||||||
|
border: 1px solid var(--_border);
|
||||||
|
opacity: 0.85;
|
||||||
|
}
|
||||||
|
.state { font-size: 0.75em; padding: 0.05rem 0.45rem; border-radius: 999px; border: 1px solid currentColor; }
|
||||||
|
.state.addable { color: var(--_accent); }
|
||||||
|
.state.configured { color: var(--_ok); }
|
||||||
|
.state.bound-elsewhere { opacity: 0.6; }
|
||||||
|
.row-actions { display: flex; gap: 0.5rem; align-items: center; grid-row: span 2; }
|
||||||
|
.row-err { color: var(--_err); font-size: 0.8em; }
|
||||||
|
</style>
|
||||||
|
<div class="card">
|
||||||
|
<div class="head">
|
||||||
|
<span class="title">Beacon discovery</span>
|
||||||
|
<span class="hint">plugins advertising themselves on this network</span>
|
||||||
|
<span class="spacer"></span>
|
||||||
|
<button class="scan" type="button">Scan</button>
|
||||||
|
</div>
|
||||||
|
<div class="summary" hidden></div>
|
||||||
|
<div class="error" hidden></div>
|
||||||
|
<ul></ul>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
function h(tag, cls, text) {
|
||||||
|
const n = document.createElement(tag);
|
||||||
|
if (cls) n.className = cls;
|
||||||
|
if (text != null) n.textContent = text;
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function readError(res) {
|
||||||
|
const body = await res.text().catch(() => "");
|
||||||
|
try {
|
||||||
|
const j = JSON.parse(body);
|
||||||
|
return j.error || j.message || body || `HTTP ${res.status}`;
|
||||||
|
} catch {
|
||||||
|
return body || `HTTP ${res.status}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class MetaBeaconScan extends HTMLElement {
|
||||||
|
constructor() {
|
||||||
|
super();
|
||||||
|
this.attachShadow({ mode: "open" });
|
||||||
|
this.shadowRoot.innerHTML = TEMPLATE;
|
||||||
|
this._scanBtn = this.shadowRoot.querySelector("button.scan");
|
||||||
|
this._summary = this.shadowRoot.querySelector(".summary");
|
||||||
|
this._error = this.shadowRoot.querySelector(".error");
|
||||||
|
this._list = this.shadowRoot.querySelector("ul");
|
||||||
|
this._busy = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
connectedCallback() {
|
||||||
|
if (this._wired) return;
|
||||||
|
this._wired = true;
|
||||||
|
this._scanBtn.addEventListener("click", () => this.scan());
|
||||||
|
}
|
||||||
|
|
||||||
|
get label() {
|
||||||
|
return this.getAttribute("label") || "plugins";
|
||||||
|
}
|
||||||
|
|
||||||
|
async scan() {
|
||||||
|
const endpoint = this.getAttribute("scan-endpoint");
|
||||||
|
if (!endpoint || this._busy) return;
|
||||||
|
this._busy = true;
|
||||||
|
this._scanBtn.disabled = true;
|
||||||
|
this._scanBtn.textContent = "Scanning…";
|
||||||
|
this._error.hidden = true;
|
||||||
|
try {
|
||||||
|
const res = await fetch(endpoint, { method: "POST", headers: { Accept: "application/json" } });
|
||||||
|
if (!res.ok) throw new Error(await readError(res));
|
||||||
|
this._render(await res.json());
|
||||||
|
} catch (e) {
|
||||||
|
// Keep the last result visible; just say what went wrong.
|
||||||
|
this._error.textContent = `Scan failed: ${e.message}`;
|
||||||
|
this._error.hidden = false;
|
||||||
|
} finally {
|
||||||
|
this._busy = false;
|
||||||
|
this._scanBtn.disabled = false;
|
||||||
|
this._scanBtn.textContent = "Scan again";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_render(report) {
|
||||||
|
const s = report.summary || {};
|
||||||
|
this._summary.replaceChildren();
|
||||||
|
const part = (n, text) => {
|
||||||
|
const span = h("span");
|
||||||
|
span.append(h("b", null, String(n ?? 0)), ` ${text}`);
|
||||||
|
return span;
|
||||||
|
};
|
||||||
|
const parts = [
|
||||||
|
part(s.nodes, s.nodes === 1 ? "node on the network" : "nodes on the network"),
|
||||||
|
part(s.capable, this.label),
|
||||||
|
part(s.configured, "already configured"),
|
||||||
|
part(s.addable, "new"),
|
||||||
|
];
|
||||||
|
if (s.boundElsewhere) parts.push(part(s.boundElsewhere, "bound to another consumer"));
|
||||||
|
parts.forEach((p, i) => {
|
||||||
|
if (i) this._summary.append(" · ");
|
||||||
|
this._summary.append(p);
|
||||||
|
});
|
||||||
|
this._summary.hidden = false;
|
||||||
|
|
||||||
|
this._list.replaceChildren(...(report.candidates || []).map((c) => this._row(c)));
|
||||||
|
}
|
||||||
|
|
||||||
|
_row(c) {
|
||||||
|
const li = h("li");
|
||||||
|
const who = h("div", "who");
|
||||||
|
who.append(h("span", "name", c.instance));
|
||||||
|
if (c.name && c.name !== c.instance) who.append(h("span", "muted", c.name));
|
||||||
|
if (c.version) who.append(h("span", "muted", `v${c.version}`));
|
||||||
|
const chips = h("span", "chips");
|
||||||
|
for (const cap of c.caps || []) chips.append(h("span", "chip", cap));
|
||||||
|
who.append(chips);
|
||||||
|
|
||||||
|
const actions = h("div", "row-actions");
|
||||||
|
const state = h("span", `state ${c.state}`, STATE_TEXT[c.state] || c.state);
|
||||||
|
if (c.state === "configured" && c.configuredAs) state.title = `listed as "${c.configuredAs}"`;
|
||||||
|
if (c.state === "bound-elsewhere" && c.binds) state.title = `belongs to ${c.binds}`;
|
||||||
|
actions.append(state);
|
||||||
|
if (c.state === "addable") {
|
||||||
|
const add = h("button", "add", "Add");
|
||||||
|
add.type = "button";
|
||||||
|
add.addEventListener("click", () => this._add(c, add, li));
|
||||||
|
actions.append(add);
|
||||||
|
}
|
||||||
|
|
||||||
|
const where = h("div");
|
||||||
|
where.append(h("code", null, c.url));
|
||||||
|
li.append(who, actions, where);
|
||||||
|
return li;
|
||||||
|
}
|
||||||
|
|
||||||
|
async _add(candidate, btn, li) {
|
||||||
|
const endpoint = this.getAttribute("add-endpoint");
|
||||||
|
if (!endpoint) return;
|
||||||
|
let extra = {};
|
||||||
|
try {
|
||||||
|
extra = JSON.parse(this.getAttribute("add-extra") || "{}");
|
||||||
|
} catch {
|
||||||
|
/* a malformed attribute must not block the add */
|
||||||
|
}
|
||||||
|
btn.disabled = true;
|
||||||
|
btn.textContent = "Adding…";
|
||||||
|
li.querySelector(".row-err")?.remove();
|
||||||
|
try {
|
||||||
|
const res = await fetch(endpoint, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
||||||
|
body: JSON.stringify({ ...extra, name: candidate.suggestedName, url: candidate.url }),
|
||||||
|
});
|
||||||
|
if (!res.ok) throw new Error(await readError(res));
|
||||||
|
const text = await res.text();
|
||||||
|
let response = null;
|
||||||
|
try {
|
||||||
|
response = text ? JSON.parse(text) : null;
|
||||||
|
} catch {
|
||||||
|
response = text;
|
||||||
|
}
|
||||||
|
this.dispatchEvent(
|
||||||
|
new CustomEvent("beacon-added", { bubbles: true, composed: true, detail: { candidate, response } }),
|
||||||
|
);
|
||||||
|
btn.textContent = "Added";
|
||||||
|
} catch (e) {
|
||||||
|
btn.disabled = false;
|
||||||
|
btn.textContent = "Add";
|
||||||
|
li.append(h("div", "row-err", e.message));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!customElements.get("meta-beacon-scan")) {
|
||||||
|
customElements.define("meta-beacon-scan", MetaBeaconScan);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default MetaBeaconScan;
|
||||||
@@ -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;
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useState, useEffect, useCallback } from 'react';
|
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||||
import {
|
import {
|
||||||
ProcessingStatus,
|
ProcessingStatus,
|
||||||
Metrics,
|
Metrics,
|
||||||
@@ -60,29 +60,35 @@ function Monitor() {
|
|||||||
const [failedFiles, setFailedFiles] = useState<FailedFile[]>([]);
|
const [failedFiles, setFailedFiles] = useState<FailedFile[]>([]);
|
||||||
const [showPipelineHelp, setShowPipelineHelp] = useState(false);
|
const [showPipelineHelp, setShowPipelineHelp] = useState(false);
|
||||||
|
|
||||||
const fetchData = useCallback(async () => {
|
// Each endpoint renders as soon as it answers, so one slow or failing call
|
||||||
try {
|
// cannot blank the page. A tick is skipped while the previous one is still
|
||||||
const [statusRes, metricsRes, queueRes, statsRes, failedRes] = await Promise.all([
|
// out, so a slow backend never collects a pile of overlapping polls.
|
||||||
fetch('/api/processing/status'),
|
const pollInFlight = useRef(false);
|
||||||
fetch('/api/metrics'),
|
|
||||||
fetch('/api/processing/queue'),
|
|
||||||
fetch('/api/stats'),
|
|
||||||
fetch('/api/processing/failed')
|
|
||||||
]);
|
|
||||||
|
|
||||||
if (statusRes.ok) setStatus(await statusRes.json());
|
const fetchData = useCallback(async () => {
|
||||||
if (metricsRes.ok) setMetrics(await metricsRes.json());
|
if (pollInFlight.current) return;
|
||||||
if (queueRes.ok) {
|
pollInFlight.current = true;
|
||||||
const queueData = await queueRes.json();
|
|
||||||
setQueue(queueData.items || []);
|
const load = async <T,>(url: string, apply: (data: T) => void) => {
|
||||||
|
const res = await fetch(url);
|
||||||
|
if (res.ok) apply(await res.json());
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const results = await Promise.allSettled([
|
||||||
|
load<ProcessingStatus>('/api/processing/status', setStatus),
|
||||||
|
load<Metrics>('/api/metrics', setMetrics),
|
||||||
|
load<{ items?: QueueItem[] }>('/api/processing/queue', (data) => setQueue(data.items || [])),
|
||||||
|
load<RedisStats>('/api/stats', setRedisStats),
|
||||||
|
load<{ failedFiles?: FailedFile[] }>('/api/processing/failed', (data) => setFailedFiles(data.failedFiles || [])),
|
||||||
|
]);
|
||||||
|
for (const result of results) {
|
||||||
|
if (result.status === 'rejected') {
|
||||||
|
console.error('Failed to fetch data:', result.reason);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (statsRes.ok) setRedisStats(await statsRes.json());
|
} finally {
|
||||||
if (failedRes.ok) {
|
pollInFlight.current = false;
|
||||||
const failedData = await failedRes.json();
|
|
||||||
setFailedFiles(failedData.failedFiles || []);
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Failed to fetch data:', err);
|
|
||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
@@ -410,7 +416,7 @@ function Monitor() {
|
|||||||
<h3 className="section-title">File Coverage</h3>
|
<h3 className="section-title">File Coverage</h3>
|
||||||
<div className="stats-grid">
|
<div className="stats-grid">
|
||||||
<div className="stat-box">
|
<div className="stat-box">
|
||||||
<div className="stat-value">{status?.uniqueHashes ? formatNumber(status.uniqueHashes) : (redisStats ? formatNumber(redisStats.fileCount) : '-')}</div>
|
<div className="stat-value">{status?.uniqueHashes ? formatNumber(status.uniqueHashes) : (redisStats?.fileCount != null ? formatNumber(redisStats.fileCount) : '-')}</div>
|
||||||
<div className="stat-label">Unique Files</div>
|
<div className="stat-label">Unique Files</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="stat-box">
|
<div className="stat-box">
|
||||||
@@ -432,7 +438,7 @@ function Monitor() {
|
|||||||
<div className="card total-size-card">
|
<div className="card total-size-card">
|
||||||
<h2>Total Size</h2>
|
<h2>Total Size</h2>
|
||||||
<div className="total-size-value">
|
<div className="total-size-value">
|
||||||
{redisStats ? formatBytes(redisStats.totalSize) : '-'}
|
{redisStats?.totalSize != null ? formatBytes(redisStats.totalSize) : '-'}
|
||||||
</div>
|
</div>
|
||||||
<div className="total-size-label">Watch Folders</div>
|
<div className="total-size-label">Watch Folders</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import {
|
|||||||
PluginTimingsResponse
|
PluginTimingsResponse
|
||||||
} from '../types';
|
} from '../types';
|
||||||
import { formatMs, formatNumber } from '../utils/format';
|
import { formatMs, formatNumber } from '../utils/format';
|
||||||
|
import BeaconScanCard from '../components/BeaconScanCard';
|
||||||
|
|
||||||
interface AddPluginForm {
|
interface AddPluginForm {
|
||||||
pluginId: string;
|
pluginId: string;
|
||||||
@@ -33,6 +34,8 @@ function Plugins() {
|
|||||||
cpus: '0.5',
|
cpus: '0.5',
|
||||||
});
|
});
|
||||||
const [restartAllStatus, setRestartAllStatus] = useState<string | null>(null);
|
const [restartAllStatus, setRestartAllStatus] = useState<string | null>(null);
|
||||||
|
// Plugins meta-sort reaches by URL but did not spawn (added from the Scan card).
|
||||||
|
const [externalUrls, setExternalUrls] = useState<Record<string, string>>({});
|
||||||
|
|
||||||
const fetchPlugins = useCallback(async () => {
|
const fetchPlugins = useCallback(async () => {
|
||||||
try {
|
try {
|
||||||
@@ -41,6 +44,14 @@ function Plugins() {
|
|||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
setPluginsData(data);
|
setPluginsData(data);
|
||||||
setError(null);
|
setError(null);
|
||||||
|
fetch('/api/plugins/containers')
|
||||||
|
.then((r) => (r.ok ? r.json() : null))
|
||||||
|
.then((c: { plugins?: Array<{ id: string; kind?: string; url?: string }> } | null) => {
|
||||||
|
const map: Record<string, string> = {};
|
||||||
|
for (const p of c?.plugins ?? []) if (p.kind === 'external' && p.url) map[p.id] = p.url;
|
||||||
|
setExternalUrls(map);
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
} else if (res.status === 503) {
|
} else if (res.status === 503) {
|
||||||
setError('Plugin manager not yet initialized. Process a file to initialize plugins.');
|
setError('Plugin manager not yet initialized. Process a file to initialize plugins.');
|
||||||
}
|
}
|
||||||
@@ -370,6 +381,9 @@ function Plugins() {
|
|||||||
<div className="plugin-info">
|
<div className="plugin-info">
|
||||||
<span className="plugin-name">{plugin.name}</span>
|
<span className="plugin-name">{plugin.name}</span>
|
||||||
<span className="plugin-version">v{plugin.version}</span>
|
<span className="plugin-version">v{plugin.version}</span>
|
||||||
|
{externalUrls[plugin.id] && (
|
||||||
|
<span className="plugin-external" title={`external: ${externalUrls[plugin.id]}`}>external</span>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<label className="toggle" onClick={(e) => e.stopPropagation()}>
|
<label className="toggle" onClick={(e) => e.stopPropagation()}>
|
||||||
<input
|
<input
|
||||||
@@ -677,6 +691,17 @@ function Plugins() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Beacon v2: plugins advertising on the network, with Scan + Add */}
|
||||||
|
<div className="card beacon-scan-card">
|
||||||
|
<h2>Discover plugins</h2>
|
||||||
|
<p className="card-description">
|
||||||
|
Enrichment plugins installed as their own apps announce themselves on the network.
|
||||||
|
Scan to list them; Add registers one as an external plugin (meta-sort calls it by URL
|
||||||
|
and never starts or stops it). Remove it from the list like any other plugin.
|
||||||
|
</p>
|
||||||
|
<BeaconScanCard onAdded={fetchPlugins} />
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* Queue Assignment Section */}
|
{/* Queue Assignment Section */}
|
||||||
{pluginsData && pluginsData.activeCount > 0 && (
|
{pluginsData && pluginsData.activeCount > 0 && (
|
||||||
<div className="card queue-assignment-card">
|
<div className="card queue-assignment-card">
|
||||||
@@ -920,6 +945,14 @@ function Plugins() {
|
|||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.plugin-external {
|
||||||
|
margin-left: 0.5rem;
|
||||||
|
font-size: 0.7rem;
|
||||||
|
padding: 0 0.4rem;
|
||||||
|
border-radius: 3px;
|
||||||
|
border: 1px dashed var(--accent-primary);
|
||||||
|
color: var(--accent-primary);
|
||||||
|
}
|
||||||
.plugin-item {
|
.plugin-item {
|
||||||
background: var(--bg-tertiary);
|
background: var(--bg-tertiary);
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
|
|||||||
@@ -184,12 +184,12 @@ export interface Metrics {
|
|||||||
|
|
||||||
// NOTE: DuplicateGroup and DuplicateData types have been moved to meta-dup service
|
// NOTE: DuplicateGroup and DuplicateData types have been moved to meta-dup service
|
||||||
|
|
||||||
|
/** GET /api/stats: totals over meta-core's file-backed roots. */
|
||||||
export interface RedisStats {
|
export interface RedisStats {
|
||||||
fileCount: number;
|
/** null when meta-core cannot supply file totals (source 'unavailable') */
|
||||||
keyCount: number;
|
fileCount: number | null;
|
||||||
totalSize: number;
|
totalSize: number | null;
|
||||||
memoryUsage?: string;
|
source?: 'meta-core' | 'unavailable';
|
||||||
memoryUsageBytes?: number;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface QueueItem {
|
export interface QueueItem {
|
||||||
|
|||||||
@@ -1,9 +1,23 @@
|
|||||||
|
/**
|
||||||
|
* The `fileType` vocabulary — see METADATA_KEYS.md §1.
|
||||||
|
*
|
||||||
|
* ⚠ INVARIANT: a value belongs here only if an `(extension, mimeType)` lookup
|
||||||
|
* can decide it on its own. Nothing that requires knowing what the content
|
||||||
|
* *is* goes in this field — that is `contentKind`'s job — and nothing that
|
||||||
|
* decides *which app gets the record* depends on it — that is `domain`'s job
|
||||||
|
* (METADATA_KEYS.md §14.16).
|
||||||
|
*
|
||||||
|
* `card` is the one deliberate exception: it describes no bytes at all and is
|
||||||
|
* therefore never produced by the tables here, only stamped by a card feeder.
|
||||||
|
*/
|
||||||
export type SimpleFileType =
|
export type SimpleFileType =
|
||||||
'audio'
|
'audio'
|
||||||
| 'video'
|
| 'video'
|
||||||
|
| 'image'
|
||||||
| 'document'
|
| 'document'
|
||||||
| 'archive'
|
| 'archive'
|
||||||
| 'subtitle'
|
| 'subtitle'
|
||||||
| 'torrent'
|
| 'torrent'
|
||||||
|
| 'card'
|
||||||
| 'other'
|
| 'other'
|
||||||
| 'undefined';
|
| 'undefined';
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
/**
|
||||||
|
* `contentKind` → `domain` / `workForm` — the routing tables from
|
||||||
|
* METADATA_KEYS.md §1.
|
||||||
|
*
|
||||||
|
* `domain` answers "which application is this record destined for?" and is the
|
||||||
|
* key every client filters its catalogue on — **one value per app**, no
|
||||||
|
* alternation. `workForm` answers the other question the old `film`/`tv` split
|
||||||
|
* was secretly encoding: is this work complete in itself, or one instalment of
|
||||||
|
* a run? It is cross-domain, so a comic issue is `serial` in `literature`
|
||||||
|
* exactly as an episode is `serial` in `screen`.
|
||||||
|
*
|
||||||
|
* Both are **stored, not derived on read**: that is what lets the `contentKind`
|
||||||
|
* vocabulary stay open, because a peer that has never heard of a kind still
|
||||||
|
* routes the record correctly without having to interpret the token.
|
||||||
|
*
|
||||||
|
* ⚠ This binding is **permanent and one-way**. Add kinds freely; never re-map
|
||||||
|
* an existing kind to a different domain. Because the value is stored, two
|
||||||
|
* peers on different versions that disagree about where a kind belongs produce
|
||||||
|
* a split-brain that redeploying cannot heal — the wrong domain is already
|
||||||
|
* written into records across the mesh. If a kind has to move, mint a new kind.
|
||||||
|
* The `film`+`tv` → `screen` merge (METADATA_KEYS.md §14.17) is the one
|
||||||
|
* deliberate exception, taken once and paid for with a corpus sweep.
|
||||||
|
*
|
||||||
|
* ⚠ Mirror of the Rust table in `meta-feeder-sdk::domain`. Edit both together.
|
||||||
|
*/
|
||||||
|
export type Domain =
|
||||||
|
'screen'
|
||||||
|
| 'music'
|
||||||
|
| 'literature'
|
||||||
|
| 'science';
|
||||||
|
|
||||||
|
/** Is the work complete in itself, or one instalment of a run? */
|
||||||
|
export type WorkForm = 'standalone' | 'serial';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The one-way binding. A kind that is absent here has no domain, which means
|
||||||
|
* the record is **not independently routable** — correct for sidecars
|
||||||
|
* (subtitles, artwork) and for un-anchored hits, a producer bug for anything
|
||||||
|
* else.
|
||||||
|
*
|
||||||
|
* ⚠ `pack` is deliberately absent: a season pack and an album release are the
|
||||||
|
* same structural thing, so the kind alone cannot tell `screen` from `music`.
|
||||||
|
* The writer stamps `pack`'s domain from its own context — see
|
||||||
|
* {@link domainForContentKind}'s contract.
|
||||||
|
*
|
||||||
|
* ⚠ `podcast` / `podcastEpisode` are absent too: the `spoken` domain was
|
||||||
|
* retired unused, and the change that first *writes* those kinds picks their
|
||||||
|
* domain.
|
||||||
|
*/
|
||||||
|
export const domainByContentKind: { [contentKind: string]: Domain } = {
|
||||||
|
// screen — films and serials alike; the split lives in workFormByContentKind
|
||||||
|
movie: 'screen',
|
||||||
|
series: 'screen',
|
||||||
|
episode: 'screen',
|
||||||
|
// music
|
||||||
|
track: 'music',
|
||||||
|
album: 'music',
|
||||||
|
artist: 'music',
|
||||||
|
musicVideo: 'music',
|
||||||
|
djMix: 'music',
|
||||||
|
liveSet: 'music',
|
||||||
|
// literature
|
||||||
|
book: 'literature',
|
||||||
|
// An audiobook's identity is the book — same author, same ISBN family,
|
||||||
|
// same series as the ebook — so meta-read can group the two editions on
|
||||||
|
// one page. The player does not decide the domain.
|
||||||
|
audiobook: 'literature',
|
||||||
|
comic: 'literature',
|
||||||
|
manga: 'literature',
|
||||||
|
magazine: 'literature',
|
||||||
|
// science
|
||||||
|
paper: 'science',
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The `workForm` twin of {@link domainByContentKind}.
|
||||||
|
*
|
||||||
|
* ⚠ `pack` is absent for the same reason: a season pack is `serial`, an album
|
||||||
|
* release is `standalone`, and only the writer knows which.
|
||||||
|
*/
|
||||||
|
export const workFormByContentKind: { [contentKind: string]: WorkForm } = {
|
||||||
|
// screen
|
||||||
|
movie: 'standalone',
|
||||||
|
series: 'serial',
|
||||||
|
episode: 'serial',
|
||||||
|
// music — an album is a closed work, not an ongoing run, so every rung of
|
||||||
|
// the music ladder is standalone.
|
||||||
|
track: 'standalone',
|
||||||
|
album: 'standalone',
|
||||||
|
artist: 'standalone',
|
||||||
|
musicVideo: 'standalone',
|
||||||
|
djMix: 'standalone',
|
||||||
|
liveSet: 'standalone',
|
||||||
|
// literature — the split that proves workForm is not a screen-only axis.
|
||||||
|
book: 'standalone',
|
||||||
|
audiobook: 'standalone',
|
||||||
|
comic: 'serial',
|
||||||
|
manga: 'serial',
|
||||||
|
magazine: 'serial',
|
||||||
|
// science
|
||||||
|
paper: 'standalone',
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve the domain a `contentKind` belongs to.
|
||||||
|
*
|
||||||
|
* Returns `undefined` for `pack` (not derivable from the kind — the writer
|
||||||
|
* supplies it), for sidecar/format kinds that route nowhere, and for any kind
|
||||||
|
* this build has never heard of. A caller that already knows the domain from
|
||||||
|
* its own context must prefer that over this table.
|
||||||
|
*/
|
||||||
|
export function domainForContentKind(contentKind: string | undefined | null): Domain | undefined {
|
||||||
|
if (!contentKind) return undefined;
|
||||||
|
return domainByContentKind[contentKind.trim()];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve the work form a `contentKind` sits on. Same contract as
|
||||||
|
* {@link domainForContentKind}: `undefined` means "not derivable", never a
|
||||||
|
* guess. Whoever writes `contentKind` writes both of these in the same breath.
|
||||||
|
*/
|
||||||
|
export function workFormForContentKind(contentKind: string | undefined | null): WorkForm | undefined {
|
||||||
|
if (!contentKind) return undefined;
|
||||||
|
return workFormByContentKind[contentKind.trim()];
|
||||||
|
}
|
||||||
@@ -1,5 +1,14 @@
|
|||||||
import {SimpleFileType} from "../SimpleFileType.js";
|
import {SimpleFileType} from "../SimpleFileType.js";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extension → `fileType`. Half of the canonical classification table
|
||||||
|
* documented in METADATA_KEYS.md §1 (the other half is
|
||||||
|
* {@link mimeTypeMappings}); this file is the source of truth and the doc
|
||||||
|
* mirrors it.
|
||||||
|
*
|
||||||
|
* An extension absent from this map resolves to `other`, which makes the file
|
||||||
|
* invisible to every typed query — so a missing entry is not a cosmetic gap.
|
||||||
|
*/
|
||||||
export const extensionMappings: { [key: string]: SimpleFileType } = {
|
export const extensionMappings: { [key: string]: SimpleFileType } = {
|
||||||
// Audio
|
// Audio
|
||||||
'mp3': 'audio',
|
'mp3': 'audio',
|
||||||
@@ -7,7 +16,19 @@ export const extensionMappings: { [key: string]: SimpleFileType } = {
|
|||||||
'flac': 'audio',
|
'flac': 'audio',
|
||||||
'aac': 'audio',
|
'aac': 'audio',
|
||||||
'ogg': 'audio',
|
'ogg': 'audio',
|
||||||
|
'oga': 'audio',
|
||||||
|
'opus': 'audio',
|
||||||
'm4a': 'audio',
|
'm4a': 'audio',
|
||||||
|
// `m4b` is the audiobook container — without it `contentKind=audiobook`
|
||||||
|
// had no extension that resolved to `audio` (METADATA_KEYS.md §14.15).
|
||||||
|
'm4b': 'audio',
|
||||||
|
'wma': 'audio',
|
||||||
|
'aiff': 'audio',
|
||||||
|
'aif': 'audio',
|
||||||
|
'ape': 'audio',
|
||||||
|
'wv': 'audio',
|
||||||
|
'dsf': 'audio',
|
||||||
|
'mka': 'audio',
|
||||||
// Video
|
// Video
|
||||||
'mp4': 'video',
|
'mp4': 'video',
|
||||||
'mkv': 'video',
|
'mkv': 'video',
|
||||||
@@ -27,6 +48,8 @@ export const extensionMappings: { [key: string]: SimpleFileType } = {
|
|||||||
'ts': 'video',
|
'ts': 'video',
|
||||||
'vob': 'video',
|
'vob': 'video',
|
||||||
'ogm': 'video',
|
'ogm': 'video',
|
||||||
|
'ogv': 'video',
|
||||||
|
'asf': 'video',
|
||||||
'divx': 'video',
|
'divx': 'video',
|
||||||
'xvid': 'video',
|
'xvid': 'video',
|
||||||
// Document
|
// Document
|
||||||
@@ -37,31 +60,64 @@ export const extensionMappings: { [key: string]: SimpleFileType } = {
|
|||||||
'pptx': 'document',
|
'pptx': 'document',
|
||||||
'xls': 'document',
|
'xls': 'document',
|
||||||
'xlsx': 'document',
|
'xlsx': 'document',
|
||||||
|
'odt': 'document',
|
||||||
|
'ods': 'document',
|
||||||
|
'odp': 'document',
|
||||||
'txt': 'document',
|
'txt': 'document',
|
||||||
|
'md': 'document',
|
||||||
'rtf': 'document',
|
'rtf': 'document',
|
||||||
// Images (are document)
|
// Document — literature formats. Their absence blocked meta-read outright
|
||||||
'jpg': 'document',
|
// (METADATA_KEYS.md §14.15).
|
||||||
'jpeg': 'document',
|
'epub': 'document',
|
||||||
'png': 'document',
|
'mobi': 'document',
|
||||||
'gif': 'document',
|
'azw': 'document',
|
||||||
'bmp': 'document',
|
'azw3': 'document',
|
||||||
'tif': 'document',
|
'djvu': 'document',
|
||||||
'tiff': 'document',
|
// Images
|
||||||
'svg': 'document',
|
// ⚠ These used to map to `document` ("Images (are document)"), which meant
|
||||||
'webp': 'document',
|
// the `image` bucket was unreachable from this table while Rust feeders
|
||||||
|
// wrote it anyway. A consumer asking for documents must not receive
|
||||||
|
// posters — see METADATA_KEYS.md §14.15.
|
||||||
|
'jpg': 'image',
|
||||||
|
'jpeg': 'image',
|
||||||
|
'png': 'image',
|
||||||
|
'gif': 'image',
|
||||||
|
'bmp': 'image',
|
||||||
|
'tif': 'image',
|
||||||
|
'tiff': 'image',
|
||||||
|
'svg': 'image',
|
||||||
|
'webp': 'image',
|
||||||
|
'avif': 'image',
|
||||||
|
'heic': 'image',
|
||||||
|
'heif': 'image',
|
||||||
|
'ico': 'image',
|
||||||
// Archive
|
// Archive
|
||||||
'zip': 'archive',
|
'zip': 'archive',
|
||||||
'rar': 'archive',
|
'rar': 'archive',
|
||||||
'7z': 'archive',
|
'7z': 'archive',
|
||||||
'tar': 'archive',
|
'tar': 'archive',
|
||||||
|
'tgz': 'archive',
|
||||||
'gz': 'archive',
|
'gz': 'archive',
|
||||||
'bz2': 'archive',
|
'bz2': 'archive',
|
||||||
'xz': 'archive',
|
'xz': 'archive',
|
||||||
|
'zst': 'archive',
|
||||||
|
// Archive — comic containers. A `.cbz` is literally a zip, so `archive` is
|
||||||
|
// the honest byte-level answer; `contentKind=comic` + `domain=literature`
|
||||||
|
// are what route it to meta-read (METADATA_KEYS.md §14.16).
|
||||||
|
'cbz': 'archive',
|
||||||
|
'cbr': 'archive',
|
||||||
//subtitles
|
//subtitles
|
||||||
'srt': 'subtitle',
|
'srt': 'subtitle',
|
||||||
'sub': 'subtitle',
|
'sub': 'subtitle',
|
||||||
'sbv': 'subtitle',
|
'sbv': 'subtitle',
|
||||||
'vtt': 'subtitle',
|
'vtt': 'subtitle',
|
||||||
|
// ⚠ ASS/SSA is what meta-watch renders through libass — the client's
|
||||||
|
// primary subtitle format was the one this classifier did not know.
|
||||||
|
'ass': 'subtitle',
|
||||||
|
'ssa': 'subtitle',
|
||||||
|
'ttml': 'subtitle',
|
||||||
|
'dfxp': 'subtitle',
|
||||||
|
'smi': 'subtitle',
|
||||||
//torrent
|
//torrent
|
||||||
'torrent': 'torrent',
|
'torrent': 'torrent',
|
||||||
};
|
};
|
||||||
@@ -1,11 +1,32 @@
|
|||||||
import {SimpleFileType} from "../SimpleFileType.js";
|
import {SimpleFileType} from "../SimpleFileType.js";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* MIME type → `fileType`. The other half of the canonical classification
|
||||||
|
* table (see {@link extensionMappings} and METADATA_KEYS.md §1).
|
||||||
|
*
|
||||||
|
* ⚠ Resolution is conservative on purpose: when a sniffed MIME maps to a
|
||||||
|
* definite value that *disagrees* with the extension's value,
|
||||||
|
* `FileTypeConfigurable.getFileType` returns `undefined` rather than guessing
|
||||||
|
* — a wrong `fileType` routes a file to a handler that cannot open it. Adding
|
||||||
|
* a mapping here therefore also creates a new way to disagree; only add ones
|
||||||
|
* whose extension counterpart agrees.
|
||||||
|
*/
|
||||||
export const mimeTypeMappings: { [key: string]: SimpleFileType } = {
|
export const mimeTypeMappings: { [key: string]: SimpleFileType } = {
|
||||||
'text/plain': 'undefined',//text could be anything document or subtitle or other
|
'text/plain': 'undefined',//text could be anything document or subtitle or other
|
||||||
// Audio MIME types
|
// Audio MIME types
|
||||||
'audio/mpeg': 'audio',
|
'audio/mpeg': 'audio',
|
||||||
'audio/wav': 'audio',
|
'audio/wav': 'audio',
|
||||||
|
'audio/x-wav': 'audio',
|
||||||
'audio/flac': 'audio',
|
'audio/flac': 'audio',
|
||||||
|
'audio/ogg': 'audio',
|
||||||
|
'audio/opus': 'audio',
|
||||||
|
'audio/aac': 'audio',
|
||||||
|
// ftyp brands `M4A `/`M4B ` sniff as audio/mp4 while a real video mp4
|
||||||
|
// sniffs as video/mp4, so this does not collide with the `mp4` extension.
|
||||||
|
'audio/mp4': 'audio',
|
||||||
|
'audio/x-ms-wma': 'audio',
|
||||||
|
'audio/x-aiff': 'audio',
|
||||||
|
'audio/x-ape': 'audio',
|
||||||
// Video MIME types
|
// Video MIME types
|
||||||
'video/mp4': 'video',
|
'video/mp4': 'video',
|
||||||
'video/mpeg': 'video',
|
'video/mpeg': 'video',
|
||||||
@@ -13,8 +34,12 @@ export const mimeTypeMappings: { [key: string]: SimpleFileType } = {
|
|||||||
'video/x-msvideo': 'video',
|
'video/x-msvideo': 'video',
|
||||||
'video/x-flv': 'video',
|
'video/x-flv': 'video',
|
||||||
'video/x-ms-wmv': 'video',
|
'video/x-ms-wmv': 'video',
|
||||||
|
'video/x-ms-asf': 'video',
|
||||||
'video/x-matroska': 'video',
|
'video/x-matroska': 'video',
|
||||||
'video/webm': 'video',
|
'video/webm': 'video',
|
||||||
|
'video/ogg': 'video',
|
||||||
|
'video/3gpp': 'video',
|
||||||
|
'video/mp2t': 'video',
|
||||||
// Document MIME types
|
// Document MIME types
|
||||||
'application/pdf': 'document',
|
'application/pdf': 'document',
|
||||||
'application/msword': 'document',
|
'application/msword': 'document',
|
||||||
@@ -23,20 +48,47 @@ export const mimeTypeMappings: { [key: string]: SimpleFileType } = {
|
|||||||
'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'document',
|
'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'document',
|
||||||
'application/vnd.ms-excel': 'document',
|
'application/vnd.ms-excel': 'document',
|
||||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'document',
|
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'document',
|
||||||
'image/jpeg': 'document',
|
'application/vnd.oasis.opendocument.text': 'document',
|
||||||
'image/png': 'document',
|
'application/vnd.oasis.opendocument.spreadsheet': 'document',
|
||||||
'image/gif': 'document',
|
'application/vnd.oasis.opendocument.presentation': 'document',
|
||||||
|
'application/rtf': 'document',
|
||||||
|
// Literature containers (METADATA_KEYS.md §14.15)
|
||||||
|
'application/epub+zip': 'document',
|
||||||
|
'application/x-mobipocket-ebook': 'document',
|
||||||
|
'image/vnd.djvu': 'document',
|
||||||
|
'text/markdown': 'document',
|
||||||
|
// Image MIME types — no longer folded into `document` (§14.15)
|
||||||
|
'image/jpeg': 'image',
|
||||||
|
'image/png': 'image',
|
||||||
|
'image/gif': 'image',
|
||||||
|
'image/webp': 'image',
|
||||||
|
'image/bmp': 'image',
|
||||||
|
'image/tiff': 'image',
|
||||||
|
'image/svg+xml': 'image',
|
||||||
|
'image/avif': 'image',
|
||||||
|
'image/heic': 'image',
|
||||||
|
'image/x-icon': 'image',
|
||||||
// Archive MIME types
|
// Archive MIME types
|
||||||
'application/zip': 'archive',
|
'application/zip': 'archive',
|
||||||
'application/x-rar-compressed': 'archive',
|
'application/x-rar-compressed': 'archive',
|
||||||
|
'application/vnd.rar': 'archive',
|
||||||
'application/x-7z-compressed': 'archive',
|
'application/x-7z-compressed': 'archive',
|
||||||
'application/gzip': 'archive',
|
'application/gzip': 'archive',
|
||||||
|
'application/x-bzip2': 'archive',
|
||||||
|
'application/x-xz': 'archive',
|
||||||
|
'application/zstd': 'archive',
|
||||||
'application/x-tar': 'archive',
|
'application/x-tar': 'archive',
|
||||||
|
// Comic containers sniff as their underlying zip/rar, which agrees with
|
||||||
|
// the `cbz`/`cbr` extensions — both say `archive`.
|
||||||
|
'application/vnd.comicbook+zip': 'archive',
|
||||||
|
'application/vnd.comicbook-rar': 'archive',
|
||||||
//torrent
|
//torrent
|
||||||
'application/x-bittorrent': 'torrent',
|
'application/x-bittorrent': 'torrent',
|
||||||
//subtitles
|
//subtitles
|
||||||
'text/vtt': 'subtitle',
|
'text/vtt': 'subtitle',
|
||||||
'text/srt': 'subtitle',
|
'text/srt': 'subtitle',
|
||||||
'text/ssa': 'subtitle',
|
'text/ssa': 'subtitle',
|
||||||
|
'text/x-ssa': 'subtitle',
|
||||||
'text/sub': 'subtitle',
|
'text/sub': 'subtitle',
|
||||||
|
'application/x-subrip': 'subtitle',
|
||||||
};
|
};
|
||||||
@@ -13,6 +13,7 @@ export * from './tools/StringArrayOperation.js';
|
|||||||
export * from './tools/TwoStringsOperation.js';
|
export * from './tools/TwoStringsOperation.js';
|
||||||
|
|
||||||
export * from './config/AnimeKeywords.js';
|
export * from './config/AnimeKeywords.js';
|
||||||
|
export * from './config/DomainMapping.js';
|
||||||
export * from './config/ExtentionsMapping.js';
|
export * from './config/ExtentionsMapping.js';
|
||||||
export * from './config/KeywordsArray.js';
|
export * from './config/KeywordsArray.js';
|
||||||
export * from './config/MimeTypeMapping.js';
|
export * from './config/MimeTypeMapping.js';
|
||||||
|
|||||||
@@ -1,10 +1,17 @@
|
|||||||
/**
|
/**
|
||||||
* Multicodec / multihash codes for every digest meta-hash can compute.
|
* Multicodec / multihash codes for every digest meta-hash can compute.
|
||||||
*
|
*
|
||||||
* Source of truth for these numbers, mirrored in:
|
* Source of truth for these numbers. The same codes appear in the CID utility
|
||||||
|
* RANK, which is a separate thing this file does not implement:
|
||||||
* - `packages/meta-core/internal/cid/rank.go`
|
* - `packages/meta-core/internal/cid/rank.go`
|
||||||
* - the `cid_rank.rs` in each of meta-search and meta-share
|
* - the `cid_rank.rs` in each of meta-search and meta-share
|
||||||
* - `/cid-rank-vectors.json` (the golden fixture that pins them all together)
|
* - `/cid-rank-vectors.json` (the golden fixture pinning those three together)
|
||||||
|
*
|
||||||
|
* ⚠ This package used to vendor that fixture at `src/tests/cid-rank-vectors.json`
|
||||||
|
* and no test ever loaded it, so every vector added cost a commit here for
|
||||||
|
* nothing. Removed 2026-09-09. If a TypeScript rank implementation is ever
|
||||||
|
* written, re-add the path to `scripts/check-cid-vectors.sh` *and* a test that
|
||||||
|
* asserts it — a vendored fixture nobody reads is not a guard.
|
||||||
*
|
*
|
||||||
* ⚠ meta-hash encodes `codec == multihash code` (see `ComputeHash.cidFinalize`:
|
* ⚠ meta-hash encodes `codec == multihash code` (see `ComputeHash.cidFinalize`:
|
||||||
* `CID.createV1(code, create(code, digest))`), whereas the fullhash plugin and
|
* `CID.createV1(code, create(code, digest))`), whereas the fullhash plugin and
|
||||||
|
|||||||
@@ -1,166 +0,0 @@
|
|||||||
{
|
|
||||||
"$schema": "cid-rank-vectors/v1",
|
|
||||||
"$comment": [
|
|
||||||
"CANONICAL golden vectors for the CID utility rank. THE single source of truth.",
|
|
||||||
"The rank decides which of a record's several CIDs is elected canonical - the cid a",
|
|
||||||
"record is advertised and addressed by. It is reimplemented in Go, 2x Rust and 3x TS;",
|
|
||||||
"they cannot share code (independent submodules, no cargo path-dep). These vectors are",
|
|
||||||
"the only thing holding them in sync: every implementation's test suite loads this file.",
|
|
||||||
"",
|
|
||||||
"This file is VENDORED into each consuming submodule (submodule CI cannot read above its",
|
|
||||||
"own tree). scripts/check-cid-vectors.sh diffs every copy against this one.",
|
|
||||||
"",
|
|
||||||
"Ranking is by UTILITY for external retrieval, not cryptographic strength.",
|
|
||||||
"Ties break on the lexicographically smaller cid, so the election is deterministic",
|
|
||||||
"across peers and does not churn.",
|
|
||||||
"",
|
|
||||||
"See METADATA_KEYS.md section 2/14.13 and docs/cid-formats.md."
|
|
||||||
],
|
|
||||||
"ladder": {
|
|
||||||
"40": "dag-pb (IPFS block)",
|
|
||||||
"30": "sha2-256 / sha3-256 / sha3-384 - real content digests",
|
|
||||||
"25": "nzb-posting - content-derived (Message-ID set digest), but not itself fetchable",
|
|
||||||
"20": "BitTorrent infohashes - swarm interop",
|
|
||||||
"10": "midhash256 - the record address",
|
|
||||||
"5": "opaque locators (nzb-release, url, card) - never outrank a real digest",
|
|
||||||
"0": "weak/unknown digests, unparseable input"
|
|
||||||
},
|
|
||||||
"tieBreak": "lexicographically smaller cid wins",
|
|
||||||
"vectors": [
|
|
||||||
{
|
|
||||||
"name": "ipfs-dagpb",
|
|
||||||
"cid": "bafybeiaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
|
||||||
"rank": 40,
|
|
||||||
"note": "dag-pb codec 0x70 - chunked IPFS file, broadest network reach"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "sha2-256-raw-codec",
|
|
||||||
"cid": "bafkreiaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
|
||||||
"rank": 30,
|
|
||||||
"note": "fullhash/gateway convention: raw codec 0x55, mh names the algo"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "sha2-256-codec-eq-mh",
|
|
||||||
"cid": "baejbeibku6ua2l6r5olnggx4pto2sii2s5jeeawgh4cbkhlbmp52gudbua",
|
|
||||||
"rank": 30,
|
|
||||||
"note": "REAL meta-hash fixture; meta-hash sets codec == mh"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "sha3-256",
|
|
||||||
"cid": "baelbmidner7x3dd7t2kldh6wiq4w6lsye7qrwo6uoqot2t52zkhqk56fnq",
|
|
||||||
"rank": 30,
|
|
||||||
"note": "REAL meta-hash fixture"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "sha3-384",
|
|
||||||
"cid": "baekrkmeglipkjf33exqexdvijl4twipruay4wsbvt44akce43lq5rgccxgr7v6dwksmj3sxedakevc53g6ga",
|
|
||||||
"rank": 30,
|
|
||||||
"note": "REAL meta-hash fixture"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "nzb-posting",
|
|
||||||
"cid": "bagbsaeraaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
|
||||||
"rank": 25,
|
|
||||||
"note": "codec 0x1003 + REAL sha2-256 multihash (0x12) over the normalised, sorted Message-ID set - NOT a locator, so it sits ABOVE tier 5, but it addresses no fetchable block (bitswap can never satisfy a want for it - the digest is over an id set, not over any block's bytes), so it stays BELOW a real content digest (30): once meta-share materialises the media and re-seeds it, that genuine sha2-256 cid must win the canonical election, not this one. Rank MUST match on codec BEFORE falling through to the mh switch, or this scores 30 (same trap as nzb-release/url, in reverse: those need a codec check because their mh is identity 0x00; this needs one because its mh is REAL sha2-256 and would otherwise tie with tier 30)."
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "btih-v2-codec-eq-mh",
|
|
||||||
"cid": "bag3sdnzbeaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
|
||||||
"rank": 20,
|
|
||||||
"note": "meta-hash encoder convention"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "btih-v2-raw-codec",
|
|
||||||
"cid": "bafk3oijaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
|
||||||
"rank": 20,
|
|
||||||
"note": "fullhash encoder convention - SAME tier, both conventions must match"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "btih-v1-file",
|
|
||||||
"cid": "bagasbajacqaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
|
||||||
"rank": 20,
|
|
||||||
"note": "gateway per-file BitTorrent v1"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "btih-v2-file",
|
|
||||||
"cid": "bagbcbaraeaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
|
||||||
"rank": 20,
|
|
||||||
"note": "gateway per-file BitTorrent v2"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "midhash256-codec-eq-mh",
|
|
||||||
"cid": "bagacbabaeaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
|
||||||
"rank": 10,
|
|
||||||
"note": "the record address; internally meaningful, externally invisible"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "midhash256-raw-codec",
|
|
||||||
"cid": "bafkyaibaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
|
||||||
"rank": 10
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "nzb-release-locator",
|
|
||||||
"cid": "bagcsaaazcbqxa2jonz5gez3fmvvs42lomzx55ln657fp4aab",
|
|
||||||
"rank": 5,
|
|
||||||
"note": "codec 0x1005 + IDENTITY multihash 0x00. The locator code is in the CODEC slot, not the mh slot - rank MUST match on codec. Tier 5 = below midhash: a locator never outranks a real digest, it wins only as a record's sole cid."
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "url-locator",
|
|
||||||
"cid": "bagdcaaaznb2hi4dthixs6zlymfwxa3dffzxxezzpmexhazdg",
|
|
||||||
"rank": 5,
|
|
||||||
"note": "codec 0x1006 + IDENTITY multihash 0x00. Same tier/reasoning as nzb-release."
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "card-locator",
|
|
||||||
"cid": "bagdsaaanar2g2zdcor3duojvgq3ts",
|
|
||||||
"rank": 5,
|
|
||||||
"note": "codec 0x1007 + IDENTITY multihash 0x00, digest = varint(len(source)) || source || id — here (\"tmdb\",\"tv:95479\"). Same codec-slot rule as nzb-release/url: match on the CODEC, never the mh. The limit case of the family — the only CID in MetaMesh with NO bytes behind it anywhere, ever: it addresses a *work* (a series, a film), not a file, so the byte path 404s by design and bitswap never offers it (seeding is gated on sha2-256). Tier 5 is load-bearing for the planned cross-source merge: one card record may carry BOTH a TMDB and a MyAnimeList locator, and if a real card body is ever added (see card-tier-search.md §4.3) its sha2-256 must win the canonical election over both locators without any addressing change. Ranking it 0 instead would still lose to a digest, but would put the implementations back out of agreement — which is the exact failure this fixture exists to prevent."
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "sha1",
|
|
||||||
"cid": "baeircff3eqvxxaqqot2lt242stkdtk3gq4c2vra",
|
|
||||||
"rank": 0,
|
|
||||||
"note": "REAL meta-hash fixture; weak digest"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "md5",
|
|
||||||
"cid": "bahkqdvibcatpcfl7ine2n625eb5ml5mzkfaa",
|
|
||||||
"rank": 0,
|
|
||||||
"note": "REAL meta-hash fixture; weak digest"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "crc32",
|
|
||||||
"cid": "bagzafmqcathsbnrk",
|
|
||||||
"rank": 0,
|
|
||||||
"note": "REAL meta-hash fixture; weak digest"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "bt-pieces-root",
|
|
||||||
"cid": "bafkyf3qceaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
|
||||||
"rank": 0,
|
|
||||||
"note": "torrent-internal merkle root, NOT a file-identity cid"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "cidv0-rejected",
|
|
||||||
"cid": "QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG",
|
|
||||||
"rank": 0,
|
|
||||||
"note": "TRAP: Go rejected this (rank 0) while Rust's MsCid::from_str ACCEPTED it and ranked it 40 (dag-pb). Strict parse = CIDv1 base32-lower only. This vector pins the fix."
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "token-form-rejected",
|
|
||||||
"cid": "midhash256:bagacbabaeaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
|
||||||
"rank": 0,
|
|
||||||
"note": "TRAP: the deprecated <algo>:<cid> token form. Rust used to strip the prefix and rank it 10. It must now be rejected."
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "garbage",
|
|
||||||
"cid": "not-a-cid",
|
|
||||||
"rank": 0
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "empty",
|
|
||||||
"cid": "",
|
|
||||||
"rank": 0
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@@ -22,13 +22,13 @@ describe('MetaData', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('should set and get nested metadata using nested keys', () => {
|
it('should set and get nested metadata using nested keys', () => {
|
||||||
root.at('titles').at('eng').set("Star Wars");
|
root.at('titles').at('eng').at('Star Wars').set(true);
|
||||||
root.at('titles').at('jpn').set("Staru Warsu");
|
root.at('titles').at('jpn').at('Staru Warsu').set(true);
|
||||||
expect(root.at('titles').at('eng').get()).to.equal("Star Wars");
|
expect(root.at('titles').at('eng').at('Star Wars').get()).to.equal(true);
|
||||||
expect(root.at('titles').at('jpn').get()).to.equal("Staru Warsu");
|
expect(root.at('titles').at('jpn').at('Staru Warsu').get()).to.equal(true);
|
||||||
expect(root.at('titles').get()).to.deep.equal({eng: "Star Wars", jpn: "Staru Warsu"});
|
expect(root.at('titles').get()).to.deep.equal({eng: {"Star Wars": true}, jpn: {"Staru Warsu": true}});
|
||||||
expect(root.get()).to.deep.equal({
|
expect(root.get()).to.deep.equal({
|
||||||
titles: {eng: "Star Wars", jpn: "Staru Warsu"}
|
titles: {eng: {"Star Wars": true}, jpn: {"Staru Warsu": true}}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,25 @@
|
|||||||
import {TypedRecordSet} from "./basic/RecordSet.js";
|
import {TypedRecordSet} from "./basic/RecordSet.js";
|
||||||
import {ISO639_1_CODE} from "./basic/LanguageData.js";
|
import {LANG3_CODE} from "./basic/LanguageData.js";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The language triad (METADATA_KEYS.md §9).
|
||||||
|
*
|
||||||
|
* `languages` is the **union** — every language the record offers by any route
|
||||||
|
* — and the only one a query filters on. The two splits refine it and are
|
||||||
|
* optional. Rule #7: a writer that adds a member to a split MUST add the same
|
||||||
|
* member to the union in the same write; nothing reconciles them afterwards.
|
||||||
|
*/
|
||||||
export interface LanguagesMeta{
|
export interface LanguagesMeta{
|
||||||
languages?: TypedRecordSet<ISO639_1_CODE>;
|
/** The union: audio ∪ subtitles ∪ bare language statements. Filterable. */
|
||||||
|
languages?: TypedRecordSet<LANG3_CODE>;
|
||||||
|
/** Spoken/audio-track languages only. Refinement, never filtered on. */
|
||||||
|
audioLanguages?: TypedRecordSet<LANG3_CODE>;
|
||||||
|
/** Subtitle languages only (§8). Refinement, never filtered on. */
|
||||||
|
subtitleLanguages?: TypedRecordSet<LANG3_CODE>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const LanguagesMetaFields = [
|
export const LanguagesMetaFields = [
|
||||||
"languages",
|
"languages",
|
||||||
|
"audioLanguages",
|
||||||
|
"subtitleLanguages",
|
||||||
];
|
];
|
||||||
@@ -8,8 +8,9 @@ export interface VideoMeta {
|
|||||||
increment?: string;
|
increment?: string;
|
||||||
movieYear?: string;
|
movieYear?: string;
|
||||||
videoType?: VideoType;
|
videoType?: VideoType;
|
||||||
|
title?: string;//display title (localized); the one name to show
|
||||||
originalTitle?: string;//title in original language
|
originalTitle?: string;//title in original language
|
||||||
titles?: LanguageData<string>;// <ISO 639-3 lang codes, title>
|
titles?: LanguageData<Record<string, true>>;// key-set: <ISO 639-3 lang code, {name: true}> — every clean name incl. AKAs (METADATA_KEYS.md §3)
|
||||||
}
|
}
|
||||||
|
|
||||||
export const VideoMetaFields = [
|
export const VideoMetaFields = [
|
||||||
|
|||||||
@@ -1,9 +1,21 @@
|
|||||||
/**
|
/**
|
||||||
* key is language ISO 639-3 code
|
* key is a `lang3` code: ISO 639-2/**B** — `eng`, `jpn`, `fre`/`ger`/`chi`,
|
||||||
* https://en.wikipedia.org/wiki/List_of_ISO_639-3_codes
|
* NOT the 639-2/T (= 639-3) spellings `fra`/`deu`/`zho`.
|
||||||
|
*
|
||||||
|
* This is the vocabulary the stack compares against: `languages:` query filters
|
||||||
|
* match it literally, and `meta_feeder_sdk::lang::normalize_lang_code` folds
|
||||||
|
* incoming codes onto it. See METADATA_KEYS.md §"Value formats" and §14.3 —
|
||||||
|
* the card tier (`titles/*`, `posters/*`) is still on /T and has not converged.
|
||||||
|
* https://en.wikipedia.org/wiki/List_of_ISO_639-2_codes
|
||||||
*/
|
*/
|
||||||
export type LanguageData<T> = Record<string, T>;
|
export type LanguageData<T> = Record<string, T>;
|
||||||
export type ISO639_1_CODE = string;
|
export type LANG3_CODE = string;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @deprecated Misnamed: no writer has ever emitted 2-letter ISO 639-1 codes
|
||||||
|
* here. Use {@link LANG3_CODE}. Kept as an alias so existing imports compile.
|
||||||
|
*/
|
||||||
|
export type ISO639_1_CODE = LANG3_CODE;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* jpn, jpr and jpa already exist. Creating jpl is for japan-latin. Used for japanese romaji NON ISO 639-3 standard.
|
* jpn, jpr and jpa already exist. Creating jpl is for japan-latin. Used for japanese romaji NON ISO 639-3 standard.
|
||||||
|
|||||||
@@ -1,2 +1,16 @@
|
|||||||
export type SimpleFileType = 'audio' | 'video' | 'document' | 'archive' | 'other' | 'undefined';
|
/**
|
||||||
|
* The `fileType` vocabulary — METADATA_KEYS.md §1. Kept in lockstep with
|
||||||
|
* `filename-tool`'s `SimpleFileType`, which is the classifier that produces
|
||||||
|
* these values; this copy is the wire/type-level mirror.
|
||||||
|
*/
|
||||||
|
export type SimpleFileType =
|
||||||
|
'audio'
|
||||||
|
| 'video'
|
||||||
|
| 'image'
|
||||||
|
| 'document'
|
||||||
|
| 'archive'
|
||||||
|
| 'subtitle'
|
||||||
|
| 'torrent'
|
||||||
|
| 'card'
|
||||||
|
| 'other'
|
||||||
|
| 'undefined';
|
||||||
|
|||||||
Reference in New Issue
Block a user