Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
33f576c92a | ||
|
|
b4528a099a | ||
|
|
9280e23e83 |
@@ -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`).
|
||||||
|
|||||||
@@ -237,7 +237,7 @@ export class UnifiedAPIServer {
|
|||||||
this.setupStatsRoutes();
|
this.setupStatsRoutes();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Service discovery — meta-discovery v1 neighbour list, served from 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();
|
||||||
|
|
||||||
@@ -592,20 +592,23 @@ export class UnifiedAPIServer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Service discovery — meta-discovery v1. Served from this service's own UDP
|
* Service discovery — beacon v2 (docs/project-architecture/beacon-v2.md).
|
||||||
* neighbour map; no meta-core round trip, so the nav survives a core outage.
|
* 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 {
|
||||||
// meta-discovery v1: neighbours heard over UDP, served from this service's
|
// beacon v2: neighbours heard over UDP, served from this service's own
|
||||||
// own map. Unlike /api/services below it needs no meta-core, so the nav
|
// view. Unlike /api/services below it needs no meta-core, so the nav still
|
||||||
// still renders when the core is down. `services` is kept as an alias
|
// renders when the core is down. `?all=1` returns every instance,
|
||||||
|
// `?cap=<pattern>` filters by capability. `services` is kept as an alias
|
||||||
// while any older dashboard build is still in circulation.
|
// while any older dashboard build is still in circulation.
|
||||||
this.app.get('/api/neighbors', async (_request, reply) => {
|
this.app.get('/api/neighbors', async (request, reply) => {
|
||||||
const leaderClient = this.kvManager?.getLeaderClient();
|
const leaderClient = this.kvManager?.getLeaderClient();
|
||||||
if (!leaderClient) {
|
if (!leaderClient) {
|
||||||
return reply.send({ current: 'meta-sort', enabled: false, count: 0, neighbors: [] });
|
return reply.send({ current: 'meta-sort', enabled: false, count: 0, neighbors: [] });
|
||||||
}
|
}
|
||||||
const neighbors = leaderClient.getNeighbors();
|
const q = (request.query ?? {}) as { all?: string; cap?: string };
|
||||||
|
const neighbors = leaderClient.getNeighbors({ all: !!q.all, cap: q.cap || undefined });
|
||||||
return reply.send({
|
return reply.send({
|
||||||
current: 'meta-sort',
|
current: 'meta-sort',
|
||||||
enabled: true,
|
enabled: true,
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
/**
|
/**
|
||||||
* meta-discovery v1 — UDP multicast service discovery.
|
* Beacon v2 — local resource advertise / discover over UDP multicast
|
||||||
|
* (239.255.99.1:9099).
|
||||||
*
|
*
|
||||||
* Replaces the two file-based mechanisms that required a shared /meta-core
|
* Every node advertises resources tagged with capability strings
|
||||||
* volume: `locks/kv-leader.info` (locating meta-core at boot) and
|
* (`metamesh.core`, `metamesh.service/meta-sort`, `metamesh.transport/nzb@1`)
|
||||||
* `services/<name>-<host>.json` (the dashboard nav registry). Both answered the
|
* and keeps a live view of everyone else's. This service uses it to locate
|
||||||
* same question — where is meta-core, and who else is on this network — so one
|
* meta-core (the `metamesh.core` resource carries its /urls block) and to feed
|
||||||
* announce packet answers both, and discovery scope becomes the docker network
|
* the nav menu (`metamesh.service/*`), with no shared volume.
|
||||||
* rather than the mounted volume.
|
|
||||||
*
|
*
|
||||||
* The normative spec is docs/project-architecture/service-discovery.md.
|
* The normative spec is docs/project-architecture/beacon-v2.md.
|
||||||
*
|
*
|
||||||
* ⚠ MIRRORED FILE. Byte-identical copies live in meta-sort-core, meta-fuse-core
|
* ⚠ 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
|
* and meta-dup-core. They cannot share a package: meta-fuse-core and
|
||||||
@@ -21,17 +21,23 @@
|
|||||||
import dgram from 'dgram';
|
import dgram from 'dgram';
|
||||||
import { hostname, networkInterfaces } from 'os';
|
import { hostname, networkInterfaces } from 'os';
|
||||||
|
|
||||||
export const PROTOCOL_VERSION = 1;
|
export const PROTO = 'beacon';
|
||||||
export const DEFAULT_GROUP = '239.255.77.1';
|
export const VERSION = 2;
|
||||||
export const DEFAULT_PORT = 9399;
|
export const DEFAULT_GROUP = '239.255.99.1';
|
||||||
|
export const DEFAULT_PORT = 9099;
|
||||||
export const DEFAULT_INTERVAL_MS = 10_000;
|
export const DEFAULT_INTERVAL_MS = 10_000;
|
||||||
/** A neighbour unseen for interval × this is dropped. Replaces the reaper. */
|
/** A node unheard for interval × this is dropped (evaluated at read time). */
|
||||||
export const LIVENESS_FACTOR = 3;
|
export const LIVENESS_FACTOR = 3;
|
||||||
|
/** Senders stay under this so nothing fragments. */
|
||||||
|
export const MAX_DATAGRAM = 1400;
|
||||||
|
|
||||||
export const TYPE_DISCOVERY = 'discovery';
|
export const TYPE_PROBE = 'probe';
|
||||||
export const TYPE_ANNOUNCE = 'announce';
|
export const TYPE_ADVERTISE = 'advertise';
|
||||||
export const ROLE_CORE = 'core';
|
export const TYPE_BYE = 'bye';
|
||||||
export const ROLE_SERVICE = 'service';
|
|
||||||
|
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). */
|
/** Mirrors meta-core's GET /urls response minus redisUrl (retired). */
|
||||||
export interface MeshUrls {
|
export interface MeshUrls {
|
||||||
@@ -42,38 +48,114 @@ export interface MeshUrls {
|
|||||||
webdavUrlInternal: string;
|
webdavUrlInternal: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface MeshMessage {
|
export interface BeaconNodeInfo {
|
||||||
v: number;
|
name: string;
|
||||||
type: string;
|
instance: string;
|
||||||
name?: string;
|
|
||||||
instance?: string;
|
|
||||||
role?: string;
|
|
||||||
version?: string;
|
version?: string;
|
||||||
|
/** 'starting' | 'running'; absent reads as running. */
|
||||||
status?: string;
|
status?: string;
|
||||||
baseUrl?: string;
|
|
||||||
/** Present only when role === 'core'. */
|
|
||||||
urls?: MeshUrls;
|
|
||||||
/** Reserved for a future HMAC; v1 ignores it. */
|
|
||||||
token?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface MeshNeighbor extends MeshMessage {
|
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. */
|
/** Source address taken from the packet, never from the payload. */
|
||||||
addr: string;
|
addr: string;
|
||||||
|
/** Unix seconds. */
|
||||||
lastSeen: number;
|
lastSeen: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface MeshNodeConfig {
|
export interface MeshNodeConfig {
|
||||||
name: string;
|
name: string;
|
||||||
instance?: string;
|
instance?: string;
|
||||||
role?: string;
|
|
||||||
version?: string;
|
version?: string;
|
||||||
group?: string;
|
group?: string;
|
||||||
port?: number;
|
port?: number;
|
||||||
intervalMs?: number;
|
intervalMs?: number;
|
||||||
enabled?: boolean;
|
enabled?: boolean;
|
||||||
/** Rebuilt on every announce so the payload never goes stale. */
|
/** Rebuilt on every advertise so the payload never goes stale. */
|
||||||
payload?: () => { baseUrl?: string; status?: string; urls?: MeshUrls };
|
payload?: () => { status?: string; resources: BeaconResource[] };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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. */
|
/** IPv4 addresses of every up, non-internal interface. */
|
||||||
@@ -96,15 +178,44 @@ export function localIPv4(): string {
|
|||||||
return localInterfaceAddresses()[0] ?? hostname();
|
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 participant in the mesh: announces itself, answers probes, and keeps a
|
* One beacon v2 participant: advertises its resources, answers probes, and
|
||||||
* TTL map of everyone else.
|
* keeps a TTL map of every other node.
|
||||||
*/
|
*/
|
||||||
export class MeshNode {
|
export class MeshNode {
|
||||||
private cfg: Required<Omit<MeshNodeConfig, 'payload'>> & Pick<MeshNodeConfig, 'payload'>;
|
private cfg: Required<Omit<MeshNodeConfig, 'payload'>> & Pick<MeshNodeConfig, 'payload'>;
|
||||||
private socket: dgram.Socket | null = null;
|
private socket: dgram.Socket | null = null;
|
||||||
private timer: NodeJS.Timeout | null = null;
|
private timer: NodeJS.Timeout | null = null;
|
||||||
private neighbors = new Map<string, MeshNeighbor>();
|
private nodes = new Map<string, Seen>();
|
||||||
private ifaceAddrs: string[] = [];
|
private ifaceAddrs: string[] = [];
|
||||||
private listeners: ((n: MeshNeighbor) => void)[] = [];
|
private listeners: ((n: MeshNeighbor) => void)[] = [];
|
||||||
private started = false;
|
private started = false;
|
||||||
@@ -113,11 +224,10 @@ export class MeshNode {
|
|||||||
this.cfg = {
|
this.cfg = {
|
||||||
name: config.name,
|
name: config.name,
|
||||||
instance: config.instance ?? hostname(),
|
instance: config.instance ?? hostname(),
|
||||||
role: config.role ?? ROLE_SERVICE,
|
|
||||||
version: config.version ?? '',
|
version: config.version ?? '',
|
||||||
group: config.group ?? DEFAULT_GROUP,
|
group: config.group ?? process.env.BEACON_GROUP ?? DEFAULT_GROUP,
|
||||||
port: config.port ?? DEFAULT_PORT,
|
port: config.port ?? envNum('BEACON_PORT') ?? DEFAULT_PORT,
|
||||||
intervalMs: config.intervalMs ?? DEFAULT_INTERVAL_MS,
|
intervalMs: config.intervalMs ?? envNum('BEACON_INTERVAL_MS') ?? DEFAULT_INTERVAL_MS,
|
||||||
enabled: config.enabled ?? true,
|
enabled: config.enabled ?? true,
|
||||||
payload: config.payload,
|
payload: config.payload,
|
||||||
};
|
};
|
||||||
@@ -125,12 +235,14 @@ export class MeshNode {
|
|||||||
|
|
||||||
async start(): Promise<void> {
|
async start(): Promise<void> {
|
||||||
if (this.started || !this.cfg.enabled) {
|
if (this.started || !this.cfg.enabled) {
|
||||||
if (!this.cfg.enabled) console.log('[meshdisco] Disabled by configuration');
|
if (!this.cfg.enabled) console.log('[beacon] Disabled by configuration');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
this.started = true;
|
this.started = true;
|
||||||
|
|
||||||
await new Promise<void>((resolve) => {
|
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 });
|
const socket = dgram.createSocket({ type: 'udp4', reuseAddr: true });
|
||||||
this.socket = socket;
|
this.socket = socket;
|
||||||
|
|
||||||
@@ -138,14 +250,14 @@ export class MeshNode {
|
|||||||
socket.on('error', (err) => {
|
socket.on('error', (err) => {
|
||||||
// Never fatal: a host that blocks multicast must degrade, not
|
// Never fatal: a host that blocks multicast must degrade, not
|
||||||
// take the service down.
|
// take the service down.
|
||||||
console.error('[meshdisco] Socket error:', err.message);
|
console.error('[beacon] Socket error:', err.message);
|
||||||
});
|
});
|
||||||
|
|
||||||
socket.bind(this.cfg.port, '0.0.0.0', () => {
|
socket.bind(this.cfg.port, '0.0.0.0', () => {
|
||||||
try {
|
try {
|
||||||
socket.setMulticastTTL(1); // link-local only
|
socket.setMulticastTTL(1); // link-local only
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.warn('[meshdisco] Could not set multicast TTL:', e);
|
console.warn('[beacon] Could not set multicast TTL:', e);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Join on EVERY interface. A container on two docker networks
|
// Join on EVERY interface. A container on two docker networks
|
||||||
@@ -157,20 +269,20 @@ export class MeshNode {
|
|||||||
socket.addMembership(this.cfg.group, addr);
|
socket.addMembership(this.cfg.group, addr);
|
||||||
joined++;
|
joined++;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.warn(`[meshdisco] Join ${this.cfg.group} on ${addr} failed:`, e);
|
console.warn(`[beacon] Join ${this.cfg.group} on ${addr} failed:`, e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
console.log(
|
console.log(
|
||||||
`[meshdisco] Listening on ${this.cfg.group}:${this.cfg.port} as ` +
|
`[beacon] Listening on ${this.cfg.group}:${this.cfg.port} as ` +
|
||||||
`${this.cfg.name}/${this.cfg.instance} (joined ${joined} of ${this.ifaceAddrs.length} interfaces)`
|
`${this.cfg.name}/${this.cfg.instance} (joined ${joined} of ${this.ifaceAddrs.length} interfaces)`
|
||||||
);
|
);
|
||||||
resolve();
|
resolve();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
this.announce();
|
this.advertise();
|
||||||
this.probe();
|
this.probe();
|
||||||
this.timer = setInterval(() => this.announce(), this.cfg.intervalMs);
|
this.timer = setInterval(() => this.advertise(), this.cfg.intervalMs);
|
||||||
// Don't hold the event loop open on shutdown.
|
// Don't hold the event loop open on shutdown.
|
||||||
this.timer.unref?.();
|
this.timer.unref?.();
|
||||||
}
|
}
|
||||||
@@ -179,9 +291,9 @@ export class MeshNode {
|
|||||||
if (!this.started) return;
|
if (!this.started) return;
|
||||||
this.started = false;
|
this.started = false;
|
||||||
if (this.timer) { clearInterval(this.timer); this.timer = null; }
|
if (this.timer) { clearInterval(this.timer); this.timer = null; }
|
||||||
// Final "stopping" announce so neighbours drop us immediately rather
|
// Bye, so neighbours drop us immediately rather than waiting out the
|
||||||
// than waiting out the staleness window.
|
// staleness window.
|
||||||
this.announce('stopping');
|
this.multicast({ proto: PROTO, v: VERSION, type: TYPE_BYE, node: this.nodeInfo() });
|
||||||
await new Promise<void>((resolve) => {
|
await new Promise<void>((resolve) => {
|
||||||
if (!this.socket) return resolve();
|
if (!this.socket) return resolve();
|
||||||
try { this.socket.close(() => resolve()); } catch { resolve(); }
|
try { this.socket.close(() => resolve()); } catch { resolve(); }
|
||||||
@@ -190,135 +302,137 @@ export class MeshNode {
|
|||||||
this.listeners = [];
|
this.listeners = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Multicast a probe; every listener replies immediately. */
|
/**
|
||||||
probe(): void {
|
* Multicast a probe. Every node owning a resource matching one of `want`
|
||||||
this.send({ v: PROTOCOL_VERSION, type: TYPE_DISCOVERY });
|
* (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);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Everyone heard from inside the staleness window, sorted by name. */
|
/** Every live node, sorted by (name, instance). */
|
||||||
getNeighbors(): MeshNeighbor[] {
|
getNeighbors(): MeshNeighbor[] {
|
||||||
const cutoff = Date.now() - this.cfg.intervalMs * LIVENESS_FACTOR;
|
const cutoff = Date.now() - this.cfg.intervalMs * LIVENESS_FACTOR;
|
||||||
const out: MeshNeighbor[] = [];
|
const out: MeshNeighbor[] = [];
|
||||||
for (const [key, nb] of this.neighbors) {
|
for (const [key, s] of this.nodes) {
|
||||||
if (nb.lastSeen < cutoff) { this.neighbors.delete(key); continue; }
|
if (s.lastSeen < cutoff) { this.nodes.delete(key); continue; }
|
||||||
out.push(nb);
|
out.push(toNeighbor(s));
|
||||||
}
|
}
|
||||||
return out.sort((a, b) => (a.name ?? '').localeCompare(b.name ?? ''));
|
return out.sort((a, b) => a.name.localeCompare(b.name) || a.instance.localeCompare(b.instance));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** One row per service name, most recently seen instance wins. */
|
/** One row per node name, most recently seen instance wins. */
|
||||||
getNeighborsByName(): MeshNeighbor[] {
|
getNeighborsByName(): MeshNeighbor[] {
|
||||||
const best = new Map<string, MeshNeighbor>();
|
const best = new Map<string, MeshNeighbor>();
|
||||||
for (const nb of this.getNeighbors()) {
|
for (const nb of this.getNeighbors()) {
|
||||||
const cur = best.get(nb.name ?? '');
|
const cur = best.get(nb.name);
|
||||||
if (!cur || nb.lastSeen > cur.lastSeen) best.set(nb.name ?? '', nb);
|
if (!cur || nb.lastSeen > cur.lastSeen) best.set(nb.name, nb);
|
||||||
}
|
}
|
||||||
return [...best.values()].sort((a, b) => (a.name ?? '').localeCompare(b.name ?? ''));
|
return [...best.values()].sort((a, b) => a.name.localeCompare(b.name));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Cores only — what a locator filters on. */
|
/** This node as a row, so a UI can render itself without waiting. */
|
||||||
getCores(): MeshNeighbor[] {
|
|
||||||
return this.getNeighbors().filter((n) => n.role === ROLE_CORE && n.urls);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** This node's own announce, so a UI can render itself without waiting. */
|
|
||||||
self(): MeshNeighbor {
|
self(): MeshNeighbor {
|
||||||
return { ...this.buildAnnounce('running'), addr: '', lastSeen: Date.now() };
|
const { status, resources } = this.payload();
|
||||||
|
return toNeighbor({ node: this.nodeInfo(status), resources, addr: '', lastSeen: Date.now() });
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Fires for every announce received (after the self-echo filter). */
|
/** Fires for every advertise received (after the self-echo filter). */
|
||||||
onAnnounce(cb: (n: MeshNeighbor) => void): void {
|
onAdvertise(cb: (n: MeshNeighbor) => void): void {
|
||||||
this.listeners.push(cb);
|
this.listeners.push(cb);
|
||||||
}
|
}
|
||||||
|
|
||||||
private onMessage(buf: Buffer, rinfo: dgram.RemoteInfo): void {
|
private payload(): { status?: string; resources: BeaconResource[] } {
|
||||||
let msg: MeshMessage;
|
return this.cfg.payload ? this.cfg.payload() : { resources: [] };
|
||||||
try {
|
|
||||||
msg = JSON.parse(buf.toString('utf8')) as MeshMessage;
|
|
||||||
} catch {
|
|
||||||
return; // foreign traffic on the group
|
|
||||||
}
|
}
|
||||||
if (msg.v !== PROTOCOL_VERSION) return;
|
|
||||||
// Drop our own multicast echo.
|
|
||||||
if (msg.instance && msg.instance === this.cfg.instance && msg.name === this.cfg.name) return;
|
|
||||||
|
|
||||||
if (msg.type === TYPE_DISCOVERY) {
|
private nodeInfo(status?: string): BeaconNodeInfo {
|
||||||
this.replyTo(rinfo);
|
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;
|
return;
|
||||||
}
|
}
|
||||||
if (msg.type !== TYPE_ANNOUNCE || !msg.name) return;
|
|
||||||
|
|
||||||
const key = msg.instance ? `${msg.name}|${msg.instance}` : msg.name;
|
const node = msg.node!;
|
||||||
if (msg.status === 'stopping') { this.neighbors.delete(key); return; }
|
if (node.instance === this.cfg.instance) return; // our own echo
|
||||||
|
if (msg.type === TYPE_BYE) { this.nodes.delete(node.instance); return; }
|
||||||
|
|
||||||
const nb: MeshNeighbor = { ...msg, addr: rinfo.address, lastSeen: Date.now() };
|
const seen: Seen = { node, resources: msg.resources ?? [], addr: rinfo.address, lastSeen: Date.now() };
|
||||||
this.neighbors.set(key, nb);
|
this.nodes.set(node.instance, seen);
|
||||||
|
const nb = toNeighbor(seen);
|
||||||
for (const cb of this.listeners) {
|
for (const cb of this.listeners) {
|
||||||
try { cb(nb); } catch (e) { console.error('[meshdisco] Listener threw:', e); }
|
try { cb(nb); } catch (e) { console.error('[beacon] Listener threw:', e); }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private buildAnnounce(status: string): MeshMessage {
|
private encode(msg: BeaconMessage): Buffer {
|
||||||
const msg: MeshMessage = {
|
const body = Buffer.from(JSON.stringify(msg));
|
||||||
v: PROTOCOL_VERSION,
|
if (body.length > MAX_DATAGRAM) {
|
||||||
type: TYPE_ANNOUNCE,
|
console.warn(`[beacon] ${body.length}-byte datagram exceeds the fragmentation-safe ${MAX_DATAGRAM}`);
|
||||||
name: this.cfg.name,
|
|
||||||
instance: this.cfg.instance,
|
|
||||||
role: this.cfg.role,
|
|
||||||
version: this.cfg.version,
|
|
||||||
status,
|
|
||||||
};
|
|
||||||
if (this.cfg.payload) {
|
|
||||||
const p = this.cfg.payload();
|
|
||||||
if (p.baseUrl) msg.baseUrl = p.baseUrl;
|
|
||||||
if (p.status && status === 'running') msg.status = p.status;
|
|
||||||
// Only a core may carry a URLs block — a service announcing one
|
|
||||||
// would let any container impersonate meta-core.
|
|
||||||
if (this.cfg.role === ROLE_CORE && p.urls) msg.urls = p.urls;
|
|
||||||
}
|
}
|
||||||
return msg;
|
return body;
|
||||||
}
|
}
|
||||||
|
|
||||||
private announce(status = 'running'): void {
|
private advertise(): void {
|
||||||
this.send(this.buildAnnounce(status));
|
this.multicast(this.advertiseMsg());
|
||||||
}
|
}
|
||||||
|
|
||||||
private replyTo(rinfo: dgram.RemoteInfo): void {
|
private replyTo(msg: BeaconMessage, rinfo: dgram.RemoteInfo): void {
|
||||||
const body = Buffer.from(JSON.stringify(this.buildAnnounce('running')));
|
|
||||||
try {
|
try {
|
||||||
this.socket?.send(body, rinfo.port, rinfo.address);
|
this.socket?.send(this.encode(msg), rinfo.port, rinfo.address);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.warn('[meshdisco] Reply failed:', e);
|
console.warn('[beacon] Reply failed:', e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Writes once per interface — the default route alone reaches one network. */
|
/** Writes once per interface — the default route alone reaches one network. */
|
||||||
private send(msg: MeshMessage): void {
|
private multicast(msg: BeaconMessage): void {
|
||||||
const socket = this.socket;
|
const socket = this.socket;
|
||||||
if (!socket) return;
|
if (!socket) return;
|
||||||
const body = Buffer.from(JSON.stringify(msg));
|
const body = this.encode(msg);
|
||||||
for (const addr of this.ifaceAddrs) {
|
for (const addr of this.ifaceAddrs) {
|
||||||
try {
|
try {
|
||||||
socket.setMulticastInterface(addr);
|
socket.setMulticastInterface(addr);
|
||||||
socket.send(body, this.cfg.port, this.cfg.group);
|
socket.send(body, this.cfg.port, this.cfg.group);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.warn(`[meshdisco] Send on ${addr} failed:`, e);
|
console.warn(`[beacon] Send on ${addr} failed:`, e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface MetaCoreLocatorConfig {
|
export interface MetaCoreLocatorConfig {
|
||||||
/** This service's name, for its own announce. */
|
/** This service's name, for its own advertise. */
|
||||||
serviceName: string;
|
serviceName: string;
|
||||||
/** Browser-facing URL for the nav menu. */
|
/** Browser-facing URL for the nav menu. */
|
||||||
baseUrl?: string;
|
baseUrl?: string;
|
||||||
version?: string;
|
version?: string;
|
||||||
/**
|
/**
|
||||||
* Explicit meta-core API URL. When set this ALWAYS wins and the wire is
|
* Explicit meta-core API URL. When set this ALWAYS wins and the wire is
|
||||||
* never consulted for core selection — see the spec's "the pin always
|
* never consulted for core selection — see the spec's "the
|
||||||
* wins". This is what stops a client box from latching onto a gateway
|
* metamesh.core pin". This is what stops a client box from latching onto a
|
||||||
* box's core when both are reachable on a shared network.
|
* gateway box's core when both are reachable on a shared network.
|
||||||
*/
|
*/
|
||||||
metaCoreUrl?: string;
|
metaCoreUrl?: string;
|
||||||
group?: string;
|
group?: string;
|
||||||
@@ -328,8 +442,9 @@ export interface MetaCoreLocatorConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Locates meta-core over UDP, replacing the read of
|
* Locates meta-core over beacon v2 (the first `metamesh.core` resource that
|
||||||
* /meta-core/locks/kv-leader.info.
|
* carries `data.urls`), and advertises this service as
|
||||||
|
* `metamesh.service/<serviceName>`.
|
||||||
*/
|
*/
|
||||||
export class MetaCoreLocator {
|
export class MetaCoreLocator {
|
||||||
private node: MeshNode;
|
private node: MeshNode;
|
||||||
@@ -341,35 +456,42 @@ export class MetaCoreLocator {
|
|||||||
this.cfg = config;
|
this.cfg = config;
|
||||||
this.node = new MeshNode({
|
this.node = new MeshNode({
|
||||||
name: config.serviceName,
|
name: config.serviceName,
|
||||||
role: ROLE_SERVICE,
|
|
||||||
version: config.version,
|
version: config.version,
|
||||||
group: config.group,
|
group: config.group,
|
||||||
port: config.port,
|
port: config.port,
|
||||||
intervalMs: config.intervalMs,
|
intervalMs: config.intervalMs,
|
||||||
enabled: config.enabled,
|
enabled: config.enabled,
|
||||||
payload: () => ({ baseUrl: config.baseUrl ?? `http://${localIPv4()}` }),
|
payload: () => ({
|
||||||
|
resources: [{
|
||||||
|
id: 'service',
|
||||||
|
caps: [CAP_SERVICE_PREFIX + config.serviceName],
|
||||||
|
endpoints: { ui: config.baseUrl ?? `http://${localIPv4()}` },
|
||||||
|
}],
|
||||||
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
this.node.onAnnounce((nb) => {
|
this.node.onAdvertise((nb) => {
|
||||||
if (nb.role !== ROLE_CORE || !nb.urls) return;
|
|
||||||
if (this.cfg.metaCoreUrl) return; // pinned: the wire cannot move us
|
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;
|
const prev = this.current;
|
||||||
if (!prev) {
|
if (!prev) {
|
||||||
this.current = nb.urls;
|
this.current = urls;
|
||||||
console.log(`[meshdisco] meta-core discovered at ${nb.urls.apiUrl} (${nb.addr})`);
|
console.log(`[beacon] meta-core discovered at ${urls.apiUrl} (${nb.addr})`);
|
||||||
this.notifyChange();
|
this.notifyChange();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (prev.apiUrl === nb.urls.apiUrl) {
|
if (prev.apiUrl === urls.apiUrl) {
|
||||||
this.current = nb.urls; // refresh the rest of the fields
|
this.current = urls; // refresh the rest of the fields
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// A second, different core is announcing. Do not flap between
|
// A second, different core is advertising. Do not flap between
|
||||||
// them — keep the first and say so loudly, because on a PCS box
|
// them — keep the first and say so loudly, because on a PCS box
|
||||||
// this means a client container can see the gateway's core.
|
// this means a client container can see the gateway's core.
|
||||||
console.warn(
|
console.warn(
|
||||||
`[meshdisco] Ignoring a second meta-core at ${nb.urls.apiUrl} (${nb.addr}); ` +
|
`[beacon] Ignoring a second meta-core at ${urls.apiUrl} (${nb.addr}); ` +
|
||||||
`staying with ${prev.apiUrl}. Set META_CORE_URL to pin this explicitly.`
|
`staying with ${prev.apiUrl}. Set META_CORE_URL to pin this explicitly.`
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
@@ -377,7 +499,7 @@ export class MetaCoreLocator {
|
|||||||
|
|
||||||
async start(): Promise<void> {
|
async start(): Promise<void> {
|
||||||
if (this.cfg.metaCoreUrl) {
|
if (this.cfg.metaCoreUrl) {
|
||||||
console.log(`[meshdisco] meta-core pinned to ${this.cfg.metaCoreUrl}; discovery is advisory`);
|
console.log(`[beacon] meta-core pinned to ${this.cfg.metaCoreUrl}; discovery is advisory`);
|
||||||
}
|
}
|
||||||
await this.node.start();
|
await this.node.start();
|
||||||
}
|
}
|
||||||
@@ -409,11 +531,11 @@ export class MetaCoreLocator {
|
|||||||
while (Date.now() < deadline) {
|
while (Date.now() < deadline) {
|
||||||
const url = this.getApiUrl();
|
const url = this.getApiUrl();
|
||||||
if (url) return url;
|
if (url) return url;
|
||||||
if (!logged) { console.log('[meshdisco] Waiting for meta-core...'); logged = true; }
|
if (!logged) { console.log('[beacon] Waiting for meta-core...'); logged = true; }
|
||||||
this.node.probe();
|
this.node.probe([CAP_CORE]);
|
||||||
await new Promise((r) => setTimeout(r, 500));
|
await new Promise((r) => setTimeout(r, 500));
|
||||||
}
|
}
|
||||||
throw new Error(`[meshdisco] No meta-core found within ${timeoutMs}ms`);
|
throw new Error(`[beacon] No meta-core found within ${timeoutMs}ms`);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Fires when the elected core's apiUrl changes. Replaces the fs.watch. */
|
/** Fires when the elected core's apiUrl changes. Replaces the fs.watch. */
|
||||||
@@ -421,21 +543,27 @@ export class MetaCoreLocator {
|
|||||||
this.changeCallbacks.push(cb);
|
this.changeCallbacks.push(cb);
|
||||||
}
|
}
|
||||||
|
|
||||||
getNeighbors(): MeshNeighbor[] {
|
/**
|
||||||
return this.node.getNeighborsByName();
|
* 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 {
|
self(): MeshNeighbor {
|
||||||
return this.node.self();
|
return this.node.self();
|
||||||
}
|
}
|
||||||
|
|
||||||
probe(): void {
|
probe(want: string[] = []): void {
|
||||||
this.node.probe();
|
this.node.probe(want);
|
||||||
}
|
}
|
||||||
|
|
||||||
private notifyChange(): void {
|
private notifyChange(): void {
|
||||||
for (const cb of this.changeCallbacks) {
|
for (const cb of this.changeCallbacks) {
|
||||||
try { cb(); } catch (e) { console.error('[meshdisco] Change callback threw:', e); }
|
try { cb(); } catch (e) { console.error('[beacon] Change callback threw:', e); }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -125,7 +125,7 @@ process.on('SIGINT', async () => {
|
|||||||
// Start initial discovery and processing (streaming pipeline)
|
// Start initial discovery and processing (streaming pipeline)
|
||||||
(async () => {
|
(async () => {
|
||||||
try {
|
try {
|
||||||
// meta-core is located over UDP (meta-discovery v1) — no /meta-core
|
// meta-core is located over UDP (beacon v2) — no /meta-core
|
||||||
// volume required. META_CORE_URL, when set, pins it and discovery
|
// volume required. META_CORE_URL, when set, pins it and discovery
|
||||||
// never overrides; see docs/project-architecture/service-discovery.md.
|
// never overrides; see docs/project-architecture/service-discovery.md.
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
* 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 locate meta-core over UDP (meta-discovery v1)
|
* 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)
|
||||||
* 4. Manages reconnection on leader changes
|
* 4. Manages reconnection on leader changes
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
/**
|
/**
|
||||||
* LeaderClient - locates meta-core and exposes its URLs.
|
* LeaderClient - locates meta-core and exposes its URLs.
|
||||||
*
|
*
|
||||||
* Since meta-discovery v1 this is a thin adapter over MetaCoreLocator
|
* Since UDP discovery (meta-discovery v1, now beacon v2) this is a thin adapter
|
||||||
|
* over MetaCoreLocator
|
||||||
* (../discovery/meshdisco.js): meta-core is found by UDP announce instead of by
|
* (../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
|
* reading /meta-core/locks/kv-leader.info, which means this service no longer
|
||||||
* needs the /meta-core volume mounted at all.
|
* needs the /meta-core volume mounted at all.
|
||||||
@@ -259,12 +260,15 @@ export class LeaderClient {
|
|||||||
return this.leaderInfo;
|
return this.leaderInfo;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Neighbours for the nav menu (one row per service name). */
|
/**
|
||||||
getNeighbors(): MeshNeighbor[] {
|
* Neighbours for /api/neighbors: one row per name (every instance with
|
||||||
return this.locator.getNeighbors();
|
* `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 announce, so the menu can show itself. */
|
/** This service's own row, so the menu can show itself. */
|
||||||
self(): MeshNeighbor {
|
self(): MeshNeighbor {
|
||||||
return this.locator.self();
|
return this.locator.self();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
* - 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
|
||||||
* Services announce and discover over UDP (meta-discovery v1); there is no
|
* Services announce and discover over UDP (beacon v2); there is no
|
||||||
* separate registration step, so no ServiceRegistration export.
|
* 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
|
||||||
|
|||||||
@@ -238,6 +238,10 @@ class MetaServiceMenu extends HTMLElement {
|
|||||||
for (const n of this._neighbors) {
|
for (const n of this._neighbors) {
|
||||||
const name = n.name || "";
|
const name = n.name || "";
|
||||||
if (!name || seen.has(name)) continue;
|
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);
|
seen.add(name);
|
||||||
rows.push(n);
|
rows.push(n);
|
||||||
}
|
}
|
||||||
@@ -275,7 +279,7 @@ class MetaServiceMenu extends HTMLElement {
|
|||||||
el.href = url;
|
el.href = url;
|
||||||
el.setAttribute("role", "menuitem");
|
el.setAttribute("role", "menuitem");
|
||||||
}
|
}
|
||||||
if (!isActive && !url) el.title = "No reachable URL announced";
|
if (!isActive && !url) el.title = "No reachable URL advertised";
|
||||||
|
|
||||||
const icon = document.createElement("span");
|
const icon = document.createElement("span");
|
||||||
icon.className = "icon";
|
icon.className = "icon";
|
||||||
@@ -285,7 +289,8 @@ class MetaServiceMenu extends HTMLElement {
|
|||||||
label.textContent = titleCase(n.name);
|
label.textContent = titleCase(n.name);
|
||||||
|
|
||||||
el.append(icon, label);
|
el.append(icon, label);
|
||||||
if (n.status === "running" || isActive) {
|
// Beacon v2 omits `status` when running.
|
||||||
|
if ((n.status || "running") === "running" || isActive) {
|
||||||
const dot = document.createElement("span");
|
const dot = document.createElement("span");
|
||||||
dot.className = "dot";
|
dot.className = "dot";
|
||||||
dot.title = n.status || "running";
|
dot.title = n.status || "running";
|
||||||
|
|||||||
@@ -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",
|
||||||
];
|
];
|
||||||
@@ -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.
|
||||||
|
|||||||
Reference in New Issue
Block a user