-
Notifications
You must be signed in to change notification settings - Fork 8
feat: self-hosted socket mode entrypoint for Deno workflow apps #85
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
Draft
vegeris
wants to merge
3
commits into
main
Choose a base branch
from
evegeris-self-hosted-rosi-socket-mode
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,211 @@ | ||
| import { | ||
| ConsoleLogger, | ||
| getManifest, | ||
| getProtocolInterface, | ||
| type Logger, | ||
| LogLevel, | ||
| Protocol, | ||
| SocketModeClient, | ||
| } from "./deps.ts"; | ||
| import { getCommandline } from "./local-run.ts"; | ||
| import type { InvocationPayload } from "./types.ts"; | ||
|
|
||
| export interface SocketModeRunOptions { | ||
| appToken: string; | ||
| logger?: Logger; | ||
| logLevel?: LogLevel; | ||
| slackApiUrl?: string; | ||
| } | ||
|
|
||
| /** | ||
| * @description Runs a Slack workflow app in Socket Mode by establishing a WebSocket connection to Slack. | ||
| */ | ||
| export const runWithSocketMode = async function ( | ||
| create: typeof getManifest, | ||
| hookCLI: Protocol, | ||
| options: SocketModeRunOptions, | ||
| ): Promise<void> { | ||
| const { appToken, logLevel = LogLevel.INFO, slackApiUrl } = options; | ||
|
|
||
| // Set up logger | ||
| const logger = options.logger ?? (() => { | ||
| const defaultLogger = new ConsoleLogger(); | ||
| defaultLogger.setLevel(logLevel); | ||
| return defaultLogger; | ||
| })(); | ||
|
|
||
| // Load the manifest to get function definitions | ||
| const workingDirectory = Deno.cwd(); | ||
| const manifest = await create(workingDirectory); | ||
|
|
||
| if (!manifest.functions) { | ||
| logger.error( | ||
| `No function definitions found in the manifest`, | ||
| ); | ||
| throw new Error( | ||
| `No function definitions found in the manifest`, | ||
| ); | ||
| } | ||
|
|
||
| const devDomain = slackApiUrl ? new URL(slackApiUrl).hostname : ""; | ||
| let denoExecutablePath = "deno"; | ||
| try { | ||
| denoExecutablePath = Deno.execPath(); | ||
| } catch (e) { | ||
| logger.warn("Could not get Deno executable path, using 'deno'", e); | ||
| } | ||
| // Run the function in a subprocess with restricted permissions | ||
| const subprocessCommand = getCommandline( | ||
| Deno.mainModule, | ||
| manifest, | ||
| devDomain, | ||
| hookCLI, | ||
| ); | ||
|
|
||
| const clientOptions = slackApiUrl ? { slackApiUrl } : undefined; | ||
| const client = new SocketModeClient({ | ||
| appToken, | ||
| logLevel, | ||
| logger, | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The local run script uses the 'hook CLI protocol' for logging, but since it's not applicable here we just use the Logger that the socket mode client accepts |
||
| clientOptions, | ||
| }); | ||
|
|
||
| // Listen for incoming events | ||
| client.on("slack_event", async ({ body, ack, retry_num, retry_reason }) => { | ||
| logger.debug("Received event:", JSON.stringify(body, null, 2)); | ||
| try { | ||
| // deno-lint-ignore no-explicit-any | ||
| const payload: InvocationPayload<any> = { | ||
| body, | ||
| context: { | ||
| bot_access_token: body.event.bot_access_token, | ||
| team_id: body.team_id, | ||
| variables: Deno.env.toObject(), | ||
| }, | ||
| }; | ||
|
|
||
| // Add retry information if present | ||
| if (retry_num !== undefined && retry_num > 0) { | ||
| logger.warn( | ||
| `Retrying event (attempt ${retry_num})${ | ||
| retry_reason ? `: ${retry_reason}` : "" | ||
| }`, | ||
| ); | ||
| } | ||
|
|
||
| // Run the function in a subprocess with the same --allow-net restriction as local-run.ts (manifest.outgoing_domains) | ||
| const commander = new Deno.Command(denoExecutablePath, { | ||
| args: subprocessCommand, | ||
| stdin: "piped", | ||
| stdout: "piped", | ||
| stderr: "piped", | ||
| cwd: workingDirectory, | ||
| }); | ||
| const subprocess = commander.spawn(); | ||
| const payloadJson = JSON.stringify(payload); | ||
| const writer = subprocess.stdin.getWriter(); | ||
| await writer.write(new TextEncoder().encode(payloadJson)); | ||
| await writer.close(); | ||
|
|
||
| const output = await subprocess.output(); | ||
| const stdout = new TextDecoder().decode(output.stdout).trim(); | ||
| const stderr = new TextDecoder().decode(output.stderr); | ||
|
|
||
| if (!output.success) { | ||
| logger.error( | ||
| `Function subprocess failed (exit code ${output.code}). stderr: ${ | ||
| stderr || "(none)" | ||
| }`, | ||
| ); | ||
| await ack(); | ||
| return; | ||
| } | ||
|
|
||
| if (stdout) { | ||
| logger.info(`Function response: ${stdout}`); | ||
| } | ||
|
|
||
| await ack({}); | ||
| logger.debug("Event processed and acknowledged"); | ||
| } catch (error) { | ||
| logger.error("Error processing event:", error); | ||
| await ack(); | ||
| } | ||
| }); | ||
|
|
||
| // Handle connection lifecycle events | ||
| client.on("connected", () => { | ||
| logger.info("✅ Connected to Slack via Socket Mode"); | ||
| }); | ||
|
|
||
| client.on("disconnected", () => { | ||
| logger.warn("⚠️ Disconnected from Slack"); | ||
| }); | ||
|
|
||
| client.on("reconnecting", () => { | ||
| logger.info("🔄 Reconnecting to Slack..."); | ||
| }); | ||
|
|
||
| client.on("error", (error: Error) => { | ||
| logger.error("❌ Socket Mode error:", error); | ||
| }); | ||
|
|
||
| // Start the Socket Mode connection | ||
| logger.info("🚀 Starting Socket Mode client..."); | ||
| try { | ||
| await client.start(); | ||
| } catch (error) { | ||
| logger.error("Failed to start Socket Mode client:", error); | ||
| throw error; | ||
| } | ||
| logger.info("⚡️ Socket Mode runtime is running and listening for events"); | ||
|
|
||
| // Keep the process running | ||
| // In Deno, we can use Deno.addSignalListener to handle graceful shutdown | ||
| const handleShutdown = async (signal: string) => { | ||
| logger.info(`Received ${signal}, shutting down gracefully...`); | ||
| try { | ||
| await client.disconnect(); | ||
| logger.info("Disconnected from Slack"); | ||
| Deno.exit(0); | ||
| } catch (error) { | ||
| logger.error("Error during shutdown:", error); | ||
| Deno.exit(1); | ||
| } | ||
| }; | ||
|
|
||
| Deno.addSignalListener("SIGINT", () => handleShutdown("SIGINT")); | ||
| Deno.addSignalListener("SIGTERM", () => handleShutdown("SIGTERM")); | ||
| }; | ||
|
|
||
| if (import.meta.main) { | ||
| const appToken = Deno.env.get("SLACK_APP_TOKEN"); | ||
| if (!appToken) { | ||
| console.error( | ||
| "Error: SLACK_APP_TOKEN environment variable is required for Socket Mode", | ||
| ); | ||
| Deno.exit(1); | ||
| } | ||
|
|
||
| const logLevelStr = Deno.env.get("SLACK_LOG_LEVEL") || "INFO"; | ||
| const logLevel = LogLevel[logLevelStr as keyof typeof LogLevel] || | ||
| LogLevel.INFO; | ||
|
|
||
| const slackApiUrl = Deno.env.get("SLACK_API_URL"); | ||
|
|
||
| const hookCLI = getProtocolInterface(Deno.args); | ||
|
|
||
| try { | ||
| await runWithSocketMode( | ||
| getManifest, | ||
| hookCLI, | ||
| { | ||
| appToken, | ||
| logLevel, | ||
| slackApiUrl, | ||
| }, | ||
| ); | ||
| } catch { | ||
| Deno.exit(1); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't know why CLI-managed socket mode does not already require this permission to be set :not-sure:
The 'self hosted' script executes functions the same way as the 'local run' script; we run
local-run-function.tsas a subprocess, which dispatches function execution torun-function.ts, which should ultimately callfunctions.completeSuccessorfunctions.completeFailureusing BaseSlackAPIClient. As per Cursor:BaseSlackAPIClient uses Node’s os.release(), which in Deno is implemented with Deno.osRelease() and requires --allow-sys=osReleaseThe local run
starthook does run it with that permission, but the flags for the parent process don't get passed into the subprocess :confused_math_lady:deno run -q --config=deno.jsonc --allow-read --allow-net --allow-run --allow-env --allow-sys=osRelease https://deno.land/x/deno_slack_runtime@1.1.3/local-run.ts