JavaScript is disabled, refresh for a better experience. ambee/giterated

ambee/giterated

Git repository hosting, collaboration, and discovery for the Fediverse.

Fix networked setting request

Amber - ⁨2⁩ years ago

parent: tbd commit: ⁨4b5330d

⁨giterated-stack/src/handler.rs⁩ - ⁨30888⁩ bytes
Raw
1 use std::{any::Any, collections::HashMap, sync::Arc};
2
3 use futures_util::FutureExt;
4 use giterated_models::{
5 authenticated::AuthenticatedPayload,
6 error::{GetValueError, OperationError},
7 instance::Instance,
8 message::GiteratedMessage,
9 object::{
10 AnyObject, GiteratedObject, Object, ObjectRequest, ObjectRequestError, ObjectResponse,
11 },
12 object_backend::ObjectBackend,
13 operation::{AnyOperation, GiteratedOperation},
14 settings::{GetSetting, GetSettingError, SetSetting, Setting},
15 value::{AnyValue, GetValue, GetValueTyped, GiteratedObjectValue},
16 };
17 use serde_json::Value;
18 use tracing::{info, trace};
19
20 use crate::{
21 GiteratedOperationHandler, ObjectMeta, ObjectOperationPair, ObjectValuePair, OperationMeta,
22 OperationWrapper, SettingMeta, StackOperationState, ValueMeta,
23 };
24
25 /// Temporary name for the next generation of Giterated stack
26 #[derive(Default)]
27 pub struct GiteratedStack {
28 operation_handlers: HashMap<ObjectOperationPair, HandlerTree>,
29 value_getters: HashMap<ObjectValuePair, OperationWrapper>,
30 setting_getters: HashMap<String, OperationWrapper>,
31 metadata: RuntimeMetadata,
32 }
33
34 impl GiteratedStack {
35 pub fn merge_builder<S: GiteratedStackState>(
36 &mut self,
37 builder: SubstackBuilder<S>,
38 ) -> &mut Self {
39 for (target, handler) in builder.operation_handlers {
40 let tree = self.get_or_create_tree(&target);
41
42 tree.push(handler);
43 }
44
45 for (target, handler) in builder.value_getters {
46 assert!(self.value_getters.insert(target, handler).is_none());
47 }
48
49 for (target, handler) in builder.setting_getters {
50 assert!(self.setting_getters.insert(target, handler).is_none());
51 }
52
53 self.metadata.append(builder.metadata);
54
55 self
56 }
57
58 fn get_or_create_tree(&mut self, target: &ObjectOperationPair) -> &mut HandlerTree {
59 if self.operation_handlers.contains_key(target) {
60 self.operation_handlers.get_mut(target).unwrap()
61 } else {
62 self.operation_handlers
63 .insert(target.clone(), HandlerTree::default());
64
65 self.operation_handlers.get_mut(target).unwrap()
66 }
67 }
68 }
69
70 pub struct HandlerTree {
71 elements: Vec<OperationWrapper>,
72 }
73
74 impl Default for HandlerTree {
75 fn default() -> Self {
76 Self { elements: vec![] }
77 }
78 }
79
80 impl HandlerTree {
81 pub fn push(&mut self, handler: OperationWrapper) {
82 self.elements.push(handler);
83 }
84
85 pub async fn handle(
86 &self,
87 object: &Box<dyn Any + Send + Sync>,
88 operation: &Box<dyn Any + Send + Sync>,
89 operation_state: &StackOperationState,
90 ) -> Result<Box<dyn Any + 'static>, OperationError<Box<dyn Any + 'static>>> {
91 for handler in self.elements.iter() {
92 match handler.handle(object, &operation, operation_state).await {
93 Ok(success) => return Ok(success),
94 Err(err) => match err {
95 OperationError::Operation(failure) => {
96 return Err(OperationError::Operation(failure))
97 }
98 OperationError::Internal(e) => return Err(OperationError::Internal(e)),
99 _ => {
100 continue;
101 }
102 },
103 }
104 }
105
106 Err(OperationError::Unhandled)
107 }
108 }
109
110 /// Stores runtime metadata for all in-use Giterated protocol types.
111 #[derive(Default)]
112 struct RuntimeMetadata {
113 objects: HashMap<String, ObjectMeta>,
114 operations: HashMap<ObjectOperationPair, OperationMeta>,
115 values: HashMap<ObjectValuePair, ValueMeta>,
116 settings: HashMap<String, SettingMeta>,
117 }
118
119 /// Defines a type that is a valid Giterated runtime state.
120 ///
121 /// This allows for extraction of state in handlers, based on a
122 /// [`FromOperationState<S>`] impl on (what is in this case) [`Self`].
123 pub trait GiteratedStackState: Send + Sync + Clone {}
124
125 impl<T: Send + Sync + Clone> GiteratedStackState for T {}
126
127 pub struct SubstackBuilder<S: GiteratedStackState> {
128 operation_handlers: HashMap<ObjectOperationPair, OperationWrapper>,
129 value_getters: HashMap<ObjectValuePair, OperationWrapper>,
130 setting_getters: HashMap<String, OperationWrapper>,
131 metadata: RuntimeMetadata,
132 state: S,
133 }
134
135 impl<S: GiteratedStackState + 'static> SubstackBuilder<S> {
136 pub fn new(state: S) -> Self {
137 Self {
138 operation_handlers: Default::default(),
139 value_getters: Default::default(),
140 setting_getters: Default::default(),
141 metadata: Default::default(),
142 state,
143 }
144 }
145 }
146
147 impl<S: GiteratedStackState + 'static> SubstackBuilder<S> {
148 /// Insert an operation handler into the runtime builder.
149 ///
150 /// # Type Registration
151 /// Inserting the handler will automatically, if required, register the operation type of the
152 /// handler. It will **not** register the object type automatically.
153 pub fn operation<A, O, D, H>(&mut self, handler: H) -> &mut Self
154 where
155 O: GiteratedObject + 'static,
156 D: GiteratedOperation<O> + 'static + Clone,
157 H: GiteratedOperationHandler<A, O, D, S> + 'static + Clone + Send + Sync,
158 D::Failure: Send + Sync,
159 D::Success: Send + Sync,
160 {
161 let object_name = handler.object_name().to_string();
162 let operation_name = handler.operation_name().to_string();
163
164 let wrapped = OperationWrapper::new(handler, self.state.clone());
165
166 let pair = ObjectOperationPair {
167 object_name,
168 operation_name,
169 };
170
171 self.operation_handlers.insert(pair, wrapped);
172
173 self.metadata.register_operation::<O, D>();
174
175 self
176 }
177
178 /// Register a [`GiteratedObject`] type with the runtime.
179 ///
180 /// # Type Registration
181 /// This will register the provided object type.
182 pub fn object<O: GiteratedObject + 'static>(&mut self) -> &mut Self {
183 self.metadata.register_object::<O>();
184
185 // Insert handler so ObjectRequest is handled properly
186 let handler = move |_object: &Instance,
187 operation: ObjectRequest,
188 _state: S,
189 _operation_state: StackOperationState,
190 stack: Arc<GiteratedStack>| {
191 async move {
192 for (_object_name, object_meta) in stack.metadata.objects.iter() {
193 if (object_meta.from_str)(&operation.0).is_ok() {
194 return Ok(ObjectResponse(operation.0));
195 }
196 }
197
198 Err(OperationError::Unhandled)
199 }
200 .boxed_local()
201 };
202
203 self.operation(handler);
204
205 self
206 }
207
208 /// Register a [`Setting`] type with the runtime.
209 ///
210 /// # Type Registration
211 /// This will register the provided setting type.
212 pub fn setting<T: Setting + 'static>(&mut self) -> &mut Self {
213 self.metadata.register_setting::<T>();
214
215 self
216 }
217
218 /// Register a [`GiteratedObjectValue<O>`] type with the runtime, providing
219 /// its associated handler for [`GetValue`].
220 ///
221 /// # Type Registration
222 /// This will register the provided [`GiteratedObjectValue`] type for its matching / specified
223 /// object type. It will **not** register the object type automatically.
224 pub fn value<O, V, A, F>(&mut self, handler: F) -> &mut Self
225 where
226 O: GiteratedObject + 'static,
227 V: GiteratedObjectValue<Object = O> + 'static + Clone,
228 F: GiteratedOperationHandler<A, O, GetValueTyped<V>, S> + Clone + 'static + Send + Sync,
229 {
230 let object_name = handler.object_name().to_string();
231 let value_name = V::value_name().to_string();
232
233 let wrapped = OperationWrapper::new(handler, self.state.clone());
234
235 let handler_object_name = object_name.clone();
236 let handler_value_name = value_name.clone();
237
238 // Insert handler so GetValue is handled properly
239 let _handler = move |object: &O,
240 operation: GetValueTyped<AnyValue<O>>,
241 _state: S,
242 operation_state: StackOperationState,
243 stack: Arc<GiteratedStack>| {
244 let stack = stack.clone();
245 let object_name = handler_object_name;
246 let value_name = handler_value_name;
247 let object = object.clone();
248 async move {
249 for (target, getter) in stack.value_getters.iter() {
250 if target.object_kind != object_name {
251 continue;
252 }
253
254 if target.value_kind != value_name {
255 continue;
256 }
257
258 return match getter
259 .handle(
260 &(Box::new(object.clone()) as Box<dyn Any + Send + Sync>),
261 &(Box::new(GetValueTyped::<V> {
262 value_name: operation.value_name,
263 ty: Default::default(),
264 }) as Box<dyn Any + Send + Sync>),
265 &operation_state,
266 )
267 .await {
268 Ok(success) => Ok(*success.downcast::<<GetValueTyped<V> as GiteratedOperation<O>>::Success>().unwrap()),
269 Err(err) => Err(match err {
270 OperationError::Operation(failure) => OperationError::Operation(*failure.downcast::<<GetValueTyped<V> as GiteratedOperation<O>>::Failure>().unwrap()),
271 OperationError::Internal(internal) => OperationError::Internal(internal),
272 OperationError::Unhandled => OperationError::Unhandled,
273 }),
274 }
275 }
276
277 Err(OperationError::Unhandled)
278 }
279 .boxed_local()
280 };
281
282 assert!(self
283 .value_getters
284 .insert(
285 ObjectValuePair {
286 object_kind: object_name,
287 value_kind: value_name
288 },
289 wrapped
290 )
291 .is_none());
292
293 self.metadata.register_value::<O, V>();
294
295 self
296 }
297
298 /// Register a handler for [`GetSetting`] for it's associated object type.
299 pub fn object_settings<O, A, F>(&mut self, handler: F) -> &mut Self
300 where
301 O: GiteratedObject + 'static,
302 F: GiteratedOperationHandler<A, O, GetSetting, S> + Clone + 'static + Send + Sync,
303 {
304 let object_name = handler.object_name().to_string();
305
306 let wrapped = OperationWrapper::new(handler, self.state.clone());
307
308 assert!(self.setting_getters.insert(object_name, wrapped).is_none());
309
310 self
311 }
312 }
313
314 impl RuntimeMetadata {
315 fn register_object<O: GiteratedObject + 'static>(&mut self) {
316 let object_name = O::object_name().to_string();
317
318 let object_meta = ObjectMeta {
319 name: object_name.clone(),
320 from_str: Box::new(|str| Ok(Box::new(O::from_str(&str).map_err(|_| ())?))),
321 any_is_same: Box::new(|any| any.is::<O>()),
322 };
323
324 if self.objects.insert(object_name, object_meta).is_some() {
325 trace!(
326 "Registration of object {} overwrote previous registration.",
327 O::object_name()
328 );
329 } else {
330 trace!("Registration of object {}.", O::object_name())
331 }
332 }
333
334 fn register_operation<O: GiteratedObject + 'static, D: GiteratedOperation<O> + 'static>(
335 &mut self,
336 ) {
337 let object_name = O::object_name().to_string();
338 let operation_name = D::operation_name().to_string();
339
340 if self
341 .operations
342 .insert(
343 ObjectOperationPair {
344 object_name: object_name.clone(),
345 operation_name: operation_name.clone(),
346 },
347 OperationMeta {
348 name: operation_name,
349 object_kind: object_name,
350 deserialize: Box::new(|bytes| {
351 Ok(Box::new(serde_json::from_slice::<D>(bytes)?)
352 as Box<dyn Any + Send + Sync>)
353 }),
354 any_is_same: Box::new(|any_box| any_box.is::<D>()),
355 serialize_success: Box::new(|any| {
356 let to_serialize = any.downcast::<D::Success>().unwrap();
357 serde_json::to_vec(&to_serialize)
358 }),
359 serialize_error: Box::new(|any| {
360 let to_serialize = any.downcast::<D::Failure>().unwrap();
361 serde_json::to_vec(&to_serialize)
362 }),
363 },
364 )
365 .is_some()
366 {
367 trace!(
368 "Registration of object operation {}<{}> overwrote previous registration.",
369 D::operation_name(),
370 O::object_name()
371 );
372 } else {
373 trace!(
374 "Registration of object operation {}<{}>.",
375 D::operation_name(),
376 O::object_name()
377 )
378 }
379 }
380
381 fn register_value<
382 O: GiteratedObject + 'static,
383 V: GiteratedObjectValue<Object = O> + 'static,
384 >(
385 &mut self,
386 ) {
387 let object_name = O::object_name().to_string();
388 let value_name = V::value_name().to_string();
389 let value_name_for_get = V::value_name().to_string();
390
391 if self
392 .values
393 .insert(
394 ObjectValuePair {
395 object_kind: object_name.clone(),
396 value_kind: value_name.clone(),
397 },
398 ValueMeta {
399 name: value_name.clone(),
400 deserialize: Box::new(|bytes| Ok(Box::new(serde_json::from_slice(&bytes)?))),
401 serialize: Box::new(|value| {
402 let value = value.downcast::<V>().unwrap();
403
404 Ok(serde_json::to_vec(&*value)?)
405 }),
406 typed_get: Box::new(move || {
407 Box::new(GetValueTyped::<V> {
408 value_name: value_name_for_get.clone(),
409 ty: Default::default(),
410 })
411 }),
412 is_get_value_typed: Box::new(move |typed| typed.is::<GetValueTyped<V>>()),
413 },
414 )
415 .is_some()
416 {
417 trace!(
418 "Registration of value <{}>::{} overwrote previous registration.",
419 O::object_name(),
420 V::value_name()
421 );
422 } else {
423 trace!(
424 "Registration of value <{}>::{}.",
425 O::object_name(),
426 V::value_name()
427 );
428 }
429 }
430
431 fn register_setting<S: Setting + 'static>(&mut self) {
432 let setting_name = S::name().to_string();
433
434 if self
435 .settings
436 .insert(
437 setting_name.clone(),
438 SettingMeta {
439 name: setting_name,
440 deserialize: Box::new(|bytes| Ok(Box::new(serde_json::from_slice(bytes)?))),
441 serialize: Box::new(|source| Ok(*source.downcast::<Value>().unwrap())),
442 },
443 )
444 .is_some()
445 {
446 trace!(
447 "Registration of setting {} overwrote previous registration.",
448 S::name()
449 );
450 } else {
451 trace!("Registration of setting {}.", S::name());
452 }
453 }
454
455 fn append(&mut self, other: Self) {
456 self.objects.extend(other.objects);
457 self.operations.extend(other.operations);
458 self.values.extend(other.values);
459 self.settings.extend(other.settings);
460 }
461 }
462 impl GiteratedStack {
463 /// Handles a giterated network message, returning either a raw success
464 /// payload or a serialized error payload.
465 pub async fn handle_network_message(
466 &self,
467 message: AuthenticatedPayload,
468 operation_state: &StackOperationState,
469 ) -> Result<Vec<u8>, OperationError<Vec<u8>>> {
470 let message: GiteratedMessage<AnyObject, AnyOperation> = message.into_message();
471
472 // Deserialize the object, also getting the object type's name
473 let (object_type, object) = {
474 let mut result = None;
475
476 for (object_type, object_meta) in self.metadata.objects.iter() {
477 if let Ok(object) = (object_meta.from_str)(&message.object.0) {
478 result = Some((object_type.clone(), object));
479 break;
480 }
481 }
482
483 result
484 }
485 .ok_or_else(|| OperationError::Unhandled)?;
486
487 trace!(
488 "Handling network message {}::<{}>",
489 message.operation,
490 object_type
491 );
492
493 if message.operation == "get_value" {
494 // Special case
495 let operation: GetValue = serde_json::from_slice(&message.payload.0).unwrap();
496
497 return self
498 .network_get_value(object, object_type.clone(), operation, operation_state)
499 .await;
500 } else if message.operation == "get_setting" {
501 let operation: GetSetting = serde_json::from_slice(&message.payload.0).unwrap();
502 info!("1");
503 let setting_meta = self
504 .metadata
505 .settings
506 .get(&operation.setting_name)
507 .ok_or_else(|| OperationError::Unhandled)?;
508 info!("2");
509 let raw_result = self
510 .get_setting(object, object_type.clone(), operation, operation_state)
511 .await;
512 info!("3");
513 return match raw_result {
514 Ok(success) => {
515 info!("3a");
516 // Success is the setting type, serialize it
517 let serialized = (setting_meta.serialize)(success).unwrap();
518
519 Ok(serde_json::to_vec(&serialized).unwrap())
520 }
521 Err(err) => Err(match err {
522 OperationError::Operation(failure) => {
523 info!("3b");
524 // We know how to resolve this type
525 let failure: GetSettingError = *failure.downcast().unwrap();
526
527 OperationError::Operation(serde_json::to_vec(&failure).unwrap())
528 }
529 OperationError::Internal(internal) => OperationError::Internal(internal),
530 OperationError::Unhandled => OperationError::Unhandled,
531 }),
532 };
533 }
534
535 let target = ObjectOperationPair {
536 object_name: object_type.clone(),
537 operation_name: message.operation.clone(),
538 };
539
540 // Resolve the target operations from the handlers table
541 let handler = self
542 .operation_handlers
543 .get(&target)
544 .ok_or_else(|| OperationError::Unhandled)?;
545
546 trace!(
547 "Resolved operation handler for network message {}::<{}>",
548 message.operation,
549 object_type
550 );
551
552 // Deserialize the operation
553 let meta = self
554 .metadata
555 .operations
556 .get(&target)
557 .ok_or_else(|| OperationError::Unhandled)?;
558
559 let operation = (meta.deserialize)(&message.payload.0)
560 .map_err(|e| OperationError::Internal(e.to_string()))?;
561
562 trace!(
563 "Deserialized operation for network message {}::<{}>",
564 message.operation,
565 object_type
566 );
567
568 trace!(
569 "Calling handler for network message {}::<{}>",
570 message.operation,
571 object_type
572 );
573
574 // Get the raw result of the operation, where the return values are boxed.
575 let raw_result = handler.handle(&object, &operation, operation_state).await;
576
577 trace!(
578 "Finished handling network message {}::<{}>",
579 message.operation,
580 object_type
581 );
582
583 // Deserialize the raw result for the network
584 match raw_result {
585 Ok(success) => Ok((meta.serialize_success)(success)
586 .map_err(|e| OperationError::Internal(e.to_string()))?),
587 Err(err) => Err(match err {
588 OperationError::Operation(failure) => OperationError::Operation(
589 (meta.serialize_error)(failure)
590 .map_err(|e| OperationError::Internal(e.to_string()))?,
591 ),
592 OperationError::Internal(internal) => OperationError::Internal(internal),
593 OperationError::Unhandled => OperationError::Unhandled,
594 }),
595 }
596 }
597
598 pub async fn network_get_value(
599 &self,
600 object: Box<dyn Any + Send + Sync>,
601 object_kind: String,
602 operation: GetValue,
603 operation_state: &StackOperationState,
604 ) -> Result<Vec<u8>, OperationError<Vec<u8>>> {
605 trace!("Handling network get_value for {}", operation.value_name);
606
607 let value_meta = self
608 .metadata
609 .values
610 .get(&ObjectValuePair {
611 object_kind: object_kind.clone(),
612 value_kind: operation.value_name.clone(),
613 })
614 .ok_or_else(|| OperationError::Unhandled)?;
615
616 for (target, getter) in self.value_getters.iter() {
617 if target.object_kind != object_kind {
618 continue;
619 }
620
621 if target.value_kind != operation.value_name {
622 continue;
623 }
624
625 return match getter
626 .handle(&(object), &((value_meta.typed_get)()), &operation_state)
627 .await
628 {
629 Ok(success) => {
630 // Serialize success, which is the value type itself
631 let serialized = (value_meta.serialize)(success)
632 .map_err(|e| OperationError::Internal(e.to_string()))?;
633
634 Ok(serialized)
635 }
636 Err(err) => Err(match err {
637 OperationError::Operation(failure) => {
638 // Failure is sourced from GetValue operation, but this is hardcoded for now
639 let failure: GetValueError = *failure.downcast().unwrap();
640
641 OperationError::Operation(
642 serde_json::to_vec(&failure)
643 .map_err(|e| OperationError::Internal(e.to_string()))?,
644 )
645 }
646 OperationError::Internal(internal) => OperationError::Internal(internal),
647 OperationError::Unhandled => OperationError::Unhandled,
648 }),
649 };
650 }
651
652 Err(OperationError::Unhandled)
653 }
654
655 pub async fn get_setting(
656 &self,
657 object: Box<dyn Any + Send + Sync>,
658 object_kind: String,
659 operation: GetSetting,
660 operation_state: &StackOperationState,
661 ) -> Result<Box<dyn Any + Send + Sync>, OperationError<Box<dyn Any + Send + Sync>>> {
662 trace!(
663 "Handling network {}::get_setting for {}",
664 object_kind,
665 operation.setting_name
666 );
667
668 let setting_getter = self
669 .setting_getters
670 .get(&object_kind)
671 .ok_or_else(|| OperationError::Unhandled)?;
672
673 setting_getter
674 .handle(&object, &(Box::new(operation) as Box<_>), operation_state)
675 .await
676 }
677
678 pub async fn network_set_setting(
679 &self,
680 _operation: SetSetting,
681 _operation_state: &StackOperationState,
682 ) -> Result<Vec<u8>, OperationError<Vec<u8>>> {
683 todo!()
684 }
685 }
686
687 use core::fmt::Debug;
688
689 #[async_trait::async_trait(?Send)]
690 impl ObjectBackend<StackOperationState> for Arc<GiteratedStack> {
691 async fn object_operation<O, D>(
692 &self,
693 in_object: O,
694 operation_name: &str,
695 payload: D,
696 operation_state: &StackOperationState,
697 ) -> Result<D::Success, OperationError<D::Failure>>
698 where
699 O: GiteratedObject + Debug + 'static,
700 D: GiteratedOperation<O> + Debug + 'static,
701 {
702 // Erase object and operation types.
703 let object = Box::new(in_object.clone()) as Box<dyn Any + Send + Sync>;
704 let operation = Box::new(payload) as Box<dyn Any + Send + Sync>;
705
706 // We need to determine the type of the object, iterate through all known
707 // object types and check if the &dyn Any we have is the same type as the
708 // object type.
709 let object_type = {
710 let mut object_type = None;
711
712 for (object_name, object_meta) in self.metadata.objects.iter() {
713 if (object_meta.any_is_same)(&in_object) {
714 object_type = Some(object_name.clone());
715 break;
716 }
717 }
718
719 object_type
720 }
721 .ok_or_else(|| OperationError::Unhandled)?;
722
723 // We need to hijack get_value, set_setting, and get_setting.
724 if operation_name == "get_value" {
725 let mut value_meta = None;
726 for (_, meta) in self.metadata.values.iter() {
727 if (meta.is_get_value_typed)(&operation) {
728 value_meta = Some(meta);
729 break;
730 }
731 }
732
733 let value_meta = value_meta.ok_or_else(|| OperationError::Unhandled)?;
734
735 let value_name = value_meta.name.clone();
736
737 trace!("Handling get_value for {}::{}", object_type, value_name);
738
739 for (target, getter) in self.value_getters.iter() {
740 if target.object_kind != object_type {
741 continue;
742 }
743
744 if target.value_kind != value_name {
745 continue;
746 }
747
748 return match getter
749 .handle(&(object), &((value_meta.typed_get)()), &operation_state)
750 .await
751 {
752 Ok(success) => Ok(*success.downcast().unwrap()),
753 Err(err) => Err(match err {
754 OperationError::Operation(failure) => {
755 OperationError::Operation(*failure.downcast::<D::Failure>().unwrap())
756 }
757 OperationError::Internal(internal) => OperationError::Internal(internal),
758 OperationError::Unhandled => OperationError::Unhandled,
759 }),
760 };
761 }
762
763 return Err(OperationError::Unhandled);
764 } else if operation.is::<GetSetting>() {
765 let get_setting: Box<GetSetting> = operation.downcast().unwrap();
766 let _setting_name = get_setting.setting_name.clone();
767
768 let _setting_meta = self
769 .metadata
770 .settings
771 .get(&object_type)
772 .ok_or_else(|| OperationError::Unhandled)?;
773
774 let raw_result = self
775 .get_setting(object, object_type.clone(), *get_setting, operation_state)
776 .await;
777
778 return match raw_result {
779 Ok(success) => {
780 // Success is the setting type, serialize it
781 // let serialized = (setting_meta.serialize)(success).unwrap();
782
783 // Ok(serde_json::to_vec(&serialized).unwrap())
784 Ok(*success.downcast().unwrap())
785 }
786 Err(err) => Err(match err {
787 OperationError::Operation(failure) => {
788 // We know this is the right type
789 OperationError::Operation(*failure.downcast().unwrap())
790 }
791 OperationError::Internal(internal) => OperationError::Internal(internal),
792 OperationError::Unhandled => OperationError::Unhandled,
793 }),
794 };
795 } else if operation.is::<SetSetting>() {
796 todo!()
797 } else if operation.is::<ObjectRequest>() {
798 todo!()
799 }
800
801 // Resolve the operation from the known operations table.
802 let operation_type = {
803 let mut operation_type = None;
804
805 for (target, operation_meta) in self.metadata.operations.iter() {
806 // Skip elements that we know will not match
807 if target.object_name != object_type {
808 continue;
809 }
810
811 if target.operation_name != operation_name {
812 continue;
813 }
814
815 if (operation_meta.any_is_same)(&operation) {
816 operation_type = Some(target.clone());
817 break;
818 }
819 }
820
821 operation_type
822 }
823 .ok_or_else(|| OperationError::Unhandled)?;
824
825 // Resolve the handler from our handler tree
826 let handler_tree = self
827 .operation_handlers
828 .get(&operation_type)
829 .ok_or_else(|| OperationError::Unhandled)?;
830
831 let raw_result = handler_tree
832 .handle(&object, &operation, operation_state)
833 .await;
834
835 // Convert the dynamic result back into its concrete type
836 match raw_result {
837 Ok(result) => Ok(*result.downcast::<D::Success>().unwrap()),
838 Err(err) => Err(match err {
839 OperationError::Internal(internal) => OperationError::Internal(internal),
840 OperationError::Operation(boxed_error) => {
841 OperationError::Operation(*boxed_error.downcast::<D::Failure>().unwrap())
842 }
843 OperationError::Unhandled => OperationError::Unhandled,
844 }),
845 }
846 }
847
848 async fn get_object<O: GiteratedObject + Debug + 'static>(
849 &self,
850 object_str: &str,
851 _operation_state: &StackOperationState,
852 ) -> Result<Object<StackOperationState, O, Self>, OperationError<ObjectRequestError>> {
853 // TODO: Authorization?
854 for (_object_name, object_meta) in self.metadata.objects.iter() {
855 if let Ok(object) = (object_meta.from_str)(object_str) {
856 return Ok(unsafe {
857 Object::new_unchecked(*object.downcast::<O>().unwrap(), self.clone())
858 });
859 }
860 }
861
862 Err(OperationError::Unhandled)
863 }
864 }
865