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

ambee/giterated

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

Remove unwrap statements and return OperationError's

erremilia - ⁨2⁩ years ago

parent: tbd commit: ⁨cf491a4

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