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

ambee/giterated

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

Create `NetworkedSubstack`.

# giterated-protocol - Create `NetworkedSubstack` which will handle all networked operations giterated needs - Add support for `NetworkedSubstack` for both the daemon and client - Pipe everything through but leave APIs temp # `giterated-daemon` - Remove a bunch of random old code, dead code, and files that aren't needed. - Moved all connection handling to `client.rs`, simplified connection logic with new types

Amber - ⁨2⁩ years ago

parent: tbd commit: ⁨202bb12

⁨giterated-stack/src/stack.rs⁩ - ⁨44316⁩ 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;
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>(
95 &self,
96 object: O,
97 new_value: AnyValue,
98 operation_state: &StackOperationState,
99 ) where
100 O: GiteratedObject + 'static,
101 {
102 trace!(
103 "value updated {}::{}",
104 O::object_name(),
105 new_value.kind().value_kind
106 );
107 let object = AnyObject::new(object);
108
109 // First, resolve a handler for the exact object value pair
110 if let Some(handler) = self.value_change.get(&new_value.kind()) {
111 // TODO
112 let _ = handler
113 .handle((object.clone(), new_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: new_value.kind().value_kind,
121 };
122 if let Some(handler) = self.value_change.get(&target) {
123 // TODO
124 let _ = handler
125 .handle((object.clone(), new_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(), new_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(), new_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 if let Some(handler) = self.value_getters.get(&ObjectValuePair {
867 object_kind: "any",
868 value_kind: &get_value.value_name,
869 }) {
870 match handler
871 .handle(
872 (object.clone(), get_value.value_name.clone()),
873 operation_state.clone(),
874 )
875 .await
876 {
877 Ok(success) => {
878 self.value_update(in_object, success.clone(), operation_state)
879 .await;
880
881 return Ok(*(Box::new((value_meta.serialize)(success).unwrap())
882 as Box<dyn Any>)
883 .downcast()
884 .unwrap());
885 }
886 Err(err) => {
887 match err {
888 OperationError::Operation(operation_error) => {
889 return Err(OperationError::Operation(
890 operation_error
891 .0
892 .downcast_ref::<D::Failure>()
893 .unwrap()
894 .clone(),
895 ));
896 }
897 OperationError::Internal(internal) => {
898 // This DOES NOT result in an early return
899 warn!("An internal error occurred during a failable handler operation. {:?}", internal);
900 }
901 OperationError::Unhandled => {
902 // This DOES NOT result in an early return
903 }
904 }
905 }
906 }
907 }
908
909 if let Some(handler) = self.value_getters.get(&ObjectValuePair {
910 object_kind: O::object_name(),
911 value_kind: "any",
912 }) {
913 match handler
914 .handle(
915 (object.clone(), get_value.value_name.clone()),
916 operation_state.clone(),
917 )
918 .await
919 {
920 Ok(success) => {
921 self.value_update(in_object, success.clone(), operation_state)
922 .await;
923
924 return Ok(*(Box::new((value_meta.serialize)(success).unwrap())
925 as Box<dyn Any>)
926 .downcast()
927 .unwrap());
928 }
929 Err(err) => {
930 match err {
931 OperationError::Operation(operation_error) => {
932 return Err(OperationError::Operation(
933 operation_error
934 .0
935 .downcast_ref::<D::Failure>()
936 .unwrap()
937 .clone(),
938 ));
939 }
940 OperationError::Internal(internal) => {
941 // This DOES NOT result in an early return
942 warn!("An internal error occurred during a failable handler operation. {:?}", internal);
943 }
944 OperationError::Unhandled => {
945 // This DOES NOT result in an early return
946 }
947 }
948 }
949 }
950 }
951
952 if let Some(handler) = self.value_getters.get(&ObjectValuePair {
953 object_kind: "any",
954 value_kind: "any",
955 }) {
956 match handler
957 .handle(
958 (object.clone(), get_value.value_name.clone()),
959 operation_state.clone(),
960 )
961 .await
962 {
963 Ok(success) => {
964 self.value_update(in_object, success.clone(), operation_state)
965 .await;
966
967 return Ok(*(Box::new((value_meta.serialize)(success).unwrap())
968 as Box<dyn Any>)
969 .downcast()
970 .unwrap());
971 }
972 Err(err) => {
973 match err {
974 OperationError::Operation(operation_error) => {
975 return Err(OperationError::Operation(
976 operation_error
977 .0
978 .downcast_ref::<D::Failure>()
979 .unwrap()
980 .clone(),
981 ));
982 }
983 OperationError::Internal(internal) => {
984 // This DOES NOT result in an early return
985 warn!("An internal error occurred during a failable handler operation. {:?}", internal);
986 }
987 OperationError::Unhandled => {
988 // This DOES NOT result in an early return
989 }
990 }
991 }
992 }
993 }
994
995 if let Some(handler) = self.value_getters.get(&ObjectValuePair {
996 object_kind: O::object_name(),
997 value_kind: &get_value.value_name,
998 }) {
999 match handler
1000 .handle(
1001 (object.clone(), get_value.value_name.clone()),
1002 operation_state.clone(),
1003 )
1004 .await
1005 {
1006 Ok(success) => {
1007 self.value_update(in_object, success.clone(), operation_state)
1008 .await;
1009
1010 return Ok(*(Box::new((value_meta.serialize)(success).unwrap())
1011 as Box<dyn Any>)
1012 .downcast()
1013 .unwrap());
1014 }
1015 Err(err) => {
1016 match err {
1017 OperationError::Operation(operation_error) => {
1018 return Err(OperationError::Operation(
1019 operation_error
1020 .0
1021 .downcast_ref::<D::Failure>()
1022 .unwrap()
1023 .clone(),
1024 ));
1025 }
1026 OperationError::Internal(internal) => {
1027 // This DOES NOT result in an early return
1028 warn!("An internal error occurred during a failable handler operation. {:?}", internal);
1029 }
1030 OperationError::Unhandled => {
1031 // This DOES NOT result in an early return
1032 }
1033 }
1034 }
1035 }
1036 }
1037 } else if operation.is::<GetSetting>() {
1038 let get_setting: &GetSetting = operation.downcast_ref().unwrap();
1039 let setting_name = get_setting.setting_name.clone();
1040
1041 let raw_result = self
1042 .get_setting(
1043 object,
1044 O::object_name().to_string(),
1045 get_setting.clone(),
1046 operation_state,
1047 )
1048 .await;
1049
1050 return match raw_result {
1051 Ok(success) => {
1052 // Success is the setting type, serialize it
1053 // let serialized = (setting_meta.serialize)(success).unwrap();
1054
1055 // Ok(serde_json::to_vec(&serialized).unwrap())
1056 Ok(success.downcast_ref::<D::Success>().unwrap().clone())
1057 }
1058 Err(err) => Err(match err {
1059 OperationError::Operation(failure) => {
1060 // We know this is the right type
1061 OperationError::Operation(*failure.downcast().unwrap())
1062 }
1063 OperationError::Internal(internal) => {
1064 OperationError::Internal(internal.context(format!(
1065 "{}::get_setting::<{}> handler outcome",
1066 O::object_name(),
1067 setting_name
1068 )))
1069 }
1070 OperationError::Unhandled => OperationError::Unhandled,
1071 }),
1072 };
1073 } else if operation.is::<SetSetting>() {
1074 todo!()
1075 } else if operation.is::<ObjectRequest>() {
1076 todo!()
1077 }
1078
1079 // Resolve the operation from the known operations table.
1080 let operation_type = {
1081 let mut operation_type = None;
1082
1083 for (target, operation_meta) in self.metadata.operations.iter() {
1084 // Skip elements that we know will not match
1085 if target.object_name != O::object_name() {
1086 continue;
1087 }
1088
1089 if target.operation_name != operation_name {
1090 continue;
1091 }
1092
1093 if (operation_meta.any_is_same)(&operation) {
1094 operation_type = Some(target.clone());
1095 break;
1096 }
1097 }
1098
1099 operation_type
1100 }
1101 .ok_or_else(|| OperationError::Unhandled)?;
1102
1103 // Resolve the handler from our handler tree
1104 let handler_tree = self
1105 .operation_handlers
1106 .get(&operation_type)
1107 .ok_or_else(|| OperationError::Unhandled)?;
1108
1109 let raw_result = handler_tree
1110 .handle((object, operation), operation_state.clone())
1111 .await;
1112
1113 // Convert the dynamic result back into its concrete type
1114 match raw_result {
1115 Ok(result) => Ok(result.0.downcast_ref::<D::Success>().unwrap().clone()),
1116 Err(err) => Err(match err {
1117 OperationError::Internal(internal) => {
1118 OperationError::Internal(internal.context(format!(
1119 "operation {}::{} handler outcome",
1120 operation_type.object_name, operation_type.operation_name
1121 )))
1122 }
1123 OperationError::Operation(boxed_error) => OperationError::Operation(
1124 boxed_error.0.downcast_ref::<D::Failure>().unwrap().clone(),
1125 ),
1126 OperationError::Unhandled => OperationError::Unhandled,
1127 }),
1128 }
1129 }
1130
1131 async fn get_object<O>(
1132 &self,
1133 object_str: &str,
1134 _operation_state: &StackOperationState,
1135 ) -> Result<Object<StackOperationState, O, Self>, OperationError<ObjectRequestError>>
1136 where
1137 O: GiteratedObject + Debug + 'static,
1138 {
1139 // TODO: Authorization?
1140 for (_object_name, object_meta) in self.metadata.objects.iter() {
1141 if let Ok(object) = (object_meta.from_str)(object_str) {
1142 return Ok(unsafe {
1143 Object::new_unchecked(object.downcast_ref::<O>().unwrap().clone(), self.clone())
1144 });
1145 }
1146 }
1147
1148 Err(OperationError::Unhandled)
1149 }
1150 }
1151
1152 // Placeholder
1153 impl GiteratedStack {
1154 pub async fn new_operation_func(
1155 &self,
1156 _object: AnyObject,
1157 _operation: AnyOperation,
1158 _operation_state: StackOperationState,
1159 ) -> Result<AnySuccess, OperationError<AnyFailure>> {
1160 todo!()
1161 }
1162 }
1163
1164 /// Defines a type that is a valid Giterated runtime state.
1165 ///
1166 /// This allows for extraction of state in handlers, based on a
1167 /// [`FromOperationState<S>`] impl on (what is in this case) [`Self`].
1168 pub trait GiteratedStackState: Send + Sync + Clone {}
1169
1170 impl<T: Send + Sync + Clone> GiteratedStackState for T {}
1171
1172 #[async_trait::async_trait(?Send)]
1173 impl<R, S, T> HandlerResolvable<R, S> for Option<T>
1174 where
1175 T: HandlerResolvable<R, S>,
1176 {
1177 type Error = MissingValue;
1178
1179 async fn from_handler_state(
1180 required_parameters: &R,
1181 operation_state: &S,
1182 ) -> Result<Option<T>, MissingValue> {
1183 Ok(T::from_handler_state(required_parameters, operation_state)
1184 .await
1185 .ok())
1186 }
1187 }
1188