Skip to content
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

DM-48977: Switch to new Python type variable syntax #410

Merged
merged 1 commit into from
Feb 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions changelog.d/20250217_150229_rra_DM_48977.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Bug fixes

- Fix jitter calculations in Nublado businesses.
6 changes: 2 additions & 4 deletions src/mobu/asyncio.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@
from contextlib import AbstractAsyncContextManager
from datetime import timedelta
from types import TracebackType
from typing import Literal, TypeVar

T = TypeVar("T")
from typing import Literal

__all__ = [
"aclosing_iter",
Expand Down Expand Up @@ -88,7 +86,7 @@ async def loop() -> None:
return asyncio.ensure_future(loop())


async def wait_first(*args: Coroutine[None, None, T]) -> T | None:
async def wait_first[T](*args: Coroutine[None, None, T]) -> T | None:
"""Return the result of the first awaitable to finish.

The other awaitables will be cancelled. The first awaitable determines
Expand Down
15 changes: 6 additions & 9 deletions src/mobu/services/business/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from collections.abc import AsyncGenerator, AsyncIterable
from datetime import timedelta
from enum import Enum
from typing import Generic, TypedDict, TypeVar
from typing import TypedDict

from safir.datetime import current_datetime
from structlog.stdlib import BoundLogger
Expand All @@ -19,9 +19,6 @@
from ...models.user import AuthenticatedUser
from ...sentry import capturing_start_span, start_transaction

T = TypeVar("T", bound="BusinessOptions")
U = TypeVar("U")

__all__ = ["Business"]


Expand All @@ -37,7 +34,7 @@ class BusinessCommand(Enum):
STOP = "STOP"


class Business(Generic[T], metaclass=ABCMeta):
class Business[T: BusinessOptions](metaclass=ABCMeta):
"""Base class for monkey business (one type of repeated operation).

The basic flow for a monkey business is as follows:
Expand Down Expand Up @@ -114,21 +111,21 @@ def __init__(

# Methods that should be overridden by child classes if needed.

async def startup(self) -> None:
async def startup(self) -> None: # noqa: B027
Copy link
Member

Choose a reason for hiding this comment

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

What about return None for these instead of disabling linting? That is, if that gets rid of the warning which I don't actually know if it does...

Copy link
Member Author

Choose a reason for hiding this comment

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

Oh, good call, I will try that and see if that suppresses the Ruff warning.

"""Run before the start of the first iteration and then not again."""

@abstractmethod
async def execute(self) -> None:
"""Execute the core of each business loop."""

async def close(self) -> None:
async def close(self) -> None: # noqa: B027
"""Clean up any allocated resources.

This should be overridden by child classes to free any resources that
were allocated in ``__init__``.
"""

async def shutdown(self) -> None:
async def shutdown(self) -> None: # noqa: B027
"""Perform any cleanup required after stopping."""

# Public Business API called by the Monkey class. These methods handle the
Expand Down Expand Up @@ -258,7 +255,7 @@ async def pause(self, interval: timedelta) -> bool:
except (TimeoutError, QueueEmpty):
return True

async def iter_with_timeout(
async def iter_with_timeout[U](
self, iterable: AsyncIterable[U], timeout: timedelta
) -> AsyncGenerator[U]:
"""Run an iterator with a timeout.
Expand Down
19 changes: 12 additions & 7 deletions src/mobu/services/business/nublado.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from random import SystemRandom
from typing import Generic, TypeVar
from typing import Any

import sentry_sdk
from rubin.nublado.client import JupyterLabSession, NubladoClient
Expand All @@ -35,12 +35,11 @@
from ...sentry import capturing_start_span, start_transaction
from .base import Business

T = TypeVar("T", bound="NubladoBusinessOptions")

__all__ = ["NubladoBusiness", "ProgressLogMessage"]

_ANSI_REGEX = re.compile(r"(?:\x1B[@-_]|[\x80-\x9F])[0-?]*[ -/]*[@-~]")
"""Regex that matches ANSI escape sequences."""

_CHDIR_TEMPLATE = 'import os; os.chdir("{wd}")'
"""Template to construct the code to run to set the working directory."""

Expand Down Expand Up @@ -78,7 +77,9 @@ def __str__(self) -> str:
return f"{timestamp} - {self.message}"


class NubladoBusiness(Business, Generic[T], metaclass=ABCMeta):
class NubladoBusiness[T: NubladoBusinessOptions](
Business[T], metaclass=ABCMeta
):
"""Base class for business that executes Python code in a Nublado notebook.

This class modifies the core `~mobu.business.base.Business` loop by
Expand Down Expand Up @@ -216,9 +217,11 @@ async def shutdown(self) -> None:
async def idle(self) -> None:
if self.options.jitter:
self.logger.info("Idling...")
jitter = self.options.jitter.total_seconds()
delay_seconds = self._random.uniform(0, jitter)
delay = timedelta(seconds=delay_seconds)
with capturing_start_span(op="idle"):
extra_delay = self._random.uniform(0, self.options.jitter)
await self.pause(self.options.idle_time + extra_delay)
await self.pause(self.options.idle_time + delay)
else:
await super().idle()

Expand Down Expand Up @@ -304,7 +307,9 @@ async def open_session(
self, notebook: str | None = None
) -> AsyncGenerator[JupyterLabSession]:
self.logger.info("Creating lab session")
opts = {"max_websocket_size": self.options.max_websocket_message_size}
opts: dict[str, Any] = {
"max_websocket_size": self.options.max_websocket_message_size
}
create_session_cm = capturing_start_span(op="create_session")
create_session_cm.__enter__()
async with self._client.open_lab_session(notebook, **opts) as session:
Expand Down
5 changes: 1 addition & 4 deletions src/mobu/services/business/tap.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import asyncio
from abc import ABCMeta, abstractmethod
from concurrent.futures import ThreadPoolExecutor
from typing import Generic, TypeVar

import pyvo
import requests
Expand All @@ -21,12 +20,10 @@
from ...sentry import capturing_start_span, start_transaction
from .base import Business

T = TypeVar("T", bound="TAPBusinessOptions")

__all__ = ["TAPBusiness"]


class TAPBusiness(Business, Generic[T], metaclass=ABCMeta):
class TAPBusiness[T: TAPBusinessOptions](Business[T], metaclass=ABCMeta):
"""Base class for business that executes TAP query.

This class modifies the core `~mobu.business.base.Business` loop by
Expand Down
Loading