Skip to content
Draft
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
24 changes: 20 additions & 4 deletions runpod/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,13 +71,17 @@
"put": "runpod.apps.markers",
# logger
"RunPodLogger": "runpod._logger",
# submodule
# submodules
"cli": "runpod.cli",
"serverless": "runpod.serverless",
}

# type checkers cannot see through __getattr__; mirror the lazy table so
# consumers get real definitions (tests/test_init_typing.py keeps it in sync)
if TYPE_CHECKING:
from runpod import (
cli as cli,
)
from runpod import (
serverless as serverless,
)
Expand Down Expand Up @@ -223,14 +227,17 @@
Endpoint as Endpoint,
)

# eagerly-defined names that are computed on first read instead of at import
_DEFERRED_ATTRS = ("api_key",)

# lazy names resolve through __getattr__, so __all__ derives from the
# lazy table plus the eagerly-defined module attributes
__all__ = [
*_LAZY_ATTRS,
"__version__",
"SSH_KEY_PATH",
"profile",
"api_key",
*_DEFERRED_ATTRS,
"endpoint_url_base",
]

Expand Down Expand Up @@ -272,6 +279,13 @@ def __getattr__(name):
"recurring schedules are not supported by the runpod api. "
"use an external scheduler to invoke a deployed queue function with .spawn()."
)
if name == "api_key":
# resolved on first read so a bare import never touches the credential
# store (and its toml parsers); assigning runpod.api_key still works
# because the assignment lands in module globals and bypasses this hook.
# setdefault keeps a key another thread assigned while this one was
# reading the credential store.
return globals().setdefault("api_key", _load_api_key())
module_path = _LAZY_ATTRS.get(name)
if module_path is None:
raise AttributeError(f"module 'runpod' has no attribute {name!r}")
Expand All @@ -281,13 +295,15 @@ def __getattr__(name):
return value


# importlib.reload(runpod) re-executes this module in the same namespace; drop
# a previously resolved key so the reload picks up the current environment
globals().pop("api_key", None)

# ------------------------------- Config Paths ------------------------------- #
SSH_KEY_PATH = os.path.expanduser("~/.runpod/ssh")

profile = _selected_profile() # pylint: disable=invalid-name

api_key = _load_api_key() # pylint: disable=invalid-name

endpoint_url_base = os.environ.get(
"RUNPOD_ENDPOINT_BASE_URL", "https://api.runpod.ai/v2"
) # pylint: disable=invalid-name
Expand Down
32 changes: 29 additions & 3 deletions runpod/serverless/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"""

import argparse
import importlib
import json
import os
import signal
Expand All @@ -13,13 +14,10 @@
from typing import Any

from ..version import __version__ as runpod_version
from . import worker
from .modules.rp_fitness import register_fitness_check
from .modules.rp_logger import RunPodLogger
from .modules.rp_prestart import has_prestart_hooks as _has_prestart_hooks
from .modules.rp_prestart import register_prestart_hook
from .modules.rp_progress import progress_update
from .utils.rp_volume_cache import VolumeCache

__all__ = [
"VolumeCache",
Expand All @@ -30,6 +28,32 @@
"start",
]

# names resolved on first access (PEP 562). worker, progress and the utils
# package pull in aiohttp, boto3 helpers and the http client, which a process
# that only imports runpod.serverless to register hooks never needs.
_LAZY_ATTRS = {
"VolumeCache": ("runpod.serverless.utils.rp_volume_cache", "VolumeCache"),
"progress_update": ("runpod.serverless.modules.rp_progress", "progress_update"),
"utils": ("runpod.serverless.utils", None),
"worker": ("runpod.serverless.worker", None),
}


def __getattr__(name):
Comment thread
deanq marked this conversation as resolved.
Resolved
target = _LAZY_ATTRS.get(name)
if target is None:
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
module_path, attribute = target
module = importlib.import_module(module_path)
value = module if attribute is None else getattr(module, attribute)
globals()[name] = value
return value


def __dir__():
return sorted(set(globals()) | set(_LAZY_ATTRS))


log = RunPodLogger()


Expand Down Expand Up @@ -218,5 +242,7 @@ def start(config: dict[str, Any]):
)
return

from . import worker # pylint: disable=import-outside-toplevel

worker.main(config)
return
44 changes: 34 additions & 10 deletions runpod/serverless/utils/__init__.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,36 @@
""" Allows for the import of all modules in the utils directory. """

from .rp_download import download_files_from_urls
from .rp_upload import upload_file_to_bucket, upload_in_memory_object
from .rp_volume_cache import VolumeCache

__all__ = [
"download_files_from_urls",
"upload_file_to_bucket",
"upload_in_memory_object",
"VolumeCache",
]
import importlib

# resolved on first access (PEP 562): rp_download and rp_upload pull in
# requests, tqdm and the ssrf guard, which workers that never download or
# upload files should not pay for at import time.
_LAZY_ATTRS = {
"download_files_from_urls": "runpod.serverless.utils.rp_download",
"upload_file_to_bucket": "runpod.serverless.utils.rp_upload",
"upload_in_memory_object": "runpod.serverless.utils.rp_upload",
"VolumeCache": "runpod.serverless.utils.rp_volume_cache",
}

# submodules that the former eager imports bound on this package; resolved
# lazily and kept out of __all__
_LAZY_SUBMODULES = ("rp_download", "rp_upload", "rp_volume_cache")

__all__ = list(_LAZY_ATTRS)


def __getattr__(name):
if name in _LAZY_SUBMODULES:
# importing a submodule binds it on this package, so later reads skip
# this hook
return importlib.import_module(f"{__name__}.{name}")
module_path = _LAZY_ATTRS.get(name)
if module_path is None:
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
value = getattr(importlib.import_module(module_path), name)
globals()[name] = value
return value


def __dir__():
return sorted(set(globals()) | set(_LAZY_ATTRS) | set(_LAZY_SUBMODULES))
23 changes: 20 additions & 3 deletions runpod/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,26 @@
without a generated module, such as a source checkout that was never installed.
"""

from importlib.metadata import PackageNotFoundError, version
import sys

UNKNOWN_VERSION = "unknown"

_METADATA_NAMES = ("PackageNotFoundError", "version")


def __getattr__(name):
"""expose importlib.metadata's `version` and `PackageNotFoundError` lazily.

importing importlib.metadata costs several ms, and built wheels never need
it because they ship runpod/_version.py. The names stay available on this
module for existing `from runpod.version import version` users.
"""
if name not in _METADATA_NAMES:
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
from importlib import metadata # pylint: disable=import-outside-toplevel

return getattr(metadata, name)


def get_version() -> str:
"""Get the version of the runpod package tree being imported."""
Expand All @@ -24,9 +40,10 @@ def get_version() -> str:
else:
return generated_version

module = sys.modules[__name__]
try:
return version("runpod")
except PackageNotFoundError:
return module.version("runpod")
except module.PackageNotFoundError:
return UNKNOWN_VERSION


Expand Down
Loading
Loading