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

ambee/giterated

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

Giterated Stack `ObjectValue` and `Setting` refactor.

This refactor adds value and setting update events, as well as value getters. Additionally, the stack is now the owner of the ability to write settings into storage. This is accomplished with the `MetadataProvider` trait. This sets up the ground work for push federation, cache, and basically everything else. commit 7befc583cb3e0c6719506c550ed66ac76293413c Author: Amber <[email protected]> Date: Fri Sep 29 15:46:48 2023 -0500 Finish value and settings refactor in the stack. commit 3ac09994a0caafd1a0b95d9a781c7f202f20e75b Author: Amber <[email protected]> Date: Fri Sep 29 09:46:32 2023 -0500 Add set_setting handling back in commit 84fd31e3eae85d98fa68a28b333dbb32cde3bdb8 Author: Amber <[email protected]> Date: Wed Sep 27 06:36:31 2023 -0500 Remove some allocations from meta types commit 16c310ce3680c4a14ed35083b6a230aaecd43152 Author: Amber <[email protected]> Date: Wed Sep 27 05:35:03 2023 -0500 Add cargo metadata commit eb2520a20001bac7b21c6c3d34f62db32f0ada80 Author: Amber <[email protected]> Date: Wed Sep 27 05:26:27 2023 -0500 Refactor setting and value management to use the unified stack. Allows for tight management, inspection, and eventing of setting and value management. commit 901fe103da0fce4b40f33b0a8b64404049ae03cf Author: Amber <[email protected]> Date: Wed Sep 27 02:38:33 2023 -0500 Set up ground work for value / settings refactor

Amber - ⁨2⁩ years ago

parent: tbd commit: ⁨c377e4d

⁨giterated-stack/src/handler.rs⁩ - ⁨42335⁩ 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 self
426 }
427
428 /// Register a [`GiteratedObjectValue<O>`] type with the runtime, providing
429 /// its associated handler for [`GetValue`].
430 ///
431 /// # Type Registration
432 /// This will register the provided [`GiteratedObjectValue`] type for its matching / specified
433 /// object type. It will **not** register the object type automatically.
434 pub fn value<O, V, A, F>(&mut self, handler: F) -> &mut Self
435 where
436 O: GiteratedObject + 'static,
437 V: GiteratedObjectValue<Object = O> + 'static + Clone,
438 F: GiteratedOperationHandler<A, O, GetValueTyped<V>, S> + Clone + 'static + Send + Sync,
439 {
440 let object_name = handler.object_name().to_string();
441 let value_name = V::value_name().to_string();
442
443 let wrapped = OperationWrapper::new(handler, self.state.clone());
444
445 let handler_object_name = object_name.clone();
446 let handler_value_name = value_name.clone();
447
448 // Insert handler so GetValue is handled properly
449 let _handler = move |object: &O,
450 operation: GetValueTyped<AnyValue<O>>,
451 _state: S,
452 operation_state: StackOperationState,
453 stack: Arc<GiteratedStack>| {
454 let stack = stack;
455 let object_name = handler_object_name;
456 let value_name = handler_value_name;
457 let object = object.clone();
458 async move {
459 for (target, getter) in stack.value_getters.iter() {
460 if target.object_kind != object_name {
461 continue;
462 }
463
464 if target.value_kind != value_name {
465 continue;
466 }
467
468 return match getter
469 .handle(
470 &(Box::new(object.clone()) as Box<dyn Any + Send + Sync>),
471 &(Box::new(GetValueTyped::<V> {
472 value_name: operation.value_name,
473 ty: Default::default(),
474 }) as Box<dyn Any + Send + Sync>),
475 &operation_state,
476 )
477 .await {
478 Ok(success) => Ok(*success.downcast::<<GetValueTyped<V> as GiteratedOperation<O>>::Success>().unwrap()),
479 Err(err) => Err(match err {
480 OperationError::Operation(failure) => OperationError::Operation(*failure.downcast::<<GetValueTyped<V> as GiteratedOperation<O>>::Failure>().unwrap()),
481 OperationError::Internal(internal) => OperationError::Internal(internal),
482 OperationError::Unhandled => OperationError::Unhandled,
483 }),
484 }
485 }
486
487 Err(OperationError::Unhandled)
488 }
489 .boxed_local()
490 };
491
492 assert!(self
493 .value_getters
494 .insert(
495 ObjectValuePair {
496 object_kind: object_name,
497 value_kind: value_name
498 },
499 wrapped
500 )
501 .is_none());
502
503 self.metadata.register_value::<O, V>();
504
505 self
506 }
507
508 /// Register a handler for [`GetSetting`] for it's associated object type.
509 pub fn object_settings<O, A, F>(&mut self, handler: F) -> &mut Self
510 where
511 O: GiteratedObject + 'static,
512 F: GiteratedOperationHandler<A, O, GetSetting, S> + Clone + 'static + Send + Sync,
513 {
514 let object_name = handler.object_name().to_string();
515
516 let wrapped = OperationWrapper::new(handler, self.state.clone());
517
518 assert!(self.setting_getters.insert(object_name, wrapped).is_none());
519
520 self
521 }
522
523 pub fn value_change<O, A, F, V>(&mut self, handler: F) -> &mut Self
524 where
525 O: GiteratedObject + 'static,
526 F: GiteratedOperationHandler<A, O, ValueChangedShim<V>, S> + Clone + 'static + Send + Sync,
527 V: GiteratedObjectValue<Object = O> + Clone + 'static,
528 {
529 let object_name = handler.object_name().to_string();
530
531 let wrapped = OperationWrapper::new(handler, self.state.clone());
532
533 assert!(self.setting_getters.insert(object_name, wrapped).is_none());
534
535 self
536 }
537
538 pub fn object_metadata_provider(&mut self, provider: Box<dyn MetadataProvider>) -> &mut Self {
539 self.metadata_providers.push(provider);
540
541 self
542 }
543 }
544
545 #[derive(Serialize, Deserialize, Clone)]
546 pub struct ValueChangedShim<V> {
547 new_value: V,
548 }
549
550 impl<O, V> GiteratedOperation<O> for ValueChangedShim<V>
551 where
552 O: GiteratedObject,
553 V: GiteratedObjectValue<Object = O>,
554 {
555 type Success = V;
556
557 type Failure = MissingValue;
558 }
559
560 impl RuntimeMetadata {
561 fn register_object<O: GiteratedObject + 'static>(&mut self) {
562 let object_name = O::object_name().to_string();
563
564 let object_meta = ObjectMeta::new::<O>();
565
566 if self.objects.insert(object_name, object_meta).is_some() {
567 trace!(
568 "Registration of object {} overwrote previous registration.",
569 O::object_name()
570 );
571 } else {
572 trace!("Registration of object {}.", O::object_name())
573 }
574 }
575
576 fn register_operation<O: GiteratedObject + 'static, D: GiteratedOperation<O> + 'static>(
577 &mut self,
578 ) {
579 let object_name = O::object_name().to_string();
580 let operation_name = D::operation_name().to_string();
581
582 if self
583 .operations
584 .insert(
585 ObjectOperationPair {
586 object_name: object_name,
587 operation_name: operation_name,
588 },
589 OperationMeta::new::<O, D>(),
590 )
591 .is_some()
592 {
593 trace!(
594 "Registration of object operation {}<{}> overwrote previous registration.",
595 D::operation_name(),
596 O::object_name()
597 );
598 } else {
599 trace!(
600 "Registration of object operation {}<{}>.",
601 D::operation_name(),
602 O::object_name()
603 )
604 }
605 }
606
607 fn register_value<
608 O: GiteratedObject + 'static,
609 V: GiteratedObjectValue<Object = O> + 'static,
610 >(
611 &mut self,
612 ) {
613 let object_name = O::object_name().to_string();
614 let value_name = V::value_name().to_string();
615
616 if self
617 .values
618 .insert(
619 ObjectValuePair {
620 object_kind: object_name,
621 value_kind: value_name,
622 },
623 ValueMeta::new::<V>(),
624 )
625 .is_some()
626 {
627 trace!(
628 "Registration of value <{}>::{} overwrote previous registration.",
629 O::object_name(),
630 V::value_name()
631 );
632 } else {
633 trace!(
634 "Registration of value <{}>::{}.",
635 O::object_name(),
636 V::value_name()
637 );
638 }
639 }
640
641 fn register_setting<O: GiteratedObject + 'static, S: Setting + 'static>(&mut self) {
642 if self
643 .settings
644 .insert(
645 ObjectSettingPair {
646 object_kind: O::object_name().to_string(),
647 setting_name: S::name().to_string(),
648 },
649 SettingMeta::new::<O, S>(),
650 )
651 .is_some()
652 {
653 trace!(
654 "Registration of setting {} overwrote previous registration.",
655 S::name()
656 );
657 } else {
658 trace!("Registration of setting {}.", S::name());
659 }
660 }
661
662 fn append(&mut self, other: Self) {
663 self.objects.extend(other.objects);
664 self.operations.extend(other.operations);
665 self.values.extend(other.values);
666 self.settings.extend(other.settings);
667 }
668 }
669 impl GiteratedStack {
670 /// Handles a giterated network message, returning either a raw success
671 /// payload or a serialized error payload.
672 pub async fn handle_network_message(
673 &self,
674 message: AuthenticatedPayload,
675 operation_state: &StackOperationState,
676 ) -> Result<Vec<u8>, OperationError<Vec<u8>>> {
677 let message: GiteratedMessage<AnyObject, AnyOperation> = message.into_message();
678
679 // Deserialize the object, also getting the object type's name
680 let (object_type, object) = {
681 let mut result = None;
682
683 for (object_type, object_meta) in self.metadata.objects.iter() {
684 if let Ok(object) = (object_meta.from_str)(&message.object.0) {
685 result = Some((object_type.clone(), object));
686 break;
687 }
688 }
689
690 result
691 }
692 .ok_or_else(|| OperationError::Unhandled)?;
693
694 trace!(
695 "Handling network message {}::<{}>",
696 message.operation,
697 object_type
698 );
699
700 if message.operation == "get_value" {
701 // Special case
702 let operation: GetValue = serde_json::from_slice(&message.payload.0).unwrap();
703
704 let result = self
705 .network_get_value(
706 object,
707 object_type.clone(),
708 operation.clone(),
709 operation_state,
710 )
711 .await;
712
713 // In the case of internal errors, attach context
714 let result = result.map_err(|err| match err {
715 OperationError::Operation(operation) => OperationError::Operation(operation),
716 OperationError::Internal(internal) => {
717 OperationError::Internal(internal.context(format!(
718 "{}::get_value::<{}> outcome",
719 object_type, operation.value_name
720 )))
721 }
722 OperationError::Unhandled => OperationError::Unhandled,
723 });
724
725 return result;
726 } else if message.operation == "get_setting" {
727 let operation: GetSetting = serde_json::from_slice(&message.payload.0).unwrap();
728 let setting_meta = self
729 .metadata
730 .settings
731 .get(&ObjectSettingPair {
732 object_kind: object_type.clone(),
733 setting_name: operation.setting_name.clone(),
734 })
735 .ok_or_else(|| OperationError::Unhandled)?;
736 let raw_result = self
737 .get_setting(object, object_type.clone(), operation, operation_state)
738 .await;
739 return match raw_result {
740 Ok(success) => {
741 // Success is the setting type, serialize it
742 let serialized = (setting_meta.serialize)(&(*success)).unwrap();
743
744 Ok(serde_json::to_vec(&serialized).unwrap())
745 }
746 Err(err) => Err(match err {
747 OperationError::Operation(failure) => {
748 // We know how to resolve this type
749 let failure: GetSettingError = *failure.downcast().unwrap();
750
751 OperationError::Operation(serde_json::to_vec(&failure).unwrap())
752 }
753 OperationError::Internal(internal) => {
754 OperationError::Internal(internal.context(format!(
755 "{}::get_setting::<{}> handler outcome",
756 object_type, setting_meta.name
757 )))
758 }
759 OperationError::Unhandled => OperationError::Unhandled,
760 }),
761 };
762 } else if message.operation == "set_setting" {
763 let operation: SetSetting = serde_json::from_slice(&message.payload.0).unwrap();
764
765 trace!(
766 "Handling network {}::set_setting for {}",
767 object_type,
768 operation.setting_name
769 );
770
771 let setting_meta = self
772 .metadata
773 .settings
774 .get(&ObjectSettingPair {
775 object_kind: object_type.clone(),
776 setting_name: operation.setting_name.clone(),
777 })
778 .unwrap();
779
780 let setting = (setting_meta.deserialize)(operation.value.0)
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.as_ref()) {
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), object_meta, &(*setting), setting_meta)
808 .await;
809
810 return match raw_result {
811 Ok(_) => {
812 (setting_meta.setting_updated)(
813 object,
814 setting,
815 operation_state.runtime.clone(),
816 operation_state,
817 )
818 .await;
819
820 Ok(serde_json::to_vec(&()).unwrap())
821 }
822 Err(e) => Err(OperationError::Internal(e.context(format!(
823 "writing object {} setting {}",
824 object_type, operation.setting_name
825 )))),
826 };
827 }
828
829 trace!(
830 "Failed to resolve setting provider for setting {} for object {}",
831 operation.setting_name,
832 object_type,
833 );
834 }
835 }
836
837 let target = ObjectOperationPair {
838 object_name: object_type.clone(),
839 operation_name: message.operation.clone(),
840 };
841
842 // Resolve the target operations from the handlers table
843 let handler = self
844 .operation_handlers
845 .get(&target)
846 .ok_or_else(|| OperationError::Unhandled)?;
847
848 trace!(
849 "Resolved operation handler for network message {}::<{}>",
850 message.operation,
851 object_type
852 );
853
854 // Deserialize the operation
855 let meta = self
856 .metadata
857 .operations
858 .get(&target)
859 .ok_or_else(|| OperationError::Unhandled)?;
860
861 let operation =
862 (meta.deserialize)(&message.payload.0).as_internal_error_with_context(format!(
863 "deserializing operation {}::{}",
864 target.object_name, target.operation_name
865 ))?;
866
867 trace!(
868 "Deserialized operation for network message {}::<{}>",
869 message.operation,
870 object_type
871 );
872
873 trace!(
874 "Calling handler for network message {}::<{}>",
875 message.operation,
876 object_type
877 );
878
879 // Get the raw result of the operation, where the return values are boxed.
880 let raw_result = handler.handle(&object, &operation, operation_state).await;
881
882 trace!(
883 "Finished handling network message {}::<{}>",
884 message.operation,
885 object_type
886 );
887
888 // Deserialize the raw result for the network
889 match raw_result {
890 Ok(success) => Ok((meta.serialize_success)(success).as_internal_error()?),
891 Err(err) => Err(match err {
892 OperationError::Operation(failure) => {
893 OperationError::Operation((meta.serialize_error)(failure).as_internal_error()?)
894 }
895 OperationError::Internal(internal) => {
896 OperationError::Internal(internal.context(format!(
897 "operation {}::{} handler outcome",
898 target.object_name, target.operation_name
899 )))
900 }
901 OperationError::Unhandled => OperationError::Unhandled,
902 }),
903 }
904 }
905
906 pub async fn network_get_value(
907 &self,
908 object: Box<dyn Any + Send + Sync>,
909 object_kind: String,
910 operation: GetValue,
911 operation_state: &StackOperationState,
912 ) -> Result<Vec<u8>, OperationError<Vec<u8>>> {
913 trace!("Handling network get_value for {}", operation.value_name);
914
915 let value_meta = self
916 .metadata
917 .values
918 .get(&ObjectValuePair {
919 object_kind: object_kind.clone(),
920 value_kind: operation.value_name.clone(),
921 })
922 .ok_or_else(|| OperationError::Unhandled)?;
923
924 for (target, getter) in self.value_getters.iter() {
925 if target.object_kind != object_kind {
926 continue;
927 }
928
929 if target.value_kind != operation.value_name {
930 continue;
931 }
932
933 return match getter
934 .handle(&(object), &((value_meta.typed_get)()), operation_state)
935 .await
936 {
937 Ok(success) => {
938 // Serialize success, which is the value type itself
939 let serialized = (value_meta.serialize)(success).as_internal_error()?;
940
941 Ok(serialized)
942 }
943 Err(err) => Err(match err {
944 OperationError::Operation(failure) => {
945 // Failure is sourced from GetValue operation, but this is hardcoded for now
946 let failure: GetValueError = *failure.downcast().unwrap();
947
948 OperationError::Operation(serde_json::to_vec(&failure).as_internal_error()?)
949 }
950 OperationError::Internal(internal) => OperationError::Internal(internal),
951 OperationError::Unhandled => OperationError::Unhandled,
952 }),
953 };
954 }
955
956 Err(OperationError::Unhandled)
957 }
958
959 pub async fn get_setting(
960 &self,
961 object: Box<dyn Any + Send + Sync>,
962 object_kind: String,
963 operation: GetSetting,
964 operation_state: &StackOperationState,
965 ) -> Result<Box<dyn Any + Send + Sync>, OperationError<Box<dyn Any + Send + Sync>>> {
966 trace!(
967 "Handling network {}::get_setting for {}",
968 object_kind,
969 operation.setting_name
970 );
971
972 let setting_getter = self
973 .setting_getters
974 .get(&object_kind)
975 .ok_or_else(|| OperationError::Unhandled)?;
976
977 setting_getter
978 .handle(&object, &(Box::new(operation) as Box<_>), operation_state)
979 .await
980 }
981
982 pub async fn network_set_setting(
983 &self,
984 object: Box<dyn Any + Send + Sync>,
985 object_kind: String,
986 operation: SetSetting,
987 operation_state: &StackOperationState,
988 ) -> Result<Vec<u8>, OperationError<Vec<u8>>> {
989 trace!(
990 "Handling network {}::set_setting for {}",
991 object_kind,
992 operation.setting_name
993 );
994
995 let target = ObjectSettingPair {
996 object_kind: object_kind.clone(),
997 setting_name: operation.setting_name.clone(),
998 };
999
1000 let handler = self.setting_change.get(&target).unwrap();
1001
1002 let raw_result = handler
1003 .handle(&object, &(Box::new(operation) as _), operation_state)
1004 .await;
1005
1006 match raw_result {
1007 Ok(_) => {
1008 // Serialize success, which is the value type itself
1009 let serialized = serde_json::to_vec(&()).as_internal_error()?;
1010
1011 Ok(serialized)
1012 }
1013 Err(err) => Err(match err {
1014 OperationError::Operation(failure) => {
1015 // Failure is sourced from GetValue operation, but this is hardcoded for now
1016 let failure: GetValueError = *failure.downcast().unwrap();
1017
1018 OperationError::Operation(serde_json::to_vec(&failure).as_internal_error()?)
1019 }
1020 OperationError::Internal(internal) => OperationError::Internal(internal),
1021 OperationError::Unhandled => OperationError::Unhandled,
1022 }),
1023 }
1024 }
1025 }
1026
1027 use core::fmt::Debug;
1028
1029 #[async_trait::async_trait(?Send)]
1030 impl ObjectBackend<StackOperationState> for Arc<GiteratedStack> {
1031 async fn object_operation<O, D>(
1032 &self,
1033 in_object: O,
1034 operation_name: &str,
1035 payload: D,
1036 operation_state: &StackOperationState,
1037 ) -> Result<D::Success, OperationError<D::Failure>>
1038 where
1039 O: GiteratedObject + Debug + 'static,
1040 D: GiteratedOperation<O> + Debug + 'static,
1041 {
1042 // Erase object and operation types.
1043 let object = Box::new(in_object.clone()) as Box<dyn Any + Send + Sync>;
1044 let operation = Box::new(payload) as Box<dyn Any + Send + Sync>;
1045
1046 // We need to hijack get_value, set_setting, and get_setting.
1047 if operation_name == "get_value" {
1048 let mut value_meta = None;
1049 for (_, meta) in self.metadata.values.iter() {
1050 if (meta.is_get_value_typed)(&operation) {
1051 value_meta = Some(meta);
1052 break;
1053 }
1054 }
1055
1056 let value_meta = value_meta.ok_or_else(|| OperationError::Unhandled)?;
1057
1058 let value_name = value_meta.name.clone();
1059
1060 trace!(
1061 "Handling get_value for {}::{}",
1062 O::object_name(),
1063 value_name
1064 );
1065
1066 for (target, getter) in self.value_getters.iter() {
1067 if target.object_kind != O::object_name() {
1068 continue;
1069 }
1070
1071 if target.value_kind != value_name {
1072 continue;
1073 }
1074
1075 return match getter
1076 .handle(&(object), &((value_meta.typed_get)()), operation_state)
1077 .await
1078 {
1079 Ok(success) => Ok(*success.downcast().unwrap()),
1080 Err(err) => Err(match err {
1081 OperationError::Operation(failure) => {
1082 OperationError::Operation(*failure.downcast::<D::Failure>().unwrap())
1083 }
1084 OperationError::Internal(internal) => {
1085 OperationError::Internal(internal.context(format!(
1086 "{}::get_value::<{}> handler outcome",
1087 O::object_name(),
1088 value_name
1089 )))
1090 }
1091 OperationError::Unhandled => OperationError::Unhandled,
1092 }),
1093 };
1094 }
1095
1096 return Err(OperationError::Unhandled);
1097 } else if operation.is::<GetSetting>() {
1098 let get_setting: Box<GetSetting> = operation.downcast().unwrap();
1099 let setting_name = get_setting.setting_name.clone();
1100
1101 let raw_result = self
1102 .get_setting(
1103 object,
1104 O::object_name().to_string(),
1105 *get_setting,
1106 operation_state,
1107 )
1108 .await;
1109
1110 return match raw_result {
1111 Ok(success) => {
1112 // Success is the setting type, serialize it
1113 // let serialized = (setting_meta.serialize)(success).unwrap();
1114
1115 // Ok(serde_json::to_vec(&serialized).unwrap())
1116 Ok(*success.downcast().unwrap())
1117 }
1118 Err(err) => Err(match err {
1119 OperationError::Operation(failure) => {
1120 // We know this is the right type
1121 OperationError::Operation(*failure.downcast().unwrap())
1122 }
1123 OperationError::Internal(internal) => {
1124 OperationError::Internal(internal.context(format!(
1125 "{}::get_setting::<{}> handler outcome",
1126 O::object_name(),
1127 setting_name
1128 )))
1129 }
1130 OperationError::Unhandled => OperationError::Unhandled,
1131 }),
1132 };
1133 } else if operation.is::<SetSetting>() {
1134 todo!()
1135 } else if operation.is::<ObjectRequest>() {
1136 todo!()
1137 }
1138
1139 // Resolve the operation from the known operations table.
1140 let operation_type = {
1141 let mut operation_type = None;
1142
1143 for (target, operation_meta) in self.metadata.operations.iter() {
1144 // Skip elements that we know will not match
1145 if target.object_name != O::object_name() {
1146 continue;
1147 }
1148
1149 if target.operation_name != operation_name {
1150 continue;
1151 }
1152
1153 if (operation_meta.any_is_same)(&operation) {
1154 operation_type = Some(target.clone());
1155 break;
1156 }
1157 }
1158
1159 operation_type
1160 }
1161 .ok_or_else(|| OperationError::Unhandled)?;
1162
1163 // Resolve the handler from our handler tree
1164 let handler_tree = self
1165 .operation_handlers
1166 .get(&operation_type)
1167 .ok_or_else(|| OperationError::Unhandled)?;
1168
1169 let raw_result = handler_tree
1170 .handle(&object, &operation, operation_state)
1171 .await;
1172
1173 // Convert the dynamic result back into its concrete type
1174 match raw_result {
1175 Ok(result) => Ok(*result.downcast::<D::Success>().unwrap()),
1176 Err(err) => Err(match err {
1177 OperationError::Internal(internal) => {
1178 OperationError::Internal(internal.context(format!(
1179 "operation {}::{} handler outcome",
1180 operation_type.object_name, operation_type.operation_name
1181 )))
1182 }
1183 OperationError::Operation(boxed_error) => {
1184 OperationError::Operation(*boxed_error.downcast::<D::Failure>().unwrap())
1185 }
1186 OperationError::Unhandled => OperationError::Unhandled,
1187 }),
1188 }
1189 }
1190
1191 async fn get_object<O: GiteratedObject + Debug + 'static>(
1192 &self,
1193 object_str: &str,
1194 _operation_state: &StackOperationState,
1195 ) -> Result<Object<StackOperationState, O, Self>, OperationError<ObjectRequestError>> {
1196 // TODO: Authorization?
1197 for (_object_name, object_meta) in self.metadata.objects.iter() {
1198 if let Ok(object) = (object_meta.from_str)(object_str) {
1199 return Ok(unsafe {
1200 Object::new_unchecked(*object.downcast::<O>().unwrap(), self.clone())
1201 });
1202 }
1203 }
1204
1205 Err(OperationError::Unhandled)
1206 }
1207 }
1208