robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

bfredlMerge pull request #41186 from Rawan10101/fix-wasm-browser69e61d52e2

master
8.1 KiB253 linesraw
1// TODO: Add a fallback when SharedArrayBuffer is unavailable.
2// Transport: owns the worker and SharedArrayBuffer
3class WorkerTransport {
4  constructor(workerPath, { cols = 80, rows = 24, cap = 1 << 16 } = {}) {
5    this.CAP = cap;
6    this.sab = new SharedArrayBuffer(12 + this.CAP);
7    this.state = new Int32Array(this.sab, 0, 3); // [head, tail, closed]
8    this.ringData = new Uint8Array(this.sab, 12, this.CAP); // offset 12
9
10    this._bytesHandlers = [];
11    this._statusHandlers = [];
12    this._readyHandlers = [];
13    this._exitHandlers = [];
14
15    this.worker = new Worker(workerPath);
16    this.worker.onmessage = (ev) => {
17      console.log("[main] worker message", ev.data.type, ev.data);
18      this._onWorkerMessage(ev.data);
19    };
20    this.worker.onerror = (e) => this._emitStatus("worker error: " + e.message);
21    this.worker.postMessage({ type: "init", sab: this.sab, cols, rows });
22  }
23
24  shutdown() {
25    Atomics.store(this.state, 2, 1);
26    Atomics.notify(this.state, 0);
27    this.worker.postMessage({ type: "shutdown" });
28  }
29
30  _onWorkerMessage(msg) {
31    console.log("[main] _onWorkerMessage got", msg.type);
32
33    if (msg.type === "stdout") {
34      console.log(`[main] stdout bytes:`, msg.bytes);
35      this._bytesHandlers.forEach((h) => h(msg.bytes));
36    } else if (msg.type === "stderr") {
37      const text = new TextDecoder().decode(new Uint8Array(msg.bytes));
38      this._emitStatus("[stderr] " + text);
39    } else if (msg.type === "status") {
40      this._emitStatus(msg.text);
41    } else if (msg.type === "shared-info") {
42      this.sharedState = new Int32Array(
43        msg.memory,
44        msg.statePtr,
45        1 + 256 + 256,
46      );
47      console.log("[main] shared-info received, direct futex wake enabled");
48    } else if (msg.type === "ready") {
49      console.log("[main] worker signaled ready, RPC channel should be live");
50      this._readyHandlers.forEach((h) => h());
51    }
52    else if (msg.type === "exited") {
53      console.log("worker signaled nvim exited, code=", msg.code);
54      this._exitHandlers.forEach((h) => h(msg.code));
55    }
56  }
57
58  _emitStatus(text) {
59    console.log("[main] status:", text);
60    this._statusHandlers.forEach((h) => h(text));
61  }
62
63  send(bytes) {
64    console.log("[main] Send: writing", bytes.length, "bytes");
65    const hexStr = Array.from(bytes)
66      .map((b) => b.toString(16).padStart(2, "0"))
67      .join(" ");
68    console.log(`[main] Send: ${bytes.length} bytes: ${hexStr}`);
69
70    let lastHead = 0;
71    for (let i = 0; i < bytes.length; i++) {
72      const b = bytes[i];
73      const head = Atomics.load(this.state, 0);
74      const tail = Atomics.load(this.state, 1);
75      const next = (head + 1) % this.CAP;
76      if (next === tail) {
77        console.error("[main] Send: ring buffer full");
78        return false;
79      }
80      this.ringData[head] = b;
81      Atomics.store(this.state, 0, next);
82      lastHead = next;
83    }
84
85    if (this.sharedState) {
86      // Write straight into the C-side shared struct, then wake the futex.
87      // This only works if the worker is already inside
88      // emscripten_futex_wait() at the moment call notify() if it is
89      // not waiting yet, the notify does nothing. Atomics.notify() does not
90      // queue up a wake for some future wait() call as it only wakes threads
91      // that are waiting right now.
92      const STDIN_FD = 9;
93      const tail = Atomics.load(this.state, 1);
94      const n = (lastHead - tail + this.CAP) % this.CAP;
95      Atomics.store(this.sharedState, 1 + STDIN_FD, n); // readable[STDIN_FD] = n
96      Atomics.add(this.sharedState, 0, 1); // generation++
97      Atomics.notify(this.sharedState, 0, 1); // wake the futex_wait, if any
98      console.log("[main] Send Done, direct notified futex, n=", n);
99    }
100    // There's a real startup race here: if this send() happens before the
101    // worker's event loop has reached its first Atomics.wait() (e.g.
102    // auto-attach fires the instant ready arrives), the direct notify
103    // above lands on nobody and is silently wasted. And if the C side poll
104    // loop only reacts to notify events instead of rechecking the shared
105    // value on every scan that missed wake is gone for good and the
106    // request just sits in the ring buffer forever.
107    //
108    // But until the worker actually starts blocking, it is still free to
109    // process its own message queue so this postMessage gets handled
110    // right away, routing through the worker's own markReadable() ->
111    // uv_browser_set_readable ccall path. That makes send() correct
112    // whether or not nvim has reached its poll loop yet instead of
113    // depending on lucky notify timing.
114    this.worker.postMessage({ type: "readable-hint" });
115    console.log(
116      "[main] SEND DONE, also sent readable-hint as belt-and-suspenders",
117    );
118
119    return true;
120  }
121
122  onBytes(cb) {
123    this._bytesHandlers.push(cb);
124  }
125  onStatus(cb) {
126    this._statusHandlers.push(cb);
127  }
128  onReady(cb) {
129    this._readyHandlers.push(cb);
130  }
131  onExit(cb) {
132    this._exitHandlers.push(cb);
133  }
134  persist() {
135    this.worker.postMessage({ type: "persist" });
136  }
137}
138
139class RpcClient {
140  constructor(transport) {
141    this.transport = transport;
142    this.nextMsgId = 1;
143    this.pending = new Map();
144    this.notificationHandlers = new Map();
145
146    this._buffer = new Uint8Array(0);
147
148    transport.onBytes((bytes) => this._handleBytes(bytes));
149  }
150
151  _handleBytes(newBytes) {
152    console.log(
153      "[RpcClient] _handleBytes",
154      newBytes.length,
155      newBytes.slice(0, 32),
156    );
157
158    const combined = new Uint8Array(this._buffer.length + newBytes.length);
159    combined.set(this._buffer, 0);
160    combined.set(newBytes, this._buffer.length);
161    this._buffer = combined;
162
163    const { messages, consumed } = MsgpackCodec.decodeMultiple(this._buffer);
164
165    for (const msg of messages) {
166      console.log("[RpcClient] raw decoded:", JSON.stringify(msg));
167      this._dispatch(msg);
168    }
169
170    this._buffer = this._buffer.slice(consumed);
171  }
172
173  _dispatch(rawMsg) {
174    console.log("[RpcClient] dispatching:", rawMsg);
175
176    let msg;
177    try {
178      msg = Protocol.parseMessage(rawMsg);
179    } catch (e) {
180      console.error("[RpcClient] parse failed", rawMsg, e);
181      return;
182    }
183
184    console.log("[RpcClient] parsed:", msg);
185
186    if (msg.kind === "response") {
187      const p = this.pending.get(msg.msgid);
188      if (!p) {
189        console.warn("[RpcClient] unknown msgid", msg.msgid, "pending:", [
190          ...this.pending.keys(),
191        ]);
192        return;
193      }
194      this.pending.delete(msg.msgid);
195      clearTimeout(p.timeoutId);
196      console.log("[RpcClient] resolved msgid", msg.msgid);
197      if (msg.error) {
198        p.reject(new Error(msg.error));
199      } else {
200        p.resolve(msg.result);
201      }
202    } else if (msg.kind === "notification") {
203      console.log("[RpcClient] notification:", msg.method);
204      const handlers = this.notificationHandlers.get(msg.method) || [];
205      handlers.forEach((h) => h(msg.params));
206    } else if (msg.kind === "request") {
207      console.warn("[RpcClient] unhandled request", msg);
208    }
209  }
210
211  request(method, params = []) {
212    const msgid = this.nextMsgId++;
213    const bytes = Protocol.encodeRequest(msgid, method, params);
214    console.log(
215      `[RpcClient] sending request ${msgid} (${method}), ${bytes.length} bytes`,
216    );
217
218    return new Promise((resolve, reject) => {
219      this.pending.set(msgid, {
220        resolve,
221        reject,
222        method,
223        timestamp: Date.now(),
224      });
225
226      const timeoutId = setTimeout(() => {
227        if (this.pending.has(msgid)) {
228          this.pending.delete(msgid);
229          reject(new Error(`Request ${msgid} (${method}) timed out after 30s`));
230        }
231      }, 30000);
232
233      this.pending.get(msgid).timeoutId = timeoutId;
234
235      this.transport.send(bytes);
236    });
237  }
238
239  notify(method, params = []) {
240    const bytes = Protocol.encodeNotification(method, params);
241    console.log(
242      `[RpcClient] sending notification ${method}, ${bytes.length} bytes`,
243    );
244    this.transport.send(bytes);
245  }
246
247  on(method, handler) {
248    if (!this.notificationHandlers.has(method)) {
249      this.notificationHandlers.set(method, []);
250    }
251    this.notificationHandlers.get(method).push(handler);
252  }
253}