-
Notifications
You must be signed in to change notification settings - Fork 1
feat: headless API for external UI control #336
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
myleshorton
wants to merge
5
commits into
main
Choose a base branch
from
adam/headless-proxy-api
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
1fe81d4
feat: add headless API for external UI control of WASM proxy
myleshorton 5f9d739
docs: add headless API documentation to README
myleshorton c5a5863
fix: address PR review comments on headless API
myleshorton 9d6508f
fix: use const assertion for Connection.state type in test
myleshorton 2c1d04b
fix: address PR review comments (round 2)
myleshorton File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| import {readyEmitter, sharingEmitter, connectionsEmitter, averageThroughputEmitter, lifetimeConnectionsEmitter, lifetimeChunksEmitter, WasmInterface} from './utils/wasmInterface' | ||
|
|
||
| // Mock WasmInterface before importing headlessApi | ||
| jest.mock('./utils/wasmInterface', () => { | ||
| const {StateEmitter} = jest.requireActual('./hooks/useStateEmitter') | ||
| const readyEmitter = new StateEmitter(false) | ||
| const sharingEmitter = new StateEmitter(false) | ||
| const connectionsEmitter = new StateEmitter([]) | ||
| const averageThroughputEmitter = new StateEmitter(0) | ||
| const lifetimeConnectionsEmitter = new StateEmitter(0) | ||
| const lifetimeChunksEmitter = new StateEmitter([]) | ||
|
|
||
| const mockInstance = {} | ||
|
|
||
| class MockWasmInterface { | ||
| initialize = jest.fn().mockResolvedValue(mockInstance) | ||
| start = jest.fn() | ||
| stop = jest.fn() | ||
| ready = false | ||
| initializing = false | ||
| connectionMap = {} | ||
| throughput = {bytesPerSec: 0} | ||
| connections = [] | ||
| } | ||
|
|
||
| return { | ||
| WasmInterface: MockWasmInterface, | ||
| readyEmitter, | ||
| sharingEmitter, | ||
| connectionsEmitter, | ||
| averageThroughputEmitter, | ||
| lifetimeConnectionsEmitter, | ||
| lifetimeChunksEmitter, | ||
| } | ||
| }) | ||
|
|
||
| // Import after mock is set up | ||
| import {LanternProxy} from './headlessApi' | ||
|
|
||
| beforeEach(() => { | ||
| // Reset emitter state between tests | ||
| readyEmitter.update(false) | ||
| sharingEmitter.update(false) | ||
| connectionsEmitter.update([]) | ||
| averageThroughputEmitter.update(0) | ||
| lifetimeConnectionsEmitter.update(0) | ||
| lifetimeChunksEmitter.update([]) | ||
| }) | ||
|
|
||
| describe('LanternProxy.on / off', () => { | ||
| test('on() delivers emitter updates to subscribers', () => { | ||
| const cb = jest.fn() | ||
| LanternProxy.on('ready', cb) | ||
| readyEmitter.update(true) | ||
| expect(cb).toHaveBeenCalledWith(true) | ||
| }) | ||
|
|
||
| test('on() returns an unsubscribe function', () => { | ||
| const cb = jest.fn() | ||
| const unsub = LanternProxy.on('throughput', cb) | ||
| averageThroughputEmitter.update(100) | ||
| expect(cb).toHaveBeenCalledTimes(1) | ||
|
|
||
| unsub() | ||
| averageThroughputEmitter.update(200) | ||
| expect(cb).toHaveBeenCalledTimes(1) // no new calls | ||
| }) | ||
|
|
||
| test('off() removes a specific callback', () => { | ||
| const cb1 = jest.fn() | ||
| const cb2 = jest.fn() | ||
| LanternProxy.on('sharing', cb1) | ||
| LanternProxy.on('sharing', cb2) | ||
|
|
||
| LanternProxy.off('sharing', cb1) | ||
| sharingEmitter.update(true) | ||
|
|
||
| expect(cb1).not.toHaveBeenCalled() | ||
| expect(cb2).toHaveBeenCalledWith(true) | ||
| }) | ||
|
|
||
| test('multiple event types work independently', () => { | ||
| const readyCb = jest.fn() | ||
| const connCb = jest.fn() | ||
| LanternProxy.on('ready', readyCb) | ||
| LanternProxy.on('connections', connCb) | ||
|
|
||
| readyEmitter.update(true) | ||
| expect(readyCb).toHaveBeenCalledWith(true) | ||
| expect(connCb).not.toHaveBeenCalled() | ||
|
|
||
| const conns = [{state: 1, workerIdx: 0, addr: '1.2.3.4'}] | ||
| connectionsEmitter.update(conns) | ||
| expect(connCb).toHaveBeenCalledWith(conns) | ||
| }) | ||
| }) | ||
|
|
||
| describe('LanternProxy.getState', () => { | ||
| test('returns current emitter state', () => { | ||
| readyEmitter.update(true) | ||
| sharingEmitter.update(true) | ||
| averageThroughputEmitter.update(500) | ||
| lifetimeConnectionsEmitter.update(42) | ||
|
|
||
| const state = LanternProxy.getState() | ||
| expect(state.ready).toBe(true) | ||
| expect(state.sharing).toBe(true) | ||
| expect(state.throughput).toBe(500) | ||
| expect(state.lifetimeConnections).toBe(42) | ||
| }) | ||
|
|
||
| test('returns shallow copies of arrays', () => { | ||
| const conns = [{state: 1, workerIdx: 0, addr: '1.2.3.4'}] | ||
| connectionsEmitter.update(conns) | ||
|
|
||
| const state = LanternProxy.getState() | ||
| expect(state.connections).toEqual(conns) | ||
| expect(state.connections).not.toBe(conns) // different reference | ||
| }) | ||
| }) | ||
|
|
||
| describe('LanternProxy.init', () => { | ||
| test('concurrent calls return the same promise', () => { | ||
| const p1 = LanternProxy.init() | ||
| const p2 = LanternProxy.init() | ||
| expect(p1).toBe(p2) | ||
| }) | ||
| }) | ||
|
|
||
| describe('window.LanternProxy', () => { | ||
| test('is exposed globally', () => { | ||
| expect((window as any).LanternProxy).toBe(LanternProxy) | ||
| }) | ||
|
|
||
| test('is not writable', () => { | ||
| expect(() => { | ||
| (window as any).LanternProxy = 'overwrite' | ||
| }).toThrow() | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,141 @@ | ||
| /** | ||
| * Headless API for controlling the unbounded WASM proxy without rendering any UI. | ||
| * | ||
| * Usage (as a module or after the deferred script has loaded): | ||
| * <browsers-unbounded data-headless="true"></browsers-unbounded> | ||
| * <script defer src="https://embed.lantern.io/static/js/main.js"></script> | ||
| * <script type="module"> | ||
| * const proxy = window.LanternProxy; | ||
| * // Subscribe to events BEFORE calling init() to avoid missing them | ||
| * proxy.on('ready', (isReady) => { | ||
| * if (isReady) proxy.start(); | ||
| * }); | ||
| * proxy.on('connections', (conns) => console.log(conns)); | ||
| * proxy.on('throughput', (bps) => console.log(bps)); | ||
| * await proxy.init(); | ||
| * </script> | ||
| */ | ||
|
|
||
| import {WasmInterface, connectionsEmitter, averageThroughputEmitter, lifetimeConnectionsEmitter, lifetimeChunksEmitter, readyEmitter, sharingEmitter, type Connection, type Chunk} from './utils/wasmInterface' | ||
| import {Targets, WASM_CLIENT_CONFIG} from './constants' | ||
|
|
||
| export type ProxyEvent = 'ready' | 'sharing' | 'connections' | 'throughput' | 'lifetimeConnections' | 'chunks' | ||
|
|
||
| export interface ProxyState { | ||
| ready: boolean | ||
| sharing: boolean | ||
| connections: Connection[] | ||
| throughput: number | ||
| lifetimeConnections: number | ||
| chunks: Chunk[] | ||
| } | ||
|
|
||
| type EventCallback<T = unknown> = (value: T) => void | ||
|
|
||
| const listeners = new Map<string, Set<EventCallback>>() | ||
|
|
||
| function emitToListeners(event: string, value: unknown) { | ||
| const set = listeners.get(event) | ||
| if (set) set.forEach(cb => cb(value)) | ||
| } | ||
|
|
||
| // Wire up emitters to forward to external listeners | ||
| function wireEmitters() { | ||
| readyEmitter.on((v) => emitToListeners('ready', v)) | ||
| sharingEmitter.on((v) => emitToListeners('sharing', v)) | ||
| connectionsEmitter.on((v) => emitToListeners('connections', v)) | ||
| averageThroughputEmitter.on((v) => emitToListeners('throughput', v)) | ||
| lifetimeConnectionsEmitter.on((v) => emitToListeners('lifetimeConnections', v)) | ||
| lifetimeChunksEmitter.on((v) => emitToListeners('chunks', v)) | ||
| } | ||
|
|
||
| let wasmInterface: WasmInterface | null = null | ||
| let initialized = false | ||
| let initPromise: Promise<void> | null = null | ||
|
|
||
| export const LanternProxy = { | ||
| /** | ||
| * Initialize the WASM proxy. Must be called before start(). | ||
| * Safe to call concurrently — subsequent calls return the same promise. | ||
| * @param options.mock - Use mock client for testing (default: false) | ||
| */ | ||
| init(options?: { mock?: boolean }): Promise<void> { | ||
| if (initialized) { | ||
| return Promise.resolve() | ||
| } | ||
| if (initPromise) { | ||
| return initPromise | ||
| } | ||
| initPromise = (async () => { | ||
| const mock = options?.mock ?? false | ||
| wasmInterface = new WasmInterface() | ||
| const instance = await wasmInterface.initialize({mock, target: Targets.WEB}) | ||
| if (!instance) { | ||
| initPromise = null | ||
| throw new Error('WASM proxy failed to initialize') | ||
| } | ||
| initialized = true | ||
| })() | ||
| return initPromise | ||
| }, | ||
|
|
||
| /** Start proxying traffic (fire-and-forget). Must call init() first. */ | ||
| start(): void { | ||
| if (!initialized || !wasmInterface) throw new Error('LanternProxy not initialized — call and await init() first') | ||
| wasmInterface.start() | ||
| }, | ||
|
|
||
| /** Stop proxying traffic (fire-and-forget). Must call init() first. */ | ||
| stop(): void { | ||
| if (!initialized || !wasmInterface) throw new Error('LanternProxy not initialized — call and await init() first') | ||
| wasmInterface.stop() | ||
| }, | ||
|
|
||
| /** Subscribe to a proxy event. Returns an unsubscribe function. */ | ||
| on<T = unknown>(event: ProxyEvent, callback: EventCallback<T>): () => void { | ||
| if (!listeners.has(event)) listeners.set(event, new Set()) | ||
| const set = listeners.get(event)! | ||
| set.add(callback as EventCallback) | ||
| return () => set.delete(callback as EventCallback) | ||
| }, | ||
|
|
||
| /** Unsubscribe from a proxy event. */ | ||
| off(event: ProxyEvent, callback: EventCallback): void { | ||
| listeners.get(event)?.delete(callback) | ||
| }, | ||
|
|
||
| /** Get a snapshot of the current proxy state. Arrays are shallow-copied. */ | ||
| getState(): ProxyState { | ||
| return { | ||
| ready: readyEmitter.state, | ||
| sharing: sharingEmitter.state, | ||
| connections: [...connectionsEmitter.state], | ||
| throughput: averageThroughputEmitter.state, | ||
| lifetimeConnections: lifetimeConnectionsEmitter.state, | ||
| chunks: [...lifetimeChunksEmitter.state], | ||
| } | ||
| }, | ||
|
|
||
| /** Whether init() has been called successfully. */ | ||
| get initialized(): boolean { | ||
| return initialized | ||
| }, | ||
|
|
||
| /** The WASM client config (discovery server, egress, etc). Read-only. */ | ||
| get config() { | ||
| return {...WASM_CLIENT_CONFIG} | ||
| }, | ||
| } | ||
|
|
||
| // Wire emitters immediately so subscriptions work before init() | ||
| wireEmitters() | ||
|
|
||
| // Expose globally — use defineProperty to prevent accidental overwrites | ||
| if (!(window as any).LanternProxy) { | ||
| Object.defineProperty(window, 'LanternProxy', { | ||
| value: LanternProxy, | ||
| writable: false, | ||
| enumerable: false, | ||
| configurable: false, | ||
| }) | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.