Skip to content
Draft
Show file tree
Hide file tree
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
2 changes: 2 additions & 0 deletions temporalio/bridge/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ temporalio-sdk-core = { version = "0.12.0", path = "./sdk-core/crates/sdk-core",
"ephemeral-server",
"envconfig",
"prometheus",
# Replay must retain the result groups of Stream create and describe Local Activities.
"disable_workflow_task_chunking",
] }
temporalio-streams = { version = "0.1.0", path = "./sdk-core/crates/streams" }
tokio = "1.26"
Expand Down
1 change: 1 addition & 0 deletions temporalio/bridge/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ mod client_rpc_generated;
mod envconfig;
mod metric;
mod runtime;
mod streams;
mod testing;
mod worker;

Expand Down
221 changes: 221 additions & 0 deletions temporalio/bridge/src/streams.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
use futures::future::BoxFuture;
use prost::Message;
use pyo3::exceptions::asyncio::CancelledError;
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::sync::PyOnceLock;
use pyo3::types::{PyBytes, PyType};
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError};
use temporalio_sdk_core::StreamRuntimes;
use temporalio_streams::proto::{
AppendRecordsRequest, AppendRecordsResponse, CreateStreamRequest, CreateStreamResponse,
DescribeStreamRequest, DescribeStreamResponse, ReadRecordsRequest, ReadRecordsResponse,
};
use temporalio_streams::record::StoreLimits;
use temporalio_streams::{
AppendError, CreateError, DescribeError, ReadError, StreamError, StreamRuntime, StreamStore,
WireReason,
};

struct PythonStore {
caller: Py<PyAny>,
event_loop_task_locals: Arc<OnceLock<pyo3_async_runtimes::TaskLocals>>,
}

enum CallState {
Pending,
Running(Py<PyAny>),
Dropped,
Done,
}

// Release this lock before acquiring the GIL to avoid a deadlock with `OnTask`.
fn lock(state: &Mutex<CallState>) -> MutexGuard<'_, CallState> {
state.lock().unwrap_or_else(PoisonError::into_inner)
}

#[pyclass]
struct OnTask {
state: Arc<Mutex<CallState>>,
}

#[pymethods]
impl OnTask {
fn __call__(&self, task: Py<PyAny>) -> PyResult<()> {
let mut state = lock(&self.state);
if matches!(*state, CallState::Dropped) {
drop(state);
return Err(CancelledError::new_err(()));
}
*state = CallState::Running(task);
Ok(())
}
}

// Dropping a Core future must also stop its Python Store task.
struct CallGuard<'a> {
state: Arc<Mutex<CallState>>,
task_locals: &'a pyo3_async_runtimes::TaskLocals,
}

impl Drop for CallGuard<'_> {
fn drop(&mut self) {
let state = std::mem::replace(&mut *lock(&self.state), CallState::Dropped);
if let CallState::Running(task) = state {
// `asyncio` requires cross-thread cancellation to run through its event loop.
let _ = Python::try_attach(|py| {
let cancel = task.getattr(py, "cancel")?;
let event_loop = self.task_locals.event_loop(py);
event_loop.call_method1("call_soon_threadsafe", (cancel,))?;
PyResult::Ok(())
});
}
}
}

impl PythonStore {
async fn call<Request, Response, R>(
&self,
operation: &'static str,
request: Request,
request_id: Option<String>,
) -> Result<Response, StreamError<R>>
where
Request: Message,
Response: Message + Default,
R: WireReason,
{
let Some(task_locals) = self.event_loop_task_locals.get() else {
return Err(StreamError::store_unavailable(
"The Worker hasn't set the event loop of its Stream Stores yet",
));
};
let state = Arc::new(Mutex::new(CallState::Pending));
let _guard = CallGuard {
state: state.clone(),
task_locals,
};
let called = Python::try_attach(|py| {
let on_task = OnTask {
state: state.clone(),
};
let request = PyBytes::new(py, &request.encode_to_vec());
let arguments = (operation, request, request_id, on_task);
let coroutine = (self.caller.bind(py)).call_method1("call", arguments)?;
pyo3_async_runtimes::into_future_with_locals(task_locals, coroutine)
});
let answer = match called {
Some(Ok(answer)) => answer.await,
Some(Err(err)) => Err(err),
None => return Err(interpreter_gone(operation)),
};
let done = Python::try_attach(|py| {
let _task = std::mem::replace(&mut *lock(&state), CallState::Done);
match answer {
Ok(response) => (response.bind(py).cast::<PyBytes>().ok())
.and_then(|bytes| Response::decode(bytes.as_bytes()).ok())
.ok_or_else(|| {
StreamError::store_corrupt(format!(
"The Store didn't answer the {operation} call with its encoded \
response message"
))
}),
Err(err) => Err(store_error(py, err)),
}
});
done.unwrap_or_else(|| Err(interpreter_gone(operation)))
}
}

fn interpreter_gone<R: WireReason>(operation: &str) -> StreamError<R> {
StreamError::store_unavailable(format!(
"The Python interpreter is shutting down, so the Store can't take the {operation} call"
))
}

// Only Store refusals retain their reason. Other exceptions can be retried.
fn store_error<R: WireReason>(py: Python<'_>, err: PyErr) -> StreamError<R> {
let refusal = || -> PyResult<Option<(i32, String)>> {
let value = err.value(py);
if !value.is_instance(stream_error_type(py)?)? {
return Ok(None);
}
let reason = value.getattr("reason")?.extract()?;
Ok(Some((reason, value.getattr("message")?.extract()?)))
};
match refusal() {
Ok(Some((reason, message))) => StreamError::from_wire(reason, message),
_ => StreamError::store_unavailable(err.to_string()),
}
}

fn stream_error_type(py: Python<'_>) -> PyResult<&Bound<'_, PyType>> {
static STREAM_ERROR: PyOnceLock<Py<PyType>> = PyOnceLock::new();
STREAM_ERROR.import(py, "temporalio.exceptions", "StreamError")
}

impl StreamStore for PythonStore {
fn create_stream(
&self,
request: CreateStreamRequest,
request_id: String,
) -> BoxFuture<'_, Result<CreateStreamResponse, CreateError>> {
Box::pin(self.call("CreateStream", request, Some(request_id)))
}

fn append_records(
&self,
request: AppendRecordsRequest,
request_id: String,
) -> BoxFuture<'_, Result<AppendRecordsResponse, AppendError>> {
Box::pin(self.call("AppendRecords", request, Some(request_id)))
}

fn read_records(
&self,
request: ReadRecordsRequest,
) -> BoxFuture<'_, Result<ReadRecordsResponse, ReadError>> {
Box::pin(self.call("ReadRecords", request, None))
}

fn describe_stream(
&self,
request: DescribeStreamRequest,
) -> BoxFuture<'_, Result<DescribeStreamResponse, DescribeError>> {
Box::pin(self.call("DescribeStream", request, None))
}
}

fn store_limits(
(max_record_bytes, max_batch_bytes, max_batch_records): (usize, usize, usize),
) -> PyResult<StoreLimits> {
StoreLimits::default()
.with_max_record_bytes(max_record_bytes)
.and_then(|limits| limits.with_max_batch_bytes(max_batch_bytes))
.and_then(|limits| limits.with_max_batch_records(max_batch_records))
.map_err(|err| PyValueError::new_err(err.message))
}

#[derive(FromPyObject)]
pub(crate) struct WorkerStreams {
limits: Option<(usize, usize, usize)>,
stores: Vec<(String, Py<PyAny>)>,
}

impl WorkerStreams {
pub(crate) fn into_runtimes(
self,
task_locals: &Arc<OnceLock<pyo3_async_runtimes::TaskLocals>>,
) -> PyResult<StreamRuntimes> {
let limits = (self.limits.map(store_limits).transpose()?).unwrap_or_default();
let runtimes = self.stores.into_iter().map(|(name, caller)| {
let store = PythonStore {
caller,
event_loop_task_locals: task_locals.clone(),
};
let runtime = StreamRuntime::new(Arc::new(store), limits);
(name, Arc::new(runtime))
});
Ok(StreamRuntimes::new(runtimes))
}
}
4 changes: 4 additions & 0 deletions temporalio/bridge/src/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ use tracing::error;

use crate::client;
use crate::runtime;
use crate::streams::WorkerStreams;

pyo3::create_exception!(temporal_sdk_bridge, PollShutdownError, PyException);

Expand Down Expand Up @@ -65,6 +66,7 @@ pub struct WorkerConfig {
plugins: Vec<(String, String)>,
storage_drivers: HashSet<String>,
disable_payload_error_limit: bool,
streams: WorkerStreams,
}

#[derive(FromPyObject)]
Expand Down Expand Up @@ -720,6 +722,7 @@ fn convert_worker_config(
conf: WorkerConfig,
task_locals: Arc<OnceLock<pyo3_async_runtimes::TaskLocals>>,
) -> PyResult<temporalio_sdk_core::WorkerConfig> {
let stream_runtimes = conf.streams.into_runtimes(&task_locals)?;
let converted_tuner = convert_tuner_holder(conf.tuner, task_locals)?;
let converted_versioning_strategy = convert_versioning_strategy(conf.versioning_strategy);
temporalio_sdk_core::WorkerConfig::builder()
Expand Down Expand Up @@ -781,6 +784,7 @@ fn convert_worker_config(
.collect::<HashSet<_>>(),
)
.disable_payload_error_limit(conf.disable_payload_error_limit)
.stream_runtimes(stream_runtimes)
.build()
.map_err(|err| PyValueError::new_err(format!("Invalid worker config: {err}")))
}
Expand Down
41 changes: 41 additions & 0 deletions temporalio/bridge/streams.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
"""Stream Store calls through SDK Core. (unstable)

Nothing in this module should be considered stable. The API may change.
"""

from __future__ import annotations

import asyncio
from collections.abc import Callable, Sequence
from dataclasses import dataclass
from typing import Any, Protocol


class StoreCaller(Protocol):
"""What SDK Core calls to reach a Stream Store that is a Python object."""

async def call(
self,
operation: str,
request: bytes,
request_id: str | None,
on_task: Callable[[asyncio.Task[Any]], None],
) -> bytes:
"""Call the Store for a Stream operation with its encoded request, and
return its encoded response.

``request_id`` is that of a create or an append, and ``None`` for the
other operations.
"""
...


@dataclass
class WorkerStreams:
"""Python representation of the Rust struct for the Stream Stores of a worker."""

limits: tuple[int, int, int] | None
"""The ``max_record_bytes``, the ``max_batch_bytes`` and the ``max_batch_records``
of the Stream config, or ``None`` with no Stream config."""
stores: Sequence[tuple[str, StoreCaller]]
"""The caller of each Stream Store that Workflow code can use, by Store name."""
2 changes: 2 additions & 0 deletions temporalio/bridge/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import temporalio.bridge.proto.workflow_activation
import temporalio.bridge.proto.workflow_completion
import temporalio.bridge.runtime
import temporalio.bridge.streams
import temporalio.bridge.temporal_sdk_bridge
import temporalio.converter
import temporalio.converter._extstore
Expand Down Expand Up @@ -63,6 +64,7 @@ class WorkerConfig:
plugins: Sequence[tuple[str, str]]
storage_drivers: set[str]
disable_payload_error_limit: bool
streams: temporalio.bridge.streams.WorkerStreams


@dataclass
Expand Down
Loading
Loading