lxy 0.1.1

A convenient async http and RPC framework in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
use std::any::TypeId;
use std::ptr;
use std::sync::{Arc, RwLock};

use crate::error::Result;
use crate::utils::map::TypedMap;

use super::{BoxedFactory, BoxedResolver, Container, Factory, Resolver};

/// A very simple but safe wrapper around a raw pointer to an `Arc<T>`,
/// aims to erase the type `T` while preserving the reference counting semantics.
///
/// With [ResolvedRaw] stored in containers,
/// we will be able to store different types in a single container cache.
#[derive(Debug)]
pub struct ResolvedRaw {
  ptr: *const (),
  clone_fn: unsafe fn(*const ()) -> *const (),
  drop_fn: unsafe fn(*const ()),
}

unsafe impl Send for ResolvedRaw {}
unsafe impl Sync for ResolvedRaw {}

unsafe fn clone_arc<T>(ptr: *const ()) -> *const ()
where
  T: 'static,
{
  // SAFETY: `ptr` originated from `Arc::into_raw(Arc<T>)`.
  unsafe { Arc::increment_strong_count(ptr as *const T) };
  ptr
}

unsafe fn drop_arc<T>(ptr: *const ())
where
  T: 'static,
{
  // SAFETY: `ptr` originated from `Arc::into_raw(Arc<T>)`.
  drop(unsafe { Arc::from_raw(ptr as *const T) });
}

impl<T> From<Arc<T>> for ResolvedRaw
where
  T: 'static + Sized,
{
  fn from(arc: Arc<T>) -> Self {
    ResolvedRaw {
      ptr: Arc::into_raw(arc) as *const (),
      clone_fn: clone_arc::<T>,
      drop_fn: drop_arc::<T>,
    }
  }
}

impl Clone for ResolvedRaw {
  fn clone(&self) -> Self {
    ResolvedRaw {
      ptr: unsafe { (self.clone_fn)(self.ptr) },
      clone_fn: self.clone_fn,
      drop_fn: self.drop_fn,
    }
  }
}

impl Drop for ResolvedRaw {
  fn drop(&mut self) {
    if self.ptr.is_null() {
      return;
    }

    unsafe { (self.drop_fn)(self.ptr) };
  }
}

impl ResolvedRaw {
  /// Converts back to `Arc<T>`.
  ///
  /// # Safety
  ///
  /// The caller must ensure that the original type `T` is the same as the type being converted to.
  /// Otherwise, this will lead to undefined behavior.
  unsafe fn recover<T>(mut self) -> Arc<T> {
    // we make a null ptr to underlaying Arc<T> and swap it with self.0 to avoid double free
    let ptr = self.ptr as *const T;
    self.ptr = ptr::null::<()>();
    unsafe { Arc::from_raw(ptr) }
  }
}

/// A trait to easily convert any type into [ResolvedRaw].
trait IntoResolvedRaw {
  fn into_resolved_raw(self) -> ResolvedRaw;
}

impl<T> IntoResolvedRaw for T
where
  T: 'static + Sized,
{
  fn into_resolved_raw(self) -> ResolvedRaw {
    let arc = Arc::new(self);
    ResolvedRaw {
      ptr: Arc::into_raw(arc) as *const (),
      clone_fn: clone_arc::<T>,
      drop_fn: drop_arc::<T>,
    }
  }
}

/// Simple wrapper resolver to map any resolved [T] into [ResolvedRaw].
#[derive(Clone)]
struct MapIntoResolvedRaw<T>(T);

impl<Rg, R> Resolver<Rg> for MapIntoResolvedRaw<R>
where
  R: Resolver<Rg> + Clone + Send + Sync + 'static,
  R::Return: IntoResolvedRaw + 'static,
{
  type Return = ResolvedRaw;

  fn resolve(&self, registry: &Rg) -> Result<ResolvedRaw> {
    self
      .0
      .resolve(registry)
      .map(|resolved| resolved.into_resolved_raw())
  }
}

struct RawResolver<Registry>(BoxedResolver<Registry, ResolvedRaw>);

impl<Registry> RawResolver<Registry> {
  fn new<R>(resolver: R) -> Self
  where
    R: Resolver<Registry> + Clone + Send + Sync + 'static,
    R::Return: IntoResolvedRaw + 'static,
  {
    Self(BoxedResolver::new(MapIntoResolvedRaw(resolver)))
  }
}

/// A singleton container
///
/// ## Cache
///
/// The container maintains an internal cache to store resolved instances.
/// When an instance is requested via the `get` method, the container first checks
/// the cache to see if the instance has already been created. If it has, the cached
/// instance is returned. If not, the container uses the registered factory to create
/// the instance, stores it in the cache, and then returns it.
///
/// ## Thread Safety
///
/// The container uses `RwLock` to ensure thread-safe access to the cache. This allows multiple threads
/// to read from the cache concurrently, while write access (when adding new instances) is exclusive.
/// This design ensures that the container can be safely used in multi-threaded environments.
///
/// ## Example
///
/// ```rust
/// use std::sync::Arc;
/// use lxy::container::{RawContainer, Container, Value};
///
/// #[derive(Debug, Clone)]
/// struct Service;
///
/// #[derive(Debug)]
/// struct App {
///    service: Arc<Service>,
/// }
///
/// let mut container = RawContainer::default();
///
/// container.add(Value(Service));
/// container.bind(Service);
/// container.add(|service: Arc<Service>| App { service });
///
/// let app = container.get::<App>();  // Ok(Arc<App>)
/// let app2 = container.get::<App>(); // Ok(Arc<App>)
///
/// assert!(app.is_ok());
/// assert_eq!(Arc::into_raw(app.unwrap()), Arc::into_raw(app2.unwrap()));
/// ```
#[derive(Default, Clone)]
pub struct RawContainer {
  map: Arc<RwLock<TypedMap<RawResolver<Self>>>>,
  cache: Arc<RwLock<TypedMap<ResolvedRaw>>>,
}

impl RawContainer {
  /// Creates a new empty [RawContainer].
  pub fn new() -> Self {
    Self::default()
  }
}

impl Container for RawContainer {
  fn add<F, T, Deps>(&mut self, factory: F)
  where
    F: Factory<T, Deps>,
    T: 'static,
    Deps: 'static,
  {
    let id: TypeId = TypeId::of::<T>();

    // We need to clear the cache entry when a new factory is added for the same type.
    self
      .map
      .write()
      .unwrap()
      .insert(id, RawResolver::new(BoxedFactory::new(factory)));

    self.cache.write().unwrap().remove(&id);
  }

  fn bind<T>(&mut self, instance: T)
  where
    T: 'static,
  {
    let id: TypeId = TypeId::of::<T>();
    self
      .cache
      .write()
      .unwrap()
      .insert(id, instance.into_resolved_raw());
  }

  fn get<T>(&self) -> Result<Arc<T>>
  where
    T: 'static,
  {
    use crate::error::TypedError;

    let id: TypeId = TypeId::of::<T>();

    // Check cache first
    let mut entry = self.cache.read().unwrap().get(&id).cloned();

    if entry.is_none() {
      // Get resolver or return error
      let resolver = self
        .map
        .read()
        .unwrap()
        .get(&id)
        .ok_or_else(|| {
          super::TypeNotRegistered::error(format!(
            "Type '{}' is not registered in the container",
            std::any::type_name::<T>()
          ))
        })?
        .0
        .clone();

      // Resolve (may fail with dependency errors)
      let raw = resolver.resolve(self)?;

      // Cache the result
      self.cache.write().unwrap().entry(id).or_insert(raw.clone());
      entry = Some(raw);
    }

    entry.map(|raw| unsafe { raw.recover() }).ok_or_else(|| {
      unreachable!(
        "Entry must be Some at this point as we either got it from cache or just inserted it"
      )
    })
  }

  fn drop<T>(&mut self)
  where
    T: 'static,
  {
    let id: TypeId = TypeId::of::<T>();
    self.cache.write().unwrap().remove(&id);
  }
}

#[cfg(test)]
mod tests {
  use super::{RawContainer, ResolvedRaw};
  use crate::container::{Container, DependencyResolutionFailed, TypeNotRegistered, Value};
  use std::sync::Arc;

  #[derive(PartialEq, Debug, Clone)]
  struct Service;

  #[derive(PartialEq, Debug)]
  struct App {
    service: Arc<Service>,
  }

  #[test]
  fn test_create_from_arc() {
    let value = Arc::new(42);
    assert_eq!(Arc::strong_count(&value), 1);

    let raw: ResolvedRaw = value.clone().into();
    assert_eq!(Arc::strong_count(&value), 2);

    let recovered = unsafe { raw.recover::<i32>() };
    assert_eq!(Arc::strong_count(&value), 2);
    assert_eq!(*recovered, 42);
  }

  #[test]
  fn test_resolved_raw_clone_increments_strong_count() {
    use std::mem::ManuallyDrop;

    let value = Arc::new(123_i32);
    assert_eq!(Arc::strong_count(&value), 1);

    // Keep one Arc alive so we can reliably inspect strong_count.
    let raw: ManuallyDrop<ResolvedRaw> = ManuallyDrop::new(value.clone().into());
    assert_eq!(Arc::strong_count(&value), 2);

    // Cloning ResolvedRaw must create another strong reference.
    let _raw2: ManuallyDrop<ResolvedRaw> = ManuallyDrop::new((*raw).clone());
    assert_eq!(Arc::strong_count(&value), 3,);
  }

  #[test]
  fn test_all_together() {
    let mut container = RawContainer::default();

    container.add(Value(Service));
    container.add(|service: Arc<Service>| App { service });

    let app = container.get::<App>();
    let app2 = container.get::<App>();

    assert!(app.is_ok());
    assert_eq!(Arc::into_raw(app.unwrap()), Arc::into_raw(app2.unwrap()));
  }

  #[test]
  fn test_drop_removes_instance_from_cache_without_factory() {
    let mut container = RawContainer::default();

    // Bind an instance directly to the cache without a factory
    container.bind(Service);

    // Verify the instance is in the cache
    let service = container.get::<Service>();
    assert!(service.is_ok());

    // Drop the instance
    container.drop::<Service>();

    // Subsequent get should return Err since there's no factory
    let service_after_drop = container.get::<Service>();
    assert!(service_after_drop.is_err());
  }

  #[test]
  fn test_drop_allows_factory_to_create_new_instance() {
    use std::sync::atomic::{AtomicU32, Ordering};

    #[derive(Debug, Clone)]
    struct CountedService {
      id: u32,
    }

    let mut container = RawContainer::default();

    // Counter to track factory invocations - local to this test for isolation
    // Arc<AtomicU32> is used to satisfy Factory trait bounds (Send + Sync)
    let counter = Arc::new(AtomicU32::new(0));

    // Add a factory that creates a new instance with incremented counter each time
    let counter_clone = counter.clone();
    container.add(move || {
      let id = counter_clone.fetch_add(1, Ordering::SeqCst);
      CountedService { id }
    });

    // Get the first instance - factory creates it with id=0
    let service1 = container
      .get::<CountedService>()
      .expect("First get should create and cache instance");
    assert_eq!(service1.id, 0);

    // Get again - should return the cached instance (id=0)
    let service1_again = container
      .get::<CountedService>()
      .expect("Second get should return cached instance");
    assert_eq!(service1_again.id, 0);
    assert!(Arc::ptr_eq(&service1, &service1_again));

    // Drop the cached instance
    container.drop::<CountedService>();

    // Get again - should re-resolve from factory with new id=1
    let service2 = container
      .get::<CountedService>()
      .expect("Third get should re-resolve from factory");
    assert_eq!(
      service2.id, 1,
      "Factory should create new instance after drop"
    );

    // Verify the instances are different Arc pointers
    assert!(
      !Arc::ptr_eq(&service1, &service2),
      "New instance should be created, not reusing dropped one"
    );
  }

  #[test]
  fn test_type_not_registered_error() {
    let container = RawContainer::new();

    let result = container.get::<Service>();
    assert!(result.is_err());

    let err = result.unwrap_err();
    assert!(err.is(TypeNotRegistered));
    assert!(err.message().contains("Service"));
  }

  #[test]
  fn test_dependency_chain_error() {
    #[derive(Debug)]
    struct Config;

    #[derive(Debug)]
    struct ServiceWithConfig {
      _config: Arc<Config>,
    }

    let mut container = RawContainer::new();

    // Register Service that depends on Config (not registered)
    container.add(|config: Arc<Config>| ServiceWithConfig { _config: config });

    let result = container.get::<ServiceWithConfig>();
    assert!(result.is_err());

    let err = result.unwrap_err();
    assert!(err.is(DependencyResolutionFailed));
    assert!(err.message().contains("ServiceWithConfig"));
    assert!(err.message().contains("Config"));

    // Check source chain
    let source = err.source().expect("Should have source error");
    assert!(source.to_string().contains("Config"));
  }

  #[test]
  fn test_deep_dependency_chain_error() {
    #[derive(Debug)]
    struct Config;

    #[derive(Debug)]
    struct ServiceWithConfig {
      _config: Arc<Config>,
    }

    #[derive(Debug)]
    struct AppWithService {
      _service: Arc<ServiceWithConfig>,
    }

    let mut container = RawContainer::new();

    // Create chain: App -> Service -> Config (Config missing)
    container.add(|config: Arc<Config>| ServiceWithConfig { _config: config });
    container.add(|service: Arc<ServiceWithConfig>| AppWithService { _service: service });

    let result = container.get::<AppWithService>();
    assert!(result.is_err());

    let err = result.unwrap_err();
    // Should show: App failed because Service failed because Config missing
    assert!(err.message().contains("AppWithService"));
    assert!(err.message().contains("ServiceWithConfig"));

    // Check that we can trace through the source chain
    let mut source_opt = err.source();
    let mut depth = 0;
    while let Some(source) = source_opt {
      depth += 1;
      source_opt = source.source();
    }
    assert_eq!(depth, 2, "Should have 2 levels in the error chain");
  }
}