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

ambee/giterated

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

`giterated_cache` initial implementation

# Giterated Stack - Added the ability for dynamic substack handlers to exist for operations relevant to caching. - Added type metadata to the dynamic types. # Giterated Cache - Created - Implemented caching and fetching from cache. Hell fucking yes!!!! It works so good. Are you snooping in the commit logs because you're curious about the history of giterated? Cool that it got so big... tell me I say hi :)

Amber - ⁨2⁩ years ago

parent: tbd commit: ⁨86afeef

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