返回 CodeWhale
rpc.test.mjs
根目录 / crates / tui / extension-host / test / rpc.test.mjs
1 // The RPC peer's host-to-core requests: cancellation by AbortSignal.
2 import { test } from 'node:test'
3 import assert from 'node:assert/strict'
4 import { ErrorCode } from '../dist/protocol.mjs'
5 import { RpcError, RpcPeer } from '../dist/rpc.mjs'
6
7 function peer() {
8 const sent = []
9 const rpc = new RpcPeer((message) => sent.push(message), 'plugin')
10 return { rpc, sent }
11 }
12
13 test('an aborted request sends $/cancel for its id and rejects as cancelled at once', async () => {
14 const { rpc, sent } = peer()
15 const controller = new AbortController()
16 const request = rpc.request('registry/unregister', { owner: { plugin_id: 'p', generation: 1, owner_token: 't' }, handle: 1 }, controller.signal)
17 const id = sent[0].id
18 assert.equal(sent.length, 1)
19 controller.abort()
20 await assert.rejects(request, (error) => error instanceof RpcError && error.code === ErrorCode.Cancelled)
21 assert.deepEqual(sent[1], { jsonrpc: '2.0', method: '$/cancel', params: { id } })
22 // The answer that arrives anyway is dropped: nothing waits for it and nothing throws.
23 rpc.handle({ jsonrpc: '2.0', id, result: {} })
24 // A second abort is a no-op.
25 controller.abort()
26 assert.equal(sent.length, 2)
27 })
28
29 test('an already-aborted signal sends nothing, and an answered request is never cancelled afterwards', async () => {
30 const { rpc, sent } = peer()
31 const aborted = AbortSignal.abort()
32 await assert.rejects(rpc.request('registry/unregister', { owner: { plugin_id: 'p', generation: 1, owner_token: 't' }, handle: 1 }, aborted), (error) => error.code === ErrorCode.Cancelled)
33 assert.equal(sent.length, 0)
34
35 const controller = new AbortController()
36 const request = rpc.request('registry/unregister', { owner: { plugin_id: 'p', generation: 1, owner_token: 't' }, handle: 2 }, controller.signal)
37 rpc.handle({ jsonrpc: '2.0', id: sent[0].id, result: {} })
38 assert.deepEqual(await request, {})
39 controller.abort()
40 assert.equal(sent.length, 1, 'no $/cancel for a request that was already answered')
41 })
42
42 lines Plain Text