2 Commits
Author SHA1 Message Date
Worph e788537907 advertise over beacon v2 as metamesh.enrich/<id> so meta-sort's Plugins page can find it (Scan -> Add)
Build and Push Docker Image / build (push) Failing after 16s
2026-10-04 17:19:20 +00:00
Worph 2fd0099eee improve search and fix languages
Build and Push Docker Image / build (push) Failing after 17s
2026-09-14 22:29:58 +02:00
4 changed files with 295 additions and 26 deletions
+188
View File
@@ -0,0 +1,188 @@
/**
* Beacon v2 advertiser — makes this plugin findable by meta-sort's Plugins
* page (Scan → Add) without anyone typing its URL.
*
* Advertises one resource, cap `metamesh.enrich/<manifest id>`, on the beacon
* group (239.255.99.1:9099): unsolicited every 10 s, and unicast in reply to
* any probe whose `want` matches. Says `bye` on shutdown. It keeps no view of
* other nodes — a plugin only needs to be found. Spec:
* meta-root docs/project-architecture/beacon-v2.md.
*
* Env:
* ENABLE_UDP_DISCOVERY false/0/no/off disables
* BEACON_ADVERTISE_URL endpoints.http (default http://$HOSTNAME:$PORT)
* BEACON_BINDS the one meta-sort instance allowed to list it
* (meta-sort sets this on containers it spawns)
* BEACON_GROUP / BEACON_PORT / BEACON_INTERVAL_MS
*
* ⚠ MIRRORED FILE. Byte-identical copies live in every TypeScript
* metamesh-plugin-*; see meta-root `scripts/check-mirrors.sh`. Never fatal: a
* host that blocks multicast logs a warning and the plugin serves on.
*/
import dgram from 'dgram';
import { hostname, networkInterfaces } from 'os';
const PROTO = 'beacon';
const VERSION = 2;
interface Resource {
id: string;
caps: string[];
endpoints: Record<string, string>;
binds?: string;
}
interface NodeInfo {
name: string;
instance: string;
version?: string;
}
function envNum(key: string): number | undefined {
const n = Number(process.env[key]);
return Number.isFinite(n) && n > 0 ? n : undefined;
}
function enabled(): boolean {
const v = (process.env.ENABLE_UDP_DISCOVERY ?? '').trim().toLowerCase();
return !['false', '0', 'no', 'off'].includes(v);
}
/** IPv4 addresses of every up, non-internal interface. */
function interfaceAddresses(): string[] {
const out: string[] = [];
for (const list of Object.values(networkInterfaces())) {
for (const ni of list ?? []) {
const v4 = (ni as { family: string | number }).family === 'IPv4' || (ni as { family: string | number }).family === 4;
if (v4 && !ni.internal && ni.address) out.push(ni.address);
}
}
return out;
}
/** Same matching rules as the spec: `*`, `x/*`, optional `@contract`. */
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 [pb, pc] = split(pattern);
const [cb, cc] = split(cap);
if (pc !== null && cc !== pc) return false;
if (pb.endsWith('/*')) {
const prefix = pb.slice(0, -2);
const rest = cb.startsWith(prefix) ? cb.slice(prefix.length) : '';
return rest.startsWith('/') && rest.length > 1;
}
return pb === cb;
}
let socket: dgram.Socket | null = null;
let timer: NodeJS.Timeout | null = null;
let node: NodeInfo | null = null;
let resource: Resource | null = null;
let ifaces: string[] = [];
let group = '239.255.99.1';
let udpPort = 9099;
function send(msg: object, dest?: { address: string; port: number }): void {
const s = socket;
if (!s) return;
const body = Buffer.from(JSON.stringify(msg));
if (dest) {
s.send(body, dest.port, dest.address, () => {});
return;
}
// Once per interface: the default route alone reaches one network.
for (const addr of ifaces) {
try {
s.setMulticastInterface(addr);
s.send(body, udpPort, group, () => {});
} catch (e) {
console.warn(`[beacon] send on ${addr} failed:`, e);
}
}
}
function advertise(dest?: { address: string; port: number }): void {
if (!node || !resource) return;
send({ proto: PROTO, v: VERSION, type: 'advertise', node, resources: [resource] }, dest);
}
/**
* Start advertising this plugin. Call once the HTTP server is listening, so a
* consumer that hears it can reach it. Idempotent.
*/
export function startBeacon(pluginId: string, version: string, httpPort: number): void {
if (socket || !enabled()) return;
group = process.env.BEACON_GROUP || group;
udpPort = envNum('BEACON_PORT') ?? udpPort;
const intervalMs = envNum('BEACON_INTERVAL_MS') ?? 10_000;
const instance = process.env.HOSTNAME || hostname();
const url = (process.env.BEACON_ADVERTISE_URL || `http://${instance}:${httpPort}`).replace(/\/+$/, '');
const binds = (process.env.BEACON_BINDS || '').trim();
node = { name: `metamesh-plugin-${pluginId}`, instance, ...(version ? { version } : {}) };
resource = {
id: pluginId,
caps: [`metamesh.enrich/${pluginId}`],
endpoints: { http: url, manifest: '/manifest' },
...(binds ? { binds } : {}),
};
const s = dgram.createSocket({ type: 'udp4', reuseAddr: true });
socket = s;
s.on('error', (err) => console.warn('[beacon] socket error:', err.message));
s.on('message', (buf, rinfo) => {
let m: { proto?: string; v?: number; type?: string; from?: string; want?: string[] };
try {
m = JSON.parse(buf.toString('utf8'));
} catch {
return; // foreign traffic on the shared group
}
if (m?.proto !== PROTO || m.v !== VERSION || m.type !== 'probe' || m.from === instance) return;
const want = Array.isArray(m.want) ? m.want : [];
if (want.length === 0 || resource!.caps.some((c) => want.some((p) => capMatches(p, c)))) {
advertise({ address: rinfo.address, port: rinfo.port });
}
});
s.bind(udpPort, '0.0.0.0', () => {
try {
s.setMulticastTTL(1);
} catch {
/* best effort */
}
ifaces = interfaceAddresses();
for (const addr of ifaces) {
try {
s.addMembership(group, addr);
} catch (e) {
console.warn(`[beacon] join ${group} on ${addr} failed:`, e);
}
}
console.log(`[beacon] advertising metamesh.enrich/${pluginId} at ${url} on ${group}:${udpPort}`);
advertise();
timer = setInterval(() => advertise(), intervalMs);
timer.unref?.();
});
}
/** Say `bye` so consumers drop this plugin at once. */
export async function stopBeacon(): Promise<void> {
if (!socket || !node) return;
if (timer) clearInterval(timer);
send({ proto: PROTO, v: VERSION, type: 'bye', node });
// Let the bye datagrams leave before the socket closes under them.
await new Promise((r) => setTimeout(r, 50));
const s = socket;
socket = null;
await new Promise<void>((resolve) => {
try {
s.close(() => resolve());
} catch {
resolve();
}
});
}
+3 -2
View File
@@ -24,6 +24,7 @@
import Fastify from 'fastify';
import type { HealthResponse, ProcessRequest, ProcessResponse, CallbackPayload, ConfigureRequest, ConfigureResponse } from './types.js';
import { manifest, process as processFile } from './plugin.js';
import { startBeacon, stopBeacon } from './beacon-advertise.js';
const app = Fastify({ logger: true });
let ready = false;
@@ -47,5 +48,5 @@ app.post<{ Body: ProcessRequest }>('/process', async (request, reply) => {
});
const port = parseInt(process.env.PORT || '8080', 10);
app.listen({ port, host: '0.0.0.0' }).then(() => { ready = true; console.log(`[${manifest.id}] Listening on port ${port}`); });
process.on('SIGTERM', async () => { ready = false; await app.close(); process.exit(0); });
app.listen({ port, host: '0.0.0.0' }).then(() => { startBeacon(manifest.id, manifest.version, port); ready = true; console.log(`[${manifest.id}] Listening on port ${port}`); });
process.on('SIGTERM', async () => { await stopBeacon(); ready = false; await app.close(); process.exit(0); });
+40 -15
View File
@@ -21,11 +21,17 @@
* Matroska stream tags already carry. A `fra` member would be dropped by a
* `languages:fre` filter.
*
* ⚠ Audio only. Consumers read `languages/*` as the AUDIO-language set
* (meta-watch `cards::audio_languages`); subtitle-track languages belong to
* `subtitleLanguages/*` (subtitle-extractor). Title keys are not a source
* either: `titles/<lang>` names the language of a TITLE (tmdb files
* `originalTitle` under `original_language`), not of the file's audio.
* ⚠ Audio only as a SOURCE — but it writes two keys, not one. This plugin reads
* audio tracks, so the codes it finds are audio languages and land in
* `audioLanguages/<lang3>`; every one of them is ALSO written to
* `languages/<lang3>`, the union that queries filter on (METADATA_KEYS §9,
* rule #7 — "a union field is written, never computed"). Nothing reconciles the
* two after the fact, so a record with the split set and the union unset is
* invisible to every language filter on every peer. Subtitle-track languages
* belong to `subtitleLanguages/*` (subtitle-extractor), which owes the union
* member for the same reason. Title keys are not a source either:
* `titles/<lang>` names the language of a TITLE (tmdb files `originalTitle`
* under `original_language`), not of the file's audio.
*
* ⚠ No `titles/*` write. The old `titles/{firstAudioLang || 'eng'}` =
* `originalTitle` guess overwrote better identity (tmdb, jellyfin-nfo,
@@ -41,8 +47,8 @@ import { MetaCoreClient } from './meta-core-client.js';
export const manifest: PluginManifest = {
id: 'language',
name: 'Language Aggregator',
version: '1.1.0',
description: 'Adds audio-track languages to the languages/<lang3> key-set',
version: '1.2.0',
description: 'Adds audio-track languages to the audioLanguages/<lang3> and languages/<lang3> key-sets',
author: 'MetaMesh',
dependencies: ['ffmpeg'],
priority: 40,
@@ -50,6 +56,7 @@ export const manifest: PluginManifest = {
defaultQueue: 'fast',
timeout: 30000,
schema: {
audioLanguages: { label: 'Audio languages', type: 'array', readonly: true },
languages: { label: 'Languages', type: 'array', readonly: true },
},
config: {},
@@ -170,23 +177,41 @@ export function audioLanguagesFromMeta(existingMeta: Record<string, unknown> | u
}
/**
* Whether the record already carries `languages/<code>`, in either shape: the
* flat key, or the nested `languages: { <code>: ... }` object meta-sort's
* reconstructed document holds.
* Whether the record already carries `<field>/<code>`, in either shape: the flat
* key, or the nested `<field>: { <code>: ... }` object meta-sort's reconstructed
* document holds.
*/
function hasMember(existingMeta: Record<string, unknown> | undefined, code: string): boolean {
function hasMember(
existingMeta: Record<string, unknown> | undefined,
field: string,
code: string,
): boolean {
if (!existingMeta) return false;
if (existingMeta[`languages/${code}`] !== undefined) return true;
const nested = existingMeta['languages'];
if (existingMeta[`${field}/${code}`] !== undefined) return true;
const nested = existingMeta[field];
return !!nested && typeof nested === 'object' && !Array.isArray(nested)
&& (nested as Record<string, unknown>)[code] !== undefined;
}
/** The `languages/<code>` members to add — never one the record already has. */
/**
* The members to add — never one the record already has.
*
* Each audio code is written TWICE: once to `audioLanguages/<code>` (what this
* plugin actually observed — a spoken track) and once to `languages/<code>`
* (the union every query filters on). METADATA_KEYS §9 rule #7 makes the second
* write mandatory, not a convenience: the union is stored, never computed, and
* a query cannot ask for `audioLanguages OR subtitleLanguages` — the gateway
* wire ANDs across keys, so an OR of the splits would return strictly less.
*/
export function languageWrites(existingMeta: Record<string, unknown> | undefined): Record<string, string> {
const writes: Record<string, string> = {};
for (const code of audioLanguagesFromMeta(existingMeta)) {
if (!hasMember(existingMeta, code)) writes[`languages/${code}`] = 'true';
if (!hasMember(existingMeta, 'audioLanguages', code)) {
writes[`audioLanguages/${code}`] = 'true';
}
if (!hasMember(existingMeta, 'languages', code)) {
writes[`languages/${code}`] = 'true';
}
}
return writes;
}
+64 -9
View File
@@ -164,18 +164,47 @@ describe('audioLanguagesFromMeta', () => {
});
describe('languageWrites', () => {
it('skips members already present in the flat or nested form', () => {
expect(languageWrites(nestedDoc({ 'languages/jpn': 'true' }))).toEqual({ 'languages/eng': 'true' });
expect(languageWrites(nestedDoc({ languages: { eng: 'true', jpn: true } }))).toEqual({});
it('writes each audio code to BOTH the split and the union (METADATA_KEYS §9 rule #7)', () => {
expect(languageWrites(nestedDoc())).toEqual({
'audioLanguages/jpn': 'true',
'languages/jpn': 'true',
'audioLanguages/eng': 'true',
'languages/eng': 'true',
});
});
it('skips members already present in the flat or nested form, per field', () => {
// The union is already there; the split is not — the record still owes
// the split, and vice versa. The two are tracked independently.
expect(languageWrites(nestedDoc({ 'languages/jpn': 'true' }))).toEqual({
'audioLanguages/jpn': 'true',
'audioLanguages/eng': 'true',
'languages/eng': 'true',
});
expect(languageWrites(nestedDoc({ languages: { eng: 'true', jpn: true } }))).toEqual({
'audioLanguages/jpn': 'true',
'audioLanguages/eng': 'true',
});
expect(
languageWrites(nestedDoc({ audioLanguages: { eng: 'true', jpn: 'true' }, languages: { eng: 'true', jpn: 'true' } })),
).toEqual({});
});
});
describe('process', () => {
it('writes the audio languages/* key-set from the nested payload in one merge', async () => {
it('writes the audio split AND the union from the nested payload in one merge', async () => {
const { callback, writer } = await run(nestedDoc());
expect(callback?.status).toBe('completed');
expect(writer.calls).toEqual([
{ hashId: 'cid-1', metadata: { 'languages/jpn': 'true', 'languages/eng': 'true' } },
{
hashId: 'cid-1',
metadata: {
'audioLanguages/jpn': 'true',
'languages/jpn': 'true',
'audioLanguages/eng': 'true',
'languages/eng': 'true',
},
},
]);
});
@@ -183,14 +212,27 @@ describe('process', () => {
const flat = Object.fromEntries(REAL_STREAMS.map((s, i) => [`stream/${i}`, s]));
const { callback, writer } = await run(flat);
expect(callback?.status).toBe('completed');
expect(writer.calls[0].metadata).toEqual({ 'languages/jpn': 'true', 'languages/eng': 'true' });
expect(writer.calls[0].metadata).toEqual({
'audioLanguages/jpn': 'true',
'languages/jpn': 'true',
'audioLanguages/eng': 'true',
'languages/eng': 'true',
});
});
it('never writes titles/* or any non-languages key, even with originalTitle and title keys', async () => {
it('every split member has a matching union member — the record is never left half-written', async () => {
const { writer } = await run(nestedDoc());
const keys = writer.calls.flatMap((c) => Object.keys(c.metadata));
for (const k of keys.filter((k) => k.startsWith('audioLanguages/'))) {
expect(keys).toContain(`languages/${k.slice('audioLanguages/'.length)}`);
}
});
it('never writes titles/* or any non-language key, even with originalTitle and title keys', async () => {
const { writer } = await run(nestedDoc({ 'titles/eng/Better Title': 'true', titles: { jpn: { '番組': 'true' } } }));
const keys = writer.calls.flatMap((c) => Object.keys(c.metadata));
expect(keys.length).toBeGreaterThan(0);
expect(keys.every((k) => k.startsWith('languages/'))).toBe(true);
expect(keys.every((k) => k.startsWith('languages/') || k.startsWith('audioLanguages/'))).toBe(true);
expect(keys.some((k) => k.startsWith('titles'))).toBe(false);
});
@@ -209,10 +251,23 @@ describe('process', () => {
});
it('is idempotent: a re-run over a record that already has the members writes nothing', async () => {
const { writer } = await run(nestedDoc({ 'languages/jpn': 'true', 'languages/eng': 'true' }));
const { writer } = await run(nestedDoc({
'audioLanguages/jpn': 'true', 'audioLanguages/eng': 'true',
'languages/jpn': 'true', 'languages/eng': 'true',
}));
expect(writer.calls).toEqual([]);
});
it('backfills the union on a record written before the split existed', async () => {
// Pre-1.2.0 records carry only `languages/*`. A re-run must add the
// split without disturbing the union that is already correct.
const { writer } = await run(nestedDoc({ 'languages/jpn': 'true', 'languages/eng': 'true' }));
expect(writer.calls[0].metadata).toEqual({
'audioLanguages/jpn': 'true',
'audioLanguages/eng': 'true',
});
});
it('fails the task when the write is rejected', async () => {
const { callback } = await run(nestedDoc(), new RecordingWriter(false));
expect(callback?.status).toBe('failed');