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

ambee/giterated

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

Fix settings

Amber - ⁨2⁩ years ago

parent: tbd commit: ⁨c518454

⁨giterated-stack/src/handler.rs⁩ - ⁨44673⁩ bytes
Raw
1 use std::{any::Any, collections::HashMap, sync::Arc};
2
3 use futures_util::FutureExt;
4 use giterated_models::{
5 authenticated::AuthenticatedPayload,
6 error::{GetValueError, IntoInternalError, OperationError},
7 instance::Instance,
8 message::GiteratedMessage,
9 object::{
10 AnyObject, GiteratedObject, Object, ObjectRequest, ObjectRequestError, ObjectResponse,
11 },
12 object_backend::ObjectBackend,
13 operation::{AnyOperation, GiteratedOperation},
14 settings::{GetSetting, GetSettingError, SetSetting, Setting},
15 value::{AnyValue, GetValue, GetValueTyped, GiteratedObjectValue},
16 };
17
18 use serde::{Deserialize, Serialize};
19 use tracing::trace;
20
21 use crate::{
22 provider::MetadataProvider, GiteratedOperationHandler, MissingValue, ObjectMeta,
23 ObjectOperationPair, ObjectSettingPair, ObjectValuePair, OperationMeta, OperationWrapper,
24 SettingMeta, SettingUpdate, StackOperationState, ValueMeta,
25 };
26
27 /// Temporary name for the next generation of Giterated stack
28 #[derive(Default)]
29 pub struct GiteratedStack {
30 operation_handlers: HashMap<ObjectOperationPair, HandlerTree>,
31 value_getters: HashMap<ObjectValuePair, OperationWrapper>,
32 setting_getters: HashMap<String, OperationWrapper>,
33 value_change: HashMap<ObjectValuePair, OperationWrapper>,
34 setting_change: HashMap<ObjectSettingPair, OperationWrapper>,
35 metadata_providers: Vec<Box<dyn MetadataProvider>>,
36 metadata: RuntimeMetadata,
37 }
38
39 impl Debug for GiteratedStack {
40 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41 f.debug_struct("GiteratedStack").finish()
42 }
43 }
44
45 #[derive(Clone)]
46 pub struct ValueChangeEvent(Arc<dyn Any + Send + Sync>);
47
48 impl GiteratedStack {
49 pub fn merge_builder<S: GiteratedStackState>(
50 &mut self,
51 mut builder: SubstackBuilder<S>,
52 ) -> &mut Self {
53 for (target, handler) in builder.operation_handlers {
54 let tree = self.get_or_create_tree(&target);
55
56 tree.push(handler);
57 }
58
59 for (target, handler) in builder.value_getters {
60 assert!(self.value_getters.insert(target, handler).is_none());
61 }
62
63 for (target, handler) in builder.setting_getters {
64 assert!(self.setting_getters.insert(target, handler).is_none());
65 }
66
67 for (target, handler) in builder.value_change {
68 self.value_change.insert(target, handler);
69 }
70
71 for (target, handler) in builder.setting_change {
72 self.setting_change.insert(target, handler);
73 }
74
75 self.metadata_providers
76 .append(&mut builder.metadata_providers);
77
78 self.metadata.append(builder.metadata);
79
80 self
81 }
82
83 pub async fn value_update<O, V>(
84 &self,
85 object: O,
86 new_value: V,
87 operation_state: &StackOperationState,
88 ) where
89 O: GiteratedObject + 'static,
90 V: GiteratedObjectValue<Object = O> + 'static,
91 {
92 trace!("value updated {}::{}", O::object_name(), V::value_name());
93 let target = ObjectValuePair::from_types::<O, V>();
94
95 if let Some(handler) = self.value_change.get(&target) {
96 // TODO
97 let _ = handler
98 .handle(
99 &(Box::new(object) as _),
100 &(Box::new(ValueChangedShim { new_value }) as _),
101 operation_state,
102 )
103 .await;
104 }
105 }
106
107 pub async fn setting_update<O, S>(
108 &self,
109 object: O,
110 new_setting: S,
111 operation_state: &StackOperationState,
112 ) where
113 O: GiteratedObject + 'static,
114 S: Setting + 'static,
115 {
116 trace!("setting updated {}::{}", O::object_name(), S::name());
117 let target = ObjectSettingPair::from_types::<O, S>();
118
119 if let Some(handler) = self.setting_change.get(&target) {
120 let _ = handler
121 .handle(
122 &(Box::new(object) as _),
123 &(Box::new(SettingUpdate(new_setting)) as _),
124 operation_state,
125 )
126 .await;
127 }
128 }
129
130 pub async fn new_object<O>(&self, _new_object: &O, _operation_state: &StackOperationState)
131 where
132 O: GiteratedObject,
133 {
134 // TODO
135 }
136
137 /// Writes a setting for the specified object.
138 pub async fn write_setting<O, S>(
139 &self,
140 object: &O,
141 setting: S,
142 ) -> Result<(), OperationError<()>>
143 where
144 O: GiteratedObject + 'static,
145 S: Setting + 'static + Clone,
146 {
147 for provider in self.metadata_providers.iter() {
148 if provider.provides_for(object as &dyn Any) {
149 let setting_meta = self
150 .metadata
151 .settings
152 .get(&ObjectSettingPair {
153 object_kind: O::object_name().to_string(),
154 setting_name: S::name().to_string(),
155 })
156 .ok_or_else(|| OperationError::Unhandled)?;
157
158 let object_meta = self
159 .metadata
160 .objects
161 .get(O::object_name())
162 .ok_or_else(|| OperationError::Unhandled)?;
163
164 let result = provider
165 .write(object, object_meta, &setting, setting_meta)
166 .await
167 .as_internal_error_with_context(format!("writing setting {}", S::name()));
168
169 return result;
170 }
171 }
172
173 Err(OperationError::Unhandled)
174 }
175
176 /// Gets a setting for the specified object.
177 pub async fn new_get_setting<O, S>(&self, object: &O) -> Result<S, OperationError<MissingValue>>
178 where
179 O: GiteratedObject + 'static,
180 S: Setting + 'static,
181 {
182 for provider in self.metadata_providers.iter() {
183 if provider.provides_for(object as &dyn Any) {
184 trace!(
185 "Resolving setting {} for object {} from provider.",
186 S::name(),
187 O::object_name()
188 );
189
190 let setting_meta = self
191 .metadata
192 .settings
193 .get(&ObjectSettingPair {
194 object_kind: O::object_name().to_string(),
195 setting_name: S::name().to_string(),
196 })
197 .ok_or_else(|| OperationError::Unhandled)?;
198
199 let object_meta = self
200 .metadata
201 .objects
202 .get(O::object_name())
203 .ok_or_else(|| OperationError::Unhandled)?;
204
205 let value = provider
206 .read(object, object_meta, setting_meta)
207 .await
208 .as_internal_error_with_context(format!("getting setting {}", S::name()))?;
209
210 return serde_json::from_value(value)
211 .as_internal_error_with_context("deserializing setting");
212 }
213 }
214 trace!(
215 "No provider registered for setting {} and object {}",
216 S::name(),
217 O::object_name()
218 );
219
220 Err(OperationError::Unhandled)
221 }
222
223 fn get_or_create_tree(&mut self, target: &ObjectOperationPair) -> &mut HandlerTree {
224 if self.operation_handlers.contains_key(target) {
225 self.operation_handlers.get_mut(target).unwrap()
226 } else {
227 self.operation_handlers
228 .insert(target.clone(), HandlerTree::default());
229
230 self.operation_handlers.get_mut(target).unwrap()
231 }
232 }
233 }
234
235 #[derive(Default)]
236 pub struct HandlerTree {
237 elements: Vec<OperationWrapper>,
238 }
239
240 impl HandlerTree {
241 pub fn push(&mut self, handler: OperationWrapper) {
242 self.elements.push(handler);
243 }
244
245 pub async fn handle(
246 &self,
247 object: &Box<dyn Any + Send + Sync>,
248 operation: &Box<dyn Any + Send + Sync>,
249 operation_state: &StackOperationState,
250 ) -> Result<Box<dyn Any + 'static>, OperationError<Box<dyn Any + 'static>>> {
251 for handler in self.elements.iter() {
252 match handler.handle(object, operation, operation_state).await {
253 Ok(success) => return Ok(success),
254 Err(err) => match err {
255 OperationError::Operation(failure) => {
256 return Err(OperationError::Operation(failure))
257 }
258 OperationError::Internal(e) => return Err(OperationError::Internal(e)),
259 _ => {
260 continue;
261 }
262 },
263 }
264 }
265
266 Err(OperationError::Unhandled)
267 }
268 }
269
270 /// Stores runtime metadata for all in-use Giterated protocol types.
271 #[derive(Default)]
272 struct RuntimeMetadata {
273 objects: HashMap<String, ObjectMeta>,
274 operations: HashMap<ObjectOperationPair, OperationMeta>,
275 values: HashMap<ObjectValuePair, ValueMeta>,
276 settings: HashMap<ObjectSettingPair, SettingMeta>,
277 }
278
279 /// Defines a type that is a valid Giterated runtime state.
280 ///
281 /// This allows for extraction of state in handlers, based on a
282 /// [`FromOperationState<S>`] impl on (what is in this case) [`Self`].
283 pub trait GiteratedStackState: Send + Sync + Clone {}
284
285 impl<T: Send + Sync + Clone> GiteratedStackState for T {}
286
287 pub struct SubstackBuilder<S: GiteratedStackState> {
288 operation_handlers: HashMap<ObjectOperationPair, OperationWrapper>,
289 value_getters: HashMap<ObjectValuePair, OperationWrapper>,
290 setting_getters: HashMap<String, OperationWrapper>,
291 metadata: RuntimeMetadata,
292 value_change: HashMap<ObjectValuePair, OperationWrapper>,
293 metadata_providers: Vec<Box<dyn MetadataProvider>>,
294 setting_change: HashMap<ObjectSettingPair, OperationWrapper>,
295
296 state: S,
297 }
298
299 impl<S: GiteratedStackState + 'static> SubstackBuilder<S> {
300 pub fn new(state: S) -> Self {
301 Self {
302 operation_handlers: Default::default(),
303 value_getters: Default::default(),
304 setting_getters: Default::default(),
305 metadata: Default::default(),
306 value_change: Default::default(),
307 metadata_providers: Default::default(),
308 setting_change: Default::default(),
309 state,
310 }
311 }
312 }
313
314 impl<S: GiteratedStackState + 'static> SubstackBuilder<S> {
315 /// Insert an operation handler into the runtime builder.
316 ///
317 /// # Type Registration
318 /// Inserting the handler will automatically, if required, register the operation type of the
319 /// handler. It will **not** register the object type automatically.
320 pub fn operation<A, O, D, H>(&mut self, handler: H) -> &mut Self
321 where
322 O: GiteratedObject + 'static,
323 D: GiteratedOperation<O> + 'static + Clone,
324 H: GiteratedOperationHandler<A, O, D, S> + 'static + Clone + Send + Sync,
325 D::Failure: Send + Sync,
326 D::Success: Send + Sync,
327 {
328 let object_name = handler.object_name().to_string();
329 let operation_name = handler.operation_name().to_string();
330
331 let wrapped = OperationWrapper::new(handler, self.state.clone());
332
333 let pair = ObjectOperationPair {
334 object_name,
335 operation_name,
336 };
337
338 self.operation_handlers.insert(pair, wrapped);
339
340 self.metadata.register_operation::<O, D>();
341
342 self
343 }
344
345 /// Register a [`GiteratedObject`] type with the runtime.
346 ///
347 /// # Type Registration
348 /// This will register the provided object type.
349 pub fn object<O: GiteratedObject + 'static>(&mut self) -> &mut Self {
350 self.metadata.register_object::<O>();
351
352 // Insert handler so ObjectRequest is handled properly
353 let handler = move |_object: &Instance,
354 operation: ObjectRequest,
355 _state: S,
356 _operation_state: StackOperationState,
357 stack: Arc<GiteratedStack>| {
358 async move {
359 for (_object_name, object_meta) in stack.metadata.objects.iter() {
360 if (object_meta.from_str)(&operation.0).is_ok() {
361 return Ok(ObjectResponse(operation.0));
362 }
363 }
364
365 Err(OperationError::Unhandled)
366 }
367 .boxed_local()
368 };
369
370 self.operation(handler);
371
372 self
373 }
374
375 /// Register a [`Setting`] type with the runtime.
376 ///
377 /// # Type Registration
378 /// This will register the provided setting type.
379 pub fn setting<O: GiteratedObject + 'static, T: Setting + 'static>(&mut self) -> &mut Self {
380 self.metadata.register_setting::<O, T>();
381
382 self
383 }
384
385 /// Register a [`GiteratedObjectValue`] that is also a [`Setting`], which
386 /// allows for automatic value updates.
387 pub fn value_setting<
388 O: GiteratedObject + 'static + Clone,
389 T: GiteratedObjectValue<Object = O> + Setting + 'static + Clone,
390 >(
391 &mut self,
392 ) -> &mut Self {
393 self.metadata.register_setting::<O, T>();
394 self.metadata.register_value::<O, T>();
395
396 self.setting_change.insert(
397 ObjectSettingPair {
398 object_kind: O::object_name().to_string(),
399 setting_name: T::name().to_string(),
400 },
401 OperationWrapper::new(
402 move |object: &O,
403 setting: SettingUpdate<T>,
404 _state: (),
405 operation_state: StackOperationState,
406 stack: Arc<GiteratedStack>| {
407 trace!(
408 "value setting updated {}::{}",
409 O::object_name(),
410 T::value_name()
411 );
412 let object = object.clone();
413 async move {
414 stack
415 .value_update(object, setting.0, &operation_state)
416 .await;
417 Ok(())
418 }
419 .boxed_local()
420 },
421 (),
422 ),
423 );
424
425 let wrapped = OperationWrapper::new(
426 |object: &O,
427 operation: GetValueTyped<T>,
428 state: _,
429 operation_state: StackOperationState,
430 stack: Arc<GiteratedStack>| {
431 let object = object.clone();
432 async move {
433 match stack
434 .get_setting(
435 Box::new(object.clone()) as _,
436 O::object_name().to_string(),
437 GetSetting {
438 setting_name: T::name().to_string(),
439 },
440 &operation_state,
441 )
442 .await
443 {
444 Ok(setting) => Ok(*setting.downcast::<T>().unwrap()),
445 Err(err) => {
446 panic!("Error: {:?}", err);
447 }
448 }
449 }
450 .boxed_local()
451 },
452 self.state.clone(),
453 );
454
455 self.value_getters.insert(
456 ObjectValuePair {
457 object_kind: O::object_name().to_string(),
458 value_kind: T::value_name().to_string(),
459 },
460 wrapped,
461 );
462
463 self
464 }
465
466 /// Register a [`GiteratedObjectValue<O>`] type with the runtime, providing
467 /// its associated handler for [`GetValue`].
468 ///
469 /// # Type Registration
470 /// This will register the provided [`GiteratedObjectValue`] type for its matching / specified
471 /// object type. It will **not** register the object type automatically.
472 pub fn value<O, V, A, F>(&mut self, handler: F) -> &mut Self
473 where
474 O: GiteratedObject + 'static,
475 V: GiteratedObjectValue<Object = O> + 'static + Clone,
476 F: GiteratedOperationHandler<A, O, GetValueTyped<V>, S> + Clone + 'static + Send + Sync,
477 {
478 let object_name = handler.object_name().to_string();
479 let value_name = V::value_name().to_string();
480
481 let wrapped = OperationWrapper::new(handler, self.state.clone());
482
483 let handler_object_name = object_name.clone();
484 let handler_value_name = value_name.clone();
485
486 // Insert handler so GetValue is handled properly
487 let _handler = move |object: &O,
488 operation: GetValueTyped<AnyValue<O>>,
489 _state: S,
490 operation_state: StackOperationState,
491 stack: Arc<GiteratedStack>| {
492 let stack = stack;
493 let object_name = handler_object_name;
494 let value_name = handler_value_name;
495 let object = object.clone();
496 async move {
497 for (target, getter) in stack.value_getters.iter() {
498 if target.object_kind != object_name {
499 continue;
500 }
501
502 if target.value_kind != value_name {
503 continue;
504 }
505
506 return match getter
507 .handle(
508 &(Box::new(object.clone()) as Box<dyn Any + Send + Sync>),
509 &(Box::new(GetValueTyped::<V> {
510 value_name: operation.value_name,
511 ty: Default::default(),
512 }) as Box<dyn Any + Send + Sync>),
513 &operation_state,
514 )
515 .await {
516 Ok(success) => Ok(*success.downcast::<<GetValueTyped<V> as GiteratedOperation<O>>::Success>().unwrap()),
517 Err(err) => Err(match err {
518 OperationError::Operation(failure) => OperationError::Operation(*failure.downcast::<<GetValueTyped<V> as GiteratedOperation<O>>::Failure>().unwrap()),
519 OperationError::Internal(internal) => OperationError::Internal(internal),
520 OperationError::Unhandled => OperationError::Unhandled,
521 }),
522 }
523 }
524
525 Err(OperationError::Unhandled)
526 }
527 .boxed_local()
528 };
529
530 assert!(self
531 .value_getters
532 .insert(
533 ObjectValuePair {
534 object_kind: object_name,
535 value_kind: value_name
536 },
537 wrapped
538 )
539 .is_none());
540
541 self.metadata.register_value::<O, V>();
542
543 self
544 }
545
546 /// Register a handler for [`GetSetting`] for it's associated object type.
547 pub fn object_settings<O, A, F>(&mut self, handler: F) -> &mut Self
548 where
549 O: GiteratedObject + 'static,
550 F: GiteratedOperationHandler<A, O, GetSetting, S> + Clone + 'static + Send + Sync,
551 {
552 let object_name = handler.object_name().to_string();
553
554 let wrapped = OperationWrapper::new(handler, self.state.clone());
555
556 assert!(self.setting_getters.insert(object_name, wrapped).is_none());
557
558 self
559 }
560
561 pub fn value_change<O, A, F, V>(&mut self, handler: F) -> &mut Self
562 where
563 O: GiteratedObject + 'static,
564 F: GiteratedOperationHandler<A, O, ValueChangedShim<V>, S> + Clone + 'static + Send + Sync,
565 V: GiteratedObjectValue<Object = O> + Clone + 'static,
566 {
567 let object_name = handler.object_name().to_string();
568
569 let wrapped = OperationWrapper::new(handler, self.state.clone());
570
571 assert!(self.setting_getters.insert(object_name, wrapped).is_none());
572
573 self
574 }
575
576 pub fn object_metadata_provider(&mut self, provider: Box<dyn MetadataProvider>) -> &mut Self {
577 self.metadata_providers.push(provider);
578
579 self
580 }
581 }
582
583 #[derive(Serialize, Deserialize, Clone)]
584 pub struct ValueChangedShim<V> {
585 new_value: V,
586 }
587
588 impl<O, V> GiteratedOperation<O> for ValueChangedShim<V>
589 where
590 O: GiteratedObject,
591 V: GiteratedObjectValue<Object = O>,
592 {
593 type Success = V;
594
595 type Failure = MissingValue;
596 }
597
598 impl RuntimeMetadata {
599 fn register_object<O: GiteratedObject + 'static>(&mut self) {
600 let object_name = O::object_name().to_string();
601
602 let object_meta = ObjectMeta::new::<O>();
603
604 if self.objects.insert(object_name, object_meta).is_some() {
605 trace!(
606 "Registration of object {} overwrote previous registration.",
607 O::object_name()
608 );
609 } else {
610 trace!("Registration of object {}.", O::object_name())
611 }
612 }
613
614 fn register_operation<O: GiteratedObject + 'static, D: GiteratedOperation<O> + 'static>(
615 &mut self,
616 ) {
617 let object_name = O::object_name().to_string();
618 let operation_name = D::operation_name().to_string();
619
620 if self
621 .operations
622 .insert(
623 ObjectOperationPair {
624 object_name: object_name,
625 operation_name: operation_name,
626 },
627 OperationMeta::new::<O, D>(),
628 )
629 .is_some()
630 {
631 trace!(
632 "Registration of object operation {}<{}> overwrote previous registration.",
633 D::operation_name(),
634 O::object_name()
635 );
636 } else {
637 trace!(
638 "Registration of object operation {}<{}>.",
639 D::operation_name(),
640 O::object_name()
641 )
642 }
643 }
644
645 fn register_value<
646 O: GiteratedObject + 'static,
647 V: GiteratedObjectValue<Object = O> + 'static,
648 >(
649 &mut self,
650 ) {
651 let object_name = O::object_name().to_string();
652 let value_name = V::value_name().to_string();
653
654 if self
655 .values
656 .insert(
657 ObjectValuePair {
658 object_kind: object_name,
659 value_kind: value_name,
660 },
661 ValueMeta::new::<V>(),
662 )
663 .is_some()
664 {
665 trace!(
666 "Registration of value <{}>::{} overwrote previous registration.",
667 O::object_name(),
668 V::value_name()
669 );
670 } else {
671 trace!(
672 "Registration of value <{}>::{}.",
673 O::object_name(),
674 V::value_name()
675 );
676 }
677 }
678
679 fn register_setting<O: GiteratedObject + 'static, S: Setting + 'static>(&mut self) {
680 if self
681 .settings
682 .insert(
683 ObjectSettingPair {
684 object_kind: O::object_name().to_string(),
685 setting_name: S::name().to_string(),
686 },
687 SettingMeta::new::<O, S>(),
688 )
689 .is_some()
690 {
691 trace!(
692 "Registration of setting {} overwrote previous registration.",
693 S::name()
694 );
695 } else {
696 trace!("Registration of setting {}.", S::name());
697 }
698 }
699
700 fn append(&mut self, other: Self) {
701 self.objects.extend(other.objects);
702 self.operations.extend(other.operations);
703 self.values.extend(other.values);
704 self.settings.extend(other.settings);
705 }
706 }
707 impl GiteratedStack {
708 /// Handles a giterated network message, returning either a raw success
709 /// payload or a serialized error payload.
710 pub async fn handle_network_message(
711 &self,
712 message: AuthenticatedPayload,
713 operation_state: &StackOperationState,
714 ) -> Result<Vec<u8>, OperationError<Vec<u8>>> {
715 let message: GiteratedMessage<AnyObject, AnyOperation> = message.into_message();
716
717 // Deserialize the object, also getting the object type's name
718 let (object_type, object) = {
719 let mut result = None;
720
721 for (object_type, object_meta) in self.metadata.objects.iter() {
722 if let Ok(object) = (object_meta.from_str)(&message.object.0) {
723 result = Some((object_type.clone(), object));
724 break;
725 }
726 }
727
728 result
729 }
730 .ok_or_else(|| OperationError::Unhandled)?;
731
732 trace!(
733 "Handling network message {}::<{}>",
734 message.operation,
735 object_type
736 );
737
738 if message.operation == "get_value" {
739 // Special case
740 let operation: GetValue = serde_json::from_slice(&message.payload.0).unwrap();
741
742 let result = self
743 .network_get_value(
744 object,
745 object_type.clone(),
746 operation.clone(),
747 operation_state,
748 )
749 .await;
750
751 // In the case of internal errors, attach context
752 let result = result.map_err(|err| match err {
753 OperationError::Operation(operation) => OperationError::Operation(operation),
754 OperationError::Internal(internal) => {
755 OperationError::Internal(internal.context(format!(
756 "{}::get_value::<{}> outcome",
757 object_type, operation.value_name
758 )))
759 }
760 OperationError::Unhandled => OperationError::Unhandled,
761 });
762
763 return result;
764 } else if message.operation == "get_setting" {
765 let operation: GetSetting = serde_json::from_slice(&message.payload.0).unwrap();
766 let setting_meta = self
767 .metadata
768 .settings
769 .get(&ObjectSettingPair {
770 object_kind: object_type.clone(),
771 setting_name: operation.setting_name.clone(),
772 })
773 .ok_or_else(|| OperationError::Unhandled)?;
774 let raw_result = self
775 .get_setting(object, object_type.clone(), operation, operation_state)
776 .await;
777 return match raw_result {
778 Ok(success) => {
779 // Success is the setting type, serialize it
780 let serialized = (setting_meta.serialize)(&(*success)).unwrap();
781
782 Ok(serde_json::to_vec(&serialized).unwrap())
783 }
784 Err(err) => Err(match err {
785 OperationError::Operation(failure) => {
786 // We know how to resolve this type
787 let failure: GetSettingError = *failure.downcast().unwrap();
788
789 OperationError::Operation(serde_json::to_vec(&failure).unwrap())
790 }
791 OperationError::Internal(internal) => {
792 OperationError::Internal(internal.context(format!(
793 "{}::get_setting::<{}> handler outcome",
794 object_type, setting_meta.name
795 )))
796 }
797 OperationError::Unhandled => OperationError::Unhandled,
798 }),
799 };
800 } else if message.operation == "set_setting" {
801 let operation: SetSetting = serde_json::from_slice(&message.payload.0).unwrap();
802
803 trace!(
804 "Handling network {}::set_setting for {}",
805 object_type,
806 operation.setting_name
807 );
808
809 let setting_meta = self
810 .metadata
811 .settings
812 .get(&ObjectSettingPair {
813 object_kind: object_type.clone(),
814 setting_name: operation.setting_name.clone(),
815 })
816 .unwrap();
817
818 let setting = (setting_meta.deserialize)(operation.value.0)
819 .as_internal_error_with_context(format!(
820 "deserializing setting {} for object {}",
821 operation.setting_name, object_type
822 ))?;
823
824 trace!(
825 "Deserialized setting {} for object {}",
826 operation.setting_name,
827 object_type,
828 );
829
830 for provider in self.metadata_providers.iter() {
831 if provider.provides_for(object.as_ref()) {
832 trace!(
833 "Resolved setting provider for setting {} for object {}",
834 operation.setting_name,
835 object_type,
836 );
837
838 let object_meta = self
839 .metadata
840 .objects
841 .get(&object_type)
842 .ok_or_else(|| OperationError::Unhandled)?;
843
844 let raw_result = provider
845 .write(&(*object), object_meta, &(*setting), setting_meta)
846 .await;
847
848 return match raw_result {
849 Ok(_) => {
850 (setting_meta.setting_updated)(
851 object,
852 setting,
853 operation_state.runtime.clone(),
854 operation_state,
855 )
856 .await;
857
858 Ok(serde_json::to_vec(&()).unwrap())
859 }
860 Err(e) => Err(OperationError::Internal(e.context(format!(
861 "writing object {} setting {}",
862 object_type, operation.setting_name
863 )))),
864 };
865 }
866
867 trace!(
868 "Failed to resolve setting provider for setting {} for object {}",
869 operation.setting_name,
870 object_type,
871 );
872 }
873 }
874
875 let target = ObjectOperationPair {
876 object_name: object_type.clone(),
877 operation_name: message.operation.clone(),
878 };
879
880 // Resolve the target operations from the handlers table
881 let handler = self
882 .operation_handlers
883 .get(&target)
884 .ok_or_else(|| OperationError::Unhandled)?;
885
886 trace!(
887 "Resolved operation handler for network message {}::<{}>",
888 message.operation,
889 object_type
890 );
891
892 // Deserialize the operation
893 let meta = self
894 .metadata
895 .operations
896 .get(&target)
897 .ok_or_else(|| OperationError::Unhandled)?;
898
899 let operation =
900 (meta.deserialize)(&message.payload.0).as_internal_error_with_context(format!(
901 "deserializing operation {}::{}",
902 target.object_name, target.operation_name
903 ))?;
904
905 trace!(
906 "Deserialized operation for network message {}::<{}>",
907 message.operation,
908 object_type
909 );
910
911 trace!(
912 "Calling handler for network message {}::<{}>",
913 message.operation,
914 object_type
915 );
916
917 // Get the raw result of the operation, where the return values are boxed.
918 let raw_result = handler.handle(&object, &operation, operation_state).await;
919
920 trace!(
921 "Finished handling network message {}::<{}>",
922 message.operation,
923 object_type
924 );
925
926 // Deserialize the raw result for the network
927 match raw_result {
928 Ok(success) => Ok((meta.serialize_success)(success).as_internal_error()?),
929 Err(err) => Err(match err {
930 OperationError::Operation(failure) => {
931 OperationError::Operation((meta.serialize_error)(failure).as_internal_error()?)
932 }
933 OperationError::Internal(internal) => {
934 OperationError::Internal(internal.context(format!(
935 "operation {}::{} handler outcome",
936 target.object_name, target.operation_name
937 )))
938 }
939 OperationError::Unhandled => OperationError::Unhandled,
940 }),
941 }
942 }
943
944 pub async fn network_get_value(
945 &self,
946 object: Box<dyn Any + Send + Sync>,
947 object_kind: String,
948 operation: GetValue,
949 operation_state: &StackOperationState,
950 ) -> Result<Vec<u8>, OperationError<Vec<u8>>> {
951 trace!("Handling network get_value for {}", operation.value_name);
952
953 let value_meta = self
954 .metadata
955 .values
956 .get(&ObjectValuePair {
957 object_kind: object_kind.clone(),
958 value_kind: operation.value_name.clone(),
959 })
960 .ok_or_else(|| OperationError::Unhandled)?;
961
962 for (target, getter) in self.value_getters.iter() {
963 if target.object_kind != object_kind {
964 continue;
965 }
966
967 if target.value_kind != operation.value_name {
968 continue;
969 }
970
971 return match getter
972 .handle(&(object), &((value_meta.typed_get)()), operation_state)
973 .await
974 {
975 Ok(success) => {
976 // Serialize success, which is the value type itself
977 let serialized = (value_meta.serialize)(success).as_internal_error()?;
978
979 Ok(serialized)
980 }
981 Err(err) => Err(match err {
982 OperationError::Operation(failure) => {
983 // Failure is sourced from GetValue operation, but this is hardcoded for now
984 let failure: GetValueError = *failure.downcast().unwrap();
985
986 OperationError::Operation(serde_json::to_vec(&failure).as_internal_error()?)
987 }
988 OperationError::Internal(internal) => OperationError::Internal(internal),
989 OperationError::Unhandled => OperationError::Unhandled,
990 }),
991 };
992 }
993
994 Err(OperationError::Unhandled)
995 }
996
997 pub async fn get_setting(
998 &self,
999 object: Box<dyn Any + Send + Sync>,
1000 object_kind: String,
1001 operation: GetSetting,
1002 operation_state: &StackOperationState,
1003 ) -> Result<Box<dyn Any + Send + Sync>, OperationError<Box<dyn Any + Send + Sync>>> {
1004 trace!(
1005 "Handling network {}::get_setting for {}",
1006 object_kind,
1007 operation.setting_name
1008 );
1009
1010 for provider in self.metadata_providers.iter() {
1011 if provider.provides_for(object.as_ref()) {
1012 let setting_meta = self
1013 .metadata
1014 .settings
1015 .get(&ObjectSettingPair {
1016 object_kind: object_kind.clone(),
1017 setting_name: operation.setting_name.clone(),
1018 })
1019 .ok_or_else(|| OperationError::Unhandled)?;
1020
1021 let object_meta = self
1022 .metadata
1023 .objects
1024 .get(&object_kind)
1025 .ok_or_else(|| OperationError::Unhandled)?;
1026
1027 let result = provider
1028 .read(object.as_ref(), object_meta, setting_meta)
1029 .await
1030 .as_internal_error_with_context(format!(
1031 "reading setting {}",
1032 operation.setting_name
1033 ))?;
1034
1035 return Ok(
1036 (setting_meta.deserialize)(result).as_internal_error_with_context(format!(
1037 "deserializing setting {}",
1038 operation.setting_name
1039 ))?,
1040 );
1041 }
1042 }
1043
1044 todo!()
1045 }
1046
1047 pub async fn network_set_setting(
1048 &self,
1049 object: Box<dyn Any + Send + Sync>,
1050 object_kind: String,
1051 operation: SetSetting,
1052 operation_state: &StackOperationState,
1053 ) -> Result<Vec<u8>, OperationError<Vec<u8>>> {
1054 trace!(
1055 "Handling network {}::set_setting for {}",
1056 object_kind,
1057 operation.setting_name
1058 );
1059
1060 let target = ObjectSettingPair {
1061 object_kind: object_kind.clone(),
1062 setting_name: operation.setting_name.clone(),
1063 };
1064
1065 let handler = self.setting_change.get(&target).unwrap();
1066
1067 let raw_result = handler
1068 .handle(&object, &(Box::new(operation) as _), operation_state)
1069 .await;
1070
1071 match raw_result {
1072 Ok(_) => {
1073 // Serialize success, which is the value type itself
1074 let serialized = serde_json::to_vec(&()).as_internal_error()?;
1075
1076 Ok(serialized)
1077 }
1078 Err(err) => Err(match err {
1079 OperationError::Operation(failure) => {
1080 // Failure is sourced from GetValue operation, but this is hardcoded for now
1081 let failure: GetValueError = *failure.downcast().unwrap();
1082
1083 OperationError::Operation(serde_json::to_vec(&failure).as_internal_error()?)
1084 }
1085 OperationError::Internal(internal) => OperationError::Internal(internal),
1086 OperationError::Unhandled => OperationError::Unhandled,
1087 }),
1088 }
1089 }
1090 }
1091
1092 use core::fmt::Debug;
1093
1094 #[async_trait::async_trait(?Send)]
1095 impl ObjectBackend<StackOperationState> for Arc<GiteratedStack> {
1096 async fn object_operation<O, D>(
1097 &self,
1098 in_object: O,
1099 operation_name: &str,
1100 payload: D,
1101 operation_state: &StackOperationState,
1102 ) -> Result<D::Success, OperationError<D::Failure>>
1103 where
1104 O: GiteratedObject + Debug + 'static,
1105 D: GiteratedOperation<O> + Debug + 'static,
1106 {
1107 // Erase object and operation types.
1108 let object = Box::new(in_object.clone()) as Box<dyn Any + Send + Sync>;
1109 let operation = Box::new(payload) as Box<dyn Any + Send + Sync>;
1110
1111 // We need to hijack get_value, set_setting, and get_setting.
1112 if operation_name == "get_value" {
1113 let mut value_meta = None;
1114 for (_, meta) in self.metadata.values.iter() {
1115 if (meta.is_get_value_typed)(&operation) {
1116 value_meta = Some(meta);
1117 break;
1118 }
1119 }
1120
1121 let value_meta = value_meta.ok_or_else(|| OperationError::Unhandled)?;
1122
1123 let value_name = value_meta.name.clone();
1124
1125 trace!(
1126 "Handling get_value for {}::{}",
1127 O::object_name(),
1128 value_name
1129 );
1130
1131 for (target, getter) in self.value_getters.iter() {
1132 if target.object_kind != O::object_name() {
1133 continue;
1134 }
1135
1136 if target.value_kind != value_name {
1137 continue;
1138 }
1139
1140 return match getter
1141 .handle(&(object), &((value_meta.typed_get)()), operation_state)
1142 .await
1143 {
1144 Ok(success) => Ok(*success.downcast().unwrap()),
1145 Err(err) => Err(match err {
1146 OperationError::Operation(failure) => {
1147 OperationError::Operation(*failure.downcast::<D::Failure>().unwrap())
1148 }
1149 OperationError::Internal(internal) => {
1150 OperationError::Internal(internal.context(format!(
1151 "{}::get_value::<{}> handler outcome",
1152 O::object_name(),
1153 value_name
1154 )))
1155 }
1156 OperationError::Unhandled => OperationError::Unhandled,
1157 }),
1158 };
1159 }
1160
1161 return Err(OperationError::Unhandled);
1162 } else if operation.is::<GetSetting>() {
1163 let get_setting: Box<GetSetting> = operation.downcast().unwrap();
1164 let setting_name = get_setting.setting_name.clone();
1165
1166 let raw_result = self
1167 .get_setting(
1168 object,
1169 O::object_name().to_string(),
1170 *get_setting,
1171 operation_state,
1172 )
1173 .await;
1174
1175 return match raw_result {
1176 Ok(success) => {
1177 // Success is the setting type, serialize it
1178 // let serialized = (setting_meta.serialize)(success).unwrap();
1179
1180 // Ok(serde_json::to_vec(&serialized).unwrap())
1181 Ok(*success.downcast().unwrap())
1182 }
1183 Err(err) => Err(match err {
1184 OperationError::Operation(failure) => {
1185 // We know this is the right type
1186 OperationError::Operation(*failure.downcast().unwrap())
1187 }
1188 OperationError::Internal(internal) => {
1189 OperationError::Internal(internal.context(format!(
1190 "{}::get_setting::<{}> handler outcome",
1191 O::object_name(),
1192 setting_name
1193 )))
1194 }
1195 OperationError::Unhandled => OperationError::Unhandled,
1196 }),
1197 };
1198 } else if operation.is::<SetSetting>() {
1199 todo!()
1200 } else if operation.is::<ObjectRequest>() {
1201 todo!()
1202 }
1203
1204 // Resolve the operation from the known operations table.
1205 let operation_type = {
1206 let mut operation_type = None;
1207
1208 for (target, operation_meta) in self.metadata.operations.iter() {
1209 // Skip elements that we know will not match
1210 if target.object_name != O::object_name() {
1211 continue;
1212 }
1213
1214 if target.operation_name != operation_name {
1215 continue;
1216 }
1217
1218 if (operation_meta.any_is_same)(&operation) {
1219 operation_type = Some(target.clone());
1220 break;
1221 }
1222 }
1223
1224 operation_type
1225 }
1226 .ok_or_else(|| OperationError::Unhandled)?;
1227
1228 // Resolve the handler from our handler tree
1229 let handler_tree = self
1230 .operation_handlers
1231 .get(&operation_type)
1232 .ok_or_else(|| OperationError::Unhandled)?;
1233
1234 let raw_result = handler_tree
1235 .handle(&object, &operation, operation_state)
1236 .await;
1237
1238 // Convert the dynamic result back into its concrete type
1239 match raw_result {
1240 Ok(result) => Ok(*result.downcast::<D::Success>().unwrap()),
1241 Err(err) => Err(match err {
1242 OperationError::Internal(internal) => {
1243 OperationError::Internal(internal.context(format!(
1244 "operation {}::{} handler outcome",
1245 operation_type.object_name, operation_type.operation_name
1246 )))
1247 }
1248 OperationError::Operation(boxed_error) => {
1249 OperationError::Operation(*boxed_error.downcast::<D::Failure>().unwrap())
1250 }
1251 OperationError::Unhandled => OperationError::Unhandled,
1252 }),
1253 }
1254 }
1255
1256 async fn get_object<O: GiteratedObject + Debug + 'static>(
1257 &self,
1258 object_str: &str,
1259 _operation_state: &StackOperationState,
1260 ) -> Result<Object<StackOperationState, O, Self>, OperationError<ObjectRequestError>> {
1261 // TODO: Authorization?
1262 for (_object_name, object_meta) in self.metadata.objects.iter() {
1263 if let Ok(object) = (object_meta.from_str)(object_str) {
1264 return Ok(unsafe {
1265 Object::new_unchecked(*object.downcast::<O>().unwrap(), self.clone())
1266 });
1267 }
1268 }
1269
1270 Err(OperationError::Unhandled)
1271 }
1272 }
1273