browser-model-manager 0.0.0-stage → 0.1.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/CHANGELOG.md +15 -0
- package/LICENSE +21 -0
- package/PROVENANCE.json +16 -0
- package/README.md +607 -2
- package/THIRD_PARTY_NOTICES +4 -0
- package/dist/acquisition/grants.d.ts +31 -0
- package/dist/acquisition/grants.js +75 -0
- package/dist/acquisition/index.d.ts +4 -0
- package/dist/acquisition/index.js +6 -0
- package/dist/acquisition/output.d.ts +12 -0
- package/dist/acquisition/output.js +19 -0
- package/dist/acquisition/phases.d.ts +3 -0
- package/dist/acquisition/phases.js +64 -0
- package/dist/acquisition/progress.d.ts +29 -0
- package/dist/acquisition/progress.js +124 -0
- package/dist/acquisition/slots.d.ts +35 -0
- package/dist/acquisition/slots.js +296 -0
- package/dist/cache/index.d.ts +3 -0
- package/dist/cache/index.js +4 -0
- package/dist/cache/model-cache.d.ts +152 -0
- package/dist/cache/model-cache.js +1585 -0
- package/dist/cache/sha256.d.ts +11 -0
- package/dist/cache/sha256.js +97 -0
- package/dist/cache/shard-store.d.ts +89 -0
- package/dist/cache/shard-store.js +204 -0
- package/dist/contracts/budgets.d.ts +41 -0
- package/dist/contracts/budgets.js +48 -0
- package/dist/contracts/errors.d.ts +43 -0
- package/dist/contracts/errors.js +2 -0
- package/dist/contracts/grant.d.ts +47 -0
- package/dist/contracts/grant.js +44 -0
- package/dist/contracts/index.d.ts +6 -0
- package/dist/contracts/index.js +7 -0
- package/dist/contracts/leases.d.ts +20 -0
- package/dist/contracts/leases.js +14 -0
- package/dist/contracts/lifecycle.d.ts +88 -0
- package/dist/contracts/lifecycle.js +12 -0
- package/dist/contracts/manifest.d.ts +95 -0
- package/dist/contracts/manifest.js +174 -0
- package/dist/handles/cross-tab.d.ts +16 -0
- package/dist/handles/cross-tab.js +29 -0
- package/dist/handles/handle.d.ts +24 -0
- package/dist/handles/handle.js +93 -0
- package/dist/handles/index.d.ts +3 -0
- package/dist/handles/index.js +4 -0
- package/dist/handles/leases.d.ts +45 -0
- package/dist/handles/leases.js +103 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +7 -0
- package/package.json +43 -4
- package/schema/model-manifest.v1.schema.json +215 -0
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// Asset leases. A loaded handle holds reference-counted leases on the verified local assets it needs;
|
|
2
|
+
// manager eviction or deletion cannot remove a leased asset. Leases constrain the manager, not the
|
|
3
|
+
// browser's ability to reclaim storage: when the platform takes an asset anyway, the lease is
|
|
4
|
+
// invalidated, affected operations settle and release their resources, and nothing repairs over the
|
|
5
|
+
// network inside an operation. Reacquisition and re-admission happen outside engine execution, under
|
|
6
|
+
// the app's consent policy.
|
|
7
|
+
/** Every cause maps to exactly one manager error and settlement rule (exhaustive by its type). */
|
|
8
|
+
export const LEASE_INVALIDATION = Object.freeze({
|
|
9
|
+
'browser-eviction': { error: 'evicted', settlement: 'fail-pending-and-release' },
|
|
10
|
+
corruption: { error: 'corrupt', settlement: 'fail-pending-and-release' },
|
|
11
|
+
'cross-tab-deletion': { error: 'invalidated', settlement: 'fail-pending-and-release' },
|
|
12
|
+
'device-loss': { error: 'invalidated', settlement: 'fail-pending-and-dispose-handle' },
|
|
13
|
+
'worker-loss': { error: 'invalidated', settlement: 'fail-pending-and-dispose-handle' },
|
|
14
|
+
});
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import type { CancellationSignal, LoadedModelCapability } from 'stylegan-js';
|
|
2
|
+
import type { AcquisitionBudget, LiveResidencyLimit } from './budgets.ts';
|
|
3
|
+
import type { ManagerError, Result } from './errors.ts';
|
|
4
|
+
import type { AcquisitionGrant, GrantDecision, GrantOwnerId } from './grant.ts';
|
|
5
|
+
import type { AssetLease, LeaseInvalidationCause } from './leases.ts';
|
|
6
|
+
import type { AssetDescriptor, ModelManifestV1 } from './manifest.ts';
|
|
7
|
+
/** Inventory of one asset as last observed; `unknown` never authorises a fetch. */
|
|
8
|
+
export type AssetInventory = 'verified-local' | 'partial' | 'absent' | 'unknown';
|
|
9
|
+
export interface ManagerStatus {
|
|
10
|
+
readonly manifestSha256: string;
|
|
11
|
+
readonly assets: readonly {
|
|
12
|
+
readonly sha256: string;
|
|
13
|
+
readonly size: number;
|
|
14
|
+
readonly inventory: AssetInventory;
|
|
15
|
+
readonly leased: boolean;
|
|
16
|
+
}[];
|
|
17
|
+
/** Bytes still to transfer for the approved scope, or null when inventory is unknown. */
|
|
18
|
+
readonly remainingBytes: number | null;
|
|
19
|
+
readonly persistentStorage: 'granted' | 'not-granted' | 'unknown';
|
|
20
|
+
}
|
|
21
|
+
export interface ManagerCapabilities {
|
|
22
|
+
readonly opfs: boolean;
|
|
23
|
+
readonly opfsSyncHandles: boolean;
|
|
24
|
+
readonly cacheStorage: boolean;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Reads verified local bytes only. `allowRepair` is fixed at false across OPFS and Cache Storage: a
|
|
28
|
+
* missing or corrupt unit is an error, never a fetch. (`readOnly`, `has()` or `peek()` alone are not
|
|
29
|
+
* this boundary; the type is.)
|
|
30
|
+
*/
|
|
31
|
+
export interface VerifiedLocalReader {
|
|
32
|
+
readonly allowRepair: false;
|
|
33
|
+
/** Exact-length bytes whose platform SHA-256 matched on this read. */
|
|
34
|
+
read(asset: AssetDescriptor): Promise<Result<Uint8Array, ManagerError>>;
|
|
35
|
+
}
|
|
36
|
+
/** A loaded model: the engine capability plus the leases that keep its bytes. */
|
|
37
|
+
export interface LoadedModelHandle {
|
|
38
|
+
readonly manifestSha256: string;
|
|
39
|
+
readonly capability: LoadedModelCapability;
|
|
40
|
+
readonly leases: readonly AssetLease[];
|
|
41
|
+
/** Fired once when any lease is invalidated; the handle's pending operations then settle. */
|
|
42
|
+
onInvalidated(listener: (cause: LeaseInvalidationCause) => void): void;
|
|
43
|
+
release(): Promise<void>;
|
|
44
|
+
}
|
|
45
|
+
export interface ModelManager {
|
|
46
|
+
/** Acquisition-free. */
|
|
47
|
+
status(): Promise<Result<ManagerStatus, ManagerError>>;
|
|
48
|
+
/** Acquisition-free. */
|
|
49
|
+
capabilities(): ManagerCapabilities;
|
|
50
|
+
/** Records the app's decision on a grant; only `approved` lets acquire() transfer bytes. */
|
|
51
|
+
authorize(grant: AcquisitionGrant, decision: GrantDecision): void;
|
|
52
|
+
/** Transfers the grant's scope within its budget; verified chunks are kept on cancel. */
|
|
53
|
+
acquire(owner: GrantOwnerId, budget: AcquisitionBudget): Promise<Result<void, ManagerError>>;
|
|
54
|
+
/** Re-hashes local bytes; a corrupt unit is removed and reported, not refetched here. */
|
|
55
|
+
verify(assets: readonly AssetDescriptor[]): Promise<Result<void, ManagerError>>;
|
|
56
|
+
/** Builds a loaded handle over verified local bytes only. */
|
|
57
|
+
load(manifest: ModelManifestV1, reader: VerifiedLocalReader, residency: LiveResidencyLimit): Promise<Result<LoadedModelHandle, ManagerError>>;
|
|
58
|
+
/** Leases the assets a handle needs; the manager will not evict them while held. */
|
|
59
|
+
lease(sha256: readonly string[]): Result<readonly AssetLease[], ManagerError>;
|
|
60
|
+
/** Called by the platform adapters when a leased asset goes away underneath. */
|
|
61
|
+
invalidate(sha256: string, cause: LeaseInvalidationCause): void;
|
|
62
|
+
/** Cancels this owner's acquisition; a shared fetch stops when its last approved owner leaves. */
|
|
63
|
+
cancel(owner: GrantOwnerId): void;
|
|
64
|
+
dispose(): Promise<void>;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* The manager is constructed with no globals and no I/O: storage backends and the fetch function
|
|
68
|
+
* arrive as arguments, and nothing starts until a grant is authorised.
|
|
69
|
+
*/
|
|
70
|
+
export type CreateModelManager = (options: {
|
|
71
|
+
readonly manifest: ModelManifestV1;
|
|
72
|
+
readonly manifestSha256: string;
|
|
73
|
+
readonly storage: ManagerStorage;
|
|
74
|
+
readonly fetcher: ManagerFetcher;
|
|
75
|
+
}) => ModelManager;
|
|
76
|
+
/** Storage backends handed in by the caller (OPFS root, Cache Storage), typed by the implementation bead. */
|
|
77
|
+
export interface ManagerStorage {
|
|
78
|
+
readonly opfsRoot?: object;
|
|
79
|
+
readonly cacheStorage?: object;
|
|
80
|
+
}
|
|
81
|
+
/** The network, handed in; only acquire() under an approved grant calls it. */
|
|
82
|
+
export type ManagerFetcher = (url: string, init: {
|
|
83
|
+
readonly signal?: CancellationSignal;
|
|
84
|
+
}) => Promise<{
|
|
85
|
+
readonly ok: boolean;
|
|
86
|
+
readonly status: number;
|
|
87
|
+
readonly body: object | null;
|
|
88
|
+
}>;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// Manager lifecycle: construct, authorise, acquire, verify, load, lease, invalidate, dispose.
|
|
2
|
+
//
|
|
3
|
+
// Survey inputs (classic a42829b): Assets/model-cache.mjs (acquire/bytes/open with network repair,
|
|
4
|
+
// per-read platform SHA, exact-length buffers, unit corruption repair, URL-independent pinned reuse,
|
|
5
|
+
// Cache Storage fallback) and Assets/shard-store.mjs (OPFS shards, Safari worker sync handles). Those
|
|
6
|
+
// mechanisms are retained inside the manager. What crosses to the engine is only a loaded handle
|
|
7
|
+
// over verified local bytes: the repair-capable handle never does, and neither do status() or
|
|
8
|
+
// capabilities(), which read state without starting any acquisition. Candidate cache identities
|
|
9
|
+
// (checkface-model-blobs-v1) and on-origin result/session formats stay compatible; model caches are
|
|
10
|
+
// separate from app retention, and model-cache eviction never deletes exports or recovery records.
|
|
11
|
+
// An in-flight app uses one immutable manifest identity.
|
|
12
|
+
export {};
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import type { Result } from './errors.ts';
|
|
2
|
+
export declare const MANIFEST_SCHEMA_MAJOR = 1;
|
|
3
|
+
/** The bounded e4e stream's WASM heap limit (encoderStream.maxWasmBytes in the candidate). */
|
|
4
|
+
export declare const E4E_MAX_WASM_BYTES = 268435456;
|
|
5
|
+
/**
|
|
6
|
+
* Where an asset lives: hosted at an https `url`, or unpublished at a relative `file` path, the form
|
|
7
|
+
* model-conv writes before hosting adds URLs. The manager loads hosted manifests only.
|
|
8
|
+
*/
|
|
9
|
+
export type AssetLocation = {
|
|
10
|
+
readonly url: string;
|
|
11
|
+
readonly file?: never;
|
|
12
|
+
} | {
|
|
13
|
+
readonly file: string;
|
|
14
|
+
readonly url?: never;
|
|
15
|
+
};
|
|
16
|
+
/** One downloadable file, addressed by content; large files arrive as verified chunks. */
|
|
17
|
+
export type AssetDescriptor = AssetLocation & {
|
|
18
|
+
readonly sha256: string;
|
|
19
|
+
readonly size: number;
|
|
20
|
+
readonly chunks?: readonly (AssetLocation & {
|
|
21
|
+
readonly sha256: string;
|
|
22
|
+
readonly size: number;
|
|
23
|
+
})[];
|
|
24
|
+
};
|
|
25
|
+
export type NoiseAsset = AssetDescriptor & {
|
|
26
|
+
readonly name: string;
|
|
27
|
+
readonly shape: readonly number[];
|
|
28
|
+
};
|
|
29
|
+
export type EncoderStreamDescriptor = AssetDescriptor & {
|
|
30
|
+
readonly sourceEncoderSha256: string;
|
|
31
|
+
readonly preprocessingSha256: string;
|
|
32
|
+
/** Admitted on phones (by its measured memory), never a blanket phone rule. */
|
|
33
|
+
readonly phoneAdmitted: boolean;
|
|
34
|
+
readonly maxWasmBytes: number;
|
|
35
|
+
};
|
|
36
|
+
/** Which kernel candidate produced the shipped kernel, and from what source. */
|
|
37
|
+
export interface KernelProvenance {
|
|
38
|
+
readonly candidateId: string;
|
|
39
|
+
readonly sourceHash: string;
|
|
40
|
+
readonly sha256: string;
|
|
41
|
+
}
|
|
42
|
+
export interface ModelManifestV1 {
|
|
43
|
+
readonly schemaVersion: typeof MANIFEST_SCHEMA_MAJOR;
|
|
44
|
+
readonly bundleVersion: string;
|
|
45
|
+
readonly modelSourceSha256: string;
|
|
46
|
+
readonly noiseSha256: string;
|
|
47
|
+
readonly mapping: AssetDescriptor;
|
|
48
|
+
readonly synthesis: AssetDescriptor;
|
|
49
|
+
readonly average?: AssetDescriptor;
|
|
50
|
+
readonly noise: readonly NoiseAsset[];
|
|
51
|
+
readonly encoder?: AssetDescriptor;
|
|
52
|
+
readonly encoderStream?: EncoderStreamDescriptor;
|
|
53
|
+
readonly landmarks?: AssetDescriptor;
|
|
54
|
+
readonly alignmentSha256?: string;
|
|
55
|
+
readonly kernel?: KernelProvenance;
|
|
56
|
+
readonly releaseQualified?: boolean;
|
|
57
|
+
/** Everything else in major 1, kept as parsed JSON. */
|
|
58
|
+
readonly [extra: string]: unknown;
|
|
59
|
+
}
|
|
60
|
+
/** The app's runtime manifest: a model manifest that names its kernel provenance. */
|
|
61
|
+
export type RuntimeManifest = ModelManifestV1 & {
|
|
62
|
+
readonly kernel: KernelProvenance;
|
|
63
|
+
};
|
|
64
|
+
/** Generator, photo encoder and preprocessing identities, kept separate. */
|
|
65
|
+
export interface AssetIdentity {
|
|
66
|
+
readonly generator: {
|
|
67
|
+
readonly modelSourceSha256: string;
|
|
68
|
+
readonly noiseSha256: string;
|
|
69
|
+
readonly mappingSha256: string;
|
|
70
|
+
readonly synthesisSha256: string;
|
|
71
|
+
};
|
|
72
|
+
readonly photoEncoder?: {
|
|
73
|
+
readonly sourceEncoderSha256: string;
|
|
74
|
+
readonly streamSha256: string;
|
|
75
|
+
};
|
|
76
|
+
readonly preprocessing?: {
|
|
77
|
+
readonly alignmentSha256: string;
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
export type ManifestErrorCode = 'not-an-object' | 'newer-major' | 'unsupported-major' | 'invalid-field' | 'invalid-asset';
|
|
81
|
+
export interface ManifestError {
|
|
82
|
+
readonly code: ManifestErrorCode;
|
|
83
|
+
/** JSON path of the offending value. */
|
|
84
|
+
readonly path: string;
|
|
85
|
+
readonly message: string;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Validates a manifest from the network or a producer. An unknown or newer major is rejected.
|
|
89
|
+
* Hosted assets (url) are required unless `unpublished` is set, as a producer checking its own
|
|
90
|
+
* output before hosting would.
|
|
91
|
+
*/
|
|
92
|
+
export declare function parseModelManifest(value: unknown, options?: {
|
|
93
|
+
readonly unpublished?: boolean;
|
|
94
|
+
}): Result<ModelManifestV1, ManifestError>;
|
|
95
|
+
export declare function assetIdentity(m: ModelManifestV1): AssetIdentity;
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
// Model manifest compatibility. The manager owns the producer-facing JSON schema
|
|
2
|
+
// (schema/model-manifest.v1.schema.json); cloudflare-model-host and model-conv validate the manifests
|
|
3
|
+
// they emit against it as a dev-dependency, so the manager never depends on them at runtime. Weights
|
|
4
|
+
// stay out of tarballs and private source provenance stays out of published manifests. Descriptor and
|
|
5
|
+
// content identities survive renames: assets are addressed by SHA-256 (the WebGL coefficient assets
|
|
6
|
+
// also feed direct WebGPU, so they stay even though WebGL execution is gone).
|
|
7
|
+
//
|
|
8
|
+
// Shape (the candidate runtime manifest, next.facemorph.me /runtime/manifest.json, SHA-256 d9e37e50…):
|
|
9
|
+
// schemaVersion 1; generator assets mapping, synthesis, average, noise[]; identities modelSourceSha256
|
|
10
|
+
// and noiseSha256; optional runtime/webgpu/webgl/codec bundles, canaries, the photo encoder (encoder,
|
|
11
|
+
// encoderStream with phoneAdmitted and maxWasmBytes), alignment (landmarks, photo, alignmentSha256)
|
|
12
|
+
// and kernel provenance (candidateId, sourceHash). Fields beyond these are allowed within major 1.
|
|
13
|
+
export const MANIFEST_SCHEMA_MAJOR = 1;
|
|
14
|
+
/** The bounded e4e stream's WASM heap limit (encoderStream.maxWasmBytes in the candidate). */
|
|
15
|
+
export const E4E_MAX_WASM_BYTES = 268435456;
|
|
16
|
+
const HEX64 = /^[0-9a-f]{64}$/;
|
|
17
|
+
const isRecord = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
18
|
+
class Reject extends Error {
|
|
19
|
+
error;
|
|
20
|
+
constructor(code, path, message) {
|
|
21
|
+
super(message);
|
|
22
|
+
this.error = { code, path, message };
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
const field = (path, message) => {
|
|
26
|
+
throw new Reject('invalid-field', path, message);
|
|
27
|
+
};
|
|
28
|
+
const RELATIVE_FILE = /^(?![/\\])(?!.*(^|\/)\.\.(\/|$))(?![a-zA-Z][a-zA-Z0-9+.-]*:)[^\s\\]+$/;
|
|
29
|
+
/** Exactly one of an https url without credentials, or (when allowed) a relative file path. */
|
|
30
|
+
function location(v, path, unpublished) {
|
|
31
|
+
if ('url' in v === 'file' in v)
|
|
32
|
+
throw new Reject('invalid-asset', path, 'exactly one of url and file');
|
|
33
|
+
if ('file' in v) {
|
|
34
|
+
if (!unpublished)
|
|
35
|
+
throw new Reject('invalid-asset', `${path}.file`, 'an unpublished asset where a hosted url is required');
|
|
36
|
+
if (typeof v.file !== 'string' || !RELATIVE_FILE.test(v.file))
|
|
37
|
+
throw new Reject('invalid-asset', `${path}.file`, 'a relative path inside the output');
|
|
38
|
+
}
|
|
39
|
+
else if (typeof v.url !== 'string' || !/^https:\/\/[^/@\s]+\/\S*$/.test(v.url)) {
|
|
40
|
+
throw new Reject('invalid-asset', `${path}.url`, 'an https URL without credentials');
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
function asset(v, path, unpublished) {
|
|
44
|
+
if (!isRecord(v))
|
|
45
|
+
throw new Reject('invalid-asset', path, 'an asset descriptor');
|
|
46
|
+
location(v, path, unpublished);
|
|
47
|
+
if (typeof v.sha256 !== 'string' || !HEX64.test(v.sha256))
|
|
48
|
+
throw new Reject('invalid-asset', `${path}.sha256`, 'lowercase hex SHA-256');
|
|
49
|
+
if (!Number.isSafeInteger(v.size) || v.size < 0)
|
|
50
|
+
throw new Reject('invalid-asset', `${path}.size`, 'a non-negative integer');
|
|
51
|
+
if (v.chunks !== undefined) {
|
|
52
|
+
if (!Array.isArray(v.chunks) || v.chunks.length === 0)
|
|
53
|
+
throw new Reject('invalid-asset', `${path}.chunks`, 'a non-empty list');
|
|
54
|
+
let total = 0;
|
|
55
|
+
v.chunks.forEach((c, i) => {
|
|
56
|
+
const p = `${path}.chunks[${i}]`;
|
|
57
|
+
if (!isRecord(c))
|
|
58
|
+
throw new Reject('invalid-asset', p, 'a chunk');
|
|
59
|
+
location(c, p, unpublished);
|
|
60
|
+
if (typeof c.sha256 !== 'string' || !HEX64.test(c.sha256))
|
|
61
|
+
throw new Reject('invalid-asset', `${p}.sha256`, 'lowercase hex SHA-256');
|
|
62
|
+
if (!Number.isSafeInteger(c.size) || c.size <= 0)
|
|
63
|
+
throw new Reject('invalid-asset', `${p}.size`, 'a positive integer');
|
|
64
|
+
total += c.size;
|
|
65
|
+
});
|
|
66
|
+
if (total !== v.size)
|
|
67
|
+
throw new Reject('invalid-asset', `${path}.chunks`, 'chunk sizes do not add up to the asset size');
|
|
68
|
+
}
|
|
69
|
+
return v;
|
|
70
|
+
}
|
|
71
|
+
/** Every nested asset descriptor (sha256, size and a url or file), as the candidate's collectAssets walks them. */
|
|
72
|
+
function eachAsset(v, path, unpublished, depth = 0) {
|
|
73
|
+
if (!isRecord(v) && !Array.isArray(v))
|
|
74
|
+
return;
|
|
75
|
+
if (isRecord(v) && 'sha256' in v && 'size' in v && ('url' in v || 'file' in v)) {
|
|
76
|
+
asset(v, path, unpublished);
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
if (depth >= 4)
|
|
80
|
+
return;
|
|
81
|
+
for (const [k, item] of Object.entries(v))
|
|
82
|
+
eachAsset(item, Array.isArray(v) ? `${path}[${k}]` : `${path}.${k}`, unpublished, depth + 1);
|
|
83
|
+
}
|
|
84
|
+
const hex = (v, path) => {
|
|
85
|
+
if (typeof v !== 'string' || !HEX64.test(v))
|
|
86
|
+
field(path, 'lowercase hex SHA-256');
|
|
87
|
+
};
|
|
88
|
+
function manifest(v, unpublished) {
|
|
89
|
+
if (!isRecord(v))
|
|
90
|
+
throw new Reject('not-an-object', '$', 'a manifest is a JSON object');
|
|
91
|
+
const major = v.schemaVersion;
|
|
92
|
+
if (!Number.isSafeInteger(major))
|
|
93
|
+
field('$.schemaVersion', 'an integer major version');
|
|
94
|
+
if (major > MANIFEST_SCHEMA_MAJOR)
|
|
95
|
+
throw new Reject('newer-major', '$.schemaVersion', `major ${String(major)} is newer than this manager (${MANIFEST_SCHEMA_MAJOR})`);
|
|
96
|
+
if (major !== MANIFEST_SCHEMA_MAJOR)
|
|
97
|
+
throw new Reject('unsupported-major', '$.schemaVersion', `major ${String(major)} is not supported`);
|
|
98
|
+
if (typeof v.bundleVersion !== 'string' || v.bundleVersion === '')
|
|
99
|
+
field('$.bundleVersion', 'a non-empty string');
|
|
100
|
+
hex(v.modelSourceSha256, '$.modelSourceSha256');
|
|
101
|
+
hex(v.noiseSha256, '$.noiseSha256');
|
|
102
|
+
asset(v.mapping, '$.mapping', unpublished);
|
|
103
|
+
asset(v.synthesis, '$.synthesis', unpublished);
|
|
104
|
+
if (!Array.isArray(v.noise) || v.noise.length === 0)
|
|
105
|
+
field('$.noise', 'a non-empty list');
|
|
106
|
+
v.noise.forEach((n, i) => {
|
|
107
|
+
asset(n, `$.noise[${i}]`, unpublished);
|
|
108
|
+
const r = n;
|
|
109
|
+
if (typeof r.name !== 'string' ||
|
|
110
|
+
!Array.isArray(r.shape) ||
|
|
111
|
+
!r.shape.every((d) => Number.isSafeInteger(d) && d > 0))
|
|
112
|
+
field(`$.noise[${i}]`, 'name and shape');
|
|
113
|
+
});
|
|
114
|
+
if (v.releaseQualified !== undefined && typeof v.releaseQualified !== 'boolean')
|
|
115
|
+
field('$.releaseQualified', 'a boolean');
|
|
116
|
+
if (v.alignmentSha256 !== undefined)
|
|
117
|
+
hex(v.alignmentSha256, '$.alignmentSha256');
|
|
118
|
+
const s = v.encoderStream;
|
|
119
|
+
if (s !== undefined) {
|
|
120
|
+
asset(s, '$.encoderStream', unpublished);
|
|
121
|
+
const e = s;
|
|
122
|
+
hex(e.sourceEncoderSha256, '$.encoderStream.sourceEncoderSha256');
|
|
123
|
+
hex(e.preprocessingSha256, '$.encoderStream.preprocessingSha256');
|
|
124
|
+
if (typeof e.phoneAdmitted !== 'boolean')
|
|
125
|
+
field('$.encoderStream.phoneAdmitted', 'a boolean');
|
|
126
|
+
if (!Number.isSafeInteger(e.maxWasmBytes) ||
|
|
127
|
+
e.maxWasmBytes <= 0 ||
|
|
128
|
+
e.maxWasmBytes > E4E_MAX_WASM_BYTES)
|
|
129
|
+
field('$.encoderStream.maxWasmBytes', `1 to ${E4E_MAX_WASM_BYTES}`);
|
|
130
|
+
}
|
|
131
|
+
const k = v.kernel;
|
|
132
|
+
if (k !== undefined) {
|
|
133
|
+
if (!isRecord(k) || typeof k.candidateId !== 'string' || k.candidateId === '')
|
|
134
|
+
field('$.kernel.candidateId', 'a candidate id');
|
|
135
|
+
hex(k.sourceHash, '$.kernel.sourceHash');
|
|
136
|
+
hex(k.sha256, '$.kernel.sha256');
|
|
137
|
+
}
|
|
138
|
+
eachAsset(v, '$', unpublished);
|
|
139
|
+
return v;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Validates a manifest from the network or a producer. An unknown or newer major is rejected.
|
|
143
|
+
* Hosted assets (url) are required unless `unpublished` is set, as a producer checking its own
|
|
144
|
+
* output before hosting would.
|
|
145
|
+
*/
|
|
146
|
+
export function parseModelManifest(value, options = {}) {
|
|
147
|
+
try {
|
|
148
|
+
return { ok: true, value: manifest(value, options.unpublished === true) };
|
|
149
|
+
}
|
|
150
|
+
catch (e) {
|
|
151
|
+
if (e instanceof Reject)
|
|
152
|
+
return { ok: false, error: e.error };
|
|
153
|
+
throw e;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
export function assetIdentity(m) {
|
|
157
|
+
return {
|
|
158
|
+
generator: {
|
|
159
|
+
modelSourceSha256: m.modelSourceSha256,
|
|
160
|
+
noiseSha256: m.noiseSha256,
|
|
161
|
+
mappingSha256: m.mapping.sha256,
|
|
162
|
+
synthesisSha256: m.synthesis.sha256,
|
|
163
|
+
},
|
|
164
|
+
...(m.encoderStream
|
|
165
|
+
? {
|
|
166
|
+
photoEncoder: {
|
|
167
|
+
sourceEncoderSha256: m.encoderStream.sourceEncoderSha256,
|
|
168
|
+
streamSha256: m.encoderStream.sha256,
|
|
169
|
+
},
|
|
170
|
+
}
|
|
171
|
+
: {}),
|
|
172
|
+
...(m.alignmentSha256 ? { preprocessing: { alignmentSha256: m.alignmentSha256 } } : {}),
|
|
173
|
+
};
|
|
174
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { LeaseRegistry, Removable } from './leases.ts';
|
|
2
|
+
export declare const DELETION_CHANNEL = "facemorph-model-assets-v1";
|
|
3
|
+
/** The BroadcastChannel surface used here, structurally. */
|
|
4
|
+
export interface ChannelLike {
|
|
5
|
+
postMessage(message: unknown): void;
|
|
6
|
+
addEventListener(type: 'message', listener: (event: {
|
|
7
|
+
data: unknown;
|
|
8
|
+
}) => void): void;
|
|
9
|
+
removeEventListener(type: 'message', listener: (event: {
|
|
10
|
+
data: unknown;
|
|
11
|
+
}) => void): void;
|
|
12
|
+
}
|
|
13
|
+
/** Removes the assets from every store and tells the other tabs. Returns what it removed. */
|
|
14
|
+
export declare function deleteAssets(sha256s: readonly string[], stores: readonly Removable[], channel: ChannelLike): Promise<string[]>;
|
|
15
|
+
/** Invalidates this tab's leases on assets another tab deleted. Returns the unsubscribe function. */
|
|
16
|
+
export declare function listenForDeletions(channel: ChannelLike, registry: LeaseRegistry): () => void;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// Deletion across tabs (fm-ffn7). Eviction respects leases in every tab (leases.ts, Web Locks). Deletion is the
|
|
2
|
+
// person's explicit action (clear the model cache): it removes the assets even while another tab holds them, and says
|
|
3
|
+
// so on a BroadcastChannel. Every other tab that listens invalidates its leases on those assets with the
|
|
4
|
+
// 'cross-tab-deletion' cause: its handles' pending operations settle with the typed error and release, and nothing is
|
|
5
|
+
// refetched. An asset that vanishes without a message (site data cleared) is caught by the next verified read.
|
|
6
|
+
export const DELETION_CHANNEL = 'facemorph-model-assets-v1';
|
|
7
|
+
const isDeleted = (d) => !!d &&
|
|
8
|
+
d.type === 'deleted' &&
|
|
9
|
+
Array.isArray(d.sha256s) &&
|
|
10
|
+
d.sha256s.every((s) => typeof s === 'string' && /^[0-9a-f]{64}$/.test(s));
|
|
11
|
+
/** Removes the assets from every store and tells the other tabs. Returns what it removed. */
|
|
12
|
+
export async function deleteAssets(sha256s, stores, channel) {
|
|
13
|
+
for (const sha of sha256s)
|
|
14
|
+
for (const store of stores)
|
|
15
|
+
await store.remove(sha);
|
|
16
|
+
channel.postMessage({ type: 'deleted', sha256s: [...sha256s] });
|
|
17
|
+
return [...sha256s];
|
|
18
|
+
}
|
|
19
|
+
/** Invalidates this tab's leases on assets another tab deleted. Returns the unsubscribe function. */
|
|
20
|
+
export function listenForDeletions(channel, registry) {
|
|
21
|
+
const onMessage = (event) => {
|
|
22
|
+
if (!isDeleted(event.data))
|
|
23
|
+
return;
|
|
24
|
+
for (const sha of event.data.sha256s)
|
|
25
|
+
registry.invalidate(sha, 'cross-tab-deletion');
|
|
26
|
+
};
|
|
27
|
+
channel.addEventListener('message', onMessage);
|
|
28
|
+
return () => channel.removeEventListener('message', onMessage);
|
|
29
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { LoadedModelCapability } from 'stylegan-js';
|
|
2
|
+
import type { ManagerError } from '../contracts/errors.ts';
|
|
3
|
+
import type { LoadedModelHandle } from '../contracts/lifecycle.ts';
|
|
4
|
+
import type { LeaseRegistry } from './leases.ts';
|
|
5
|
+
/** Thrown by a handle's operations once it is invalidated or released; `error` is the structured manager error. */
|
|
6
|
+
export declare class HandleUnavailable extends Error {
|
|
7
|
+
readonly error: ManagerError;
|
|
8
|
+
constructor(error: ManagerError);
|
|
9
|
+
}
|
|
10
|
+
export interface HandleState {
|
|
11
|
+
readonly pending: number;
|
|
12
|
+
readonly state: 'live' | 'invalidated' | 'released';
|
|
13
|
+
}
|
|
14
|
+
export declare function createLoadedHandle({ manifestSha256, capability, assets, registry, }: {
|
|
15
|
+
manifestSha256: string;
|
|
16
|
+
capability: LoadedModelCapability;
|
|
17
|
+
assets: readonly {
|
|
18
|
+
sha256: string;
|
|
19
|
+
bytes: number;
|
|
20
|
+
}[];
|
|
21
|
+
registry: LeaseRegistry;
|
|
22
|
+
}): LoadedModelHandle & {
|
|
23
|
+
inspect(): HandleState;
|
|
24
|
+
};
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// A loaded model handle (fm-ffn7, contracts/lifecycle.ts LoadedModelHandle): the engine capability plus the leases
|
|
2
|
+
// that keep its verified local bytes. The capability it hands out cannot acquire anything: it runs only what the
|
|
3
|
+
// adapter loaded from a VerifiedLocalReader. When any leased asset is invalidated, every pending operation settles
|
|
4
|
+
// at once as failed with the typed manager error, the adapter's sessions are disposed and the leases released; later
|
|
5
|
+
// calls fail the same way. Nothing is refetched: reacquisition and re-admission are the app's, outside the engine.
|
|
6
|
+
// release() does the same without an error: pending operations settle, then sessions and leases go.
|
|
7
|
+
/** Thrown by a handle's operations once it is invalidated or released; `error` is the structured manager error. */
|
|
8
|
+
export class HandleUnavailable extends Error {
|
|
9
|
+
error;
|
|
10
|
+
constructor(error) {
|
|
11
|
+
super(error.message);
|
|
12
|
+
this.name = 'HandleUnavailable';
|
|
13
|
+
this.error = error;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
export function createLoadedHandle({ manifestSha256, capability, assets, registry, }) {
|
|
17
|
+
let state = 'live';
|
|
18
|
+
let failure = null;
|
|
19
|
+
const pending = new Set();
|
|
20
|
+
const listeners = [];
|
|
21
|
+
let disposed = null;
|
|
22
|
+
const shutDown = () => (disposed ??= capability.dispose().finally(() => leases.forEach((l) => l.release())));
|
|
23
|
+
const holder = {
|
|
24
|
+
invalidated(cause, error) {
|
|
25
|
+
if (state !== 'live')
|
|
26
|
+
return;
|
|
27
|
+
state = 'invalidated';
|
|
28
|
+
failure = error;
|
|
29
|
+
for (const reject of pending)
|
|
30
|
+
reject(new HandleUnavailable(error));
|
|
31
|
+
pending.clear();
|
|
32
|
+
// Either settlement rule (contracts/leases.ts) releases the sessions and leases: the asset is gone, so the
|
|
33
|
+
// handle cannot run again; device and worker loss also leave nothing of the handle to reuse.
|
|
34
|
+
void shutDown();
|
|
35
|
+
for (const l of listeners)
|
|
36
|
+
l(cause);
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
const leases = registry.lease(assets, holder);
|
|
40
|
+
const unavailable = () => new HandleUnavailable(failure ?? {
|
|
41
|
+
code: 'invalidated',
|
|
42
|
+
cause: 'worker-loss',
|
|
43
|
+
message: 'the loaded handle was released',
|
|
44
|
+
});
|
|
45
|
+
/** Runs an operation that settles early, as failed, if the handle is invalidated or released meanwhile. */
|
|
46
|
+
function guard(run) {
|
|
47
|
+
if (state !== 'live')
|
|
48
|
+
return Promise.reject(unavailable());
|
|
49
|
+
return new Promise((resolve, reject) => {
|
|
50
|
+
const settle = (e) => reject(e);
|
|
51
|
+
pending.add(settle);
|
|
52
|
+
run().then((v) => {
|
|
53
|
+
if (!pending.delete(settle))
|
|
54
|
+
return; // already settled by invalidation or release
|
|
55
|
+
resolve(v);
|
|
56
|
+
}, (e) => {
|
|
57
|
+
if (!pending.delete(settle))
|
|
58
|
+
return;
|
|
59
|
+
reject(e);
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
const wrapped = {
|
|
64
|
+
identity: capability.identity,
|
|
65
|
+
latent: capability.latent,
|
|
66
|
+
image: capability.image,
|
|
67
|
+
provider: capability.provider,
|
|
68
|
+
unsupported: capability.unsupported,
|
|
69
|
+
map: (request, signal, onTiming) => guard(() => capability.map(request, signal, onTiming)),
|
|
70
|
+
synthesize: (request, signal, onTiming) => guard(() => capability.synthesize(request, signal, onTiming)),
|
|
71
|
+
dispose: () => handle.release(),
|
|
72
|
+
};
|
|
73
|
+
const handle = {
|
|
74
|
+
manifestSha256,
|
|
75
|
+
capability: wrapped,
|
|
76
|
+
leases,
|
|
77
|
+
onInvalidated(listener) {
|
|
78
|
+
listeners.push(listener);
|
|
79
|
+
},
|
|
80
|
+
async release() {
|
|
81
|
+
if (state === 'live') {
|
|
82
|
+
state = 'released';
|
|
83
|
+
const error = unavailable();
|
|
84
|
+
for (const reject of pending)
|
|
85
|
+
reject(error);
|
|
86
|
+
pending.clear();
|
|
87
|
+
}
|
|
88
|
+
await shutDown();
|
|
89
|
+
},
|
|
90
|
+
inspect: () => ({ pending: pending.size, state }),
|
|
91
|
+
};
|
|
92
|
+
return handle;
|
|
93
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { ManagerError } from '../contracts/errors.ts';
|
|
2
|
+
import { type AssetLease, type LeaseInvalidationCause } from '../contracts/leases.ts';
|
|
3
|
+
export interface LeaseHolder {
|
|
4
|
+
/** Called once per holder when any of its assets is invalidated. */
|
|
5
|
+
invalidated(cause: LeaseInvalidationCause, error: ManagerError & {
|
|
6
|
+
code: 'invalidated' | 'evicted' | 'corrupt';
|
|
7
|
+
}): void;
|
|
8
|
+
}
|
|
9
|
+
export interface LeaseRegistry {
|
|
10
|
+
/** Leases each asset for `holder`; the returned leases release individually (idempotent). */
|
|
11
|
+
lease(assets: readonly {
|
|
12
|
+
sha256: string;
|
|
13
|
+
bytes: number;
|
|
14
|
+
}[], holder: LeaseHolder): AssetLease[];
|
|
15
|
+
refCount(sha256: string): number;
|
|
16
|
+
leased(): string[];
|
|
17
|
+
/** The platform took `sha256` from under its holders: each holder hears once. */
|
|
18
|
+
invalidate(sha256: string, cause: LeaseInvalidationCause): number;
|
|
19
|
+
}
|
|
20
|
+
export declare function invalidationError(sha256: string, cause: LeaseInvalidationCause): ManagerError & {
|
|
21
|
+
code: 'invalidated' | 'evicted' | 'corrupt';
|
|
22
|
+
};
|
|
23
|
+
/** The Web Locks API's request(), structurally; across tabs a held lease is a shared lock on its asset. */
|
|
24
|
+
export interface AssetLocks {
|
|
25
|
+
request<T>(name: string, options: {
|
|
26
|
+
mode: 'shared' | 'exclusive';
|
|
27
|
+
ifAvailable?: boolean;
|
|
28
|
+
}, run: (lock: unknown) => Promise<T>): Promise<T>;
|
|
29
|
+
}
|
|
30
|
+
export declare const lockName: (sha256: string) => string;
|
|
31
|
+
/** With `locks`, every leased asset also holds a shared Web Lock until its last local lease is released, so another
|
|
32
|
+
* tab's eviction (which needs the lock exclusively) keeps it too. */
|
|
33
|
+
export declare function createLeaseRegistry({ locks }?: {
|
|
34
|
+
locks?: AssetLocks;
|
|
35
|
+
}): LeaseRegistry;
|
|
36
|
+
/** Where the manager keeps asset bytes: anything that can remove one asset by digest (shard store, blob store). */
|
|
37
|
+
export interface Removable {
|
|
38
|
+
remove(sha256: string): Promise<unknown>;
|
|
39
|
+
}
|
|
40
|
+
/** Manager-controlled eviction: removes the requested assets from every store except leased ones, in this tab (local
|
|
41
|
+
* count) and, with `locks`, in any tab (an asset whose lock cannot be taken exclusively right now is kept). */
|
|
42
|
+
export declare function evictUnleased(sha256s: readonly string[], stores: readonly Removable[], registry: LeaseRegistry, locks?: AssetLocks): Promise<{
|
|
43
|
+
removed: string[];
|
|
44
|
+
kept: string[];
|
|
45
|
+
}>;
|