File size: 12,475 Bytes
8a29801
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
/**

 * DevServerBridge β€” phone-side WebSocket connection to a `mentra-miniapp dev`

 * sidecar running on a developer's laptop.

 *

 * Multiplexed over a single WebSocket per dev miniapp:

 *   laptop β†’ phone : {type: "reload"}                 β†’ trigger WebView.reload()

 *   laptop β†’ phone : {type: "respawn-bg"}             β†’ restart the background JSContext

 *   phone  β†’ laptop: {type: "log", level, args, ...}  β†’ forwarded console calls

 *

 * Lifecycle: `connect(packageName, devUrl, devPort)` is called from

 * MiniappHost.mountDev once the dev applet is mounted. `disconnect(packageName)`

 * is called from MiniappHost.unmount. Reconnect with exponential backoff on

 * unexpected close β€” the dev server is the developer's laptop and may bounce.

 *

 * Outgoing logs are buffered in a small ring while disconnected; flushed on

 * reconnect. This catches early-startup logs the developer would otherwise

 * miss when re-launching the dev server.

 */

const LOG_TAG = "DEV_SERVER_BRIDGE"
const PROTOCOL_VERSION = "mentra-dev/1"
const HELLO_TIMEOUT_MS = 1_000
const BACKOFF_MIN_MS = 1_000
const BACKOFF_MAX_MS = 30_000
const RING_BUFFER_MAX_ENTRIES = 100
const RING_BUFFER_MAX_BYTES = 32 * 1024
/** A handler for a dev server signal. A promise holds the package's later signals until it settles. */
export type DevSignalHandler = (packageName: string) => void | Promise<void>

type State = "idle" | "connecting" | "connected" | "disconnected" | "closed"

interface BufferedLog {
  packageName: string
  level: string
  args: unknown[]
  timestamp: number
  /** "ui" = WebView, "background" = JSContext. Stamped at capture time. */
  source: "ui" | "background"
  size: number
}

interface BridgeEntry {
  state: State
  ws: WebSocket | null
  url: string
  attempts: number
  ringBuffer: BufferedLog[]
  ringBytes: number
  reloadHandler: ((packageName: string) => void) | null
  reconnectTimer: ReturnType<typeof setTimeout> | null
}

class DevServerBridge {
  private entries = new Map<string, BridgeEntry>()
  private globalReloadHandler: DevSignalHandler | null = null
  private globalRespawnBackgroundHandler: DevSignalHandler | null = null
  /** Each package's signals run in the order the dev server sent them, one at a time. */
  private signalQueues = new Map<string, Promise<void>>()

  /**

   * Register a global reload handler. MiniappHost calls this once at boot. The

   * bridge invokes the handler with the offending packageName whenever a

   * reload signal is received.

   */
  public onReload(handler: DevSignalHandler): void {
    this.globalReloadHandler = handler
  }

  /**

   * Register a global background-respawn handler. Fires when the dev

   * server sends `{type: "respawn-bg"}` β€” emitted on filesystem changes

   * under `src/background/`. The host (MentraJSRouter via the

   * bootstrap) should kill + respawn the JSContext to pick up the

   * change. WebView reload is separate (see `onReload`).

   */
  public onRespawnBackground(handler: DevSignalHandler | null): void {
    this.globalRespawnBackgroundHandler = handler
  }

  /** Clear the background-respawn handler when the miniapp engine is stopped. */
  public clearRespawnBackgroundHandler(): void {
    this.globalRespawnBackgroundHandler = null
  }

  /** Open (or re-open) a bridge to the given dev server. */
  public connect(packageName: string, devHostUrl: string, devPort: number): void {
    const url = this.buildWsUrl(devHostUrl, devPort)
    let entry = this.entries.get(packageName)
    if (entry) {
      // Already have an entry; if the URL changed (e.g. LAN IP shifted), close
      // and rebuild.
      if (entry.url === url && (entry.state === "connecting" || entry.state === "connected")) return
      this.teardownEntry(entry)
    }
    entry = {
      state: "idle",
      ws: null,
      url,
      attempts: 0,
      ringBuffer: [],
      ringBytes: 0,
      reloadHandler: null,
      reconnectTimer: null,
    }
    this.entries.set(packageName, entry)
    this.openSocket(packageName, entry)
  }

  /** Close a bridge for good. Called from MiniappHost.unmount. */
  public disconnect(packageName: string): void {
    const entry = this.entries.get(packageName)
    if (!entry) return
    entry.state = "closed"
    this.teardownEntry(entry)
    this.entries.delete(packageName)
  }

  /**

   * Forward a `log` envelope to the connected dev sidecar. Called from

   * the JSContext side (`MentraJSRouter.__log` handler) AND the WebView

   * side (`MentraUIRouter.routeFromWebView` for `type:"log"` frames).

   *

   * `source` distinguishes the two halves so the CLI can prefix lines

   * `[UI]` vs `[MentraJS]`. Logs are silently dropped when no bridge

   * exists for the package (no `mentra-miniapp dev` running) and

   * buffered in the per-bridge ring while disconnected.

   */
  public forwardLog(
    packageName: string,
    level: string,
    args: unknown[],
    timestamp: number,
    source: "ui" | "background",
  ): void {
    const entry = this.entries.get(packageName)
    if (!entry) return
    const message = JSON.stringify({type: "log", level, args, packageName, timestamp, source})
    if (entry.state === "connected" && entry.ws) {
      try {
        entry.ws.send(message)
        return
      } catch {
        // Fall through to buffer.
      }
    }
    this.bufferLog(entry, {packageName, level, args, timestamp, source, size: message.length})
  }

  // -----------------------------------------------------------------------

  /**

   * Run a signal after the package's earlier ones have settled. A `reload` that follows a `respawn-bg` (one save that

   * touched both layers) waits for the new background, so the reloaded screen doesn't start against the old one or one

   * being torn down, and two respawns never overlap. A handler's failure is logged and doesn't hold the queue.

   */
  private enqueueSignal(packageName: string, signal: string, run: () => void | Promise<void>): void {
    const previous = this.signalQueues.get(packageName) ?? Promise.resolve()
    const next = previous.then(async () => {
      try {
        await run()
      } catch (error) {
        console.warn(`${LOG_TAG}: ${packageName} ${signal} failed`, error)
      }
    })
    this.signalQueues.set(packageName, next)
    void next.then(() => {
      if (this.signalQueues.get(packageName) === next) this.signalQueues.delete(packageName)
    })
  }

  private buildWsUrl(devHostUrl: string, devPort: number): string {
    let host: string
    try {
      const parsed = new URL(devHostUrl)
      host = parsed.hostname
    } catch {
      // devHostUrl might already be just an IP; best-effort.
      host = devHostUrl.replace(/^https?:\/\//, "").split(":")[0].split("/")[0]
    }
    return `ws://${host}:${devPort}/__mentra_dev`
  }

  private openSocket(packageName: string, entry: BridgeEntry): void {
    if (entry.state === "closed") return
    entry.state = "connecting"
    const ws = new WebSocket(entry.url)
    entry.ws = ws

    let helloTimer: ReturnType<typeof setTimeout> | null = null
    let helloAcked = false

    const teardown = (reason: string): void => {
      if (helloTimer) {
        clearTimeout(helloTimer)
        helloTimer = null
      }
      try {
        ws.close()
      } catch {
        /* ignore */
      }
      if (entry.state === "closed") return
      entry.state = "disconnected"
      entry.ws = null
      entry.attempts++
      console.log(`${LOG_TAG}: ${packageName} disconnected (${reason}); reconnect in ${this.backoffMs(entry.attempts)}ms`)
      this.scheduleReconnect(packageName, entry)
    }

    ws.onopen = () => {
      // Send hello; wait for hello-ack to confirm we hit the right server.
      try {
        ws.send(JSON.stringify({type: "hello", protocol: PROTOCOL_VERSION}))
      } catch {
        teardown("hello send failed")
        return
      }
      helloTimer = setTimeout(() => {
        if (!helloAcked) {
          teardown("hello-ack timeout")
        }
      }, HELLO_TIMEOUT_MS)
    }

    ws.onmessage = (ev) => {
      const data = typeof ev.data === "string" ? ev.data : null
      if (!data) return
      let parsed: {type?: string; protocol?: string} | null = null
      try {
        parsed = JSON.parse(data)
      } catch {
        return
      }
      if (!parsed) return

      if (parsed.type === "hello-ack") {
        if (parsed.protocol !== PROTOCOL_VERSION) {
          teardown(`protocol mismatch: server sent ${parsed.protocol}, expected ${PROTOCOL_VERSION}`)
          return
        }
        helloAcked = true
        if (helloTimer) {
          clearTimeout(helloTimer)
          helloTimer = null
        }
        entry.state = "connected"
        entry.attempts = 0
        console.log(`${LOG_TAG}: ${packageName} connected to ${entry.url}`)
        this.flushRingBuffer(packageName, entry)
        return
      }

      if (parsed.type === "reload") {
        console.log(`${LOG_TAG}: ${packageName} received reload signal`)
        this.enqueueSignal(packageName, "reload", () => this.globalReloadHandler?.(packageName))
        return
      }

      // Two-layer dev signal: filesystem changes under src/background/
      // trigger a full JSContext kill + respawn (not just a WebView
      // reload). The host's MentraJSRouter listens here.
      if (parsed.type === "respawn-bg") {
        console.log(`${LOG_TAG}: ${packageName} received respawn-bg signal`)
        this.enqueueSignal(packageName, "respawn-bg", () => this.globalRespawnBackgroundHandler?.(packageName))
        return
      }
    }

    ws.onerror = () => {
      // onclose follows; defer all teardown to that path so we don't double-fire.
    }

    ws.onclose = () => {
      teardown(helloAcked ? "ws closed" : "ws closed before hello-ack")
    }
  }

  private scheduleReconnect(packageName: string, entry: BridgeEntry): void {
    if (entry.state === "closed") return
    if (entry.reconnectTimer) clearTimeout(entry.reconnectTimer)
    const delay = this.backoffMs(entry.attempts)
    entry.reconnectTimer = setTimeout(() => {
      entry.reconnectTimer = null
      // Verify still alive and still in the bridge map.
      const current = this.entries.get(packageName)
      if (!current || current !== entry || entry.state === "closed") return
      this.openSocket(packageName, entry)
    }, delay)
  }

  private backoffMs(attempts: number): number {
    const exp = Math.min(BACKOFF_MAX_MS, BACKOFF_MIN_MS * Math.pow(2, Math.max(0, attempts - 1)))
    const jitter = exp * (0.8 + Math.random() * 0.4)
    return Math.round(jitter)
  }

  private bufferLog(entry: BridgeEntry, log: BufferedLog): void {
    entry.ringBuffer.push(log)
    entry.ringBytes += log.size
    while (
      entry.ringBuffer.length > RING_BUFFER_MAX_ENTRIES ||
      entry.ringBytes > RING_BUFFER_MAX_BYTES
    ) {
      const dropped = entry.ringBuffer.shift()
      if (dropped) entry.ringBytes -= dropped.size
      if (entry.ringBuffer.length === 0) {
        entry.ringBytes = 0
        break
      }
    }
  }

  private flushRingBuffer(packageName: string, entry: BridgeEntry): void {
    if (entry.ringBuffer.length === 0) return
    const buffered = entry.ringBuffer
    entry.ringBuffer = []
    entry.ringBytes = 0
    if (!entry.ws) return
    for (const log of buffered) {
      try {
        entry.ws.send(
          JSON.stringify({
            type: "log",
            level: log.level,
            args: log.args,
            packageName: log.packageName,
            timestamp: log.timestamp,
            source: log.source,
          }),
        )
      } catch {
        // Re-buffer on failure and bail.
        entry.ringBuffer.unshift(log)
        entry.ringBytes += log.size
        return
      }
    }
  }

  private teardownEntry(entry: BridgeEntry): void {
    if (entry.reconnectTimer) {
      clearTimeout(entry.reconnectTimer)
      entry.reconnectTimer = null
    }
    if (entry.ws) {
      try {
        entry.ws.close()
      } catch {
        /* ignore */
      }
      entry.ws = null
    }
  }
}

const devServerBridge = new DevServerBridge()
export default devServerBridge