Skip to content

Commit

Permalink
Merge pull request #10 from PerfectThymeTech/marvinbuss/restructure_app
Browse files Browse the repository at this point in the history
Restructure core app
  • Loading branch information
marvinbuss authored Aug 28, 2024
2 parents 752e48d + fc7f46c commit 3d0fee2
Show file tree
Hide file tree
Showing 6 changed files with 71 additions and 49 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/webapp.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Function App Deployment
name: Web App Deployment
on:
push:
branches:
Expand Down
58 changes: 13 additions & 45 deletions code/backend/app.py
Original file line number Diff line number Diff line change
@@ -1,70 +1,38 @@
import sys
import traceback
from datetime import datetime

from aiohttp import web
from aiohttp.web import Request, Response
from botbuilder.core import TurnContext
from botbuilder.core.integration import aiohttp_error_middleware
from botbuilder.integration.aiohttp import (
CloudAdapter,
ConfigurationBotFrameworkAuthentication,
)
from botbuilder.schema import Activity, ActivityTypes
from bots.assistant import AssistantBot
from bots.assistant_bot import AssistantBot
from bots.utils_bot import BotUtils
from core.config import settings as CONFIG
from utils import enable_logging

# Enable logging
enable_logging()

# Create adapter.
# See https://aka.ms/about-bot-adapter to learn more about how bots work.
# Create cloud adapter
ADAPTER = CloudAdapter(ConfigurationBotFrameworkAuthentication(CONFIG))
ADAPTER.on_turn_error = BotUtils.on_error


# Catch-all for errors.
async def on_error(context: TurnContext, error: Exception):
# This check writes out errors to console log .vs. app insights.
# NOTE: In production environment, you should consider logging this to Azure
# application insights.
print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
traceback.print_exc()

# Send a message to the user
await context.send_activity("The bot encountered an error or bug.")
await context.send_activity(
"To continue to run this bot, please fix the bot source code."
)
# Send a trace activity if we're talking to the Bot Framework Emulator
if context.activity.channel_id == "emulator":
# Create a trace activity that contains the error object
trace_activity = Activity(
label="TurnError",
name="on_turn_error Trace",
timestamp=datetime.now(datetime.UTC),
type=ActivityTypes.trace,
value=f"{error}",
value_type="https://www.botframework.com/schemas/error",
)
# Send a trace activity, which will be displayed in Bot Framework Emulator
await context.send_activity(trace_activity)


ADAPTER.on_turn_error = on_error

# Create the Bot
# Create bot
BOT = AssistantBot()

# Create app
APP = web.Application(middlewares=[aiohttp_error_middleware])


# Listen for incoming requests on /api/messages
async def messages(req: Request) -> Response:
return await ADAPTER.process(req, BOT)


APP = web.Application(middlewares=[aiohttp_error_middleware])
# Add route to app
APP.router.add_post("/api/messages", messages)

# Enable logging
enable_logging()


if __name__ == "__main__":
try:
web.run_app(APP, host="localhost", port=CONFIG.PORT)
Expand Down
File renamed without changes.
40 changes: 40 additions & 0 deletions code/backend/bots/utils_bot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
from datetime import datetime

from botbuilder.core import TurnContext
from botbuilder.schema import Activity, ActivityTypes
from utils import get_logger

logger = get_logger(__name__)


class BotUtils:

@staticmethod
async def on_error(turn_context: TurnContext, error: Exception) -> None:
"""Handles errors in the bot.
turn_context (TurnContext): The turn context.
error (Exception): The exception in the bot framework.
RETURNS (None): No return value.
"""
# Log error
logger.error("Unexpected error within the application", error)

# Send a message to the user
await turn_context.send_activity(
"The bot encountered an error or bug. The team will get notified and look into the issue. Sorry for any inconveniences caused."
)

# For the Bot Framework emulator channel send a trace activity
if turn_context.activity.channel_id == "emulator":
# Create a trace activity that contains the error object
trace_activity = Activity(
label="TurnError",
name="on_turn_error Trace",
timestamp=datetime.now(datetime.UTC),
type=ActivityTypes.trace,
value=f"{error}",
value_type="https://www.botframework.com/schemas/error",
)
# Send a trace activity, which will be displayed in Bot Framework Emulator
await turn_context.send_activity(trace_activity)
18 changes: 16 additions & 2 deletions code/backend/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@
from opentelemetry.sdk.resources import Resource


def enable_logging():
def enable_logging() -> None:
"""Initializes the logging via open telemetry for the bot framework.
RETURNS (None): No return value.
"""
# Configure base logger
log_level = logging.DEBUG if settings.DEBUG else settings.LOGGING_LEVEL
logging.basicConfig(format="%(asctime)s:%(levelname)s:%(message)s", level=log_level)
Expand Down Expand Up @@ -43,6 +47,11 @@ def enable_logging():


def get_logger(name: str) -> logging.Logger:
"""Creates and returns a logger instance with the configured logging level that is connected to the open telemetry exporter.
name (str): Child name of the logger.
RETURNS (Logger): Returns a logger instance to capture logs.
"""
# Init logger
logger = logging.getLogger(f"{settings.PROJECT_NAME}.{name}")

Expand All @@ -54,7 +63,12 @@ def get_logger(name: str) -> logging.Logger:


def get_tracer(name: str) -> trace.Tracer:
"""Creates and returns a tracer instance with the configured logging level that is connected to the open telemetry exporter.
name (str): Child name of the tracer.
RETURNS (Tracer): Returns a tracer instance to capture traces.
"""
# Init tracer
tracer = trace.get_tracer(name)
tracer = trace.get_tracer(f"{settings.PROJECT_NAME}.{name}")

return tracer
2 changes: 1 addition & 1 deletion code/infra/terraform.tf
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ terraform {
}
time = {
source = "hashicorp/time"
version = "0.9.1"
version = "0.12.0"
}
local = {
source = "hashicorp/local"
Expand Down

0 comments on commit 3d0fee2

Please sign in to comment.