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

ambee/giterated

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

The long awaited, exhalted huge networking stack change.

Amber - ⁨2⁩ years ago

parent: tbd commit: ⁨21b6a72

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