Builder for a :py:class:`dagger.Module`.
| 64 | |
| 65 | |
| 66 | class Module: |
| 67 | """Builder for a :py:class:`dagger.Module`.""" |
| 68 | |
| 69 | def __init__(self, main_name: str = MAIN_OBJECT): |
| 70 | self._main_name = main_name |
| 71 | self._converter: JsonConverter = make_converter() |
| 72 | self._objects: dict[str, ObjectType] = {} |
| 73 | self._enums: dict[str, type[enum.Enum]] = {} |
| 74 | self._main: ObjectType | None = None |
| 75 | # Escape hatch if there's too much noise from showing stack traces |
| 76 | # from exceptions raised in functions by default. Not documented |
| 77 | # intentionally for now. |
| 78 | self.log_exceptions = True |
| 79 | |
| 80 | @property |
| 81 | def main_cls(self) -> type[ObjectType]: |
| 82 | assert self._main is not None |
| 83 | return self._main.cls |
| 84 | |
| 85 | def is_main(self, other: ObjectType) -> bool: |
| 86 | """Check if the given object is the main object of the module.""" |
| 87 | return self.main_cls is other.cls |
| 88 | |
| 89 | async def serve(self): |
| 90 | if await dag.current_function_call().parent_name(): |
| 91 | result = await self.invoke() |
| 92 | else: |
| 93 | try: |
| 94 | result = await self._typedefs() |
| 95 | except TypeError as e: |
| 96 | raise RegistrationError(str(e)) from e |
| 97 | |
| 98 | try: |
| 99 | output = json.dumps(result) |
| 100 | except (TypeError, ValueError) as e: |
| 101 | # Not expected to happen because unstructuring should reduce |
| 102 | # Python complex types to primitive values that are easily |
| 103 | # serialized to JSON. If not, it's something that should be caught |
| 104 | # earlier. |
| 105 | msg = f"Failed to serialize final result as JSON: {e}" |
| 106 | raise InvalidResultError(msg) from e |
| 107 | |
| 108 | if logger.isEnabledFor(logging.DEBUG): |
| 109 | logger.debug( |
| 110 | "output => %s", |
| 111 | textwrap.shorten(repr(output), 144), |
| 112 | ) |
| 113 | |
| 114 | await dag.current_function_call().return_value(dagger.JSON(output)) |
| 115 | |
| 116 | async def register(self): |
| 117 | """Register the module and its types with the Dagger API.""" |
| 118 | try: |
| 119 | result = await self._typedefs() |
| 120 | output = json.dumps(result) |
| 121 | except TypeError as e: |
| 122 | raise RegistrationError(str(e), e) from e |
| 123 | await anyio.Path(TYPE_DEF_FILE).write_text(output) |
no outgoing calls