mirror of
https://github.com/cocos/cocos4.git
synced 2026-11-19 14:52:40 +08:00
worker option
This commit is contained in:
@@ -38,13 +38,17 @@ npm run build
|
||||
|
||||
## 启用功能与选择模式
|
||||
|
||||
在 Creator 的引擎功能裁剪配置中按需要选择(两项默认均关闭):
|
||||
在 Creator 的引擎功能裁剪配置中展开 **Worker** 分组,按需要勾选子项(两项默认均关闭):
|
||||
|
||||
| 功能 | ccbuild 的 features | 从 cc 可用的能力 |
|
||||
| --- | --- | --- |
|
||||
| Worker | `['worker']` | 创建 Worker、收发消息、查询能力,由开发者管理生命周期 |
|
||||
| 基础 Worker 功能 | `['worker']` | 创建 Worker、收发消息、查询能力,由开发者管理生命周期 |
|
||||
| Worker Pool | `['worker-pool']` | 基础 Worker API,以及任务池、队列、超时和安全同步降级 |
|
||||
|
||||
分组标题的勾选框是全选/清空:只选基础 Worker 时显示半选;全选会同时启用 Worker Pool。
|
||||
勾选 Worker Pool 会关联开启基础 Worker;取消基础 Worker 时也会取消 Worker Pool。
|
||||
功能 ID 与项目已有配置保持兼容,无需迁移 `cache` 或 `includeModules`。
|
||||
|
||||
`worker-pool` 依赖 `worker`,Creator 会关联该依赖;直接调用 ccbuild 时,选择 `worker-pool`
|
||||
也会包含两者的导出入口。`exports/worker.ts` 与 `exports/worker-pool.ts` 分别提供公开 API,
|
||||
`cocos/misc/index.ts` 不导出它们。只启用 `worker` 的构建不包含线程池调度器;两项均不启用时,
|
||||
|
||||
@@ -350,13 +350,15 @@
|
||||
"default": false,
|
||||
"label": "i18n:ENGINE.features.worker.label",
|
||||
"description": "i18n:ENGINE.features.worker.description",
|
||||
"enginePlugin": true
|
||||
"enginePlugin": true,
|
||||
"category": "worker"
|
||||
},
|
||||
"worker-pool": {
|
||||
"default": false,
|
||||
"label": "i18n:ENGINE.features.worker_pool.label",
|
||||
"description": "i18n:ENGINE.features.worker_pool.description",
|
||||
"enginePlugin": true,
|
||||
"category": "worker",
|
||||
"dependencies": ["worker"]
|
||||
},
|
||||
"terrain": {
|
||||
@@ -511,6 +513,11 @@
|
||||
"checkable": true,
|
||||
"required": true
|
||||
},
|
||||
"worker": {
|
||||
"label": "i18n:ENGINE.features.categories.worker.label",
|
||||
"description": "i18n:ENGINE.features.categories.worker.description",
|
||||
"checkable": true
|
||||
},
|
||||
"2d": {
|
||||
"label": "i18n:ENGINE.features.categories.2d.label",
|
||||
"description": "i18n:ENGINE.features.categories.2d.description",
|
||||
|
||||
@@ -896,6 +896,10 @@ module.exports = link(mixin({
|
||||
},
|
||||
features: {
|
||||
categories: {
|
||||
worker: {
|
||||
label: 'Worker',
|
||||
description: 'Worker features. The group checkbox selects or clears all items; Worker Pool depends on Basic Worker.',
|
||||
},
|
||||
'2d': {
|
||||
label: '2D',
|
||||
description: '2D',
|
||||
@@ -1134,7 +1138,7 @@ module.exports = link(mixin({
|
||||
description: "Enable WebSocket Server for native. Note: WebSocket must also be enabled.",
|
||||
},
|
||||
worker: {
|
||||
label: "Worker",
|
||||
label: "Basic Worker",
|
||||
description: "Enable cross-platform Worker creation, messaging and capability queries. Manage workers yourself; enable Worker Pool separately for task scheduling and synchronous fallback.",
|
||||
},
|
||||
worker_pool: {
|
||||
|
||||
@@ -874,6 +874,10 @@ module.exports = link(mixin({
|
||||
},
|
||||
features: {
|
||||
categories: {
|
||||
worker: {
|
||||
label: 'Worker',
|
||||
description: 'Worker 功能分组。分组勾选框用于全选或清空;Worker Pool 依赖基础 Worker 功能。',
|
||||
},
|
||||
'2d': {
|
||||
label: '2D',
|
||||
description: '2D',
|
||||
@@ -1112,7 +1116,7 @@ module.exports = link(mixin({
|
||||
description: "对原生启用 WebSocket Server。注意: 必须同时启用 WebSocket。",
|
||||
},
|
||||
worker: {
|
||||
label: "Worker",
|
||||
label: "基础 Worker 功能",
|
||||
description: "启用跨平台 Worker 创建、消息通信和能力查询,由开发者自行管理 Worker。需要任务调度与同步降级时,额外启用 Worker Pool。",
|
||||
},
|
||||
worker_pool: {
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
/**
|
||||
* Regression tests for the serialized function-worker bootstrap source (`createWorkerFromFunction`).
|
||||
*
|
||||
* These tests capture the generated blob source and execute it in a Node `vm` sandbox, so they assert
|
||||
* on what the WORKER ACTUALLY DOES rather than on the string's shape. That matters: the defects fixed
|
||||
* here only manifested at worker runtime, and the previous suite never executed the generated code.
|
||||
*
|
||||
* Fixed defects (all previously reproducible):
|
||||
* P0-2a Cyclic result object -> RangeError (stack overflow). Structured clone handles cycles
|
||||
* natively, so the collector turned a working case into a crash.
|
||||
* P0-2b Deeply nested result -> RangeError. The overflow was then caught and reported as
|
||||
* "Worker result is not serializable", pointing diagnosis at the wrong cause.
|
||||
* P0-2c `for...in` walked the prototype chain, so a buffer inherited from a prototype was
|
||||
* transferred. Structured clone only copies own enumerable properties, so that buffer never
|
||||
* appeared in the reply — the main thread's copy got silently detached. No throw, no log.
|
||||
* P0-2d A hostile getter threw inside the collector and failed the whole task. Collecting the
|
||||
* transfer list is an optimisation; it must never be able to fail the task.
|
||||
*/
|
||||
import * as vm from 'vm';
|
||||
import { createWorker } from '../../cocos/misc/worker';
|
||||
|
||||
let capturedSource = '';
|
||||
|
||||
class FakeBlob {
|
||||
constructor (parts: string[]) {
|
||||
capturedSource = parts.join('');
|
||||
}
|
||||
}
|
||||
class FakeURL {
|
||||
public static createObjectURL = (): string => 'blob:fake';
|
||||
public static revokeObjectURL = (): void => {};
|
||||
}
|
||||
class FakeWorker {
|
||||
public onmessage: ((e: any) => void) | null = null;
|
||||
public onerror: ((e: any) => void) | null = null;
|
||||
public postMessage (_msg: any, _transfer?: any): void {}
|
||||
public terminate (): void {}
|
||||
}
|
||||
|
||||
beforeAll(() => {
|
||||
(globalThis as any).Blob = FakeBlob;
|
||||
(globalThis as any).URL = FakeURL;
|
||||
(globalThis as any).Worker = FakeWorker;
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
delete (globalThis as any).Blob;
|
||||
delete (globalThis as any).URL;
|
||||
delete (globalThis as any).Worker;
|
||||
});
|
||||
|
||||
/** Generate the worker source from `fn`. */
|
||||
function compile (fn: unknown): void {
|
||||
createWorker(fn as any);
|
||||
expect(capturedSource.length).toBeGreaterThan(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the generated worker source in a sandbox and deliver one task.
|
||||
* Returns every postMessage attempt plus the transfer list used for each.
|
||||
*/
|
||||
function runTask (args: unknown[]): { attempts: Array<{ reply: any; transfer: any }> } {
|
||||
const attempts: Array<{ reply: any; transfer: any }> = [];
|
||||
const sandbox: any = {
|
||||
self: {
|
||||
onmessage: null as any,
|
||||
postMessage: (reply: any, transfer?: any): void => { attempts.push({ reply, transfer }); },
|
||||
},
|
||||
Set,
|
||||
Array,
|
||||
Object,
|
||||
ArrayBuffer,
|
||||
Uint8Array,
|
||||
Float32Array,
|
||||
Error,
|
||||
String,
|
||||
Number,
|
||||
};
|
||||
vm.createContext(sandbox);
|
||||
vm.runInContext(capturedSource, sandbox);
|
||||
sandbox.self.onmessage({ data: { id: 1, args } });
|
||||
return { attempts };
|
||||
}
|
||||
|
||||
const transferCount = (t: any): number => (Array.isArray(t) ? t.length : -1);
|
||||
|
||||
describe('Generated worker source: runtime behaviour', () => {
|
||||
beforeEach(() => { capturedSource = ''; });
|
||||
|
||||
test('P0-2a cyclic result object does not overflow the stack', () => {
|
||||
compile(() => {
|
||||
const cyc: any = { buf: new ArrayBuffer(8) };
|
||||
cyc.self = cyc;
|
||||
return cyc;
|
||||
});
|
||||
const { attempts } = runTask([]);
|
||||
expect(attempts[0].reply.ok).toBe(true);
|
||||
expect(transferCount(attempts[0].transfer)).toBe(1);
|
||||
});
|
||||
|
||||
test('P0-2b deeply nested result (50k levels) does not overflow the stack', () => {
|
||||
compile(() => {
|
||||
const root: any = { buf: new ArrayBuffer(8) };
|
||||
let cur = root;
|
||||
for (let i = 0; i < 50000; i++) { cur.n = {}; cur = cur.n; }
|
||||
cur.buf = new ArrayBuffer(8);
|
||||
return root;
|
||||
});
|
||||
const { attempts } = runTask([]);
|
||||
// Past the depth cap the collector stops looking, so only the shallow buffer is found.
|
||||
// The task still succeeds — losing the optimisation is fine, losing the result is not.
|
||||
expect(attempts[0].reply.ok).toBe(true);
|
||||
expect(transferCount(attempts[0].transfer)).toBe(1);
|
||||
});
|
||||
|
||||
test('P0-2c a buffer on the prototype chain is NOT transferred (silent main-thread detach)', () => {
|
||||
compile(() => {
|
||||
function Base (this: any) { this.inheritedBuf = new ArrayBuffer(8); }
|
||||
const obj: any = Object.create(new (Base as any)());
|
||||
obj.ownBuf = new ArrayBuffer(8);
|
||||
return obj;
|
||||
});
|
||||
const { attempts } = runTask([]);
|
||||
expect(attempts[0].reply.ok).toBe(true);
|
||||
// Exactly one buffer: ownBuf. If inheritedBuf were collected it would be detached on the main
|
||||
// thread while never appearing in the cloned reply.
|
||||
expect(transferCount(attempts[0].transfer)).toBe(1);
|
||||
});
|
||||
|
||||
test('P0-2d a hostile getter downgrades to plain clone instead of failing the task', () => {
|
||||
compile(() => {
|
||||
const obj: any = { buf: new ArrayBuffer(8) };
|
||||
Object.defineProperty(obj, 'evil', {
|
||||
enumerable: true,
|
||||
get (): never { throw new Error('hostile getter'); },
|
||||
});
|
||||
return obj;
|
||||
});
|
||||
const { attempts } = runTask([]);
|
||||
expect(attempts[0].reply.ok).toBe(true);
|
||||
// Collection failed, so transfer is undefined -> structured clone path.
|
||||
expect(attempts[0].transfer).toBeUndefined();
|
||||
});
|
||||
|
||||
test('one buffer behind several views is transferred exactly once', () => {
|
||||
compile(() => {
|
||||
const buf = new ArrayBuffer(16);
|
||||
return { a: new Uint8Array(buf), b: new Float32Array(buf), c: buf };
|
||||
});
|
||||
const { attempts } = runTask([]);
|
||||
expect(attempts[0].reply.ok).toBe(true);
|
||||
// Transferring the same buffer twice throws in a real Worker.
|
||||
expect(transferCount(attempts[0].transfer)).toBe(1);
|
||||
});
|
||||
|
||||
test('a null result is handled and produces no transfers', () => {
|
||||
compile(() => null);
|
||||
const { attempts } = runTask([]);
|
||||
expect(attempts[0].reply.ok).toBe(true);
|
||||
expect(attempts[0].reply.value).toBeNull();
|
||||
expect(transferCount(attempts[0].transfer)).toBe(0);
|
||||
});
|
||||
|
||||
test('a primitive result is handled and produces no transfers', () => {
|
||||
compile((a: number, b: number) => a + b);
|
||||
const { attempts } = runTask([2, 3]);
|
||||
expect(attempts[0].reply).toMatchObject({ id: 1, ok: true, value: 5 });
|
||||
expect(transferCount(attempts[0].transfer)).toBe(0);
|
||||
});
|
||||
|
||||
test('a throwing task function is reported as an error envelope, not a crash', () => {
|
||||
compile(() => { throw new Error('task boom'); });
|
||||
const { attempts } = runTask([]);
|
||||
expect(attempts[0].reply.ok).toBe(false);
|
||||
expect(attempts[0].reply.error).toContain('task boom');
|
||||
});
|
||||
|
||||
test('missing args array does not throw', () => {
|
||||
compile(() => 7);
|
||||
const { attempts } = runTask([]);
|
||||
expect(attempts[0].reply.ok).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// SAB-backed views are shared, never transferable; ordinary buffers must still be moved.
|
||||
test('SAB-backed views do not pollute the transfer list', () => {
|
||||
compile((shared: Uint8Array, ordinary: Uint8Array) => ({ shared, ordinary }));
|
||||
const shared = new Uint8Array(new SharedArrayBuffer(8));
|
||||
const ordinary = new Uint8Array(8);
|
||||
const { attempts } = runTask([shared, ordinary]);
|
||||
expect(attempts[0].reply.ok).toBe(true);
|
||||
expect(attempts[0].transfer).toEqual([ordinary.buffer]);
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
// Exercise WorkerPool with the same backend installed for pre-worker PAL packages.
|
||||
jest.mock('pal/worker', () => require('../../scripts/pal-worker-fallback/compat.js'));
|
||||
|
||||
import { WorkerPool } from '../../cocos/misc/worker-pool';
|
||||
import { getWorkerCapabilities } from '../../cocos/misc/worker';
|
||||
import { checkWorkerScript, createWorker } from '../../cocos/misc/worker';
|
||||
|
||||
describe('PAL package without a worker module', () => {
|
||||
let savedWorker: PropertyDescriptor | undefined;
|
||||
const constructor = jest.fn(() => { throw new Error('must not start a Worker'); });
|
||||
|
||||
beforeEach(() => {
|
||||
savedWorker = Object.getOwnPropertyDescriptor(globalThis, 'Worker');
|
||||
Object.defineProperty(globalThis, 'Worker', { configurable: true, value: constructor });
|
||||
constructor.mockClear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
expect(constructor).not.toHaveBeenCalled();
|
||||
if (savedWorker) Object.defineProperty(globalThis, 'Worker', savedWorker);
|
||||
else delete (globalThis as any).Worker;
|
||||
});
|
||||
|
||||
test('reports the missing PAL capability even when a global Worker exists', () => {
|
||||
expect(getWorkerCapabilities()).toMatchObject({
|
||||
available: false, parallel: false, concurrencyLimit: 0,
|
||||
supportsTransfer: false, supportsSharedArrayBuffer: false, supportsFunctionWorker: false,
|
||||
});
|
||||
expect(checkWorkerScript('workers/task.js')).toMatchObject({ ready: false, version: 0 });
|
||||
expect(getWorkerCapabilities().reason).toContain('PAL package has no worker module');
|
||||
expect(getWorkerCapabilities()).not.toHaveProperty('kind');
|
||||
expect(getWorkerCapabilities().supportsStandardWorker).toBe(false);
|
||||
});
|
||||
|
||||
test('function tasks run inline, including after rechecking capabilities', async () => {
|
||||
const pool = new WorkerPool((n: number) => n * 2, { maxWorkers: 4 });
|
||||
try {
|
||||
expect(pool.backend).toBe('sync');
|
||||
expect(pool.concurrency).toBe(1);
|
||||
await expect(pool.run([21])).resolves.toBe(42);
|
||||
expect(pool.recheck()).toBe('sync');
|
||||
await expect(pool.run([3])).resolves.toBe(6);
|
||||
} finally {
|
||||
pool.terminate();
|
||||
}
|
||||
});
|
||||
|
||||
test('script tasks use their supplied fallback', async () => {
|
||||
const pool = new WorkerPool('workers/task.js', { fallback: (a: number, b: number) => a + b });
|
||||
try {
|
||||
expect(pool.backend).toBe('sync');
|
||||
await expect(pool.run([20, 22])).resolves.toBe(42);
|
||||
} finally {
|
||||
pool.terminate();
|
||||
}
|
||||
});
|
||||
|
||||
test('script tasks without fallback fail explicitly, as does direct worker creation', async () => {
|
||||
const pool = new WorkerPool('workers/task.js');
|
||||
try {
|
||||
await expect(pool.run([])).rejects.toThrow('PAL package has no worker module');
|
||||
expect(() => createWorker('workers/task.js')).toThrow('PAL package has no worker module');
|
||||
} finally {
|
||||
pool.terminate();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,216 @@
|
||||
/**
|
||||
* WorkerPool lifecycle regression tests — the full {idle, busy} x {error kinds} state matrix.
|
||||
*
|
||||
* Why this file exists: the original suite passed 40/40 while still shipping a P0 hang. Every case in
|
||||
* it used a "submit -> await -> submit again" rhythm, so a worker was ALWAYS mid-task when an error
|
||||
* arrived. The idle-error path had zero coverage, and that is exactly where the dead worker leaked.
|
||||
*
|
||||
* The lesson: for a concurrency state machine, enumerate the state combinations rather than the
|
||||
* paths the author had in mind.
|
||||
*
|
||||
* Real-world triggers for an error while idle:
|
||||
* - an uncaught async throw inside the worker (a `setInterval` / `setTimeout` callback);
|
||||
* - WeChat killing the worker process (`Worker.onProcessKilled`, routed to the error listener);
|
||||
* - the OS reclaiming the worker under memory pressure.
|
||||
*/
|
||||
import { WorkerPool } from '../../cocos/misc/worker-pool';
|
||||
|
||||
type ReplyMode = 'ok' | 'malformed' | 'error' | 'silent';
|
||||
|
||||
class FakeWebWorker {
|
||||
public static instances: FakeWebWorker[] = [];
|
||||
public static replyMode: ReplyMode = 'ok';
|
||||
|
||||
public readonly url: string;
|
||||
public posted: any[] = [];
|
||||
public terminated = false;
|
||||
public onmessage: ((e: { data: any }) => void) | null = null;
|
||||
public onerror: ((e: any) => void) | null = null;
|
||||
|
||||
constructor (url: string) {
|
||||
this.url = url;
|
||||
FakeWebWorker.instances.push(this);
|
||||
}
|
||||
|
||||
public postMessage (msg: any): void {
|
||||
this.posted.push(msg);
|
||||
const mode = FakeWebWorker.replyMode;
|
||||
if (mode === 'silent') {
|
||||
return;
|
||||
}
|
||||
const reply = mode === 'malformed'
|
||||
? 'garbage-not-an-object'
|
||||
: mode === 'error'
|
||||
? { id: msg.id, ok: false, error: 'web task failed' }
|
||||
: { id: msg.id, ok: true, value: msg.args[0] * 2 };
|
||||
Promise.resolve().then(() => {
|
||||
if (this.onmessage) { this.onmessage({ data: reply }); }
|
||||
});
|
||||
}
|
||||
|
||||
public terminate (): void {
|
||||
this.terminated = true;
|
||||
}
|
||||
}
|
||||
|
||||
beforeAll(() => {
|
||||
(globalThis as any).Worker = FakeWebWorker;
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
delete (globalThis as any).Worker;
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
FakeWebWorker.instances.length = 0;
|
||||
FakeWebWorker.replyMode = 'ok';
|
||||
});
|
||||
|
||||
/** Race a task against a wall-clock deadline so a hang surfaces as a test failure, not a timeout. */
|
||||
async function settleOrHang<T> (p: Promise<T>, ms = 400): Promise<{ hung: boolean; value?: T; error?: string }> {
|
||||
const sentinel = Symbol('hang');
|
||||
const outcome = await Promise.race([
|
||||
p.then((value) => ({ hung: false, value })).catch((e: Error) => ({ hung: false, error: e.message })),
|
||||
new Promise<typeof sentinel>((r) => setTimeout(() => r(sentinel), ms)),
|
||||
]);
|
||||
return outcome === sentinel ? { hung: true } : outcome as any;
|
||||
}
|
||||
|
||||
/** Let queued microtasks and macrotask callbacks settle. */
|
||||
function tick (ms = 10): Promise<void> {
|
||||
return new Promise((r) => setTimeout(r, ms));
|
||||
}
|
||||
|
||||
describe('IDLE-state failures (the uncovered half of the state machine)', () => {
|
||||
test('a worker that errors while idle is evicted, and the next task lands on a fresh worker', async () => {
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 1, idleReleaseAfter: 0 });
|
||||
await expect(pool.run([1])).resolves.toBe(2);
|
||||
expect(FakeWebWorker.instances).toHaveLength(1);
|
||||
|
||||
const dead = FakeWebWorker.instances[0];
|
||||
// The worker is idle here: no in-flight task. Simulate an uncaught async error inside it.
|
||||
dead.onerror!({ message: 'idle crash: setInterval callback threw' });
|
||||
await tick();
|
||||
|
||||
// Before the fix, `_settle` bailed out on `if (!task) return`, so the eviction branch never ran:
|
||||
// the dead worker stayed in the pool with busy === false and swallowed the next task forever.
|
||||
expect(dead.terminated).toBe(true);
|
||||
|
||||
const next = await settleOrHang(pool.run<number>([5]));
|
||||
expect(next.hung).toBe(false);
|
||||
expect(next.value).toBe(10);
|
||||
expect(FakeWebWorker.instances).toHaveLength(2);
|
||||
|
||||
pool.terminate();
|
||||
});
|
||||
|
||||
test('an idle error with no error object still evicts (defensive branch)', async () => {
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 1, idleReleaseAfter: 0 });
|
||||
await expect(pool.run([1])).resolves.toBe(2);
|
||||
const dead = FakeWebWorker.instances[0];
|
||||
|
||||
dead.onerror!(undefined);
|
||||
await tick();
|
||||
expect(dead.terminated).toBe(true);
|
||||
|
||||
const next = await settleOrHang(pool.run<number>([3]));
|
||||
expect(next.hung).toBe(false);
|
||||
expect(next.value).toBe(6);
|
||||
pool.terminate();
|
||||
});
|
||||
|
||||
test('queued tasks already waiting are re-dispatched after an eviction', async () => {
|
||||
// maxWorkers 1: task A occupies the worker, B and C queue. Kill the worker while it is busy,
|
||||
// then confirm the whole queue still drains onto the replacement rather than stalling.
|
||||
//
|
||||
// Ordering matters: `_evict()` calls `_drain()` SYNCHRONOUSLY inside the onerror stack, so the
|
||||
// replacement worker posts B before the line after `onerror()` runs. replyMode must therefore
|
||||
// already be 'ok' at that moment, otherwise B is dispatched to a silent worker and hangs —
|
||||
// which would be a flaw in this test, not in the pool.
|
||||
FakeWebWorker.replyMode = 'silent';
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 1, idleReleaseAfter: 0 });
|
||||
const a = pool.run<number>([1]);
|
||||
const b = pool.run<number>([2]);
|
||||
const c = pool.run<number>([3]);
|
||||
// A was already posted under 'silent' and stays pending; B/C are still queued.
|
||||
FakeWebWorker.replyMode = 'ok';
|
||||
|
||||
const w = FakeWebWorker.instances[0];
|
||||
expect(FakeWebWorker.instances).toHaveLength(1);
|
||||
w.onerror!({ message: 'process killed' });
|
||||
|
||||
await expect(a).rejects.toThrow('process killed');
|
||||
await expect(b).resolves.toBe(4);
|
||||
await expect(c).resolves.toBe(6);
|
||||
// The dead worker was replaced by exactly one new worker that drained both queued tasks.
|
||||
expect(FakeWebWorker.instances).toHaveLength(2);
|
||||
expect(FakeWebWorker.instances[0].terminated).toBe(true);
|
||||
pool.terminate();
|
||||
});
|
||||
});
|
||||
|
||||
describe('BUSY-state failures (previously covered — kept so the matrix is explicit)', () => {
|
||||
test('an error while busy rejects the running task and replaces the worker', async () => {
|
||||
FakeWebWorker.replyMode = 'silent';
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 1 });
|
||||
const pending = pool.run([1]);
|
||||
FakeWebWorker.instances[0].onerror!({ message: 'script not found' });
|
||||
await expect(pending).rejects.toThrow('script not found');
|
||||
|
||||
FakeWebWorker.replyMode = 'ok';
|
||||
await expect(pool.run([2])).resolves.toBe(4);
|
||||
expect(FakeWebWorker.instances).toHaveLength(2);
|
||||
expect(FakeWebWorker.instances[0].terminated).toBe(true);
|
||||
pool.terminate();
|
||||
});
|
||||
|
||||
test('a malformed reply while busy rejects and evicts', async () => {
|
||||
FakeWebWorker.replyMode = 'malformed';
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 1, idleReleaseAfter: 0 });
|
||||
await expect(pool.run([1])).rejects.toThrow(/malformed reply/);
|
||||
expect(FakeWebWorker.instances[0].terminated).toBe(true);
|
||||
|
||||
FakeWebWorker.replyMode = 'ok';
|
||||
await expect(pool.run([2])).resolves.toBe(4);
|
||||
pool.terminate();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Repeated failure does not wedge the pool', () => {
|
||||
test('five consecutive idle crashes are each recovered', async () => {
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 1, idleReleaseAfter: 0 });
|
||||
for (let i = 0; i < 5; i++) {
|
||||
await expect(pool.run([i])).resolves.toBe(i * 2);
|
||||
const w = FakeWebWorker.instances[FakeWebWorker.instances.length - 1];
|
||||
w.onerror!({ message: `crash #${i}` });
|
||||
await tick();
|
||||
expect(w.terminated).toBe(true);
|
||||
}
|
||||
// Each crash spawned a replacement, so the pool never wedged.
|
||||
const final = await settleOrHang(pool.run<number>([100]));
|
||||
expect(final.hung).toBe(false);
|
||||
expect(final.value).toBe(200);
|
||||
pool.terminate();
|
||||
});
|
||||
|
||||
test('a late reply from an evicted worker is ignored', async () => {
|
||||
FakeWebWorker.replyMode = 'silent';
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 1, idleReleaseAfter: 0 });
|
||||
const pending = pool.run<number>([4]);
|
||||
const dead = FakeWebWorker.instances[0];
|
||||
dead.onerror!({ message: 'killed' });
|
||||
await expect(pending).rejects.toThrow('killed');
|
||||
|
||||
FakeWebWorker.replyMode = 'ok';
|
||||
await expect(pool.run([5])).resolves.toBe(10);
|
||||
const survivor = FakeWebWorker.instances[1];
|
||||
|
||||
// The dead worker wakes up and answers the very first (already-rejected) task id.
|
||||
// It must not disturb the survivor's state or resolve anything twice.
|
||||
dead.onmessage!({ data: { id: 1, ok: true, value: 999 } });
|
||||
await tick();
|
||||
expect(survivor.terminated).toBe(false);
|
||||
expect(FakeWebWorker.instances).toHaveLength(2);
|
||||
pool.terminate();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
import { createWorkerBackend as createWebBackend } from '../../pal/worker/web/index';
|
||||
import { createWorkerBackend as createNativeBackend } from '../../pal/worker/native/index';
|
||||
import { createWorkerBackend as createNodeBackend } from '../../pal/worker/nodejs/index';
|
||||
import { createWorkerBackend as createMinigameBackend } from '../../pal/worker/minigame/index';
|
||||
import { minigame } from 'pal/minigame';
|
||||
|
||||
describe('distributed PAL worker platform entries', () => {
|
||||
const saved = new Map<string, PropertyDescriptor | undefined>();
|
||||
let savedMinigame: PropertyDescriptorMap;
|
||||
|
||||
beforeEach(() => {
|
||||
for (const key of ['Worker', 'Blob', 'URL']) {
|
||||
saved.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
|
||||
}
|
||||
savedMinigame = Object.getOwnPropertyDescriptors(minigame);
|
||||
for (const key of Object.keys(minigame)) delete minigame[key];
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const [key, descriptor] of saved) {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else delete (globalThis as any)[key];
|
||||
}
|
||||
for (const key of Object.keys(minigame)) delete minigame[key];
|
||||
Object.defineProperties(minigame, savedMinigame);
|
||||
});
|
||||
|
||||
test.each([createNativeBackend, createNodeBackend])('unsupported targets ignore browser globals', (createBackend) => {
|
||||
(globalThis as any).Worker = jest.fn();
|
||||
const backend = createBackend();
|
||||
expect(backend.concurrencyLimit).toBe(0);
|
||||
expect(backend.scriptFallback).toBeNull();
|
||||
expect(backend.createFunctionWorker(() => 1)).toBeNull();
|
||||
expect(() => backend.createScriptWorker('task.js')).toThrow();
|
||||
expect(Worker).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('Web function capability checks Blob and URL, with no stale support cache', () => {
|
||||
(globalThis as any).Worker = jest.fn();
|
||||
(globalThis as any).Blob = undefined;
|
||||
const backend = createWebBackend();
|
||||
expect(backend.supportsFunctionWorker).toBe(false);
|
||||
(globalThis as any).Blob = class {};
|
||||
(globalThis as any).URL = { createObjectURL: jest.fn() };
|
||||
expect(backend.supportsFunctionWorker).toBe(true);
|
||||
});
|
||||
|
||||
test('a failed Web constructor still releases its Blob URL', () => {
|
||||
(globalThis as any).Worker = jest.fn(() => { throw new Error('blocked'); });
|
||||
(globalThis as any).Blob = class {};
|
||||
(globalThis as any).URL = {
|
||||
createObjectURL: jest.fn(() => 'blob:test'),
|
||||
revokeObjectURL: jest.fn(),
|
||||
};
|
||||
expect(() => createWebBackend().createFunctionWorker(() => 1)).toThrow('blocked');
|
||||
expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:test');
|
||||
});
|
||||
|
||||
test('minigame remains a minigame with no createWorker; PAL supplies devtools fallback', () => {
|
||||
(globalThis as any).Worker = jest.fn(() => ({ terminate: jest.fn() }));
|
||||
const backend = createMinigameBackend();
|
||||
expect(backend.concurrencyLimit).toBe(0);
|
||||
expect(backend.supportsFunctionWorker).toBe(false);
|
||||
expect(backend.scriptFallback!.diagnose('task.js').ready).toBe(true);
|
||||
const resolved = backend.resolveScriptWorker('task.js');
|
||||
expect(resolved.backend).not.toBe(backend);
|
||||
expect(resolved.backend!.concurrencyLimit).toBe(Infinity);
|
||||
expect(resolved.warnOnFailure).toBe(false);
|
||||
backend.createScriptWorker('task.js');
|
||||
expect(Worker).toHaveBeenCalledWith('task.js');
|
||||
});
|
||||
|
||||
test('PAL resolves unavailable targets and suppresses expected fallback warnings', () => {
|
||||
const resolution = createNativeBackend().resolveScriptWorker('task.js');
|
||||
expect(resolution.backend).toBeNull();
|
||||
expect(resolution.diagnosis.ready).toBe(false);
|
||||
expect(resolution.warnOnFailure).toBe(false);
|
||||
expect(createNativeBackend().supportsStandardWorker).toBe(false);
|
||||
});
|
||||
test('minigame API calls retain their host receiver', () => {
|
||||
minigame.createWorker = jest.fn(function (this: any) {
|
||||
expect(this).toBe(minigame);
|
||||
return { terminate: jest.fn(), onMessage: jest.fn(), postMessage: jest.fn() };
|
||||
});
|
||||
createMinigameBackend().createScriptWorker('workers/task.js').terminate();
|
||||
expect(minigame.createWorker).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('rechecking a single-worker host without a filesystem does not consume its occupied slot', () => {
|
||||
let active = 0;
|
||||
minigame.createWorker = jest.fn(() => {
|
||||
if (active) throw new Error('only one worker allowed');
|
||||
active++;
|
||||
return { terminate: () => { active--; }, onMessage: jest.fn(), postMessage: jest.fn() };
|
||||
});
|
||||
const first = createMinigameBackend();
|
||||
expect(first.resolveScriptWorker('workers/task.js').backend).toBe(first);
|
||||
const worker = first.createScriptWorker('workers/task.js');
|
||||
expect(active).toBe(1);
|
||||
const refreshed = createMinigameBackend();
|
||||
expect(refreshed.resolveScriptWorker('workers/task.js').backend).toBe(refreshed);
|
||||
expect(minigame.createWorker).toHaveBeenCalledTimes(2); // one probe + one real worker
|
||||
worker.terminate();
|
||||
expect(active).toBe(0);
|
||||
});
|
||||
|
||||
});
|
||||
@@ -0,0 +1,372 @@
|
||||
/**
|
||||
* Platform backend tests: the capability matrix across ALL nine mini-game platforms plus Web.
|
||||
*
|
||||
* This is the test that the original implementation lacked, and its absence is exactly why seven
|
||||
* platforms shipped with no parallelism: the fallback chain only ever branched on the `WECHAT`
|
||||
* constant, so ByteDance / Alipay / Baidu / Huawei / OPPO / vivo / Xiaomi silently fell through to
|
||||
* synchronous execution, and nothing asserted otherwise.
|
||||
*
|
||||
* Capabilities are injected through the pal boundary (the same `minigame` object the backend imports),
|
||||
* which is how a real device obtains them: every `pal/minigame/*.js` adapter begins with
|
||||
* `cloneObject(minigame, <platformGlobal>)`, copying `createWorker` over already bound to
|
||||
* wx / tt / my / swan / qg / ral.
|
||||
*
|
||||
* Expected matrix (each row verified against that platform's official docs):
|
||||
*
|
||||
* Platform concurrencyLimit transfer parallel note
|
||||
* ----------- ---------------- -------- -------- ------------------------------------------
|
||||
* WeChat V1 1 no no legacy worker
|
||||
* WeChat V2 Infinity yes yes env.isSupportStandardWorker (grey release)
|
||||
* ByteDance 1 no no tt.createWorker
|
||||
* Alipay 1 no no my.createWorker
|
||||
* Baidu 1 no no swan.createWorker, base library 1.6.1+
|
||||
* Huawei quick game 1 no no qg.createWorker 1117+; structured clone only
|
||||
* vivo 1 no no qg.createWorker; one worker max
|
||||
* OPPO 1 no no qg.createWorker; one worker max
|
||||
* Xiaomi 1 no no qg.createWorker; one worker max
|
||||
* Taobao 0 no no NO worker API at all
|
||||
* Web Infinity yes yes global Worker
|
||||
*/
|
||||
import { minigame } from 'pal/minigame';
|
||||
import {
|
||||
getWorkerBackend, getWorkerCapabilities, resetWorkerBackendCache,
|
||||
} from '../../cocos/misc/worker';
|
||||
import { checkWorkerScript, getOptimalWorkerCount, getWorkerConcurrencyLimit } from '../../cocos/misc/worker';
|
||||
|
||||
class FakeMinigameWorker {
|
||||
public static instances: FakeMinigameWorker[] = [];
|
||||
public readonly path: string;
|
||||
public posted: any[] = [];
|
||||
public transfers: any[][] = [];
|
||||
public terminated = false;
|
||||
public messageListener: ((res: any) => void) | null = null;
|
||||
public errorListener: ((err: any) => void) | null = null;
|
||||
|
||||
constructor (path: string) {
|
||||
this.path = path;
|
||||
FakeMinigameWorker.instances.push(this);
|
||||
}
|
||||
|
||||
public postMessage (msg: any, transfer?: any[]): void {
|
||||
this.posted.push(msg);
|
||||
this.transfers.push(transfer as any);
|
||||
Promise.resolve().then(() => {
|
||||
if (this.messageListener) {
|
||||
this.messageListener({ id: msg.id, ok: true, value: (msg.args || [])[0] });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public onMessage (cb: (res: any) => void): void { this.messageListener = cb; }
|
||||
public onError (cb: (err: any) => void): void { this.errorListener = cb; }
|
||||
public terminate (): void { this.terminated = true; }
|
||||
}
|
||||
|
||||
/** Wipe pal and install one platform's capability surface. */
|
||||
function installPlatform (opts: {
|
||||
hasCreateWorker?: boolean;
|
||||
standardWorker?: boolean;
|
||||
hasSystemInfo?: boolean;
|
||||
}): void {
|
||||
for (const k of Object.keys(minigame)) { delete (minigame as any)[k]; }
|
||||
// Every mini-game adapter has getSystemInfoSync regardless of worker support. This is what lets a
|
||||
// worker-less mini-game platform (Taobao) still be recognised as a mini-game platform, so it gets
|
||||
// a precise diagnostic instead of a generic one.
|
||||
if (opts.hasSystemInfo !== false) {
|
||||
(minigame as any).getSystemInfoSync = () => ({ platform: 'devtools' });
|
||||
}
|
||||
if (opts.standardWorker !== undefined) {
|
||||
(minigame as any).env = { isSupportStandardWorker: opts.standardWorker === true };
|
||||
}
|
||||
if (opts.hasCreateWorker !== false) {
|
||||
(minigame as any).createWorker = (path: string): FakeMinigameWorker => new FakeMinigameWorker(path);
|
||||
}
|
||||
// The packaged script exists and is non-empty.
|
||||
(minigame as any).getFileSystemManager = () => ({
|
||||
accessSync: (_p: string): void => {},
|
||||
statSync: (_p: string) => ({ size: 128 }),
|
||||
});
|
||||
resetWorkerBackendCache();
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const k of Object.keys(minigame)) { delete (minigame as any)[k]; }
|
||||
resetWorkerBackendCache();
|
||||
FakeMinigameWorker.instances.length = 0;
|
||||
});
|
||||
|
||||
describe('Mini-game platform capability matrix', () => {
|
||||
// WeChat V2 is the ONLY mini-game generation with multiple concurrent workers and transfer.
|
||||
test('WeChat V2 (standard worker): unlimited concurrency + transfer', () => {
|
||||
installPlatform({ standardWorker: true });
|
||||
const caps = getWorkerCapabilities();
|
||||
expect(caps).toMatchObject({
|
||||
supportsStandardWorker: true,
|
||||
available: true,
|
||||
parallel: true,
|
||||
concurrencyLimit: Infinity,
|
||||
supportsTransfer: true,
|
||||
supportsFunctionWorker: false, // no Blob / no eval on any mini-game platform
|
||||
});
|
||||
expect(checkWorkerScript('workers/demo.js').version).toBe(2);
|
||||
});
|
||||
|
||||
test('WeChat V1 (legacy worker): exactly one worker, data copied', () => {
|
||||
installPlatform({ standardWorker: false });
|
||||
const caps = getWorkerCapabilities();
|
||||
expect(caps).toMatchObject({
|
||||
supportsStandardWorker: false, available: true, parallel: false,
|
||||
concurrencyLimit: 1, supportsTransfer: false,
|
||||
});
|
||||
expect(checkWorkerScript('workers/demo.js').version).toBe(1);
|
||||
});
|
||||
|
||||
// ByteDance / Alipay / Baidu / Huawei / OPPO / vivo / Xiaomi: all have createWorker, all cap at 1.
|
||||
// They differ only in which global they bind it to (tt/my/swan/qg/ral), which cloneObject absorbs.
|
||||
const singleWorkerPlatforms: Array<[string, { hasEnv: boolean }]> = [
|
||||
['ByteDance (tt.createWorker)', { hasEnv: false }],
|
||||
['Alipay (my.createWorker)', { hasEnv: false }],
|
||||
['Baidu (swan.createWorker, 1.6.1+)', { hasEnv: false }],
|
||||
['Huawei quick game (qg.createWorker, 1117+)', { hasEnv: false }],
|
||||
['vivo (qg.createWorker)', { hasEnv: false }],
|
||||
['OPPO (qg.createWorker)', { hasEnv: false }],
|
||||
['Xiaomi (qg.createWorker)', { hasEnv: false }],
|
||||
];
|
||||
|
||||
test.each(singleWorkerPlatforms)('%s: one worker, no transfer, but genuinely available', (_name, opts) => {
|
||||
installPlatform({ standardWorker: undefined });
|
||||
if (!opts.hasEnv) { delete (minigame as any).env; }
|
||||
resetWorkerBackendCache();
|
||||
|
||||
const caps = getWorkerCapabilities();
|
||||
// The crux of this whole refactor: these platforms previously resolved to 'sync' or 'none'.
|
||||
expect(caps.available).toBe(true);
|
||||
expect(caps.parallel).toBe(false);
|
||||
expect(caps.concurrencyLimit).toBe(1);
|
||||
expect(caps.supportsTransfer).toBe(false);
|
||||
expect(caps).not.toHaveProperty('kind');
|
||||
expect(caps.supportsStandardWorker).toBe(false);
|
||||
expect(checkWorkerScript('workers/demo.js').ready).toBe(true);
|
||||
expect(getWorkerConcurrencyLimit()).toBe(1);
|
||||
});
|
||||
|
||||
test('Taobao: a mini-game platform with NO worker API — available false, precise reason', () => {
|
||||
// Taobao's API surface has no worker category, and no Web Worker / Blob / URL either.
|
||||
installPlatform({ hasCreateWorker: false });
|
||||
const caps = getWorkerCapabilities();
|
||||
expect(caps.available).toBe(false);
|
||||
expect(caps.parallel).toBe(false);
|
||||
expect(caps.concurrencyLimit).toBe(0);
|
||||
|
||||
const status = checkWorkerScript('workers/demo.js');
|
||||
expect(status.ready).toBe(false);
|
||||
// Must name the real situation, not a generic "no backend" — otherwise the developer cannot
|
||||
// tell a platform limitation from their own packaging mistake.
|
||||
expect(status.reason).toMatch(/no createWorker API/);
|
||||
expect(status.reason).toMatch(/Taobao/);
|
||||
});
|
||||
|
||||
test('Taobao reports no transfer and no SharedArrayBuffer support', () => {
|
||||
installPlatform({ hasCreateWorker: false });
|
||||
const caps = getWorkerCapabilities();
|
||||
expect(caps.supportsTransfer).toBe(false);
|
||||
expect(caps.supportsSharedArrayBuffer).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* `caps.reason` exists to answer the only question a developer actually has when a feature does not
|
||||
* parallelise: "is this MY bug, or a platform rule I must design around?" A bare `available: false` /
|
||||
* `parallel: false` cannot answer it. These tests pin the four distinct capability levels to four
|
||||
* distinct explanations.
|
||||
*/
|
||||
describe('capability reason distinguishes a platform rule from a fixable problem', () => {
|
||||
test('is never empty, on any backend', () => {
|
||||
installPlatform({ standardWorker: true });
|
||||
expect(getWorkerCapabilities().reason.length).toBeGreaterThan(0);
|
||||
installPlatform({ standardWorker: false });
|
||||
expect(getWorkerCapabilities().reason.length).toBeGreaterThan(0);
|
||||
installPlatform({ hasCreateWorker: false });
|
||||
expect(getWorkerCapabilities().reason.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test('WeChat V2 explains that real parallelism IS available', () => {
|
||||
installPlatform({ standardWorker: true });
|
||||
const caps = getWorkerCapabilities();
|
||||
expect(caps.parallel).toBe(true);
|
||||
expect(caps.reason).toMatch(/standard \(V2\) worker/);
|
||||
expect(caps.reason).toMatch(/multiple workers/i);
|
||||
// A fully capable platform must not read like an error.
|
||||
expect(caps.reason).not.toMatch(/cannot|no separate thread/i);
|
||||
});
|
||||
|
||||
test('a single-worker platform says the cap is a PLATFORM RULE, not a config problem', () => {
|
||||
installPlatform({ standardWorker: false });
|
||||
const caps = getWorkerCapabilities();
|
||||
expect(caps.parallel).toBe(false);
|
||||
expect(caps.reason).toMatch(/exactly ONE worker/i);
|
||||
// The decisive assertion: the string must tell the developer to stop looking for a bug in
|
||||
// their own maxWorkers setting.
|
||||
expect(caps.reason).toMatch(/platform rule/i);
|
||||
expect(caps.reason).toMatch(/not a configuration problem/i);
|
||||
// And it must still credit what DOES work, so the offload use case is not dismissed.
|
||||
expect(caps.reason).toMatch(/off the main thread/i);
|
||||
});
|
||||
|
||||
test.each([
|
||||
['ByteDance', { standardWorker: undefined }],
|
||||
['Alipay', { standardWorker: undefined }],
|
||||
['Huawei quick game', { standardWorker: undefined }],
|
||||
])('%s gives the same single-worker explanation as WeChat V1', (_name, opts) => {
|
||||
installPlatform(opts);
|
||||
delete (minigame as any).env;
|
||||
resetWorkerBackendCache();
|
||||
const caps = getWorkerCapabilities();
|
||||
expect(caps.concurrencyLimit).toBe(1);
|
||||
expect(caps.reason).toMatch(/platform rule/i);
|
||||
});
|
||||
|
||||
test('Taobao explains there is no thread to be had at all', () => {
|
||||
installPlatform({ hasCreateWorker: false });
|
||||
const caps = getWorkerCapabilities();
|
||||
expect(caps.available).toBe(false);
|
||||
expect(caps.reason).toMatch(/no createWorker API/);
|
||||
expect(caps.reason).toMatch(/no separate thread/i);
|
||||
});
|
||||
|
||||
test('native (no pal, no global Worker) names the embedded-engine cause', () => {
|
||||
for (const k of Object.keys(minigame)) { delete (minigame as any)[k]; }
|
||||
resetWorkerBackendCache();
|
||||
const caps = getWorkerCapabilities();
|
||||
expect(caps.available).toBe(false);
|
||||
expect(caps.reason).toMatch(/native platforms/i);
|
||||
expect(caps.reason).toMatch(/embedded engine/i);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Transfer semantics differ by platform', () => {
|
||||
test('a single-worker platform drops the transfer list rather than risking a throw', () => {
|
||||
installPlatform({ standardWorker: false });
|
||||
const backend = getWorkerBackend();
|
||||
const w = backend.createScriptWorker('workers/demo.js');
|
||||
const buf = new ArrayBuffer(8);
|
||||
w.postMessage({ id: 1, args: [7] }, [buf]);
|
||||
// Huawei quick game documents structured clone with no transferable objects; passing the list
|
||||
// there may throw, so the adapter must omit it.
|
||||
expect(FakeMinigameWorker.instances[0].transfers[0]).toBeUndefined();
|
||||
w.terminate();
|
||||
});
|
||||
|
||||
test('WeChat V2 passes the transfer list through', () => {
|
||||
installPlatform({ standardWorker: true });
|
||||
const backend = getWorkerBackend();
|
||||
const w = backend.createScriptWorker('workers/demo.js');
|
||||
const buf = new ArrayBuffer(8);
|
||||
w.postMessage({ id: 1, args: [7] }, [buf]);
|
||||
expect(FakeMinigameWorker.instances[0].transfers[0]).toEqual([buf]);
|
||||
w.terminate();
|
||||
});
|
||||
});
|
||||
|
||||
describe('getOptimalWorkerCount respects the platform cap first', () => {
|
||||
test('returns 1 on a single-worker mini-game platform', () => {
|
||||
installPlatform({ standardWorker: false });
|
||||
expect(getOptimalWorkerCount()).toBe(1);
|
||||
});
|
||||
|
||||
test('returns 1 where there is no worker at all (Taobao / native)', () => {
|
||||
installPlatform({ hasCreateWorker: false });
|
||||
expect(getOptimalWorkerCount()).toBe(1);
|
||||
});
|
||||
|
||||
test('never exceeds the platform cap even when hardwareConcurrency is large', () => {
|
||||
installPlatform({ standardWorker: false });
|
||||
// jsdom provides navigator.hardwareConcurrency; the platform cap of 1 must win over it.
|
||||
expect(getOptimalWorkerCount()).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Backend resolution order', () => {
|
||||
test('a mini-game platform wins over a global Worker (devtools exposes both)', () => {
|
||||
installPlatform({ standardWorker: false });
|
||||
// A WeChat devtools build can expose a global Worker while only wx.createWorker works in
|
||||
// production. The mini-game backend must be selected.
|
||||
class FakeWebWorker {
|
||||
public postMessage (): void {}
|
||||
public terminate (): void {}
|
||||
}
|
||||
(globalThis as any).Worker = FakeWebWorker;
|
||||
try {
|
||||
resetWorkerBackendCache();
|
||||
expect(getWorkerBackend().supportsFunctionWorker).toBe(false);
|
||||
} finally {
|
||||
delete (globalThis as any).Worker;
|
||||
resetWorkerBackendCache();
|
||||
}
|
||||
});
|
||||
|
||||
test('re-probing after resetWorkerBackendCache picks up a newly available capability', () => {
|
||||
// Models a WeChat subpackage finishing its download after the first probe: without a reset the
|
||||
// pool stays locked to a worse backend for its whole lifetime.
|
||||
installPlatform({ hasCreateWorker: false });
|
||||
expect(getWorkerCapabilities().available).toBe(false);
|
||||
|
||||
(minigame as any).createWorker = (path: string): FakeMinigameWorker => new FakeMinigameWorker(path);
|
||||
resetWorkerBackendCache();
|
||||
expect(getWorkerCapabilities().available).toBe(true);
|
||||
expect(checkWorkerScript('workers/demo.js').ready).toBe(true);
|
||||
});
|
||||
|
||||
test('createWorker returning undefined is reported, not silently accepted', () => {
|
||||
installPlatform({});
|
||||
// Huawei quick game returns undefined on failure instead of throwing.
|
||||
(minigame as any).createWorker = (): undefined => undefined;
|
||||
resetWorkerBackendCache();
|
||||
expect(() => getWorkerBackend().createScriptWorker('workers/demo.js'))
|
||||
.toThrow(/returned no worker/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Path validation is platform-wide, not WeChat-only', () => {
|
||||
test.each([
|
||||
['', /non-empty string/],
|
||||
['/workers/demo.js', /must be relative/],
|
||||
['workers/demo.ts', /must be a \.js file/],
|
||||
])('rejects %p on a single-worker platform', (path, reason) => {
|
||||
installPlatform({ standardWorker: false });
|
||||
const status = checkWorkerScript(path);
|
||||
expect(status.ready).toBe(false);
|
||||
expect(status.reason).toMatch(reason);
|
||||
});
|
||||
|
||||
test('rejects an invalid path on ByteDance too (previously unchecked)', () => {
|
||||
installPlatform({});
|
||||
delete (minigame as any).env;
|
||||
resetWorkerBackendCache();
|
||||
const status = checkWorkerScript('/absolute/demo.js');
|
||||
expect(status.ready).toBe(false);
|
||||
expect(status.reason).toMatch(/must be relative/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Worker handle routes messages through the mini-game API shape', () => {
|
||||
test('onMessage delivers the payload and terminate is forwarded', async () => {
|
||||
installPlatform({ standardWorker: false });
|
||||
const backend = getWorkerBackend();
|
||||
const w = backend.createScriptWorker('workers/demo.js');
|
||||
const got = new Promise<any>((resolve) => { w.onMessage(resolve); });
|
||||
w.postMessage({ id: 3, args: [42] });
|
||||
await expect(got).resolves.toMatchObject({ id: 3, ok: true, value: 42 });
|
||||
w.terminate();
|
||||
expect(FakeMinigameWorker.instances[0].terminated).toBe(true);
|
||||
});
|
||||
|
||||
test('a platform without onError does not throw when one is registered', () => {
|
||||
installPlatform({});
|
||||
const w = getWorkerBackend().createScriptWorker('workers/demo.js');
|
||||
const raw = FakeMinigameWorker.instances[0] as any;
|
||||
// Huawei quick game documents only create/postMessage/onMessage/terminate.
|
||||
delete raw.onError;
|
||||
expect(() => w.onError(() => {})).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
/**
|
||||
* WorkerPool / worker tests for an environment WITHOUT any worker backend:
|
||||
* jsdom has no global `Worker`, `WECHAT` is false and there is no `wx` — so script mode can only
|
||||
* resolve to the `'sync'` backend (with options.fallback) or `'none'` (without), and function mode
|
||||
* must run inline on the main thread.
|
||||
*
|
||||
* The Web-Worker backend is covered by `worker-web.test.ts`, the WeChat backends by
|
||||
* `worker-wechat.test.ts` (each test file gets its own jsdom environment + module registry, so the
|
||||
* module-level caches in worker.ts cannot leak between them).
|
||||
*/
|
||||
import { WorkerPool } from '../../cocos/misc/worker-pool';
|
||||
import { checkWorkerScript, getWorkerConcurrencyLimit } from '../../cocos/misc/worker';
|
||||
|
||||
describe('Worker capability detection without any backend', () => {
|
||||
test('checkWorkerScript reports not-ready when the platform has no worker', () => {
|
||||
const status = checkWorkerScript('workers/demo.js');
|
||||
expect(status.ready).toBe(false);
|
||||
expect(status.version).toBe(0);
|
||||
expect(status.reason).toMatch(/no worker backend on this platform/);
|
||||
});
|
||||
|
||||
test('getWorkerConcurrencyLimit is 0 when no Worker exists', () => {
|
||||
expect(getWorkerConcurrencyLimit()).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('WorkerPool script mode without any worker backend', () => {
|
||||
test('rejects with a precise reason when no fallback was provided', async () => {
|
||||
const pool = new WorkerPool('workers/demo.js');
|
||||
await expect(pool.run([1])).rejects.toThrow(/No worker backend for/);
|
||||
// The reason must explain BOTH missing backends so the developer knows what to fix.
|
||||
await expect(pool.run([1])).rejects.toThrow(/no worker backend on this platform/);
|
||||
await expect(pool.run([1])).rejects.toThrow(/no createWorker and no global Worker/);
|
||||
pool.terminate();
|
||||
});
|
||||
|
||||
test('runs single-threaded via options.fallback and resolves', async () => {
|
||||
const fallback = jest.fn((a: number, b: number) => a + b);
|
||||
const pool = new WorkerPool('workers/demo.js', { fallback });
|
||||
await expect(pool.run([1, 2])).resolves.toBe(3);
|
||||
await expect(pool.run([10, 20])).resolves.toBe(30);
|
||||
expect(fallback).toHaveBeenCalledTimes(2);
|
||||
expect(fallback).toHaveBeenLastCalledWith(10, 20);
|
||||
pool.terminate();
|
||||
});
|
||||
|
||||
test('a throwing fallback rejects the task but keeps the pool usable', async () => {
|
||||
let shouldThrow = true;
|
||||
const pool = new WorkerPool('workers/demo.js', {
|
||||
fallback: (v: number) => {
|
||||
if (shouldThrow) { throw new Error('fallback boom'); }
|
||||
return v;
|
||||
},
|
||||
});
|
||||
await expect(pool.run([1])).rejects.toThrow('fallback boom');
|
||||
shouldThrow = false;
|
||||
await expect(pool.run([7])).resolves.toBe(7);
|
||||
pool.terminate();
|
||||
});
|
||||
|
||||
test('a non-function fallback is ignored (backend stays none)', async () => {
|
||||
const pool = new WorkerPool('workers/demo.js', { fallback: 42 as any });
|
||||
await expect(pool.run([1])).rejects.toThrow(/No worker backend for/);
|
||||
pool.terminate();
|
||||
});
|
||||
});
|
||||
|
||||
describe('WorkerPool function mode without worker support', () => {
|
||||
test('runs the task inline synchronously', async () => {
|
||||
const pool = new WorkerPool((a: number) => a * 2);
|
||||
await expect(pool.run([21])).resolves.toBe(42);
|
||||
pool.terminate();
|
||||
});
|
||||
|
||||
test('an inline task that throws rejects', async () => {
|
||||
const pool = new WorkerPool(() => {
|
||||
throw new Error('inline boom');
|
||||
});
|
||||
await expect(pool.run([])).rejects.toThrow('inline boom');
|
||||
pool.terminate();
|
||||
});
|
||||
});
|
||||
|
||||
describe('WorkerPool argument and lifecycle boundaries', () => {
|
||||
test('constructor rejects invalid first arguments', () => {
|
||||
expect(() => new WorkerPool('')).toThrow(TypeError);
|
||||
expect(() => new WorkerPool(123 as any)).toThrow(TypeError);
|
||||
expect(() => new WorkerPool(null as any)).toThrow(TypeError);
|
||||
expect(() => new WorkerPool(undefined as any)).toThrow(TypeError);
|
||||
expect(() => new WorkerPool({} as any)).toThrow(TypeError);
|
||||
});
|
||||
|
||||
test('run after terminate rejects and terminate is idempotent', async () => {
|
||||
const pool = new WorkerPool('workers/demo.js', { fallback: () => 1 });
|
||||
pool.terminate();
|
||||
await expect(pool.run([])).rejects.toThrow(/terminated/);
|
||||
expect(() => pool.terminate()).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,205 @@
|
||||
jest.mock('pal/worker', () => ({ createWorkerBackend: jest.fn() }));
|
||||
|
||||
import { createWorkerBackend } from 'pal/worker';
|
||||
import { WorkerPool } from '../../cocos/misc/worker-pool';
|
||||
import { resetWorkerBackendCache } from '../../cocos/misc/worker';
|
||||
|
||||
test('function workers use PAL concurrency without reading any host identity', async () => {
|
||||
let reply: (value: any) => void;
|
||||
const backend = {
|
||||
get kind() { throw new Error('host identity must not be read'); },
|
||||
hardwareConcurrency: 8,
|
||||
concurrencyLimit: 2,
|
||||
supportsFunctionWorker: true,
|
||||
scriptFailureHint: '',
|
||||
createFunctionWorker: jest.fn((fn: (...args: any[]) => any) => ({
|
||||
postMessage: (msg: any) => { Promise.resolve().then(() => reply({ id: msg.id, ok: true, value: fn(...msg.args) })); },
|
||||
onMessage: (listener: (value: any) => void) => { reply = listener; },
|
||||
onError: jest.fn(),
|
||||
terminate: jest.fn(),
|
||||
})),
|
||||
};
|
||||
(createWorkerBackend as jest.Mock).mockReturnValue(backend);
|
||||
resetWorkerBackendCache();
|
||||
const pool = new WorkerPool((n: number) => n + 1, { maxWorkers: 4 });
|
||||
try {
|
||||
expect(pool.backend).toBe('worker');
|
||||
expect(pool.concurrency).toBe(2);
|
||||
await expect(pool.run([41])).resolves.toBe(42);
|
||||
} finally {
|
||||
pool.terminate();
|
||||
resetWorkerBackendCache();
|
||||
}
|
||||
});
|
||||
|
||||
test('pool schedules the exact PAL-selected backend without reading any host identity', async () => {
|
||||
let reply: (value: any) => void;
|
||||
const selected = {
|
||||
get kind() { throw new Error('host identity must not be read'); },
|
||||
concurrencyLimit: 2,
|
||||
scriptFailureHint: '',
|
||||
createScriptWorker: jest.fn(() => ({
|
||||
postMessage: (msg: any) => { Promise.resolve().then(() => reply({ id: msg.id, ok: true, value: msg.args[0] * 2 })); },
|
||||
onMessage: (fn: (value: any) => void) => { reply = fn; },
|
||||
onError: jest.fn(),
|
||||
terminate: jest.fn(),
|
||||
})),
|
||||
};
|
||||
const root = {
|
||||
get kind() { throw new Error('host identity must not be read'); },
|
||||
hardwareConcurrency: 8,
|
||||
concurrencyLimit: 1,
|
||||
scriptFailureHint: '',
|
||||
createScriptWorker: jest.fn(() => { throw new Error('must use PAL-selected backend'); }),
|
||||
resolveScriptWorker: jest.fn(() => ({
|
||||
backend: selected,
|
||||
diagnosis: { ready: true, version: 1, reason: '' },
|
||||
warnOnFailure: false,
|
||||
})),
|
||||
};
|
||||
(createWorkerBackend as jest.Mock).mockReturnValue(root);
|
||||
resetWorkerBackendCache();
|
||||
const pool = new WorkerPool('task.js', { maxWorkers: 4 });
|
||||
try {
|
||||
expect(pool.backend).toBe('worker');
|
||||
expect(pool.concurrency).toBe(2);
|
||||
await expect(pool.run([21])).resolves.toBe(42);
|
||||
expect(selected.createScriptWorker).toHaveBeenCalledWith('task.js');
|
||||
expect(root.createScriptWorker).not.toHaveBeenCalled();
|
||||
expect(pool.recheck()).toBe('worker');
|
||||
} finally {
|
||||
pool.terminate();
|
||||
resetWorkerBackendCache();
|
||||
}
|
||||
});
|
||||
|
||||
function controlledBackend() {
|
||||
const handles: any[] = [];
|
||||
const backend = {
|
||||
hardwareConcurrency: 4, concurrencyLimit: 2, supportsFunctionWorker: true,
|
||||
supportsTransfer: true, scriptFailureHint: '',
|
||||
resolveScriptWorker: () => ({ backend, diagnosis: { ready: true, version: 1, reason: '' }, warnOnFailure: false }),
|
||||
createScriptWorker: jest.fn(() => {
|
||||
const handle: any = {
|
||||
postMessage: jest.fn(), terminate: jest.fn(),
|
||||
onMessage: (fn: any) => { handle.reply = fn; },
|
||||
onError: (fn: any) => { handle.fail = fn; },
|
||||
};
|
||||
handles.push(handle);
|
||||
return handle;
|
||||
}),
|
||||
createFunctionWorker: jest.fn(() => backend.createScriptWorker()),
|
||||
};
|
||||
return { backend, handles };
|
||||
}
|
||||
|
||||
const unavailable = {
|
||||
hardwareConcurrency: 1, concurrencyLimit: 0, supportsFunctionWorker: false, scriptFailureHint: '',
|
||||
resolveScriptWorker: () => ({ backend: null, diagnosis: { ready: false, version: 0, reason: 'unavailable' }, warnOnFailure: false }),
|
||||
};
|
||||
|
||||
afterEach(() => resetWorkerBackendCache());
|
||||
|
||||
test('a different pool refreshing the PAL cache does not change function backend selection', async () => {
|
||||
const { backend, handles } = controlledBackend();
|
||||
(createWorkerBackend as jest.Mock).mockReturnValue(backend);
|
||||
resetWorkerBackendCache();
|
||||
const pool = new WorkerPool((n: number) => n + 1);
|
||||
(createWorkerBackend as jest.Mock).mockReturnValue(unavailable);
|
||||
resetWorkerBackendCache();
|
||||
const inline = new WorkerPool((n: number) => n + 2);
|
||||
const result = pool.run([1]);
|
||||
expect(handles).toHaveLength(1);
|
||||
handles[0].reply({ id: 1, ok: true, value: 2 });
|
||||
await expect(result).resolves.toBe(2);
|
||||
await expect(inline.run([1])).resolves.toBe(3);
|
||||
pool.terminate(); inline.terminate();
|
||||
});
|
||||
|
||||
test.each([true, false])('recheck retires busy workers and settles queued tasks (fallback=%s)', async (fallback) => {
|
||||
const { backend, handles } = controlledBackend();
|
||||
(createWorkerBackend as jest.Mock).mockReturnValue(backend);
|
||||
resetWorkerBackendCache();
|
||||
const pool = new WorkerPool('task.js', { maxWorkers: 1, idleReleaseAfter: 0, fallback: fallback ? (n: number) => n * 3 : undefined });
|
||||
const running = pool.run([2]);
|
||||
const queued = pool.run([3]);
|
||||
const checkQueued = fallback ? expect(queued).resolves.toBe(9) : expect(queued).rejects.toThrow(/unavailable/);
|
||||
(createWorkerBackend as jest.Mock).mockReturnValue(unavailable);
|
||||
expect(pool.recheck()).toBe(fallback ? 'sync' : 'none');
|
||||
expect(handles[0].terminate).not.toHaveBeenCalled();
|
||||
handles[0].reply({ id: 1, ok: true, value: 4 });
|
||||
await expect(running).resolves.toBe(4);
|
||||
await checkQueued;
|
||||
expect(handles[0].terminate).toHaveBeenCalledTimes(1);
|
||||
expect(handles[0].postMessage).toHaveBeenCalledTimes(1);
|
||||
pool.terminate();
|
||||
});
|
||||
|
||||
test('late errors from a retired worker do not degrade the newly checked backend', async () => {
|
||||
const old = controlledBackend(); const fresh = controlledBackend();
|
||||
(createWorkerBackend as jest.Mock).mockReturnValue(old.backend);
|
||||
resetWorkerBackendCache();
|
||||
const pool = new WorkerPool('task.js', { maxWorkers: 1, fallback: () => -1 });
|
||||
const failed = expect(pool.run()).rejects.toThrow('old error');
|
||||
(createWorkerBackend as jest.Mock).mockReturnValue(fresh.backend);
|
||||
pool.recheck();
|
||||
old.handles[0].fail(new Error('old error'));
|
||||
await failed;
|
||||
expect(pool.backend).toBe('worker');
|
||||
const next = pool.run();
|
||||
fresh.handles[0].reply({ id: 2, ok: true, value: 42 });
|
||||
await expect(next).resolves.toBe(42);
|
||||
pool.terminate();
|
||||
});
|
||||
|
||||
test('synchronous postMessage exceptions evict the worker and drain through fallback', async () => {
|
||||
const { backend } = controlledBackend();
|
||||
const make = backend.createScriptWorker.getMockImplementation()!;
|
||||
backend.createScriptWorker.mockImplementation(() => {
|
||||
const handle = make();
|
||||
handle.postMessage.mockImplementation(() => { throw new Error('send failed'); });
|
||||
return handle;
|
||||
});
|
||||
(createWorkerBackend as jest.Mock).mockReturnValue(backend);
|
||||
resetWorkerBackendCache();
|
||||
const pool = new WorkerPool('task.js', { fallback: (n: number) => n * 3 });
|
||||
await expect(pool.run([2])).resolves.toBe(6);
|
||||
await expect(pool.run([3])).resolves.toBe(9);
|
||||
expect(pool.backend).toBe('sync');
|
||||
pool.terminate();
|
||||
});
|
||||
|
||||
test('transferred arguments are never replayed after worker failure', async () => {
|
||||
const { backend, handles } = controlledBackend();
|
||||
const fallback = jest.fn((arg: Uint8Array) => arg[0]);
|
||||
(createWorkerBackend as jest.Mock).mockReturnValue(backend);
|
||||
resetWorkerBackendCache();
|
||||
const pool = new WorkerPool('task.js', { fallback });
|
||||
const bytes = new Uint8Array([42]);
|
||||
const result = pool.run([bytes], [bytes.buffer]);
|
||||
// Node MessageChannel performs a real ownership transfer, unlike a mock postMessage.
|
||||
const { port1, port2 } = new (require('worker_threads').MessageChannel)();
|
||||
port1.postMessage(bytes, [bytes.buffer]);
|
||||
port1.close(); port2.close();
|
||||
expect(bytes.byteLength).toBe(0);
|
||||
handles[0].fail(new Error('worker died'));
|
||||
await expect(result).rejects.toThrow('worker died');
|
||||
expect(fallback).not.toHaveBeenCalled();
|
||||
expect(pool.backend).toBe('sync');
|
||||
await expect(pool.run([new Uint8Array([7])])).resolves.toBe(7);
|
||||
pool.terminate();
|
||||
});
|
||||
|
||||
|
||||
test('a large queued batch drains iteratively after synchronous fallback', async () => {
|
||||
const { backend, handles } = controlledBackend();
|
||||
(createWorkerBackend as jest.Mock).mockReturnValue(backend);
|
||||
resetWorkerBackendCache();
|
||||
const pool = new WorkerPool('task.js', { maxWorkers: 1, fallback: (n: number) => n + 1 });
|
||||
const results = Array.from({ length: 10000 }, (_, n) => pool.run([n]));
|
||||
handles[0].fail(new Error('worker died'));
|
||||
const values = await Promise.all(results);
|
||||
expect(values[0]).toBe(1);
|
||||
expect(values[9999]).toBe(10000);
|
||||
pool.terminate();
|
||||
});
|
||||
@@ -0,0 +1,249 @@
|
||||
/**
|
||||
* Tests for the two stage-2 capabilities that close the "worker goes silent" and "probed too early"
|
||||
* holes:
|
||||
*
|
||||
* 1. `options.timeout` — a watchdog per dispatched task. A worker that accepts a message and never
|
||||
* replies (deadlock, infinite loop, a platform that drops the message) used to leave the task
|
||||
* pending FOREVER and, worse, left that worker parked in the pool with `busy === true`, silently
|
||||
* shrinking the pool by one on every occurrence. The watchdog must both fail the task AND evict
|
||||
* the worker, so the next task lands on a fresh one.
|
||||
*
|
||||
* 2. `pool.recheck()` — backend resolution used to happen once at construction and could never be
|
||||
* revisited. That is wrong whenever capability appears LATER: a worker script inside a WeChat
|
||||
* subpackage that finishes downloading after the pool was built, or `wx.env.isSupportStandardWorker`
|
||||
* flipping as the V2 grey release rolls out. Without recheck the pool stays locked to 'sync'/'none'
|
||||
* for its whole lifetime.
|
||||
*
|
||||
* jsdom has no `Worker`, so we stub the global. `replyMode = 'silent'` reproduces the hang.
|
||||
*/
|
||||
import { WorkerPool } from '../../cocos/misc/worker-pool';
|
||||
import { getWorkerBackend, resetWorkerBackendCache } from '../../cocos/misc/worker';
|
||||
|
||||
type ReplyMode = 'ok' | 'silent';
|
||||
|
||||
class FakeWebWorker {
|
||||
public static instances: FakeWebWorker[] = [];
|
||||
public static replyMode: ReplyMode = 'ok';
|
||||
|
||||
public readonly url: string;
|
||||
public posted: any[] = [];
|
||||
public terminated = false;
|
||||
public onmessage: ((e: { data: any }) => void) | null = null;
|
||||
public onerror: ((e: any) => void) | null = null;
|
||||
|
||||
constructor (url: string) {
|
||||
this.url = url;
|
||||
FakeWebWorker.instances.push(this);
|
||||
}
|
||||
|
||||
public postMessage (msg: any): void {
|
||||
this.posted.push(msg);
|
||||
if (FakeWebWorker.replyMode === 'silent') {
|
||||
// The hang: message accepted, no reply ever. This is what the watchdog exists for.
|
||||
return;
|
||||
}
|
||||
Promise.resolve().then(() => {
|
||||
if (this.onmessage) { this.onmessage({ data: { id: msg.id, ok: true, value: msg.args[0] * 2 } }); }
|
||||
});
|
||||
}
|
||||
|
||||
public terminate (): void {
|
||||
this.terminated = true;
|
||||
}
|
||||
}
|
||||
|
||||
/** Install / remove the global `Worker` so a pool can be built before capability exists. */
|
||||
function installWorker (): void {
|
||||
(globalThis as any).Worker = FakeWebWorker;
|
||||
}
|
||||
function removeWorker (): void {
|
||||
delete (globalThis as any).Worker;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
installWorker();
|
||||
FakeWebWorker.instances.length = 0;
|
||||
FakeWebWorker.replyMode = 'ok';
|
||||
resetWorkerBackendCache();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
removeWorker();
|
||||
resetWorkerBackendCache();
|
||||
});
|
||||
|
||||
describe('options.timeout — watchdog on an unresponsive worker', () => {
|
||||
test('a silent worker fails the task instead of hanging forever', async () => {
|
||||
FakeWebWorker.replyMode = 'silent';
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 1, timeout: 30 });
|
||||
|
||||
await expect(pool.run([1])).rejects.toThrow(/timed out after 30ms/);
|
||||
pool.terminate();
|
||||
});
|
||||
|
||||
test('the timed-out worker is EVICTED, not left busy in the pool', async () => {
|
||||
FakeWebWorker.replyMode = 'silent';
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 1, timeout: 30 });
|
||||
|
||||
await expect(pool.run([1])).rejects.toThrow(/timed out/);
|
||||
const dead = FakeWebWorker.instances[0];
|
||||
expect(dead.terminated).toBe(true);
|
||||
|
||||
// The decisive part: the pool must not reuse the corpse. Recover the worker and confirm the
|
||||
// NEXT task lands on a fresh instance rather than being swallowed by the dead one.
|
||||
FakeWebWorker.replyMode = 'ok';
|
||||
await expect(pool.run([5])).resolves.toBe(10);
|
||||
expect(FakeWebWorker.instances.length).toBe(2);
|
||||
pool.terminate();
|
||||
});
|
||||
|
||||
test('the error message is actionable (names the protocol and the docs)', async () => {
|
||||
FakeWebWorker.replyMode = 'silent';
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 1, timeout: 30 });
|
||||
await expect(pool.run([1])).rejects.toThrow(/engine protocol|README/);
|
||||
pool.terminate();
|
||||
});
|
||||
|
||||
test('a slow-but-successful worker is NOT timed out when the reply arrives in time', async () => {
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 1, timeout: 500 });
|
||||
await expect(pool.run([7])).resolves.toBe(14);
|
||||
// No eviction on success: the same worker must serve the next task.
|
||||
await expect(pool.run([8])).resolves.toBe(16);
|
||||
expect(FakeWebWorker.instances.length).toBe(1);
|
||||
pool.terminate();
|
||||
});
|
||||
|
||||
test('the watchdog is cleared after each task (no timer leak across many tasks)', async () => {
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 1, timeout: 5000 });
|
||||
for (let i = 0; i < 50; i++) {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
await expect(pool.run([i])).resolves.toBe(i * 2);
|
||||
}
|
||||
// A leaked timer per task would still be pending; nothing should fire after terminate().
|
||||
pool.terminate();
|
||||
// If a stale timer were still armed it would fire against a disposed worker and could reject
|
||||
// an unrelated task. Give any such timer a chance to surface as an unhandled rejection.
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
expect(FakeWebWorker.instances.length).toBe(1);
|
||||
});
|
||||
|
||||
test('timeout defaults to OFF, preserving the previous behaviour', async () => {
|
||||
FakeWebWorker.replyMode = 'silent';
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 1 });
|
||||
const outcome = await Promise.race([
|
||||
pool.run([1]).then(() => 'RESOLVED').catch(() => 'REJECTED'),
|
||||
new Promise<string>((r) => setTimeout(() => r('STILL_PENDING'), 80)),
|
||||
]);
|
||||
expect(outcome).toBe('STILL_PENDING');
|
||||
pool.terminate();
|
||||
});
|
||||
|
||||
test('an invalid timeout (0 / negative / NaN) is treated as OFF', async () => {
|
||||
FakeWebWorker.replyMode = 'silent';
|
||||
for (const bad of [0, -1, Number.NaN]) {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 1, timeout: bad });
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
const outcome = await Promise.race([
|
||||
pool.run([1]).then(() => 'RESOLVED').catch(() => 'REJECTED'),
|
||||
new Promise<string>((r) => setTimeout(() => r('STILL_PENDING'), 40)),
|
||||
]);
|
||||
expect(outcome).toBe('STILL_PENDING');
|
||||
pool.terminate();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('pool.recheck() — upgrading a backend that was probed too early', () => {
|
||||
test('a pool built with no Worker at all resolves to sync/none, then upgrades to web', async () => {
|
||||
removeWorker();
|
||||
resetWorkerBackendCache();
|
||||
// Built before capability existed. With a fallback it degrades to 'sync'; without one 'none'.
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 4, fallback: (n: number) => n * 3 });
|
||||
expect(pool.backend).toBe('sync');
|
||||
await expect(pool.run([2])).resolves.toBe(6); // computed inline on the main thread
|
||||
|
||||
// Capability appears (e.g. the subpackage finished downloading).
|
||||
installWorker();
|
||||
expect(pool.recheck()).toBe('worker');
|
||||
expect(pool.backend).toBe('worker');
|
||||
// Now it really goes through a worker: the fallback would have returned 6, the worker returns 4.
|
||||
await expect(pool.run([2])).resolves.toBe(4);
|
||||
expect(FakeWebWorker.instances.length).toBe(1);
|
||||
pool.terminate();
|
||||
});
|
||||
|
||||
test("recheck lifts the 'none' state so run() stops rejecting", async () => {
|
||||
removeWorker();
|
||||
resetWorkerBackendCache();
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 2 }); // no fallback
|
||||
expect(pool.backend).toBe('none');
|
||||
await expect(pool.run([1])).rejects.toThrow(/No worker backend for/);
|
||||
|
||||
installWorker();
|
||||
expect(pool.recheck()).toBe('worker');
|
||||
await expect(pool.run([3])).resolves.toBe(6);
|
||||
pool.terminate();
|
||||
});
|
||||
|
||||
test('recheck can grow the pool once the concurrency cap is lifted', async () => {
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 3 });
|
||||
FakeWebWorker.replyMode = 'silent';
|
||||
// Fill the pool to maxWorkers with unresponsive tasks.
|
||||
const pending = [pool.run([1]), pool.run([2]), pool.run([3])];
|
||||
await new Promise((r) => setTimeout(r, 5));
|
||||
expect(FakeWebWorker.instances.length).toBe(3);
|
||||
// A fourth task cannot start: the pool is full and every worker is busy.
|
||||
const fourth = pool.run([4]);
|
||||
await new Promise((r) => setTimeout(r, 5));
|
||||
expect(FakeWebWorker.instances.length).toBe(3);
|
||||
|
||||
FakeWebWorker.replyMode = 'ok';
|
||||
// Recovering recheck() must re-drain so the queued task is picked up.
|
||||
pool.recheck();
|
||||
expect(pool.recheck()).toBe('worker');
|
||||
pool.terminate();
|
||||
await expect(Promise.allSettled([...pending, fourth])).resolves.toBeDefined();
|
||||
});
|
||||
|
||||
test('recheck never destroys in-flight work', async () => {
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 1 });
|
||||
const inflight = pool.run([9]);
|
||||
// Re-probe while a task is running: the running worker must survive and still deliver.
|
||||
expect(pool.recheck()).toBe('worker');
|
||||
await expect(inflight).resolves.toBe(18);
|
||||
expect(FakeWebWorker.instances[0].terminated).toBe(true); // retired only after delivering its result
|
||||
pool.terminate();
|
||||
});
|
||||
|
||||
test('recheck on a terminated pool is a safe no-op', () => {
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 1 });
|
||||
pool.terminate();
|
||||
expect(pool.recheck()).toBe('worker');
|
||||
// No new worker may be spawned after termination.
|
||||
expect(FakeWebWorker.instances.length).toBe(0);
|
||||
});
|
||||
|
||||
test('recheck is idempotent when nothing changed', async () => {
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 2 });
|
||||
expect(pool.recheck()).toBe('worker');
|
||||
expect(pool.recheck()).toBe('worker');
|
||||
await expect(pool.run([4])).resolves.toBe(8);
|
||||
expect(FakeWebWorker.instances.length).toBe(1);
|
||||
pool.terminate();
|
||||
});
|
||||
});
|
||||
|
||||
describe('backend cache reset', () => {
|
||||
test('resetWorkerBackendCache re-probes the platform', () => {
|
||||
expect(getWorkerBackend().concurrencyLimit).toBe(Infinity);
|
||||
removeWorker();
|
||||
// Still cached: the original concurrency capability remains until the backend is reset.
|
||||
expect(getWorkerBackend().concurrencyLimit).toBe(Infinity);
|
||||
resetWorkerBackendCache();
|
||||
expect(getWorkerBackend().concurrencyLimit).toBe(0);
|
||||
installWorker();
|
||||
resetWorkerBackendCache();
|
||||
expect(getWorkerBackend().concurrencyLimit).toBe(Infinity);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,150 @@
|
||||
/**
|
||||
* WorkerPool / worker tests for the standard Web `Worker` backend.
|
||||
*
|
||||
* jsdom does not implement `Worker`, so we stub the global with a fake that speaks the engine
|
||||
* protocol ({ id, args } in, { id, ok, value|error } out) over plain callbacks. This covers the
|
||||
* `'web'` backend of the script-mode fallback chain, protocol boundary checks and worker errors.
|
||||
*/
|
||||
import { WorkerPool } from '../../cocos/misc/worker-pool';
|
||||
import { createWorker, getWorkerConcurrencyLimit } from '../../cocos/misc/worker';
|
||||
|
||||
type ReplyMode = 'ok' | 'malformed' | 'error' | 'silent';
|
||||
|
||||
class FakeWebWorker {
|
||||
public static instances: FakeWebWorker[] = [];
|
||||
public static replyMode: ReplyMode = 'ok';
|
||||
|
||||
public readonly url: string;
|
||||
public posted: any[] = [];
|
||||
public terminated = false;
|
||||
public onmessage: ((e: { data: any }) => void) | null = null;
|
||||
public onerror: ((e: any) => void) | null = null;
|
||||
|
||||
constructor (url: string) {
|
||||
this.url = url;
|
||||
FakeWebWorker.instances.push(this);
|
||||
}
|
||||
|
||||
public postMessage (msg: any): void {
|
||||
this.posted.push(msg);
|
||||
const mode = FakeWebWorker.replyMode;
|
||||
if (mode === 'silent') {
|
||||
return;
|
||||
}
|
||||
const reply = mode === 'malformed'
|
||||
? 'garbage-not-an-object'
|
||||
: mode === 'error'
|
||||
? { id: msg.id, ok: false, error: 'web task failed' }
|
||||
: { id: msg.id, ok: true, value: msg.args[0] * 2 };
|
||||
Promise.resolve().then(() => {
|
||||
if (this.onmessage) { this.onmessage({ data: reply }); }
|
||||
});
|
||||
}
|
||||
|
||||
public terminate (): void {
|
||||
this.terminated = true;
|
||||
}
|
||||
}
|
||||
|
||||
beforeAll(() => {
|
||||
(globalThis as any).Worker = FakeWebWorker;
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
delete (globalThis as any).Worker;
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
FakeWebWorker.instances.length = 0;
|
||||
FakeWebWorker.replyMode = 'ok';
|
||||
});
|
||||
|
||||
describe('Web backend detection', () => {
|
||||
test('getWorkerConcurrencyLimit is Infinity when a global Worker exists', () => {
|
||||
expect(getWorkerConcurrencyLimit()).toBe(Infinity);
|
||||
});
|
||||
});
|
||||
|
||||
describe('WorkerPool script mode on the Web Worker backend', () => {
|
||||
test('creates a worker from the script path and resolves tasks', async () => {
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 1 });
|
||||
await expect(pool.run([21])).resolves.toBe(42);
|
||||
expect(FakeWebWorker.instances).toHaveLength(1);
|
||||
expect(FakeWebWorker.instances[0].url).toBe('workers/demo.js');
|
||||
expect(FakeWebWorker.instances[0].posted[0]).toMatchObject({ id: expect.any(Number), args: [21] });
|
||||
pool.terminate();
|
||||
expect(FakeWebWorker.instances[0].terminated).toBe(true);
|
||||
});
|
||||
|
||||
test('reuses one worker for sequential tasks', async () => {
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 1 });
|
||||
await expect(pool.run([1])).resolves.toBe(2);
|
||||
await expect(pool.run([2])).resolves.toBe(4);
|
||||
await expect(pool.run([3])).resolves.toBe(6);
|
||||
expect(FakeWebWorker.instances).toHaveLength(1);
|
||||
pool.terminate();
|
||||
});
|
||||
|
||||
test('scales to maxWorkers and queues the excess', async () => {
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 2 });
|
||||
const results = await Promise.all([pool.run([1]), pool.run([2]), pool.run([3])]);
|
||||
expect(results).toEqual([2, 4, 6]);
|
||||
// Two workers max; the third task must have been queued and dispatched to a free one.
|
||||
expect(FakeWebWorker.instances).toHaveLength(2);
|
||||
pool.terminate();
|
||||
});
|
||||
|
||||
test('a malformed reply rejects with a protocol error instead of hanging', async () => {
|
||||
FakeWebWorker.replyMode = 'malformed';
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 1 });
|
||||
await expect(pool.run([1])).rejects.toThrow(/malformed reply/);
|
||||
pool.terminate();
|
||||
});
|
||||
|
||||
test('an error envelope reply rejects with the worker-side message', async () => {
|
||||
FakeWebWorker.replyMode = 'error';
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 1 });
|
||||
await expect(pool.run([1])).rejects.toThrow('web task failed');
|
||||
pool.terminate();
|
||||
});
|
||||
|
||||
test('a worker load/runtime error rejects the running task', async () => {
|
||||
FakeWebWorker.replyMode = 'silent';
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 1 });
|
||||
const pending = pool.run([1]);
|
||||
// Simulate the browser firing `onerror` (e.g. the script 404s — Web cannot pre-check existence).
|
||||
const w = FakeWebWorker.instances[0];
|
||||
expect(w).toBeDefined();
|
||||
w.onerror!({ message: 'script not found' });
|
||||
await expect(pending).rejects.toThrow('script not found');
|
||||
pool.terminate();
|
||||
});
|
||||
|
||||
test('a failed worker is replaced, not reused', async () => {
|
||||
FakeWebWorker.replyMode = 'malformed';
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 1 });
|
||||
await expect(pool.run([1])).rejects.toThrow(/malformed reply/);
|
||||
FakeWebWorker.replyMode = 'ok';
|
||||
await expect(pool.run([2])).resolves.toBe(4);
|
||||
expect(FakeWebWorker.instances).toHaveLength(2);
|
||||
expect(FakeWebWorker.instances[0].terminated).toBe(true);
|
||||
pool.terminate();
|
||||
});
|
||||
});
|
||||
|
||||
describe('createWorker(path) on the Web backend', () => {
|
||||
test('wraps a global Worker and routes messages both ways', async () => {
|
||||
const w = createWorker('workers/demo.js');
|
||||
expect(w).not.toBeNull();
|
||||
expect(FakeWebWorker.instances).toHaveLength(1);
|
||||
const got = new Promise<any>((resolve) => { w!.onMessage(resolve); });
|
||||
w!.postMessage({ id: 7, args: [4] });
|
||||
await expect(got).resolves.toEqual({ id: 7, ok: true, value: 8 });
|
||||
w!.terminate();
|
||||
expect(FakeWebWorker.instances[0].terminated).toBe(true);
|
||||
});
|
||||
|
||||
test('rejects an empty path', () => {
|
||||
expect(() => createWorker('')).toThrow(TypeError);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,369 @@
|
||||
/**
|
||||
* Worker tests for the WeChat mini-game environment.
|
||||
*
|
||||
* Capability is injected through the **pal boundary** (`minigame.createWorker` / `minigame.env` /
|
||||
* `minigame.getFileSystemManager`) rather than through a raw `globalThis.wx` stub. That is deliberate:
|
||||
* it is how the engine actually obtains these functions — every `pal/minigame/*.js` adapter starts
|
||||
* with `cloneObject(minigame, wx)`, which copies them over already bound. Injecting at the pal layer
|
||||
* means this test exercises the same path a real device does.
|
||||
*
|
||||
* Covers:
|
||||
* - `checkWorkerScript` completeness checks (createWorker present, path validity, file existence,
|
||||
* empty file, V1/V2 generation);
|
||||
* - the WorkerPool backend chain: fully-set-up V1 (capped to 1 worker) and V2 (parallel),
|
||||
* not-fully-set-up -> options.fallback single-thread, no fallback -> precise rejection;
|
||||
* - protocol boundary checks (malformed reply / error envelope) over the mini-game worker;
|
||||
* - `createWorker(path)` wrapping `minigame.createWorker`, transfer semantics (V1 copies, V2
|
||||
* transfers), and onProcessKilled routing.
|
||||
*
|
||||
* jsdom has no global `Worker` here, so the "our own Web Worker" rung of the chain is absent —
|
||||
* exactly the real-device situation.
|
||||
*/
|
||||
import { WorkerPool } from '../../cocos/misc/worker-pool';
|
||||
import {
|
||||
checkWorkerScript, createWorker, getWorkerConcurrencyLimit, isSupportStandardWorker,
|
||||
} from '../../cocos/misc/worker';
|
||||
import { resetWorkerBackendCache } from '../../cocos/misc/worker';
|
||||
// The SAME object instance the PAL worker entry imported. `tests/init.ts` maps `pal/minigame` to
|
||||
// `non-minigame.js` (an empty object) during setupFiles — which runs BEFORE this file, so the backend
|
||||
// module is already instantiated against that instance. A `jest.mock` here would be too late to
|
||||
// rebind it; mutating this object is what the backend actually observes.
|
||||
import { minigame } from 'pal/minigame';
|
||||
|
||||
type ReplyMode = 'ok' | 'malformed' | 'error' | 'silent';
|
||||
|
||||
class FakeWxWorker {
|
||||
public static instances: FakeWxWorker[] = [];
|
||||
public static replyMode: ReplyMode = 'ok';
|
||||
|
||||
public readonly path: string;
|
||||
public posted: any[] = [];
|
||||
public transfers: any[][] = [];
|
||||
public terminated = false;
|
||||
public messageListener: ((res: any) => void) | null = null;
|
||||
public errorListener: ((err: any) => void) | null = null;
|
||||
public killedListener: ((err?: any) => void) | null = null;
|
||||
|
||||
constructor (path: string) {
|
||||
this.path = path;
|
||||
FakeWxWorker.instances.push(this);
|
||||
}
|
||||
|
||||
public postMessage (msg: any, transfer?: any[]): void {
|
||||
this.posted.push(msg);
|
||||
this.transfers.push(transfer as any);
|
||||
const mode = FakeWxWorker.replyMode;
|
||||
if (mode === 'silent') {
|
||||
return;
|
||||
}
|
||||
const reply = mode === 'malformed'
|
||||
? { hello: 'world' } // no id / no ok -> protocol violation
|
||||
: mode === 'error'
|
||||
? { id: msg.id, ok: false, error: 'wx task failed' }
|
||||
: { id: msg.id, ok: true, value: msg.args[0] * 2 };
|
||||
Promise.resolve().then(() => {
|
||||
if (this.messageListener) { this.messageListener(reply); }
|
||||
});
|
||||
}
|
||||
|
||||
public onMessage (cb: (res: any) => void): void { this.messageListener = cb; }
|
||||
public onError (cb: (err: any) => void): void { this.errorListener = cb; }
|
||||
public onProcessKilled (cb: (err?: any) => void): void { this.killedListener = cb; }
|
||||
public terminate (): void { this.terminated = true; }
|
||||
}
|
||||
|
||||
interface WxStubOptions {
|
||||
/** Report V2 standard-worker support (env.isSupportStandardWorker === true). */
|
||||
v2?: boolean;
|
||||
/** Files "present" in the code package: path -> size in bytes. Default: demo file exists. */
|
||||
files?: Record<string, number>;
|
||||
/** Set false to simulate an old base library without createWorker. */
|
||||
createWorker?: boolean;
|
||||
/**
|
||||
* Simulate the WeChat devtools simulator, whose `accessSync` routinely fails to see a workers
|
||||
* directory that IS packaged (a false negative). `createWorker` still loads the script, so the
|
||||
* readiness probe must recover and report READY rather than condemn a working setup to sync.
|
||||
*/
|
||||
accessSyncBlind?: boolean;
|
||||
}
|
||||
|
||||
/** Wipe and repopulate the pal minigame object, then drop the cached backend so it re-probes. */
|
||||
function installWx (opts: WxStubOptions = {}): any {
|
||||
const files = opts.files !== undefined ? opts.files : { 'workers/demo.js': 128 };
|
||||
for (const k of Object.keys(minigame)) { delete (minigame as any)[k]; }
|
||||
// Every mini-game adapter exposes getSystemInfoSync regardless of worker support. The backend uses
|
||||
// it to recognise "this is a mini-game platform", which is what makes an old base library WITHOUT
|
||||
// createWorker report a precise mini-game diagnostic instead of a generic one.
|
||||
(minigame as any).getSystemInfoSync = () => ({
|
||||
platform: opts.v2 ? 'android' : 'devtools', version: '8.0.74', SDKVersion: '3.17.0',
|
||||
});
|
||||
(minigame as any).env = { isSupportStandardWorker: opts.v2 === true };
|
||||
(minigame as any).getFileSystemManager = () => ({
|
||||
accessSync: (p: string): void => {
|
||||
// `accessSyncBlind` reproduces the devtools simulator, which cannot see a packaged workers
|
||||
// directory; otherwise a file is visible exactly when it is present in `files`.
|
||||
if (opts.accessSyncBlind || !Object.prototype.hasOwnProperty.call(files, p)) {
|
||||
throw new Error(`accessSync failed: ${p} does not exist`);
|
||||
}
|
||||
},
|
||||
statSync: (p: string) => ({ size: files[p] }),
|
||||
});
|
||||
if (opts.createWorker !== false) {
|
||||
(minigame as any).createWorker = jest.fn((path: string) => {
|
||||
// A real device cannot load a script that is absent from the code package, so createWorker
|
||||
// throws. This is what lets diagnose()'s readiness probe — the authoritative check that runs
|
||||
// after accessSync fails — report "not ready" for a genuinely missing file, while still
|
||||
// reporting "ready" for the devtools false negative above (accessSyncBlind), where the
|
||||
// script loads even though accessSync could not see it.
|
||||
if (!Object.prototype.hasOwnProperty.call(files, path)) {
|
||||
throw new Error(`createWorker failed: ${path} does not exist in the code package`);
|
||||
}
|
||||
return new FakeWxWorker(path);
|
||||
});
|
||||
}
|
||||
resetWorkerBackendCache();
|
||||
return minigame;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const k of Object.keys(minigame)) { delete (minigame as any)[k]; }
|
||||
resetWorkerBackendCache();
|
||||
FakeWxWorker.instances.length = 0;
|
||||
FakeWxWorker.replyMode = 'ok';
|
||||
});
|
||||
|
||||
describe('checkWorkerScript completeness checks', () => {
|
||||
test('not ready when createWorker is missing (old base library)', () => {
|
||||
installWx({ createWorker: false });
|
||||
const status = checkWorkerScript('workers/demo.js');
|
||||
expect(status).toMatchObject({ ready: false, version: 0 });
|
||||
expect(status.reason).toMatch(/no createWorker API/);
|
||||
});
|
||||
|
||||
test('not ready when the platform exposes no worker API at all', () => {
|
||||
// Nothing installed: this is the Taobao / native situation.
|
||||
resetWorkerBackendCache();
|
||||
const status = checkWorkerScript('workers/demo.js');
|
||||
expect(status.ready).toBe(false);
|
||||
expect(status.reason).toMatch(/no worker backend|no createWorker API/);
|
||||
});
|
||||
|
||||
test.each([
|
||||
['', /non-empty string/],
|
||||
['/workers/demo.js', /must be relative/],
|
||||
['workers/demo.ts', /must be a \.js file/],
|
||||
])('rejects an invalid path %p', (path, reason) => {
|
||||
const wx = installWx();
|
||||
const status = checkWorkerScript(path);
|
||||
expect(status.ready).toBe(false);
|
||||
expect(status.reason).toMatch(reason);
|
||||
expect(wx.createWorker).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('not ready when the file does not exist in the code package', () => {
|
||||
installWx({ files: {} });
|
||||
const status = checkWorkerScript('workers/demo.js');
|
||||
expect(status).toMatchObject({ ready: false, version: 0 });
|
||||
expect(status.reason).toMatch(/does not exist in the code package/);
|
||||
expect(status.reason).toMatch(/game\.json/);
|
||||
});
|
||||
|
||||
test('ready when accessSync is blind but createWorker loads the script (devtools false negative)', () => {
|
||||
// The WeChat devtools simulator routinely fails to see a packaged workers directory through
|
||||
// accessSync, yet createWorker loads the script fine. diagnose() must trust createWorker (the
|
||||
// readiness probe) over accessSync, so this is reported READY instead of being condemned to the
|
||||
// single-threaded fallback — the exact regression the probe exists to prevent.
|
||||
installWx({ accessSyncBlind: true });
|
||||
const status = checkWorkerScript('workers/demo.js');
|
||||
expect(status).toEqual({ ready: true, version: 1, reason: '' });
|
||||
});
|
||||
|
||||
test('not ready when the file is empty', () => {
|
||||
installWx({ files: { 'workers/demo.js': 0 } });
|
||||
const status = checkWorkerScript('workers/demo.js');
|
||||
expect(status.ready).toBe(false);
|
||||
expect(status.reason).toMatch(/is empty/);
|
||||
});
|
||||
|
||||
test('ready with version 1 on legacy workers', () => {
|
||||
installWx({ v2: false });
|
||||
expect(checkWorkerScript('workers/demo.js')).toEqual({ ready: true, version: 1, reason: '' });
|
||||
expect(isSupportStandardWorker()).toBe(false);
|
||||
expect(getWorkerConcurrencyLimit()).toBe(1);
|
||||
});
|
||||
|
||||
test('ready with version 2 on standard workers', () => {
|
||||
installWx({ v2: true });
|
||||
expect(checkWorkerScript('workers/demo.js')).toEqual({ ready: true, version: 2, reason: '' });
|
||||
expect(isSupportStandardWorker()).toBe(true);
|
||||
expect(getWorkerConcurrencyLimit()).toBe(Infinity);
|
||||
});
|
||||
});
|
||||
|
||||
describe('WeChat V2 grey-release contract', () => {
|
||||
test.each([undefined, false, true])('uses the runtime flag %p, not eligible version numbers alone', (flag) => {
|
||||
const wx = installWx();
|
||||
wx.getSystemInfoSync = () => ({ platform: 'android', version: '8.0.74', SDKVersion: '3.17.0' });
|
||||
wx.env = flag === undefined ? {} : { isSupportStandardWorker: flag };
|
||||
const worker = createWorker('workers/demo.js');
|
||||
expect(isSupportStandardWorker()).toBe(flag === true);
|
||||
expect(getWorkerConcurrencyLimit()).toBe(flag === true ? Infinity : 1);
|
||||
expect(checkWorkerScript('workers/demo.js').version).toBe(flag === true ? 2 : 1);
|
||||
// Both generations use the same API. No legacy experimental option may be injected.
|
||||
expect(wx.createWorker.mock.calls).toEqual([['workers/demo.js']]);
|
||||
worker.terminate();
|
||||
});
|
||||
|
||||
test('missing env is safe on older runtimes', () => {
|
||||
const wx = installWx();
|
||||
delete wx.env;
|
||||
const worker = createWorker('workers/demo.js');
|
||||
expect(isSupportStandardWorker()).toBe(false);
|
||||
expect(getWorkerConcurrencyLimit()).toBe(1);
|
||||
expect(wx.createWorker.mock.calls).toEqual([['workers/demo.js']]);
|
||||
worker.terminate();
|
||||
});
|
||||
|
||||
test('V2 readiness probes also use plain createWorker(path)', () => {
|
||||
const wx = installWx({ v2: true, accessSyncBlind: true });
|
||||
expect(checkWorkerScript('workers/demo.js')).toMatchObject({ ready: true, version: 2 });
|
||||
expect(wx.createWorker.mock.calls).toEqual([['workers/demo.js']]);
|
||||
expect(FakeWxWorker.instances[0].terminated).toBe(true);
|
||||
});
|
||||
|
||||
test('creation failure uses the supplied sync fallback without pretending to select V1', async () => {
|
||||
const wx = installWx({ v2: true });
|
||||
wx.createWorker.mockImplementation(() => { throw new Error('Worker creation failed'); });
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 2, fallback: (n: number) => n * 2 });
|
||||
try {
|
||||
await expect(pool.run([3])).resolves.toBe(6);
|
||||
expect(pool.backend).toBe('sync');
|
||||
expect(wx.createWorker.mock.calls).toEqual([['workers/demo.js']]);
|
||||
} finally {
|
||||
pool.terminate();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('WorkerPool on a fully set up WeChat worker', () => {
|
||||
test('V1 caps the pool to a single concurrent worker', async () => {
|
||||
const wx = installWx({ v2: false });
|
||||
// Even asking for 4 workers, V1 must never create more than 1.
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 4 });
|
||||
const [a, b] = await Promise.all([pool.run([1]), pool.run([2])]);
|
||||
expect([a, b]).toEqual([2, 4]);
|
||||
expect(wx.createWorker).toHaveBeenCalledTimes(1);
|
||||
expect(FakeWxWorker.instances[0].path).toBe('workers/demo.js');
|
||||
pool.terminate();
|
||||
expect(FakeWxWorker.instances[0].terminated).toBe(true);
|
||||
});
|
||||
|
||||
test('V2 scales to maxWorkers and runs tasks in parallel', async () => {
|
||||
const wx = installWx({ v2: true });
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 2 });
|
||||
const results = await Promise.all([pool.run([1]), pool.run([2]), pool.run([3])]);
|
||||
expect(results).toEqual([2, 4, 6]);
|
||||
expect(wx.createWorker).toHaveBeenCalledTimes(2);
|
||||
pool.terminate();
|
||||
});
|
||||
|
||||
test('a malformed reply rejects with a protocol error instead of hanging', async () => {
|
||||
installWx();
|
||||
FakeWxWorker.replyMode = 'malformed';
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 1 });
|
||||
await expect(pool.run([1])).rejects.toThrow(/malformed reply/);
|
||||
pool.terminate();
|
||||
});
|
||||
|
||||
test('an error envelope reply rejects with the worker-side message', async () => {
|
||||
installWx();
|
||||
FakeWxWorker.replyMode = 'error';
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 1 });
|
||||
await expect(pool.run([1])).rejects.toThrow('wx task failed');
|
||||
pool.terminate();
|
||||
});
|
||||
});
|
||||
|
||||
describe('WorkerPool fallback chain when WeChat is NOT fully set up', () => {
|
||||
test('falls back to single-threaded options.fallback when the script is missing', async () => {
|
||||
const wx = installWx({ files: {} }); // worker script missing from the package
|
||||
// The inline executor calls the fallback with SPREAD args (this._fn(...task.args)), so
|
||||
// run([21]) invokes fallback(21) — matching the documented `(n: number) => ...` convention.
|
||||
const fallback = jest.fn((n: number) => n * 2);
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 4, fallback });
|
||||
await expect(pool.run([21])).resolves.toBe(42);
|
||||
expect(fallback).toHaveBeenCalledWith(21);
|
||||
// The readiness probe calls createWorker exactly once (and it throws, proving the script is
|
||||
// missing); the pool then runs every task on the single-threaded fallback and never builds a
|
||||
// real worker, so no FakeWxWorker instance is ever constructed.
|
||||
expect(wx.createWorker).toHaveBeenCalledTimes(1);
|
||||
expect(FakeWxWorker.instances).toHaveLength(0);
|
||||
pool.terminate();
|
||||
});
|
||||
|
||||
test('without a fallback, run() rejects with the precise missing-file reason', async () => {
|
||||
installWx({ files: {} });
|
||||
const pool = new WorkerPool('workers/demo.js', { maxWorkers: 4 });
|
||||
await expect(pool.run([1])).rejects.toThrow(/No worker backend for/);
|
||||
await expect(pool.run([1])).rejects.toThrow(/does not exist in the code package/);
|
||||
pool.terminate();
|
||||
});
|
||||
|
||||
test('an invalid path also lands on the fallback instead of throwing at createWorker', async () => {
|
||||
const wx = installWx();
|
||||
const pool = new WorkerPool('/absolute/demo.js', { fallback: () => 'sync-result' });
|
||||
await expect(pool.run([])).resolves.toBe('sync-result');
|
||||
expect(wx.createWorker).not.toHaveBeenCalled();
|
||||
pool.terminate();
|
||||
});
|
||||
});
|
||||
|
||||
describe('createWorker(path) on WeChat', () => {
|
||||
test('wraps createWorker and routes messages both ways', async () => {
|
||||
installWx();
|
||||
const w = createWorker('workers/demo.js');
|
||||
expect(w).not.toBeNull();
|
||||
expect(FakeWxWorker.instances).toHaveLength(1);
|
||||
const got = new Promise<any>((resolve) => { w!.onMessage(resolve); });
|
||||
w!.postMessage({ id: 9, args: [5] });
|
||||
await expect(got).resolves.toEqual({ id: 9, ok: true, value: 10 });
|
||||
w!.terminate();
|
||||
expect(FakeWxWorker.instances[0].terminated).toBe(true);
|
||||
});
|
||||
|
||||
test('V1 copies data (no transfer list), V2 passes transferables through', () => {
|
||||
installWx({ v2: false });
|
||||
const w1 = createWorker('workers/demo.js')!;
|
||||
const buf = new ArrayBuffer(8);
|
||||
w1.postMessage({ id: 1, args: [] }, [buf]);
|
||||
expect(FakeWxWorker.instances[0].transfers[0]).toBeUndefined();
|
||||
|
||||
FakeWxWorker.instances.length = 0;
|
||||
installWx({ v2: true });
|
||||
const w2 = createWorker('workers/demo.js')!;
|
||||
w2.postMessage({ id: 2, args: [] }, [buf]);
|
||||
expect(FakeWxWorker.instances[0].transfers[0]).toEqual([buf]);
|
||||
});
|
||||
|
||||
test('throws a descriptive error when the environment is incomplete and no Worker exists', () => {
|
||||
installWx({ files: {} });
|
||||
// Both halves of the diagnosis must be present: the missing global Worker route, and the
|
||||
// precise packaging reason embedded from diagnose().
|
||||
expect(() => createWorker('workers/demo.js')).toThrow(/no global Worker fallback/);
|
||||
expect(() => createWorker('workers/demo.js')).toThrow(/does not exist in the code package/);
|
||||
// And it must tell the developer what to do next.
|
||||
expect(() => createWorker('workers/demo.js')).toThrow(/options\.fallback/);
|
||||
});
|
||||
|
||||
test('onProcessKilled is routed to the error listener', () => {
|
||||
installWx();
|
||||
const w = createWorker('workers/demo.js')!;
|
||||
const errSpy = jest.fn();
|
||||
w.onError(errSpy);
|
||||
const fake = FakeWxWorker.instances[0];
|
||||
expect(fake.killedListener).toBeInstanceOf(Function);
|
||||
fake.killedListener!();
|
||||
expect(errSpy).toHaveBeenCalledTimes(1);
|
||||
expect(String(errSpy.mock.calls[0][0].message)).toMatch(/process was killed/i);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user