Skip to content

Commit

Permalink
🚧 Countdown logic for teardown
Browse files Browse the repository at this point in the history
Signed-off-by: ff137 <[email protected]>
  • Loading branch information
ff137 committed Feb 6, 2025
1 parent 92770ba commit 20a1353
Showing 1 changed file with 28 additions and 4 deletions.
32 changes: 28 additions & 4 deletions acapy_agent/core/profile.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Classes for managing profile information within a request context."""

import asyncio
import logging
from abc import ABC, abstractmethod
from typing import Any, Mapping, Optional, Type
Expand Down Expand Up @@ -173,6 +174,7 @@ def __init__(
self._context = (context or profile.context).start_scope(settings)
self._profile = profile
self._events = []
self._teardown_task = None

self._context.injector.bind_instance(ProfileSession, ref(self))

Expand Down Expand Up @@ -228,6 +230,10 @@ async def __aenter__(self):
self._entered,
self._profile,
)
# Cancel the teardown task if the session becomes active again
if self._teardown_task:
self._teardown_task.cancel()
self._teardown_task = None
return self

async def __aexit__(self, exc_type, exc_val, exc_tb):
Expand All @@ -240,12 +246,30 @@ async def __aexit__(self, exc_type, exc_val, exc_tb):
)
if not self._awaited and not self._entered:
LOGGER.debug(
"Tearing down profile session in def __aexit__ for profile: %s.",
"Starting countdown for profile session teardown for profile: %s.",
self._profile,
)
# Start a background task for the countdown
self._teardown_task = asyncio.create_task(self._countdown_teardown())

async def _countdown_teardown(self):
"""Wait for a countdown period before tearing down the session."""
try:
await asyncio.sleep(5) # Wait for 5 seconds
if not self._active:
LOGGER.debug(
"Tearing down profile session after countdown for profile: %s.",
self._profile,
)
await self._teardown()
self._active = False
self._teardown_task = None
LOGGER.debug("Profile session inactive for profile: %s.", self._profile)
except asyncio.CancelledError:
LOGGER.debug(
"Countdown for profile session teardown cancelled for profile: %s.",
self._profile,
)
await self._teardown()
self._active = False
LOGGER.debug("Profile session inactive for profile: %s.", self._profile)

@property
def active(self) -> bool:
Expand Down

0 comments on commit 20a1353

Please sign in to comment.