Skip to content

ASGI lifecycle events #187

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

Merged
merged 27 commits into from
Nov 14, 2023
Merged

Conversation

tonybaloney
Copy link
Contributor

@tonybaloney tonybaloney commented Jul 18, 2023

This PR calls the lifecycle event for startup and shutdown for an ASGI application provided by the new V2 wrapper.

This FastAPI application:

import fastapi
import logging

logger = logging.getLogger("azure.functions.AsgiMiddleware")

app = fastapi.FastAPI()

@app.get("/")
def index():
    logger.warning("Running primary route.")

    return {"message": "Hello, world?"}

@app.on_event("startup")
async def startup_event():
    print("Starting up...")
    logger.warning("Starting up ASGI app...")

@app.on_event("shutdown")
async def shutdown_event():
    print("Shutting down...")
    logger.warning("Shutting down ASGI app...")

And this function_app.py code:

import azure.functions as func
from fastapi_app import app as fa

app = func.AsgiFunctionApp(app=fa, http_auth_level=func.AuthLevel.ANONYMOUS)

Will run the startup and shutdown events for the Functions worker process.
screenshot 2023-07-18 at 14 33 38

@tonybaloney
Copy link
Contributor Author

Equivalent demo with quart

from quart import Quart

app = Quart(__name__)

@app.route('/')
async def hello():
    return 'hello'


@app.before_serving
async def create_db_pool():
    print("running quart startup 1")

@app.before_serving
async def use_g():
    print("Run quart startup 2")

@app.while_serving
async def lifespan():
    print("Initial startup")
    yield
    print("Shutting down quart")

@app.after_serving
async def create_db_pool():
    print("running quart shutdown 1")

@codecov
Copy link

codecov bot commented Jul 25, 2023

Codecov Report

Attention: 17 lines in your changes are missing coverage. Please review.

Comparison is base (b42035a) 93.35% compared to head (f083cf8) 92.97%.

Files Patch % Lines
azure/functions/_http_asgi.py 83.87% 3 Missing and 7 partials ⚠️
azure/functions/decorators/function_app.py 41.66% 6 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##              dev     #187      +/-   ##
==========================================
- Coverage   93.35%   92.97%   -0.39%     
==========================================
  Files          56       56              
  Lines        3116     3187      +71     
  Branches      633      649      +16     
==========================================
+ Hits         2909     2963      +54     
- Misses        128      137       +9     
- Partials       79       87       +8     
Flag Coverage Δ
unittests 92.94% <77.02%> (-0.39%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@tonybaloney tonybaloney changed the title [WIP] ASGI lifecycle events ASGI lifecycle events Jul 25, 2023
@tonybaloney
Copy link
Contributor Author

screenshot 2023-07-25 at 13 30 30 If a startup event fails, it will capture the error in the logs, fail the request and retry on the next request. The exception is not reported to the HTTP result from the initiating request.


def __del__(self):
if self.startup_task_done:
asyncio.run(self.middleware.notify_shutdown())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

curious why for shutdown, we dont raise runtimeerror if shutdown does not succeed (similar to startup)?

@gavin-aguiar gavin-aguiar merged commit ac4cbe3 into Azure:dev Nov 14, 2023
@tonybaloney tonybaloney deleted the asgi_startup_lifecycles branch November 14, 2023 20:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants