fffleet 2.8.0 → 2.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.d.ts +45 -4
- package/package.json +1 -1
- package/server.d.ts +25 -1
- package/src/auth.js +122 -17
- package/src/capabilities.js +5 -0
- package/src/client.js +4 -2
- package/src/contract.js +44 -2
- package/src/executor.js +45 -3
- package/src/flash-analysis.js +269 -0
- package/src/http-api.js +11 -3
- package/src/index.js +2 -0
- package/src/job-manager.js +2 -1
- package/src/server.js +1 -1
- package/src/types.js +4 -1
package/index.d.ts
CHANGED
|
@@ -23,8 +23,10 @@ export interface Endpoint {
|
|
|
23
23
|
* output folder) or a live scheme such as rtmp:, srt:, udp:.
|
|
24
24
|
*/
|
|
25
25
|
uri: string;
|
|
26
|
-
/** Content-Type sent when an http(s) output is uploaded. */
|
|
26
|
+
/** Content-Type sent when an http(s) output is uploaded; for an inline: output, the type of its result. */
|
|
27
27
|
contentType?: string;
|
|
28
|
+
/** inline: outputs only: the largest result accepted, in bytes (default 1 MiB, at most 8 MiB). A larger one fails the job. */
|
|
29
|
+
maxBytes?: number;
|
|
28
30
|
}
|
|
29
31
|
|
|
30
32
|
/** What a client submits. Only `kind` and `ffmpeg.args` are required. */
|
|
@@ -63,6 +65,8 @@ export interface JobSpecInput {
|
|
|
63
65
|
ffmpeg?: { args: string[]; durationMs?: number | null };
|
|
64
66
|
/** For `type: 'ffprobe'`: which sections to print (default format and streams). */
|
|
65
67
|
ffprobe?: { show?: ('format' | 'streams' | 'chapters' | 'programs')[] };
|
|
68
|
+
/** For `type: 'flash-analysis'` (the payload is named after the type): see FlashAnalysisOptions. */
|
|
69
|
+
'flash-analysis'?: FlashAnalysisOptions;
|
|
66
70
|
[section: string]: unknown;
|
|
67
71
|
}
|
|
68
72
|
|
|
@@ -122,8 +126,24 @@ export interface OutputResult {
|
|
|
122
126
|
name: string;
|
|
123
127
|
uri: string;
|
|
124
128
|
bytes: number | null;
|
|
125
|
-
/**
|
|
129
|
+
/** The output's content type, when the spec gave one (inline: outputs and flash-analysis reports). */
|
|
130
|
+
contentType?: string;
|
|
131
|
+
/** Small JSON result returned inline (`uri: 'inline:'` with a JSON content type, or a probe/report). */
|
|
126
132
|
data?: unknown;
|
|
133
|
+
/** Small non-JSON result returned inline, base64-encoded (`uri: 'inline:'`). */
|
|
134
|
+
base64?: string;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** The `flash-analysis` payload of a `type: 'flash-analysis'` job. Reports facts; the verdict is the consumer's. */
|
|
138
|
+
export interface FlashAnalysisOptions {
|
|
139
|
+
/** Only "wcag-2.3.1" for now. */
|
|
140
|
+
standard?: 'wcag-2.3.1';
|
|
141
|
+
/** Frames per second sampled from the video, 1 to 60 (default 25). */
|
|
142
|
+
sampleFps?: number;
|
|
143
|
+
/** Width the frames are scaled to before measuring, 16 to 512 (default 64). */
|
|
144
|
+
width?: number;
|
|
145
|
+
/** Only analyse the first N seconds of the input. */
|
|
146
|
+
maxSeconds?: number | null;
|
|
127
147
|
}
|
|
128
148
|
|
|
129
149
|
export interface JobEvent {
|
|
@@ -271,6 +291,18 @@ export function normalizeKinds(kinds?: JobKind[] | string): JobKind[];
|
|
|
271
291
|
export function autoSlots(opts?: { cpus?: number; kinds?: JobKind[]; coresPerSlot?: number }): Record<string, number>;
|
|
272
292
|
export function runFfmpegJob(spec: JobSpec & { id: string }, runtime: ExecutorRuntime): Promise<Required<ExecutorResult>>;
|
|
273
293
|
export function runFfprobeJob(spec: JobSpec & { id: string }, runtime: ExecutorRuntime & { ffprobePath?: string }): Promise<Required<ExecutorResult>>;
|
|
294
|
+
export function runFlashAnalysisJob(spec: JobSpec & { id: string }, runtime: ExecutorRuntime & { ffprobePath?: string }): Promise<Required<ExecutorResult>>;
|
|
295
|
+
export function parseFlashOptions(input: unknown): Required<FlashAnalysisOptions>;
|
|
296
|
+
export function buildReport(luma: number[], red: number[], options: Required<FlashAnalysisOptions>): Record<string, unknown>;
|
|
297
|
+
export function flashesOf(series: number[], sampleFps: number): { start: number, end: number }[];
|
|
298
|
+
export function frameMetrics(frame: Uint8Array, pixels: number): { luma: number, red: number };
|
|
299
|
+
export const FLASH_STANDARD: 'wcag-2.3.1';
|
|
300
|
+
export const INLINE_SCHEME: 'inline:';
|
|
301
|
+
export const INLINE_CAPABILITY: 'result:inline';
|
|
302
|
+
export const INLINE_DEFAULT_MAX_BYTES: number;
|
|
303
|
+
export const INLINE_MAX_BYTES: number;
|
|
304
|
+
export function isInline(endpoint: Endpoint): boolean;
|
|
305
|
+
export function withoutInlinePayload<T extends { data?: unknown, base64?: string }>(output: T): Omit<T, 'data' | 'base64'>;
|
|
274
306
|
|
|
275
307
|
export class JobHandle extends EventEmitter {
|
|
276
308
|
readonly id: string;
|
|
@@ -304,6 +336,10 @@ export interface FleetOptions {
|
|
|
304
336
|
/** With `clientSecret`: log in at the orchestrator (POST /v1/auth/token) and refresh the token before it expires. */
|
|
305
337
|
clientId?: string;
|
|
306
338
|
clientSecret?: string;
|
|
339
|
+
/** With `clientId`/`clientSecret`: get tokens from this OAuth2 token endpoint (an external issuer) instead of the orchestrator's own. */
|
|
340
|
+
tokenUrl?: string;
|
|
341
|
+
/** Resource indicator (RFC 8707) sent with the token request, for issuers that bind tokens to an audience. */
|
|
342
|
+
tokenResource?: string;
|
|
307
343
|
/** Narrow the token to some of the app's scopes, e.g. 'jobs'. */
|
|
308
344
|
scope?: string;
|
|
309
345
|
/** 'local' (default) runs a job here when the remote cannot be reached or answers 502/503. */
|
|
@@ -377,7 +413,7 @@ export class JobRecord {
|
|
|
377
413
|
export function byPriority(a: JobRecord, b: JobRecord): number;
|
|
378
414
|
export function pruneFinished(jobs: Map<string, JobRecord>, keep: number): void;
|
|
379
415
|
|
|
380
|
-
export type Scope = 'jobs' | 'metrics' | 'admin';
|
|
416
|
+
export type Scope = 'jobs' | 'metrics' | 'admin' | 'worker' | 'dispatch';
|
|
381
417
|
export const SCOPES: readonly Scope[];
|
|
382
418
|
/** Hashes a client secret for the clients file (`scrypt$...`). */
|
|
383
419
|
export function hashSecret(secret: string): Promise<string>;
|
|
@@ -386,7 +422,12 @@ export function verifySecret(secret: string, stored: string | undefined): Promis
|
|
|
386
422
|
export function generateSecret(): string;
|
|
387
423
|
/** Gets tokens from an orchestrator and refreshes them before they expire. */
|
|
388
424
|
export function createTokenProvider(opts: {
|
|
389
|
-
|
|
425
|
+
/** The orchestrator; its /v1/auth/token is used unless `tokenUrl` is given. */
|
|
426
|
+
url?: string;
|
|
427
|
+
/** Any OAuth2 token endpoint (client credentials grant). */
|
|
428
|
+
tokenUrl?: string;
|
|
429
|
+
/** Resource indicator (RFC 8707). */
|
|
430
|
+
resource?: string;
|
|
390
431
|
clientId: string;
|
|
391
432
|
clientSecret: string;
|
|
392
433
|
scope?: string;
|
package/package.json
CHANGED
package/server.d.ts
CHANGED
|
@@ -21,6 +21,8 @@ export interface Principal {
|
|
|
21
21
|
sub: string;
|
|
22
22
|
scopes: Set<Scope>;
|
|
23
23
|
admin: boolean;
|
|
24
|
+
/** Sees and controls every owner's jobs: `admin`, and `dispatch` (the orchestrator calling a worker). */
|
|
25
|
+
all: boolean;
|
|
24
26
|
}
|
|
25
27
|
|
|
26
28
|
export type Authenticator = (req: IncomingMessage) => Promise<Principal | null>;
|
|
@@ -73,14 +75,36 @@ export interface TokenSigner {
|
|
|
73
75
|
jwks(): { keys: Record<string, unknown>[] };
|
|
74
76
|
}
|
|
75
77
|
export function createTokenSigner(opts: { privateKey: KeyObject | string; issuer?: string; ttlSeconds?: number }): TokenSigner;
|
|
76
|
-
export function createTokenVerifier(opts: { getKey: (kid: string) => KeyObject | null | Promise<KeyObject | null>; issuer?: string }): (token: string) => Promise<{ sub: string; scope: string[]; exp: number } | null>;
|
|
78
|
+
export function createTokenVerifier(opts: { getKey: (kid: string) => KeyObject | null | Promise<KeyObject | null>; issuer?: string; audience?: string | null; algorithms?: ('EdDSA' | 'RS256')[] }): (token: string) => Promise<{ sub: string; scope: string[]; exp: number } | null>;
|
|
77
79
|
export function createRemoteKeySet(url: string, opts?: { fetch?: typeof fetch; minRefreshMs?: number }): (kid: string) => Promise<KeyObject | null>;
|
|
78
80
|
export function createAuthenticator(opts: {
|
|
79
81
|
token?: string | null;
|
|
80
82
|
verify?: ((token: string) => Promise<{ sub: string; scope: string[] } | null>) | null;
|
|
81
83
|
isActive?: (sub: string) => boolean;
|
|
84
|
+
/** Tokens from an external issuer; see `createExternalIssuer`. Revocation is the token's lifetime. */
|
|
85
|
+
external?: ExternalIssuer | null;
|
|
82
86
|
open?: boolean;
|
|
83
87
|
}): Authenticator;
|
|
88
|
+
/** External scope names mapped to {@link Scope}s unless mapped otherwise. */
|
|
89
|
+
export const DEFAULT_EXTERNAL_SCOPES: Readonly<Record<string, Scope>>;
|
|
90
|
+
/** Parses `external=internal` pairs ("fleet:submit=jobs,fleet:work=worker"), an object or a Map; `null` gives the defaults. */
|
|
91
|
+
export function parseScopeMap(spec?: string | Record<string, string> | Map<string, string> | null): Map<string, Scope>;
|
|
92
|
+
export interface ExternalIssuerOptions {
|
|
93
|
+
issuer: string;
|
|
94
|
+
jwksUrl: string;
|
|
95
|
+
/** Expected `aud`: this surface's resource identifier. */
|
|
96
|
+
audience: string;
|
|
97
|
+
scopes?: string | Record<string, string> | Map<string, string>;
|
|
98
|
+
algorithms?: ('EdDSA' | 'RS256')[];
|
|
99
|
+
fetch?: typeof fetch;
|
|
100
|
+
}
|
|
101
|
+
export interface ExternalIssuer {
|
|
102
|
+
issuer: string;
|
|
103
|
+
audience: string;
|
|
104
|
+
scopeMap: Map<string, Scope>;
|
|
105
|
+
verify: (token: string) => Promise<{ sub: string; scope: string[]; exp: number } | null>;
|
|
106
|
+
}
|
|
107
|
+
export function createExternalIssuer(opts: ExternalIssuerOptions): ExternalIssuer;
|
|
84
108
|
export interface ClientEntry {
|
|
85
109
|
id: string;
|
|
86
110
|
secretHash: string;
|
package/src/auth.js
CHANGED
|
@@ -7,8 +7,21 @@ import { FleetError } from './job-record.js';
|
|
|
7
7
|
|
|
8
8
|
const scryptAsync = promisify(scrypt);
|
|
9
9
|
|
|
10
|
-
/**
|
|
11
|
-
|
|
10
|
+
/**
|
|
11
|
+
* `jobs`: submit and see your own jobs. `metrics`: /metrics and service discovery. `admin`: everything, all owners.
|
|
12
|
+
* `worker`: register a worker and send heartbeats, nothing else. `dispatch`: call a worker's job API for every
|
|
13
|
+
* owner (held by the orchestrator only).
|
|
14
|
+
*/
|
|
15
|
+
export const SCOPES = ['jobs', 'metrics', 'admin', 'worker', 'dispatch'];
|
|
16
|
+
|
|
17
|
+
/** External (issuer) scope names mapped to the scopes above unless the operator maps them differently. */
|
|
18
|
+
export const DEFAULT_EXTERNAL_SCOPES = Object.freeze({
|
|
19
|
+
'fleet:submit': 'jobs',
|
|
20
|
+
'fleet:work': 'worker',
|
|
21
|
+
'fleet:dispatch': 'dispatch',
|
|
22
|
+
'fleet:admin': 'admin',
|
|
23
|
+
'fleet:metrics': 'metrics',
|
|
24
|
+
});
|
|
12
25
|
const SCRYPT = { N: 16384, r: 8, p: 1, keylen: 32 };
|
|
13
26
|
const LEEWAY_S = 30;
|
|
14
27
|
|
|
@@ -92,9 +105,11 @@ export function createTokenSigner({ privateKey, issuer = 'fffleet', ttlSeconds =
|
|
|
92
105
|
|
|
93
106
|
/**
|
|
94
107
|
* Verifies tokens. `getKey(kid)` returns a public KeyObject or null.
|
|
108
|
+
* Only the algorithms in `algorithms` are accepted (default EdDSA, fffleet's own tokens; an external
|
|
109
|
+
* issuer's tokens are typically `['RS256']`). With `audience` the token's `aud` must contain it.
|
|
95
110
|
* @returns {(token: string) => Promise<{ sub: string, scope: string[], exp: number } | null>}
|
|
96
111
|
*/
|
|
97
|
-
export function createTokenVerifier({ getKey, issuer = 'fffleet' }) {
|
|
112
|
+
export function createTokenVerifier({ getKey, issuer = 'fffleet', audience = null, algorithms = ['EdDSA'] }) {
|
|
98
113
|
return async token => {
|
|
99
114
|
const parts = String(token).split('.');
|
|
100
115
|
if (parts.length !== 3) return null;
|
|
@@ -105,19 +120,37 @@ export function createTokenVerifier({ getKey, issuer = 'fffleet' }) {
|
|
|
105
120
|
} catch {
|
|
106
121
|
return null;
|
|
107
122
|
}
|
|
108
|
-
if (header?.alg
|
|
123
|
+
if (!algorithms.includes(header?.alg) || typeof header.kid !== 'string') return null;
|
|
109
124
|
const key = await getKey(header.kid);
|
|
110
125
|
if (!key) return null;
|
|
111
|
-
|
|
126
|
+
const data = Buffer.from(`${parts[0]}.${parts[1]}`);
|
|
127
|
+
const sig = Buffer.from(parts[2], 'base64url');
|
|
128
|
+
let ok = false;
|
|
129
|
+
try {
|
|
130
|
+
if (header.alg === 'EdDSA') ok = key.asymmetricKeyType === 'ed25519' && verify(null, data, key, sig);
|
|
131
|
+
else if (header.alg === 'RS256') ok = key.asymmetricKeyType === 'rsa' && verify('sha256', data, key, sig);
|
|
132
|
+
} catch {
|
|
133
|
+
ok = false;
|
|
134
|
+
}
|
|
135
|
+
if (!ok) return null;
|
|
112
136
|
const now = Math.floor(Date.now() / 1000);
|
|
113
137
|
if (claims.iss !== issuer || typeof claims.sub !== 'string' || typeof claims.exp !== 'number' || claims.exp + LEEWAY_S < now) return null;
|
|
114
|
-
|
|
138
|
+
if (typeof claims.nbf === 'number' && claims.nbf - LEEWAY_S > now) return null;
|
|
139
|
+
if (audience) {
|
|
140
|
+
const aud = [].concat(claims.aud ?? []);
|
|
141
|
+
if (!aud.includes(audience)) return null;
|
|
142
|
+
}
|
|
143
|
+
// `scope` is a space-separated string (RFC 8693) or, with some issuers, `scp`/`scope` as an array.
|
|
144
|
+
const raw = claims.scope ?? claims.scp ?? '';
|
|
145
|
+
const scope = (Array.isArray(raw) ? raw : String(raw).split(' ')).filter(Boolean);
|
|
146
|
+
return { sub: claims.sub, scope, exp: claims.exp };
|
|
115
147
|
};
|
|
116
148
|
}
|
|
117
149
|
|
|
118
150
|
/**
|
|
119
|
-
* Fetches public keys from a JWK Set URL (an orchestrator's /v1/auth/keys) and caches them.
|
|
120
|
-
* An unknown key id triggers a refetch at most every `minRefreshMs`.
|
|
151
|
+
* Fetches public keys from a JWK Set URL (an orchestrator's /v1/auth/keys, or an external issuer's) and caches them.
|
|
152
|
+
* Ed25519 and RSA keys are read. An unknown key id triggers a refetch at most every `minRefreshMs`.
|
|
153
|
+
* A failed refetch keeps the keys already cached, so a short outage of the issuer does not stop verification.
|
|
121
154
|
*/
|
|
122
155
|
export function createRemoteKeySet(url, { fetch: f = globalThis.fetch, minRefreshMs = 30000 } = {}) {
|
|
123
156
|
let keys = new Map();
|
|
@@ -128,7 +161,16 @@ export function createRemoteKeySet(url, { fetch: f = globalThis.fetch, minRefres
|
|
|
128
161
|
const res = await f(url, { signal: AbortSignal.timeout(5000) });
|
|
129
162
|
if (!res.ok) throw new Error(`key set returned HTTP ${res.status}`);
|
|
130
163
|
const body = await res.json();
|
|
131
|
-
|
|
164
|
+
const next = new Map();
|
|
165
|
+
for (const k of body.keys ?? []) {
|
|
166
|
+
if (typeof k.kid !== 'string' || k.use === 'enc' || !((k.kty === 'OKP' && k.crv === 'Ed25519') || k.kty === 'RSA')) continue;
|
|
167
|
+
try {
|
|
168
|
+
next.set(k.kid, createPublicKey({ key: k, format: 'jwk' }));
|
|
169
|
+
} catch {
|
|
170
|
+
// A malformed key is skipped; the others still work.
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
keys = next;
|
|
132
174
|
}
|
|
133
175
|
return async kid => {
|
|
134
176
|
if (!keys.has(kid) && Date.now() - fetchedAt >= minRefreshMs) {
|
|
@@ -141,14 +183,16 @@ export function createRemoteKeySet(url, { fetch: f = globalThis.fetch, minRefres
|
|
|
141
183
|
|
|
142
184
|
/**
|
|
143
185
|
* Who a request is from. `scopes` decide what it may do; `admin` sees and controls every owner's jobs.
|
|
144
|
-
* @typedef {{ sub: string, scopes: Set<string>, admin: boolean }} Principal
|
|
186
|
+
* @typedef {{ sub: string, scopes: Set<string>, admin: boolean, all: boolean }} Principal
|
|
187
|
+
* `all`: sees and controls every owner's jobs (`admin`, and `dispatch`, which is the orchestrator calling a worker).
|
|
145
188
|
*/
|
|
146
189
|
|
|
147
190
|
/** @returns {Principal} */
|
|
148
191
|
export function principal(sub, scopes) {
|
|
149
192
|
const set = new Set(scopes);
|
|
150
193
|
if (set.has('admin')) for (const s of SCOPES) set.add(s);
|
|
151
|
-
|
|
194
|
+
if (set.has('dispatch')) set.add('jobs');
|
|
195
|
+
return { sub, scopes: set, admin: set.has('admin'), all: set.has('admin') || set.has('dispatch') };
|
|
152
196
|
}
|
|
153
197
|
|
|
154
198
|
/** The principal used when no authentication is configured: everything is allowed. */
|
|
@@ -165,6 +209,57 @@ export function sameSecret(a, b) {
|
|
|
165
209
|
return x.length === y.length && timingSafeEqual(x, y);
|
|
166
210
|
}
|
|
167
211
|
|
|
212
|
+
/**
|
|
213
|
+
* Parses `external=internal` pairs ("fleet:submit=jobs,fleet:work=worker") into a map.
|
|
214
|
+
* Accepts a string, an object or a Map; `null` gives the defaults. Unknown internal scopes are an error.
|
|
215
|
+
* @returns {Map<string, string>}
|
|
216
|
+
*/
|
|
217
|
+
export function parseScopeMap(spec = null) {
|
|
218
|
+
let entries;
|
|
219
|
+
if (spec instanceof Map) entries = [...spec];
|
|
220
|
+
else if (spec && typeof spec === 'object') entries = Object.entries(spec);
|
|
221
|
+
else if (typeof spec === 'string' && spec.trim()) entries = spec.split(',').map(p => p.trim()).filter(Boolean).map(p => p.split('=').map(x => x.trim()));
|
|
222
|
+
else entries = Object.entries(DEFAULT_EXTERNAL_SCOPES);
|
|
223
|
+
const map = new Map();
|
|
224
|
+
for (const [from, to] of entries) {
|
|
225
|
+
if (!from || !SCOPES.includes(to)) throw new Error(`scope map: "${from}=${to}" must map to one of ${SCOPES.join(', ')}`);
|
|
226
|
+
map.set(from, to);
|
|
227
|
+
}
|
|
228
|
+
return map;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Settings for tokens from an external OIDC issuer (a service-token provider), RS256 or EdDSA.
|
|
233
|
+
* @typedef {object} ExternalIssuer
|
|
234
|
+
* @property {string} issuer Expected `iss`.
|
|
235
|
+
* @property {string} jwksUrl Where the public keys are.
|
|
236
|
+
* @property {string} audience Expected `aud` (this surface's resource identifier).
|
|
237
|
+
* @property {string | object | Map<string, string>} [scopes] External scope name to internal scope (see parseScopeMap).
|
|
238
|
+
* @property {typeof globalThis.fetch} [fetch]
|
|
239
|
+
*/
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Builds the `external` option of createAuthenticator from ExternalIssuer settings.
|
|
243
|
+
* @param {ExternalIssuer} opts
|
|
244
|
+
*/
|
|
245
|
+
export function createExternalIssuer({ issuer, jwksUrl, audience, scopes = null, fetch: f = globalThis.fetch, algorithms = ['RS256', 'EdDSA'] }) {
|
|
246
|
+
if (!issuer || !jwksUrl || !audience) throw new Error('an external issuer needs issuer, jwksUrl and audience');
|
|
247
|
+
return {
|
|
248
|
+
issuer,
|
|
249
|
+
audience,
|
|
250
|
+
scopeMap: parseScopeMap(scopes),
|
|
251
|
+
verify: createTokenVerifier({ getKey: createRemoteKeySet(jwksUrl, { fetch: f }), issuer, audience, algorithms }),
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function peekIssuer(jwt) {
|
|
256
|
+
try {
|
|
257
|
+
return JSON.parse(Buffer.from(jwt.split('.')[1], 'base64url').toString('utf8'))?.iss ?? null;
|
|
258
|
+
} catch {
|
|
259
|
+
return null;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
168
263
|
/**
|
|
169
264
|
* Builds an authenticator: a function from a request to a Principal, or null when the request
|
|
170
265
|
* carries no valid credentials.
|
|
@@ -172,15 +267,24 @@ export function sameSecret(a, b) {
|
|
|
172
267
|
* @param {string | null} [opts.token] A static token that is granted `admin`.
|
|
173
268
|
* @param {((token: string) => Promise<{ sub: string, scope: string[] } | null>) | null} [opts.verify]
|
|
174
269
|
* @param {(sub: string) => boolean} [opts.isActive] Rejects tokens of clients that were removed.
|
|
270
|
+
* @param {ReturnType<typeof createExternalIssuer> | null} [opts.external] Tokens from an external issuer. Revocation is the token's lifetime (no `isActive` check).
|
|
175
271
|
* @param {boolean} [opts.open] Without any credentials configured, allow everything.
|
|
176
272
|
*/
|
|
177
|
-
export function createAuthenticator({ token = null, verify: verifyToken = null, isActive = () => true, open = !token && !verifyToken }) {
|
|
273
|
+
export function createAuthenticator({ token = null, verify: verifyToken = null, isActive = () => true, external = null, open = !token && !verifyToken && !external }) {
|
|
178
274
|
return async req => {
|
|
179
275
|
if (open) return OPEN;
|
|
180
276
|
const given = bearerOf(req);
|
|
181
277
|
if (!given) return null;
|
|
182
278
|
if (token && sameSecret(given, token)) return principal('admin', ['admin']);
|
|
183
|
-
if (
|
|
279
|
+
if (given.split('.').length !== 3) return null;
|
|
280
|
+
// The issuer is read from the unverified payload only to choose which verifier runs; nothing is trusted before its signature is checked.
|
|
281
|
+
if (external && peekIssuer(given) === external.issuer) {
|
|
282
|
+
const claims = await external.verify(given);
|
|
283
|
+
if (!claims) return null;
|
|
284
|
+
const scopes = claims.scope.map(s => external.scopeMap.get(s)).filter(Boolean);
|
|
285
|
+
return principal(claims.sub, scopes);
|
|
286
|
+
}
|
|
287
|
+
if (!verifyToken) return null;
|
|
184
288
|
const claims = await verifyToken(given);
|
|
185
289
|
if (!claims || !isActive(claims.sub)) return null;
|
|
186
290
|
return principal(claims.sub, claims.scope.filter(s => SCOPES.includes(s)));
|
|
@@ -270,16 +374,17 @@ function oauthError(status, error, description, basic = false) {
|
|
|
270
374
|
}
|
|
271
375
|
|
|
272
376
|
/**
|
|
273
|
-
* Client side: gets tokens from an orchestrator
|
|
377
|
+
* Client side: gets tokens from an orchestrator (`url`, its /v1/auth/token) or from any OAuth2 token endpoint (`tokenUrl`,
|
|
378
|
+
* optionally with a `resource` indicator, RFC 8707) and refreshes them before they expire.
|
|
274
379
|
* @returns {{ get: (opts?: { refresh?: boolean }) => Promise<string> }}
|
|
275
380
|
*/
|
|
276
|
-
export function createTokenProvider({ url, clientId, clientSecret, scope, fetch: f = globalThis.fetch, timeoutMs = 10000 }) {
|
|
381
|
+
export function createTokenProvider({ url, tokenUrl, resource, clientId, clientSecret, scope, fetch: f = globalThis.fetch, timeoutMs = 10000 }) {
|
|
277
382
|
let token = null;
|
|
278
383
|
let expiresAt = 0;
|
|
279
384
|
let pending = null;
|
|
280
385
|
async function fetchToken() {
|
|
281
|
-
const body = new URLSearchParams({ grant_type: 'client_credentials', client_id: clientId, client_secret: clientSecret, ...(scope ? { scope } : {}) });
|
|
282
|
-
const res = await f(`${url.replace(/\/+$/, '')}/v1/auth/token`, {
|
|
386
|
+
const body = new URLSearchParams({ grant_type: 'client_credentials', client_id: clientId, client_secret: clientSecret, ...(scope ? { scope } : {}), ...(resource ? { resource } : {}) });
|
|
387
|
+
const res = await f(tokenUrl ?? `${url.replace(/\/+$/, '')}/v1/auth/token`, {
|
|
283
388
|
method: 'POST',
|
|
284
389
|
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
|
285
390
|
body,
|
package/src/capabilities.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { execFile } from 'node:child_process';
|
|
2
2
|
import { promisify } from 'node:util';
|
|
3
|
+
import { INLINE_CAPABILITY } from './contract.js';
|
|
3
4
|
import { siblingProbe } from './ffprobe.js';
|
|
4
5
|
|
|
5
6
|
const run = promisify(execFile);
|
|
@@ -27,6 +28,10 @@ export async function detectCapabilities(ffmpegPath = 'ffmpeg') {
|
|
|
27
28
|
if (version) caps.add('type:ffmpeg');
|
|
28
29
|
if (await out(siblingProbe(ffmpegPath), ['-hide_banner', '-version'])) caps.add('type:ffprobe');
|
|
29
30
|
if (v) caps.add(`ffmpeg:${v[1]}.${v[2]}`);
|
|
31
|
+
// Built-in flash-analysis runs ffmpeg, so it is claimed only where ffmpeg is.
|
|
32
|
+
if (v) caps.add('type:flash-analysis');
|
|
33
|
+
// Inline outputs are part of this package's contract, so every build that has this module returns them.
|
|
34
|
+
caps.add(INLINE_CAPABILITY);
|
|
30
35
|
|
|
31
36
|
// " T.. ass V->V Render ASS subtitles..."
|
|
32
37
|
for (const line of (await out(ffmpegPath, ['-hide_banner', '-filters'])).split('\n')) {
|
package/src/client.js
CHANGED
|
@@ -85,15 +85,17 @@ export class JobHandle extends EventEmitter {
|
|
|
85
85
|
* @param {string} [opts.token] A static bearer token.
|
|
86
86
|
* @param {string} [opts.clientId] With clientSecret: log in at the orchestrator (POST /v1/auth/token) instead of using a static token.
|
|
87
87
|
* @param {string} [opts.clientSecret]
|
|
88
|
+
* @param {string} [opts.tokenUrl] With clientId/clientSecret: an OAuth2 token endpoint of an external issuer instead of the orchestrator's.
|
|
89
|
+
* @param {string} [opts.tokenResource] Resource indicator (RFC 8707) sent with the token request.
|
|
88
90
|
* @param {string} [opts.scope] Narrow the token to some of the client's scopes, e.g. 'jobs'.
|
|
89
91
|
* @param {'local' | 'none'} [opts.fallback]
|
|
90
92
|
* @param {ConstructorParameters<typeof JobManager>[0]} [opts.local] Options for the local runner.
|
|
91
93
|
* @param {typeof fetch} [opts.fetch]
|
|
92
94
|
* @param {number} [opts.requestTimeoutMs]
|
|
93
95
|
*/
|
|
94
|
-
export function createFleet({ url, token, clientId, clientSecret, scope, fallback = 'local', local = {}, fetch: f = globalThis.fetch, requestTimeoutMs = 10000 } = {}) {
|
|
96
|
+
export function createFleet({ url, token, clientId, clientSecret, tokenUrl, tokenResource, scope, fallback = 'local', local = {}, fetch: f = globalThis.fetch, requestTimeoutMs = 10000 } = {}) {
|
|
95
97
|
const base = url ? url.replace(/\/+$/, '') : null;
|
|
96
|
-
const login = base && clientId && clientSecret ? createTokenProvider({ url: base, clientId, clientSecret, scope, fetch: f, timeoutMs: requestTimeoutMs }) : null;
|
|
98
|
+
const login = (base || tokenUrl) && clientId && clientSecret ? createTokenProvider({ url: base, tokenUrl, resource: tokenResource, clientId, clientSecret, scope, fetch: f, timeoutMs: requestTimeoutMs }) : null;
|
|
97
99
|
const authHeaders = async (refresh = false) => {
|
|
98
100
|
if (login) return { authorization: `Bearer ${await login.get({ refresh })}` };
|
|
99
101
|
return token ? { authorization: `Bearer ${token}` } : {};
|
package/src/contract.js
CHANGED
|
@@ -27,8 +27,18 @@ export const PASSTHROUGH_SCHEMES = Object.freeze(['rtmp:', 'rtmps:', 'srt:', 'ud
|
|
|
27
27
|
* s3://bucket/key is one object; s3://bucket/prefix/ (trailing slash) is an output folder.
|
|
28
28
|
*/
|
|
29
29
|
export const OBJECT_SCHEMES = Object.freeze(['s3:']);
|
|
30
|
+
/**
|
|
31
|
+
* Batch outputs only: the result comes back in the job snapshot instead of an endpoint.
|
|
32
|
+
* JSON (`contentType: application/json`) is returned as `data`, anything else as `base64`.
|
|
33
|
+
* A result over `maxBytes` fails the job with OUTPUT_TOO_LARGE; it is never truncated.
|
|
34
|
+
*/
|
|
35
|
+
export const INLINE_SCHEME = 'inline:';
|
|
36
|
+
export const INLINE_DEFAULT_MAX_BYTES = 1024 * 1024;
|
|
37
|
+
export const INLINE_MAX_BYTES = 8 * 1024 * 1024;
|
|
38
|
+
/** Capability a worker reports when it can return inline outputs; jobs with one require it. */
|
|
39
|
+
export const INLINE_CAPABILITY = 'result:inline';
|
|
30
40
|
|
|
31
|
-
const ALL_SCHEMES = new Set([...FILE_SCHEMES, ...HTTP_SCHEMES, ...PASSTHROUGH_SCHEMES, ...OBJECT_SCHEMES]);
|
|
41
|
+
const ALL_SCHEMES = new Set([...FILE_SCHEMES, ...HTTP_SCHEMES, ...PASSTHROUGH_SCHEMES, ...OBJECT_SCHEMES, INLINE_SCHEME]);
|
|
32
42
|
|
|
33
43
|
const ID_RE = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
34
44
|
const NAME_RE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
@@ -117,6 +127,7 @@ export function validateSpec(input) {
|
|
|
117
127
|
const inputs = normalizeEndpoints(s.inputs, 'inputs', err);
|
|
118
128
|
const outputs = normalizeEndpoints(s.outputs, 'outputs', err);
|
|
119
129
|
checkObjectEndpoints(s.kind, inputs, outputs, err);
|
|
130
|
+
if (s.kind === 'stream') outputs.forEach((o, i) => { if (isInline(o)) err(`outputs[${i}].uri`, 'inline: is only supported for batch jobs'); });
|
|
120
131
|
|
|
121
132
|
// Set by a runner that applied a variant (see resolveVariant); a client does not send it.
|
|
122
133
|
const variant = s.variant;
|
|
@@ -149,7 +160,7 @@ export function validateSpec(input) {
|
|
|
149
160
|
priority,
|
|
150
161
|
...(workerPreference !== undefined ? { workerPreference: [...workerPreference] } : {}),
|
|
151
162
|
owner,
|
|
152
|
-
requires: [...new Set(requires)].sort(),
|
|
163
|
+
requires: [...new Set([...requires, ...(hasInlineOutput(outputs, variants) ? [INLINE_CAPABILITY] : [])])].sort(),
|
|
153
164
|
labels: { ...labels },
|
|
154
165
|
timeoutMs,
|
|
155
166
|
stdin,
|
|
@@ -286,10 +297,41 @@ function normalizeEndpoints(list, path, err) {
|
|
|
286
297
|
if (typeof e.contentType !== 'string') err(`${p}.contentType`, 'must be a string');
|
|
287
298
|
else out.contentType = e.contentType;
|
|
288
299
|
}
|
|
300
|
+
if (url?.protocol === INLINE_SCHEME) {
|
|
301
|
+
if (path === 'inputs') err(`${p}.uri`, 'inline: is only valid for outputs');
|
|
302
|
+
const max = e.maxBytes ?? INLINE_DEFAULT_MAX_BYTES;
|
|
303
|
+
if (!Number.isInteger(max) || max < 1 || max > INLINE_MAX_BYTES) err(`${p}.maxBytes`, `must be an integer from 1 to ${INLINE_MAX_BYTES}`);
|
|
304
|
+
else out.maxBytes = max;
|
|
305
|
+
} else if (e.maxBytes !== undefined) {
|
|
306
|
+
err(`${p}.maxBytes`, 'is only valid on an inline: output');
|
|
307
|
+
}
|
|
289
308
|
return out;
|
|
290
309
|
});
|
|
291
310
|
}
|
|
292
311
|
|
|
312
|
+
/** True for an output whose result comes back inline. */
|
|
313
|
+
export function isInline(endpoint) {
|
|
314
|
+
return typeof endpoint?.uri === 'string' && endpoint.uri.startsWith(INLINE_SCHEME);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** Whether the base outputs or any variant's outputs return a result inline (such a job needs INLINE_CAPABILITY). */
|
|
318
|
+
function hasInlineOutput(outputs, variants) {
|
|
319
|
+
return outputs.some(isInline) || (variants ?? []).some(v => (v.outputs ?? []).some(isInline));
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* The part of an output that is kept after the job ends (snapshots, lists, the orchestrator's state file):
|
|
324
|
+
* an inline result's `data` and `base64` are dropped, its size and type stay.
|
|
325
|
+
* @template {{ data?: unknown, base64?: string }} T
|
|
326
|
+
* @param {T} output
|
|
327
|
+
* @returns {Omit<T, 'data' | 'base64'>}
|
|
328
|
+
*/
|
|
329
|
+
export function withoutInlinePayload(output) {
|
|
330
|
+
if (!output || typeof output !== 'object' || (!('data' in output) && !('base64' in output))) return output;
|
|
331
|
+
const { data, base64, ...rest } = output;
|
|
332
|
+
return rest;
|
|
333
|
+
}
|
|
334
|
+
|
|
293
335
|
function checkObjectEndpoints(kind, inputs, outputs, err) {
|
|
294
336
|
const check = (list, path, isOutput) => list.forEach((e, i) => {
|
|
295
337
|
let url;
|
package/src/executor.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
2
|
import { createWriteStream } from 'node:fs';
|
|
3
|
-
import { mkdir, open, readdir, stat } from 'node:fs/promises';
|
|
3
|
+
import { mkdir, open, readdir, readFile, rm, stat } from 'node:fs/promises';
|
|
4
4
|
import { dirname, extname, join } from 'node:path';
|
|
5
5
|
import { Readable } from 'node:stream';
|
|
6
6
|
import { pipeline } from 'node:stream/promises';
|
|
7
7
|
import { fileURLToPath } from 'node:url';
|
|
8
|
-
import { HTTP_SCHEMES, resolvePlaceholders } from './contract.js';
|
|
8
|
+
import { HTTP_SCHEMES, INLINE_SCHEME, resolvePlaceholders } from './contract.js';
|
|
9
9
|
import { FleetError } from './job-record.js';
|
|
10
10
|
import { createProgressParser } from './progress.js';
|
|
11
11
|
import { parseS3Uri } from './s3.js';
|
|
@@ -76,6 +76,12 @@ export async function runFfmpegJob(spec, rt) {
|
|
|
76
76
|
await mkdir(folder ? path : dirname(path), { recursive: true });
|
|
77
77
|
outputs.push({ name: output.name, uri: output.uri, local: path, upload: 's3', folder, contentType: output.contentType });
|
|
78
78
|
values.output[output.name] = path;
|
|
79
|
+
} else if (url.protocol === INLINE_SCHEME) {
|
|
80
|
+
// Written to scratch and read back into the snapshot once ffmpeg is done (see readInlineOutput).
|
|
81
|
+
const path = join(rt.workDir, 'out', `${output.name}.bin`);
|
|
82
|
+
await mkdir(dirname(path), { recursive: true });
|
|
83
|
+
outputs.push({ name: output.name, uri: output.uri, local: path, upload: false, inline: { maxBytes: output.maxBytes, contentType: output.contentType } });
|
|
84
|
+
values.output[output.name] = path;
|
|
79
85
|
} else {
|
|
80
86
|
outputs.push({ name: output.name, uri: output.uri, local: null, upload: false });
|
|
81
87
|
values.output[output.name] = output.uri;
|
|
@@ -107,6 +113,10 @@ export async function runFfmpegJob(spec, rt) {
|
|
|
107
113
|
const results = [];
|
|
108
114
|
if (outputs.some(o => o.upload)) rt.setState('uploading');
|
|
109
115
|
for (const o of outputs) {
|
|
116
|
+
if (o.inline) {
|
|
117
|
+
results.push(await readInlineOutput(o, { exitCode, stderrTail }));
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
110
120
|
let bytes = null;
|
|
111
121
|
if (o.local) {
|
|
112
122
|
try {
|
|
@@ -124,7 +134,39 @@ export async function runFfmpegJob(spec, rt) {
|
|
|
124
134
|
return { exitCode, outputs: results, stderrTail };
|
|
125
135
|
}
|
|
126
136
|
|
|
127
|
-
|
|
137
|
+
/**
|
|
138
|
+
* Reads an inline output back from its scratch file, enforcing its size limit. The file is removed.
|
|
139
|
+
* JSON becomes `data`, anything else `base64`.
|
|
140
|
+
*/
|
|
141
|
+
export async function readInlineOutput(o, { exitCode, stderrTail }) {
|
|
142
|
+
let size;
|
|
143
|
+
try {
|
|
144
|
+
size = (await stat(o.local)).size;
|
|
145
|
+
} catch {
|
|
146
|
+
throw new FleetError('OUTPUT_MISSING', `ffmpeg did not write output "${o.name}"`, { details: { exitCode, stderrTail } });
|
|
147
|
+
}
|
|
148
|
+
const { maxBytes, contentType } = o.inline;
|
|
149
|
+
if (size > maxBytes) {
|
|
150
|
+
throw new FleetError('OUTPUT_TOO_LARGE', `output "${o.name}" is ${size} bytes; its limit is ${maxBytes}`, { details: { bytes: size, maxBytes } });
|
|
151
|
+
}
|
|
152
|
+
const buffer = await readFile(o.local);
|
|
153
|
+
await rm(o.local, { force: true });
|
|
154
|
+
const result = { name: o.name, uri: o.uri, bytes: size };
|
|
155
|
+
if (contentType) result.contentType = contentType;
|
|
156
|
+
const type = (contentType ?? '').split(';')[0].trim().toLowerCase();
|
|
157
|
+
if (type === 'application/json' || type.endsWith('+json')) {
|
|
158
|
+
try {
|
|
159
|
+
result.data = JSON.parse(buffer.toString('utf8'));
|
|
160
|
+
} catch {
|
|
161
|
+
throw new FleetError('OUTPUT_INVALID', `output "${o.name}" is not valid JSON`);
|
|
162
|
+
}
|
|
163
|
+
} else {
|
|
164
|
+
result.base64 = buffer.toString('base64');
|
|
165
|
+
}
|
|
166
|
+
return result;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export async function stageInput(input, { batch, rt, doFetch }) {
|
|
128
170
|
const url = new URL(input.uri);
|
|
129
171
|
if (url.protocol === 'file:') {
|
|
130
172
|
const path = fileURLToPath(url);
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
// The built-in flash-analysis job type: decodes a video with ffmpeg, measures relative luminance and a
|
|
2
|
+
// saturated-red measure for each sampled frame, and returns the flashes it finds as one inline JSON report.
|
|
3
|
+
//
|
|
4
|
+
// This reports facts (counts, intervals, whether more than three flashes fell in one second). It does not
|
|
5
|
+
// decide whether a video passes; that is the consumer's call. The rule is an approximation of WCAG 2.3.1,
|
|
6
|
+
// see LIMITATIONS, and has not been validated against a reference clip set.
|
|
7
|
+
|
|
8
|
+
import { execFile, spawn } from 'node:child_process';
|
|
9
|
+
import { INLINE_DEFAULT_MAX_BYTES, INLINE_SCHEME } from './contract.js';
|
|
10
|
+
import { FleetError } from './job-record.js';
|
|
11
|
+
import { siblingProbe } from './ffprobe.js';
|
|
12
|
+
import { stageInput } from './executor.js';
|
|
13
|
+
|
|
14
|
+
export const FLASH_STANDARD = 'wcag-2.3.1';
|
|
15
|
+
/** A change counts when it is at least this much of the maximum relative luminance (1.0). */
|
|
16
|
+
const STEP = 0.1;
|
|
17
|
+
/** The darker state of a flash must be below this relative luminance. */
|
|
18
|
+
const DARK_LIMIT = 0.8;
|
|
19
|
+
const MAX_FLASHES_PER_SECOND = 3;
|
|
20
|
+
const OPTION_KEYS = new Set(['standard', 'sampleFps', 'width', 'maxSeconds']);
|
|
21
|
+
|
|
22
|
+
export const LIMITATIONS = Object.freeze([
|
|
23
|
+
'sampled at sampleFps; a flash shorter than the sample spacing can be missed',
|
|
24
|
+
'frames are scaled to width before measuring, so small high-contrast areas can average out',
|
|
25
|
+
'the whole frame is measured; the WCAG flash-area limit is not applied, so the report is conservative',
|
|
26
|
+
'overlapping pairs of changes are each counted as a flash, so the count can exceed the number of visual flashes',
|
|
27
|
+
'the red measure approximates the saturated-red test; the rule is not validated against a reference clip set',
|
|
28
|
+
]);
|
|
29
|
+
|
|
30
|
+
const invalid = message => new FleetError('INVALID_SPEC', message, { status: 422 });
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Checks the `flash-analysis` payload of a spec and fills in defaults.
|
|
34
|
+
* @param {unknown} input
|
|
35
|
+
*/
|
|
36
|
+
export function parseFlashOptions(input) {
|
|
37
|
+
if (!input || typeof input !== 'object' || Array.isArray(input)) throw invalid('flash-analysis must be an object');
|
|
38
|
+
for (const key of Object.keys(input)) if (!OPTION_KEYS.has(key)) throw invalid(`flash-analysis.${key} is not a known option`);
|
|
39
|
+
const { standard = FLASH_STANDARD, sampleFps = 25, width = 64, maxSeconds = null } = /** @type {any} */ (input);
|
|
40
|
+
if (standard !== FLASH_STANDARD) throw invalid(`flash-analysis.standard must be "${FLASH_STANDARD}"`);
|
|
41
|
+
if (!Number.isInteger(sampleFps) || sampleFps < 1 || sampleFps > 60) throw invalid('flash-analysis.sampleFps must be an integer from 1 to 60');
|
|
42
|
+
if (!Number.isInteger(width) || width < 16 || width > 512) throw invalid('flash-analysis.width must be an integer from 16 to 512');
|
|
43
|
+
if (maxSeconds !== null && (!Number.isFinite(maxSeconds) || maxSeconds <= 0)) throw invalid('flash-analysis.maxSeconds must be a positive number');
|
|
44
|
+
return { standard, sampleFps, width, maxSeconds };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** sRGB byte to linear light (WCAG relative luminance input). */
|
|
48
|
+
const LINEAR = Float64Array.from({ length: 256 }, (_, v) => {
|
|
49
|
+
const c = v / 255;
|
|
50
|
+
return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Mean relative luminance of an RGB24 frame, and the mean of the red luminance of its red-dominant pixels.
|
|
55
|
+
* @param {Uint8Array} frame rgb24 bytes, pixels * 3 long
|
|
56
|
+
* @param {number} pixels
|
|
57
|
+
*/
|
|
58
|
+
export function frameMetrics(frame, pixels) {
|
|
59
|
+
let luma = 0;
|
|
60
|
+
let red = 0;
|
|
61
|
+
for (let p = 0; p < pixels * 3; p += 3) {
|
|
62
|
+
const r = frame[p];
|
|
63
|
+
const g = frame[p + 1];
|
|
64
|
+
const b = frame[p + 2];
|
|
65
|
+
luma += 0.2126 * LINEAR[r] + 0.7152 * LINEAR[g] + 0.0722 * LINEAR[b];
|
|
66
|
+
if (r > 0 && r > 2 * Math.max(g, b)) red += 0.2126 * LINEAR[r];
|
|
67
|
+
}
|
|
68
|
+
return { luma: luma / pixels, red: red / pixels };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Turning points of a series. A swing is a move of at least `step` from one turning point to the next;
|
|
73
|
+
* swings alternate in direction.
|
|
74
|
+
* @param {number[]} series
|
|
75
|
+
* @param {number} [step]
|
|
76
|
+
* @returns {{ from: number, to: number }[]} indices into series
|
|
77
|
+
*/
|
|
78
|
+
export function swingsOf(series, step = STEP) {
|
|
79
|
+
const swings = [];
|
|
80
|
+
let turn = 0;
|
|
81
|
+
let dir = 0;
|
|
82
|
+
let ext = 0;
|
|
83
|
+
for (let i = 1; i < series.length; i++) {
|
|
84
|
+
const v = series[i];
|
|
85
|
+
if (dir === 0) {
|
|
86
|
+
if (v - series[turn] >= step) {
|
|
87
|
+
dir = 1;
|
|
88
|
+
ext = i;
|
|
89
|
+
} else if (series[turn] - v >= step) {
|
|
90
|
+
dir = -1;
|
|
91
|
+
ext = i;
|
|
92
|
+
}
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
if (dir === 1) {
|
|
96
|
+
if (v > series[ext]) ext = i;
|
|
97
|
+
else if (series[ext] - v >= step) {
|
|
98
|
+
swings.push({ from: turn, to: ext });
|
|
99
|
+
turn = ext;
|
|
100
|
+
dir = -1;
|
|
101
|
+
ext = i;
|
|
102
|
+
}
|
|
103
|
+
} else if (v < series[ext]) ext = i;
|
|
104
|
+
else if (v - series[ext] >= step) {
|
|
105
|
+
swings.push({ from: turn, to: ext });
|
|
106
|
+
turn = ext;
|
|
107
|
+
dir = 1;
|
|
108
|
+
ext = i;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return swings;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Flashes in a series sampled at `sampleFps`: each pair of consecutive opposing swings of at least `step`
|
|
116
|
+
* whose darker state is below `DARK_LIMIT`. Returns start and end times in seconds, in order.
|
|
117
|
+
* @param {number[]} series
|
|
118
|
+
* @param {number} sampleFps
|
|
119
|
+
*/
|
|
120
|
+
export function flashesOf(series, sampleFps) {
|
|
121
|
+
const swings = swingsOf(series);
|
|
122
|
+
const flashes = [];
|
|
123
|
+
for (let k = 0; k + 1 < swings.length; k++) {
|
|
124
|
+
const a = swings[k];
|
|
125
|
+
const b = swings[k + 1];
|
|
126
|
+
const darker = Math.min(series[a.from], series[a.to], series[b.to]);
|
|
127
|
+
if (darker < DARK_LIMIT) flashes.push({ start: a.from / sampleFps, end: b.to / sampleFps });
|
|
128
|
+
}
|
|
129
|
+
return flashes;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const round3 = n => Math.round(n * 1000) / 1000;
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Summary of one kind of flash: counts, the most in any one second, and the intervals.
|
|
136
|
+
* @param {{ start: number, end: number }[]} flashes
|
|
137
|
+
*/
|
|
138
|
+
export function summariseFlashes(flashes) {
|
|
139
|
+
let max = 0;
|
|
140
|
+
let j = 0;
|
|
141
|
+
for (let i = 0; i < flashes.length; i++) {
|
|
142
|
+
while (flashes[i].start - flashes[j].start >= 1) j++;
|
|
143
|
+
max = Math.max(max, i - j + 1);
|
|
144
|
+
}
|
|
145
|
+
return {
|
|
146
|
+
count: flashes.length,
|
|
147
|
+
maxInAnyOneSecond: max,
|
|
148
|
+
exceedsThreePerSecond: max > MAX_FLASHES_PER_SECOND,
|
|
149
|
+
intervals: flashes.map(f => ({ startSeconds: round3(f.start), endSeconds: round3(f.end) })),
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Runs the analysis for one video and returns the report (pure apart from the child processes).
|
|
155
|
+
* Exported so the job type can also be called directly.
|
|
156
|
+
*/
|
|
157
|
+
export function buildReport(luma, red, options) {
|
|
158
|
+
return {
|
|
159
|
+
standard: options.standard,
|
|
160
|
+
sampleFps: options.sampleFps,
|
|
161
|
+
width: options.width,
|
|
162
|
+
durationSeconds: round3(luma.length / options.sampleFps),
|
|
163
|
+
generalFlashes: summariseFlashes(flashesOf(luma, options.sampleFps)),
|
|
164
|
+
redFlashes: summariseFlashes(flashesOf(red, options.sampleFps)),
|
|
165
|
+
limitations: [...LIMITATIONS],
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* The built-in job type `flash-analysis` (batch). Spec:
|
|
171
|
+
* inputs: exactly one video (file:, http(s): or s3:)
|
|
172
|
+
* outputs: exactly one inline output, which receives the report (JSON)
|
|
173
|
+
* 'flash-analysis': { standard?, sampleFps?, width?, maxSeconds? } the payload is named after the type, see parseFlashOptions
|
|
174
|
+
*
|
|
175
|
+
* @param {import('./types.js').JobSpec & { id: string, 'flash-analysis'?: unknown }} spec
|
|
176
|
+
* @param {import('./executor.js').ExecutorRuntime & { ffprobePath?: string }} rt
|
|
177
|
+
*/
|
|
178
|
+
export async function runFlashAnalysisJob(spec, rt) {
|
|
179
|
+
const options = parseFlashOptions(spec['flash-analysis'] ?? {});
|
|
180
|
+
if (spec.inputs.length !== 1) throw invalid('a flash-analysis job takes exactly one input');
|
|
181
|
+
if (spec.outputs.length !== 1 || !spec.outputs[0].uri.startsWith(INLINE_SCHEME)) {
|
|
182
|
+
throw invalid('a flash-analysis job takes exactly one inline output, which receives the report');
|
|
183
|
+
}
|
|
184
|
+
const output = spec.outputs[0];
|
|
185
|
+
|
|
186
|
+
rt.setState('staging');
|
|
187
|
+
const local = await stageInput(spec.inputs[0], { batch: true, rt, doFetch: rt.fetch ?? globalThis.fetch });
|
|
188
|
+
const source = await probeVideo(rt, local);
|
|
189
|
+
|
|
190
|
+
const outW = options.width;
|
|
191
|
+
const outH = Math.max(2, 2 * Math.round((source.height * outW) / source.width / 2));
|
|
192
|
+
const pixels = outW * outH;
|
|
193
|
+
const luma = [];
|
|
194
|
+
const red = [];
|
|
195
|
+
const args = [
|
|
196
|
+
'-hide_banner', '-loglevel', 'error', '-nostdin', '-i', local, '-an',
|
|
197
|
+
...(options.maxSeconds ? ['-t', String(options.maxSeconds)] : []),
|
|
198
|
+
'-vf', `fps=${options.sampleFps},scale=${outW}:${outH}:flags=area`,
|
|
199
|
+
'-f', 'rawvideo', '-pix_fmt', 'rgb24', 'pipe:1',
|
|
200
|
+
];
|
|
201
|
+
rt.setState('running');
|
|
202
|
+
await decodeFrames(rt.ffmpegPath ?? 'ffmpeg', args, {
|
|
203
|
+
signal: rt.signal,
|
|
204
|
+
frameBytes: pixels * 3,
|
|
205
|
+
onFrame: frame => {
|
|
206
|
+
const m = frameMetrics(frame, pixels);
|
|
207
|
+
luma.push(m.luma);
|
|
208
|
+
red.push(m.red);
|
|
209
|
+
},
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
const report = buildReport(luma, red, options);
|
|
213
|
+
const bytes = Buffer.byteLength(JSON.stringify(report));
|
|
214
|
+
const maxBytes = output.maxBytes ?? INLINE_DEFAULT_MAX_BYTES;
|
|
215
|
+
if (bytes > maxBytes) throw new FleetError('OUTPUT_TOO_LARGE', `the report is ${bytes} bytes; its limit is ${maxBytes}`, { details: { bytes, maxBytes } });
|
|
216
|
+
return {
|
|
217
|
+
exitCode: 0,
|
|
218
|
+
outputs: [{ name: output.name, uri: output.uri, bytes, contentType: 'application/json', data: report }],
|
|
219
|
+
stderrTail: null,
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function probeVideo(rt, file) {
|
|
224
|
+
const probe = rt.ffprobePath ?? siblingProbe(rt.ffmpegPath);
|
|
225
|
+
return new Promise((resolve, reject) => {
|
|
226
|
+
execFile(probe, ['-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=width,height', '-of', 'json', file], { signal: rt.signal, timeout: 60000 }, (err, stdout) => {
|
|
227
|
+
if (rt.signal.aborted) return reject(rt.signal.reason);
|
|
228
|
+
if (err) return reject(new FleetError('INPUT_FAILED', `could not read the video: ${err.message}`));
|
|
229
|
+
let stream = null;
|
|
230
|
+
try {
|
|
231
|
+
stream = JSON.parse(stdout).streams?.[0] ?? null;
|
|
232
|
+
} catch {
|
|
233
|
+
// handled below
|
|
234
|
+
}
|
|
235
|
+
if (!stream?.width || !stream?.height) return reject(new FleetError('INPUT_FAILED', 'the input has no video stream'));
|
|
236
|
+
resolve({ width: stream.width, height: stream.height });
|
|
237
|
+
});
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** Runs ffmpeg and hands each complete rgb24 frame to onFrame. A trailing partial frame is ignored. */
|
|
242
|
+
function decodeFrames(cmd, args, { signal, frameBytes, onFrame }) {
|
|
243
|
+
return new Promise((resolve, reject) => {
|
|
244
|
+
const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'], signal });
|
|
245
|
+
let stderr = '';
|
|
246
|
+
let pending = Buffer.alloc(0);
|
|
247
|
+
child.stderr.on('data', chunk => {
|
|
248
|
+
if (stderr.length < 4096) stderr += chunk;
|
|
249
|
+
});
|
|
250
|
+
child.stdout.on('data', chunk => {
|
|
251
|
+
pending = pending.length ? Buffer.concat([pending, chunk]) : chunk;
|
|
252
|
+
let off = 0;
|
|
253
|
+
while (pending.length - off >= frameBytes) {
|
|
254
|
+
onFrame(pending.subarray(off, off + frameBytes));
|
|
255
|
+
off += frameBytes;
|
|
256
|
+
}
|
|
257
|
+
pending = pending.subarray(off);
|
|
258
|
+
});
|
|
259
|
+
child.on('error', err => {
|
|
260
|
+
if (signal?.aborted) return reject(signal.reason);
|
|
261
|
+
reject(new FleetError('SPAWN_FAILED', `could not start ${cmd}: ${err.message}`));
|
|
262
|
+
});
|
|
263
|
+
child.on('close', code => {
|
|
264
|
+
if (signal?.aborted) return reject(signal.reason);
|
|
265
|
+
if (code !== 0) return reject(new FleetError('FFMPEG_EXIT', `ffmpeg exited with code ${code}`, { details: { exitCode: code, stderrTail: stderr.slice(-2000) || null } }));
|
|
266
|
+
resolve();
|
|
267
|
+
});
|
|
268
|
+
});
|
|
269
|
+
}
|
package/src/http-api.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createServer } from 'node:http';
|
|
2
2
|
import { createAuthenticator, sameSecret } from './auth.js';
|
|
3
|
+
import { withoutInlinePayload } from './contract.js';
|
|
3
4
|
import { FleetError } from './job-record.js';
|
|
4
5
|
import { METRICS_CONTENT_TYPE } from './metrics.js';
|
|
5
6
|
|
|
@@ -7,6 +8,12 @@ const JSON_LIMIT = 1024 * 1024;
|
|
|
7
8
|
const STDIN_LIMIT = 1024 * 1024;
|
|
8
9
|
const SSE_KEEPALIVE_MS = 15000;
|
|
9
10
|
|
|
11
|
+
/** A job as a list entry: its inline outputs keep their size and type, not their payload. */
|
|
12
|
+
function withoutListPayloads(job) {
|
|
13
|
+
if (!Array.isArray(job?.outputs)) return job;
|
|
14
|
+
return { ...job, outputs: job.outputs.map(withoutInlinePayload) };
|
|
15
|
+
}
|
|
16
|
+
|
|
10
17
|
/**
|
|
11
18
|
* @typedef {object} JobBackend
|
|
12
19
|
* Anything that runs jobs: the local JobManager (worker) or the orchestrator.
|
|
@@ -49,18 +56,19 @@ export function createApiHandler({ backend, token = null, authenticate = createA
|
|
|
49
56
|
return res.end(text);
|
|
50
57
|
}
|
|
51
58
|
if (!allowed(res, who, 'jobs')) return;
|
|
52
|
-
const mine = job => job && (who.
|
|
59
|
+
const mine = job => job && (who.all || job.owner === who.sub) ? job : null;
|
|
53
60
|
|
|
54
61
|
if (url.pathname === '/v1/capabilities' && req.method === 'GET') return send(res, 200, await backend.capabilities());
|
|
55
62
|
if (url.pathname === '/v1/jobs') {
|
|
56
63
|
if (req.method === 'POST') {
|
|
57
64
|
const input = await readJson(req);
|
|
58
|
-
if (!who.
|
|
65
|
+
if (!who.all && input && typeof input === 'object' && !Array.isArray(input)) input.owner = who.sub;
|
|
59
66
|
const { created, queued, job } = await backend.submit(input);
|
|
60
67
|
// 201: took a slot (or was handed to a worker) now; 202: waiting in the queue; 200: already known.
|
|
61
68
|
return send(res, created ? ((queued ?? job.state === 'queued') ? 202 : 201) : 200, job);
|
|
62
69
|
}
|
|
63
|
-
|
|
70
|
+
// Lists carry no inline payloads: a report can be large, and the job's own snapshot has it.
|
|
71
|
+
if (req.method === 'GET') return send(res, 200, { jobs: backend.list().filter(mine).map(withoutListPayloads) });
|
|
64
72
|
}
|
|
65
73
|
|
|
66
74
|
const m = url.pathname.match(/^\/v1\/jobs\/([^/]+)(\/events|\/stdin|\/stdin\/close|\/stdout)?$/);
|
package/src/index.js
CHANGED
|
@@ -3,7 +3,9 @@ export {
|
|
|
3
3
|
CONTRACT_VERSION, KINDS, STATES, isFinal, validateSpec, parseSpec, ContractError,
|
|
4
4
|
resolvePlaceholders, canonicalJson, implicitRequirements, FILE_SCHEMES, HTTP_SCHEMES, PASSTHROUGH_SCHEMES, OBJECT_SCHEMES,
|
|
5
5
|
resolveVariant, MAX_VARIANTS,
|
|
6
|
+
INLINE_SCHEME, INLINE_CAPABILITY, INLINE_DEFAULT_MAX_BYTES, INLINE_MAX_BYTES, isInline, withoutInlinePayload,
|
|
6
7
|
} from './contract.js';
|
|
8
|
+
export { runFlashAnalysisJob, parseFlashOptions, buildReport, flashesOf, frameMetrics, FLASH_STANDARD } from './flash-analysis.js';
|
|
7
9
|
export { JobManager, normalizeSlots, normalizeKinds, autoSlots } from './job-manager.js';
|
|
8
10
|
export { JobRecord, FleetError, byPriority, pruneFinished } from './job-record.js';
|
|
9
11
|
export { runFfmpegJob } from './executor.js';
|
package/src/job-manager.js
CHANGED
|
@@ -9,6 +9,7 @@ import { createInputCache, parseSize } from './input-cache.js';
|
|
|
9
9
|
import { createS3Client } from './s3.js';
|
|
10
10
|
import { runFfmpegJob } from './executor.js';
|
|
11
11
|
import { runFfprobeJob } from './ffprobe.js';
|
|
12
|
+
import { runFlashAnalysisJob } from './flash-analysis.js';
|
|
12
13
|
import { FleetError, JobRecord, byPriority, pruneFinished } from './job-record.js';
|
|
13
14
|
|
|
14
15
|
/**
|
|
@@ -63,7 +64,7 @@ export class JobManager extends EventEmitter {
|
|
|
63
64
|
this.maxQueued = maxQueued;
|
|
64
65
|
this.keepFinished = keepFinished;
|
|
65
66
|
this.progressIntervalMs = progressIntervalMs;
|
|
66
|
-
this.executors = { ffmpeg: runFfmpegJob, ffprobe: runFfprobeJob, ...executors };
|
|
67
|
+
this.executors = { ffmpeg: runFfmpegJob, ffprobe: runFfprobeJob, 'flash-analysis': runFlashAnalysisJob, ...executors };
|
|
67
68
|
this.workerId = workerId;
|
|
68
69
|
this.capabilities = capabilities;
|
|
69
70
|
this.fetch = fetchImpl;
|
package/src/server.js
CHANGED
|
@@ -4,5 +4,5 @@ export { getStream } from './http-stream.js';
|
|
|
4
4
|
export { Registry, jobMetrics, processMetrics, hostMetrics, procStats, METRICS_CONTENT_TYPE } from './metrics.js';
|
|
5
5
|
export {
|
|
6
6
|
SCOPES, hashSecret, verifySecret, generateSecret, loadSigningKey, createTokenSigner, createTokenVerifier,
|
|
7
|
-
createRemoteKeySet, createAuthenticator, createClientStore, issueToken, principal, bearerOf, OPEN,
|
|
7
|
+
createRemoteKeySet, createAuthenticator, createExternalIssuer, parseScopeMap, DEFAULT_EXTERNAL_SCOPES, createClientStore, issueToken, principal, bearerOf, OPEN,
|
|
8
8
|
} from './auth.js';
|
package/src/types.js
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* @property {string} name Referenced from args as {{input:name}} or {{output:name}}.
|
|
9
9
|
* @property {string} uri file:, http(s): or a passthrough scheme such as rtmp:.
|
|
10
10
|
* @property {string} [contentType]
|
|
11
|
+
* @property {number} [maxBytes] inline: outputs only: the largest result accepted.
|
|
11
12
|
*
|
|
12
13
|
* @typedef {object} JobSpec
|
|
13
14
|
* @property {1} contract
|
|
@@ -43,7 +44,9 @@
|
|
|
43
44
|
* @property {string} name
|
|
44
45
|
* @property {string} uri
|
|
45
46
|
* @property {number | null} bytes
|
|
46
|
-
* @property {
|
|
47
|
+
* @property {string} [contentType]
|
|
48
|
+
* @property {unknown} [data] Small JSON result returned inline (`uri: 'inline:'`).
|
|
49
|
+
* @property {string} [base64] Small non-JSON result returned inline.
|
|
47
50
|
*
|
|
48
51
|
* @typedef {object} JobEvent
|
|
49
52
|
* @property {string} jobId
|