SchemaExtension uses different task than query/mutation (thread? coroutine? idk asyncio is hard). Consider this example:
import asyncio
import strawberry
from fastapi import FastAPI
from strawberry.fastapi import GraphQLRouter
from strawberry.extensions import SchemaExtension
from strawberry.utils.await_maybe import AsyncIteratorOrIterator
@strawberry.type
class Query:
@strawberry.field
async def query(self) -> int:
print("query ", id(asyncio.current_task()))
return 1
class ExampleSchemaExtension(SchemaExtension):
async def on_operation(
self,
) -> AsyncIteratorOrIterator[None]:
print("extension pre: ", id(asyncio.current_task()))
yield
print("extension post: ", id(asyncio.current_task()))
schema = strawberry.Schema(
query=Query, extensions=[ExampleSchemaExtension]
)
graphql_router = GraphQLRouter(schema=schema)
app = FastAPI()
app.include_router(graphql_router, prefix="/graphql")
extension pre: 140178710322352
query 140178710323184
extension post: 140178710322352
INFO: 127.0.0.1:57164 - "POST /graphql HTTP/1.1" 200 OK
...:~$ cat /etc/os-release
PRETTY_NAME="Ubuntu 22.04.2 LTS"
NAME="Ubuntu"
VERSION_ID="22.04"
VERSION="22.04.2 LTS (Jammy Jellyfish)"
VERSION_CODENAME=jammy
ID=ubuntu
ID_LIKE=debian
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
UBUNTU_CODENAME=jammy
...$ pip show strawberry-graphql
Name: strawberry-graphql
Version: 0.174.0
So my use case is that using dependency injector and sql alchemy i was able to set up my project in a way that i can inject same database session anywhere within scope (task/thread/coroutine idk which is correct) of single request. This works thanks to sql alchemy scoped session param scopefunc=asyncio.current_task
. Finally I wanted to make sure session is always closed (if it wasn't done manually) by injecting session into custom extension and closing it there. Unfortunatelly because it uses different task different session is injected.
Seems to me that if extensions purpose is to prep/cleanup the request it should use same task by default or there should be a way to make it use same task.
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too