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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
//! Macros for [`async-injector`](https://docs.rs/async-injector).
//!
//! This provides the [Provider] derive, which can be used to automatically
//! construct and inject dependencies. See its documentation for how to use.

#![recursion_limit = "256"]

extern crate proc_macro;

use darling::FromMeta;
use proc_macro2::{Span, TokenStream};
use quote::{quote, quote_spanned};
use syn::spanned::Spanned as _;
use syn::*;

/// Helper derive to implement a provider.
///
/// The `Provider` derive can only be used on struct. Each field designates a
/// value that must either be injected, or provided during construction.
///
/// ```rust
/// use async_injector::Provider;
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// enum Tag {
///     Table,
///     Url,
/// }
///
/// #[derive(Provider)]
/// struct Deps {
///     fixed: String,
///     #[dependency(optional, tag = "Tag::Table")]
///     table: Option<String>,
///     #[dependency(tag = "Tag::Url")]
///     url: String,
///     #[dependency]
///     connection_limit: u32,
/// }
/// ```
///
/// This generates another struct call `<ident>Provider`, with the following
/// functions:
///
/// ```rust,no_run
/// use async_injector::{Error, Injector};
///
/// # struct Deps {}
/// impl Deps {
///     /// Construct a new provider.
///     async fn provider(injector: &Injector, fixed: String) -> Result<DepsProvider, Error>
///     # { todo!() }
/// }
///
/// struct DepsProvider {
///     /* private fields */
/// }
///
/// impl DepsProvider {
///     /// Try to construct the current value. Returns [None] unless all
///     /// required dependencies are available.
///     fn build(&mut self) -> Option<Deps>
///     # { todo!() }
///
///     /// Wait for a dependency to be updated.
///     ///
///     /// Once a dependency has been updated, the next call to [setup]
///     /// will eagerly try to build the dependency instead of waiting for
///     /// another update.
///     async fn wait(&mut self) -> Deps
///     # { todo!() }
///
///     /// Update and try to build the provided value.
///     ///
///     /// This is like combining [wait] and [build] in a manner that
///     /// allows the value to be built without waiting for it the first
///     /// time.
///     ///
///     /// The first call to [update] will return immediately, and subsequent
///     /// calls will block for updates.
///     async fn wait_for_update(&mut self) -> Option<Deps>
///     # { todo!() }
/// }
/// ```
///
/// # Field attributes
///
/// The `#[dependency]` attribute can be used to mark fields which need to be
/// injected. It takes an optional `#[dependency(tag = "..")]`, which allows you
/// to specify the tag to use when constructing the injected [Key].
///
/// ```rust,no_run
/// use async_injector::Provider;
///
/// #[derive(Provider)]
/// struct DatabaseParams {
///     #[dependency(tag = "\"url\"")]
///     url: String,
///     #[dependency]
///     connection_limit: u32,
/// }
/// ```
///
/// # Examples
///
/// ```rust,no_run
/// use async_injector::{Injector, Key, Provider};
/// use serde::Serialize;
/// use tokio_stream::StreamExt as _;
///
/// /// Fake database connection.
/// #[derive(Clone, Debug, PartialEq, Eq)]
/// struct Database {
///     url: String,
///     connection_limit: u32,
/// }
///
/// /// Provider that describes how to construct a database.
/// #[derive(Serialize)]
/// pub enum Tag {
///     DatabaseUrl,
///     ConnectionLimit,
/// }
///
/// #[derive(Provider)]
/// struct DatabaseParams {
///     #[dependency(tag = "Tag::DatabaseUrl")]
///     url: String,
///     #[dependency(tag = "Tag::ConnectionLimit")]
///     connection_limit: u32,
/// }
///
/// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let db_url_key = Key::<String>::tagged(Tag::DatabaseUrl)?;
/// let conn_limit_key = Key::<u32>::tagged(Tag::ConnectionLimit)?;
///
/// let injector = Injector::new();
///
/// let database_injector = injector.clone();
/// let mut database = DatabaseParams::provider(&injector).await?;
///
/// tokio::spawn(async move {
///     loop {
///         match database.update().await {
///             Some(update) => {
///                 database_injector.update(Database {
///                     url: update.url,
///                     connection_limit: update.connection_limit,
///                 }).await;
///             }
///             None => {
///                 database_injector.clear::<Database>().await;
///             }
///         }
///     }
/// });
///
/// let (mut database_stream, database) = injector.stream::<Database>().await;
///
/// // None of the dependencies are available, so it hasn't been constructed.
/// assert!(database.is_none());
///
/// assert!(injector
///     .update_key(&db_url_key, String::from("example.com"))
///     .await
///     .is_none());
///
/// assert!(injector.update_key(&conn_limit_key, 5).await.is_none());
///
/// let new_database = database_stream.recv().await;
///
/// // Database instance is available!
/// assert_eq!(
///     new_database,
///     Some(Database {
///         url: String::from("example.com"),
///         connection_limit: 5
///     })
/// );
///
/// Ok(())
/// # }
/// ```
///
/// [Key]: https://docs.rs/async-injector/0/async_injector/struct.Key.html
#[proc_macro_derive(Provider, attributes(dependency))]
pub fn provider_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let ast = syn::parse_macro_input!(input as DeriveInput);

    match implement(&ast) {
        Ok(stream) => stream,
        Err(e) => e.to_compile_error(),
    }
    .into()
}

/// Derive to implement the `Provider` trait.
fn implement(ast: &DeriveInput) -> syn::Result<TokenStream> {
    let st = match ast.data {
        Data::Struct(ref st) => st,
        _ => panic!("`Provider` attribute is only supported on structs"),
    };

    let config = provider_config(st)?;
    let (provider, provider_ident, fixed_args, fixed_idents) = impl_provider(ast, &config);

    let vis = &ast.vis;
    let ident = &ast.ident;
    let generics = &ast.generics;

    let output = quote! {
        impl #generics #ident #generics {
            /// Construct a new provider for this type.
            #vis async fn provider(injector: &::async_injector::Injector #(, #fixed_args)*) -> Result<#provider_ident #generics, ::async_injector::Error> {
                #provider_ident::new(injector #(, #fixed_idents)*).await
            }
        }

        #provider
    };

    Ok(output)
}

/// Build a provider configuration.
fn provider_config(st: &DataStruct) -> syn::Result<ProviderConfig<'_>> {
    let fields = provider_fields(st)?;
    Ok(ProviderConfig { fields })
}

/// Extracts provider fields.
fn provider_fields(st: &DataStruct) -> syn::Result<Vec<ProviderField<'_>>> {
    let mut fields = Vec::new();

    for field in &st.fields {
        let ident = field.ident.as_ref().expect("missing identifier for field");

        let mut dependency = None;

        for a in &field.attrs {
            let meta = match a.parse_meta() {
                Ok(meta) => meta,
                _ => continue,
            };

            if meta.path().is_ident("dependency") {
                if dependency.is_some() {
                    return Err(syn::Error::new(
                        meta.span(),
                        "multiple #[dependency] attributes are not supported",
                    ));
                }

                let d = if let Meta::Path(_) = meta {
                    DependencyAttr::default()
                } else {
                    match DependencyAttr::from_meta(&meta) {
                        Ok(d) => d,
                        Err(e) => panic!("bad #[dependency(..)] attribute: {}", e),
                    }
                };

                dependency = Some((meta.span(), d));
                continue;
            }
        }

        let dependency = match dependency {
            Some((span, dep)) => Some(Dependency {
                span,
                tag: dep.tag.map(|t| {
                    syn::parse_str::<TokenStream>(&t).expect("`tag` to be valid expression")
                }),
                optional: dep.optional,
                ty: if dep.optional {
                    optional_ty(&field.ty)
                } else {
                    &field.ty
                },
            }),
            None => None,
        };

        fields.push(ProviderField {
            ident,
            field,
            dependency,
        })
    }

    Ok(fields)
}

/// Build the provider type.
///
/// The factory is responsible for building providers that builds instances of
/// the provided type.
///
/// This step is necessary to support "fixed" fields, i.e. fields who's value
/// are provided at build time.
fn impl_provider<'a>(
    ast: &DeriveInput,
    config: &ProviderConfig<'a>,
) -> (TokenStream, Ident, Vec<TokenStream>, Vec<Ident>) {
    let provider_ident = Ident::new(&format!("{}Provider", ast.ident), Span::call_site());

    let mut provider_fields = Vec::new();
    let mut constructor_assign = Vec::new();
    let mut constructor_fields = Vec::new();
    let mut injected_update = Vec::new();
    let mut provider_extract = Vec::new();
    let mut initialized_fields = Vec::new();

    let mut fixed_args = Vec::new();
    let mut fixed_idents = Vec::new();

    for f in &config.fields {
        let field_ident = f.ident;
        let field_stream = Ident::new(&format!("{}_stream", field_ident), Span::call_site());
        let field_value = Ident::new(&format!("{}_value", field_ident), Span::call_site());

        if let Some(dep) = &f.dependency {
            let field_ty = dep.ty;

            provider_fields.push(quote!(#field_stream: ::async_injector::Stream<#field_ty>));
            provider_fields.push(quote!(#field_value: Option<#field_ty>));

            let key = match &dep.tag {
                Some(tag) => quote!(::async_injector::Key::<#field_ty>::tagged(#tag)?),
                None => quote!(::async_injector::Key::<#field_ty>::of()),
            };

            constructor_assign.push(quote! {
                let (#field_stream, #field_value) = __injector.stream_key(#key).await;
            });

            constructor_fields.push(field_stream.clone());
            constructor_fields.push(field_value.clone());

            injected_update.push(quote! {
                #field_value = self.#field_stream.recv() => {
                    self.#field_value = #field_value;
                }
            });

            if dep.optional {
                initialized_fields.push(quote_spanned! { f.field.span() =>
                    #field_ident: self.#field_value.as_ref().map(Clone::clone),
                });
            } else {
                provider_extract.push(quote_spanned! { f.field.span() =>
                    let #field_value = match self.#field_value.as_ref() {
                        Some(#field_value) => #field_value,
                        None => return None,
                    };
                });

                initialized_fields.push(quote_spanned! { dep.span =>
                    #field_ident: #field_value.clone(),
                });
            };
        } else {
            let field_ty = &f.field.ty;

            provider_fields.push(quote!(#field_ident: #field_ty));

            initialized_fields.push(quote_spanned! { f.field.span() =>
                #field_ident: self.#field_ident.clone(),
            });

            constructor_fields.push(field_ident.clone());

            fixed_args.push(quote!(#field_ident: #field_ty));
            fixed_idents.push(field_ident.clone());
        }
    }

    let ident = &ast.ident;

    let vis = &ast.vis;
    let generics = &ast.generics;
    let args = &fixed_args;

    let provider = quote_spanned! { ast.span() =>
        #vis struct #provider_ident #generics {
            /// Whether or not the injector has been initialized.
            __init: bool,
            #(#provider_fields,)*
        }

        impl #generics #provider_ident #generics {
            /// Construct a new provider.
            #vis async fn new(__injector: &::async_injector::Injector #(, #args)*) -> Result<#provider_ident #generics, ::async_injector::Error> {
                #(#constructor_assign)*

                Ok(#provider_ident {
                    __init: true,
                    #(#constructor_fields,)*
                })
            }

            /// Try to construct the current value. Returns [None] unless all
            /// required dependencies are available.
            #[allow(dead_code)]
            #vis fn build(&self) -> Option<#ident #generics> {
                #(#provider_extract)*

                Some(#ident {
                    #(#initialized_fields)*
                })
            }

            /// Wait until the provided value has changed. Either some
            /// dependencies are no longer available at which it returns `None`,
            /// or all dependencies are available after which we return the
            /// build value.
            #[allow(dead_code)]
            #vis async fn wait_for_update(&mut self) -> Option<#ident #generics> {
                if self.__init {
                    self.__init = false;
                } else {
                    self.wait_internal().await;
                }

                self.build()
            }

            /// Wait until we can successfully build the complete provided
            /// value.
            #[allow(dead_code)]
            #vis async fn wait(&mut self) -> #ident #generics {
                loop {
                    if let Some(value) = self.wait_for_update().await {
                        return value;
                    }
                }
            }

            async fn wait_internal(&mut self) {
                ::async_injector::derive::select! {
                    #(#injected_update)*
                }
            }
        }
    };

    (provider, provider_ident, fixed_args, fixed_idents)
}

/// Extract the optional type argument from the given type.
fn optional_ty(ty: &Type) -> &Type {
    match ty {
        Type::Path(ref path) => {
            let last = path.path.segments.last().expect("missing path segment");

            if last.ident != "Option" {
                panic!("optional field must be of type: Option<T>");
            }

            let arguments = match &last.arguments {
                PathArguments::AngleBracketed(ref arguments) => &arguments.args,
                other => panic!("bad path arguments: {:?}", other),
            };

            let first = arguments.iter().next().expect("at least one argument");

            match first {
                GenericArgument::Type(ref ty) => ty,
                _ => panic!("expected type generic argument"),
            }
        }
        _ => {
            panic!("expected optional type to be a path");
        }
    }
}

struct ProviderConfig<'a> {
    fields: Vec<ProviderField<'a>>,
}

struct ProviderField<'a> {
    ident: &'a Ident,
    field: &'a Field,
    dependency: Option<Dependency<'a>>,
}

#[derive(Debug)]
struct Dependency<'a> {
    span: Span,
    /// Use a string tag.
    tag: Option<TokenStream>,
    optional: bool,
    ty: &'a Type,
}

/// #[dependency(...)] attribute
#[derive(Debug, Default, FromMeta)]
#[darling(default)]
struct DependencyAttr {
    /// Use a string tag.
    tag: Option<String>,
    /// If the field is optional.
    optional: bool,
}