|
| 1 | +# |
| 2 | +# Copyright (c) 2023-2024 - Restate Software, Inc., Restate GmbH |
| 3 | +# |
| 4 | +# This file is part of the Restate SDK for Python, |
| 5 | +# which is released under the MIT license. |
| 6 | +# |
| 7 | +# You can find a copy of the license in file LICENSE in the root |
| 8 | +# directory of this repository or package, or at |
| 9 | +# https://github.com/restatedev/sdk-typescript/blob/main/LICENSE |
| 10 | +# |
| 11 | +"""example.py""" |
| 12 | +# pylint: disable=C0116 |
| 13 | +# pylint: disable=W0613 |
| 14 | +# pylint: disable=W0622 |
| 15 | + |
| 16 | +from restate import VirtualObject, ObjectContext |
| 17 | +from restate.exceptions import TerminalError |
| 18 | + |
| 19 | +failing = VirtualObject("Failing") |
| 20 | + |
| 21 | +@failing.handler(name="terminallyFailingCall") |
| 22 | +async def terminally_failing_call(ctx: ObjectContext, msg: str): |
| 23 | + raise TerminalError(message=msg) |
| 24 | + |
| 25 | +@failing.handler(name="callTerminallyFailingCall") |
| 26 | +async def call_terminally_failing_call(ctx: ObjectContext, msg: str) -> str: |
| 27 | + await ctx.object_call(terminally_failing_call, key="random-583e1bf2", arg=msg) |
| 28 | + |
| 29 | + raise Exception("Should not reach here") |
| 30 | + |
| 31 | +failures = 0 |
| 32 | + |
| 33 | +@failing.handler(name="failingCallWithEventualSuccess") |
| 34 | +async def failing_call_with_eventual_success(ctx: ObjectContext) -> int: |
| 35 | + global failures |
| 36 | + failures += 1 |
| 37 | + if failures >= 4: |
| 38 | + failures = 0 |
| 39 | + return 4 |
| 40 | + raise ValueError(f"Failed at attempt: {failures}") |
| 41 | + |
| 42 | + |
| 43 | +side_effect_failures = 0 |
| 44 | + |
| 45 | +@failing.handler(name="failingSideEffectWithEventualSuccess") |
| 46 | +async def failing_side_effect_with_eventual_success(ctx: ObjectContext) -> int: |
| 47 | + |
| 48 | + def side_effect(): |
| 49 | + global side_effect_failures |
| 50 | + side_effect_failures += 1 |
| 51 | + if side_effect_failures >= 4: |
| 52 | + side_effect_failures = 0 |
| 53 | + return 4 |
| 54 | + raise ValueError(f"Failed at attempt: {side_effect_failures}") |
| 55 | + |
| 56 | + return await ctx.run("sideEffect", side_effect) # type: ignore |
| 57 | + |
| 58 | + |
| 59 | +@failing.handler(name="terminallyFailingSideEffect") |
| 60 | +async def terminally_failing_side_effect(ctx: ObjectContext): |
| 61 | + |
| 62 | + def side_effect(): |
| 63 | + raise TerminalError(message="Terminally failing side effect") |
| 64 | + |
| 65 | + await ctx.run("sideEffect", side_effect) |
| 66 | + raise ValueError("Should not reach here") |
0 commit comments