Skip to content

Nexus samples #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

Open
wants to merge 34 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
656744a
Nexus samples
dandavison Feb 20, 2025
668c2e2
Install SDKs from github
dandavison Jun 9, 2025
e8e163e
Change to endpoint_description.md
dandavison Jun 9, 2025
80cef7b
Revert "Install SDKs from github"
dandavison Jun 9, 2025
5f92777
Get rid of type hint
dandavison Jun 9, 2025
c72c596
Remove unnecessary re-imports
dandavison Jun 9, 2025
c595f3a
Fix test
dandavison Jun 9, 2025
2e47c37
Update to use Temporal operation contexts
dandavison Jun 12, 2025
c7d0c4b
Emphasize that StartOperationContext is from Temporal
dandavison Jun 12, 2025
4af30cb
s/target/handler/
dandavison Jun 19, 2025
2e8467b
Respond to upstream rename
dandavison Jun 19, 2025
141166e
Respond to upstream: NexusStartWorkflowRequest
dandavison Jun 22, 2025
238824a
Respond to upstream: tctc.start_workflow -> WorkflowOperationToken
dandavison Jun 22, 2025
7cda991
Respond to upstream: use factories instead of decorators
dandavison Jun 23, 2025
8a80ba7
uv.lock
dandavison Jun 23, 2025
37427dd
Respond to upstream: temporal_operation_context
dandavison Jun 24, 2025
7c7abad
Respond to upstream: top-level start_workflow function
dandavison Jun 24, 2025
89137cf
Respond to upstream: from_callable, inherit from abstract base class
dandavison Jun 25, 2025
f6e83e0
Cleanup
dandavison Jun 25, 2025
bd721db
Respond to upstream
dandavison Jun 26, 2025
de4d0d5
Delete operations-as-classes sample
dandavison Jun 26, 2025
dbe1be1
Respond to upstream: rename decorators
dandavison Jun 26, 2025
8a31588
Rename service class
dandavison Jun 26, 2025
7652961
Cleanup
dandavison Jun 26, 2025
ef9af75
RTU: dependencies
dandavison Jun 26, 2025
95f7f0d
Pass through imports
dandavison Jun 26, 2025
44bea2d
Fix directory paths in README
dandavison Jun 26, 2025
9a77b92
Make namespace/task queue/enspoint names sample-specific
dandavison Jun 26, 2025
8c26601
RTU: ctx.start_workflow()
dandavison Jun 26, 2025
06596e3
Delete no-service-definition sample
dandavison Jun 26, 2025
fd7cb47
Reorganize
dandavison Jun 26, 2025
4273b91
Enable sandbox in Nexus sample
dandavison Jun 26, 2025
7a300fc
uv.lock
dandavison Jun 27, 2025
837d0f8
uv.lock
dandavison Jun 30, 2025
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
37 changes: 37 additions & 0 deletions hello_nexus/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
This sample shows how to define a Nexus service, implement the operation handlers, and
call the operations from a workflow.

### Sample directory structure

- [service.py](./service.py) - shared Nexus service definition
- [caller](./caller) - a caller workflow that executes Nexus operations, together with a worker and starter code
- [handler](./handler) - Nexus operation handlers, together with a workflow used by one of the Nexus operations, and a worker that polls for both workflow and Nexus tasks.


### Instructions

Start a Temporal server. (See the main samples repo [README](../README.md)).

Run the following:

```
temporal operator namespace create --namespace hello-nexus-basic-handler-namespace
temporal operator namespace create --namespace hello-nexus-basic-caller-namespace

temporal operator nexus endpoint create \
--name hello-nexus-basic-nexus-endpoint \
--target-namespace hello-nexus-basic-handler-namespace \
--target-task-queue my-handler-task-queue \
--description-file endpoint_description.md
```

In one terminal, in this directory, run the Temporal worker in the handler namespace:
```
uv run handler/worker.py
```

In another terminal, in this directory, run the Temporal worker in the caller namespace and start the caller
workflow:
```
uv run caller/app.py
```
Empty file added hello_nexus/__init__.py
Empty file.
Empty file.
43 changes: 43 additions & 0 deletions hello_nexus/caller/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import asyncio
import uuid
from typing import Optional

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

from hello_nexus.caller.workflows import CallerWorkflow
from hello_nexus.service import MyOutput

NAMESPACE = "hello-nexus-basic-caller-namespace"
TASK_QUEUE = "hello-nexus-basic-caller-task-queue"


async def execute_caller_workflow(
client: Optional[Client] = None,
) -> tuple[MyOutput, MyOutput]:
client = client or await Client.connect(
"localhost:7233",
namespace=NAMESPACE,
)

async with Worker(
client,
task_queue=TASK_QUEUE,
workflows=[CallerWorkflow],
):
return await client.execute_workflow(
CallerWorkflow.run,
arg="world",
id=str(uuid.uuid4()),
task_queue=TASK_QUEUE,
)


if __name__ == "__main__":
loop = asyncio.new_event_loop()
try:
results = loop.run_until_complete(execute_caller_workflow())
for output in results:
print(output.message)
except KeyboardInterrupt:
loop.run_until_complete(loop.shutdown_asyncgens())
36 changes: 36 additions & 0 deletions hello_nexus/caller/workflows.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
from temporalio import workflow
from temporalio.workflow import NexusClient

with workflow.unsafe.imports_passed_through():
from hello_nexus.service import MyInput, MyNexusService, MyOutput

NEXUS_ENDPOINT = "hello-nexus-basic-nexus-endpoint"


# This is a workflow that calls a nexus operation.
@workflow.defn
class CallerWorkflow:
# An __init__ method is always optional on a Workflow class. Here we use it to set the
# NexusClient, but that could alternatively be done in the run method.
def __init__(self):
self.nexus_client = NexusClient(
MyNexusService,
endpoint=NEXUS_ENDPOINT,
)

# The Wokflow run method invokes two Nexus operations.
@workflow.run
async def run(self, name: str) -> tuple[MyOutput, MyOutput]:
# Start the Nexus operation and wait for the result in one go, using execute_operation.
wf_result = await self.nexus_client.execute_operation(
MyNexusService.my_workflow_run_operation,
MyInput(name),
)
# We could use execute_operation for this one also, but here we demonstrate
# obtaining the operation handle and then using it to get the result.
sync_operation_handle = await self.nexus_client.start_operation(
MyNexusService.my_sync_operation,
MyInput(name),
)
sync_result = await sync_operation_handle
return sync_result, wf_result
3 changes: 3 additions & 0 deletions hello_nexus/endpoint_description.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## Service: [MyNexusService](https://github.com/temporalio/samples-python/blob/main/hello_nexus/basic/service.py)
- operation: `my_sync_operation`
- operation: `my_workflow_run_operation`
Empty file.
23 changes: 23 additions & 0 deletions hello_nexus/handler/db_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from __future__ import annotations


class MyDBClient:
"""
This class represents a resource that your Nexus operation handlers may need when they
are handling Nexus requests, but which is only available when the Nexus worker is
started. Notice that:

(a) The user's service handler class __init__ constructor takes a MyDBClient instance
(see hello_nexus.handler.MyNexusService)

(b) The user is responsible for instantiating the service handler class when they
start the worker (see hello_nexus.handler.worker), so they can pass any
necessary resources (such as this database client) to the service handler.
"""

@classmethod
def connect(cls) -> MyDBClient:
return cls()

def execute(self, query: str) -> str:
return "query-result"
58 changes: 58 additions & 0 deletions hello_nexus/handler/service_handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
"""
This file demonstrates how to implement a Nexus service.
"""

from __future__ import annotations

import uuid

from nexusrpc.handler import StartOperationContext, service_handler, sync_operation
from temporalio import nexus
from temporalio.nexus import WorkflowRunOperationContext, workflow_run_operation

from hello_nexus.handler.db_client import MyDBClient
from hello_nexus.handler.workflows import WorkflowStartedByNexusOperation
from hello_nexus.service import MyInput, MyNexusService, MyOutput


@service_handler(service=MyNexusService)
class MyNexusServiceHandler:
# You can create an __init__ method accepting what is needed by your operation
# handlers to handle requests. You typically instantiate your service handler class
# when starting your worker. See hello_nexus/basic/handler/worker.py.
def __init__(self, connected_db_client: MyDBClient):
# `connected_db_client` is intended as an example of something that might be
# required by your operation handlers when handling requests, but is only
# available at worker-start time.
self.connected_db_client = connected_db_client

# This is a nexus operation that is backed by a Temporal workflow. The start method
# starts a workflow, and returns a nexus operation token. Meanwhile, the workflow
# executes in the background; Temporal server takes care of delivering the eventual
# workflow result (success or failure) to the calling workflow.
#
# The token will be used by the caller if it subsequently wants to cancel the Nexus
# operation.
@workflow_run_operation
async def my_workflow_run_operation(
self, ctx: WorkflowRunOperationContext, input: MyInput
) -> nexus.WorkflowHandle[MyOutput]:
# You could use self.connected_db_client here.
return await ctx.start_workflow(
WorkflowStartedByNexusOperation.run,
input,
id=str(uuid.uuid4()),
)

# This is a Nexus operation that responds synchronously to all requests. That means
# that unlike the workflow run operation above, in this case the `start` method
# returns the final operation result.
#
# Sync operations are free to make arbitrary network calls, or perform CPU-bound
# computations. Total execution duration must not exceed 10s.
@sync_operation
async def my_sync_operation(
self, ctx: StartOperationContext, input: MyInput
) -> MyOutput:
# You could use self.connected_db_client here.
return MyOutput(message=f"Hello {input.name} from sync operation!")
54 changes: 54 additions & 0 deletions hello_nexus/handler/worker.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import asyncio
import logging
from typing import Optional

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

from hello_nexus.handler.db_client import MyDBClient
from hello_nexus.handler.service_handler import MyNexusServiceHandler
from hello_nexus.handler.workflows import WorkflowStartedByNexusOperation

interrupt_event = asyncio.Event()

NAMESPACE = "hello-nexus-basic-handler-namespace"
TASK_QUEUE = "my-handler-task-queue"


async def main(client: Optional[Client] = None):
logging.basicConfig(level=logging.INFO)

client = client or await Client.connect(
"localhost:7233",
namespace=NAMESPACE,
)

# Create an instance of the service handler. Your service handler class __init__ can
# be written to accept any arguments that your operation handlers need when handling
# requests. In this example we provide a database client object to the service hander.
connected_db_client = MyDBClient.connect()

# Start the worker, passing the Nexus service handler instance, in addition to the
# workflow classes that are started by your nexus operations, and any activities
# needed. This Worker will poll for both workflow tasks and Nexus tasks (this example
# doesn't use any activities).
async with Worker(
client,
task_queue=TASK_QUEUE,
workflows=[WorkflowStartedByNexusOperation],
nexus_service_handlers=[
MyNexusServiceHandler(connected_db_client=connected_db_client)
],
):
logging.info("Worker started, ctrl+c to exit")
await interrupt_event.wait()
logging.info("Shutting down")


if __name__ == "__main__":
loop = asyncio.new_event_loop()
try:
loop.run_until_complete(main())
except KeyboardInterrupt:
interrupt_event.set()
loop.run_until_complete(loop.shutdown_asyncgens())
12 changes: 12 additions & 0 deletions hello_nexus/handler/workflows.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from temporalio import workflow

with workflow.unsafe.imports_passed_through():
from hello_nexus.service import MyInput, MyOutput


# This is the workflow that is started by the `my_workflow_run_operation` nexus operation.
@workflow.defn
class WorkflowStartedByNexusOperation:
@workflow.run
async def run(self, input: MyInput) -> MyOutput:
return MyOutput(message=f"Hello {input.name} from workflow run operation!")
33 changes: 33 additions & 0 deletions hello_nexus/service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"""
This is a Nexus service definition.

A service definition defines a Nexus service as a named collection of operations, each
with input and output types. It does not implement operation handling: see the service
handler and operation handlers in hello_nexus.handler.nexus_service for that.

A Nexus service definition is used by Nexus callers (e.g. a Temporal workflow) to create
type-safe clients, and it is used by Nexus handlers to validate that they implement
correctly-named operation handlers with the correct input and output types.

The service defined in this file features two operations: echo and hello.
"""

from dataclasses import dataclass

import nexusrpc


@dataclass
class MyInput:
name: str


@dataclass
class MyOutput:
message: str


@nexusrpc.service
class MyNexusService:
my_sync_operation: nexusrpc.Operation[MyInput, MyOutput]
my_workflow_run_operation: nexusrpc.Operation[MyInput, MyOutput]
2 changes: 1 addition & 1 deletion open_telemetry/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import SERVICE_NAME, Resource
from opentelemetry.sdk.resources import SERVICE_NAME, Resource # type: ignore
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from temporalio import activity, workflow
Expand Down
13 changes: 12 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ dev = [
"pytest>=7.1.2,<8",
"pytest-asyncio>=0.18.3,<0.19",
"frozenlist>=1.4.0,<2",
"pyright>=1.1.394",
"types-pyyaml>=6.0.12.20241230,<7",
"pytest-pretty>=1.3.0",
]
bedrock = ["boto3>=1.34.92,<2"]
dsl = [
Expand All @@ -44,9 +46,12 @@ langchain = [
"tqdm>=4.62.0,<5",
"uvicorn[standard]>=0.24.0.post1,<0.25",
]
nexus = [
"nexus-rpc",
]
open-telemetry = [
"temporalio[opentelemetry]",
"opentelemetry-exporter-otlp-proto-grpc==1.18.0",
"opentelemetry-exporter-otlp-proto-grpc",
]
openai-agents = [
"openai-agents >= 0.0.19",
Expand All @@ -73,12 +78,17 @@ default-groups = [
"encryption",
"gevent",
"langchain",
"nexus",
"open-telemetry",
"pydantic-converter",
"sentry",
"trio-async",
]

[tool.uv.sources]
nexus-rpc = { path = "../nexus-sdk-python", editable = true }
temporalio = { path = "../sdk-python", editable = true }

[tool.hatch.build.targets.sdist]
include = ["./**/*.py"]

Expand All @@ -98,6 +108,7 @@ packages = [
"hello",
"langchain",
"message_passing",
"nexus",
"open_telemetry",
"patching",
"polling",
Expand Down
Loading
Loading