grafbase_hooks/
lib.rs

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
//! # Grafbase Gateway Hooks
//!
//! This crate provides the necessary types and macros to implement hooks for the [Grafbase Gateway](https://grafbase.com/docs/self-hosted-gateway).
//! A hook is a function that is called by the gateway at specific points in the request processing.
//!
//! Build your own hooks by implementing the [`Hooks`] trait, add the [`grafbase_hooks`] attribute on top of the hooks
//! implementation and register the hooks type to the gateway using the [`register_hooks`] macro.
//!
//! The hooks component is a WASM module that is loaded by the gateway at startup. Your hooks library must be compiled with the
//! [`cargo-component`](https://github.com/bytecodealliance/cargo-component) toolchain, which compiles the hooks as a wasm32-wasip1
//! module, and inserts the needed shims so the module can act as a wasm32-wasip2 component.
//!
//! ## Usage
//!
//! Create a new rust library project with cargo:
//!
//! ```no_run,bash
//! cargo new --lib my-hooks
//! cd my-hooks
//! ```
//!
//! Add the `grafbase-hooks` as a dependency:
//!
//! ```no_run,bash
//! cargo add grafbase-hooks --features derive
//! ```
//!
//! Edit the `src/lib.rs` file and add the following code:
//!
//! ```rust
//! use grafbase_hooks::{grafbase_hooks, register_hooks, Context, ErrorResponse, Headers};
//!
//! struct MyHooks;
//!
//! #[grafbase_hooks]
//! impl Hooks for MyHooks {
//!     fn new() -> Self
//!     where
//!         Self: Sized,
//!     {
//!         MyHooks
//!     }
//!
//!     fn on_gateway_request(
//!         &mut self,
//!         context: Context,
//!         headers: Headers
//!     ) -> Result<(), ErrorResponse> {
//!         if let Some(ref auth_header) = headers.get("authorization") {
//!            context.set("auth", auth_header);
//!         }
//!
//!         Ok(())
//!     }
//! }
//!
//! register_hooks!(MyHooks);
//! ```
//!
//! The example above implements the [`Hooks#on_gateway_request`] hook, which will be available in the gateway and will be called
//! for every request.
//!
//! The [`grafbase_hooks`] attribute is used to generate the necessary code for the hooks implementation and
//! the [`register_hooks`] macro registers the hooks type to the gateway. The macro must be called in the library crate root.
//!
//! The hooks are compiled with the `cargo-component` subcommand:
//!
//! ```no_run,bash
//! cargo component build --release
//! ```
//!
//! The compiled hooks wasm module is located in the `target/wasm32-wasip1/release` directory. You can configure the gateway to load
//! the hooks in the `grafbase.toml` configuration file:
//!
//! ```no_run,toml
//! [hooks]
//! location = "path/to/my_hooks.wasm"
//! ```

#![deny(missing_docs)]

#[cfg(feature = "derive")]
pub use grafbase_hooks_derive::grafbase_hooks;

pub mod access_log;
mod hooks;
pub mod http_client;

pub use hooks::{hooks, HookExports, HookImpls, Hooks};
pub use wit::{
    CacheStatus, Context, EdgeDefinition, Error, ErrorResponse, ExecutedHttpRequest, ExecutedOperation,
    ExecutedSubgraphRequest, FieldError, GraphqlResponseStatus, HeaderError, Headers, LogError, NodeDefinition,
    RequestError, SharedContext, SubgraphRequestExecutionKind, SubgraphResponse,
};

#[doc(hidden)]
pub fn init_hooks(hooks: fn() -> Box<dyn hooks::Hooks>) {
    // SAFETY: This function is called by the gateway at startup, and the hooks are initialized only once. There can
    // be no hook calls during initialization. A hook call is by definition single-threaded.
    unsafe {
        hooks::HOOKS = Some(hooks());
    }
}

/// Registers the hooks type to the gateway. This macro must be called in the library crate root for the local hooks implementation.
#[macro_export]
macro_rules! register_hooks {
    ($hook_type:ty) => {
        #[doc(hidden)]
        #[export_name = "init-hooks"]
        pub extern "C" fn __init_hooks() -> i64 {
            grafbase_hooks::init_hooks(|| Box::new(<$hook_type as grafbase_hooks::Hooks>::new()));
            grafbase_hooks::hooks().hook_implementations() as i64
        }
    };
}

mod wit {
    #![allow(clippy::too_many_arguments, clippy::missing_safety_doc, missing_docs)]

    wit_bindgen::generate!({
        skip: ["init-hooks"],
        path: "./wit/world.wit",
    });
}

struct Component;

wit::export!(Component with_types_in wit);