import type { HandlerResponse, JsonRpcHandler, } from '../../lib/json-rpc-router.js'; import type { JsonRpcId, JsonRpcResponse } from '@enbox/dwn-clients'; import { DwnServerErrorCode } from '../../dwn-error.js'; import { createJsonRpcErrorResponse, createJsonRpcSuccessResponse, JsonRpcErrorCodes } from '@enbox/dwn-clients'; /** * Closes a subscription tied to a specific `SocketConnection`. * * @param jsonRpcRequest must include JsonRpcId of the subscription request within a `subscription object`. * @param context must include the associated `SocketConnection`. * */ export const handleSubscriptionsClose: JsonRpcHandler = async ( jsonRpcRequest, context, ) => { const requestId = jsonRpcRequest.id ?? crypto.randomUUID(); if (context.socketConnection === undefined) { const jsonRpcResponse = createJsonRpcErrorResponse(requestId, JsonRpcErrorCodes.InvalidRequest, 'socket connection does not exist'); return { jsonRpcResponse }; } if (jsonRpcRequest.subscription === undefined) { const jsonRpcResponse = createJsonRpcErrorResponse(requestId, JsonRpcErrorCodes.InvalidRequest, 'subscribe options do not exist'); return { jsonRpcResponse }; } const { socketConnection } = context; const { id } = jsonRpcRequest.subscription as { id: JsonRpcId }; let jsonRpcResponse:JsonRpcResponse; try { // closing the subscription and cleaning up the reference within the given connection. await socketConnection.closeSubscription(id); jsonRpcResponse = createJsonRpcSuccessResponse(requestId, { reply: { status: 200, detail: 'Accepted' } }); } catch (error) { if (error.code === DwnServerErrorCode.ConnectionSubscriptionJsonRpcIdNotFound) { jsonRpcResponse = createJsonRpcErrorResponse(requestId, JsonRpcErrorCodes.InvalidParams, `subscription ${id} does not exist.`); } else { jsonRpcResponse = createJsonRpcErrorResponse( requestId, JsonRpcErrorCodes.InternalError, `unknown subscription close error for ${id}: ${error.message}` ); } } return { jsonRpcResponse } as HandlerResponse; };