Skip to main content

hydro_lang/compile/
deploy_provider.rs

1use std::io::Error;
2use std::pin::Pin;
3
4use bytes::{Bytes, BytesMut};
5use dfir_lang::graph::{AsCodeOptions, DfirGraph};
6use futures::{Sink, Stream};
7use serde::Serialize;
8use serde::de::DeserializeOwned;
9
10use crate::compile::builder::ExternalPortId;
11use crate::compile::ir::NetworkSink;
12use crate::location::dynamic::LocationId;
13use crate::location::{LocationKey, NetworkHint};
14
15pub trait Deploy<'a> {
16    type Meta: Default;
17    type InstantiateEnv;
18
19    type Process: Node<Meta = Self::Meta, InstantiateEnv = Self::InstantiateEnv> + Clone;
20    type Cluster: Node<Meta = Self::Meta, InstantiateEnv = Self::InstantiateEnv> + Clone;
21    type External: Node<Meta = Self::Meta, InstantiateEnv = Self::InstantiateEnv>
22        + RegisterPort<'a, Self>;
23
24    /// Whether this deployment backend supports network channels that leave serialization to code
25    /// outside of Hydro (see [`crate::networking::Embedded`]). When `false`, attempting to use such
26    /// a channel will panic during instantiation.
27    const SUPPORTS_EXTERNAL_SERIALIZATION: bool = false;
28
29    /// Generates the source and sink expressions when connecting a [`Self::Process`] to another
30    /// [`Self::Process`].
31    ///
32    /// The [`Self::InstantiateEnv`] can be used to record metadata about the created channel. The
33    /// provided `name` is the user-configured channel name from the network IR node.
34    ///
35    /// When `external_types` is [`Some`], the channel leaves serialization to code outside
36    /// of Hydro and the provided type is the raw element type that flows across the channel
37    /// unserialized.
38    #[expect(clippy::too_many_arguments, reason = "networking codegen")]
39    fn o2o_sink_source(
40        env: &mut Self::InstantiateEnv,
41        p1: &Self::Process,
42        p1_port: &<Self::Process as Node>::Port,
43        p2: &Self::Process,
44        p2_port: &<Self::Process as Node>::Port,
45        name: Option<&str>,
46        networking_info: &crate::networking::NetworkingInfo,
47        external_types: Option<(&syn::Type, &syn::Type)>,
48    ) -> (syn::Expr, syn::Expr);
49
50    /// Classifies the sending end returned by the `*_sink_source` methods: how the generated DFIR
51    /// drives it. See [`NetworkSink`].
52    ///
53    /// Defaults to [`NetworkSink::Sink`], a [`futures::Sink`] driven asynchronously via
54    /// `dest_sink`. Backends whose sending ends are plain `FnMut(Item)` callbacks (which can never
55    /// pend) override this to return [`NetworkSink::Callback`], so that the sending side is a
56    /// synchronous `for_each` instead.
57    fn network_sink(sink: syn::Expr) -> NetworkSink {
58        NetworkSink::Sink(sink)
59    }
60
61    /// Performs any runtime wiring needed after code generation for a
62    /// [`Self::Process`]-to-[`Self::Process`] channel.
63    ///
64    /// The returned closure is executed once all locations have been instantiated.
65    fn o2o_connect(
66        p1: &Self::Process,
67        p1_port: &<Self::Process as Node>::Port,
68        p2: &Self::Process,
69        p2_port: &<Self::Process as Node>::Port,
70    ) -> Box<dyn FnOnce()>;
71
72    /// Generates the source and sink expressions when connecting a [`Self::Process`] to a
73    /// [`Self::Cluster`] (one-to-many).
74    ///
75    /// The sink expression is used on the sending process and the source expression on each
76    /// receiving cluster member. The [`Self::InstantiateEnv`] can be used to record metadata
77    /// about the created channel. The provided `name` is the user-configured channel name
78    /// from the network IR node.
79    ///
80    /// When `external_types` is [`Some`], the channel leaves serialization to code outside
81    /// of Hydro and the provided type is the raw element type that flows across the channel
82    /// unserialized.
83    #[expect(clippy::too_many_arguments, reason = "networking codegen")]
84    fn o2m_sink_source(
85        env: &mut Self::InstantiateEnv,
86        p1: &Self::Process,
87        p1_port: &<Self::Process as Node>::Port,
88        c2: &Self::Cluster,
89        c2_port: &<Self::Cluster as Node>::Port,
90        name: Option<&str>,
91        networking_info: &crate::networking::NetworkingInfo,
92        external_types: Option<(&syn::Type, &syn::Type)>,
93    ) -> (syn::Expr, syn::Expr);
94
95    /// Performs any runtime wiring needed after code generation for a
96    /// [`Self::Process`]-to-[`Self::Cluster`] channel.
97    ///
98    /// The returned closure is executed once all locations have been instantiated.
99    fn o2m_connect(
100        p1: &Self::Process,
101        p1_port: &<Self::Process as Node>::Port,
102        c2: &Self::Cluster,
103        c2_port: &<Self::Cluster as Node>::Port,
104    ) -> Box<dyn FnOnce()>;
105
106    /// Generates the source and sink expressions when connecting a [`Self::Cluster`] to a
107    /// [`Self::Process`] (many-to-one).
108    ///
109    /// The sink expression is used on each sending cluster member and the source expression
110    /// on the receiving process. The [`Self::InstantiateEnv`] can be used to record metadata
111    /// about the created channel. The provided `name` is the user-configured channel name
112    /// from the network IR node.
113    ///
114    /// When `external_types` is [`Some`], the channel leaves serialization to code outside
115    /// of Hydro and the provided type is the raw element type that flows across the channel
116    /// unserialized.
117    #[expect(clippy::too_many_arguments, reason = "networking codegen")]
118    fn m2o_sink_source(
119        env: &mut Self::InstantiateEnv,
120        c1: &Self::Cluster,
121        c1_port: &<Self::Cluster as Node>::Port,
122        p2: &Self::Process,
123        p2_port: &<Self::Process as Node>::Port,
124        name: Option<&str>,
125        networking_info: &crate::networking::NetworkingInfo,
126        external_types: Option<(&syn::Type, &syn::Type)>,
127    ) -> (syn::Expr, syn::Expr);
128
129    /// Performs any runtime wiring needed after code generation for a
130    /// [`Self::Cluster`]-to-[`Self::Process`] channel.
131    ///
132    /// The returned closure is executed once all locations have been instantiated.
133    fn m2o_connect(
134        c1: &Self::Cluster,
135        c1_port: &<Self::Cluster as Node>::Port,
136        p2: &Self::Process,
137        p2_port: &<Self::Process as Node>::Port,
138    ) -> Box<dyn FnOnce()>;
139
140    /// Generates the source and sink expressions when connecting a [`Self::Cluster`] to another
141    /// [`Self::Cluster`] (many-to-many).
142    ///
143    /// The sink expression is used on each sending cluster member and the source expression
144    /// on each receiving cluster member. The [`Self::InstantiateEnv`] can be used to record
145    /// metadata about the created channel. The provided `name` is the user-configured channel
146    /// name from the network IR node.
147    ///
148    /// When `external_types` is [`Some`], the channel leaves serialization to code outside
149    /// of Hydro and the provided type is the raw element type that flows across the channel
150    /// unserialized.
151    #[expect(clippy::too_many_arguments, reason = "networking codegen")]
152    fn m2m_sink_source(
153        env: &mut Self::InstantiateEnv,
154        c1: &Self::Cluster,
155        c1_port: &<Self::Cluster as Node>::Port,
156        c2: &Self::Cluster,
157        c2_port: &<Self::Cluster as Node>::Port,
158        name: Option<&str>,
159        networking_info: &crate::networking::NetworkingInfo,
160        external_types: Option<(&syn::Type, &syn::Type)>,
161    ) -> (syn::Expr, syn::Expr);
162
163    /// Performs any runtime wiring needed after code generation for a
164    /// [`Self::Cluster`]-to-[`Self::Cluster`] channel.
165    ///
166    /// The returned closure is executed once all locations have been instantiated.
167    fn m2m_connect(
168        c1: &Self::Cluster,
169        c1_port: &<Self::Cluster as Node>::Port,
170        c2: &Self::Cluster,
171        c2_port: &<Self::Cluster as Node>::Port,
172    ) -> Box<dyn FnOnce()>;
173
174    fn e2o_many_source(
175        extra_stmts: &mut Vec<syn::Stmt>,
176        p2: &Self::Process,
177        p2_port: &<Self::Process as Node>::Port,
178        codec_type: &syn::Type,
179        encode_type: &syn::Type,
180        shared_handle: String,
181    ) -> syn::Expr;
182    fn e2o_many_sink(shared_handle: String) -> syn::Expr;
183
184    #[expect(clippy::too_many_arguments, reason = "networking codegen")]
185    fn e2o_source(
186        extra_stmts: &mut Vec<syn::Stmt>,
187        p1: &Self::External,
188        p1_port: &<Self::External as Node>::Port,
189        p2: &Self::Process,
190        p2_port: &<Self::Process as Node>::Port,
191        codec_type: &syn::Type,
192        encode_type: &syn::Type,
193        shared_handle: String,
194    ) -> syn::Expr;
195    fn e2o_connect(
196        p1: &Self::External,
197        p1_port: &<Self::External as Node>::Port,
198        p2: &Self::Process,
199        p2_port: &<Self::Process as Node>::Port,
200        many: bool,
201        server_hint: NetworkHint,
202    ) -> Box<dyn FnOnce()>;
203
204    fn o2e_sink(
205        p1: &Self::Process,
206        p1_port: &<Self::Process as Node>::Port,
207        p2: &Self::External,
208        p2_port: &<Self::External as Node>::Port,
209        shared_handle: String,
210    ) -> syn::Expr;
211
212    #[expect(clippy::too_many_arguments, reason = "networking codegen")]
213    fn e2m_source(
214        extra_stmts: &mut Vec<syn::Stmt>,
215        p1: &Self::External,
216        p1_port: &<Self::External as Node>::Port,
217        c2: &Self::Cluster,
218        c2_port: &<Self::Cluster as Node>::Port,
219        codec_type: &syn::Type,
220        encode_type: &syn::Type,
221        shared_handle: String,
222    ) -> syn::Expr {
223        let _ = (
224            extra_stmts,
225            p1,
226            p1_port,
227            c2,
228            c2_port,
229            codec_type,
230            encode_type,
231            shared_handle,
232        );
233        todo!("e2m_source is not yet supported for this deploy backend")
234    }
235
236    fn e2m_connect(
237        p1: &Self::External,
238        p1_port: &<Self::External as Node>::Port,
239        c2: &Self::Cluster,
240        c2_port: &<Self::Cluster as Node>::Port,
241        server_hint: NetworkHint,
242    ) -> Box<dyn FnOnce()> {
243        let _ = (p1, p1_port, c2, c2_port, server_hint);
244        todo!("e2m_connect is not yet supported for this deploy backend")
245    }
246
247    fn m2e_sink(
248        c1: &Self::Cluster,
249        c1_port: &<Self::Cluster as Node>::Port,
250        p2: &Self::External,
251        p2_port: &<Self::External as Node>::Port,
252        shared_handle: String,
253    ) -> syn::Expr {
254        let _ = (c1, c1_port, p2, p2_port, shared_handle);
255        todo!("m2e_sink is not yet supported for this deploy backend")
256    }
257
258    /// The IDs of `of_cluster`'s members, as an expression of type `&[Id]`.
259    /// `Id` is this backend's member ID type (see [`SupportsMemberId`]).
260    fn cluster_ids(of_cluster: LocationKey) -> syn::Expr;
261
262    /// This member's own ID, as an expression of type `Id`.
263    fn cluster_self_id() -> syn::Expr;
264
265    /// The membership events of `location_id`, as seen from `at_location`.
266    /// The expression has type `Box<dyn Stream<Item = (Id, MembershipEvent)> + Unpin>`.
267    fn cluster_membership_stream(
268        env: &mut Self::InstantiateEnv,
269        at_location: &LocationId,
270        location_id: &LocationId,
271    ) -> syn::Expr;
272
273    /// Registers an embedded stream input for the given ident and element type.
274    ///
275    /// Only meaningful for the embedded deployment backend. The default
276    /// implementation panics.
277    fn register_embedded_stream_input(
278        _env: &mut Self::InstantiateEnv,
279        _location_key: LocationKey,
280        _ident: &syn::Ident,
281        _element_type: &syn::Type,
282    ) {
283        panic!("register_embedded_stream_input is only supported by EmbeddedDeploy");
284    }
285
286    /// Registers an embedded singleton input for the given ident and element type.
287    ///
288    /// Only meaningful for the embedded deployment backend. The default
289    /// implementation panics.
290    fn register_embedded_singleton_input(
291        _env: &mut Self::InstantiateEnv,
292        _location_key: LocationKey,
293        _ident: &syn::Ident,
294        _element_type: &syn::Type,
295    ) {
296        panic!("register_embedded_singleton_input is only supported by EmbeddedDeploy");
297    }
298
299    /// Registers an embedded output for the given ident and element type.
300    ///
301    /// Only meaningful for the embedded deployment backend. The default
302    /// implementation panics.
303    fn register_embedded_output(
304        _env: &mut Self::InstantiateEnv,
305        _location_key: LocationKey,
306        _ident: &syn::Ident,
307        _element_type: &syn::Type,
308    ) {
309        panic!("register_embedded_output is only supported by EmbeddedDeploy");
310    }
311}
312
313pub trait ProcessSpec<'a, D>
314where
315    D: Deploy<'a> + ?Sized,
316{
317    fn build(self, location_key: LocationKey, name_hint: &str) -> D::Process;
318}
319
320pub trait IntoProcessSpec<'a, D>
321where
322    D: Deploy<'a> + ?Sized,
323{
324    type ProcessSpec: ProcessSpec<'a, D>;
325    fn into_process_spec(self) -> Self::ProcessSpec;
326}
327
328impl<'a, D, T> IntoProcessSpec<'a, D> for T
329where
330    D: Deploy<'a> + ?Sized,
331    T: ProcessSpec<'a, D>,
332{
333    type ProcessSpec = T;
334    fn into_process_spec(self) -> Self::ProcessSpec {
335        self
336    }
337}
338
339pub trait ClusterSpec<'a, D>
340where
341    D: Deploy<'a> + ?Sized,
342{
343    fn build(self, location_key: LocationKey, name_hint: &str) -> D::Cluster;
344}
345
346pub trait ExternalSpec<'a, D>
347where
348    D: Deploy<'a> + ?Sized,
349{
350    fn build(self, location_key: LocationKey, name_hint: &str) -> D::External;
351}
352
353pub trait Node {
354    /// A logical communication endpoint for this node.
355    ///
356    /// Implementors are free to choose the concrete representation (for example,
357    /// a handle or identifier), but it must be `Clone` so that a single logical
358    /// port can be duplicated and passed to multiple consumers. New ports are
359    /// allocated via [`Self::next_port`].
360    type Port: Clone;
361    type Meta: Default;
362    type InstantiateEnv;
363
364    /// Allocates and returns a new port.
365    fn next_port(&self) -> Self::Port;
366
367    fn update_meta(&self, meta: &Self::Meta);
368
369    fn instantiate(
370        &self,
371        env: &mut Self::InstantiateEnv,
372        meta: &mut Self::Meta,
373        graph: DfirGraph,
374        extra_stmts: &[syn::Stmt],
375        sidecars: &[syn::Expr],
376        as_code_options: &AsCodeOptions,
377    );
378}
379
380pub type DynSourceSink<Out, In, InErr> = (
381    Pin<Box<dyn Stream<Item = Out>>>,
382    Pin<Box<dyn Sink<In, Error = InErr>>>,
383);
384
385pub trait RegisterPort<'a, D>: Node + Clone
386where
387    D: Deploy<'a> + ?Sized,
388{
389    fn register(&self, external_port_id: ExternalPortId, port: Self::Port);
390
391    fn as_bytes_bidi(
392        &self,
393        external_port_id: ExternalPortId,
394    ) -> impl Future<Output = DynSourceSink<Result<BytesMut, Error>, Bytes, Error>> + 'a;
395
396    fn as_bincode_bidi<InT, OutT>(
397        &self,
398        external_port_id: ExternalPortId,
399    ) -> impl Future<Output = DynSourceSink<OutT, InT, Error>> + 'a
400    where
401        InT: Serialize + 'static,
402        OutT: DeserializeOwned + 'static;
403
404    fn as_bincode_sink<T>(
405        &self,
406        external_port_id: ExternalPortId,
407    ) -> impl Future<Output = Pin<Box<dyn Sink<T, Error = Error>>>> + 'a
408    where
409        T: Serialize + 'static;
410
411    fn as_bincode_source<T>(
412        &self,
413        external_port_id: ExternalPortId,
414    ) -> impl Future<Output = Pin<Box<dyn Stream<Item = T>>>> + 'a
415    where
416        T: DeserializeOwned + 'static;
417}
418
419/// A deployment backend that can run clusters whose member IDs have type `Id`.
420/// Each backend's generated code works with particular ID types.
421/// Hydro Deploy and the simulator use `u32`, Docker, ECS, and Maelstrom use `String`, and the
422/// embedded backend accepts any type.
423/// `with_cluster` requires this trait, so a mismatch is a compile error.
424#[diagnostic::on_unimplemented(
425    message = "this deployment backend does not identify cluster members with `{Id}`",
426    note = "create the cluster with an identifier type the backend supports, for example `flow.cluster::<Tag, u32>()` for `u32`"
427)]
428pub trait SupportsMemberId<Id> {}