41 lines
1.6 KiB
TypeScript
41 lines
1.6 KiB
TypeScript
import assert from 'node:assert/strict';
|
|
import test from 'node:test';
|
|
import { latestOnly } from '../../../waybetter/packages/shell/src/frame/syncGate.ts';
|
|
|
|
const deferred = () => {
|
|
let resolve!: () => void;
|
|
const promise = new Promise<void>(r => { resolve = r; });
|
|
return { promise, resolve };
|
|
};
|
|
|
|
test('one send in flight; only the newest queued value follows it', async () => {
|
|
const sent: number[] = [];
|
|
const gates: Array<() => void> = [];
|
|
const send = latestOnly<number>(value => { sent.push(value); const d = deferred(); gates.push(d.resolve); return d.promise; });
|
|
const settled: number[] = [];
|
|
const calls = [1, 2, 3, 4].map(value => send(value).then(() => settled.push(value)));
|
|
await Promise.resolve();
|
|
assert.deepEqual(sent, [1], 'frames 2-4 wait while 1 is in flight');
|
|
gates[0]();
|
|
await new Promise(r => setTimeout(r, 0));
|
|
assert.deepEqual(sent, [1, 4], 'the stale layouts 2 and 3 are never sent');
|
|
gates[1]();
|
|
await Promise.all(calls);
|
|
assert.deepEqual(settled.sort(), [1, 2, 3, 4], 'callers of dropped values settle once a newer one is acknowledged');
|
|
});
|
|
|
|
test('a failed send does not wedge the gate', async () => {
|
|
const sent: string[] = [];
|
|
const send = latestOnly<string>(async value => { sent.push(value); if (value === 'bad') throw new Error('native refused'); });
|
|
await send('bad');
|
|
await send('good');
|
|
assert.deepEqual(sent, ['bad', 'good']);
|
|
});
|
|
|
|
test('sends go out immediately when idle', async () => {
|
|
const sent: number[] = [];
|
|
const send = latestOnly<number>(async value => { sent.push(value); });
|
|
await send(1);
|
|
await send(2);
|
|
assert.deepEqual(sent, [1, 2]);
|
|
});
|