Source code for contree_client.models

"""Data models for the Contree API.

Generated by codegen from the OpenAPI spec - do not edit.
"""

from __future__ import annotations

import base64
import binascii
import re
import stat
from collections.abc import Callable
from contextlib import suppress
from dataclasses import dataclass, field, fields
from datetime import datetime, timezone
from enum import Enum
from types import EllipsisType
from typing import Any, Literal, TypeVar

FRACTION_RE = re.compile(r"^(.*T\d{2}:\d{2}:\d{2})\.(\d+)(.*)$")


[docs] def parse_datetime(value: str) -> datetime: """Parse an ISO 8601 timestamp, tolerating Z suffix and nanoseconds.""" v = value.strip() if v.endswith(("Z", "z")): v = v[:-1] + "+00:00" match = FRACTION_RE.match(v) if match: # python 3.10 fromisoformat accepts only 3- or 6-digit # fractions: trim nanoseconds AND zero-pad short fractions fraction = match.group(2)[:6].ljust(6, "0") v = f"{match.group(1)}.{fraction}{match.group(3)}" return datetime.fromisoformat(v)
[docs] def wire_value(value: Any) -> Any: """Recursively encode a value to its JSON-compatible wire form. Models, datetime and Enum are converted wherever they sit - directly in a field or nested inside lists and mappings. """ if isinstance(value, ContreeModel): return value.to_dict() if isinstance(value, datetime): return value.isoformat() if isinstance(value, Enum): return value.value if isinstance(value, (list, tuple)): return [wire_value(item) for item in value] if isinstance(value, dict): return {key: wire_value(item) for key, item in value.items()} return value
[docs] def omitted_dict(items: list[tuple[str, Any]]) -> dict[str, Any]: """`dict_factory` for `dataclasses.asdict` used by `to_dict()`. Fields left unset (`...`) are omitted entirely so the server-side defaults apply, while an explicit None is serialized as JSON null; datetime and enum values become JSON-friendly at any nesting depth. """ return {key: wire_value(value) for key, value in items if value is not Ellipsis}
TModel = TypeVar("TModel", bound="ContreeModel")
[docs] @dataclass class ContreeModel: """Base model with the default wire (de)serialization. `to_dict` uses each field's wire name and omits unset (`...`) fields while keeping explicit None as JSON null. `from_dict` builds the model from `parse_fields`; models whose fields need conversion (nested models, datetimes, discriminated unions) override `parse_fields` only. """
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { item.name: data[wire_name] for item in fields(cls) if (wire_name := item.metadata.get("wire_name", item.name)) in data }
[docs] @classmethod def from_dict(cls: type[TModel], data: dict[str, Any]) -> TModel: return cls(**cls.parse_fields(data))
[docs] def to_dict(self) -> dict[str, Any]: return omitted_dict( [ ( item.metadata.get("wire_name", item.name), getattr(self, item.name), ) for item in fields(self) ] )
OperationEventType = Literal[ "init", "spawn", "stdin", "stdout", "stderr", "exit", "truncated", "size_cap", "network", "shutdown", "inspect", "file_upload", "completion", ]
[docs] class OperationStatus(str, Enum): """Operation lifecycle state.""" PENDING = "PENDING" ASSIGNED = "ASSIGNED" EXECUTING = "EXECUTING" SUCCESS = "SUCCESS" FAILED = "FAILED" CANCELLED = "CANCELLED" def __str__(self) -> str: return self.value
[docs] def is_terminal(self) -> bool: """True for statuses that will never change again.""" return self in TERMINAL_STATUSES
[docs] @classmethod def terminal(cls) -> frozenset[OperationStatus]: """Statuses that will never change again.""" return TERMINAL_STATUSES
[docs] @classmethod def active(cls) -> frozenset[OperationStatus]: """Statuses of operations that are still in flight.""" return ACTIVE_STATUSES
# str-enum members compare and hash like their values, so these # also answer membership for plain strings ("SUCCESS" in ...) TERMINAL_STATUSES = frozenset( ( OperationStatus.SUCCESS, OperationStatus.FAILED, OperationStatus.CANCELLED, ) ) ACTIVE_STATUSES = frozenset( ( OperationStatus.PENDING, OperationStatus.ASSIGNED, OperationStatus.EXECUTING, ) )
[docs] @dataclass class FileItem(ContreeModel): size: int = field(metadata={"description": "File size in bytes", "example": 1024}) path: str = field( metadata={ "description": "File name (relative to the directory being listed)", "example": "passwd", } ) owner: str | int = field( metadata={"description": "File owner name or UID", "example": "root"} ) group: str | int = field( metadata={"description": "File group name or GID", "example": "root"} ) uid: int = field( metadata={"description": "User ID of the file owner", "example": 0} ) gid: int = field(metadata={"description": "Group ID of the file", "example": 0}) mode: int = field( metadata={ "description": "File mode/permissions as integer (octal representation)", "example": 33188, } ) mtime: int = field( metadata={ "description": "Last modification time as Unix timestamp", "example": 1640995200, } ) nlink: int = field(metadata={"description": "Number of hard links", "example": 1}) is_dir: bool = field( metadata={"description": "True if the item is a directory", "example": False} ) is_regular: bool = field( metadata={"description": "True if the item is a regular file", "example": True} ) is_symlink: bool = field( metadata={ "description": "True if the item is a symbolic link", "example": False, } ) is_socket: bool = field( metadata={"description": "True if the item is a socket", "example": False} ) is_fifo: bool = field( metadata={ "description": "True if the item is a FIFO/named pipe", "example": False, } ) symlink_to: str = field( metadata={ "description": ( "Target path if the item is a symbolic link, empty string otherwise" ), "example": "", } )
[docs] @dataclass class DirectoryList(ContreeModel): path: str = field( metadata={ "description": "The directory path that was listed", "example": "/etc", } ) files: list[FileItem] = field( metadata={"description": "List of files and directories in the specified path"} )
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "path": data["path"], "files": [FileItem.from_dict(item) for item in data["files"]], }
[docs] def as_text(self, short: bool = False) -> str: """Format entries like ls -l, or return one path per line with short=True.""" if short: return "".join(f"{item.path}\n" for item in self.files) rows: list[tuple[str, str, str, str, str, str, str]] = [] for item in self.files: mode = item.mode if not stat.S_IFMT(mode): for enabled, file_type in ( (item.is_symlink, stat.S_IFLNK), (item.is_dir, stat.S_IFDIR), (item.is_socket, stat.S_IFSOCK), (item.is_fifo, stat.S_IFIFO), (item.is_regular, stat.S_IFREG), ): if enabled: mode |= file_type break path = item.path if stat.S_ISLNK(mode) and item.symlink_to: path += f" -> {item.symlink_to}" owner = str(item.owner if item.owner != "" else item.uid) group = str(item.group if item.group != "" else item.gid) modified = datetime.fromtimestamp(item.mtime, timezone.utc) rows.append( ( stat.filemode(mode), str(item.nlink), owner, group, str(item.size), modified.strftime("%Y-%m-%d %H:%M"), path, ) ) if not rows: return "" links_width = max(len(row[1]) for row in rows) owner_width = max(len(row[2]) for row in rows) group_width = max(len(row[3]) for row in rows) size_width = max(len(row[4]) for row in rows) return "".join( f"{mode} {links:>{links_width}} {owner:<{owner_width}} " f"{group:<{group_width}} {size:>{size_width}} {modified} {path}\n" for mode, links, owner, group, size, modified, path in rows )
__str__ = as_text
[docs] @dataclass class GrepSubmatch(ContreeModel): text: str = field( metadata={"description": "The matched text", "example": "PermitRootLogin"} ) start: int = field( metadata={ "description": "Byte offset of the match start within the line", "example": 1, } ) end: int = field( metadata={ "description": "Byte offset of the match end within the line", "example": 16, } )
[docs] @dataclass class GrepMatch(ContreeModel): path: str = field( metadata={ "description": "File path relative to the image rootfs", "example": "/etc/ssh/sshd_config", } ) line_number: int = field( metadata={"description": "1-based line number of the match", "example": 57} ) absolute_offset: int = field( metadata={ "description": "Byte offset of the line from the start of the file", "example": 1712, } ) line_text: str = field( metadata={ "description": ( "The matching line, including the line terminator (truncated at 4096 " "bytes)" ), "example": "#PermitRootLogin prohibit-password\n", } ) line_bytes: int = field( metadata={ "description": ( "Real byte length of the matching line; greater than line_text length " "when the line was capped" ), "example": 8192, } ) submatches: list[GrepSubmatch] = field( metadata={"description": "Empty for context lines (they carry no submatches)"} ) type: Literal["match", "context"] = field( metadata={ "description": ( 'Mirrors ripgrep\'s --json message type: "match" is an actual match, ' '"context" is a\nbefore/after context line requested via before/after.' ), "example": "match", } )
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "path": data["path"], "line_number": data["line_number"], "absolute_offset": data["absolute_offset"], "line_text": data["line_text"], "line_bytes": data["line_bytes"], "submatches": [GrepSubmatch.from_dict(item) for item in data["submatches"]], "type": data["type"], }
[docs] def as_text(self) -> str: """Format one grep row with its path, line number, and trailing newline.""" separator = "-" if self.type == "context" else ":" text = f"{self.path}{separator}{self.line_number}{separator}{self.line_text}" return text if text.endswith("\n") else text + "\n"
__str__ = as_text
[docs] @dataclass class GrepResult(ContreeModel): path: str = field( metadata={ "description": ( "The first path inside the image that was searched. When `path` was " "repeated,\nsee each row's own `path` for which root it actually came " "from." ), "example": "/etc", } ) patterns: list[str] = field( metadata={ "description": "The patterns that were searched for", "example": ["^PermitRootLogin"], } ) matches: list[GrepMatch] = field( metadata={ "description": ( "File-ordered lines; each is a match or (when before/after are set) " "surrounding context" ) } ) truncated: bool = field( metadata={ "description": ( "True when max_total or the search deadline stopped the search early" ), "example": False, } )
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "path": data["path"], "patterns": data["patterns"], "matches": [GrepMatch.from_dict(item) for item in data["matches"]], "truncated": data["truncated"], }
[docs] def as_text(self) -> str: """Format grep rows in response order, separating disjoint context groups.""" output: list[str] = [] previous: GrepMatch | None = None has_context = any(row.type == "context" for row in self.matches) for row in self.matches: if ( has_context and previous is not None and ( row.path != previous.path or row.line_number != previous.line_number + 1 ) ): output.append("--\n") output.append(row.as_text()) previous = row return "".join(output)
__str__ = as_text
[docs] @dataclass class ImageImportRegistryCredentials(ContreeModel): username: str | EllipsisType = field( default=..., metadata={ "description": "Username for the registry authentication", "example": "myuser", }, ) password: str | EllipsisType = field( default=..., metadata={ "description": "Password for the registry authentication", "example": "secret", }, )
[docs] @dataclass class ImageImportRegistry(ContreeModel): url: str = field( metadata={ "description": "URL of the container registry", "example": "docker://docker.io/busybox:latest", } ) credentials: ImageImportRegistryCredentials | EllipsisType = ...
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "url": data["url"], "credentials": ( ImageImportRegistryCredentials.from_dict(data["credentials"]) ) if data.get("credentials") is not None else data.get("credentials", ...), }
[docs] @dataclass class ImageImportRequest(ContreeModel): registry: ImageImportRegistry tag: str | None | EllipsisType = field( default=..., metadata={ "description": ( "Tag to identify the image when listing publicly available images. If " "omitted, the image will be private and only accessible by ID." ), "example": "busybox:latest", }, ) timeout: int | EllipsisType = field( default=..., metadata={ "description": ( "Maximum time in seconds to wait for the import operation to complete" ), "example": 300, "default": 300, }, )
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "registry": ImageImportRegistry.from_dict(data["registry"]), "tag": data.get("tag", ...), "timeout": data.get("timeout", ...), }
[docs] @dataclass class Image(ContreeModel): uuid: str | EllipsisType = ... tag: str | None | EllipsisType = field( default=..., metadata={ "description": "Tag to identify the image", "example": "busybox:latest", }, ) created_at: str | EllipsisType = field( default=..., metadata={ "description": "ISO 8601 formatted timestamp of when the image was created", "example": "2024-01-01T12:00:00+00:00", }, ) operation_uuid: str | None | EllipsisType = field( default=..., metadata={ "description": ( "UUID of the operation that created this image.\nReturns `null` when " "the image belongs to a different namespace (e.g. public images)\nor " "when the image was not created by an operation (e.g. shared images)." ) }, )
[docs] @dataclass class ImageListResponse(ContreeModel): images: list[Image] | EllipsisType = field( default=..., metadata={"description": "List of publicly available images"} )
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "images": ([Image.from_dict(item) for item in data["images"]]) if data.get("images") is not None else data.get("images", ...), }
[docs] @dataclass class ImageImportMetadataRegistryCredentials(ContreeModel): username: str | EllipsisType = field( default=..., metadata={ "description": "Username for the registry authentication", "example": "myuser", }, ) password: str | EllipsisType = field( default=..., metadata={ "description": "Always masked in the response is present", "example": "<MASKED>", }, )
[docs] @dataclass class ImageImportMetadataRegistry(ContreeModel): url: str | EllipsisType = field( default=..., metadata={ "description": "URL of the container registry", "example": "docker://docker.io/busybox:latest", }, ) credentials: ImageImportMetadataRegistryCredentials | EllipsisType = ...
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "url": data.get("url", ...), "credentials": ( ImageImportMetadataRegistryCredentials.from_dict(data["credentials"]) ) if data.get("credentials") is not None else data.get("credentials", ...), }
[docs] @dataclass class ImageImportMetadata(ContreeModel): registry: ImageImportMetadataRegistry | EllipsisType = ... tag: str | None | EllipsisType = ... timeout: int | EllipsisType = field( default=..., metadata={ "description": ( "Maximum time in seconds to wait for the import operation to complete" ), "example": 300, "default": 300, }, )
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "registry": (ImageImportMetadataRegistry.from_dict(data["registry"])) if data.get("registry") is not None else data.get("registry", ...), "tag": data.get("tag", ...), "timeout": data.get("timeout", ...), }
[docs] @dataclass class StreamRepr(ContreeModel): value: str = field( metadata={ "description": "Content of the stream", "example": "Y29tbWFuZCBvdXRwdXQK", } ) encoding: Literal["ascii", "base64"] = field( metadata={"description": "Encoding of the content", "example": "base64"} ) truncated: bool | EllipsisType = field( default=..., metadata={"description": "Whether the output was truncated", "example": False}, )
[docs] def as_bytes(self) -> bytes: """The payload decoded to raw bytes. ``base64`` values are decoded; ``ascii`` text is UTF-8 encoded. Undecodable base64 becomes empty bytes instead of failing a live stream. """ if not self.value: return b"" if self.encoding == "base64": try: return base64.b64decode(self.value) except (binascii.Error, ValueError): return b"" return self.value.encode("utf-8", errors="replace")
[docs] def as_text(self) -> str: """The payload decoded to text (UTF-8, errors replaced).""" if self.encoding == "base64": return self.as_bytes().decode("utf-8", errors="replace") return self.value
__str__ = as_text
[docs] @classmethod def from_bytes(cls, value: bytes) -> StreamRepr: """Build a payload from raw bytes. Printable ASCII (plus tab/newline/carriage return) is stored as ``ascii``; anything else is base64-encoded - the same rule the server applies on its side. """ if all(32 <= byte < 127 or byte in (9, 10, 13) for byte in value): return cls(value=value.decode("ascii"), encoding="ascii") return cls( value=base64.b64encode(value).decode("ascii"), encoding="base64", )
[docs] @classmethod def from_text(cls, value: str) -> StreamRepr: """Build a payload from text (UTF-8 encoded unless ASCII).""" return cls.from_bytes(value.encode("utf-8"))
[docs] @dataclass class ClosableStreamRepr(ContreeModel): """Stdin payload. Delivery to the child is always complete —. stdin is never truncated on its way to the process. Only the *recorded* ``stdin`` events in the subprocess event log are capped by ``truncate_output_at``, same as stdout/stderr. This schema also carries a ``close`` flag controlling the pipe's EOF. """ value: str = field( metadata={ "description": ( "Content to write to stdin (may be empty for a close-only request)" ), "example": "aGVsbG8K", } ) encoding: Literal["ascii", "base64"] | EllipsisType = field( default=..., metadata={"description": "Encoding of the content", "default": "ascii"}, ) close: bool | EllipsisType = field( default=..., metadata={ "description": ( "`true` (default) closes stdin (EOF) after writing `value` —\nthe " "pre-existing one-shot behavior. `false` keeps the pipe\nopen so more " "data can be sent later via\n`POST " "/operations/{operationId}/subprocesses/{spid}/stdin`." ), "default": True, }, )
[docs] def as_bytes(self) -> bytes: """The payload decoded to raw bytes. ``base64`` values are decoded; ``ascii`` text is UTF-8 encoded. Undecodable base64 becomes empty bytes instead of failing a live stream. """ if not self.value: return b"" if self.encoding == "base64": try: return base64.b64decode(self.value) except (binascii.Error, ValueError): return b"" return self.value.encode("utf-8", errors="replace")
[docs] def as_text(self) -> str: """The payload decoded to text (UTF-8, errors replaced).""" if self.encoding == "base64": return self.as_bytes().decode("utf-8", errors="replace") return self.value
__str__ = as_text
[docs] @classmethod def from_bytes(cls, value: bytes) -> ClosableStreamRepr: """Build a payload from raw bytes. Printable ASCII (plus tab/newline/carriage return) is stored as ``ascii``; anything else is base64-encoded - the same rule the server applies on its side. """ if all(32 <= byte < 127 or byte in (9, 10, 13) for byte in value): return cls(value=value.decode("ascii"), encoding="ascii") return cls( value=base64.b64encode(value).decode("ascii"), encoding="base64", )
[docs] @classmethod def from_text(cls, value: str) -> ClosableStreamRepr: """Build a payload from text (UTF-8 encoded unless ASCII).""" return cls.from_bytes(value.encode("utf-8"))
[docs] @dataclass class InstanceResourcesLimits(ContreeModel): """Launch-time limits. CPU sets the VM's vCPU count. memory_mib limits. each process's address space (RLIMIT_AS, soft and hard) and the whole process tree's memory (cgroup memory.max). A request for 1 MiB is valid and enforces that limit on the workload. The backend independently selects a minimum VM RAM allocation for guest boot, networking and runtime services, for example 128 or 256 MiB. This minimum is an implementation detail and can change. It does not increase the requested workload limit. A small address-space limit can prevent the executable or runtime from loading. It includes stacks, libraries and reserved mappings; allocations can fail with ENOMEM even with overcommit enabled. Guest kernel and runtime consume part of VM RAM. Limits are maxima, not reservations. Guest root retains permission to modify cgroups. """ cpu: int | EllipsisType = field( default=..., metadata={"description": "Number of guest vCPUs.", "default": 4} ) memory_mib: int | EllipsisType = field( default=..., metadata={ "description": ( "Per-process address-space and process-tree memory limit in MiB " "(1048576 bytes)." ), "default": 4096, }, ) max_layer_bytes: int | EllipsisType = field( default=..., metadata={ "description": "Maximum writable layer size in bytes.", "example": 1073741824, "default": 12884901888, }, )
[docs] @dataclass class ProcessResourcesLimits(ContreeModel): """Launch-time limits for a subprocess and its descendants. Each omitted. or null field inherits the requested operation limit, not the VM's minimum boot memory. CPU/RAM cannot exceed the parent operation. Limits are maxima, not reservations. Concurrent processes share VM resources and can exhaust the aggregate budget. memory_mib sets RLIMIT_AS (soft and hard) before exec and memory.max for the tree. RLIMIT_AS includes reserved mappings, stacks and libraries; allocation or executable loading can fail with ENOMEM. Descendants inherit it. A local cgroup OOM kills this process tree. A VM-wide OOM can affect other processes. Guest root retains permission to modify cgroups. """ cpu: int | None | EllipsisType = field( default=..., metadata={ "description": ( "Number of guest vCPUs available to the process tree. The runtime " "selects CPU affinity; CPU sets can overlap between subprocesses." ) }, ) memory_mib: int | None | EllipsisType = field( default=..., metadata={ "description": ( "Per-process RLIMIT_AS and tree memory.max in MiB. Swap is disabled " "for this group." ) }, )
[docs] @dataclass class InstanceNetworking(ContreeModel): enabled: bool | EllipsisType = field( default=..., metadata={ "description": ( "Enable network access for the instance. When `false`, the VM starts " "without a guest network interface." ), "default": True, }, ) policy: list[str] | EllipsisType = field( default=..., metadata={ "description": ( "Network policies to apply, referenced by UUID or by tag prefixed with " "`tag:`.\n\n**References**\n\n- You can use your own policies and " "shared policies.\n- Your tag takes precedence over a shared tag with " "the same name.\n- Duplicate references and resolved policy UUIDs are " "removed while preserving first occurrence order.\n- Unknown or " "unavailable references return 404.\n- Deleted policies remain usable " "by UUID.\n\n**Permissions**\n\nUsing policies requires only the " "permission to create the instance;\n`network_policy` is not " "required.\n\n**Limits**\n\n- At most 512 references may be supplied, " "including duplicates.\n- Before and after merging, the rules are " "limited to 16384 units in total:\n sum the number of ports across " "all rules, counting an all-port rule as 1.\n All IP versions and " "protocols share this limit. Repeated rules and ports\n across " "policies count again before merging.\n- Exceeding either limit " "returns 400.\n\n**No policies**\n\nOmitting this field or passing " "`policy: []` allows all IPv4 destinations and\nglobal unicast IPv6 " "destinations on all ports.\nThe API adds four explicit rules to " "`effective_policy`:\nTCP and UDP for IPv4 `0.0.0.0/0` and IPv6 " "`2000::/3`, each with `ports: []`\n(all ports). ICMP is also allowed " "to these destinations.\nIPv6 destinations outside `2000::/3`, " "including unique-local and link-local\naddresses, require explicit " "policy rules.\n\n**Empty policies**\n\nA selected policy with no " 'rules (`{"cidrs": []}`) allows nothing.\nIf all selected policies are ' 'empty, `effective_policy` is `{"cidrs": []}`\nand all network traffic ' "is denied.\nAn empty policy combined with non-empty policies adds no " "permissions;\nthe other policies' rules still apply.\n\n**Effective " "policy**\n\n`effective_policy` contains the final combined network " "rules that will be\napplied to the operation.\nRules are combined by " "merging CIDRs per protocol and port, then grouping\nports for " "matching CIDRs and protocols." ), "example": ["12345678-9abc-baba-deda-0123456789ab", "tag:github"], "default": [], }, )
[docs] @dataclass class NetworkPolicyCIDRRule(ContreeModel): cidr: str = field( metadata={ "description": "IPv4 or IPv6 destination network in CIDR notation.", "example": "192.0.2.0/24", } ) proto: Literal["tcp", "udp"] ports: list[int] | EllipsisType = field( default=..., metadata={ "description": ( "Allowed destination ports. Omitted or empty means all ports." ), "default": [], }, )
[docs] @dataclass class NetworkPolicyCreateRequest(ContreeModel): """An allowlist of destination networks, protocols, and ports. A policy with ``{"cidrs": []}``. allows nothing. Selecting only empty policies denies all network traffic. This differs from selecting no policies (``networking.policy: []``), which allows all IPv4 destinations (``0.0.0.0/0``) and global unicast IPv6 destinations (``2000::/3``) on all ports and adds these explicit rules to ``effective_policy``. """ cidrs: list[NetworkPolicyCIDRRule]
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "cidrs": [NetworkPolicyCIDRRule.from_dict(item) for item in data["cidrs"]], }
[docs] @dataclass class InstanceNetworkingResponse(ContreeModel): enabled: bool | EllipsisType = field( default=..., metadata={ "description": ( "Enable network access for the instance. When `false`, the VM starts " "without a guest network interface." ), "default": True, }, ) policy: list[str] | EllipsisType = field( default=..., metadata={ "description": ( "Unique applied policy UUIDs in first occurrence order. Tag references " "are returned as UUIDs." ) }, ) effective_policy: NetworkPolicyCreateRequest | None | EllipsisType = field( default=..., metadata={ "description": ( "The final combined network rules that will be applied to the " "operation.\nNew instances always include an explicit effective " "policy, including when\nno policy references are specified. Omitting " "`networking.policy` or passing\n`policy: []` allows all IPv4 and " "global unicast IPv6 destinations on all ports:\nthis field contains " "four rules, TCP and UDP for both `0.0.0.0/0` (IPv4)\nand `2000::/3` " "(IPv6), with `ports: []` on each rule.\nICMP is also allowed to these " "destinations.\nIPv6 destinations outside `2000::/3` require explicit " 'policy rules.\nSelecting only empty policies (`{"cidrs": []}`) ' 'instead produces `{"cidrs": []}`,\nwhich denies all network traffic. ' "Empty policies add no permissions when\ncombined with non-empty " "policies.\nHistorical instance metadata may omit this field or " "contain null." ) }, )
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "enabled": data.get("enabled", ...), "policy": data.get("policy", ...), "effective_policy": ( NetworkPolicyCreateRequest.from_dict(data["effective_policy"]) ) if data.get("effective_policy") is not None else data.get("effective_policy", ...), }
[docs] @dataclass class NetworkPolicyTag(ContreeModel): tag: str = field(metadata={"description": "Network policy tag name"}) uuid: str
[docs] @dataclass class NetworkPolicy(ContreeModel): uuid: str cidrs: list[NetworkPolicyCIDRRule]
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "uuid": data["uuid"], "cidrs": [NetworkPolicyCIDRRule.from_dict(item) for item in data["cidrs"]], }
[docs] @dataclass class NetworkPolicyListItemSummary(ContreeModel): cidrs: int = field( metadata={ "description": ( "Number of CIDR rules in the policy, including repeated CIDRs." ) } )
[docs] @dataclass class NetworkPolicyListItem(ContreeModel): uuid: str created_at: datetime = field( metadata={"description": "Time when the policy was created."} ) tags: list[str] = field( metadata={ "description": ( "Accessible tag names resolving to this policy, sorted by name. Empty " "when none exist." ) } ) summary: NetworkPolicyListItemSummary
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "uuid": data["uuid"], "created_at": parse_datetime(data["created_at"]), "tags": data["tags"], "summary": NetworkPolicyListItemSummary.from_dict(data["summary"]), }
[docs] @dataclass class NetworkPolicyListResponse(ContreeModel): policies: list[NetworkPolicyListItem]
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "policies": [ NetworkPolicyListItem.from_dict(item) for item in data["policies"] ], }
[docs] @dataclass class ExecSpec(ContreeModel): """Process-execution surface shared between ``InstanceSpawnRequest``. (the main process) and ``POST /operations/{operationId}/subprocesses`` (additional subprocesses). VM-level concerns (image, hostname, disk limits, files, timeout, disposable, preserve_env) live on ``InstanceSpawnRequest`` only. """ command: str = field( metadata={ "description": ( "The command to execute. Same semantics as in " "`InstanceSpawnRequest.command` — when `shell=true` it is a shell " "expression, otherwise a path to an executable." ), "example": "/bin/app", } ) resources_limits: ProcessResourcesLimits | EllipsisType = ... args: list[str] | EllipsisType = field( default=..., metadata={ "description": "Arguments to pass to the command if shell is set to false.", "example": ["arg1", "arg2"], "default": [], }, ) shell: bool | EllipsisType = field( default=..., metadata={ "description": ( "Run command through a shell expression (args must be empty)." ), "default": False, }, ) env: dict[str, str] | None | EllipsisType = field( default=..., metadata={"description": "Environment variables to set in the child process."}, ) cwd: str | EllipsisType = field( default=..., metadata={ "description": ( "Working directory; empty string means image / server default." ), "default": "", }, ) uid: int | EllipsisType = field( default=..., metadata={"description": "User ID to run the process as.", "default": 0}, ) gid: int | EllipsisType = field( default=..., metadata={"description": "Group ID to run the process as.", "default": 0}, ) stdin: ClosableStreamRepr | EllipsisType = field( default=..., metadata={ "description": ( "Bytes fed to the child's stdin — honored for both the main\nprocess " "and exec'd subprocesses. With `close=false` the\npipe stays open and " "more data can be written via\n`POST " "/operations/{operationId}/subprocesses/{spid}/stdin`." ) }, ) truncate_output_at: int | EllipsisType = field( default=..., metadata={ "description": ( "Maximum number of bytes to keep per stream (stdout,\nstderr, and " "stdin) in the subprocess event log. Does not\naffect delivery to the " "child — stdin is always delivered\nin full regardless of this cap. " "Defaults to 1 MiB; capped\nat 10 MiB." ), "example": 65535, "default": 1048576, }, )
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "command": data["command"], "resources_limits": ( ProcessResourcesLimits.from_dict(data["resources_limits"]) ) if data.get("resources_limits") is not None else data.get("resources_limits", ...), "args": data.get("args", ...), "shell": data.get("shell", ...), "env": data.get("env", ...), "cwd": data.get("cwd", ...), "uid": data.get("uid", ...), "gid": data.get("gid", ...), "stdin": (ClosableStreamRepr.from_dict(data["stdin"])) if data.get("stdin") is not None else data.get("stdin", ...), "truncate_output_at": data.get("truncate_output_at", ...), }
[docs] @dataclass class FileSpec(ContreeModel): uuid: str | EllipsisType = ... uid: int | EllipsisType = field( default=..., metadata={"description": "User ID", "example": 0} ) gid: int | EllipsisType = field( default=..., metadata={"description": "Group ID", "example": 0} ) mode: str | int | EllipsisType = field( default=..., metadata={ "description": 'File mode in octal format (e.g., "0644")', "example": "0644", }, ) def __post_init__(self) -> None: # the wire format is an octal string; accept a plain int too if isinstance(self.mode, int): self.mode = f"{self.mode:04o}"
[docs] @dataclass class InstanceSpawnRequest(ContreeModel): command: str = field( metadata={ "description": ( "The command to execute. In case if `shell` is set to `true`, this " "MUST contain shell expression. \nFor example `echo hello world` or " "`ls -l /app`. \nIf `shell` is set to `false`, this must be a relative " "or absolute path to the executable inside the image rootfs. \nFor " "example: `/bin/app` or `/usr/bin/find`.\nDo not forget pass necessary " "`PATH` variable to env field, by default `PATH` is set to " "`/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`." ), "example": "/bin/app", } ) image: str disposable: bool | EllipsisType = field( default=..., metadata={ "description": ( "Creates a disposable execution environment no any state will be saved." ), "default": False, }, ) hostname: str | EllipsisType = field( default=..., metadata={ "description": "Hostname to set when execution.", "example": "container-name", "default": "linuxkit", }, ) args: list[str] | EllipsisType = field( default=..., metadata={ "description": "Arguments to pass to the command if shell is set to false.", "example": ["arg1", "arg2"], "default": [], }, ) shell: bool | EllipsisType = field( default=..., metadata={ "description": ( "Whether to run the command through a shell. If `true`, the command " "must be a shell expression and all values from args will be ignored. " "If `false`, the command field must be a path to an executable and " "args will be used. When `true`, environment variables from the image " "are automatically inherited. When `false`, they are not - use the " "`env` field to pass them explicitly." ), "default": False, }, ) env: dict[str, str] | None | EllipsisType = field( default=..., metadata={ "description": ( "Environment variables to set in the container. These are merged with " "image-defined variables when `shell` is `true`. When `shell` is " "`false`, only variables specified here are available - image-defined " "variables are not inherited." ), "example": {"KEY1": "value1", "KEY2": "value2"}, }, ) preserve_env: bool | EllipsisType = field( default=..., metadata={ "description": ( "Preserve environment variables in resulting image after execution. " "When `true`, the image's existing environment variables from " "`metadata/env` are merged with user-provided `env` values (user " "values take priority on conflicts), and the combined result is " "written back to `metadata/env` after command execution. Setting a " "variable to an empty string or `null` removes it from the preserved " "environment." ), "default": False, }, ) preserve_cwd: bool | EllipsisType = field( default=..., metadata={ "description": ( "Save the resolved initial working directory as the default in the " "resulting image. An empty or omitted `cwd` resolves to the image's " "current workdir, or `/` if none exists. The metadata file is opened " "for writing only when its contents differ from the new value. " "Directory changes made by the command do not change the saved value. " "Requires `disposable: false` to retain the metadata in a resulting " "image." ), "default": False, }, ) cwd: str | EllipsisType = field( default=..., metadata={ "description": ( "Path to the working directory, must be absolute or a special value " "the empty string. It means the default working directory of the image " "or server default will be used. If field is omitted it will be set to " "the empty string. The directory will be created automatically if it " "does not exist." ), "example": "/app", "default": "", }, ) uid: int | EllipsisType = field( default=..., metadata={ "description": "User ID to run the process as.", "example": 0, "default": 0, }, ) gid: int | EllipsisType = field( default=..., metadata={ "description": "Group ID to run the process as.", "example": 0, "default": 0, }, ) resources_limits: InstanceResourcesLimits | EllipsisType = ... networking: InstanceNetworking | EllipsisType = ... stdin: ClosableStreamRepr | EllipsisType = ... timeout: int | EllipsisType = field( default=..., metadata={"description": "Maximum execution time in seconds", "example": 60}, ) truncate_output_at: int | EllipsisType = field( default=..., metadata={ "description": ( "Maximum number of bytes to keep per stream (stdout, stderr, and " "stdin) in the subprocess event log. Does not affect stdin delivery to " "the child, which always receives the complete stream regardless of " "this cap. Default is `1048576` (1 MiB). The maximum value is " "`10485760` (10 MiB)." ), "example": 65535, "default": 1048576, }, ) files: dict[str, FileSpec] | EllipsisType = field( default=..., metadata={ "description": "Map of absolute file paths to file metadata", "example": { "/root/hello.txt": { "uuid": "a9165a5d-5c86-4bd8-8ee4-ae46c19cf45d", "uid": 0, "gid": 0, "mode": "0644", }, "/tmp/log.txt": { "uuid": "065def2a-e977-4852-8b26-a0ec05e85a90", "uid": 1000, "gid": 1000, "mode": "0600", }, }, }, )
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "command": data["command"], "image": data["image"], "disposable": data.get("disposable", ...), "hostname": data.get("hostname", ...), "args": data.get("args", ...), "shell": data.get("shell", ...), "env": data.get("env", ...), "preserve_env": data.get("preserve_env", ...), "preserve_cwd": data.get("preserve_cwd", ...), "cwd": data.get("cwd", ...), "uid": data.get("uid", ...), "gid": data.get("gid", ...), "resources_limits": ( InstanceResourcesLimits.from_dict(data["resources_limits"]) ) if data.get("resources_limits") is not None else data.get("resources_limits", ...), "networking": (InstanceNetworking.from_dict(data["networking"])) if data.get("networking") is not None else data.get("networking", ...), "stdin": (ClosableStreamRepr.from_dict(data["stdin"])) if data.get("stdin") is not None else data.get("stdin", ...), "timeout": data.get("timeout", ...), "truncate_output_at": data.get("truncate_output_at", ...), "files": ( {key: FileSpec.from_dict(value) for key, value in data["files"].items()} ) if data.get("files") is not None else data.get("files", ...), }
[docs] @dataclass class InstanceResultResources(ContreeModel): block_input: int | EllipsisType = field( default=..., metadata={"description": "Block input operations"} ) block_output: int | EllipsisType = field( default=..., metadata={"description": "Block output operations"} ) cost: float | EllipsisType = field( default=..., metadata={"description": "Operation cost"} ) elapsed_time: float | EllipsisType = field( default=..., metadata={"description": "Elapsed wall time"} ) involuntary_switches: int | EllipsisType = field( default=..., metadata={"description": "Number of involuntary context switches"} ) max_rss: int | EllipsisType = field( default=..., metadata={"description": "Maximum resident set size in KB"} ) monotonic_time: float | EllipsisType = field( default=..., metadata={"description": "Monotonic time measurement"} ) page_faults: int | EllipsisType = field( default=..., metadata={"description": "Number of page faults"} ) page_faults_io: int | EllipsisType = field( default=..., metadata={"description": "Number of page faults requiring I/O"} ) shared_memory: int | EllipsisType = field( default=..., metadata={"description": "Shared memory size"} ) signals: int | EllipsisType = field( default=..., metadata={"description": "Number of signals received"} ) swaps: int | EllipsisType = field( default=..., metadata={"description": "Number of swaps"} ) system_cpu_time: float | EllipsisType = field( default=..., metadata={"description": "System CPU time used"} ) unshared_memory: int | EllipsisType = field( default=..., metadata={"description": "Unshared memory size"} ) user_cpu_time: float | EllipsisType = field( default=..., metadata={"description": "User CPU time used"} ) voluntary_switches: int | EllipsisType = field( default=..., metadata={"description": "Number of voluntary context switches"} )
[docs] @dataclass class InstanceResultState(ContreeModel): continued: bool | EllipsisType = field( default=..., metadata={"description": "Whether the process was continued from a stop"}, ) core_dump: bool | EllipsisType = field( default=..., metadata={"description": "Whether a core dump was generated"} ) exit_code: int | EllipsisType = field( default=..., metadata={"description": "Process exit code"} ) pid: int | EllipsisType = field(default=..., metadata={"description": "Process ID"}) signal: int | EllipsisType = field( default=..., metadata={"description": "Signal that caused termination, if any"} ) stopped: bool | EllipsisType = field( default=..., metadata={"description": "Whether the process was stopped"} ) timed_out: bool | EllipsisType = field( default=..., metadata={ "description": ( "Whether process had been killed because operation timeout was reached" ) }, ) oom_killed: bool | EllipsisType = field( default=..., metadata={ "description": ( "Whether an OOM kill was observed in the process tree's cgroup." ), "default": False, }, )
[docs] @dataclass class InstanceResult(ContreeModel): """Result of an instance execution.""" resources: InstanceResultResources | EllipsisType = ... state: InstanceResultState | EllipsisType = ... stdout: StreamRepr | EllipsisType = ... stderr: StreamRepr | EllipsisType = ...
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "resources": (InstanceResultResources.from_dict(data["resources"])) if data.get("resources") is not None else data.get("resources", ...), "state": (InstanceResultState.from_dict(data["state"])) if data.get("state") is not None else data.get("state", ...), "stdout": (StreamRepr.from_dict(data["stdout"])) if data.get("stdout") is not None else data.get("stdout", ...), "stderr": (StreamRepr.from_dict(data["stderr"])) if data.get("stderr") is not None else data.get("stderr", ...), }
[docs] @dataclass class InstanceSpawnResponse(ContreeModel): uuid: str | EllipsisType = ... command: str | EllipsisType = ... image: str | EllipsisType = ... hostname: str | EllipsisType = ... args: list[str] | EllipsisType = ... shell: bool | EllipsisType = ... env: dict[str, str] | None | EllipsisType = ... preserve_env: bool | EllipsisType = ... cwd: str | EllipsisType = ... uid: int | EllipsisType = ... gid: int | EllipsisType = ... resources_limits: InstanceResourcesLimits | EllipsisType = ... networking: InstanceNetworkingResponse | EllipsisType = ... stdin: ClosableStreamRepr | EllipsisType = ... timeout: int | EllipsisType = ... truncate_output_at: int | EllipsisType = ... disposable: bool | EllipsisType = ... files: dict[str, FileSpec] | EllipsisType = ... result: InstanceResult | None | EllipsisType = ...
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "uuid": data.get("uuid", ...), "command": data.get("command", ...), "image": data.get("image", ...), "hostname": data.get("hostname", ...), "args": data.get("args", ...), "shell": data.get("shell", ...), "env": data.get("env", ...), "preserve_env": data.get("preserve_env", ...), "cwd": data.get("cwd", ...), "uid": data.get("uid", ...), "gid": data.get("gid", ...), "resources_limits": ( InstanceResourcesLimits.from_dict(data["resources_limits"]) ) if data.get("resources_limits") is not None else data.get("resources_limits", ...), "networking": (InstanceNetworkingResponse.from_dict(data["networking"])) if data.get("networking") is not None else data.get("networking", ...), "stdin": (ClosableStreamRepr.from_dict(data["stdin"])) if data.get("stdin") is not None else data.get("stdin", ...), "timeout": data.get("timeout", ...), "truncate_output_at": data.get("truncate_output_at", ...), "disposable": data.get("disposable", ...), "files": ( {key: FileSpec.from_dict(value) for key, value in data["files"].items()} ) if data.get("files") is not None else data.get("files", ...), "result": (InstanceResult.from_dict(data["result"])) if data.get("result") is not None else data.get("result", ...), }
[docs] @dataclass class OperationSummary(ContreeModel): uuid: str | EllipsisType = ... kind: Literal["image_import", "instance"] | EllipsisType = field( default=..., metadata={"description": "Type of the operation"} ) status: OperationStatus | EllipsisType = field( default=..., metadata={ "description": "Current state of the instance operation", "example": "success", }, ) error: str | None | EllipsisType = field( default=..., metadata={ "description": "Error message if the operation failed", "example": "Container image not found", }, ) created_at: str | EllipsisType = field( default=..., metadata={ "description": ( "ISO 8601 formatted timestamp when the operation was created" ), "example": "2024-01-01T12:00:00+00:00", }, ) duration: float | None | EllipsisType = field( default=..., metadata={"description": "Operation duration in seconds"} ) image_size: int | None | EllipsisType = field( default=..., metadata={ "description": ( "Bytes written for the resulting image/layer(s).\n`null` when not " "measured (e.g. disposable instance, non-SUCCESS operations)." ) }, ) consumed_cpu: float | None | EllipsisType = field( default=..., metadata={ "description": ( "Total CPU time consumed by the operation, in seconds.\n`null` when " "not measured." ) }, ) consumed_memory: int | None | EllipsisType = field( default=..., metadata={ "description": ( "Peak resident memory used by the operation's execution environment, " "in KiB.\n`null` when not measured. Shared resident pages are included." ) }, ) image_uuid: str | None | EllipsisType = field( default=..., metadata={ "description": ( "UUID of the source image this operation was run on.\nSet for INSTANCE " "operations, `null` for IMAGE_IMPORT." ) }, ) result_image_uuid: str | None | EllipsisType = field( default=..., metadata={ "description": ( "UUID of the image produced by this operation.\nOnly set for completed " "(SUCCESS) operations, `null` otherwise." ) }, )
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "uuid": data.get("uuid", ...), "kind": data.get("kind", ...), "status": (OperationStatus(data["status"])) if data.get("status") is not None else data.get("status", ...), "error": data.get("error", ...), "created_at": data.get("created_at", ...), "duration": data.get("duration", ...), "image_size": data.get("image_size", ...), "consumed_cpu": data.get("consumed_cpu", ...), "consumed_memory": data.get("consumed_memory", ...), "image_uuid": data.get("image_uuid", ...), "result_image_uuid": data.get("result_image_uuid", ...), }
[docs] @dataclass class OperationInstanceMetadata(ContreeModel): command: str = field( metadata={ "description": ( "The command to execute. In case if `shell` is set to `true`, this " "MUST contain shell expression. \nFor example `echo hello world` or " "`ls -l /app`. \nIf `shell` is set to `false`, this must be a relative " "or absolute path to the executable inside the image rootfs. \nFor " "example: `/bin/app` or `/usr/bin/find`.\nDo not forget pass necessary " "`PATH` variable to env field, by default `PATH` is set to " "`/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`." ), "example": "/bin/app", } ) image: str disposable: bool | EllipsisType = field( default=..., metadata={ "description": ( "Creates a disposable execution environment no any state will be saved." ), "default": False, }, ) hostname: str | EllipsisType = field( default=..., metadata={ "description": "Hostname to set when execution.", "example": "container-name", "default": "linuxkit", }, ) args: list[str] | EllipsisType = field( default=..., metadata={ "description": "Arguments to pass to the command if shell is set to false.", "example": ["arg1", "arg2"], "default": [], }, ) shell: bool | EllipsisType = field( default=..., metadata={ "description": ( "Whether to run the command through a shell. If `true`, the command " "must be a shell expression and all values from args will be ignored. " "If `false`, the command field must be a path to an executable and " "args will be used. When `true`, environment variables from the image " "are automatically inherited. When `false`, they are not - use the " "`env` field to pass them explicitly." ), "default": False, }, ) env: dict[str, str] | None | EllipsisType = field( default=..., metadata={ "description": ( "Environment variables to set in the container. These are merged with " "image-defined variables when `shell` is `true`. When `shell` is " "`false`, only variables specified here are available - image-defined " "variables are not inherited." ), "example": {"KEY1": "value1", "KEY2": "value2"}, }, ) preserve_env: bool | EllipsisType = field( default=..., metadata={ "description": ( "Preserve environment variables in resulting image after execution. " "When `true`, the image's existing environment variables from " "`metadata/env` are merged with user-provided `env` values (user " "values take priority on conflicts), and the combined result is " "written back to `metadata/env` after command execution. Setting a " "variable to an empty string or `null` removes it from the preserved " "environment." ), "default": False, }, ) preserve_cwd: bool | EllipsisType = field( default=..., metadata={ "description": ( "Save the resolved initial working directory as the default in the " "resulting image. An empty or omitted `cwd` resolves to the image's " "current workdir, or `/` if none exists. The metadata file is opened " "for writing only when its contents differ from the new value. " "Directory changes made by the command do not change the saved value. " "Requires `disposable: false` to retain the metadata in a resulting " "image." ), "default": False, }, ) cwd: str | EllipsisType = field( default=..., metadata={ "description": ( "Path to the working directory, must be absolute or a special value " "the empty string. It means the default working directory of the image " "or server default will be used. If field is omitted it will be set to " "the empty string. The directory will be created automatically if it " "does not exist." ), "example": "/app", "default": "", }, ) uid: int | EllipsisType = field( default=..., metadata={ "description": "User ID to run the process as.", "example": 0, "default": 0, }, ) gid: int | EllipsisType = field( default=..., metadata={ "description": "Group ID to run the process as.", "example": 0, "default": 0, }, ) resources_limits: InstanceResourcesLimits | EllipsisType = ... networking: InstanceNetworkingResponse | EllipsisType = ... stdin: ClosableStreamRepr | EllipsisType = ... timeout: int | EllipsisType = field( default=..., metadata={"description": "Maximum execution time in seconds", "example": 60}, ) truncate_output_at: int | EllipsisType = field( default=..., metadata={ "description": ( "Maximum number of bytes to keep per stream (stdout, stderr, and " "stdin) in the subprocess event log. Does not affect stdin delivery to " "the child, which always receives the complete stream regardless of " "this cap. Default is `1048576` (1 MiB). The maximum value is " "`10485760` (10 MiB)." ), "example": 65535, "default": 1048576, }, ) files: dict[str, FileSpec] | EllipsisType = field( default=..., metadata={ "description": "Map of absolute file paths to file metadata", "example": { "/root/hello.txt": { "uuid": "a9165a5d-5c86-4bd8-8ee4-ae46c19cf45d", "uid": 0, "gid": 0, "mode": "0644", }, "/tmp/log.txt": { "uuid": "065def2a-e977-4852-8b26-a0ec05e85a90", "uid": 1000, "gid": 1000, "mode": "0600", }, }, }, ) result: InstanceResult | EllipsisType = ...
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "command": data["command"], "image": data["image"], "disposable": data.get("disposable", ...), "hostname": data.get("hostname", ...), "args": data.get("args", ...), "shell": data.get("shell", ...), "env": data.get("env", ...), "preserve_env": data.get("preserve_env", ...), "preserve_cwd": data.get("preserve_cwd", ...), "cwd": data.get("cwd", ...), "uid": data.get("uid", ...), "gid": data.get("gid", ...), "resources_limits": ( InstanceResourcesLimits.from_dict(data["resources_limits"]) ) if data.get("resources_limits") is not None else data.get("resources_limits", ...), "networking": (InstanceNetworkingResponse.from_dict(data["networking"])) if data.get("networking") is not None else data.get("networking", ...), "stdin": (ClosableStreamRepr.from_dict(data["stdin"])) if data.get("stdin") is not None else data.get("stdin", ...), "timeout": data.get("timeout", ...), "truncate_output_at": data.get("truncate_output_at", ...), "files": ( {key: FileSpec.from_dict(value) for key, value in data["files"].items()} ) if data.get("files") is not None else data.get("files", ...), "result": (InstanceResult.from_dict(data["result"])) if data.get("result") is not None else data.get("result", ...), }
[docs] @dataclass class OperationResult(ContreeModel): """Result of the operation, if any.""" image: str | None | EllipsisType = ... tag: str | None | EllipsisType = field( default=..., metadata={ "description": "Tag assigned to the imported image", "example": "busybox:latest", }, )
[docs] @dataclass class OperationResponse(ContreeModel): uuid: str | EllipsisType = ... kind: Literal["image_import", "instance"] | EllipsisType = field( default=..., metadata={"description": "Type of the operation"} ) status: OperationStatus | EllipsisType = ... error: str | None | EllipsisType = ... created_at: str | EllipsisType = field( default=..., metadata={ "description": ( "ISO 8601 formatted timestamp when the operation was created" ), "example": "2024-01-01T12:00:00+00:00", }, ) duration: float | None | EllipsisType = ... image_size: int | None | EllipsisType = field( default=..., metadata={ "description": ( "Bytes written for the resulting image/layer(s).\n`null` when not " "measured (e.g. disposable instance, non-SUCCESS operations)." ) }, ) consumed_cpu: float | None | EllipsisType = field( default=..., metadata={ "description": ( "Total CPU time consumed by the operation, in seconds.\n`null` when " "not measured." ) }, ) consumed_memory: int | None | EllipsisType = field( default=..., metadata={ "description": ( "Peak resident memory used by the operation's execution environment, " "in KiB.\n`null` when not measured. Shared resident pages are included." ) }, ) image_uuid: str | None | EllipsisType = field( default=..., metadata={ "description": ( "UUID of the source image this operation was run on.\nSet for INSTANCE " "operations, `null` for IMAGE_IMPORT." ) }, ) result_image_uuid: str | None | EllipsisType = field( default=..., metadata={ "description": ( "UUID of the image produced by this operation.\nOnly set for completed " "(SUCCESS) operations, `null` otherwise." ) }, ) metadata: OperationInstanceMetadata | ImageImportMetadata | EllipsisType = ... result: OperationResult | EllipsisType = field( default=..., metadata={"description": "Result of the operation, if any"} )
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "uuid": data.get("uuid", ...), "kind": data.get("kind", ...), "status": (OperationStatus(data["status"])) if data.get("status") is not None else data.get("status", ...), "error": data.get("error", ...), "created_at": data.get("created_at", ...), "duration": data.get("duration", ...), "image_size": data.get("image_size", ...), "consumed_cpu": data.get("consumed_cpu", ...), "consumed_memory": data.get("consumed_memory", ...), "image_uuid": data.get("image_uuid", ...), "result_image_uuid": data.get("result_image_uuid", ...), "metadata": ( OperationInstanceMetadata.from_dict(data["metadata"]) if data.get("kind") == "instance" else ImageImportMetadata.from_dict(data["metadata"]) ) if data.get("metadata") is not None else data.get("metadata", ...), "result": (OperationResult.from_dict(data["result"])) if data.get("result") is not None else data.get("result", ...), }
[docs] @dataclass class Error(ContreeModel): error: Any = field( metadata={ "description": "Error message or structured validation errors", "example": "Some error occurred, this is an example of error message", } ) status: int | EllipsisType = field( default=..., metadata={"description": "HTTP status code", "example": 500} ) traceback: list[str] | EllipsisType = ...
[docs] @dataclass class FileResponse(ContreeModel): uuid: str sha256: str = field( metadata={ "description": "SHA256 hash of the file content", "example": ( "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" ), } ) size: int = field( metadata={"description": "File size in bytes; -1 if unknown", "example": 1024} )
[docs] @dataclass class File(ContreeModel): uuid: str sha256: str = field(metadata={"description": "SHA256 hash of the file content"}) size: int = field( metadata={"description": "File size in bytes; -1 if unknown", "example": 1024} ) created_at: datetime = field( metadata={"description": "When the file was first uploaded by this namespace"} ) updated_at: datetime = field( metadata={"description": "Updated on each upload of the same file"} )
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "uuid": data["uuid"], "sha256": data["sha256"], "size": data["size"], "created_at": parse_datetime(data["created_at"]), "updated_at": parse_datetime(data["updated_at"]), }
[docs] @dataclass class FilesListResponse(ContreeModel): files: list[File] | EllipsisType = ...
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "files": ([File.from_dict(item) for item in data["files"]]) if data.get("files") is not None else data.get("files", ...), }
[docs] @dataclass class WhoAmIResponse(ContreeModel): token_uuid: str = field( metadata={ "description": "UUID of the authentication token", "example": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", } ) token_expiration: int | None = field( metadata={ "description": ( "Token expiration time as Unix timestamp, or null if not set" ), "example": 1735689600, } ) permissions: dict[str, bool] = field( metadata={ "description": ( "Map of all known permission names to their granted status.\nKeys are " "permission names (e.g., `import`, `spawn`, `list`),\nvalues indicate " "whether the token has the permission." ), "example": { "import": True, "spawn": True, "spawn_disposable": False, "list": True, "cancel": False, "set_image_tag": False, "network_policy": False, }, } ) operations_stat: dict[str, int] = field( metadata={"description": "Operation statistics (reserved for future use)"} ) limits: dict[str, int] | EllipsisType = field( default=..., metadata={ "description": ( "Map of resource limit names to their values for the current token." ), "example": { "instance_max_timeout": 3600, "instance_max_concurrency": 10, "images_import_max_concurrency": 5, "images_import_max_timeout": 3600, }, }, )
[docs] @dataclass class OperationEvent(ContreeModel): """One event in the operation's event log. **Process events** carry a Spawned Process ID (``spid``) as their routing identity: ``spid=0`` is the daemon (init / network / shutdown / size_cap, plus any synthetic stderr emitted before a child existed), ``spid=1`` is the main process from ``InstanceMetadata``, and ``spid>=2`` are exec'd children (Phase 3+). Spids are Registry-assigned, monotonic, and never recycled within an operation; the kernel PID (when needed for debugging) lives inside the per-type ``data`` payload. **System events** (``completion``) describe the operation as a whole, not a specific child process — they omit ``spid`` entirely. """ id: int = field( metadata={ "description": ( "Sequential id assigned at append time. Strictly\nincreasing within a " "single operation's event log; gaps\nare possible (rare, after a " "transient producer-side\nserialization failure). Use this with " "`Last-Event-Id` /\n`?since=` to resume a dropped SSE stream." ), "example": 42, } ) ts: datetime = field( metadata={ "description": "UTC wall-clock time when the event was emitted.", "example": "2026-06-08T20:00:00.123456789Z", } ) type: OperationEventType data: EventData | dict[str, Any] = field( metadata={ "description": ( "Per-type payload. Clients should switch on `type` and\nvalidate " "`data` against the corresponding schema below." ) } ) spid: int | EllipsisType = field( default=..., metadata={ "description": ( "Spawned Process ID — present on process-scoped events\n(`init`, " "`spawn`, `stdin`, `stdout`, `stderr`, `exit`,\n`truncated`, " "`size_cap`, `network`, `shutdown`, `inspect`, `file_upload`).\nAbsent " "on operation-scoped system events\n(`completion`), which don't tie to " "a specific child." ), "example": 1, }, )
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "id": data["id"], "ts": parse_datetime(data["ts"]), "type": data["type"], "data": parse_event_data(data["type"], data["data"]), "spid": data.get("spid", ...), }
[docs] @dataclass class EventInspectParametersOptions(ContreeModel): patterns: list[str] | None globs: list[str] | None case: str max_count: int max_total: int before: int after: int
[docs] @dataclass class EventInspectParameters(ContreeModel): """Parameters for the method named in EventDataInspect. Path methods. (stat/list/open/archive/grep/upload) record path. Grep also records options. Upload records file_uuid, unpack, replace, and merge. Read/write record handle, offset, and size; write size is the input chunk length, not an acknowledgement. Close/finish record handle. Binary payloads are excluded. """ path: str | EllipsisType = ... file_uuid: str | EllipsisType = ... unpack: bool | EllipsisType = ... replace: bool | EllipsisType = ... merge: bool | EllipsisType = ... handle: str | EllipsisType = ... offset: int | EllipsisType = ... size: int | EllipsisType = ... options: EventInspectParametersOptions | EllipsisType = ...
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "path": data.get("path", ...), "file_uuid": data.get("file_uuid", ...), "unpack": data.get("unpack", ...), "replace": data.get("replace", ...), "merge": data.get("merge", ...), "handle": data.get("handle", ...), "offset": data.get("offset", ...), "size": data.get("size", ...), "options": (EventInspectParametersOptions.from_dict(data["options"])) if data.get("options") is not None else data.get("options", ...), }
[docs] @dataclass class EventDataInspect(ContreeModel): """Metadata for a guest inspect RPC. Init emits a started/completed pair. with the same request_id. Event IDs order the starts independently of completion order. A returned handle links subsequent reads, writes, finish, close, and file_upload events. All events use spid=0. Request parameters are recorded even when the method rejects them. A successful open/upload only allocates a handle; it does not complete the transfer. Read events report RPC bytes, not HTTP client receipt. File contents, directory listings, and grep matches are never recorded. Events are flushed to the journal and bypass the stream size cap. A missing completion can indicate an interrupted or lost event. These records support a future replay implementation; replay is not automatic. """ request_id: str = field( metadata={ "description": "Opaque identifier shared by the request and result events." } ) method: Literal[ "stat", "list", "open", "archive", "grep", "read", "close", "upload", "write", "finish", ] phase: Literal["started", "completed"] params: EventInspectParameters | EllipsisType = ... status: Literal["success", "error", "cancelled", "timeout"] | EllipsisType = ... error: str | None | EllipsisType = field( default=..., metadata={ "description": ( "Error category only; null on success. No exception text or file " "contents." ) }, ) handle: str | EllipsisType = field( default=..., metadata={ "description": "Present after a successful open, archive, grep, or upload." }, ) bytes: int | EllipsisType = field( default=..., metadata={"description": "Bytes returned by a successful read."} ) eof: bool | EllipsisType = field( default=..., metadata={ "description": ( "Present after a successful read; true at the end of its stream." ) }, )
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "request_id": data["request_id"], "method": data["method"], "phase": data["phase"], "params": (EventInspectParameters.from_dict(data["params"])) if data.get("params") is not None else data.get("params", ...), "status": data.get("status", ...), "error": data.get("error", ...), "handle": data.get("handle", ...), "bytes": data.get("bytes", ...), "eof": data.get("eof", ...), }
[docs] @dataclass class EventDataFileUpload(ContreeModel): """Init emits this event once after publication or cleanup of an accepted. upload. It is emitted even if the host disconnects or Finish loses its response. A rejected upload has only its inspect request/result pair. Success means publication finished. Error or cancellation can leave a partially applied merge, as specified by the upload endpoint. The event contains metadata only, uses spid=0, bypasses the stream size cap, and is flushed before shutdown. Recording does not extend the source file's TTL or guarantee its availability for future replay. """ handle: str file_uuid: str path: str = field(metadata={"description": "Clean absolute destination path."}) unpack: bool replace: bool merge: bool bytes: int = field( metadata={ "description": ( "Source bytes consumed from the upload pipe, including on " "failure.\nFor an archive, counts compressed/source bytes, not " "extracted bytes.\nThis is not a count of bytes successfully published " "to the destination." ) } ) status: Literal["success", "error", "cancelled", "timeout"] error: str | None = field( metadata={"description": "Error category only; null on success."} )
[docs] @dataclass class EventDataInit(ContreeModel): """Operation-level startup snapshot. ``hostname``, ``kernel``,. ``machine``, ``boot_id`` are best-effort — omitted if the environment couldn't provide them. """ started_at: datetime = field(metadata={"example": "2026-06-08T20:00:00.000000000Z"}) runtime_path: str = field( metadata={ "description": "Internal runtime directory for the operation.", "example": "/run/contreeinitd", } ) verbose: bool = field(metadata={"example": False}) init_pid: int = field( metadata={"description": "PID of the operation's init process.", "example": 1} ) hostname: str | EllipsisType = field(default=..., metadata={"example": "vm-abc123"}) kernel: str | EllipsisType = field( default=..., metadata={ "description": "uname release + version, space-separated.", "example": "6.10.0-generic #1 SMP PREEMPT", }, ) machine: str | EllipsisType = field(default=..., metadata={"example": "x86_64"}) boot_id: str | EllipsisType = field( default=..., metadata={ "description": "Operation-unique boot identifier.", "example": "5e0a3f24-7c2d-4f50-8e1d-9b3c8d7e6a4f", }, )
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "started_at": parse_datetime(data["started_at"]), "runtime_path": data["runtime_path"], "verbose": data["verbose"], "init_pid": data["init_pid"], "hostname": data.get("hostname", ...), "kernel": data.get("kernel", ...), "machine": data.get("machine", ...), "boot_id": data.get("boot_id", ...), }
[docs] @dataclass class EventDataSpawn(ContreeModel): """Process spawn parameters. ``env`` values for keys ending in. TOKEN/SECRET/PASSWORD/API_KEY/CREDENTIALS/AUTHORIZATION are replaced with the literal string ``<MASKED>`` before emission. """ pid: int = field( metadata={"description": "PID assigned to the process.", "example": 4242} ) command: str = field(metadata={"example": "/bin/sh"}) args: list[str] = field(metadata={"example": ["-c", "echo hi"]}) shell: bool = field( metadata={ "description": ( "If true, the command is wrapped in `<shell> -c <command>`\n(so the " "args / command may differ from the user's input)." ), "example": True, } ) cwd: str = field(metadata={"example": "/work"}) uid: int = field(metadata={"example": 1000}) gid: int = field(metadata={"example": 1000}) timeout: int = field( metadata={ "description": "Per-process SIGKILL deadline in seconds.", "example": 60, } ) truncate_at: int = field( metadata={ "description": ( "Per-stream cap (bytes) above which stdout/stderr/stdin\nchunks stop " "being emitted and the stream's `truncated`\nevent fires on EOF." ), "example": 1048576, } ) resources_limits: ProcessResourcesLimits | EllipsisType = ... cpu_affinity: list[int] | EllipsisType = field( default=..., metadata={ "description": "Effective guest vCPU IDs available to this process tree." }, ) env: dict[str, str] | EllipsisType = field( default=..., metadata={ "description": ( "Environment as passed to the process. Values for\nsecret-suffix keys " "are replaced with `<MASKED>`." ), "example": {"PATH": "/usr/bin:/bin", "DATABASE_PASSWORD": "<MASKED>"}, }, )
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "pid": data["pid"], "command": data["command"], "args": data["args"], "shell": data["shell"], "cwd": data["cwd"], "uid": data["uid"], "gid": data["gid"], "timeout": data["timeout"], "truncate_at": data["truncate_at"], "resources_limits": ( ProcessResourcesLimits.from_dict(data["resources_limits"]) ) if data.get("resources_limits") is not None else data.get("resources_limits", ...), "cpu_affinity": data.get("cpu_affinity", ...), "env": data.get("env", ...), }
[docs] @dataclass class EventDataStream(ContreeModel): """Payload for ``stdin`` / ``stdout`` / ``stderr`` events. Encoding. is ``ascii`` when every byte is printable plus ``\\\\n`` / ``\\\\r`` / ``\\\\t``; ``base64`` otherwise. Chunks are at most a few KB each — the natural read granularity from a pipe. """ value: str = field(metadata={"example": "hello world\n"}) encoding: Literal["ascii", "base64"] = field(metadata={"example": "ascii"}) truncated: bool | EllipsisType = field( default=..., metadata={ "description": ( "Always `false` on per-chunk stream events. When a stream\ncrosses " "its per-stream cap a separate `truncated`-type\nevent is emitted on " "EOF carrying the cumulative\nemitted/dropped totals." ), "example": False, }, )
[docs] def as_bytes(self) -> bytes: """The payload decoded to raw bytes. ``base64`` values are decoded; ``ascii`` text is UTF-8 encoded. Undecodable base64 becomes empty bytes instead of failing a live stream. """ if not self.value: return b"" if self.encoding == "base64": try: return base64.b64decode(self.value) except (binascii.Error, ValueError): return b"" return self.value.encode("utf-8", errors="replace")
[docs] def as_text(self) -> str: """The payload decoded to text (UTF-8, errors replaced).""" if self.encoding == "base64": return self.as_bytes().decode("utf-8", errors="replace") return self.value
__str__ = as_text
[docs] @classmethod def from_bytes(cls, value: bytes) -> EventDataStream: """Build a payload from raw bytes. Printable ASCII (plus tab/newline/carriage return) is stored as ``ascii``; anything else is base64-encoded - the same rule the server applies on its side. """ if all(32 <= byte < 127 or byte in (9, 10, 13) for byte in value): return cls(value=value.decode("ascii"), encoding="ascii") return cls( value=base64.b64encode(value).decode("ascii"), encoding="base64", )
[docs] @classmethod def from_text(cls, value: str) -> EventDataStream: """Build a payload from text (UTF-8 encoded unless ASCII).""" return cls.from_bytes(value.encode("utf-8"))
[docs] @dataclass class EventResources(ContreeModel): """Resource usage snapshot for the process. Time fields are. in microseconds; memory in kilobytes (max_rss_kb) or platform-specific units (shared_memory / unshared_memory). Some kernels populate fewer fields than others; expect zeroes for unsupported counters. """ user_time_us: int sys_time_us: int max_rss_kb: int shared_memory: int unshared_memory: int swaps: int minor_faults: int major_faults: int voluntary_ctx_switches: int involuntary_ctx_switches: int block_input_ops: int block_output_ops: int ipc_msgs_sent: int ipc_msgs_received: int signals_received: int
[docs] @dataclass class EventDataExit(ContreeModel): """Process lifecycle close-out. Carries the exit code OR the. kill signal (signal = -1 means normal exit), the ``timed_out`` flag (true only when the process's per-process timeout fired — distinguishes from an external signal/kill), wall-clock duration, and a snapshot of resource usage. """ pid: int = field( metadata={ "description": "PID of the process that just exited.", "example": 4242, } ) code: int = field( metadata={ "description": ( "Exit code (0..255) if the process exited normally; -1 if killed by " "signal." ), "example": 0, } ) signal: int = field( metadata={ "description": "Signal number if killed by signal; -1 if normal exit.", "example": -1, } ) timed_out: bool = field( metadata={ "description": ( "True only if the process's own timeout fired the kill.\nAn " "externally-driven kill (`signal` / `kill` / cancel)\nleaves " "`timed_out=false`." ), "example": False, } ) duration_ms: int = field( metadata={"description": "Wall-clock time from spawn to exit.", "example": 1234} ) resources: EventResources oom_killed: bool | EllipsisType = field( default=..., metadata={ "description": ( "An OOM kill was observed in this process tree. Missing in older " "events." ), "default": False, }, ) core_dump: bool | EllipsisType = field( default=..., metadata={ "description": ( "True when the terminating signal produced a core dump.\nAbsent in " "events recorded before the field was added —\ntreat missing as false." ), "example": False, }, )
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "pid": data["pid"], "code": data["code"], "signal": data["signal"], "timed_out": data["timed_out"], "duration_ms": data["duration_ms"], "resources": EventResources.from_dict(data["resources"]), "oom_killed": data.get("oom_killed", ...), "core_dump": data.get("core_dump", ...), }
[docs] @dataclass class EventDataTruncated(ContreeModel): """Per-stream summary emitted once on stream EOF when the. stream's ``truncate_at`` cap was crossed during its lifetime. Carries the final cumulative emitted/dropped totals (not partial numbers at cap-hit time). Absent if the stream never crossed the cap. """ stream: Literal["stdin", "stdout", "stderr"] = field(metadata={"example": "stdout"}) bytes_emitted: int = field( metadata={ "description": "Bytes that were delivered before the cap kicked in.", "example": 1048576, } ) bytes_dropped: int = field( metadata={ "description": ( "Bytes consumed from the producer but suppressed by the cap." ), "example": 4096, } )
[docs] @dataclass class EventDataSizeCap(ContreeModel): """Emitted at most once per operation when the cumulative. event-log size approached its budget. After this marker, further stream events (``stdin`` / ``stdout`` / ``stderr``) are dropped; service events continue so the lifecycle stays observable. """ limit_bytes: int = field( metadata={ "description": "Size budget at which dropping kicked in.", "example": 104857600, } ) file_size: int = field( metadata={ "description": "Approximate cumulative event-log size at cap-hit.", "example": 104800000, } )
[docs] @dataclass class NetworkInterface(ContreeModel): name: str = field(metadata={"example": "eth0"}) rx_bytes: int rx_packets: int rx_errs: int rx_drop: int tx_bytes: int tx_packets: int tx_errs: int tx_drop: int
[docs] @dataclass class EventDataNetworkConfigured(ContreeModel): """Subset of network params that were applied — empty keys. are omitted, so the object only carries what was requested. """ ip4: str | EllipsisType = field(default=..., metadata={"example": "10.0.0.5/24"}) ip4_gw: str | EllipsisType = field(default=..., metadata={"example": "10.0.0.1"}) ip6: str | EllipsisType = field(default=..., metadata={"example": "fc10:c0::33/64"}) ip6_gw: str | EllipsisType = field(default=..., metadata={"example": "fc10:c0::1"}) gw_mac: str | EllipsisType = field( default=..., metadata={ "description": "Gateway MAC address.", "example": "ee:d0:a7:48:b5:98", }, ) nameserver: str | EllipsisType = field(default=..., metadata={"example": "8.8.8.8"})
[docs] @dataclass class EventDataNetwork(ContreeModel): """Per-interface counters plus the configured network state. Emitted once at the end of the network setup phase, so the counters represent the initial baseline. Absent entirely for network-less operations. """ interfaces: list[NetworkInterface] configured: EventDataNetworkConfigured | EllipsisType = field( default=..., metadata={ "description": ( "Subset of network params that were applied — empty keys\nare omitted, " "so the object only carries what was\nrequested." ) }, ) error: str | EllipsisType = field( default=..., metadata={ "description": ( "Set if the per-interface counter read failed;\n`interfaces` then " "holds an empty list. Best-effort —\nfailure does not block shutdown." ) }, )
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "interfaces": [ NetworkInterface.from_dict(item) for item in data["interfaces"] ], "configured": (EventDataNetworkConfigured.from_dict(data["configured"])) if data.get("configured") is not None else data.get("configured", ...), "error": data.get("error", ...), }
[docs] @dataclass class EventDataShutdown(ContreeModel): """Stream-terminating marker emitted right before the operation. winds down. Distinct from the ``network`` event so consumers can recognize a clean shutdown without parsing payload- specific data. """ stopped_at: datetime = field(metadata={"example": "2026-06-08T20:01:34.567890123Z"}) reason: Literal["job_complete", "timeout", "spawn_failed", "signal"] = field( metadata={ "description": ( "Short categorical reason for the shutdown:\n * `job_complete` — " "process exited normally;\n * `timeout` — the operation timeout " "fired;\n * `spawn_failed` — the process couldn't be started;\n * " "`signal` — terminated by an external signal.\nAdditional categories " "may be added." ) } )
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "stopped_at": parse_datetime(data["stopped_at"]), "reason": data["reason"], }
[docs] @dataclass class EventDataCompletion(ContreeModel): """Terminal system-event payload, emitted once when the. operation reaches one of ``SUCCESS``, ``FAILED``, ``CANCELLED``. Carries the operation outcome and rollup counters for the log + image artifacts. Always the last event in the log; the event itself has no ``spid`` (operation-scoped, not process-scoped). """ status: OperationStatus = field( metadata={"description": "Terminal operation status."} ) duration_ms: int = field( metadata={ "description": "Wall-clock duration of the handler in milliseconds.", "example": 4327, } ) result_image_uuid: str | None | EllipsisType = field( default=..., metadata={ "description": ( "UUID of the result image the operation produced.\nPresent on every " "SUCCESS that persists an image — for\nruns that wrote no new layer, " "this is the image UUID the\noperation was spawned from (per the " "spec). Distinct\nfrom the spec uuid only when persist produced a " "new\nimage. ``null`` for disposable runs (no image was\npersisted at " "all) and for FAILED / CANCELLED outcomes." ), "example": "019eef27-7ecb-7771-8184-aaf5fa596ce2", }, ) error: str | None | EllipsisType = field( default=..., metadata={ "description": ( "Short human-readable error message when ``status`` is\n``FAILED`` or " "``CANCELLED``. ``null`` on success." ), "example": "spawn failed: exec /run/entrypoint: no such file", }, ) image_size_bytes: int | EllipsisType = field( default=..., metadata={ "description": ( "Size of the result image's runtime layer in bytes.\n``0`` for " "failed/cancelled operations and for\ndisposables (no image persisted)." ), "example": 134217728, }, ) consumed_cpu: float | None | EllipsisType = field( default=..., metadata={ "description": ( "Total CPU time consumed by the operation, in seconds; null when " "unmeasured." ) }, ) consumed_memory: int | None | EllipsisType = field( default=..., metadata={ "description": ( "Peak resident memory used by the operation's execution environment, " "in KiB; null when unmeasured." ) }, )
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "status": OperationStatus(data["status"]), "duration_ms": data["duration_ms"], "result_image_uuid": data.get("result_image_uuid", ...), "error": data.get("error", ...), "image_size_bytes": data.get("image_size_bytes", ...), "consumed_cpu": data.get("consumed_cpu", ...), "consumed_memory": data.get("consumed_memory", ...), }
[docs] @dataclass class ListNetworkPolicyTagsResponse(ContreeModel): tags: list[NetworkPolicyTag]
[docs] @classmethod def parse_fields(cls, data: dict[str, Any]) -> dict[str, Any]: return { "tags": [NetworkPolicyTag.from_dict(item) for item in data["tags"]], }
EventData = ( EventDataInit | EventDataSpawn | EventDataStream | EventDataExit | EventDataTruncated | EventDataSizeCap | EventDataNetwork | EventDataShutdown | EventDataInspect | EventDataFileUpload | EventDataCompletion ) EVENT_DATA_PARSERS: dict[str, Callable[[dict[str, Any]], EventData]] = { "init": EventDataInit.from_dict, "spawn": EventDataSpawn.from_dict, "stdin": EventDataStream.from_dict, "stdout": EventDataStream.from_dict, "stderr": EventDataStream.from_dict, "exit": EventDataExit.from_dict, "truncated": EventDataTruncated.from_dict, "size_cap": EventDataSizeCap.from_dict, "network": EventDataNetwork.from_dict, "shutdown": EventDataShutdown.from_dict, "inspect": EventDataInspect.from_dict, "file_upload": EventDataFileUpload.from_dict, "completion": EventDataCompletion.from_dict, }
[docs] def parse_event_data( event_type: str, data: Any, ) -> EventData | Any: """Decode a per-type event payload. Unknown event types and payloads that do not match the documented schema - a non-mapping body included - are returned as-is instead of failing the stream. """ if not isinstance(data, dict): return data parser = EVENT_DATA_PARSERS.get(event_type) if parser is None: return data try: return parser(data) except (KeyError, TypeError, ValueError): return data
[docs] def decode_chunk(data: object) -> bytes: """Decode a stdout/stderr event payload to raw bytes. Typed payloads delegate to :meth:`EventDataStream.as_bytes`; the raw dict a lenient event parse may leave behind is decoded the same way, and anything else becomes empty bytes instead of failing a live stream. """ if isinstance(data, (EventDataStream, StreamRepr)): return data.as_bytes() if not isinstance(data, dict): return b"" value = data.get("value", "") if not isinstance(value, str) or not value: return b"" if str(data.get("encoding", "ascii")) == "base64": with suppress(binascii.Error, ValueError): return base64.b64decode(value) return b"" return value.encode("utf-8", errors="replace")
[docs] def decode_stream(stream: StreamRepr | dict[str, Any] | None) -> str: """Decode a ``StreamRepr`` payload (model or raw dict) to a string.""" if isinstance(stream, (EventDataStream, StreamRepr)): return stream.as_text() if not isinstance(stream, dict): return "" value = stream.get("value", "") if not isinstance(value, str) or not value: return "" if stream.get("encoding") == "base64": with suppress(binascii.Error, ValueError): return base64.b64decode(value).decode("utf-8", errors="replace") return "" return value