Skip to content

Commit

Permalink
Merge pull request #356 from nautobot/u/smk4664-fix-database-connecti…
Browse files Browse the repository at this point in the history
…on-issues-socket-mode

Replace sync_to_async with database_sync_to_async
  • Loading branch information
smk4664 authored Dec 20, 2024
2 parents a279e4f + cec8d22 commit a5a5cd3
Show file tree
Hide file tree
Showing 5 changed files with 30 additions and 8 deletions.
1 change: 1 addition & 0 deletions NOTICE
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Some parts of Nautobot-App-Chatops are based upon `channels`, licensed under BSD-3-Clause by Django Software Foundation.
1 change: 1 addition & 0 deletions changes/355.fixed
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed "Server has gone away" error in Slack Socket Mode.
9 changes: 4 additions & 5 deletions nautobot_chatops/sockets/slack.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,14 @@
import json
import shlex

from asgiref.sync import sync_to_async
from django.conf import settings
from slack_sdk.socket_mode.aiohttp import SocketModeClient
from slack_sdk.socket_mode.request import SocketModeRequest
from slack_sdk.socket_mode.response import SocketModeResponse
from slack_sdk.web.async_client import AsyncWebClient

from nautobot_chatops.dispatchers.slack import SlackDispatcher
from nautobot_chatops.utils import socket_check_and_enqueue_command
from nautobot_chatops.utils import database_sync_to_async, socket_check_and_enqueue_command
from nautobot_chatops.workers import commands_help, get_commands_registry, parse_command_string


Expand Down Expand Up @@ -72,7 +71,7 @@ async def process_slash_command(client, req):
client.logger.error("%s", err)
return

registry = await sync_to_async(get_commands_registry)()
registry = await database_sync_to_async(get_commands_registry)()

if command not in registry:
SlackDispatcher(context).send_markdown(commands_help(prefix=SLASH_PREFIX))
Expand Down Expand Up @@ -211,7 +210,7 @@ async def process_interactive(client, req):

client.logger.info(f"command: {command}, subcommand: {subcommand}, params: {params}")

registry = await sync_to_async(get_commands_registry)()
registry = await database_sync_to_async(get_commands_registry)()

if command not in registry:
SlackDispatcher(context).send_markdown(commands_help(prefix=SLASH_PREFIX))
Expand Down Expand Up @@ -242,7 +241,7 @@ async def process_mention(client, req):
client.logger.error("%s", err)
return

registry = await sync_to_async(get_commands_registry)()
registry = await database_sync_to_async(get_commands_registry)()

if command not in registry:
SlackDispatcher(context).send_markdown(commands_help(prefix=SLASH_PREFIX))
Expand Down
25 changes: 23 additions & 2 deletions nautobot_chatops/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@
import sys
from datetime import datetime, timezone

from asgiref.sync import sync_to_async
from asgiref.sync import SyncToAsync
from django.conf import settings
from django.db import close_old_connections
from django.db.models import Q
from django.http import HttpResponse, JsonResponse
from nautobot.core.celery import nautobot_task
Expand All @@ -18,6 +19,26 @@
logger = logging.getLogger(__name__)


class DatabaseSyncToAsync(SyncToAsync):
"""
SyncToAsync version that cleans up old database connections when it exits.
Sourced from Channels, see NOTICE file for license information.
"""

def thread_handler(self, loop, *args, **kwargs):
"""Run the handler in a thread, closing old database connections before and after."""
close_old_connections()
try:
return super().thread_handler(loop, *args, **kwargs)
finally:
close_old_connections()


# The class is TitleCased, but we want to encourage use as a callable/decorator
database_sync_to_async = DatabaseSyncToAsync # pylint: disable=invalid-name


def get_app_config_part(prefix: str) -> dict:
"""Get part of the app config.
Expand Down Expand Up @@ -113,7 +134,7 @@ def create_command_log(dispatcher, registry, command, subcommand, params=()):
)


@sync_to_async
@database_sync_to_async
def socket_check_and_enqueue_command(*args, **kwargs):
"""Calls check_and_enqueue_command() when in Socket mode."""
return check_and_enqueue_command(*args, **kwargs)
Expand Down
2 changes: 1 addition & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit a5a5cd3

Please sign in to comment.