Skip to content

Nexus sample #174

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 10 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions hello_nexus/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from rich.traceback import install

install(show_locals=True)
72 changes: 72 additions & 0 deletions hello_nexus/caller/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import asyncio
import sys
from typing import Any, Type

from temporalio.client import Client
from temporalio.worker import UnsandboxedWorkflowRunner, Worker

interrupt_event = asyncio.Event()


async def execute_workflow(workflow_cls: Type[Any], input: Any) -> None:
client = await Client.connect(
"localhost:7233", namespace="my-caller-namespace-python"
)
task_queue = "my-caller-task-queue"

async with Worker(
client,
task_queue=task_queue,
workflows=[workflow_cls],
workflow_runner=UnsandboxedWorkflowRunner(),
):
print("🟠 Caller worker started")
result = await client.execute_workflow(
workflow_cls.run,
input,
id="my-caller-workflow-id",
task_queue=task_queue,
)
print("🟢 workflow result:", result)


if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: python -m nexus.caller.app [echo|hello] [impl|interface]")
sys.exit(1)

[wf_name, impl_or_interface] = sys.argv[1:]

if impl_or_interface == "impl":
from hello_nexus.caller.workflows_via_impl import (
Echo2CallerWorkflow,
Echo3CallerWorkflow,
EchoCallerWorkflow,
Hello2CallerWorkflow,
HelloCallerWorkflow,
)
elif impl_or_interface == "interface":
from hello_nexus.caller.workflows_via_interface import (
Echo2CallerWorkflow,
Echo3CallerWorkflow,
EchoCallerWorkflow,
Hello2CallerWorkflow,
HelloCallerWorkflow,
)
else:
raise ValueError(f"Invalid impl_or_interface: {impl_or_interface}")

fn = {
"echo": lambda: execute_workflow(EchoCallerWorkflow, "hello"),
"echo2": lambda: execute_workflow(Echo2CallerWorkflow, "hello"),
"echo3": lambda: execute_workflow(Echo3CallerWorkflow, "hello"),
"hello": lambda: execute_workflow(HelloCallerWorkflow, "world"),
"hello2": lambda: execute_workflow(Hello2CallerWorkflow, "world"),
}[wf_name]

loop = asyncio.new_event_loop()
try:
loop.run_until_complete(fn())
except KeyboardInterrupt:
interrupt_event.set()
loop.run_until_complete(loop.shutdown_asyncgens())
93 changes: 93 additions & 0 deletions hello_nexus/caller/workflows_via_impl.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
from datetime import timedelta

import xray
from temporalio import workflow
from temporalio.exceptions import FailureError
from temporalio.workflow import NexusClient

from hello_nexus.handler.nexus_service import (
EchoInput,
EchoOutput,
HelloInput,
HelloOutput,
MyNexusService,
)


class CallerWorkflowBase:
def __init__(self):
self.nexus_client = NexusClient(
MyNexusService, # or string name "my-nexus-service",
"my-nexus-endpoint-name-python",
schedule_to_close_timeout=timedelta(seconds=30),
)


@workflow.defn
class EchoCallerWorkflow(CallerWorkflowBase):
@xray.start_as_current_workflow_method_span()
@workflow.run
async def run(self, message: str) -> EchoOutput:
op_output = await self.nexus_client.execute_operation(
MyNexusService.echo,
EchoInput(message),
)
return op_output


@workflow.defn
class Echo2CallerWorkflow(CallerWorkflowBase):
@xray.start_as_current_workflow_method_span()
@workflow.run
async def run(self, message: str) -> EchoOutput:
op_output = await self.nexus_client.execute_operation(
MyNexusService.echo2,
EchoInput(message),
)
return op_output


@workflow.defn
class Echo3CallerWorkflow(CallerWorkflowBase):
@xray.start_as_current_workflow_method_span()
@workflow.run
async def run(self, message: str) -> EchoOutput:
op_output = await self.nexus_client.execute_operation(
MyNexusService.echo3,
EchoInput(message),
)
return op_output


@workflow.defn
class HelloCallerWorkflow(CallerWorkflowBase):
@xray.start_as_current_workflow_method_span()
@workflow.run
async def run(self, name: str) -> HelloOutput:
handle = await self.nexus_client.start_operation(
MyNexusService.hello,
HelloInput(name),
)
assert handle.cancel()
try:
await handle
except FailureError:
handle = await self.nexus_client.start_operation(
MyNexusService.hello,
HelloInput(name),
)
result = await handle
return result
raise AssertionError("Expected Nexus operation to be cancelled")


@workflow.defn
class Hello2CallerWorkflow(CallerWorkflowBase):
@xray.start_as_current_workflow_method_span()
@workflow.run
async def run(self, name: str) -> HelloOutput:
handle = await self.nexus_client.start_operation(
MyNexusService.hello2,
HelloInput(name),
)
return await handle
93 changes: 93 additions & 0 deletions hello_nexus/caller/workflows_via_interface.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
from datetime import timedelta

import xray
from temporalio import workflow
from temporalio.exceptions import FailureError
from temporalio.workflow import NexusClient

from hello_nexus.service.interface import (
EchoInput,
EchoOutput,
HelloInput,
HelloOutput,
MyNexusService,
)


class CallerWorkflowBase:
def __init__(self):
self.nexus_client = NexusClient(
MyNexusService, # or string name "my-nexus-service",
"my-nexus-endpoint-name-python",
schedule_to_close_timeout=timedelta(seconds=30),
)


@workflow.defn
class EchoCallerWorkflow(CallerWorkflowBase):
@xray.start_as_current_workflow_method_span()
@workflow.run
async def run(self, message: str) -> EchoOutput:
op_output = await self.nexus_client.execute_operation(
MyNexusService.echo,
EchoInput(message),
)
return op_output


@workflow.defn
class Echo2CallerWorkflow(CallerWorkflowBase):
@xray.start_as_current_workflow_method_span()
@workflow.run
async def run(self, message: str) -> EchoOutput:
op_output = await self.nexus_client.execute_operation(
MyNexusService.echo2,
EchoInput(message),
)
return op_output


@workflow.defn
class Echo3CallerWorkflow(CallerWorkflowBase):
@xray.start_as_current_workflow_method_span()
@workflow.run
async def run(self, message: str) -> EchoOutput:
op_output = await self.nexus_client.execute_operation(
MyNexusService.echo3,
EchoInput(message),
)
return op_output


@workflow.defn
class HelloCallerWorkflow(CallerWorkflowBase):
@xray.start_as_current_workflow_method_span()
@workflow.run
async def run(self, name: str) -> HelloOutput:
handle = await self.nexus_client.start_operation(
MyNexusService.hello,
HelloInput(name),
)
assert handle.cancel()
try:
await handle
except FailureError:
handle = await self.nexus_client.start_operation(
MyNexusService.hello,
HelloInput(name),
)
result = await handle
return result
raise AssertionError("Expected Nexus operation to be cancelled")


@workflow.defn
class Hello2CallerWorkflow(CallerWorkflowBase):
@xray.start_as_current_workflow_method_span()
@workflow.run
async def run(self, name: str) -> HelloOutput:
handle = await self.nexus_client.start_operation(
MyNexusService.hello2,
HelloInput(name),
)
return await handle
14 changes: 14 additions & 0 deletions hello_nexus/clean
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
temporal-delete-all my-target-namespace-python
temporal-delete-all my-caller-namespace-python

temporal operator namespace create --namespace my-target-namespace-python
temporal operator namespace create --namespace my-caller-namespace-python

sleep 1

temporal operator nexus endpoint create \
--name my-nexus-endpoint-name-python \
--target-namespace my-target-namespace-python \
--target-task-queue my-target-task-queue-python \
--description-file ./hello_nexus/service/description.md

14 changes: 14 additions & 0 deletions hello_nexus/handler/activities.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import asyncio

from temporalio import activity

from hello_nexus.service.interface import (
HelloInput,
HelloOutput,
)


@activity.defn
async def hello_activity(input: HelloInput) -> HelloOutput:
await asyncio.sleep(1)
return HelloOutput(message=f"hello {input.name}")
3 changes: 3 additions & 0 deletions hello_nexus/handler/dbclient.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
class MyDBClient:
def execute(self, query: str) -> str:
return "<query result>"
Loading