-
Notifications
You must be signed in to change notification settings - Fork 0
feat(runtime): complete ADR-002 bridge migration to BridgeProtocol #153
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
Merged
Merged
Changes from 1 commit
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
e00e532
feat(runtime): complete ADR-002 bridge migration to BridgeProtocol
bbopen 90a1c16
fix: remove getBridgeInfo references from examples and type tests
bbopen 5f71dff
fix(node): add cwd to PYTHONPATH for module resolution
bbopen 2dc24d9
fix: address CodeRabbit review feedback
bbopen 90f99f0
feat: add minWorkers and onWorkerReady for pool pre-spawning and per-…
bbopen edb82c0
fix(worker-pool): crash recovery and race condition fixes (#155, #157)
bbopen 4faccc5
fix(ci): add pyarrow to codec-suite ML requirements
bbopen 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
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
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 |
|---|---|---|
| @@ -1,149 +1,86 @@ | ||
| /** | ||
| * HTTP runtime bridge | ||
| * HTTP runtime bridge for BridgeProtocol. | ||
| * | ||
| * HttpBridge extends BridgeProtocol and uses HttpIO transport for | ||
| * stateless HTTP POST-based communication with a Python server. | ||
| * | ||
| * @see https://github.com/bbopen/tywrap/issues/149 | ||
| */ | ||
|
|
||
| import { decodeValueAsync } from '../utils/codec.js'; | ||
| import { BridgeProtocol, type BridgeProtocolOptions } from './bridge-protocol.js'; | ||
| import { HttpIO, type HttpIOOptions } from './http-io.js'; | ||
| import type { CodecOptions } from './safe-codec.js'; | ||
|
|
||
| import { BoundedContext } from './bounded-context.js'; | ||
| import { BridgeExecutionError, BridgeTimeoutError } from './errors.js'; | ||
| // ============================================================================= | ||
| // OPTIONS | ||
| // ============================================================================= | ||
|
|
||
| /** | ||
| * Configuration options for HttpBridge. | ||
| */ | ||
| export interface HttpBridgeOptions { | ||
| /** Base URL for the Python server (e.g., 'http://localhost:8000') */ | ||
| baseURL: string; | ||
| headers?: Record<string, string>; | ||
| timeoutMs?: number; | ||
| } | ||
|
|
||
| interface HttpCallPayload { | ||
| module: string; | ||
| functionName: string; | ||
| args: unknown[]; | ||
| kwargs?: Record<string, unknown>; | ||
| } | ||
|
|
||
| interface HttpInstantiatePayload { | ||
| module: string; | ||
| className: string; | ||
| args: unknown[]; | ||
| kwargs?: Record<string, unknown>; | ||
| } | ||
| /** Additional headers to include in each request */ | ||
| headers?: Record<string, string>; | ||
|
|
||
| interface HttpCallMethodPayload { | ||
| handle: string; | ||
| methodName: string; | ||
| args: unknown[]; | ||
| kwargs?: Record<string, unknown>; | ||
| } | ||
| /** Timeout in ms for requests. Default: 30000 (30 seconds) */ | ||
| timeoutMs?: number; | ||
|
|
||
| interface HttpDisposePayload { | ||
| handle: string; | ||
| /** Codec options for validation/serialization */ | ||
| codec?: CodecOptions; | ||
| } | ||
|
|
||
| export class HttpBridge extends BoundedContext { | ||
| private readonly baseURL: string; | ||
| private readonly headers: Record<string, string>; | ||
| private readonly timeoutMs: number; | ||
|
|
||
| constructor(options: HttpBridgeOptions = { baseURL: 'http://localhost:8000' }) { | ||
| super(); | ||
| this.baseURL = options.baseURL.replace(/\/$/, ''); | ||
| this.headers = { 'content-type': 'application/json', ...(options.headers ?? {}) }; | ||
| this.timeoutMs = options.timeoutMs ?? 30000; | ||
| } | ||
|
|
||
| /** | ||
| * HttpBridge is stateless, so init is a no-op. | ||
| */ | ||
| protected async doInit(): Promise<void> { | ||
| // Stateless - no initialization required | ||
| } | ||
| // ============================================================================= | ||
| // HTTP BRIDGE | ||
| // ============================================================================= | ||
|
|
||
| /** | ||
| * HTTP-based runtime bridge for executing Python code. | ||
| * | ||
| * HttpBridge provides a stateless HTTP transport for communication with | ||
| * a Python server. Each request is independent - no connection state is | ||
| * maintained between calls. | ||
| * | ||
| * Features: | ||
| * - Stateless HTTP POST communication | ||
| * - Timeout handling via AbortController | ||
| * - Full SafeCodec validation (NaN/Infinity rejection, key validation) | ||
| * - Automatic Arrow decoding for DataFrames/ndarrays | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * const bridge = new HttpBridge({ baseURL: 'http://localhost:8000' }); | ||
| * await bridge.init(); | ||
| * | ||
| * const result = await bridge.call('math', 'sqrt', [16]); | ||
| * console.log(result); // 4.0 | ||
| * | ||
| * await bridge.dispose(); | ||
| * ``` | ||
| */ | ||
| export class HttpBridge extends BridgeProtocol { | ||
| /** | ||
| * HttpBridge is stateless, so dispose is a no-op. | ||
| * Create a new HttpBridge instance. | ||
| * | ||
| * @param options - Configuration options for the bridge | ||
| */ | ||
| protected async doDispose(): Promise<void> { | ||
| // Stateless - no cleanup required | ||
| } | ||
|
|
||
| async call<T = unknown>( | ||
| module: string, | ||
| functionName: string, | ||
| args: unknown[], | ||
| kwargs?: Record<string, unknown> | ||
| ): Promise<T> { | ||
| const payload: HttpCallPayload = { module, functionName, args, kwargs }; | ||
| const res = await this.post(`${this.baseURL}/call`, payload); | ||
| return (await decodeValueAsync(res)) as T; | ||
| } | ||
|
|
||
| async instantiate<T = unknown>( | ||
| module: string, | ||
| className: string, | ||
| args: unknown[], | ||
| kwargs?: Record<string, unknown> | ||
| ): Promise<T> { | ||
| const payload: HttpInstantiatePayload = { module, className, args, kwargs }; | ||
| const res = await this.post(`${this.baseURL}/instantiate`, payload); | ||
| return (await decodeValueAsync(res)) as T; | ||
| } | ||
|
|
||
| async callMethod<T = unknown>( | ||
| handle: string, | ||
| methodName: string, | ||
| args: unknown[], | ||
| kwargs?: Record<string, unknown> | ||
| ): Promise<T> { | ||
| const payload: HttpCallMethodPayload = { handle, methodName, args, kwargs }; | ||
| const res = await this.post(`${this.baseURL}/call_method`, payload); | ||
| return (await decodeValueAsync(res)) as T; | ||
| } | ||
|
|
||
| async disposeInstance(handle: string): Promise<void> { | ||
| const payload: HttpDisposePayload = { handle }; | ||
| await this.post(`${this.baseURL}/dispose_instance`, payload); | ||
| } | ||
|
|
||
| private async post(url: string, body: unknown): Promise<unknown> { | ||
| const controller = typeof AbortController !== 'undefined' ? new AbortController() : undefined; | ||
| const timer = controller ? setTimeout(() => controller.abort(), this.timeoutMs) : undefined; | ||
| try { | ||
| const resp = await fetch(url, { | ||
| method: 'POST', | ||
| headers: this.headers, | ||
| body: JSON.stringify(body), | ||
| signal: controller?.signal, | ||
| }); | ||
| if (!resp.ok) { | ||
| const text = await safeText(resp); | ||
| throw new BridgeExecutionError(`HTTP ${resp.status}: ${text || resp.statusText}`); | ||
| } | ||
| const ct = resp.headers.get('content-type') ?? ''; | ||
| if (ct.includes('application/json')) { | ||
| return (await resp.json()) as unknown; | ||
| } | ||
| const text = await resp.text(); | ||
| try { | ||
| return JSON.parse(text) as unknown; | ||
| } catch { | ||
| return text as unknown; | ||
| } | ||
| } catch (error) { | ||
| // Handle abort/timeout errors | ||
| if (error instanceof Error && error.name === 'AbortError') { | ||
| throw new BridgeTimeoutError(`Request timed out after ${this.timeoutMs}ms`); | ||
| } | ||
| throw error; | ||
| } finally { | ||
| if (timer) { | ||
| clearTimeout(timer); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| async function safeText(resp: Response): Promise<string> { | ||
| try { | ||
| return await resp.text(); | ||
| } catch { | ||
| return ''; | ||
| constructor(options: HttpBridgeOptions) { | ||
| // Create HTTP transport | ||
| const transport = new HttpIO({ | ||
| baseURL: options.baseURL, | ||
| headers: options.headers, | ||
| defaultTimeoutMs: options.timeoutMs, | ||
| }); | ||
|
|
||
| // Initialize BridgeProtocol with transport and codec options | ||
| const protocolOptions: BridgeProtocolOptions = { | ||
| transport, | ||
| codec: options.codec, | ||
| defaultTimeoutMs: options.timeoutMs, | ||
| }; | ||
|
|
||
| super(protocolOptions); | ||
| } | ||
| } | ||
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.