Skip to content
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -318,8 +318,12 @@ runs as edited.

What a generated entrypoint cannot carry is in the list above: a module whose
manifest says which files it is, or names a runtime, keeps that runtime
instead. There is no `debug` terminal on this path, and a function error
reaches the caller as the exec failure with the process's stderr.
instead. There is no `debug` terminal on this path. A function error reaches
the caller as its own error. On an engine that gives the call's process
`DAGGER_FUNCTION_ERROR_PATH`, it keeps its values, such as an exec's exit code
and output, so a caller sees an `ExecError`; on an older engine, only its
message gets past the entrypoint. Either way, an API error keeps the call it
names as its origin.

Generation writes an entrypoint into a module that has none, or whose manifest
names one served from elsewhere, and leaves a Dang entrypoint in the module's
Expand Down
49 changes: 43 additions & 6 deletions sdk/src/dagger/mod/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,14 @@
from dagger import telemetry
from dagger._exceptions import QueryError
from dagger.client._session import mark_module_runtime
from dagger.mod._exceptions import ModuleError
from dagger.mod._exceptions import (
FUNCTION_ERROR_PATH_ENV,
ErrorOriginFilter,
ModuleError,
function_error_message,
report_function_error,
write_function_error,
)

logger = logging.getLogger(__package__)

Expand Down Expand Up @@ -62,17 +69,42 @@ def main(argv: list[str] | None = None) -> int:
call.set_defaults(run=_call)

args = parser.parse_args(argv)
if _error_file(args):
# The engine reads an error's origin from the file.
logger.addFilter(ErrorOriginFilter())
try:
args.run(args)
except (ModuleError, QueryError) as e:
logger.error(str(e)) # noqa: TRY400 - the message is the whole story
# The engine shows an error it is given in a file; logging it
# would show it twice.
if not _error_file(args):
logger.error(str(e)) # noqa: TRY400 - the message is the whole story
_report(args, e)
return 2
except Exception:
except Exception as e:
logger.exception("Unhandled exception")
_report(args, e)
return 1
return 0


def _error_file(args: argparse.Namespace) -> str:
"""The file the engine gives a call's process for its error, if any."""
if args.run is not _call:
return ""
return os.environ.get(FUNCTION_ERROR_PATH_ENV, "")


def _report(args: argparse.Namespace, exc: Exception) -> None:
"""Give the engine a failed call's error, after everything it logged."""
if args.run is not _call:
return
if path := _error_file(args):
write_function_error(path, exc)
else:
report_function_error(function_error_message(exc))


def _entrypoint(args: argparse.Namespace) -> None:
from dagger.client._descriptor import registering_types
from dagger.mod._entrypoint import write_entrypoint
Expand Down Expand Up @@ -104,17 +136,22 @@ def _call(args: argparse.Namespace) -> None:
request = json.load(sys.stdin)
telemetry.initialize()
try:
result = anyio.run(_dispatch, request)
result = anyio.run(_dispatch, request, bool(_error_file(args)))
finally:
telemetry.shutdown()
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(result))


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

return await load_module().dispatch(request)
# The file keeps the error's whole traceback: the logs show the user's
# code, and nothing of an API error the engine shows the origin of, the
# call that failed with its logs.
mod = load_module(short_tracebacks=error_file)
mod.short_tracebacks = error_file
return await mod.dispatch(request)


def _exit(code: int) -> None:
Expand Down
27 changes: 25 additions & 2 deletions sdk/src/dagger/mod/_entrypoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
ObjectDescription,
TypeRef,
)
from dagger.mod._exceptions import FUNCTION_ERROR_MARKER

HEADER = "# Code generated by dagger. DO NOT EDIT.\n"

Expand Down Expand Up @@ -63,6 +64,7 @@ def render_main(name: str, client_version: str, outside: Sequence[str] = ()) ->
for path in outside
),
exclude=SOURCES_EXCLUDE,
marker=_quote(FUNCTION_ERROR_MARKER),
)


Expand Down Expand Up @@ -203,6 +205,13 @@ def _indent(lines: list[str], width: int) -> list[str]:

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

# A call's process has no current function call to return an error to, so a
# failed call fails its exec, whose error carries the end of the process's
# stderr. call() raises the error that the last marker line there reports
# (report_function_error), and the exec's own error when there is none: the
# exec failed before the function did. The exec still fails, so a failed call
# is not cached. The build is synced first so that its failure stays out of
# the rescue and keeps its values, such as the failed install's output.
MAIN_TEMPLATE = """{header}
# Needs Dagger v1.0.0-beta.26 or later; older engines report a missing "naming" field.
type Entrypoint implements ModuleEntrypoint {{
Expand Down Expand Up @@ -231,15 +240,29 @@ def _indent(lines: list[str], width: int) -> list[str]:
fnName: fnName,
fnArgs: fnArgs,
}}}})
let result = runtime
let installed = runtime
.withEnvVariable("DAGGER_MODULE_CALL_DIGEST", callDigest ?? "")
.withEnvVariable("DAGGER_CLIENT_VERSION", clientVersion)
.sync
let result = installed
.withExec(["python", "-m", "dagger.mod", "call", "--output", "/dagger/result.json"], stdin: request, experimentalPrivilegedNesting: true)
.file("/dagger/result.json")
.contents
.contents rescue {{
err: GraphQLError => raiseFunctionError(err)
}}
(result :: JSON!)
}}

let raiseFunctionError(err: GraphQLError!): String! {{
let marker = {marker}
let stderr = ((JSON.decode(err.extensions) :: {{{{stderr: String}}}}).stderr ?? "") rescue ""
let lines = stderr.split("\\n").filter {{ line => line.hasPrefix(marker) }}
if (lines.isEmpty) {{
raise err
}}
raise ((JSON.decode(lines.takeLast(1).join("").trimPrefix(marker)) :: String!) rescue err.message)
}}

let runtime: Container! {{
PythonModuleBuild(
contextDir: directory.withDirectory(".", currentModule.contextDirectory, exclude: ["**/.venv", "**/__pycache__"]),
Expand Down
Loading