Skip to main content

dex_sdk/
worker.rs

1// Copyright (c) 2026 Super Durable, Inc.
2//
3// Licensed under the Sustainable Use License 1.0.
4// You may not use this file except in compliance with the License.
5// See the LICENSE file in the repository root.
6//
7// SPDX-License-Identifier: LicenseRef-Sustainable-Use-1.0
8
9use std::collections::HashMap;
10use std::sync::Arc;
11use std::sync::atomic::{AtomicU8, Ordering};
12
13use crate::client::flow_service_tls::flow_service_endpoint;
14use crate::credential::{CredentialChannel, CredentialInterceptor};
15use dex_protocol::dex::SyncAttributeIndexRequest;
16use dex_protocol::dex::flow_service_client::FlowServiceClient;
17use tokio::runtime::Runtime;
18use tokio::sync::watch;
19
20use crate::server_protocol::{NegotiatedServerProtocolVersion, negotiate_server_protocol};
21use crate::value_hydrator::ValueHydrator;
22use crate::worker_dispatcher::WorkerDispatcher;
23use crate::worker_pull::PullWorker;
24use crate::{BlobCache, Registry, SdkError, SdkResult, WorkerOptions};
25
26const CREATED: u8 = 0;
27const RUNNING: u8 = 1;
28const STOPPED: u8 = 2;
29
30/// Runs registered Flow Step and RPC handlers through outbound task streams.
31///
32/// A Worker owns an internal Tokio runtime and is one-shot. [`Self::start`] negotiates the Server
33/// protocol, synchronizes Attribute indexes, then blocks while serving. Call [`Self::stop`]
34/// from another thread to request graceful shutdown. The Worker runs at most the configured number
35/// of handlers concurrently and needs only an outbound connection to Dex. See [`crate::PullWorkerOptions`].
36///
37/// # Examples
38///
39/// ```no_run
40/// use dex_sdk::{BlobCache, BlobCacheConfig, Registry, Worker, WorkerOptions};
41/// use std::sync::Arc;
42///
43/// let cache = Arc::new(BlobCache::open(BlobCacheConfig::new(
44///     "/tmp/dex-blobs", 64 * 1024 * 1024, 0,
45/// )?)?);
46/// let worker = Worker::try_new(Registry::new(), cache, WorkerOptions::new())?;
47/// worker.start()?;
48/// # Ok::<(), Box<dyn std::error::Error>>(())
49/// ```
50pub struct Worker {
51    runtime: Runtime,
52    flow_service: FlowServiceClient<CredentialChannel>,
53    attribute_indexes: HashMap<String, i32>,
54    attribute_index_sync_timeout: std::time::Duration,
55    pull: PullWorker,
56    shutdown: watch::Sender<bool>,
57    state: AtomicU8,
58    negotiated_protocol_version: NegotiatedServerProtocolVersion,
59}
60
61impl Worker {
62    /// Creates a Worker or panics when options or runtime initialization are invalid.
63    ///
64    /// # Panics
65    ///
66    /// Panics for invalid pull options, zero index-sync timeout, invalid Dex endpoint, or Tokio
67    /// runtime creation failure. Invalid TLS settings also panic. Prefer [`Self::try_new`] for recoverable startup.
68    pub fn new(registry: Registry, blob_cache: Arc<BlobCache>, options: WorkerOptions) -> Self {
69        Self::try_new(registry, blob_cache, options)
70            .unwrap_or_else(|error| panic!("cannot create Rust Worker: {error}"))
71    }
72
73    /// Creates a one-shot pull Worker with a lazy outbound connection.
74    ///
75    /// # Errors
76    ///
77    /// Returns [`SdkError::FlowDefinition`] for invalid Worker options, or Service for runtime
78    /// and endpoint initialization failures. Invalid TLS options return [`SdkError::InvalidArgument`].
79    /// The connection is lazy; certificate and handshake failures occur during [`Self::start`].
80    pub fn try_new(
81        registry: Registry,
82        blob_cache: Arc<BlobCache>,
83        options: WorkerOptions,
84    ) -> SdkResult<Self> {
85        let runtime = Runtime::new().map_err(service_error)?;
86        if options.attribute_index_sync_timeout_value().is_zero() {
87            return Err(SdkError::FlowDefinition {
88                message: "attribute index sync timeout must be positive".to_string(),
89            });
90        }
91        let endpoint = flow_service_endpoint(
92            options.server_address_value(),
93            options.flow_service_tls_value(),
94            "worker",
95        )?;
96        let flow_service = {
97            let _runtime_guard = runtime.enter();
98            FlowServiceClient::new(CredentialChannel::new(
99                endpoint.connect_lazy(),
100                CredentialInterceptor::new(options.credential_value()),
101            ))
102        };
103        let pull_channel = {
104            let _runtime_guard = runtime.enter();
105            crate::worker_pull::outbound_task_channel(endpoint.clone(), options.credential_value())
106        };
107        let attribute_indexes = registry.attribute_indexes().clone();
108        let hydrator = ValueHydrator::new(flow_service.clone(), blob_cache);
109        let negotiated_protocol_version = NegotiatedServerProtocolVersion::default();
110        let dispatcher =
111            WorkerDispatcher::new(registry, hydrator, negotiated_protocol_version.clone());
112        let pull = PullWorker::new(options.pull_value(), &dispatcher, pull_channel)?;
113        let (shutdown, _) = watch::channel(false);
114        Ok(Self {
115            runtime,
116            flow_service,
117            attribute_indexes,
118            attribute_index_sync_timeout: options.attribute_index_sync_timeout_value(),
119            pull,
120            shutdown,
121            state: AtomicU8::new(CREATED),
122            negotiated_protocol_version,
123        })
124    }
125
126    /// Negotiates protocol, synchronizes Attribute indexes, and serves until stopped or failed.
127    ///
128    /// Changed in 1.23.0: busy streams send transport keepalives during handler execution.
129    /// These preserve the connection; handlers must still record progress within their heartbeat timeout.
130    ///
131    /// Stream errors are logged and retried. After [`Self::stop`], this method drains
132    /// active handlers for the configured timeout, cancels any remaining handlers, and waits for
133    /// them to return. Call this method only once, on a dedicated thread.
134    ///
135    /// # Errors
136    ///
137    /// Returns FlowDefinition if called more than once, or Service for index synchronization,
138    /// timeout, incompatible Server protocol, and server failures. An unreachable Server returns
139    /// the Service error carrying the original gRPC status code, such as `UNAVAILABLE`.
140    /// Startup also fails with a Service error whose code is `FAILED_PRECONDITION` when
141    /// `max_concurrent_tasks` exceeds the Server setting `matching.maxConcurrentTasksCap`. The
142    /// first registered stream reports that setting; the Worker then half-closes its streams.
143    /// Returns a service error exposing [`SdkError::pull_registration_error`] after draining when permanent-rejection shutdown is enabled.
144    pub fn start(&self) -> SdkResult<()> {
145        let result = self.start_worker();
146        self.pull
147            .registration
148            .finish(result.as_ref().err().cloned());
149        result
150    }
151
152    fn start_worker(&self) -> SdkResult<()> {
153        self.state
154            .compare_exchange(CREATED, RUNNING, Ordering::AcqRel, Ordering::Acquire)
155            .map_err(|_| SdkError::FlowDefinition {
156                message: "Worker can only be started once".to_string(),
157            })?;
158        let shutdown = self.shutdown.subscribe();
159        let mut flow_service = self.flow_service.clone();
160        let server_info_result = self.runtime.block_on(async {
161            tokio::time::timeout(
162                self.attribute_index_sync_timeout,
163                flow_service.get_server_info(()),
164            )
165            .await
166        });
167        let server_info = match server_info_result {
168            Ok(Ok(response)) => response.into_inner(),
169            Ok(Err(status)) => {
170                self.state.store(STOPPED, Ordering::Release);
171                return Err(SdkError::from_status(
172                    status,
173                    "get_server_info",
174                    None,
175                    crate::sdk_error::FlowTargetRequirement::None,
176                ));
177            }
178            Err(elapsed) => {
179                self.state.store(STOPPED, Ordering::Release);
180                return Err(service_error(format!("GetServerInfo: {elapsed}")));
181            }
182        };
183        let negotiated_protocol_version =
184            negotiate_server_protocol(&server_info).map_err(|error| {
185                self.state.store(STOPPED, Ordering::Release);
186                service_error(error)
187            })?;
188        self.negotiated_protocol_version
189            .store(negotiated_protocol_version);
190        let sync_result = self.runtime.block_on(async {
191            tokio::time::timeout(
192                self.attribute_index_sync_timeout,
193                flow_service.sync_attribute_indexes(SyncAttributeIndexRequest {
194                    attribute_indexes: self.attribute_indexes.clone(),
195                }),
196            )
197            .await
198        });
199        match sync_result {
200            Ok(Ok(_)) => {}
201            Ok(Err(status)) => {
202                self.state.store(STOPPED, Ordering::Release);
203                return Err(service_error(status));
204            }
205            Err(elapsed) => {
206                self.state.store(STOPPED, Ordering::Release);
207                return Err(service_error(elapsed));
208            }
209        }
210        let result = self.runtime.block_on(self.pull.run(shutdown));
211        self.state.store(STOPPED, Ordering::Release);
212        result
213    }
214
215    /// Waits until a Step-and-RPC slot and, when reserved, an RPC-only slot have registered once.
216    ///
217    /// Safe before or after [`Self::start`] and for concurrent callers. Start the Worker on a
218    /// dedicated thread. Drop this future to cancel the wait, or use `tokio::time::timeout`.
219    /// Completion remains latched after shutdown; use [`Self::pull_registration_state`] for probes.
220    ///
221    /// # Errors
222    ///
223    /// Returns a service error exposing [`SdkError::pull_registration_error`] for a permanent rejection without another registered
224    /// stream before readiness. Returns the startup error if startup fails, or InvalidArgument
225    /// for shutdown before readiness.
226    /// When `max_concurrent_tasks` exceeds the Server setting `matching.maxConcurrentTasksCap`,
227    /// readiness is never reported and this returns the same `FAILED_PRECONDITION` Service error
228    /// as [`Self::start`].
229    ///
230    /// ```no_run
231    /// # async fn ready(worker: &dex_sdk::Worker) -> Result<(), Box<dyn std::error::Error>> {
232    /// tokio::time::timeout(std::time::Duration::from_secs(10), worker.wait_pull_registered()).await??;
233    /// assert!(worker.pull_registration_state().is_ready);
234    /// # Ok(()) }
235    /// ```
236    pub async fn wait_pull_registered(&self) -> SdkResult<()> {
237        self.pull.registration.wait().await
238    }
239
240    /// Returns zero for the obsolete reserved-RPC decline counter.
241    ///
242    /// Deprecated: the Server assigns work to reserved slots, and the Worker never declines tasks
243    /// for capacity. This method remains callable after shutdown and is safe for concurrent reads.
244    /// Remove calls to it; existing callers keep compiling with a deprecation warning.
245    ///
246    /// ```no_run
247    /// # fn inspect(worker: &dex_sdk::Worker) {
248    /// #[expect(deprecated, reason = "the counter is kept for source compatibility")]
249    /// let declines: u64 = worker.pull_reserved_rpc_declines();
250    /// assert_eq!(declines, 0);
251    /// # }
252    /// ```
253    #[deprecated(note = "reserved slots never decline for capacity; this counter is always zero")]
254    pub fn pull_reserved_rpc_declines(&self) -> u64 {
255        0
256    }
257
258    /// Returns an independent snapshot of current pull slot-kind registrations.
259    ///
260    /// Readiness latches after each required slot kind registers once. Only a permanent rejection with no
261    /// registered stream makes it false. Successful registration clears that slot kind's error.
262    /// Transient disconnects and Stop do not clear readiness. See [`Self::wait_pull_registered`] for a startup and probe example.
263    pub fn pull_registration_state(&self) -> crate::PullRegistrationState {
264        self.pull.registration.snapshot()
265    }
266
267    /// Requests shutdown of a running Worker and returns immediately.
268    ///
269    /// Calling `stop` before or after `start` is safe; [`Self::start`] observes the shutdown signal.
270    /// No new handler starts after this request. Idle streams half-close immediately; busy streams
271    /// finish their handler and send its final output before half-closing. Task frames arriving
272    /// after Stop are dropped without invoking a handler, including after half-close. Streams keep
273    /// reading until the Server ends them or the drain deadline expires. At that deadline, busy
274    /// streams whose final output is not yet queued are reset and their handlers are cancelled;
275    /// [`Self::start`] waits for their return. Dex treats a task on a reset stream as one that may
276    /// have run. A busy stream whose final output is already queued still sends it and half-closes.
277    /// A stream whose last final output Dex has not yet acknowledged with a new task waits up to
278    /// five seconds past the drain deadline for the Server to end it, even after its handler has
279    /// returned. [`Self::start`] can therefore return up to five seconds after the drain deadline.
280    /// Every other stream still open at the deadline, including one blocked on a send, is reset.
281    /// Stop is idempotent.
282    /// Changed in 1.35.0: tasks received after Stop are returned without running or consuming a
283    /// retry. Draining preserves final output before the stream closes. Use this method for
284    /// graceful shutdown and join the thread running [`Self::start`] before releasing resources.
285    pub fn stop(&self) {
286        self.pull.stop_accepting_tasks();
287        self.pull.registration.finish(None);
288        self.shutdown.send_replace(true);
289    }
290}
291
292fn service_error(error: impl std::fmt::Display) -> SdkError {
293    SdkError::Service {
294        service: crate::ServiceError::local("worker", error.to_string()),
295    }
296}