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

ambee/giterated

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

Fix internal call values

Amber - ⁨2⁩ years ago

parent: tbd commit: ⁨8e8ab90

⁨giterated-stack/src/stack.rs⁩ - ⁨31052⁩ 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};
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 .unwrap();
370
371 let setting = (setting_meta.deserialize)(operation.value)
372 .as_internal_error_with_context(format!(
373 "deserializing setting {} for object {}",
374 operation.setting_name, object_type
375 ))?;
376
377 trace!(
378 "Deserialized setting {} for object {}",
379 operation.setting_name,
380 object_type,
381 );
382
383 for provider in self.metadata_providers.iter() {
384 if provider.provides_for(object.0.as_ref()) {
385 trace!(
386 "Resolved setting provider for setting {} for object {}",
387 operation.setting_name,
388 object_type,
389 );
390
391 let object_meta = self
392 .metadata
393 .objects
394 .get(&object_type)
395 .ok_or_else(|| OperationError::Unhandled)?;
396
397 let raw_result = provider
398 .write(object.clone(), object_meta, setting.clone(), setting_meta)
399 .await;
400
401 return match raw_result {
402 Ok(_) => {
403 (setting_meta.setting_updated)(
404 object,
405 setting,
406 operation_state.runtime.clone(),
407 operation_state,
408 )
409 .await;
410
411 Ok(serde_json::to_vec(&()).unwrap())
412 }
413 Err(e) => Err(OperationError::Internal(e.context(format!(
414 "writing object {} setting {}",
415 object_type, operation.setting_name
416 )))),
417 };
418 }
419
420 trace!(
421 "Failed to resolve setting provider for setting {} for object {}",
422 operation.setting_name,
423 object_type,
424 );
425 }
426 }
427
428 let target = ObjectOperationPair {
429 object_name: &object_type,
430 operation_name: &message.operation,
431 };
432
433 // Resolve the target operations from the handlers table
434 let handler = self
435 .operation_handlers
436 .get(&target)
437 .ok_or_else(|| OperationError::Unhandled)?;
438
439 trace!(
440 "Resolved operation handler for network message {}::<{}>",
441 message.operation,
442 object_type
443 );
444
445 // Deserialize the operation
446 let meta = self
447 .metadata
448 .operations
449 .get(&target)
450 .ok_or_else(|| OperationError::Unhandled)?;
451
452 let operation =
453 (meta.deserialize)(&message.payload.0).as_internal_error_with_context(format!(
454 "deserializing operation {}::{}",
455 target.object_name, target.operation_name
456 ))?;
457
458 trace!(
459 "Deserialized operation for network message {}::<{}>",
460 message.operation,
461 object_type
462 );
463
464 trace!(
465 "Calling handler for network message {}::<{}>",
466 message.operation,
467 object_type
468 );
469
470 // Get the raw result of the operation, where the return values are boxed.
471 let raw_result = handler
472 .handle((object.clone(), operation.clone()), operation_state.clone())
473 .await;
474
475 trace!(
476 "Finished handling network message {}::<{}>",
477 message.operation,
478 object_type
479 );
480
481 // Deserialize the raw result for the network
482 match raw_result {
483 Ok(success) => Ok((meta.serialize_success)(success).as_internal_error()?),
484 Err(err) => Err(match err {
485 OperationError::Operation(failure) => {
486 OperationError::Operation((meta.serialize_error)(failure).as_internal_error()?)
487 }
488 OperationError::Internal(internal) => {
489 OperationError::Internal(internal.context(format!(
490 "operation {}::{} handler outcome",
491 target.object_name, target.operation_name
492 )))
493 }
494 OperationError::Unhandled => OperationError::Unhandled,
495 }),
496 }
497 }
498
499 pub async fn network_get_value(
500 &self,
501 object: AnyObject,
502 object_kind: String,
503 operation: GetValue,
504 operation_state: &StackOperationState,
505 ) -> Result<Vec<u8>, OperationError<Vec<u8>>> {
506 trace!("Handling network get_value for {}", operation.value_name);
507
508 let value_meta = self
509 .metadata
510 .values
511 .get(&ObjectValuePair {
512 object_kind: &object_kind,
513 value_kind: &operation.value_name,
514 })
515 .ok_or_else(|| OperationError::Unhandled)?;
516
517 for (target, getter) in self.value_getters.iter() {
518 if target.object_kind != object_kind {
519 continue;
520 }
521
522 if target.value_kind != operation.value_name {
523 continue;
524 }
525
526 return match getter
527 .handle((object.clone(),), operation_state.clone())
528 .await
529 {
530 Ok(success) => {
531 // Serialize success, which is the value type itself
532 let serialized = (value_meta.serialize)(success).as_internal_error()?;
533
534 Ok(serialized)
535 }
536 Err(err) => Err(match err {
537 OperationError::Operation(failure) => {
538 // Failure is sourced from GetValue operation, but this is hardcoded for now
539 let failure: &GetValueError = failure.0.downcast_ref().unwrap();
540
541 OperationError::Operation(serde_json::to_vec(&failure).as_internal_error()?)
542 }
543 OperationError::Internal(internal) => OperationError::Internal(internal),
544 OperationError::Unhandled => OperationError::Unhandled,
545 }),
546 };
547 }
548
549 Err(OperationError::Unhandled)
550 }
551
552 pub async fn get_setting(
553 &self,
554 object: AnyObject,
555 object_kind: String,
556 operation: GetSetting,
557 _operation_state: &StackOperationState,
558 ) -> Result<AnySetting, OperationError<Box<dyn Any + Send + Sync>>> {
559 trace!(
560 "Handling network {}::get_setting for {}",
561 object_kind,
562 operation.setting_name
563 );
564
565 for provider in self.metadata_providers.iter() {
566 if provider.provides_for(object.0.as_ref()) {
567 let setting_meta = self
568 .metadata
569 .settings
570 .get(&ObjectSettingPair {
571 object_kind: &object_kind,
572 setting_name: &operation.setting_name,
573 })
574 .ok_or_else(|| OperationError::Unhandled)?;
575
576 let object_meta = self
577 .metadata
578 .objects
579 .get(&object_kind)
580 .ok_or_else(|| OperationError::Unhandled)?;
581
582 let result = provider
583 .read(object.clone(), object_meta, setting_meta)
584 .await
585 .as_internal_error_with_context(format!(
586 "reading setting {}",
587 operation.setting_name
588 ))?;
589
590 return (setting_meta.deserialize)(result).as_internal_error_with_context(format!(
591 "deserializing setting {}",
592 operation.setting_name
593 ));
594 }
595 }
596
597 trace!("setting {} doesn't exist", operation.setting_name);
598
599 Err(OperationError::Unhandled)
600 }
601
602 pub async fn network_set_setting(
603 &self,
604 object: AnyObject,
605 object_kind: String,
606 operation: SetSetting,
607 operation_state: &StackOperationState,
608 ) -> Result<Vec<u8>, OperationError<Vec<u8>>> {
609 trace!(
610 "Handling network {}::set_setting for {}",
611 object_kind,
612 operation.setting_name
613 );
614
615 let target = ObjectSettingPair {
616 object_kind: &object_kind,
617 setting_name: &operation.setting_name,
618 };
619
620 let handler = self.setting_change.get(&target).unwrap();
621
622 let setting_meta = self
623 .metadata
624 .settings
625 .get(&ObjectSettingPair {
626 object_kind: &object_kind,
627 setting_name: &operation.setting_name,
628 })
629 .ok_or_else(|| OperationError::Unhandled)?;
630
631 let setting =
632 (setting_meta.deserialize)(operation.value).as_internal_error_with_context(format!(
633 "deserializing setting {} for object {}",
634 operation.setting_name, object_kind
635 ))?;
636
637 let raw_result = handler
638 .handle((object, setting.clone()), operation_state.clone())
639 .await;
640
641 match raw_result {
642 Ok(_) => {
643 // Serialize success, which is the value type itself
644 let serialized = serde_json::to_vec(&()).as_internal_error()?;
645
646 Ok(serialized)
647 }
648 Err(err) => Err(match err {
649 OperationError::Operation(operation) => OperationError::Internal(operation),
650 OperationError::Internal(internal) => OperationError::Internal(internal),
651 OperationError::Unhandled => OperationError::Unhandled,
652 }),
653 }
654 }
655 }
656
657 #[async_trait::async_trait(?Send)]
658 impl ObjectBackend<StackOperationState> for Arc<GiteratedStack> {
659 async fn object_operation<O, D>(
660 &self,
661 in_object: O,
662 operation_name: &str,
663 payload: D,
664 operation_state: &StackOperationState,
665 ) -> Result<D::Success, OperationError<D::Failure>>
666 where
667 O: GiteratedObject + Debug + 'static,
668 D: GiteratedOperation<O> + Debug + 'static,
669 D::Success: Clone,
670 D::Failure: Clone,
671 {
672 // Erase object and operation types.
673 let object = AnyObject(Arc::new(in_object.clone()) as Arc<dyn Any + Send + Sync>);
674 let operation = AnyOperation(Arc::new(payload) as Arc<dyn Any + Send + Sync>);
675
676 // We need to hijack get_value, set_setting, and get_setting.
677 if operation_name == "get_value" {
678 let get_value = operation
679 .0
680 .downcast_ref::<GetValue>()
681 .ok_or_else(|| OperationError::Unhandled)?;
682
683 let value_meta = self
684 .metadata
685 .values
686 .get(&ObjectValuePair {
687 object_kind: O::object_name(),
688 value_kind: &get_value.value_name,
689 })
690 .ok_or_else(|| OperationError::Unhandled)?;
691 let value_name = value_meta.name.clone();
692
693 trace!(
694 "Handling get_value for {}::{}",
695 O::object_name(),
696 value_name
697 );
698
699 for (target, getter) in self.value_getters.iter() {
700 if target.object_kind != O::object_name() {
701 continue;
702 }
703
704 if target.value_kind != value_name {
705 continue;
706 }
707
708 trace!(
709 "Calling handler for get_value {}::{}",
710 O::object_name(),
711 value_name
712 );
713
714 return match getter
715 .handle((object.clone(),), operation_state.clone())
716 .await
717 {
718 Ok(success) => Ok(*(Box::new((value_meta.serialize)(success).unwrap())
719 as Box<dyn Any>)
720 .downcast()
721 .unwrap()),
722 Err(err) => Err(match err {
723 OperationError::Operation(failure) => OperationError::Operation(
724 failure.0.downcast_ref::<D::Failure>().unwrap().clone(),
725 ),
726 OperationError::Internal(internal) => {
727 OperationError::Internal(internal.context(format!(
728 "{}::get_value::<{}> handler outcome",
729 O::object_name(),
730 value_name
731 )))
732 }
733 OperationError::Unhandled => OperationError::Unhandled,
734 }),
735 };
736 }
737 } else if operation.0.is::<GetSetting>() {
738 let get_setting: &GetSetting = operation.0.downcast_ref().unwrap();
739 let setting_name = get_setting.setting_name.clone();
740
741 let raw_result = self
742 .get_setting(
743 object,
744 O::object_name().to_string(),
745 get_setting.clone(),
746 operation_state,
747 )
748 .await;
749
750 return match raw_result {
751 Ok(success) => {
752 // Success is the setting type, serialize it
753 // let serialized = (setting_meta.serialize)(success).unwrap();
754
755 // Ok(serde_json::to_vec(&serialized).unwrap())
756 Ok(success.0.downcast_ref::<D::Success>().unwrap().clone())
757 }
758 Err(err) => Err(match err {
759 OperationError::Operation(failure) => {
760 // We know this is the right type
761 OperationError::Operation(*failure.downcast().unwrap())
762 }
763 OperationError::Internal(internal) => {
764 OperationError::Internal(internal.context(format!(
765 "{}::get_setting::<{}> handler outcome",
766 O::object_name(),
767 setting_name
768 )))
769 }
770 OperationError::Unhandled => OperationError::Unhandled,
771 }),
772 };
773 } else if operation.0.is::<SetSetting>() {
774 todo!()
775 } else if operation.0.is::<ObjectRequest>() {
776 todo!()
777 }
778
779 // Resolve the operation from the known operations table.
780 let operation_type = {
781 let mut operation_type = None;
782
783 for (target, operation_meta) in self.metadata.operations.iter() {
784 // Skip elements that we know will not match
785 if target.object_name != O::object_name() {
786 continue;
787 }
788
789 if target.operation_name != operation_name {
790 continue;
791 }
792
793 if (operation_meta.any_is_same)(&operation) {
794 operation_type = Some(target.clone());
795 break;
796 }
797 }
798
799 operation_type
800 }
801 .ok_or_else(|| OperationError::Unhandled)?;
802
803 // Resolve the handler from our handler tree
804 let handler_tree = self
805 .operation_handlers
806 .get(&operation_type)
807 .ok_or_else(|| OperationError::Unhandled)?;
808
809 let raw_result = handler_tree
810 .handle((object, operation), operation_state.clone())
811 .await;
812
813 // Convert the dynamic result back into its concrete type
814 match raw_result {
815 Ok(result) => Ok(result.0.downcast_ref::<D::Success>().unwrap().clone()),
816 Err(err) => Err(match err {
817 OperationError::Internal(internal) => {
818 OperationError::Internal(internal.context(format!(
819 "operation {}::{} handler outcome",
820 operation_type.object_name, operation_type.operation_name
821 )))
822 }
823 OperationError::Operation(boxed_error) => OperationError::Operation(
824 boxed_error.0.downcast_ref::<D::Failure>().unwrap().clone(),
825 ),
826 OperationError::Unhandled => OperationError::Unhandled,
827 }),
828 }
829 }
830
831 async fn get_object<O>(
832 &self,
833 object_str: &str,
834 _operation_state: &StackOperationState,
835 ) -> Result<Object<StackOperationState, O, Self>, OperationError<ObjectRequestError>>
836 where
837 O: GiteratedObject + Debug + 'static,
838 {
839 // TODO: Authorization?
840 for (_object_name, object_meta) in self.metadata.objects.iter() {
841 if let Ok(object) = (object_meta.from_str)(object_str) {
842 return Ok(unsafe {
843 Object::new_unchecked(
844 object.0.downcast_ref::<O>().unwrap().clone(),
845 self.clone(),
846 )
847 });
848 }
849 }
850
851 Err(OperationError::Unhandled)
852 }
853 }
854
855 /// Defines a type that is a valid Giterated runtime state.
856 ///
857 /// This allows for extraction of state in handlers, based on a
858 /// [`FromOperationState<S>`] impl on (what is in this case) [`Self`].
859 pub trait GiteratedStackState: Send + Sync + Clone {}
860
861 impl<T: Send + Sync + Clone> GiteratedStackState for T {}
862
863 #[async_trait::async_trait(?Send)]
864 impl<R, S, T> HandlerResolvable<R, S> for Option<T>
865 where
866 T: HandlerResolvable<R, S>,
867 {
868 type Error = MissingValue;
869
870 async fn from_handler_state(
871 required_parameters: &R,
872 operation_state: &S,
873 ) -> Result<Option<T>, MissingValue> {
874 Ok(T::from_handler_state(required_parameters, operation_state)
875 .await
876 .ok())
877 }
878 }
879