|
| 1 | +import { Controller } from "../index" |
| 2 | +import { Empty } from "@shared/proto/common" |
| 3 | +import { EmptyRequest } from "@shared/proto/common" |
| 4 | +import { StreamingResponseHandler, getRequestRegistry } from "../grpc-handler" |
| 5 | + |
| 6 | +// Keep track of active chatButtonClicked subscriptions by controller ID |
| 7 | +const activeChatButtonClickedSubscriptions = new Map<string, StreamingResponseHandler>() |
| 8 | + |
| 9 | +/** |
| 10 | + * Subscribe to chatButtonClicked events |
| 11 | + * @param controller The controller instance |
| 12 | + * @param request The empty request |
| 13 | + * @param responseStream The streaming response handler |
| 14 | + * @param requestId The ID of the request (passed by the gRPC handler) |
| 15 | + */ |
| 16 | +export async function subscribeToChatButtonClicked( |
| 17 | + controller: Controller, |
| 18 | + request: EmptyRequest, |
| 19 | + responseStream: StreamingResponseHandler, |
| 20 | + requestId?: string, |
| 21 | +): Promise<void> { |
| 22 | + const controllerId = controller.id |
| 23 | + console.log(`[DEBUG] set up chatButtonClicked subscription for controller ${controllerId}`) |
| 24 | + |
| 25 | + // Add this subscription to the active subscriptions with the controller ID |
| 26 | + activeChatButtonClickedSubscriptions.set(controllerId, responseStream) |
| 27 | + |
| 28 | + // Register cleanup when the connection is closed |
| 29 | + const cleanup = () => { |
| 30 | + activeChatButtonClickedSubscriptions.delete(controllerId) |
| 31 | + } |
| 32 | + |
| 33 | + // Register the cleanup function with the request registry if we have a requestId |
| 34 | + if (requestId) { |
| 35 | + getRequestRegistry().registerRequest(requestId, cleanup, { type: "chatButtonClicked_subscription" }, responseStream) |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +/** |
| 40 | + * Send a chatButtonClicked event to a specific controller's subscription |
| 41 | + * @param controllerId The ID of the controller to send the event to |
| 42 | + */ |
| 43 | +export async function sendChatButtonClickedEvent(controllerId: string): Promise<void> { |
| 44 | + // Get the subscription for this specific controller |
| 45 | + const responseStream = activeChatButtonClickedSubscriptions.get(controllerId) |
| 46 | + |
| 47 | + if (!responseStream) { |
| 48 | + console.log(`[DEBUG] No active subscription for controller ${controllerId}`) |
| 49 | + return |
| 50 | + } |
| 51 | + |
| 52 | + try { |
| 53 | + const event: Empty = {} |
| 54 | + await responseStream( |
| 55 | + event, |
| 56 | + false, // Not the last message |
| 57 | + ) |
| 58 | + } catch (error) { |
| 59 | + console.error(`Error sending chatButtonClicked event to controller ${controllerId}:`, error) |
| 60 | + // Remove the subscription if there was an error |
| 61 | + activeChatButtonClickedSubscriptions.delete(controllerId) |
| 62 | + } |
| 63 | +} |
0 commit comments