forked from Blendman974/faceclaw
Phone CPU usage optimization
This commit is contained in:
1 parent
44eddedc01
commit
9560f3ac8d
26 files changed
+606
-167
No files matched your search
@@ -1,9 +1,47 @@
|
||||
package com.faceclaw.app
|
||||
|
||||
import kotlin.test.*
|
||||
import kotlin.random.Random
|
||||
|
||||
class DisplayListTest {
|
||||
private fun hex(s: String) = s.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
|
||||
@Test fun screenCopyPreservesOffsetsClippingPaddingAndAliasing() {
|
||||
val random = Random(42)
|
||||
val renderer = DisplayListRenderer(emptyMap())
|
||||
for (sourceWidth in listOf(1, 2, 3, 7, 8, 640)) for (destinationWidth in listOf(1, 2, 3, 7, 8, 640)) {
|
||||
for (shared in listOf(false, true)) for (shift in listOf(-3, 0, 2)) {
|
||||
val sourceHeight = random.nextInt(1, 5); val destinationHeight = random.nextInt(1, 5)
|
||||
val sourceOffset = random.nextInt(4); val destinationOffset = random.nextInt(4)
|
||||
val size = maxOf(sourceOffset + (sourceWidth + 1) / 2 * sourceHeight,
|
||||
destinationOffset + (destinationWidth + 1) / 2 * destinationHeight) + 3
|
||||
val source = random.nextBytes(size)
|
||||
val destination = if (shared) source else random.nextBytes(size)
|
||||
val expectedSource = source.copyOf()
|
||||
val expectedDestination = if (shared) expectedSource else destination.copyOf()
|
||||
// Original per-pixel semantics, including cascading writes when
|
||||
// views alias and ignoring shiftX when reading the source.
|
||||
val referenceSource = DisplayListRenderer.Target(expectedSource, sourceWidth, sourceHeight, sourceOffset, 5)
|
||||
val referenceDestination = DisplayListRenderer.Target(expectedDestination, destinationWidth, destinationHeight, destinationOffset, shift)
|
||||
for (y in 0 until sourceHeight) for (x in 0 until sourceWidth)
|
||||
referenceDestination.put(x, y, referenceSource.get(x, y))
|
||||
assertEquals(emptySet(), renderer.render(DrawProtocol.SCREEN,
|
||||
DisplayListRenderer.Target(source, sourceWidth, sourceHeight, sourceOffset, 5),
|
||||
DisplayListRenderer.Target(destination, destinationWidth, destinationHeight, destinationOffset, shift)))
|
||||
assertContentEquals(expectedDestination, destination, "$sourceWidth/$destinationWidth shared=$shared shift=$shift")
|
||||
assertContentEquals(expectedSource, source)
|
||||
}
|
||||
}
|
||||
val source = random.nextBytes(640 * 480 / 2)
|
||||
val destination = ByteArray(source.size)
|
||||
renderer.render(DrawProtocol.SCREEN, DisplayListRenderer.Target(source,640,480), DisplayListRenderer.Target(destination,640,480))
|
||||
assertContentEquals(source, destination)
|
||||
}
|
||||
@Test fun invalidGraphDoesNotCopyScreenIntoComposition() {
|
||||
val screen = hex("12345678"); val composition = hex("9abcdef0")
|
||||
val resources = mapOf(1 to DrawProtocol.displayList(listOf(byteArrayOf(99,0))))
|
||||
assertFails { DisplayListRenderer(resources).render(1, DisplayListRenderer.Target(screen,8,1), DisplayListRenderer.Target(composition,8,1)) }
|
||||
assertContentEquals(hex("9abcdef0"), composition)
|
||||
}
|
||||
@Test fun oddPixelsRawRleClippingFontsNestedListsAndLut() {
|
||||
val raw = DrawProtocol.rawImage(3, 3, hex("123045607890"))
|
||||
val font = ByteArray(197); font[0]=1; font[67]=193.toByte(); hex("0801011f").copyInto(font,193)
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.faceclaw.app
|
||||
|
||||
import kotlin.test.*
|
||||
|
||||
class PreviewPackingTest {
|
||||
private fun level(value: Byte): Int = minOf(15, ((value.toInt() and 255) + 8) / 16)
|
||||
|
||||
@Test
|
||||
fun everyPairOfGrayValuesHasTheSameWireEncoding() {
|
||||
val pixels = ByteArray(65536 * 2) { if (it % 2 == 0) (it / 512).toByte() else (it / 2).toByte() }
|
||||
val packed = BmpUtil.pack4bppFromGray8(pixels, 512, 256)
|
||||
for (i in packed.indices) {
|
||||
assertEquals((level(pixels[i * 2]) * 16 + level(pixels[i * 2 + 1])).toByte(), packed[i], "pair $i")
|
||||
}
|
||||
for (v in 0..255) assertEquals(level(v.toByte()), BmpUtil.nibbleForGray(v))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun oddWidthsPadEveryRowAndIgnoreTrailingInput() {
|
||||
for (width in listOf(1, 3, 5, 639, 641)) {
|
||||
val height = 7
|
||||
val pixels = ByteArray(width * height + 13) { (it * 73 + 19).toByte() }
|
||||
val stride = (width + 1) / 2
|
||||
val packed = BmpUtil.pack4bppFromGray8(pixels, width, height)
|
||||
assertEquals(stride * height, packed.size)
|
||||
for (y in 0 until height) {
|
||||
for (x in 0 until width) {
|
||||
val byte = packed[y * stride + x / 2].toInt() and 255
|
||||
assertEquals(level(pixels[y * width + x]), if (x % 2 == 0) byte / 16 else byte % 16)
|
||||
}
|
||||
assertEquals(0, packed[(y + 1) * stride - 1].toInt() and 15)
|
||||
}
|
||||
}
|
||||
assertContentEquals(ByteArray(4), BmpUtil.pack4bppFromGray8(null, 3, 2))
|
||||
assertContentEquals(ByteArray(4), BmpUtil.pack4bppFromGray8(ByteArray(5) { -1 }, 3, 2))
|
||||
assertTrue(BmpUtil.pack4bppFromGray8(null, 0, 2).isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun wireFramesSkipPreviewButExplicitReadbackIncludesLatestShellAndPixels() {
|
||||
val compositor = SurfaceCompositor(false)
|
||||
compositor.configureScreen(3, 2)
|
||||
compositor.configureSurface("app", 0, 0, 3, 2, 0, SurfaceCompositor.TRANSPARENCY_OPAQUE)
|
||||
// One white 2x1 shell layer at (0,0), with no dimming or selection.
|
||||
val header = listOf(1, 1, 0, 0, 2, 1, 256, 0, 0).flatMap { listOf(it.toByte(), (it shr 8).toByte()) }.toByteArray()
|
||||
compositor.setShellScene(ArrayByteReader(header + byteArrayOf(-16, -16)))
|
||||
val wire = compositor.applyAndComposite("app", ArrayByteReader(ByteArray(6) { 32 }), 0, 0, 3, 2, "first")
|
||||
assertSame(wire.screenGray, wire.gray) // ShellScene.preview allocates its own pixels.
|
||||
assertContentEquals(ByteArray(6) { 32 }, wire.screenGray)
|
||||
assertEquals(1, wire.shellScene.layers.size)
|
||||
val preview = assertNotNull(compositor.previewComposite())
|
||||
assertContentEquals(byteArrayOf(-16, -16, 32, 32, 32, 32), preview.gray)
|
||||
assertEquals(wire.fingerprint, preview.fingerprint)
|
||||
assertContentEquals(wire.screenGray, preview.screenGray)
|
||||
|
||||
// Updates while hidden retain the newest frame. Preview reads don't
|
||||
// consume the wire sequence or affect the next submitted frame.
|
||||
val newer = compositor.applyAndComposite("app", ArrayByteReader(ByteArray(6) { 64 }), 0, 0, 3, 2, "second")
|
||||
assertEquals(wire.seq + 1, newer.seq)
|
||||
assertSame(newer.screenGray, newer.gray)
|
||||
assertContentEquals(byteArrayOf(-16, -16, 64, 64, 64, 64), compositor.previewComposite()!!.gray)
|
||||
compositor.setBlanked(true)
|
||||
assertContentEquals(ByteArray(6), compositor.previewComposite()!!.gray)
|
||||
compositor.setBlanked(false)
|
||||
assertContentEquals(byteArrayOf(-16, -16, 64, 64, 64, 64), compositor.previewComposite()!!.gray)
|
||||
}
|
||||
}
|
||||
@@ -126,6 +126,51 @@ class ResourceCacheTest {
|
||||
assertNull(TexturePlanner.plan(null, ByteArray(packed.size), 8, 4, draws, cache, 1, true, 8, testPlatform()))
|
||||
}
|
||||
|
||||
@Test fun imagePixelLoopsPreserveClippingTransparencyAndNeighborNibbles() {
|
||||
val width = 12
|
||||
val height = 8
|
||||
for (imageWidth in listOf(3, 4, 5, 9)) {
|
||||
val imageHeight = 5
|
||||
val pixels = ByteArray(imageWidth * imageHeight) { i ->
|
||||
if (i % 3 == 0) 0 else (((i % 15) + 1) * 16).toByte()
|
||||
}
|
||||
val id = ImageAtlas.ensure("pixel-loop-$imageWidth", imageWidth, imageHeight, ArrayByteReader(pixels))
|
||||
for (left in listOf(-1, 0, 1, 2, 10, 11, 14)) for (top in listOf(-1, 0, 1, 7, 9)) {
|
||||
val gray = ByteArray(width * height) { ((it % 15 + 1) * 16).toByte() }
|
||||
val visibleInk = ArrayList<Int>()
|
||||
for (row in 0 until imageHeight) for (col in 0 until imageWidth) {
|
||||
val x = left + col; val y = top + row; val value = pixels[row * imageWidth + col]
|
||||
if (x in 0 until width && y in 0 until height && value.toInt() != 0) {
|
||||
gray[y * width + x] = value
|
||||
visibleInk.add(y * width + x)
|
||||
}
|
||||
}
|
||||
val expected = BmpUtil.pack4bppFromGray8(gray, width, height)
|
||||
val draws = arrayOf(SurfaceCompositor.ScreenDraw.image(id, left, top))
|
||||
val plan = TexturePlanner.plan(null, expected, width, height, draws, ResourceCacheState(), 1, true, 8, testPlatform())
|
||||
if (left < 0 || top < 0 || left >= width || top >= height) {
|
||||
assertNull(plan) // The wire format cannot replay negative image origins.
|
||||
continue
|
||||
}
|
||||
val result = assertNotNull(plan, "$imageWidth at $left,$top")
|
||||
assertEquals(1, result.drawnImages)
|
||||
val actual = ByteArray(expected.size) { 0x55 }
|
||||
DisplayListRenderer(uploaded(result.resourceCommands)).execute(
|
||||
DrawProtocol.sequence(DrawProtocol.fromOptimized(result.payload, width, height)),
|
||||
DisplayListRenderer.Target(actual, width, height))
|
||||
assertContentEquals(expected, actual, "$imageWidth at $left,$top")
|
||||
|
||||
// A conflicting visible ink pixel must reject the cached draw.
|
||||
if (visibleInk.isNotEmpty()) {
|
||||
val offset = visibleInk.first()
|
||||
gray[offset] = 0
|
||||
assertNull(TexturePlanner.plan(null, BmpUtil.pack4bppFromGray8(gray, width, height),
|
||||
width, height, draws, ResourceCacheState(), 1, true, 8, testPlatform()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun registerFont(key: String, encodings: List<Int>, size: Int = 2): Int {
|
||||
val out = ByteSink(); val name = key.encodeToByteArray()
|
||||
out.write(name.size); out.write(name, 0, name.size); out.write(size)
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.faceclaw.app
|
||||
|
||||
import kotlin.random.Random
|
||||
import kotlin.test.*
|
||||
|
||||
class RleEncoderTest {
|
||||
/** Deliberately simple per-pixel reference, independent of the byte scan. */
|
||||
private fun reference(packed: ByteArray): ByteArray {
|
||||
val output = ArrayList<Byte>()
|
||||
var color = -1
|
||||
var count = 0
|
||||
fun flush() {
|
||||
while (count > 0) {
|
||||
val n = minOf(count, 65535)
|
||||
when {
|
||||
n <= 15 -> output.add((n * 16 + color).toByte())
|
||||
n <= 255 -> { output.add(color.toByte()); output.add(n.toByte()) }
|
||||
else -> { output.add(color.toByte()); output.add(0); output.add(n.toByte()); output.add((n / 256).toByte()) }
|
||||
}
|
||||
count -= n
|
||||
}
|
||||
}
|
||||
for (byte in packed) for (pixel in listOf((byte.toInt() and 255) / 16, byte.toInt() and 15)) {
|
||||
if (pixel != color) { flush(); color = pixel }
|
||||
count++
|
||||
}
|
||||
flush()
|
||||
return output.toByteArray()
|
||||
}
|
||||
|
||||
@Test fun allTwoByteInputsPreserveExactTokensAcrossNibbleBoundaries() {
|
||||
for (value in 0..65535) {
|
||||
val packed = byteArrayOf((value / 256).toByte(), value.toByte())
|
||||
assertContentEquals(reference(packed), BleImageOptimizer.rleEncode(packed), "input $value")
|
||||
}
|
||||
assertContentEquals(ByteArray(0), BleImageOptimizer.rleEncode(ByteArray(0)))
|
||||
}
|
||||
|
||||
@Test fun longRunsAndEveryTokenBoundaryAtBothNibbleAlignments() {
|
||||
for (length in listOf(1, 2, 14, 15, 16, 254, 255, 256, 65534, 65535, 65536, 131070, 131071)) {
|
||||
for (prefix in 0..1) for (color in listOf(0, 7, 15)) {
|
||||
val values = List(prefix) { (color + 1) % 16 } + List(length) { color } + listOf((color + 2) % 16)
|
||||
val packed = ByteArray((values.size + 1) / 2) { i ->
|
||||
(values[i * 2] * 16 + (values.getOrNull(i * 2 + 1) ?: 0)).toByte()
|
||||
}
|
||||
assertContentEquals(reference(packed), BleImageOptimizer.rleEncode(packed), "$prefix/$length/$color")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun noiseAndMixedRunsPreserveExactWireOutput() {
|
||||
val random = Random(123)
|
||||
repeat(100) {
|
||||
val data = random.nextBytes(random.nextInt(1, 4096))
|
||||
assertContentEquals(reference(data), BleImageOptimizer.rleEncode(data))
|
||||
repeat(20) {
|
||||
val start = random.nextInt(data.size)
|
||||
data.fill((random.nextInt(16) * 17).toByte(), start, minOf(data.size, start + random.nextInt(1, 200)))
|
||||
}
|
||||
assertContentEquals(reference(data), BleImageOptimizer.rleEncode(data))
|
||||
}
|
||||
val screen = ByteArray(640 * 480 / 2) { 0x77 }
|
||||
assertContentEquals(reference(screen), BleImageOptimizer.rleEncode(screen))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const vm = require('node:vm');
|
||||
const ts = require('typescript');
|
||||
|
||||
// Exercise the controller's real methods without starting BLE or the app shell.
|
||||
function harness() {
|
||||
const source = ts.createSourceFile('controller.ts', fs.readFileSync('app/g2/dashboard-controller.ts', 'utf8'), ts.ScriptTarget.Latest, true);
|
||||
const controller = source.statements.find(node => ts.isClassDeclaration(node) && node.name.text === 'DashboardController');
|
||||
const names = ['attachPhonePreview', 'schedulePreviewUpdate', 'updateCompositePreview'];
|
||||
const methods = names.map(name => controller.members.find(node => node.name?.getText(source) === name).getText(source));
|
||||
let now = 1000, focus = true, interactive = true, activityPresent = true, previews = 0, records = 0;
|
||||
const timers = new Map();
|
||||
const activity = { hasWindowFocus: () => focus, getSystemService: () => ({ isInteractive: () => interactive }) };
|
||||
const context = { exports: {}, global: { isAndroid: true },
|
||||
Application: { android: { get foregroundActivity() { return activityPresent ? activity : null; } } },
|
||||
android: { content: { Context: { POWER_SERVICE: 'power' } } },
|
||||
Date: { now: () => now }, CONNECTED_PREVIEW_MIN_UPDATE_MS: 100, RECORDING_MIN_CAPTURE_MS: 200,
|
||||
previewColorSetting: { get: () => 'green' },
|
||||
setTimeout: fn => { const id = timers.size + 1; timers.set(id, fn); return id; },
|
||||
clearTimeout: id => timers.delete(id),
|
||||
};
|
||||
vm.runInNewContext(ts.transpileModule(`export class Harness { ${methods.join('\n')} }`, {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
|
||||
}).outputText, context);
|
||||
const instance = new context.exports.Harness();
|
||||
Object.assign(instance, { lastConnectedPreviewUpdateAtMs: 0, lastRecordCaptureAtMs: 0,
|
||||
phonePreviewVisible: null, previewTrailingTimer: null, screenRecordingActive: false,
|
||||
display: { getCompositePreview: () => { previews++; return {}; }, recordScreenFrame: () => records++ },
|
||||
setDisplayPreview() {},
|
||||
});
|
||||
return { instance, timers, previews: () => previews, records: () => records,
|
||||
tick: (ms = 1000) => { now += ms; instance.updateCompositePreview(); },
|
||||
focus: value => { focus = value; }, interactive: value => { interactive = value; },
|
||||
activity: value => { activityPresent = value; } };
|
||||
}
|
||||
|
||||
test('phone preview skips hidden pages, background activity and screen off; resumes with latest frame', () => {
|
||||
const h = harness();
|
||||
h.tick();
|
||||
assert.equal(h.previews(), 0);
|
||||
let shown = true;
|
||||
const detach = h.instance.attachPhonePreview(() => shown);
|
||||
assert.equal(h.previews(), 1);
|
||||
shown = false; h.tick();
|
||||
shown = true; h.focus(false); h.tick();
|
||||
h.focus(true); h.interactive(false); h.tick();
|
||||
h.interactive(true); h.activity(false); h.tick();
|
||||
assert.equal(h.previews(), 1);
|
||||
h.activity(true); h.tick();
|
||||
assert.equal(h.previews(), 2);
|
||||
detach(); h.tick();
|
||||
assert.equal(h.previews(), 2);
|
||||
});
|
||||
|
||||
test('explicit GIF recording continues without rendering a hidden phone bitmap', () => {
|
||||
const h = harness();
|
||||
h.instance.screenRecordingActive = true;
|
||||
h.instance.attachPhonePreview(() => true);
|
||||
h.interactive(false);
|
||||
h.tick(); h.tick(100); h.tick(100);
|
||||
assert.equal(h.records(), 3);
|
||||
assert.equal(h.previews(), 1);
|
||||
h.instance.phonePreviewVisible = null;
|
||||
h.tick();
|
||||
assert.equal(h.records(), 4);
|
||||
h.instance.screenRecordingActive = false;
|
||||
h.tick();
|
||||
assert.equal(h.records(), 4);
|
||||
});
|
||||
|
||||
test('page detach cancels trailing previews and cannot detach a newer page', () => {
|
||||
const h = harness();
|
||||
const oldDetach = h.instance.attachPhonePreview(() => true);
|
||||
const newDetach = h.instance.attachPhonePreview(() => true);
|
||||
oldDetach();
|
||||
h.tick();
|
||||
assert.equal(h.previews(), 3);
|
||||
h.instance.schedulePreviewUpdate();
|
||||
assert.equal(h.timers.size, 1);
|
||||
newDetach();
|
||||
assert.equal(h.timers.size, 0);
|
||||
h.instance.schedulePreviewUpdate();
|
||||
assert.equal(h.timers.size, 0);
|
||||
});
|
||||
@@ -21,17 +21,20 @@ int main(int argc, const char **argv) { @autoreleasepool {
|
||||
NSString *failure = [server start:atoi(argv[1])];
|
||||
if (failure.length) return 3;
|
||||
puts("READY"); fflush(stdout);
|
||||
for (;;) { @autoreleasepool {
|
||||
__weak FaceclawRemoteInput *weakServer = server;
|
||||
[server setRequestListener:^{ @autoreleasepool {
|
||||
FaceclawRemoteInput *server = weakServer;
|
||||
if (![NSThread isMainThread]) exit(4);
|
||||
NSString *raw = [server nextRequest];
|
||||
if (raw) {
|
||||
NSDictionary *request = [NSJSONSerialization JSONObjectWithData:[raw dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
|
||||
NSDictionary *body = [NSJSONSerialization JSONObjectWithData:[request[@"body"] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
|
||||
if ([body[@"text"] isEqual:@"stop"]) { [server stop]; usleep(300000); puts("STOPPED"); fflush(stdout); return 0; }
|
||||
if ([body[@"text"] isEqual:@"stop"]) { [server stop]; usleep(300000); puts("STOPPED"); fflush(stdout); exit(0); }
|
||||
NSData *reply = [NSJSONSerialization dataWithJSONObject:@{@"ok":@YES, @"echo":body ?: @{}} options:0 error:nil];
|
||||
[server complete:[request[@"id"] longLongValue] response:[[NSString alloc] initWithData:reply encoding:NSUTF8StringEncoding]];
|
||||
}
|
||||
usleep(1000);
|
||||
}}
|
||||
}}];
|
||||
[[NSRunLoop mainRunLoop] run];
|
||||
}}
|
||||
`);
|
||||
const binary = path.join(directory, 'probe');
|
||||
@@ -66,7 +69,7 @@ int main(int argc, const char **argv) { @autoreleasepool {
|
||||
await send(options, { action: 'input', gesture: 'click' });
|
||||
await assert.rejects(send(options, { action: 'text', text: 'stop' }));
|
||||
assert.equal(await exited, 0);
|
||||
console.log('Native socket probe passed: crypto, framing, UTF-8, multiple connections, shutdown.');
|
||||
console.log('Native socket probe passed: crypto, framing, UTF-8, main-thread request notifications, multiple connections, shutdown.');
|
||||
} finally { child.kill(); }
|
||||
}
|
||||
main().catch(error => { console.error(error); process.exitCode = 1; }).finally(() => fs.rmSync(directory, { recursive: true, force: true }));
|
||||
@@ -0,0 +1,83 @@
|
||||
const { test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const vm = require('node:vm');
|
||||
const ts = require('typescript');
|
||||
|
||||
function fixture() {
|
||||
let ready, changed, tokens = [{}], polls = 0, active = 0, maxActive = 0;
|
||||
const queue = [], replies = [], timers = new Map(), handled = [];
|
||||
const native = {
|
||||
start() {}, addresses: () => ['127.0.0.1'], stop: () => { queue.length = 0; },
|
||||
nextRequest() { polls++; return queue.length ? JSON.stringify(queue.shift()) : null; },
|
||||
complete: (id, response) => replies.push({ id, ...JSON.parse(response) }),
|
||||
};
|
||||
let handle = async body => ({ ok: true, body });
|
||||
const modules = {
|
||||
'../native/settings-store': { getStringSetting: (_k, d) => d, setStringSetting() {},
|
||||
onSettingsStoreChanged: cb => { changed = cb; return () => { changed = null; }; } },
|
||||
'../native/remote-input': { remoteNative: cb => { ready = cb; return native; }, remoteInterfaces: () => [],
|
||||
randomTokenSecret() {}, tokenHash() {} },
|
||||
'./listeners': require('../.test-build/app/remote/listeners.js'),
|
||||
'./protocol': { TokenStore: class { list() { return tokens; } }, REMOTE_PORT: 8791,
|
||||
handleRequest: async body => {
|
||||
handled.push(body); active++; maxActive = Math.max(maxActive, active);
|
||||
try { return await handle(body); } finally { active--; }
|
||||
} },
|
||||
};
|
||||
const context = { exports: {}, require: id => modules[id],
|
||||
setInterval: (fn, ms) => { timers.set(fn, ms); return fn; }, clearInterval: id => timers.delete(id) };
|
||||
vm.runInNewContext(ts.transpileModule(fs.readFileSync('app/remote/service.ts', 'utf8'), {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 },
|
||||
}).outputText, context);
|
||||
const stop = context.exports.startRemoteInput({});
|
||||
return { stop, timers, replies, handled, get polls() { return polls; }, get maxActive() { return maxActive; },
|
||||
setHandle: fn => { handle = fn; },
|
||||
notify: () => ready(), enqueue: (id, expiresAt = Date.now() + 5000) => queue.push({ id, body: id, expiresAt }),
|
||||
tokens: value => { tokens = value; changed('remoteInput.tokens.v1'); },
|
||||
};
|
||||
}
|
||||
const settle = () => new Promise(resolve => setImmediate(resolve));
|
||||
|
||||
test('idle remote sockets do not poll native requests, including network reconciliation', () => {
|
||||
const f = fixture();
|
||||
assert.deepEqual([...f.timers.values()], [3000]);
|
||||
for (let i = 0; i < 100; i++) for (const tick of f.timers.keys()) tick();
|
||||
assert.equal(f.polls, 0);
|
||||
f.stop(); assert.equal(f.timers.size, 0);
|
||||
});
|
||||
|
||||
test('request notifications drain serially without losing wakeups while busy', async () => {
|
||||
const f = fixture(); let release;
|
||||
f.setHandle(body => body === 'a' ? new Promise(resolve => { release = resolve; }) : { ok: true });
|
||||
f.enqueue('a'); f.notify();
|
||||
f.enqueue('b'); f.notify(); f.enqueue('c'); f.notify();
|
||||
assert.deepEqual(f.handled, ['a']);
|
||||
release({ ok: true }); await settle();
|
||||
assert.deepEqual(f.handled, ['a', 'b', 'c']);
|
||||
assert.deepEqual(f.replies.map(r => r.id), ['a', 'b', 'c']);
|
||||
assert.equal(f.maxActive, 1);
|
||||
const idlePolls = f.polls; await settle(); assert.equal(f.polls, idlePolls);
|
||||
f.stop();
|
||||
});
|
||||
|
||||
test('expired requests and failed handlers do not prevent queued requests from draining', async () => {
|
||||
const f = fixture(); f.setHandle(body => { if (body === 'bad') throw Error('test'); return { ok: true }; });
|
||||
f.enqueue('expired', 0); f.enqueue('bad'); f.enqueue('good'); f.notify(); await settle();
|
||||
assert.deepEqual(f.handled, ['bad', 'good']);
|
||||
assert.equal(f.replies[0].error, 'failed'); assert.equal(f.replies[1].ok, true);
|
||||
f.stop();
|
||||
});
|
||||
|
||||
test('token removal and service shutdown stop dispatch, and re-enabling tokens resumes it', async () => {
|
||||
const f = fixture();
|
||||
f.enqueue('removed'); f.tokens([]); f.notify(); await settle();
|
||||
assert.deepEqual(f.handled, []); assert.equal(f.timers.size, 0);
|
||||
f.tokens([{}]); f.enqueue('resumed'); f.notify(); await settle();
|
||||
assert.deepEqual(f.handled, ['resumed']);
|
||||
let release; f.setHandle(() => new Promise(resolve => { release = resolve; }));
|
||||
f.enqueue('in-flight'); f.notify(); f.stop();
|
||||
f.enqueue('late'); f.notify(); release({ ok: true }); await settle();
|
||||
assert.deepEqual(f.replies.map(r => r.id), ['resumed']);
|
||||
assert.deepEqual(f.handled, ['resumed', 'in-flight']);
|
||||
});
|
||||
Reference in new issue
Block a user