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
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,28 @@ dagger call python-sdk mod --path my-module config set \
--base-image python:3.13-slim
```

### Serve calls from one process

A module can ask the engine to run its calls in one warm process per session,
which skips the interpreter start and the imports of every call after the
first:

```toml
[tool.dagger]
serve = true
```

The setting takes effect at the next `dagger generate`, which adds a `serve`
member to the module's generated entrypoint. Only an engine that includes
module server support serves calls this way. On any other engine the module
keeps working, and every call runs in a new process.

The process runs one call at a time. Before each call ends, it restores
`os.environ` and the working directory. Everything else persists into the
later calls of the same session and module: module globals, files written to
the container, and secrets a global holds. A call that finds the process busy
runs in a new process, so a call cannot rely on what an earlier call left.

## Generate SDK files

`dagger generate` regenerates every recorded scope. A recorded module can also
Expand Down
2 changes: 1 addition & 1 deletion dagger-module.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ source = "dang"

[[dependencies]]
name = "sdk-helpers"
source = "github.com/dagger/sdk-helpers@v1.0.10"
source = "github.com/dagger/sdk-helpers@v1.0.11"

[[dependencies]]
name = "python-sdk-runtime"
Expand Down
2 changes: 2 additions & 0 deletions dagger.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@
[["version","2"]]
["","git-latest",["github.com/dagger/alpine"],"refs/heads/main"]
["","git-latest",["github.com/dagger/sdk-helpers",["version","v1.0.10"]],"refs/tags/v1.0.10"]
["","git-latest",["github.com/dagger/sdk-helpers",["version","v1.0.11"]],"refs/tags/v1.0.11"]
["","git-latest",["github.com/dagger/sdk-helpers",["version","v1.0.8"]],"refs/tags/v1.0.8"]
["","git-latest",["github.com/dagger/sdk-helpers",["version","v1.0.9"]],"refs/tags/v1.0.9"]
["","git-sha",["github.com/containernetworking/plugins","refs/tags/v1.9.0"],"9b3772e1a7abf93cbb7c6526a28bc0d27b830e02"]
["","git-sha",["github.com/dagger/alpine","main"],"ff6a5f4c28364912d92c00e682dd0bf19f524ef9"]
["","git-sha",["github.com/dagger/alpine","refs/heads/main"],"ff6a5f4c28364912d92c00e682dd0bf19f524ef9"]
["","git-sha",["github.com/dagger/sdk-helpers","refs/tags/v1.0.10"],"3d0cf3b4f6c901b288658421af8f2e3bbaebc663"]
["","git-sha",["github.com/dagger/sdk-helpers","refs/tags/v1.0.11"],"3be7456c40d9206b648ac44e418f30aa79bc6190"]
["","git-sha",["github.com/dagger/sdk-helpers","refs/tags/v1.0.8"],"31dafd0c74d9a08faa00c09dce87a5af072e7a9d"]
["","git-sha",["github.com/dagger/sdk-helpers","refs/tags/v1.0.9"],"daffbc01a1b3f3df7b1c417a7d2c83cd06d1bd33"]
["","git-sha",["github.com/libfuse/sshfs","refs/tags/sshfs-3.7.6"],"7a2d988775446ebe7af9b01c99b3b8e86bddb05a"]
Expand Down
1 change: 1 addition & 0 deletions sdk/codegen/src/codegen/packages.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
SESSION_NAMES = frozenset(
{
"_as_session",
"_generation",
"_loads",
"_ready",
"aclose",
Expand Down
21 changes: 21 additions & 0 deletions sdk/src/dagger/client/_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,15 @@ def from_env(cls) -> "ConnectParams | None":
raise ClientConnectionError(msg) from e


# A module server sets these per call, so that each call's requests reach the
# engine as that call's client, whichever session sends them.
request_headers: dict[str, str] = {}


class TelemetryTransport(httpx.AsyncHTTPTransport):
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
propagate.inject(request.headers)
request.headers.update(request_headers)
return await super().handle_async_request(request)


Expand Down Expand Up @@ -365,6 +371,7 @@ def __init__(self, connection: BaseConnection | None = None) -> None:
# set up: the session the generated global client builds is over it.
self.connection = SharedConnection() if connection is None else connection
self._loads: dict[str, _Load] = {}
self._generation = _load_generation

@property
def session(self) -> ClientSession: # type: ignore[override]
Expand Down Expand Up @@ -406,6 +413,9 @@ def __getattr__(self, name: str) -> Any:

async def load(self, target: "Target") -> None:
"""Serve the module a target names, once per session."""
if self._generation != _load_generation:
self.forget()
self._generation = _load_generation
entry = self._loads.setdefault(target.name, _Load(target))
if entry.target != target:
# Whole descriptors: the two may differ only by pin, and the
Expand All @@ -430,6 +440,17 @@ async def load(self, target: "Target") -> None:
entry.done = True


# A module server runs each call as another engine client, which has loaded
# nothing, so it makes every session forget its loads between calls.
_load_generation = 0


def forget_loads() -> None:
"""Make every session load its targets again."""
global _load_generation # noqa: PLW0603
_load_generation += 1


_module_runtime = False


Expand Down
36 changes: 25 additions & 11 deletions sdk/src/dagger/mod/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,16 @@

import argparse
import json
import logging
import pathlib
import sys
import tomllib
from typing import Any

import anyio

from dagger import telemetry
from dagger._exceptions import QueryError
from dagger.client._session import mark_module_runtime
from dagger.mod._exceptions import ModuleError

logger = logging.getLogger(__package__)
from dagger.mod._exceptions import log_failure


def main(argv: list[str] | None = None) -> int:
Expand Down Expand Up @@ -58,15 +55,17 @@ def main(argv: list[str] | None = None) -> int:
call.add_argument("--output", required=True, type=pathlib.Path)
call.set_defaults(run=_call)

serve = commands.add_parser(
"serve",
help="import the module once and run the calls the engine sends, one at a time",
)
serve.set_defaults(run=_serve)

args = parser.parse_args(argv)
try:
args.run(args)
except (ModuleError, QueryError) as e:
logger.error(str(e)) # noqa: TRY400 - the message is the whole story
return 2
except Exception:
logger.exception("Unhandled exception")
return 1
except Exception as e: # noqa: BLE001 - log_failure logs the traceback
return log_failure(e)
return 0


Expand All @@ -83,9 +82,17 @@ def _entrypoint(args: argparse.Namespace) -> None:
client_version=args.client_version,
output=args.output,
outside=args.outside,
serve=_opts_in_to_serve(pathlib.Path("pyproject.toml")),
)


def _opts_in_to_serve(pyproject: pathlib.Path) -> bool:
if not pyproject.is_file():
return False
config = tomllib.loads(pyproject.read_text()).get("tool", {}).get("dagger", {})
return config.get("serve") is True


def _describe(args: argparse.Namespace) -> None:
from dagger.client._descriptor import registering_types
from dagger.mod._describe import describe_json
Expand All @@ -108,6 +115,13 @@ def _call(args: argparse.Namespace) -> None:
args.output.write_text(json.dumps(result))


def _serve(_: argparse.Namespace) -> None:
from dagger.mod._serve import serve
from dagger.mod.cli import load_module

serve(load_module())


async def _dispatch(request: dict[str, Any]) -> Any:
from dagger.mod.cli import load_module

Expand Down
29 changes: 24 additions & 5 deletions sdk/src/dagger/mod/_entrypoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,21 @@
HEADER = "# Code generated by dagger. DO NOT EDIT.\n"


def write_entrypoint(
def write_entrypoint( # noqa: PLR0913
desc: ModuleDescription,
*,
name: str,
client_version: str,
output: pathlib.Path,
outside: Sequence[str] = (),
serve: bool = False,
) -> None:
"""Write types.dang and main.dang for the module."""
output.mkdir(parents=True, exist_ok=True)
(output / "types.dang").write_text(render_types(desc))
(output / "main.dang").write_text(render_main(name, client_version, outside))
(output / "main.dang").write_text(
render_main(name, client_version, outside, serve=serve)
)


def render_types(desc: ModuleDescription) -> str:
Expand All @@ -44,13 +47,20 @@ def render_types(desc: ModuleDescription) -> str:
return "\n".join(lines)


def render_main(name: str, client_version: str, outside: Sequence[str] = ()) -> str:
def render_main(
name: str,
client_version: str,
outside: Sequence[str] = (),
*,
serve: bool = False,
) -> str:
"""Return the module and each directory outside it from sources.

`client_version` is the engine release the module's code is generated
for, which the entrypoint declares when it starts the module's process.
`outside` holds the directories outside the module that its build reads,
relative to the module directory.
relative to the module directory. `serve` adds the member an engine
starts one warm module process from, for the module's calls in a session.
"""
return MAIN_TEMPLATE.format(
header=HEADER,
Expand All @@ -63,6 +73,7 @@ def render_main(name: str, client_version: str, outside: Sequence[str] = ()) ->
for path in outside
),
exclude=SOURCES_EXCLUDE,
serve=SERVE_MEMBER if serve else "",
)


Expand Down Expand Up @@ -201,6 +212,14 @@ def _indent(lines: list[str], width: int) -> list[str]:

SOURCES_EXCLUDE = '["**/.git", "**/.venv", "**/__pycache__"]'

SERVE_MEMBER = """ pub serve: Container! {
runtime
.withEnvVariable("DAGGER_CLIENT_VERSION", clientVersion)
.withDefaultArgs(["python", "-m", "dagger.mod", "serve"])
}

"""

MAIN_TEMPLATE = """{header}
type Entrypoint implements ModuleEntrypoint {{
let moduleName: String! = {name}
Expand Down Expand Up @@ -237,7 +256,7 @@ def _indent(lines: list[str], width: int) -> list[str]:
(result :: JSON!)
}}

let runtime: Container! {{
{serve} let runtime: Container! {{
PythonModuleBuild(
contextDir: directory.withDirectory(".", currentModule.contextDirectory, exclude: ["**/.venv", "**/__pycache__"]),
subPath: currentModule.sourceSubpath,
Expand Down
12 changes: 12 additions & 0 deletions sdk/src/dagger/mod/_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,18 @@
logger = logging.getLogger(__package__)


def log_failure(e: Exception) -> int:
"""Log why a call or command failed and return its exit status.

Call it from the except block, which gives the traceback.
"""
if isinstance(e, ModuleError | QueryError):
logger.error(str(e))
return 2
logger.exception("Unhandled exception") # noqa: LOG004 - called from an except block
return 1


class ModuleError(DaggerError):
"""Base class for all errors raised by modules.

Expand Down
Loading