Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
5 changes: 5 additions & 0 deletions .changeset/slack-socket-ack-rejection.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@chat-adapter/slack": patch
---

Stop a failed Socket Mode `ack()` from crashing the process. When an event arrived while the socket was closing or reconnecting, `ack()` rejected with `slack_socket_mode_no_reply_received_error`. `SocketModeClient` doesn't await its `slack_event` listeners, so the rejection went unhandled and Node exited, for example in the middle of a graceful shutdown. The adapter now logs `Error handling socket mode event` instead, and Slack redelivers the unacknowledged event. This covers both `mode: "socket"` and `startSocketModeListener()`.
78 changes: 78 additions & 0 deletions packages/adapter-slack/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12821,6 +12821,35 @@ describe("socket mode - routeSocketEvent", () => {
{ type: "hello" }
);
});

it("logs instead of rejecting when ack fails", async () => {
const { chatInstance, slackEventHandler } = await createSocketAdapter();
const error = new Error(
"Failed to send a WebSocket message as the client is not ready"
);

await expect(
slackEventHandler({
ack: vi.fn().mockRejectedValue(error),
type: "events_api",
body: {
event: {
type: "message",
channel: "C123",
ts: "1234567890.123456",
text: "hello from socket",
user: "U_USER",
},
},
})
).resolves.toBeUndefined();

expect(mockLogger.error).toHaveBeenCalledWith(
"Error handling socket mode event",
{ type: "events_api", error }
);
expect(chatInstance).not.toHaveDispatched("processMessage");
});
});

describe("socket mode - disconnect", () => {
Expand Down Expand Up @@ -13231,6 +13260,55 @@ describe("startSocketModeListener", () => {
expect(response.status).toBe(500);
expect(await response.text()).toContain("waitUntil");
});

it("logs instead of rejecting when ack fails", async () => {
mockSocketOn.mockClear();
const adapter = createSlackAdapter({
botToken: "xoxb-test-token",
signingSecret: secret,
appToken: "xapp-test-token",
logger: mockLogger,
});
const abortController = new AbortController();
const waitUntil = vi.fn();
await adapter.startSocketModeListener(
{ waitUntil },
1000,
abortController.signal,
"https://example.com/api/webhooks/slack"
);
await vi.waitFor(() => {
expect(mockSocketOn).toHaveBeenCalledWith(
"slack_event",
expect.any(Function)
);
});
const slackEventHandler = mockSocketOn.mock.calls.find(
(call: unknown[]) => call[0] === "slack_event"
)?.[1] as (args: {
ack: () => Promise<void>;
body: Record<string, unknown>;
type: string;
}) => Promise<void>;
const error = new Error(
"Failed to send a WebSocket message as the client is not ready"
);

await expect(
slackEventHandler({
ack: vi.fn().mockRejectedValue(error),
type: "events_api",
body: {},
})
).resolves.toBeUndefined();

expect(mockLogger.error).toHaveBeenCalledWith(
"Error handling socket mode event",
{ type: "events_api", error }
);
abortController.abort();
await waitUntil.mock.calls[0]?.[0];
});
});

describe("routeSocketEvent with options", () => {
Expand Down
70 changes: 46 additions & 24 deletions packages/adapter-slack/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2806,12 +2806,14 @@ export class SlackAdapter implements Adapter<SlackThreadId, unknown> {
});
}

await this.routeSocketEvent(
body as Record<string, unknown>,
type as string,
ack,
undefined,
retry_num
await this.handleSocketEventSafely(type as string, () =>
this.routeSocketEvent(
body as Record<string, unknown>,
type as string,
ack,
undefined,
retry_num
)
);
}
);
Expand Down Expand Up @@ -3045,24 +3047,26 @@ export class SlackAdapter implements Adapter<SlackThreadId, unknown> {
}

const eventType = type as string;
if (webhookUrl) {
await ack();
await this.forwardSocketEvent(webhookUrl, {
type: "socket_event",
eventType,
body: body as Record<string, unknown>,
retryNum: retry_num,
timestamp: Date.now(),
});
} else {
await this.routeSocketEvent(
body as Record<string, unknown>,
eventType,
ack,
options,
retry_num
);
}
await this.handleSocketEventSafely(eventType, async () => {
if (webhookUrl) {
await ack();
await this.forwardSocketEvent(webhookUrl, {
type: "socket_event",
eventType,
body: body as Record<string, unknown>,
retryNum: retry_num,
timestamp: Date.now(),
});
} else {
await this.routeSocketEvent(
body as Record<string, unknown>,
eventType,
ack,
options,
retry_num
);
}
});
}
);

Expand Down Expand Up @@ -3144,6 +3148,24 @@ export class SlackAdapter implements Adapter<SlackThreadId, unknown> {
}
}

/**
* Run a `slack_event` listener's work, logging a failure instead of throwing.
* SocketModeClient doesn't await its listeners, so a rejection would be an
* unhandled rejection, which terminates Node. The usual cause is `ack()`
* rejecting while the socket is closing or reconnecting; Slack redelivers
* the unacknowledged event, so it isn't lost.
*/
private async handleSocketEventSafely(
type: string,
handle: () => Promise<void>
): Promise<void> {
try {
await handle();
} catch (error) {
this.logger.error("Error handling socket mode event", { type, error });
}
}

/**
* Disconnect the socket mode client.
* No-op if not connected.
Expand Down