1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
use bytes::Bytes;
use wasmrs_frames::{Metadata, PayloadError, RawPayload};
use wasmrs_runtime::RtRc;

use crate::operations::OperationList;
use crate::{BoxFlux, BoxMono};

/// An alias to [Box<dyn std::error::Error + Send + Sync + 'static>]
pub type GenericError = Box<dyn std::error::Error + Send + Sync + 'static>;
/// An alias for a [Vec<(String, String, RtRc<T>)>]
pub type OperationMap<T> = Vec<(String, String, RtRc<T>)>;
/// An alias for the function that creates the output for a task.
pub type OperationHandler<I, O> = Box<dyn Fn(I) -> Result<O, GenericError> + Send + Sync>;

/// An alias for [Mono<ParsedPayload, PayloadError>]
pub type IncomingMono = BoxMono<Payload, PayloadError>;
/// An alias for [Mono<Payload, PayloadError>]
pub type OutgoingMono = BoxMono<RawPayload, PayloadError>;
/// An alias for [FluxReceiver<ParsedPayload, PayloadError>]
pub type IncomingStream = BoxFlux<Payload, PayloadError>;
/// An alias for [FluxReceiver<Payload, PayloadError>]
pub type OutgoingStream = BoxFlux<RawPayload, PayloadError>;

#[allow(missing_debug_implementations)]
#[derive(Debug)]
/// A [Payload] with pre-parsed [Metadata].
pub struct Payload {
  /// The parsed [Metadata].
  pub metadata: Metadata,
  /// The raw data bytes.
  pub data: Bytes,
}

impl Payload {
  /// Create a new [ParsedPayload] from the given [Metadata] and [Bytes].
  pub fn new(metadata: Metadata, data: Bytes) -> Self {
    Self { metadata, data }
  }
}

impl TryFrom<RawPayload> for Payload {
  type Error = crate::Error;

  fn try_from(mut value: RawPayload) -> Result<Self, Self::Error> {
    Ok(Payload {
      metadata: value.parse_metadata()?,
      data: value.data.unwrap_or_default(),
    })
  }
}

#[derive(Default)]
/// A list of all the operations exported by a wasmrs implementer.
pub struct Handlers {
  op_list: OperationList,
  request_response_handlers: OperationMap<OperationHandler<IncomingMono, OutgoingMono>>,
  request_stream_handlers: OperationMap<OperationHandler<IncomingMono, OutgoingStream>>,
  request_channel_handlers: OperationMap<OperationHandler<IncomingStream, OutgoingStream>>,
  request_fnf_handlers: OperationMap<OperationHandler<IncomingMono, ()>>,
}

impl std::fmt::Debug for Handlers {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    f.debug_struct("Handlers").field("op_list", &self.op_list).finish()
  }
}

impl Handlers {
  /// Get the operation list.
  pub fn op_list(&self) -> &OperationList {
    &self.op_list
  }

  /// Register a Request/Response style handler on the host.
  pub fn register_request_response(
    &mut self,
    ns: impl AsRef<str>,
    op: impl AsRef<str>,
    handler: OperationHandler<IncomingMono, OutgoingMono>,
  ) -> usize {
    let list = &mut self.request_response_handlers;
    list.push((ns.as_ref().to_owned(), op.as_ref().to_owned(), RtRc::new(handler)));
    let index = list.len() - 1;
    self
      .op_list
      .add_export(index as _, crate::OperationType::RequestResponse, ns, op);
    index
  }

  /// Register a Request/Response style handler on the host.
  pub fn register_request_stream(
    &mut self,
    ns: impl AsRef<str>,
    op: impl AsRef<str>,
    handler: OperationHandler<IncomingMono, OutgoingStream>,
  ) -> usize {
    let list = &mut self.request_stream_handlers;
    list.push((ns.as_ref().to_owned(), op.as_ref().to_owned(), RtRc::new(handler)));
    let index = list.len() - 1;
    self
      .op_list
      .add_export(index as _, crate::OperationType::RequestStream, ns, op);
    index
  }

  /// Register a Request/Response style handler on the host.
  pub fn register_request_channel(
    &mut self,
    ns: impl AsRef<str>,
    op: impl AsRef<str>,
    handler: OperationHandler<IncomingStream, OutgoingStream>,
  ) -> usize {
    let list = &mut self.request_channel_handlers;
    list.push((ns.as_ref().to_owned(), op.as_ref().to_owned(), RtRc::new(handler)));
    let index = list.len() - 1;
    self
      .op_list
      .add_export(index as _, crate::OperationType::RequestChannel, ns, op);
    index
  }

  /// Register a Request/Response style handler on the host.
  pub fn register_fire_and_forget(
    &mut self,
    ns: impl AsRef<str>,
    op: impl AsRef<str>,
    handler: OperationHandler<IncomingMono, ()>,
  ) -> usize {
    let list = &mut self.request_fnf_handlers;
    list.push((ns.as_ref().to_owned(), op.as_ref().to_owned(), RtRc::new(handler)));
    let index = list.len() - 1;
    self
      .op_list
      .add_export(index as _, crate::OperationType::RequestFnF, ns, op);
    index
  }

  #[must_use]
  /// Get a Request/Response handler by id.
  pub fn get_request_response_handler(&self, index: u32) -> Option<RtRc<OperationHandler<IncomingMono, OutgoingMono>>> {
    let a = self
      .request_response_handlers
      .get(index as usize)
      .map(|(_, _, h)| h.clone());
    a
  }
  #[must_use]
  /// Get a Request/Response handler by id.
  pub fn get_request_stream_handler(&self, index: u32) -> Option<RtRc<OperationHandler<IncomingMono, OutgoingStream>>> {
    let a = self
      .request_stream_handlers
      .get(index as usize)
      .map(|(_, _, h)| h.clone());
    a
  }
  #[must_use]
  /// Get a Request/Response handler by id.
  pub fn get_request_channel_handler(
    &self,
    index: u32,
  ) -> Option<RtRc<OperationHandler<IncomingStream, OutgoingStream>>> {
    let a = self
      .request_channel_handlers
      .get(index as usize)
      .map(|(_, _, h)| h.clone());
    a
  }
  #[must_use]
  /// Get a Request/Response handler by id.
  pub fn get_fnf_handler(&self, index: u32) -> Option<RtRc<OperationHandler<IncomingMono, ()>>> {
    let a = self.request_fnf_handlers.get(index as usize).map(|(_, _, h)| h.clone());
    a
  }
}