1use crate::core::Reason;
2use crate::{
3 Context, Declaration, Error, Result, core,
4 portable::{Outcome, Payload},
5};
6use futures::{FutureExt, future::LocalBoxFuture};
7use serde::{Serialize, de::DeserializeOwned};
8use serde_json::Value;
9#[cfg(feature = "views")]
10use std::collections::BTreeSet;
11use std::{any::Any, collections::BTreeMap, future::Future, rc::Rc};
12
13pub(crate) type Data = Rc<dyn Any>;
14pub(crate) type Factory = Rc<dyn Fn(Declaration) -> Result<Data>>;
15pub(crate) type LocalMethod =
16 Rc<dyn Fn(Data, Context, Box<dyn Any>) -> LocalBoxFuture<'static, Result<Box<dyn Any>>>>;
17pub(crate) type PortableMethod =
18 Rc<dyn Fn(Data, Context, Payload) -> LocalBoxFuture<'static, Result<Outcome>>>;
19pub(crate) type BeforeCreate = Rc<dyn Fn() -> LocalBoxFuture<'static, Result<Data>>>;
20#[cfg(feature = "views")]
21type Access = Rc<dyn Fn(&str) -> BTreeSet<String>>;
22
23#[derive(Clone)]
24pub(crate) struct Implementation {
25 pub factory: Factory,
26 pub local: BTreeMap<String, LocalMethod>,
27 pub portable: BTreeMap<String, PortableMethod>,
28 pub before_create: Option<BeforeCreate>,
29 #[cfg(feature = "rpc")]
30 pub contract: Option<Result<(String, tembra_contracts::PreparedContract, String)>>,
31 #[cfg(feature = "views")]
32 pub access: Option<Access>,
33}
34
35pub struct Service<E> {
37 pub(crate) metadata: core::Service,
38 pub(crate) implementation: Implementation,
39 marker: std::marker::PhantomData<E>,
40}
41
42pub struct Codec<A, R> {
45 pub decode: fn(Value) -> std::result::Result<A, String>,
48 pub encode: fn(R) -> std::result::Result<Value, String>,
51}
52
53impl<E: 'static> Service<E> {
54 pub fn new(
56 name: impl Into<String>,
57 create: impl Fn(Declaration) -> Result<E> + 'static,
58 ) -> Self {
59 Self {
60 metadata: core::Service::new(name, std::iter::empty::<String>()),
61 implementation: Implementation {
62 factory: Rc::new(move |declaration| Ok(Rc::new(create(declaration)?) as Data)),
63 local: BTreeMap::new(),
64 portable: BTreeMap::new(),
65 before_create: None,
66 #[cfg(feature = "rpc")]
67 contract: None,
68 #[cfg(feature = "views")]
69 access: None,
70 },
71 marker: std::marker::PhantomData,
72 }
73 }
74
75 pub fn before_create<P, F, Fut>(mut self, prepare: F) -> Self
77 where
78 P: 'static,
79 F: Fn() -> Fut + 'static,
80 Fut: Future<Output = Result<P>> + 'static,
81 {
82 self.implementation.before_create = Some(Rc::new(move || {
83 let ready = prepare();
84 async move { Ok(Rc::new(ready.await?) as Data) }.boxed_local()
85 }));
86 self
87 }
88
89 pub fn signature(mut self, signature: Option<String>) -> Self {
91 self.metadata.signature = signature;
92 self
93 }
94
95 pub fn contract(self, binding: impl Into<String>, prepared: &[u8]) -> Self {
97 let binding = binding.into();
98 #[cfg(feature = "rpc")]
99 {
100 let mut service = self;
101 service.implementation.contract = Some((|| {
102 let contract = tembra_contracts::PreparedContract::decode(prepared)
103 .map_err(|error| Error::invalid("contract", error.to_string()))?;
104 let signature = contract
105 .service_signatures()
106 .map_err(|error| Error::invalid("contract", error.to_string()))?
107 .remove(&binding)
108 .ok_or_else(|| Error::invalid("contract", "missing service signature"))?;
109 Ok((binding, contract, signature))
110 })());
111 service
112 }
113 #[cfg(not(feature = "rpc"))]
114 {
115 let _ = (binding, prepared);
116 self
117 }
118 }
119
120 pub fn lifetime(mut self, lifetime: core::Lifetime, linger_ms: u32) -> Self {
122 self.metadata.lifetime = lifetime;
123 self.metadata.linger_ms = linger_ms;
124 self
125 }
126
127 pub fn method<A, R, F, Fut>(mut self, name: impl Into<String>, handle: F) -> Self
129 where
130 A: DeserializeOwned + 'static,
131 R: Serialize + 'static,
132 F: Fn(Rc<E>, Context, A) -> Fut + 'static,
133 Fut: Future<Output = Result<R>> + 'static,
134 {
135 let name = name.into();
136 let handle = Rc::new(handle);
137 let portable = handle.clone();
138 self.implementation.local.insert(
139 name.clone(),
140 Rc::new(move |environment, context, arguments| {
141 let result = environment
142 .downcast::<E>()
143 .map_err(|_| type_error())
144 .and_then(|environment| {
145 let arguments = arguments.downcast::<A>().map_err(|_| type_error())?;
146 Ok(handle(environment, context, *arguments))
147 });
148 async move { Ok(Box::new(result?.await?) as Box<dyn Any>) }.boxed_local()
149 }),
150 );
151 self.implementation.portable.insert(
152 name.clone(),
153 Rc::new(move |environment, context, arguments: Payload| {
154 let result = environment
155 .downcast::<E>()
156 .map_err(|_| type_error())
157 .and_then(|environment| {
158 let arguments =
160 serde_json::from_value(arguments.data_only()?).map_err(|error| {
161 Error::invalid(Reason::Arguments, error.to_string())
162 })?;
163 Ok(portable(environment, context, arguments))
164 });
165 async move {
166 serde_json::to_value(result?.await?)
167 .map(|value| Payload::data(value).into())
168 .map_err(|error| Error::invalid(Reason::Result, error.to_string()))
169 }
170 .boxed_local()
171 }),
172 );
173 self.metadata.methods.insert(name);
174 self
175 }
176
177 pub fn method_with<A, R, F, Fut>(
181 mut self,
182 name: impl Into<String>,
183 handle: F,
184 codec: Codec<A, R>,
185 ) -> Self
186 where
187 A: 'static,
188 R: 'static,
189 F: Fn(Rc<E>, Context, A) -> Fut + 'static,
190 Fut: Future<Output = Result<R>> + 'static,
191 {
192 let name = name.into();
193 let handle = Rc::new(handle);
194 let portable = handle.clone();
195 let Codec { decode, encode } = codec;
196 self.implementation.local.insert(
197 name.clone(),
198 Rc::new(move |environment, context, arguments| {
199 let result = environment
200 .downcast::<E>()
201 .map_err(|_| type_error())
202 .and_then(|environment| {
203 let arguments = arguments.downcast::<A>().map_err(|_| type_error())?;
204 Ok(handle(environment, context, *arguments))
205 });
206 async move { Ok(Box::new(result?.await?) as Box<dyn Any>) }.boxed_local()
207 }),
208 );
209 self.implementation.portable.insert(
210 name.clone(),
211 Rc::new(move |environment, context, arguments: Payload| {
212 let result = environment
213 .downcast::<E>()
214 .map_err(|_| type_error())
215 .and_then(|environment| {
216 let arguments = decode(arguments.data_only()?)
218 .map_err(|message| Error::invalid(Reason::Arguments, message))?;
219 Ok(portable(environment, context, arguments))
220 });
221 async move {
222 encode(result?.await?)
223 .map(|value| Payload::data(value).into())
224 .map_err(|message| Error::invalid(Reason::Result, message))
225 }
226 .boxed_local()
227 }),
228 );
229 self.metadata.methods.insert(name);
230 self
231 }
232}
233
234impl<E: 'static> Service<E> {
235 pub fn local_method<A, R, F, Fut>(mut self, name: impl Into<String>, handle: F) -> Self
242 where
243 A: 'static,
244 R: 'static,
245 F: Fn(Rc<E>, Context, A) -> Fut + 'static,
246 Fut: Future<Output = Result<R>> + 'static,
247 {
248 let name = name.into();
249 let handle = Rc::new(handle);
250 self.implementation.local.insert(
251 name.clone(),
252 Rc::new(move |environment, context, arguments| {
253 let result = environment
254 .downcast::<E>()
255 .map_err(|_| type_error())
256 .and_then(|environment| {
257 let arguments = arguments.downcast::<A>().map_err(|_| type_error())?;
258 Ok(handle(environment, context, *arguments))
259 });
260 async move { Ok(Box::new(result?.await?) as Box<dyn Any>) }.boxed_local()
261 }),
262 );
263 self.implementation.portable.remove(&name);
264 self.metadata.methods.insert(name);
265 self
266 }
267}
268
269impl<E: 'static> Service<E> {
270 pub fn payload_method<F, Fut, R>(mut self, name: impl Into<String>, handle: F) -> Self
277 where
278 F: Fn(Rc<E>, Context, Payload) -> Fut + 'static,
279 Fut: Future<Output = Result<R>> + 'static,
280 R: Into<Outcome> + 'static,
281 {
282 let name = name.into();
283 let handle = Rc::new(handle);
284 self.implementation.portable.insert(
285 name.clone(),
286 Rc::new(move |environment, context, payload| {
287 let result = environment
288 .downcast::<E>()
289 .map_err(|_| type_error())
290 .map(|environment| handle(environment, context, payload));
291 async move { result?.await.map(Into::into) }.boxed_local()
292 }),
293 );
294 self.implementation.local.remove(&name);
295 self.metadata.methods.insert(name);
296 self
297 }
298}
299
300impl Implementation {
301 pub(crate) fn local_only(&self, method: &str) -> bool {
303 self.local.contains_key(method) && !self.portable.contains_key(method)
304 }
305}
306
307pub(crate) fn type_error() -> Error {
309 Error::invalid(
310 Reason::RustType,
311 "native argument or result type does not match the method",
312 )
313}
314
315#[derive(Clone, Debug, PartialEq, Eq)]
319pub struct Provider {
320 pub name: String,
322 pub api_version: u32,
324}
325
326impl Provider {
327 pub fn new(name: impl Into<String>, api_version: u32) -> Self {
329 Self {
330 name: name.into(),
331 api_version,
332 }
333 }
334}
335
336pub struct Orb {
338 pub(crate) metadata: core::Orb,
339 pub(crate) factory: Factory,
340 pub(crate) services: BTreeMap<String, Implementation>,
341 #[cfg(feature = "hooks")]
342 pub(crate) hooks: BTreeMap<String, crate::hooks::Signature>,
343 #[cfg(feature = "hooks")]
344 pub(crate) contributions: Vec<crate::hooks::Contribution>,
345}
346
347impl Orb {
348 pub fn new(name: impl Into<String>, api_version: u32) -> Self {
350 Self {
351 metadata: core::Orb::new(name, api_version),
352 factory: Rc::new(|_| Ok(Rc::new(()) as Data)),
353 services: BTreeMap::new(),
354 #[cfg(feature = "hooks")]
355 hooks: BTreeMap::new(),
356 #[cfg(feature = "hooks")]
357 contributions: Vec::new(),
358 }
359 }
360
361 pub fn declaration(&self) -> &core::Orb {
364 &self.metadata
365 }
366
367 pub fn requires(mut self, requirement: core::Requirement) -> Self {
369 self.metadata.requires.push(requirement);
370 #[cfg(feature = "hooks")]
371 self.bind_hook_requirements();
372 self
373 }
374
375 pub fn isolated(mut self) -> Self {
377 self.metadata.isolated = true;
378 self
379 }
380
381 pub fn service<E>(mut self, service: Service<E>) -> Self {
383 self.services
384 .insert(service.metadata.name.clone(), service.implementation);
385 self.metadata.services.push(service.metadata);
386 self
387 }
388}
389
390#[cfg(feature = "hooks")]
391impl Orb {
392 pub fn hook<A: 'static, R: 'static>(mut self, hook: crate::Hook<A, R>) -> Self {
394 if let Some(signature) = &hook.wit {
395 self.metadata
396 .hook_signatures
397 .insert(hook.name.clone(), signature.clone());
398 }
399 self.hooks.insert(hook.name.clone(), hook.identity());
400 self.metadata.hooks.insert(hook.name);
401 self
402 }
403
404 #[doc(hidden)]
406 pub fn contribute_portable<F, Fut>(
407 mut self,
408 target: impl Into<String>,
409 hook: impl Into<String>,
410 signature: impl Into<String>,
411 priority: i32,
412 handle: F,
413 ) -> Self
414 where
415 F: Fn(Context, Value) -> Fut + 'static,
416 Fut: Future<Output = Result<Option<Value>>> + 'static,
417 {
418 self.contributions.push(crate::hooks::Contribution {
419 target: target.into(),
420 hook: hook.into(),
421 priority,
422 signature: crate::hooks::Signature {
423 native: None,
424 wit: Some(signature.into()),
425 },
426 local: None,
427 portable: Rc::new(move |context, value| handle(context, value).boxed_local()),
428 });
429 self.bind_hook_requirements();
430 self
431 }
432
433 pub fn contribute<A, R, F, Fut>(
436 mut self,
437 target: impl Into<String>,
438 hook: &crate::Hook<A, R>,
439 priority: i32,
440 handle: F,
441 ) -> Self
442 where
443 A: DeserializeOwned + 'static,
444 R: 'static,
445 F: Fn(Context, A) -> Fut + 'static,
446 Fut: Future<Output = Result<R>> + 'static,
447 {
448 self.contributions
449 .push(hook.contribution(target.into(), priority, handle));
450 self.bind_hook_requirements();
451 self
452 }
453
454 fn bind_hook_requirements(&mut self) {
456 for contribution in &self.contributions {
457 let Some(signature) = &contribution.signature.wit else {
458 continue;
459 };
460 for requirement in &mut self.metadata.requires {
461 if requirement.orb == contribution.target
462 && requirement.hooks.contains(&contribution.hook)
463 {
464 requirement
465 .hook_signatures
466 .entry(contribution.hook.clone())
467 .or_insert_with(|| signature.clone());
468 }
469 }
470 }
471 }
472}
473
474impl Orb {
475 pub fn create<T: 'static>(
477 mut self,
478 create: impl Fn(Declaration) -> Result<T> + 'static,
479 ) -> Self {
480 self.factory = Rc::new(move |declaration| Ok(Rc::new(create(declaration)?) as Data));
481 self
482 }
483}
484
485#[cfg(feature = "views")]
486impl<E: 'static> Service<E> {
487 pub fn access(mut self, policy: impl Fn(&str) -> BTreeSet<String> + 'static) -> Self {
489 self.implementation.access = Some(Rc::new(policy));
490 self
491 }
492}