Skip to main content

dex_sdk/
registry.rs

1// Copyright (c) 2026 Super Durable, Inc.
2//
3// Licensed under the Super Durable Source 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-Super-Durable-1.0
8
9use std::any::TypeId;
10use std::collections::{HashMap, HashSet};
11use std::sync::Arc;
12
13use crate::persistence::{PersistenceDefinition, PersistenceKind};
14use crate::rpc::RegisteredRpc;
15use crate::step::RegisteredStep;
16use crate::step_options::ErasedStepOptions;
17use crate::{Context, Flow, HandlerResult, SdkError, SdkResult, StepDecision, Wait};
18use dex_protocol::dex::Value as ProtoValue;
19
20#[derive(Clone, Default)]
21/// Validates and stores all Flow definitions used by a Client or Worker.
22///
23/// Registration checks unique Flow, Step, RPC, and persistence names; starting-Step constraints;
24/// Attribute index consistency; RPC locks; and handler options. Cloning is cheap because it shares
25/// the registered data.
26///
27/// # Examples
28///
29/// ```
30/// use dex_sdk::{Flow, Registry};
31///
32/// struct OrderFlow;
33/// impl Flow for OrderFlow { type StartInput = String; }
34///
35/// let registry = Registry::new().register(OrderFlow)?;
36/// # Ok::<(), dex_sdk::SdkError>(())
37/// ```
38pub struct Registry {
39    inner: Arc<RegistryInner>,
40}
41
42#[derive(Clone, Default)]
43struct RegistryInner {
44    flows: HashMap<&'static str, RegisteredFlow>,
45    attribute_indexes: HashMap<String, i32>,
46}
47
48#[derive(Clone)]
49pub(crate) struct RegisteredFlow {
50    pub(crate) name: &'static str,
51    pub(crate) type_id: TypeId,
52    pub(crate) steps: HashMap<&'static str, RegisteredStep>,
53    pub(crate) start_step: Option<RegisteredStep>,
54    pub(crate) rpcs: HashMap<&'static str, RegisteredRpc>,
55    pub(crate) persistence: HashMap<String, PersistenceDefinition>,
56    pub(crate) handler: Arc<dyn ErasedFlow>,
57}
58
59impl Registry {
60    /// Creates an empty registry.
61    pub fn new() -> Self {
62        Self::default()
63    }
64
65    /// Validates and adds one owned Flow definition.
66    ///
67    /// # Errors
68    ///
69    /// Returns [`SdkError::FlowDefinition`] for invalid or conflicting names, schemas, indexes,
70    /// Steps, RPCs, locks, or options.
71    pub fn register<SomeFlow: Flow>(mut self, flow: SomeFlow) -> SdkResult<Self> {
72        let flow = Arc::new(flow);
73        let name = require_static_name(flow.flow_type(), "Flow type")?;
74        let registered = assemble_flow(name, Arc::clone(&flow))?;
75        let inner = Arc::make_mut(&mut self.inner);
76        let mut additions = Vec::new();
77        for definition in registered.persistence.values() {
78            let Some(index) = &definition.index else {
79                continue;
80            };
81            if definition.kind == PersistenceKind::AttributeMap
82                && index.key().is_none_or(str::is_empty)
83            {
84                return Err(definition_error(format!(
85                    "Flow {name} indexed AttributeMap {} requires an index key",
86                    definition.name
87                )));
88            }
89            let key = index.key().unwrap_or(&definition.name).to_string();
90            let index_type = index.proto_value();
91            if inner
92                .attribute_indexes
93                .get(&key)
94                .is_some_and(|existing| *existing != index_type)
95            {
96                return Err(definition_error(format!(
97                    "Attribute index {key} has conflicting types"
98                )));
99            }
100            additions.push((key, index_type));
101        }
102        if inner.flows.insert(name, registered).is_some() {
103            return Err(definition_error(format!("duplicate Flow {name}")));
104        }
105        inner.attribute_indexes.extend(additions);
106        Ok(self)
107    }
108
109    pub(crate) fn flow(&self, name: &str) -> SdkResult<&RegisteredFlow> {
110        self.inner
111            .flows
112            .get(name)
113            .ok_or_else(|| SdkError::FlowDefinition {
114                message: format!("Flow is not registered: {name}"),
115            })
116    }
117
118    pub(crate) fn rpc(&self, name: &str) -> SdkResult<&RegisteredRpc> {
119        let mut matched = None;
120        for flow in self.inner.flows.values() {
121            let Some(rpc) = flow.rpcs.get(name) else {
122                continue;
123            };
124            if matched.is_some() {
125                return Err(SdkError::FlowDefinition {
126                    message: format!("RPC name is ambiguous across registered Flows: {name}"),
127                });
128            }
129            matched = Some(rpc);
130        }
131        matched.ok_or_else(|| SdkError::FlowDefinition {
132            message: format!("RPC is not registered: {name}"),
133        })
134    }
135
136    pub(crate) fn attribute_indexes(&self) -> &HashMap<String, i32> {
137        &self.inner.attribute_indexes
138    }
139}
140
141fn assemble_flow<SomeFlow: Flow>(
142    name: &'static str,
143    flow: Arc<SomeFlow>,
144) -> SdkResult<RegisteredFlow> {
145    let timeout_handler = flow.timeout_handler();
146    let mut steps = HashMap::new();
147    let mut start_step = None;
148    for step in flow.steps().into_definitions() {
149        require_static_name(step.name, "Step type")?;
150        if step.starting {
151            if start_step.is_some() {
152                return Err(definition_error(format!(
153                    "Flow {name} must not have multiple start Steps"
154                )));
155            }
156            start_step = Some(step.clone());
157        }
158        if steps.insert(step.name, step).is_some() {
159            return Err(definition_error(format!(
160                "Flow {name} has a duplicate Step"
161            )));
162        }
163    }
164
165    let persistence = assemble_persistence(name, flow.persistence().definitions())?;
166    let mut rpcs = HashMap::new();
167    for rpc in flow.rpcs().bind(Arc::clone(&flow)) {
168        require_static_name(rpc.name, "RPC name")?;
169        validate_rpc(name, &rpc, &persistence)?;
170        if rpcs.insert(rpc.name, rpc).is_some() {
171            return Err(definition_error(format!("Flow {name} has a duplicate RPC")));
172        }
173    }
174    Ok(RegisteredFlow {
175        name,
176        type_id: TypeId::of::<SomeFlow>(),
177        steps,
178        start_step,
179        rpcs,
180        persistence,
181        handler: Arc::new(TypedFlow {
182            flow,
183            timeout_handler,
184        }),
185    })
186}
187
188pub(crate) trait ErasedFlow: Send + Sync {
189    fn has_timeout_handler(&self) -> bool;
190    fn handle_timeout(&self, context: &mut Context) -> HandlerResult<StepDecision>;
191    fn wait_for(
192        &self,
193        step_type: &str,
194        context: &mut Context,
195        input: &ProtoValue,
196    ) -> HandlerResult<Wait>;
197    fn execute(
198        &self,
199        step_type: &str,
200        context: &mut Context,
201        input: &ProtoValue,
202    ) -> HandlerResult<StepDecision>;
203    fn step_options(&self, step_type: &str) -> HandlerResult<ErasedStepOptions>;
204}
205
206struct TypedFlow<SomeFlow> {
207    flow: Arc<SomeFlow>,
208    timeout_handler: Option<crate::FlowTimeoutHandler<SomeFlow>>,
209}
210
211impl<SomeFlow: Flow> ErasedFlow for TypedFlow<SomeFlow> {
212    fn has_timeout_handler(&self) -> bool {
213        self.timeout_handler.is_some()
214    }
215
216    fn handle_timeout(&self, context: &mut Context) -> HandlerResult<StepDecision> {
217        let handler = self
218            .timeout_handler
219            .ok_or_else(|| crate::HandlerError::new("Flow has no timeout handler"))?;
220        handler(self.flow.as_ref(), context)
221    }
222    fn wait_for(
223        &self,
224        step_type: &str,
225        context: &mut Context,
226        input: &ProtoValue,
227    ) -> HandlerResult<Wait> {
228        self.flow
229            .steps()
230            .find(step_type)
231            .ok_or_else(|| {
232                crate::HandlerError::new(format!("Step is not registered: {step_type}"))
233            })?
234            .wait_for(context, input)
235    }
236
237    fn execute(
238        &self,
239        step_type: &str,
240        context: &mut Context,
241        input: &ProtoValue,
242    ) -> HandlerResult<StepDecision> {
243        self.flow
244            .steps()
245            .find(step_type)
246            .ok_or_else(|| {
247                crate::HandlerError::new(format!("Step is not registered: {step_type}"))
248            })?
249            .execute(context, input)
250    }
251
252    fn step_options(&self, step_type: &str) -> HandlerResult<ErasedStepOptions> {
253        Ok(self
254            .flow
255            .steps()
256            .find(step_type)
257            .ok_or_else(|| {
258                crate::HandlerError::new(format!("Step is not registered: {step_type}"))
259            })?
260            .options())
261    }
262}
263
264fn assemble_persistence(
265    flow_name: &str,
266    definitions: &[PersistenceDefinition],
267) -> SdkResult<HashMap<String, PersistenceDefinition>> {
268    let mut persistence = HashMap::new();
269    for definition in definitions {
270        if definition.name.is_empty() {
271            return Err(definition_error(format!(
272                "Flow {flow_name} has an empty persistence definition name"
273            )));
274        }
275        if persistence
276            .insert(definition.name.clone(), definition.clone())
277            .is_some()
278        {
279            return Err(definition_error(format!(
280                "Flow {flow_name} has duplicate persistence definition {}",
281                definition.name
282            )));
283        }
284    }
285    Ok(persistence)
286}
287
288fn validate_rpc(
289    flow_name: &str,
290    rpc: &RegisteredRpc,
291    persistence: &HashMap<String, PersistenceDefinition>,
292) -> SdkResult<()> {
293    if rpc.timeout.is_some_and(|timeout| timeout.is_zero()) {
294        return Err(definition_error(format!(
295            "Flow {flow_name} RPC {} timeout must be positive",
296            rpc.name
297        )));
298    }
299    let mut locks = HashSet::new();
300    for lock in &rpc.locks {
301        let physical_name = lock.physical_name();
302        let logical_name = physical_name.split('/').next().unwrap_or(&physical_name);
303        let definition = persistence.get(logical_name).ok_or_else(|| {
304            definition_error(format!(
305                "Flow {flow_name} RPC {} locks an unregistered Attribute",
306                rpc.name
307            ))
308        })?;
309        if !matches!(
310            definition.kind,
311            PersistenceKind::Attribute | PersistenceKind::AttributeMap
312        ) {
313            return Err(definition_error(format!(
314                "Flow {flow_name} RPC {} locks a non-Attribute",
315                rpc.name
316            )));
317        }
318        if !locks.insert(physical_name) {
319            return Err(definition_error(format!(
320                "Flow {flow_name} RPC {} has a duplicate lock",
321                rpc.name
322            )));
323        }
324    }
325    Ok(())
326}
327
328fn require_static_name(name: &'static str, kind: &str) -> SdkResult<&'static str> {
329    if name.is_empty() {
330        Err(definition_error(format!("{kind} is required")))
331    } else {
332        Ok(name)
333    }
334}
335
336fn definition_error(message: impl Into<String>) -> SdkError {
337    SdkError::FlowDefinition {
338        message: message.into(),
339    }
340}
341
342pub(crate) fn physical_name(name: &str, instance: &str) -> String {
343    if instance.is_empty() {
344        panic!("persistence instance is required");
345    }
346    let mut encoded = String::new();
347    for byte in instance.bytes() {
348        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
349            encoded.push(char::from(byte));
350        } else {
351            encoded.push_str(&format!("%{byte:02X}"));
352        }
353    }
354    format!("{name}/{encoded}")
355}
356
357pub(crate) fn decode_instance(physical_name: &str, prefix: &str) -> Result<String, String> {
358    let encoded = physical_name
359        .strip_prefix(prefix)
360        .ok_or_else(|| format!("map key {physical_name} does not start with {prefix}"))?;
361    let bytes = encoded.as_bytes();
362    let mut decoded = Vec::with_capacity(bytes.len());
363    let mut index = 0;
364    while index < bytes.len() {
365        if bytes[index] == b'%' {
366            if index + 2 >= bytes.len() {
367                return Err(format!("invalid percent encoding in {physical_name}"));
368            }
369            let high = hex_value(bytes[index + 1])?;
370            let low = hex_value(bytes[index + 2])?;
371            decoded.push(high * 16 + low);
372            index += 3;
373        } else {
374            decoded.push(bytes[index]);
375            index += 1;
376        }
377    }
378    String::from_utf8(decoded).map_err(|error| error.to_string())
379}
380
381fn hex_value(byte: u8) -> Result<u8, String> {
382    match byte {
383        b'0'..=b'9' => Ok(byte - b'0'),
384        b'a'..=b'f' => Ok(byte - b'a' + 10),
385        b'A'..=b'F' => Ok(byte - b'A' + 10),
386        _ => Err(format!(
387            "invalid percent-encoding digit {}",
388            char::from(byte)
389        )),
390    }
391}