generated from MetaMask/metamask-module-template
-
Notifications
You must be signed in to change notification settings - Fork 5
feat(ocap-kernel): add IO kernel service for vat I/O streams #840
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 all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
453ff26
feat(ocap-kernel): add IO kernel service for vat I/O streams (#831)
FUDCo 06deef3
fix: guard all socket event handlers against stale socket refs
FUDCo 484d2dc
chore: remove obsolete eslint-disable comments
FUDCo ee05e0f
fix: roll back IO channels and subcluster on launch failure
FUDCo 7da3a23
fix: destroy IO channels after vat termination
FUDCo 56ebebb
fix: address remaining bugbot issues
FUDCo 2f3d77a
fix: scope IO service names by subcluster ID to prevent collisions
FUDCo c0d6609
fix: throw early when config declares IO but no factory is provided
FUDCo 5181c64
fix: use StringDecoder to handle multi-byte UTF-8 across TCP chunks
FUDCo a7e58db
fix: prevent cleanup errors from masking original failures
FUDCo cbe4883
fix: destroy IO channels on kernel reset, harden createChannels rollback
FUDCo 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
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 |
|---|---|---|
| @@ -0,0 +1,263 @@ | ||
| import { makeSQLKernelDatabase } from '@metamask/kernel-store/sqlite/nodejs'; | ||
| import { waitUntilQuiescent } from '@metamask/kernel-utils'; | ||
| import { Kernel } from '@metamask/ocap-kernel'; | ||
| import type { IOChannel, IOConfig } from '@metamask/ocap-kernel'; | ||
| import * as net from 'node:net'; | ||
| import * as os from 'node:os'; | ||
| import * as path from 'node:path'; | ||
| import { describe, it, expect, afterEach } from 'vitest'; | ||
|
|
||
| import { getBundleSpec, makeTestLogger } from './utils.ts'; | ||
|
|
||
| function tempSocketPath(): string { | ||
| return path.join( | ||
| os.tmpdir(), | ||
| `io-int-${Date.now()}-${Math.random().toString(36).slice(2)}.sock`, | ||
| ); | ||
| } | ||
|
|
||
| async function connectToSocket(socketPath: string): Promise<net.Socket> { | ||
| return new Promise((resolve, reject) => { | ||
| const client = net.createConnection(socketPath, () => { | ||
| client.removeListener('error', reject); | ||
| resolve(client); | ||
| }); | ||
| client.on('error', reject); | ||
| }); | ||
| } | ||
|
|
||
| async function writeLine(socket: net.Socket, line: string): Promise<void> { | ||
| return new Promise((resolve, reject) => { | ||
| socket.write(`${line}\n`, (error) => { | ||
| if (error) { | ||
| reject(error); | ||
| } else { | ||
| resolve(); | ||
| } | ||
| }); | ||
| }); | ||
| } | ||
|
|
||
| async function readLine(socket: net.Socket): Promise<string> { | ||
| return new Promise((resolve) => { | ||
| let buffer = ''; | ||
| const onData = (data: Buffer): void => { | ||
| buffer += data.toString(); | ||
| const idx = buffer.indexOf('\n'); | ||
| if (idx !== -1) { | ||
| socket.removeListener('data', onData); | ||
| resolve(buffer.slice(0, idx)); | ||
| } | ||
| }; | ||
| socket.on('data', onData); | ||
| }); | ||
| } | ||
|
|
||
| async function makeTestSocketChannel( | ||
| _name: string, | ||
| socketPath: string, | ||
| ): Promise<IOChannel> { | ||
| const fsPromises = await import('node:fs/promises'); | ||
| const lineQueue: string[] = []; | ||
| const readerQueue: { resolve: (value: string | null) => void }[] = []; | ||
| let currentSocket: net.Socket | null = null; | ||
| let lineBuffer = ''; | ||
| let closed = false; | ||
|
|
||
| function deliverLine(line: string): void { | ||
| const reader = readerQueue.shift(); | ||
| if (reader) { | ||
| reader.resolve(line); | ||
| } else { | ||
| lineQueue.push(line); | ||
| } | ||
| } | ||
|
|
||
| function deliverEOF(): void { | ||
| while (readerQueue.length > 0) { | ||
| readerQueue.shift()?.resolve(null); | ||
| } | ||
| } | ||
|
|
||
| const server = net.createServer((socket) => { | ||
| if (currentSocket) { | ||
| socket.destroy(); | ||
| return; | ||
| } | ||
| currentSocket = socket; | ||
| lineBuffer = ''; | ||
| socket.on('data', (data: Buffer) => { | ||
| lineBuffer += data.toString(); | ||
| let idx = lineBuffer.indexOf('\n'); | ||
| while (idx !== -1) { | ||
| deliverLine(lineBuffer.slice(0, idx)); | ||
| lineBuffer = lineBuffer.slice(idx + 1); | ||
| idx = lineBuffer.indexOf('\n'); | ||
| } | ||
| }); | ||
| socket.on('end', () => { | ||
| if (lineBuffer.length > 0) { | ||
| deliverLine(lineBuffer); | ||
| lineBuffer = ''; | ||
| } | ||
| currentSocket = null; | ||
| deliverEOF(); | ||
| }); | ||
| socket.on('error', () => { | ||
| currentSocket = null; | ||
| deliverEOF(); | ||
| }); | ||
| }); | ||
|
|
||
| try { | ||
| await fsPromises.unlink(socketPath); | ||
| } catch { | ||
| // ignore | ||
| } | ||
|
|
||
| await new Promise<void>((resolve, reject) => { | ||
| server.on('error', reject); | ||
| server.listen(socketPath, () => { | ||
| server.removeListener('error', reject); | ||
| resolve(); | ||
| }); | ||
| }); | ||
|
|
||
| return { | ||
| async read() { | ||
| if (closed) { | ||
| return null; | ||
| } | ||
| const queued = lineQueue.shift(); | ||
| if (queued !== undefined) { | ||
| return queued; | ||
| } | ||
| if (!currentSocket) { | ||
| return null; | ||
| } | ||
| return new Promise<string | null>((resolve) => { | ||
| readerQueue.push({ resolve }); | ||
| }); | ||
| }, | ||
| async write(data: string) { | ||
| if (!currentSocket) { | ||
| throw new Error('no connected client'); | ||
| } | ||
| const socket = currentSocket; | ||
| return new Promise<void>((resolve, reject) => { | ||
| socket.write(`${data}\n`, (error) => { | ||
| if (error) { | ||
| reject(error); | ||
| } else { | ||
| resolve(); | ||
| } | ||
| }); | ||
| }); | ||
| }, | ||
| async close() { | ||
| if (closed) { | ||
| return; | ||
| } | ||
| closed = true; | ||
| deliverEOF(); | ||
| currentSocket?.destroy(); | ||
| currentSocket = null; | ||
| await new Promise<void>((resolve) => { | ||
| server.close(() => resolve()); | ||
| }); | ||
| try { | ||
| await fsPromises.unlink(socketPath); | ||
| } catch { | ||
| // ignore | ||
| } | ||
| }, | ||
| }; | ||
| } | ||
|
|
||
| describe('IO kernel service', () => { | ||
| const clients: net.Socket[] = []; | ||
|
|
||
| afterEach(async () => { | ||
| for (const client of clients) { | ||
| client.destroy(); | ||
| } | ||
| clients.length = 0; | ||
| }); | ||
|
|
||
| it('reads and writes through an IO channel', async () => { | ||
| const socketPath = tempSocketPath(); | ||
| const kernelDatabase = await makeSQLKernelDatabase({ | ||
| dbFilename: ':memory:', | ||
| }); | ||
| const { logger } = makeTestLogger(); | ||
|
|
||
| const { NodejsPlatformServices } = await import('@ocap/nodejs'); | ||
| const kernel = await Kernel.make( | ||
| new NodejsPlatformServices({ | ||
| logger: logger.subLogger({ tags: ['platform'] }), | ||
| }), | ||
| kernelDatabase, | ||
| { | ||
| resetStorage: true, | ||
| logger, | ||
| ioChannelFactory: async (name: string, config: IOConfig) => { | ||
| if (config.type !== 'socket') { | ||
| throw new Error(`unsupported: ${config.type}`); | ||
| } | ||
| return makeTestSocketChannel(name, config.path); | ||
| }, | ||
| }, | ||
| ); | ||
|
|
||
| const config = { | ||
| bootstrap: 'io', | ||
| forceReset: true, | ||
| io: { | ||
| repl: { | ||
| type: 'socket' as const, | ||
| path: socketPath, | ||
| }, | ||
| }, | ||
| services: ['repl'], | ||
| vats: { | ||
| io: { | ||
| bundleSpec: getBundleSpec('io-vat'), | ||
| parameters: { name: 'io' }, | ||
| }, | ||
| }, | ||
| }; | ||
|
|
||
| const { rootKref } = await kernel.launchSubcluster(config); | ||
| await waitUntilQuiescent(); | ||
|
|
||
| // Connect to the socket | ||
| const client = await connectToSocket(socketPath); | ||
| clients.push(client); | ||
|
|
||
| // Small delay for connection setup | ||
| await new Promise((resolve) => setTimeout(resolve, 20)); | ||
|
|
||
| // Send a line from the test to the vat | ||
| await writeLine(client, 'hello from test'); | ||
|
|
||
| // Trigger the vat to read and verify it received the data | ||
| await kernel.queueMessage(rootKref, 'doRead', []); | ||
| await waitUntilQuiescent(100); | ||
|
|
||
| const bufferResult = await kernel.queueMessage( | ||
| rootKref, | ||
| 'getReadBuffer', | ||
| [], | ||
| ); | ||
| await waitUntilQuiescent(100); | ||
| expect(bufferResult.body).toContain('hello from test'); | ||
|
|
||
| // Trigger the vat to write | ||
| const linePromise = readLine(client); | ||
| await kernel.queueMessage(rootKref, 'doWrite', ['hello from vat']); | ||
| await waitUntilQuiescent(100); | ||
|
|
||
| const received = await linePromise; | ||
| expect(received).toBe('hello from vat'); | ||
| }); | ||
| }); | ||
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.