|
| 1 | +import asyncio |
| 2 | +from dataclasses import dataclass |
| 3 | +from datetime import timedelta |
| 4 | +from typing import List, Optional |
| 5 | + |
| 6 | +from temporalio import workflow |
| 7 | +from temporalio.exceptions import ApplicationError |
| 8 | + |
| 9 | +with workflow.unsafe.imports_passed_through(): |
| 10 | + from message_passing.introduction import Language |
| 11 | + from message_passing.introduction.activities import call_greeting_service |
| 12 | + |
| 13 | + |
| 14 | +@dataclass |
| 15 | +class GetLanguagesInput: |
| 16 | + include_unsupported: bool |
| 17 | + |
| 18 | + |
| 19 | +@dataclass |
| 20 | +class ApproveInput: |
| 21 | + name: str |
| 22 | + |
| 23 | + |
| 24 | +@workflow.defn |
| 25 | +class GreetingWorkflow: |
| 26 | + """ |
| 27 | + A workflow that that returns a greeting in one of two languages. |
| 28 | +
|
| 29 | + It supports a Query to obtain the current language, an Update to change the |
| 30 | + current language and receive the previous language in response, and a Signal |
| 31 | + to approve the Workflow so that it is allowed to return its result. |
| 32 | + """ |
| 33 | + |
| 34 | + # 👉 This Workflow does not use any async handlers and so cannot use any |
| 35 | + # Activities. It only supports two languages, whose greetings are hardcoded |
| 36 | + # in the Workflow definition. See GreetingWorkflowWithAsyncHandler below for |
| 37 | + # a Workflow that uses an async Update handler to call an Activity. |
| 38 | + |
| 39 | + def __init__(self) -> None: |
| 40 | + self.approved_for_release = False |
| 41 | + self.approver_name: Optional[str] = None |
| 42 | + self.greetings = { |
| 43 | + Language.CHINESE: "你好,世界", |
| 44 | + Language.ENGLISH: "Hello, world", |
| 45 | + } |
| 46 | + self.language = Language.ENGLISH |
| 47 | + self.lock = asyncio.Lock() # used by the async handler below |
| 48 | + |
| 49 | + @workflow.run |
| 50 | + async def run(self) -> str: |
| 51 | + # 👉 In addition to waiting for the `approve` Signal, we also wait for |
| 52 | + # all handlers to finish. Otherwise, the Workflow might return its |
| 53 | + # result while an async set_language_using_activity Update is in |
| 54 | + # progress. |
| 55 | + await workflow.wait_condition( |
| 56 | + lambda: self.approved_for_release and workflow.all_handlers_finished() |
| 57 | + ) |
| 58 | + return self.greetings[self.language] |
| 59 | + |
| 60 | + @workflow.query |
| 61 | + def get_languages(self, input: GetLanguagesInput) -> List[Language]: |
| 62 | + # 👉 A Query handler returns a value: it can inspect but must not mutate the Workflow state. |
| 63 | + if input.include_unsupported: |
| 64 | + return sorted(Language) |
| 65 | + else: |
| 66 | + return sorted(self.greetings) |
| 67 | + |
| 68 | + @workflow.signal |
| 69 | + def approve(self, input: ApproveInput) -> None: |
| 70 | + # 👉 A Signal handler mutates the Workflow state but cannot return a value. |
| 71 | + self.approved_for_release = True |
| 72 | + self.approver_name = input.name |
| 73 | + |
| 74 | + @workflow.update |
| 75 | + def set_language(self, language: Language) -> Language: |
| 76 | + # 👉 An Update handler can mutate the Workflow state and return a value. |
| 77 | + previous_language, self.language = self.language, language |
| 78 | + return previous_language |
| 79 | + |
| 80 | + @set_language.validator |
| 81 | + def validate_language(self, language: Language) -> None: |
| 82 | + if language not in self.greetings: |
| 83 | + # 👉 In an Update validator you raise any exception to reject the Update. |
| 84 | + raise ValueError(f"{language.name} is not supported") |
| 85 | + |
| 86 | + @workflow.update |
| 87 | + async def set_language_using_activity(self, language: Language) -> Language: |
| 88 | + # 👉 This update handler is async, so it can execute an activity. |
| 89 | + if language not in self.greetings: |
| 90 | + # 👉 We use a lock so that, if this handler is executed multiple |
| 91 | + # times, each execution can schedule the activity only when the |
| 92 | + # previously scheduled activity has completed. This ensures that |
| 93 | + # multiple calls to set_language are processed in order. |
| 94 | + async with self.lock: |
| 95 | + greeting = await workflow.execute_activity( |
| 96 | + call_greeting_service, |
| 97 | + language, |
| 98 | + start_to_close_timeout=timedelta(seconds=10), |
| 99 | + ) |
| 100 | + if greeting is None: |
| 101 | + # 👉 An update validator cannot be async, so cannot be used |
| 102 | + # to check that the remote call_greeting_service supports |
| 103 | + # the requested language. Raising ApplicationError will fail |
| 104 | + # the Update, but the WorkflowExecutionUpdateAccepted event |
| 105 | + # will still be added to history. |
| 106 | + raise ApplicationError( |
| 107 | + f"Greeting service does not support {language.name}" |
| 108 | + ) |
| 109 | + self.greetings[language] = greeting |
| 110 | + previous_language, self.language = self.language, language |
| 111 | + return previous_language |
| 112 | + |
| 113 | + @workflow.query |
| 114 | + def get_language(self) -> Language: |
| 115 | + return self.language |
0 commit comments