grafbase-sdk 0.23.1

An SDK to implement extensions for the Grafbase Gateway
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
use crate::{
    component::AnyExtension,
    types::{
        AuthorizedOperationContext, Configuration, Error, IndexedSchema, ResolvedField, Response, SubgraphHeaders,
        SubgraphSchema, SubscriptionItem, Variables,
    },
};

/// A resolver extension is called by the gateway to resolve a specific field.
///
/// # Example
///
/// You can initialize a new resolver extension with the Grafbase CLI:
///
/// ```bash
/// grafbase extension init --type resolver my-resolver
/// ```
///
/// This will generate the following:
///
/// ```rust
/// use grafbase_sdk::{
///     ResolverExtension,
///     types::{AuthorizedOperationContext, Configuration, Error, ResolvedField, Response, SubgraphHeaders, SubgraphSchema, Variables},
/// };
///
/// #[derive(ResolverExtension)]
/// struct MyResolver {
///     config: Config
/// }
///
/// // Configuration in the TOML for this extension
/// #[derive(serde::Deserialize)]
/// struct Config {
///     #[serde(default)]
///     key: Option<String>
/// }
///
/// impl ResolverExtension for MyResolver {
///     fn new(subgraph_schemas: Vec<SubgraphSchema>, config: Configuration) -> Result<Self, Error> {
///         let config: Config = config.deserialize()?;
///         Ok(Self { config })
///     }
///
///     fn resolve(
///         &mut self,
///         ctx: &AuthorizedOperationContext,
///         prepared: &[u8],
///         headers: SubgraphHeaders,
///         variables: Variables,
///     ) -> Result<Response, Error> {
///         // field which must be resolved. The prepared bytes can be customized to store anything you need in the operation cache.
///         let field = ResolvedField::try_from(prepared)?;
///         Ok(Response::null())
///     }
/// }
/// ```
/// ## Configuration
///
/// The configuration provided in the `new` method is the one defined in the `grafbase.toml`
/// file by the extension user:
///
/// ```toml
/// [extensions.my-resolver.config]
/// key = "value"
/// ```
///
/// Once your business logic is written down you can compile your extension with:
///
/// ```bash
/// grafbase extension build
/// ```
///
/// It will generate all the necessary files in a `build` directory which you can specify in the
/// `grafbase.toml` configuration with:
///
/// ```toml
/// [extensions.my-resolver]
/// path = "<project path>/build"
/// ```
///
/// ## Directives
///
/// In addition to the Rust extension, a `definitions.graphql` file will be also generated. It
/// should define directives for subgraph owners and any necessary input types, scalars or enum
/// necessary for those. Directives have two purposes for resolvers: define which fields can be
/// resolved, providing the necessary metadata for it, and provide global metadata with schema
/// directive.
///
/// A HTTP resolver extension could have the following directives for example:
///
/// ```graphql
/// scalar URL
///
/// directive @httpEndpoint(name: String!, url: URL!) on SCHEMA
///
/// directive @http(endpoint: String!, path: String!) on FIELD_DEFINITION
/// ```
///
/// The `@httpEndpoint` directive would be provided during the [new()](ResolverExtension::new())
/// method as a schema [crate::types::Directive]. The whole subgraph schema is also provided for
/// each subgraph where this extension is used. While the latter can be accessed with
/// [ResolvedField::directive()] in the [resolve()](ResolverExtension::resolve()) method.
///
pub trait ResolverExtension: Sized + 'static {
    /// Creates a new instance of the extension. The [Configuration] will contain all the
    /// configuration defined in the `grafbase.toml` by the extension user in a serialized format.
    /// Furthermore the complete subgraph schema is provided whenever this extension is used.
    ///
    /// # Configuration example
    ///
    /// The following TOML configuration:
    /// ```toml
    /// [extensions.my-auth.config]
    /// my_custom_key = "value"
    /// ```
    ///
    /// can be easily deserialized with:
    ///
    /// ```rust
    /// # use grafbase_sdk::types::{Configuration, Error};
    /// # fn dummy(config: Configuration) -> Result<(), Error> {
    /// #[derive(serde::Deserialize)]
    /// struct Config {
    ///     my_custom_key: String
    /// }
    ///
    /// let config: Config = config.deserialize()?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Directive example
    ///
    /// ```graphql
    /// extend schema @httpEdnpoint(name: "example", url: "https://example.com")
    /// ```
    ///
    /// can be easily deserialized with:
    ///
    /// ```rust
    /// # use grafbase_sdk::types::{Error, SubgraphSchema};
    /// # fn dummy(subgraph_schemas: Vec<SubgraphSchema>) -> Result<(), Error> {
    /// #[derive(serde::Deserialize)]
    /// struct HttpEndpoint {
    ///     name: String,
    ///     url: String
    /// }
    /// for schema in subgraph_schemas {
    ///     for directive in schema.directives() {
    ///         match directive.name() {
    ///             "httpEndpoint" => {
    ///                  let http_endpoint: HttpEndpoint = directive.arguments()?;
    ///             }
    ///             _ => unreachable!()
    ///         }
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    fn new(subgraph_schemas: Vec<SubgraphSchema>, config: Configuration) -> Result<Self, Error>;

    /// Prepares the field for resolution. The resulting byte array will be part of the operation
    /// cache. Backwards compatibility is not a concern as the cache is only re-used for the same
    /// schema and extension versions.
    /// By default the [ResolvedField] is cached for a simpler implementation.
    fn prepare(&mut self, field: ResolvedField<'_>) -> Result<Vec<u8>, Error> {
        Ok(field.into())
    }

    /// Resolves the field with the provided prepared bytes, headers and variables. With the
    /// default [prepare()](ResolverExtension::prepare()) you can retrieve all the relevant
    /// information with:
    /// ```rust
    /// # use grafbase_sdk::types::{SubgraphHeaders, Variables, Response, Error, ResolvedField};
    /// # fn resolve(prepared: &[u8], headers: SubgraphHeaders, variables: Variables) -> Result<Response, Error> {
    /// let field = ResolvedField::try_from(prepared)?;
    /// # Ok(Response::null())
    /// # }
    /// ```
    ///
    /// If you're not doing any data transformation it's best to forward the JSON or CBOR bytes,
    /// with [Response::json] and [Response::cbor] respectively, directly to the gateway. The
    /// gateway will always validate the subgraph data and deal with error propagation. Otherwise
    /// use [Response::data] to use the fastest supported serialization format.
    fn resolve(
        &mut self,
        ctx: &AuthorizedOperationContext,
        prepared: &[u8],
        headers: SubgraphHeaders,
        variables: Variables,
    ) -> Result<Response, Error>;

    /// Resolves a subscription for the given prepared bytes, headers, and variables.
    /// Subscriptions must implement the [Subscription] trait. It's also possible to provide a
    /// de-duplication key. If provided the gateway will first check if there is an existing
    /// subscription with the same key and if there is, re-use it for the new client. This greatly
    /// limits the impact on the upstream service. So you have two choices for the result type:
    /// - return a `Ok(subscription)` directly, without any de-duplication
    /// - return a `Ok((key, callback))` with an optional de-duplication key and a callback
    ///   function. The latter is only called if no existing subscription exists for the given key.
    #[allow(unused_variables)]
    fn resolve_subscription<'s>(
        &'s mut self,
        ctx: &'s AuthorizedOperationContext,
        prepared: &'s [u8],
        headers: SubgraphHeaders,
        variables: Variables,
    ) -> Result<impl IntoSubscription<'s>, Error> {
        unimplemented!("Subscription resolution not implemented for this resolver extension");

        // So that Rust doesn't complain about the unknown type
        #[allow(unused)]
        Ok(PhantomSubscription)
    }
}

/// A trait for consuming field outputs from streams.
///
/// This trait provides an abstraction over different implementations
/// of subscriptions to field output streams. Implementors should handle
/// the details of their specific transport mechanism while providing a
/// consistent interface for consumers.
pub trait Subscription {
    /// Retrieves the next field output from the subscription.
    ///
    /// Returns:
    /// - `Ok(Some(Data))` if a field output was available
    /// - `Ok(None)` if the subscription has ended normally
    /// - `Err(Error)` if an error occurred while retrieving the next field output
    fn next(&mut self) -> Result<Option<SubscriptionItem>, Error>;
}

pub type SubscriptionCallback<'s> = Box<dyn FnOnce() -> Result<Box<dyn Subscription + 's>, Error> + 's>;

pub trait IntoSubscription<'s> {
    fn into_deduplication_key_and_subscription_callback(self) -> (Option<Vec<u8>>, SubscriptionCallback<'s>);
}

impl<'s, S> IntoSubscription<'s> for S
where
    S: Subscription + 's,
{
    fn into_deduplication_key_and_subscription_callback(self) -> (Option<Vec<u8>>, SubscriptionCallback<'s>) {
        (None, Box::new(move || Ok(Box::new(self))))
    }
}

impl<'s, Callback, S> IntoSubscription<'s> for (Vec<u8>, Callback)
where
    Callback: FnOnce() -> Result<S, Error> + 's,
    S: Subscription + 's,
{
    fn into_deduplication_key_and_subscription_callback(self) -> (Option<Vec<u8>>, SubscriptionCallback<'s>) {
        (
            Some(self.0),
            Box::new(move || {
                let s = (self.1)()?;
                Ok(Box::new(s) as Box<dyn Subscription + 's>)
            }),
        )
    }
}

impl<'s, Callback, S> IntoSubscription<'s> for (Option<Vec<u8>>, Callback)
where
    Callback: FnOnce() -> Result<S, Error> + 's,
    S: Subscription + 's,
{
    fn into_deduplication_key_and_subscription_callback(self) -> (Option<Vec<u8>>, SubscriptionCallback<'s>) {
        (
            self.0,
            Box::new(move || {
                let s = (self.1)()?;
                Ok(Box::new(s) as Box<dyn Subscription + 's>)
            }),
        )
    }
}

impl<'s, Callback, S> IntoSubscription<'s> for (String, Callback)
where
    Callback: FnOnce() -> Result<S, Error> + 's,
    S: Subscription + 's,
{
    fn into_deduplication_key_and_subscription_callback(self) -> (Option<Vec<u8>>, SubscriptionCallback<'s>) {
        (
            Some(self.0.into()),
            Box::new(move || {
                let s = (self.1)()?;
                Ok(Box::new(s) as Box<dyn Subscription + 's>)
            }),
        )
    }
}

impl<'s, Callback, S> IntoSubscription<'s> for (Option<String>, Callback)
where
    Callback: FnOnce() -> Result<S, Error> + 's,
    S: Subscription + 's,
{
    fn into_deduplication_key_and_subscription_callback(self) -> (Option<Vec<u8>>, SubscriptionCallback<'s>) {
        (
            self.0.map(Into::into),
            Box::new(move || {
                let s = (self.1)()?;
                Ok(Box::new(s) as Box<dyn Subscription + 's>)
            }),
        )
    }
}

impl<'s, Callback, S> IntoSubscription<'s> for (Callback, Vec<u8>)
where
    Callback: FnOnce() -> Result<S, Error> + 's,
    S: Subscription + 's,
{
    fn into_deduplication_key_and_subscription_callback(self) -> (Option<Vec<u8>>, SubscriptionCallback<'s>) {
        (self.1, self.0).into_deduplication_key_and_subscription_callback()
    }
}

impl<'s, Callback, S> IntoSubscription<'s> for (Callback, Option<Vec<u8>>)
where
    Callback: FnOnce() -> Result<S, Error> + 's,
    S: Subscription + 's,
{
    fn into_deduplication_key_and_subscription_callback(self) -> (Option<Vec<u8>>, SubscriptionCallback<'s>) {
        (self.1, self.0).into_deduplication_key_and_subscription_callback()
    }
}

impl<'s, Callback, S> IntoSubscription<'s> for (Callback, String)
where
    Callback: FnOnce() -> Result<S, Error> + 's,
    S: Subscription + 's,
{
    fn into_deduplication_key_and_subscription_callback(self) -> (Option<Vec<u8>>, SubscriptionCallback<'s>) {
        (self.1, self.0).into_deduplication_key_and_subscription_callback()
    }
}

impl<'s, Callback, S> IntoSubscription<'s> for (Callback, Option<String>)
where
    Callback: FnOnce() -> Result<S, Error> + 's,
    S: Subscription + 's,
{
    fn into_deduplication_key_and_subscription_callback(self) -> (Option<Vec<u8>>, SubscriptionCallback<'s>) {
        (self.1, self.0).into_deduplication_key_and_subscription_callback()
    }
}

#[doc(hidden)]
pub fn register<T: ResolverExtension>() {
    pub(super) struct Proxy<T: ResolverExtension>(T);

    impl<T: ResolverExtension> AnyExtension for Proxy<T> {
        fn prepare(&mut self, field: ResolvedField<'_>) -> Result<Vec<u8>, Error> {
            self.0.prepare(field)
        }

        fn resolve(
            &mut self,
            ctx: &AuthorizedOperationContext,

            prepared: &[u8],
            headers: SubgraphHeaders,
            variables: Variables,
        ) -> Response {
            self.0.resolve(ctx, prepared, headers, variables).into()
        }

        fn resolve_subscription<'a>(
            &'a mut self,
            ctx: &'a AuthorizedOperationContext,

            prepared: &'a [u8],
            headers: SubgraphHeaders,
            variables: Variables,
        ) -> Result<(Option<Vec<u8>>, SubscriptionCallback<'a>), Error> {
            let (key, callback) = self
                .0
                .resolve_subscription(ctx, prepared, headers, variables)?
                .into_deduplication_key_and_subscription_callback();
            Ok((key, callback))
        }
    }

    crate::component::register_extension(Box::new(|subgraph_schemas, config| {
        let schemas = subgraph_schemas
            .into_iter()
            .map(IndexedSchema::from)
            .collect::<Vec<_>>();
        <T as ResolverExtension>::new(schemas.into_iter().map(SubgraphSchema).collect(), config)
            .map(|extension| Box::new(Proxy(extension)) as Box<dyn AnyExtension>)
    }))
}

struct PhantomSubscription;

impl Subscription for PhantomSubscription {
    fn next(&mut self) -> Result<Option<SubscriptionItem>, Error> {
        Ok(None) // No-op implementation for the phantom subscription
    }
}