Skip to content

🎨 catalog: lifespan managers for fastapi apps #7483

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 29 commits into from
Apr 8, 2025

Conversation

pcrespov
Copy link
Member

@pcrespov pcrespov commented Apr 7, 2025

What do these changes do?

FastAPI has deprecated the on_startup and on_shutdown events in favor of the lifespan events contexts. This PR introduces a postgres_lifespan: LifespanManager as a demonstration of how app_lifespan can coordinate multiple independent lifespan managers within a single FastAPI application.

The initial focus is on standardizing the lifespan for a PostgreSQL database. Using postgres_lifespan centralizes the setup and teardown logic for PostgreSQL, allowing it to be shared across all microservices. The catalog service already incorporates postgres_lifespan into its own application lifespan. This should be used as example to extend to other micro-services

The example below corresponds to the output of test_app_lifespan_composition It shows how nested lifespans can be composed so that state flows cleanly from parent to child. It also demonstrates the order of execution during startup/shutdown and how errors affect that flow.

-> postgres_sync_engine starting ...
       -> postgres_async_engine starting ...
               -> app database starting ...
                        -> rabbitmq starting ...
                                -> app rpc-server starting ...
                                <- app rpc-server done (<1ms)
                        <- rabbitmq done (<1ms)
                <- app database done (1ms)
        <- postgres_async_engine done (1ms)
<- postgres_sync_engine done (1ms)

Future work will extend this approach to additional FastAPI apps and later to aiohttp-based services, enabling consistent and modular resource management across the stack.

  • ⚠️ Note: When FastAPI(..., lifespan=app_lifespan) is used, the on_startup and on_shutdown events are not triggered.
  • Recommended order for setting up a FastAPI application:
    1. Define the lifespan by composing the necessary modules.
    2. Create the app instance: app = FastAPI(lifespan=events.lifecycle)
    3. Add middlewares: app.add_middleware(...)
    4. Register routes: app.include_router(...)
    5. Set up exception handlers: app.add_exception_handler(...)
  • The app's lifecycle is managed by the web server via the ASGI protocol, which standardizes communication between async Python apps and servers.

Related issue/s

How to test

cd packages/service-library
make "install-dev[fastapi]"
pytest -vv tests/test_*lifespan*.py

Dev-ops

None

@pcrespov pcrespov self-assigned this Apr 7, 2025
@pcrespov pcrespov added the a:services-library issues on packages/service-libs label Apr 7, 2025
Copy link

codecov bot commented Apr 7, 2025

Codecov Report

Attention: Patch coverage is 90.51095% with 13 lines in your changes missing coverage. Please review.

Project coverage is 87.47%. Comparing base (e162382) to head (0ccb681).
Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #7483      +/-   ##
==========================================
+ Coverage   87.41%   87.47%   +0.06%     
==========================================
  Files        1740     1734       -6     
  Lines       67273    67132     -141     
  Branches     1140     1142       +2     
==========================================
- Hits        58806    58724      -82     
+ Misses       8146     8087      -59     
  Partials      321      321              
Flag Coverage Δ
integrationtests 65.16% <100.00%> (+0.02%) ⬆️
unittests 86.65% <90.51%> (+0.05%) ⬆️
Components Coverage Δ
api ∅ <ø> (∅)
pkg_aws_library 93.91% <ø> (ø)
pkg_dask_task_models_library 97.09% <ø> (ø)
pkg_models_library 91.94% <ø> (ø)
pkg_notifications_library 85.26% <ø> (ø)
pkg_postgres_database 88.18% <ø> (ø)
pkg_service_integration 70.03% <ø> (ø)
pkg_service_library 72.78% <72.91%> (+0.54%) ⬆️
pkg_settings_library 90.78% <ø> (ø)
pkg_simcore_sdk 85.40% <ø> (ø)
agent 96.46% <ø> (ø)
api_server 90.02% <ø> (ø)
autoscaling 96.08% <ø> (ø)
catalog 91.92% <100.00%> (+0.09%) ⬆️
clusters_keeper 99.24% <ø> (ø)
dask_sidecar 91.29% <ø> (ø)
datcore_adapter 98.12% <ø> (ø)
director 76.78% <ø> (ø)
director_v2 91.30% <100.00%> (ø)
dynamic_scheduler 97.35% <ø> (ø)
dynamic_sidecar 90.11% <ø> (ø)
efs_guardian 89.79% <ø> (ø)
invitations 93.28% <ø> (ø)
payments 92.66% <ø> (ø)
resource_usage_tracker 89.12% <ø> (-0.11%) ⬇️
storage 87.72% <ø> (+0.07%) ⬆️
webclient ∅ <ø> (∅)
webserver 85.91% <ø> (-0.04%) ⬇️

Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update e162382...0ccb681. Read the comment docs.

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@pcrespov pcrespov force-pushed the mai/common-lifespans branch from 36d20c7 to 2a56df1 Compare April 7, 2025 15:29
@pcrespov pcrespov changed the title 🎨 WIP: Mai/common lifespans 🎨 lifespan managers for fastapi apps Apr 7, 2025
@pcrespov pcrespov added the t:maintenance Some planned maintenance work label Apr 7, 2025
@pcrespov pcrespov added this to the Pauwel Kwak milestone Apr 7, 2025
@pcrespov pcrespov changed the title 🎨 lifespan managers for fastapi apps 🎨 catalog: lifespan managers for fastapi apps Apr 7, 2025
@pcrespov pcrespov marked this pull request as ready for review April 7, 2025 17:53
@pcrespov pcrespov requested review from sanderegg and GitHK as code owners April 7, 2025 17:53
Copy link
Member

@sanderegg sanderegg left a comment

Choose a reason for hiding this comment

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

Thanks, this looks very promising!
A few questions here and there.

Copy link
Contributor

@GitHK GitHK left a comment

Choose a reason for hiding this comment

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

Please consider my naming change issue. I'd like to keep things aligned accross. I have the pattern I mentioned in my comment already in place in two services and I would like to avoid having different styles.

@pcrespov pcrespov requested a review from GitHK April 8, 2025 09:03
Copy link
Collaborator

@matusdrobuliak66 matusdrobuliak66 left a comment

Choose a reason for hiding this comment

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

👍

Copy link
Contributor

@GitHK GitHK left a comment

Choose a reason for hiding this comment

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

As discussed OK with the changes. Just let's alright the naming. I'd like to avoid having it mixed, which is even more confusing

@pcrespov pcrespov force-pushed the mai/common-lifespans branch from a9ecdce to c81269f Compare April 8, 2025 13:39
@pcrespov pcrespov enabled auto-merge (squash) April 8, 2025 13:40
pcrespov added 20 commits April 8, 2025 16:29
…stgres integration and cleanup old connection logic
…to events module and updating related handlers
@pcrespov pcrespov force-pushed the mai/common-lifespans branch from c81269f to 1fd7453 Compare April 8, 2025 14:29
Copy link

sonarqubecloud bot commented Apr 8, 2025

@pcrespov pcrespov merged commit 927caed into ITISFoundation:master Apr 8, 2025
94 checks passed
@pcrespov pcrespov deleted the mai/common-lifespans branch April 8, 2025 15:54
@matusdrobuliak66 matusdrobuliak66 mentioned this pull request Apr 15, 2025
56 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
a:services-library issues on packages/service-libs t:maintenance Some planned maintenance work
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants