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