Files
upstream-affine/packages/common/infra/src/op/__tests__/consumer.spec.ts
upstream-mirror 702cc698a7
Some checks failed
Build & Test / Analyze (javascript, affine) (push) Failing after 4s
Build & Test / Analyze (typescript, affine) (push) Failing after 3s
Build & Test / Rust test filter (push) Failing after 4s
Build & Test / Check yarn binary (push) Failing after 3s
Build & Test / E2E BlockSuite Test (3) (push) Failing after 3s
Build & Test / Analyze (javascript, blocksuite) (push) Failing after 3s
Build & Test / Analyze (typescript, blocksuite) (push) Failing after 3s
Build & Test / Mobile native build filter (push) Failing after 3s
Build & Test / E2E BlockSuite Test (1) (push) Failing after 4s
Build & Test / E2E BlockSuite Test (2) (push) Failing after 4s
Build & Test / E2E Mobile Test (1) (push) Failing after 3s
Build & Test / Unit Test (1) (push) Has been skipped
Build & Test / Unit Test (2) (push) Has been skipped
Build & Test / Unit Test (3) (push) Has been skipped
Build & Test / Unit Test (4) (push) Has been skipped
Build & Test / Unit Test (5) (push) Has been skipped
Build & Test / Native Unit Test (push) Has been skipped
Build & Test / E2E BlockSuite Test (4) (push) Failing after 3s
Build & Test / E2E BlockSuite Test (5) (push) Failing after 3s
Build & Test / E2E BlockSuite Cross Browser Test (push) Failing after 3s
Build & Test / E2E Mobile Test (2) (push) Failing after 3s
Build & Test / Build AFFiNE native (x86_64-unknown-linux-gnu) (push) Failing after 3s
Build & Test / Build Server native (push) Failing after 3s
Build & Test / Check Git Status (push) Has been skipped
Build & Test / Server Test (0, 4) (push) Has been skipped
Build & Test / Server Test (1, 4) (push) Has been skipped
Build & Test / Server Test (2, 4) (push) Has been skipped
Build & Test / Server Test (3, 4) (push) Has been skipped
Build & Test / Server Test with Elasticsearch (push) Has been skipped
Build & Test / Build @affine/electron renderer (push) Failing after 3s
Build & Test / Copilot test filter (push) Failing after 4s
Build & Test / Lint Rust (push) Has been skipped
Build & Test / Server Test with Embedded Search (push) Has been skipped
Build & Test / Server Test with Manticore Search (push) Has been skipped
Build & Test / Server E2E Test (push) Has been skipped
Build & Test / Cloud Desktop E2E Test (push) Has been skipped
Build & Test / Cloud E2E Test 1/2 (push) Has been skipped
Build & Test / Cloud E2E Test 2/2 (push) Has been skipped
Build & Test / Build Android app (push) Has been skipped
Build & Test / Test Android app (push) Has been skipped
Build & Test / Run native tests (push) Has been skipped
Build & Test / Server Copilot Api Test (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (1, 5) (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (2, 5) (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (3, 5) (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (4, 5) (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (5, 5) (push) Has been skipped
Release / Canary Gate (push) Has been skipped
Build & Test / Build AFFiNE native (aarch64-apple-darwin) (push) Has been cancelled
Build & Test / Lint (push) Has been cancelled
Build & Test / Typecheck (push) Has been cancelled
Build & Test / Build AFFiNE native (x86_64-apple-darwin) (push) Has been cancelled
Build & Test / Desktop Test (ubuntu-latest, linux, x64, x86_64-unknown-linux-gnu, true) (push) Has been cancelled
Build & Test / Desktop Test (windows-latest, windows, x64, x86_64-pc-windows-msvc, true) (push) Has been cancelled
Build & Test / E2E Test (1) (push) Has been cancelled
Build & Test / E2E Test (2) (push) Has been cancelled
Build & Test / E2E Test (3) (push) Has been cancelled
Build & Test / E2E Test (4) (push) Has been cancelled
Build & Test / E2E Test (5) (push) Has been cancelled
Build & Test / Build AFFiNE native (aarch64-pc-windows-msvc) (push) Has been cancelled
Build & Test / Build AFFiNE native (x86_64-pc-windows-msvc) (push) Has been cancelled
Build & Test / Desktop Test (macos-latest, macos, arm64, aarch64-apple-darwin, true) (push) Has been cancelled
Build & Test / Desktop Test (macos-latest, macos, x64, x86_64-apple-darwin, false) (push) Has been cancelled
Build & Test / 3, 2, 1 Launch (push) Has been cancelled
Build & Test / Build iOS app (push) Has been cancelled
Copilot Test Automatically / Setup Test (push) Failing after 1s
Release / Prepare (push) Failing after 2s
Release / Release Cloud (push) Has been skipped
Release / Release Desktop (push) Has been skipped
Release / Release Docker Image (push) Has been skipped
Release / Release Mobile (push) Has been skipped
snapshot of https://github.com/toeverything/AFFiNE.git (canary, 2026-09-16; blobs > 131072B omitted)
2026-09-16 04:01:20 +05:00

267 lines
6.9 KiB
TypeScript

import { afterEach } from 'node:test';
import { Observable } from 'rxjs';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { OpConsumer } from '../consumer';
import { type MessageHandlers, transfer } from '../message';
import type { OpSchema } from '../types';
interface TestOps extends OpSchema {
add: [{ a: number; b: number }, number];
any: [any, any];
}
declare module 'vitest' {
interface TestContext {
consumer: OpConsumer<TestOps>;
handlers: MessageHandlers;
postMessage: ReturnType<typeof vi.fn>;
}
}
describe('op consumer', () => {
beforeEach(ctx => {
const { port2 } = new MessageChannel();
// @ts-expect-error patch postMessage
port2.postMessage = vi.fn(port2.postMessage);
// @ts-expect-error patch postMessage
ctx.postMessage = port2.postMessage;
ctx.consumer = new OpConsumer(port2);
// @ts-expect-error internal api
ctx.handlers = ctx.consumer.handlers;
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it('should throw if no handler registered', async ctx => {
ctx.handlers.call({ type: 'call', id: 'add:1', name: 'add', payload: {} });
await vi.advanceTimersToNextTimerAsync();
expect(ctx.postMessage.mock.lastCall?.[0]).toMatchObject({
type: 'return',
id: 'add:1',
error: {
message: 'Handler for operation [add] is not registered.',
name: 'Error',
},
});
});
it('should handle call message', async ctx => {
ctx.consumer.register('add', ({ a, b }) => a + b);
ctx.handlers.call({
type: 'call',
id: 'add:1',
name: 'add',
payload: { a: 1, b: 2 },
});
await vi.advanceTimersToNextTimerAsync();
expect(ctx.postMessage.mock.calls[0][0]).toMatchInlineSnapshot(`
{
"data": 3,
"id": "add:1",
"type": "return",
}
`);
});
it('should serialize string errors with message', async ctx => {
ctx.consumer.register('any', () => {
throw 'worker panic';
});
ctx.handlers.call({ type: 'call', id: 'any:1', name: 'any', payload: {} });
await vi.advanceTimersToNextTimerAsync();
expect(ctx.postMessage.mock.calls[0][0]).toMatchObject({
type: 'return',
id: 'any:1',
error: {
name: 'Error',
message: 'worker panic',
},
});
});
it('should serialize plain object errors with fallback message', async ctx => {
ctx.consumer.register('any', () => {
throw { reason: 'panic', code: 'E_PANIC' };
});
ctx.handlers.call({ type: 'call', id: 'any:1', name: 'any', payload: {} });
await vi.advanceTimersToNextTimerAsync();
const message = ctx.postMessage.mock.calls[0][0]?.error?.message;
expect(typeof message).toBe('string');
expect(message).toContain('"reason":"panic"');
expect(message).toContain('"code":"E_PANIC"');
});
it('serializes worker stacks for calls and observables', async ctx => {
for (const kind of ['call', 'observable'] as const) {
ctx.postMessage.mockClear();
const marker = 'WORKER_STACK_MARKER';
const error = new TypeError(marker);
error.stack = `TypeError: ${marker}\n at workerTask (worker.ts:42:7)`;
ctx.consumer.register('any', () => {
if (kind === 'observable') {
return new Observable(observer => observer.error(error));
}
throw error;
});
if (kind === 'observable') {
ctx.handlers.subscribe({
type: 'subscribe',
id: 'any:1',
name: 'any',
payload: undefined,
});
} else {
ctx.handlers.call({
type: 'call',
id: 'any:1',
name: 'any',
payload: undefined,
});
}
await vi.advanceTimersToNextTimerAsync();
expect(ctx.postMessage.mock.calls[0][0].error).toMatchObject({
name: 'TypeError',
message: marker,
stacktrace: expect.stringContaining('worker.ts:42:7'),
});
}
});
it('should handle cancel message', async ctx => {
ctx.consumer.register('add', ({ a, b }, { signal }) => {
const { reject, resolve, promise } = Promise.withResolvers<number>();
signal?.addEventListener('abort', () => {
reject(new Error('canceled'));
});
setTimeout(() => {
resolve(a + b);
}, Number.MAX_SAFE_INTEGER);
return promise;
});
ctx.handlers.call({
type: 'call',
id: 'add:1',
name: 'add',
payload: { a: 1, b: 2 },
});
ctx.handlers.cancel({ type: 'cancel', id: 'add:1' });
await vi.advanceTimersByTimeAsync(1);
expect(ctx.postMessage).not.toBeCalled();
});
it('should transfer transferables in return', async ctx => {
const data = new Uint8Array([1, 2, 3]);
const nonTransferred = new Uint8Array([4, 5, 6]);
ctx.consumer.register('any', () => {
return transfer({ data: { data, nonTransferred } }, [data.buffer]);
});
ctx.handlers.call({ type: 'call', id: 'any:1', name: 'any', payload: {} });
await vi.advanceTimersToNextTimerAsync();
expect(ctx.postMessage).toHaveBeenCalledOnce();
expect(data.byteLength).toBe(0);
expect(nonTransferred.byteLength).toBe(3);
});
it('should handle subscribe message', async ctx => {
ctx.consumer.register('any', data => {
return new Observable(observer => {
data.forEach((v: number) => observer.next(v));
observer.complete();
});
});
ctx.handlers.subscribe({
type: 'subscribe',
id: 'any:1',
name: 'any',
payload: transfer(new Uint8Array([1, 2, 3]), [
new Uint8Array([1, 2, 3]).buffer,
]),
});
await vi.advanceTimersToNextTimerAsync();
expect(ctx.postMessage.mock.calls.map(call => call[0]))
.toMatchInlineSnapshot(`
[
{
"data": 1,
"id": "any:1",
"type": "next",
},
{
"data": 2,
"id": "any:1",
"type": "next",
},
{
"data": 3,
"id": "any:1",
"type": "next",
},
{
"id": "any:1",
"type": "complete",
},
]
`);
});
it('should handle unsubscribe message', async ctx => {
ctx.consumer.register('any', data => {
return new Observable(observer => {
data.forEach((v: number) => {
setTimeout(() => {
observer.next(v);
}, 1);
});
setTimeout(() => {
observer.complete();
}, 1);
});
});
ctx.handlers.subscribe({
type: 'subscribe',
id: 'any:1',
name: 'any',
payload: transfer(new Uint8Array([1, 2, 3]), [
new Uint8Array([1, 2, 3]).buffer,
]),
});
ctx.handlers.unsubscribe({ type: 'unsubscribe', id: 'any:1' });
await vi.advanceTimersToNextTimerAsync();
expect(ctx.postMessage.mock.calls).toMatchInlineSnapshot(`
[
[
{
"id": "any:1",
"type": "complete",
},
],
]
`);
});
});