Skip to content
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

make json-rpc server id handling spec-compliant #807

Merged
merged 3 commits into from
Aug 26, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 25 additions & 11 deletions packages/chopsticks/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const httpLogger = defaultLogger.child({ name: 'http' })
const wsLogger = defaultLogger.child({ name: 'ws' })

const singleRequest = z.object({
id: z.number(),
id: z.optional(z.union([z.number().int(), z.string(), z.null()])),
ermalkaleci marked this conversation as resolved.
Show resolved Hide resolved
jsonrpc: z.literal('2.0'),
method: z.string(),
params: z.array(z.any()).default([]),
Expand Down Expand Up @@ -91,6 +91,22 @@ export const createServer = async (handler: Handler, port: number) => {
},
}

const safeHandleRequest = async (request: z.infer<typeof singleRequest>) => {
try {
const result = handler(request, emptySubscriptionManager)
return request.id === undefined ? undefined : { id: request.id, jsonrpc: '2.0', result }
} catch (err: any) {
return {
jsonrpc: '2.0',
id: request.id,
error: {
code: -32603,
message: err.message,
},
}
}
}

const server = http.createServer(async (req, res) => {
if (req.method === 'OPTIONS') {
return respond(res)
Expand All @@ -112,25 +128,23 @@ export const createServer = async (handler: Handler, port: number) => {

let response: any
if (Array.isArray(parsed.data)) {
response = await Promise.all(
parsed.data.map((req) => {
const result = handler(req, emptySubscriptionManager)
return { id: req.id, jsonrpc: '2.0', result }
}),
)
response = await Promise.all(parsed.data.map(safeHandleRequest))
response = response.filter((r) => r !== undefined)
} else {
const result = await handler(parsed.data, emptySubscriptionManager)
response = { id: parsed.data.id, jsonrpc: '2.0', result }
response = await safeHandleRequest(parsed.data)
}

respond(res, JSON.stringify(response))
if (response !== undefined) {
respond(res, JSON.stringify(response))
}
} catch (err: any) {
respond(
res,
JSON.stringify({
jsonrpc: '2.0',
id: 1,
id: null,
error: {
code: -32700,
message: err.message,
},
}),
Expand Down