()
| 40 | const PIN_CAP = 300; |
| 41 | |
| 42 | function protocolSource(): string { |
| 43 | const L: string[] = [ |
| 44 | 'export class Protocol {', |
| 45 | ' private handlers = new Map<string, (x: Uint8Array) => unknown>();', |
| 46 | ' private outbox: Uint8Array[] = [];', |
| 47 | '', |
| 48 | ' receiveOne(raw: Uint8Array): void {', |
| 49 | ' const kind = raw[0] as MessageKind;', |
| 50 | ' if (kind === MessageKind.Request) {', |
| 51 | ' this.dispatchRequest(raw);', |
| 52 | ' this.outbox.push(MessageCodec.serializeAck(raw[1] ?? 0));', |
| 53 | ' } else if (kind === MessageKind.Cancel) {', |
| 54 | ' this.outbox.push(MessageCodec.serializeCancel(raw[1] ?? 0));', |
| 55 | ' }', |
| 56 | ' }', |
| 57 | '', |
| 58 | ' private dispatchRequest(raw: Uint8Array): void {', |
| 59 | ' const id = raw[1] ?? 0;', |
| 60 | " const method = String(raw[2] ?? '');", |
| 61 | ' const handler = this.handlers.get(method);', |
| 62 | ' if (!handler) {', |
| 63 | ' this.outbox.push(MessageCodec.serializeReplyErr(id, new Error(`no handler: ${method}`)));', |
| 64 | ' return;', |
| 65 | ' }', |
| 66 | ' const started = Date.now();', |
| 67 | ' let result: unknown;', |
| 68 | ' try {', |
| 69 | ' result = handler(raw.subarray(3));', |
| 70 | ' } catch (err) {', |
| 71 | ' this.outbox.push(MessageCodec.serializeReplyErr(id, err as Error));', |
| 72 | ' return;', |
| 73 | ' }', |
| 74 | ' if (Date.now() - started > 1000) {', |
| 75 | ' this.outbox.push(MessageCodec.serializeAck(id));', |
| 76 | ' }', |
| 77 | ' if (this.outbox.length > 64) {', |
| 78 | ' this.outbox.splice(0, this.outbox.length - 64);', |
| 79 | ' }', |
| 80 | ' this.outbox.push(MessageCodec.serializeReply(id, result ?? null));', |
| 81 | ' }', |
| 82 | ]; |
| 83 | for (let i = 0; i < 300; i++) { |
| 84 | L.push('', ` trackMetric${i}(value: number): number {`, ` return value * ${i + 1} + this.outbox.length;`, ' }'); |
| 85 | } |
| 86 | L.push( |
| 87 | '}', |
| 88 | '', |
| 89 | 'export const enum MessageKind {', |
| 90 | ' Request = 1,', |
| 91 | ' Reply = 2,', |
| 92 | ' ReplyErr = 3,', |
| 93 | ' Cancel = 4,', |
| 94 | ' Ack = 5,', |
| 95 | '}', |
| 96 | '', |
| 97 | 'export class MessageCodec {', |
| 98 | ' static serializeRequest(id: number, method: string): Uint8Array {', |
| 99 | ' const body = new TextEncoder().encode(method);', |
no test coverage detected