Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
953fcc9ff7 | ||
|
|
3d54813cf9 | ||
|
|
4b4755a9e0 | ||
|
|
bab23b89f2 | ||
|
|
b83f86c3d8 |
@@ -0,0 +1,82 @@
|
|||||||
|
# Gitea twin of .github/workflows/docker.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, master]
|
||||||
|
tags: ['v*']
|
||||||
|
pull_request:
|
||||||
|
branches: [main, master]
|
||||||
|
|
||||||
|
env:
|
||||||
|
REGISTRY: ipcr-push-85-17-246-67.nip.io
|
||||||
|
IMAGE_NAME: metadec.eth/${{ github.event.repository.name }}
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
packages: write
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Install Docker CLI
|
||||||
|
run: curl -fsSL https://download.docker.com/linux/static/stable/x86_64/docker-28.5.1.tgz | tar -xz -C /usr/local/bin --strip-components=1 docker/docker
|
||||||
|
|
||||||
|
- name: Trust the Mesh Router CA
|
||||||
|
run: printf '%s\n' "$IPCR_CA_PEM" > /tmp/ipcr-ca.pem
|
||||||
|
env:
|
||||||
|
IPCR_CA_PEM: ${{ vars.IPCR_CA_PEM }}
|
||||||
|
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
uses: docker/setup-buildx-action@v3
|
||||||
|
with:
|
||||||
|
version: latest
|
||||||
|
buildkitd-config-inline: |
|
||||||
|
[registry."${{ env.REGISTRY }}"]
|
||||||
|
ca = ["/tmp/ipcr-ca.pem"]
|
||||||
|
|
||||||
|
- name: Log in to IPCR
|
||||||
|
if: github.event_name != 'pull_request'
|
||||||
|
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
|
||||||
|
id: meta
|
||||||
|
uses: docker/metadata-action@v5
|
||||||
|
with:
|
||||||
|
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||||
|
tags: |
|
||||||
|
type=ref,event=branch
|
||||||
|
type=ref,event=pr
|
||||||
|
type=semver,pattern={{version}}
|
||||||
|
type=semver,pattern={{major}}.{{minor}}
|
||||||
|
type=sha
|
||||||
|
|
||||||
|
- name: Build and push
|
||||||
|
uses: docker/build-push-action@v5
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
push: ${{ github.event_name != 'pull_request' }}
|
||||||
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
+5
-1
@@ -33,7 +33,8 @@ import type {
|
|||||||
ConfigureRequest,
|
ConfigureRequest,
|
||||||
ConfigureResponse,
|
ConfigureResponse,
|
||||||
} from './types.js';
|
} from './types.js';
|
||||||
import { manifest, process as processFile } from './plugin.js';
|
import { manifest, process as processFile, configure } from './plugin.js';
|
||||||
|
import { startBeacon, stopBeacon } from './beacon-advertise.js';
|
||||||
|
|
||||||
const app = Fastify({ logger: true });
|
const app = Fastify({ logger: true });
|
||||||
let ready = false;
|
let ready = false;
|
||||||
@@ -53,6 +54,7 @@ app.get('/manifest', async () => manifest);
|
|||||||
app.post<{ Body: ConfigureRequest }>('/configure', async (request): Promise<ConfigureResponse> => {
|
app.post<{ Body: ConfigureRequest }>('/configure', async (request): Promise<ConfigureResponse> => {
|
||||||
try {
|
try {
|
||||||
pluginConfig = request.body.config || {};
|
pluginConfig = request.body.config || {};
|
||||||
|
configure(pluginConfig);
|
||||||
console.log('[file-info] Configuration updated');
|
console.log('[file-info] Configuration updated');
|
||||||
return { status: 'ok' };
|
return { status: 'ok' };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -90,12 +92,14 @@ const port = parseInt(process.env.PORT || '8080', 10);
|
|||||||
const host = process.env.HOST || '0.0.0.0';
|
const host = process.env.HOST || '0.0.0.0';
|
||||||
|
|
||||||
app.listen({ port, host }).then(() => {
|
app.listen({ port, host }).then(() => {
|
||||||
|
startBeacon(manifest.id, manifest.version, port);
|
||||||
ready = true;
|
ready = true;
|
||||||
console.log(`[file-info] Plugin listening on http://${host}:${port}`);
|
console.log(`[file-info] Plugin listening on http://${host}:${port}`);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Graceful shutdown
|
// Graceful shutdown
|
||||||
process.on('SIGTERM', async () => {
|
process.on('SIGTERM', async () => {
|
||||||
|
await stopBeacon();
|
||||||
ready = false;
|
ready = false;
|
||||||
await app.close();
|
await app.close();
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
|
|||||||
+55
-2
@@ -105,9 +105,57 @@ export const manifest: PluginManifest = {
|
|||||||
readonly: true,
|
readonly: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
config: {},
|
config: {
|
||||||
|
forceRecompute: { type: 'boolean', label: 'Force Recompute', default: false },
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** Overwrite `fileName` even when another writer already set one. Default off. */
|
||||||
|
let forceRecompute = false;
|
||||||
|
|
||||||
|
export function configure(config: Record<string, unknown>): void {
|
||||||
|
forceRecompute = config.forceRecompute === true;
|
||||||
|
console.log(`[file-info] Config: forceRecompute=${forceRecompute}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether we may write `fileName` on this record.
|
||||||
|
*
|
||||||
|
* `fileName` has **two writers** (METADATA_KEYS.md §`fileName`): this plugin,
|
||||||
|
* which knows the on-disk basename, and the indexer feeders, which emit the raw
|
||||||
|
* release string at ingest. They meet on one record whenever meta-share
|
||||||
|
* materialises a search hit into a tree meta-core watches — the bytes' midhash
|
||||||
|
* is the record's content CID, so this plugin lands on the record the feeder
|
||||||
|
* already wrote.
|
||||||
|
*
|
||||||
|
* A Usenet posting's on-disk name is the poster's, and posters obfuscate it
|
||||||
|
* (`9765de45fa2d4522a80d01363d3c0919.mkv`). Writing it unconditionally destroyed
|
||||||
|
* the only readable name the record had, in a last-writer-wins race that showed
|
||||||
|
* up as hex on meta-watch's source rows.
|
||||||
|
*
|
||||||
|
* Precedence, mirroring the `still` rule the registry already legislates: the
|
||||||
|
* writer that knows less yields, and it yields by skipping a record that already
|
||||||
|
* carries a value. We know less — a basename is a container's filing detail,
|
||||||
|
* a release string is the release's identity.
|
||||||
|
*
|
||||||
|
* The record is re-read over the network rather than trusted from
|
||||||
|
* `existingMeta`: that map is delivered nested for grouped keys, and it is
|
||||||
|
* snapshotted before dispatch. `existingMeta` is the fallback for standalone /
|
||||||
|
* test mode, where `getProperty` cannot reach meta-core and answers `null`.
|
||||||
|
*/
|
||||||
|
async function mayWriteFileName(
|
||||||
|
metaCore: MetaCoreClient,
|
||||||
|
request: ProcessRequest,
|
||||||
|
cid: string,
|
||||||
|
fileName: string
|
||||||
|
): Promise<boolean> {
|
||||||
|
if (forceRecompute) return true;
|
||||||
|
const existing = (await metaCore.getProperty(cid, 'fileName')) ?? request.existingMeta?.fileName ?? null;
|
||||||
|
if (!existing || existing === fileName) return true;
|
||||||
|
console.log(`[file-info] Keeping existing fileName "${existing}" (not overwriting with "${fileName}")`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
export async function process(
|
export async function process(
|
||||||
request: ProcessRequest,
|
request: ProcessRequest,
|
||||||
sendCallback: (payload: CallbackPayload) => Promise<void>
|
sendCallback: (payload: CallbackPayload) => Promise<void>
|
||||||
@@ -165,7 +213,12 @@ export async function process(
|
|||||||
await metaCore.setProperty(cid, 'mimeType', mimeType);
|
await metaCore.setProperty(cid, 'mimeType', mimeType);
|
||||||
}
|
}
|
||||||
await metaCore.setProperty(cid, 'sizeByte', String(fileSize));
|
await metaCore.setProperty(cid, 'sizeByte', String(fileSize));
|
||||||
await metaCore.setProperty(cid, 'fileName', fileName);
|
if (await mayWriteFileName(metaCore, request, cid, fileName)) {
|
||||||
|
await metaCore.setProperty(cid, 'fileName', fileName);
|
||||||
|
}
|
||||||
|
// `extension` is unguarded on purpose: METADATA_KEYS.md names exactly one
|
||||||
|
// writer for it (this plugin), so there is nothing to yield to — and it
|
||||||
|
// describes the bytes on disk, which is precisely what we are looking at.
|
||||||
await metaCore.setProperty(cid, 'extension', extension);
|
await metaCore.setProperty(cid, 'extension', extension);
|
||||||
|
|
||||||
const duration = Date.now() - startTime;
|
const duration = Date.now() - startTime;
|
||||||
|
|||||||
@@ -0,0 +1,179 @@
|
|||||||
|
/**
|
||||||
|
* `fileName` precedence regression tests.
|
||||||
|
*
|
||||||
|
* `fileName` has two writers (METADATA_KEYS.md §`fileName`): this plugin, which
|
||||||
|
* knows a file's on-disk basename, and the indexer feeders, which emit the raw
|
||||||
|
* release string at ingest. They collide on one record whenever meta-share
|
||||||
|
* materialises a search hit into a tree meta-core watches.
|
||||||
|
*
|
||||||
|
* The regression these guard: a Usenet posting's on-disk name is the poster's,
|
||||||
|
* and posters obfuscate it — writing it unconditionally replaced the readable
|
||||||
|
* release string with `9765de45fa2d4522a80d01363d3c0919.mkv` on a record the
|
||||||
|
* whole UI reads.
|
||||||
|
*
|
||||||
|
* These drive the real write path against a stand-in meta-core, so they assert
|
||||||
|
* what is actually PUT rather than what the callback says.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest';
|
||||||
|
import * as http from 'http';
|
||||||
|
import { promises as fs } from 'fs';
|
||||||
|
import * as path from 'path';
|
||||||
|
import * as os from 'os';
|
||||||
|
|
||||||
|
let processFile: typeof import('../src/plugin.js').process;
|
||||||
|
let configure: typeof import('../src/plugin.js').configure;
|
||||||
|
|
||||||
|
/** Properties the stand-in meta-core currently holds, per cid. */
|
||||||
|
let record: Record<string, string>;
|
||||||
|
/** Every `PUT /meta/{cid}/{key}` the plugin made, in order. */
|
||||||
|
let writes: Array<{ key: string; value: string }>;
|
||||||
|
|
||||||
|
let server: http.Server;
|
||||||
|
let metaCoreUrl: string;
|
||||||
|
let testDir: string;
|
||||||
|
/** A file whose basename is the obfuscated shape a Usenet poster produces. */
|
||||||
|
let obfuscatedFile: string;
|
||||||
|
|
||||||
|
const OBFUSCATED = '9765de45fa2d4522a80d01363d3c0919.mkv';
|
||||||
|
const RELEASE = 'The.Magical.Revolution.of.the.Reincarnated.Princess-S01E09';
|
||||||
|
|
||||||
|
const noopCallback = async (): Promise<void> => {};
|
||||||
|
|
||||||
|
/** Run the plugin over the obfuscated-named file against the stand-in meta-core. */
|
||||||
|
async function run(cid: string, existingMeta: Record<string, string> = {}): Promise<void> {
|
||||||
|
await processFile(
|
||||||
|
{
|
||||||
|
taskId: `task-${cid}`,
|
||||||
|
cid,
|
||||||
|
filePath: obfuscatedFile,
|
||||||
|
callbackUrl: 'http://localhost/callback',
|
||||||
|
metaCoreUrl,
|
||||||
|
existingMeta,
|
||||||
|
},
|
||||||
|
noopCallback
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const written = (key: string): string | undefined => writes.find((w) => w.key === key)?.value;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
const plugin = await import('../src/plugin.js');
|
||||||
|
processFile = plugin.process;
|
||||||
|
configure = plugin.configure;
|
||||||
|
|
||||||
|
testDir = await fs.mkdtemp(path.join(os.tmpdir(), 'file-info-guard-'));
|
||||||
|
obfuscatedFile = path.join(testDir, OBFUSCATED);
|
||||||
|
await fs.writeFile(obfuscatedFile, 'fake video content');
|
||||||
|
|
||||||
|
// Stand-in meta-core: just enough of the property API for this plugin.
|
||||||
|
server = http.createServer((req, res) => {
|
||||||
|
const url = new URL(req.url ?? '/', 'http://localhost');
|
||||||
|
const parts = url.pathname.split('/').filter(Boolean); // ['meta', cid, key?]
|
||||||
|
const key = parts[2];
|
||||||
|
if (req.method === 'GET' && key) {
|
||||||
|
const value = record[key];
|
||||||
|
if (value === undefined) {
|
||||||
|
res.writeHead(404).end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ value }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (req.method === 'PUT' && key) {
|
||||||
|
let body = '';
|
||||||
|
req.on('data', (c) => (body += c));
|
||||||
|
req.on('end', () => {
|
||||||
|
const value = String(JSON.parse(body || '{}').value ?? '');
|
||||||
|
writes.push({ key, value });
|
||||||
|
record[key] = value;
|
||||||
|
res.writeHead(200, { 'Content-Type': 'application/json' }).end('{}');
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res.writeHead(200, { 'Content-Type': 'application/json' }).end('{}');
|
||||||
|
});
|
||||||
|
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||||
|
const addr = server.address() as { port: number };
|
||||||
|
metaCoreUrl = `http://127.0.0.1:${addr.port}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||||
|
await fs.rm(testDir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
record = {};
|
||||||
|
writes = [];
|
||||||
|
configure({}); // forceRecompute defaults back to off
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('fileName precedence', () => {
|
||||||
|
it('never overwrites a release string a feeder already wrote', async () => {
|
||||||
|
record.fileName = RELEASE;
|
||||||
|
|
||||||
|
await run('cid-feeder-wrote-first');
|
||||||
|
|
||||||
|
expect(written('fileName')).toBeUndefined();
|
||||||
|
expect(record.fileName).toBe(RELEASE);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('still writes every key it owns when it yields on fileName', async () => {
|
||||||
|
record.fileName = RELEASE;
|
||||||
|
|
||||||
|
await run('cid-other-keys-survive');
|
||||||
|
|
||||||
|
// `extension` has exactly one writer, so it is never withheld — and it
|
||||||
|
// describes the bytes on disk, which is what this plugin is looking at.
|
||||||
|
expect(written('extension')).toBe('mkv');
|
||||||
|
expect(written('sizeByte')).toBe('18');
|
||||||
|
expect(written('fileType')).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('writes fileName when the record carries none', async () => {
|
||||||
|
await run('cid-first-sighting');
|
||||||
|
|
||||||
|
expect(written('fileName')).toBe(OBFUSCATED);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('writes fileName when the record already holds the same value', async () => {
|
||||||
|
record.fileName = OBFUSCATED;
|
||||||
|
|
||||||
|
await run('cid-same-value');
|
||||||
|
|
||||||
|
expect(record.fileName).toBe(OBFUSCATED);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('overwrites when forceRecompute is on', async () => {
|
||||||
|
record.fileName = RELEASE;
|
||||||
|
configure({ forceRecompute: true });
|
||||||
|
|
||||||
|
await run('cid-forced');
|
||||||
|
|
||||||
|
expect(written('fileName')).toBe(OBFUSCATED);
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Standalone / test mode: `getProperty` cannot reach meta-core and answers
|
||||||
|
* `null` for both "absent" and "unreachable", so the dispatch snapshot is
|
||||||
|
* the only evidence left that someone else owns the key.
|
||||||
|
*/
|
||||||
|
it('falls back to existingMeta when meta-core is unreachable', async () => {
|
||||||
|
const unreachable = 'http://127.0.0.1:1';
|
||||||
|
await processFile(
|
||||||
|
{
|
||||||
|
taskId: 'task-offline',
|
||||||
|
cid: 'cid-offline',
|
||||||
|
filePath: obfuscatedFile,
|
||||||
|
callbackUrl: 'http://localhost/callback',
|
||||||
|
metaCoreUrl: unreachable,
|
||||||
|
existingMeta: { fileName: RELEASE },
|
||||||
|
},
|
||||||
|
noopCallback
|
||||||
|
);
|
||||||
|
|
||||||
|
// Nothing reached our stand-in meta-core, and nothing threw.
|
||||||
|
expect(writes).toHaveLength(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user