| 58 | } |
| 59 | |
| 60 | export class WasmAnalyzer implements IAnalyzer { |
| 61 | private inner: WasmInner; |
| 62 | private streams = new Map<number, WasmStream>(); |
| 63 | private isPumping = false; |
| 64 | |
| 65 | constructor(inner: WasmInner) { |
| 66 | this.inner = inner; |
| 67 | } |
| 68 | |
| 69 | private schedulePump() { |
| 70 | if (this.isPumping) { |
| 71 | return; |
| 72 | } |
| 73 | this.isPumping = true; |
| 74 | setTimeout(this.pumpLoop, 0); |
| 75 | } |
| 76 | |
| 77 | private pumpLoop = () => { |
| 78 | if (this.streams.size === 0) { |
| 79 | this.isPumping = false; |
| 80 | return; |
| 81 | } |
| 82 | |
| 83 | const start = Date.now(); |
| 84 | let idleCount = 0; |
| 85 | while (this.streams.size > 0 && Date.now() - start < 15) { |
| 86 | const eventStr = this.inner.pump(); |
| 87 | if (!eventStr) { |
| 88 | idleCount++; |
| 89 | if (idleCount > 1000) { |
| 90 | break; |
| 91 | } |
| 92 | continue; |
| 93 | } |
| 94 | idleCount = 0; |
| 95 | try { |
| 96 | const event = JSON.parse(eventStr) as WasmEvent; |
| 97 | const stream = this.streams.get(event.id); |
| 98 | if (stream) { |
| 99 | if (event.event === 'analysisResult' && event.data) { |
| 100 | stream.queue.push(event.data); |
| 101 | } else if (event.event === 'analysisComplete') { |
| 102 | stream.queue.push(null); |
| 103 | } else if (event.event === 'analysisError' && event.error) { |
| 104 | stream.error = new Error(event.error); |
| 105 | } |
| 106 | if (stream.nextResolve) { |
| 107 | const resolve = stream.nextResolve; |
| 108 | stream.nextResolve = null; |
| 109 | resolve(null); |
| 110 | } |
| 111 | } |
| 112 | } catch (e) { |
| 113 | console.error('Failed to parse WASM pump event', e); |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | if (this.streams.size > 0) { |