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 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
//! Plugin system for the router.
//!
//! Provides a customization mechanism for the router.
//!
//! Requests received by the router make their way through a processing pipeline. Each request is
//! processed at:
//! - router
//! - execution
//! - subgraph (multiple in parallel if multiple subgraphs are accessed)
//! stages.
//!
//! A plugin can choose to interact with the flow of requests at any or all of these stages of
//! processing. At each stage a [`Service`] is provided which provides an appropriate
//! mechanism for interacting with the request and response.
pub mod serde;
#[macro_use]
pub mod test;
use std::any::TypeId;
use std::fmt;
use std::sync::Arc;
use std::task::Context;
use std::task::Poll;
use ::serde::de::DeserializeOwned;
use ::serde::Deserialize;
use async_trait::async_trait;
use futures::future::BoxFuture;
use multimap::MultiMap;
use once_cell::sync::Lazy;
use schemars::gen::SchemaGenerator;
use schemars::JsonSchema;
use tower::buffer::future::ResponseFuture;
use tower::buffer::Buffer;
use tower::BoxError;
use tower::Service;
use tower::ServiceBuilder;
use crate::graphql;
use crate::layers::ServiceBuilderExt;
use crate::notification::Notify;
use crate::router_factory::Endpoint;
use crate::services::execution;
use crate::services::router;
use crate::services::subgraph;
use crate::services::supergraph;
use crate::ListenAddr;
type InstanceFactory = fn(
&serde_json::Value,
Arc<String>,
Notify<String, graphql::Response>,
) -> BoxFuture<Result<Box<dyn DynPlugin>, BoxError>>;
type SchemaFactory = fn(&mut SchemaGenerator) -> schemars::schema::Schema;
/// Global list of plugins.
#[linkme::distributed_slice]
pub static PLUGINS: [Lazy<PluginFactory>] = [..];
/// Initialise details for a plugin
#[non_exhaustive]
pub struct PluginInit<T> {
/// Configuration
pub config: T,
/// Router Supergraph Schema (schema definition language)
pub supergraph_sdl: Arc<String>,
pub(crate) notify: Notify<String, graphql::Response>,
}
impl<T> PluginInit<T>
where
T: for<'de> Deserialize<'de>,
{
#[deprecated = "use PluginInit::builder() instead"]
/// Create a new PluginInit for the supplied config and SDL.
pub fn new(config: T, supergraph_sdl: Arc<String>) -> Self {
Self::builder()
.config(config)
.supergraph_sdl(supergraph_sdl)
.notify(Notify::builder().build())
.build()
}
/// Try to create a new PluginInit for the supplied JSON and SDL.
///
/// This will fail if the supplied JSON cannot be deserialized into the configuration
/// struct.
#[deprecated = "use PluginInit::try_builder() instead"]
pub fn try_new(
config: serde_json::Value,
supergraph_sdl: Arc<String>,
) -> Result<Self, BoxError> {
Self::try_builder()
.config(config)
.supergraph_sdl(supergraph_sdl)
.notify(Notify::builder().build())
.build()
}
#[cfg(test)]
pub(crate) fn fake_new(config: T, supergraph_sdl: Arc<String>) -> Self {
PluginInit {
config,
supergraph_sdl,
notify: Notify::for_tests(),
}
}
}
#[buildstructor::buildstructor]
impl<T> PluginInit<T>
where
T: for<'de> Deserialize<'de>,
{
/// Create a new PluginInit builder
#[builder(entry = "builder", exit = "build", visibility = "pub")]
/// Build a new PluginInit for the supplied configuration and SDL.
///
/// You can reuse a notify instance, or Build your own.
pub(crate) fn new_builder(
config: T,
supergraph_sdl: Arc<String>,
notify: Notify<String, graphql::Response>,
) -> Self {
PluginInit {
config,
supergraph_sdl,
notify,
}
}
#[builder(entry = "try_builder", exit = "build", visibility = "pub")]
/// Try to build a new PluginInit for the supplied json configuration and SDL.
///
/// You can reuse a notify instance, or Build your own.
/// invoking build() will fail if the JSON doesn't comply with the configuration format.
pub(crate) fn try_new_builder(
config: serde_json::Value,
supergraph_sdl: Arc<String>,
notify: Notify<String, graphql::Response>,
) -> Result<Self, BoxError> {
let config: T = serde_json::from_value(config)?;
Ok(PluginInit {
config,
supergraph_sdl,
notify,
})
}
/// Create a new PluginInit builder
#[builder(entry = "fake_builder", exit = "build", visibility = "pub")]
fn fake_new_builder(
config: T,
supergraph_sdl: Option<Arc<String>>,
notify: Option<Notify<String, graphql::Response>>,
) -> Self {
PluginInit {
config,
supergraph_sdl: supergraph_sdl.unwrap_or_default(),
notify: notify.unwrap_or_else(Notify::for_tests),
}
}
}
/// Factories for plugin schema and configuration.
#[derive(Clone)]
pub struct PluginFactory {
pub(crate) name: String,
instance_factory: InstanceFactory,
schema_factory: SchemaFactory,
pub(crate) type_id: TypeId,
}
impl fmt::Debug for PluginFactory {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PluginFactory")
.field("name", &self.name)
.field("type_id", &self.type_id)
.finish()
}
}
impl PluginFactory {
pub(crate) fn is_apollo(&self) -> bool {
self.name.starts_with("apollo.") || self.name.starts_with("experimental.")
}
/// Create a plugin factory.
pub fn new<P: PluginUnstable>(group: &str, name: &str) -> PluginFactory {
let plugin_factory_name = if group.is_empty() {
name.to_string()
} else {
format!("{group}.{name}")
};
tracing::debug!(%plugin_factory_name, "creating plugin factory");
PluginFactory {
name: plugin_factory_name,
instance_factory: |configuration, schema, notify| {
Box::pin(async move {
let init = PluginInit::try_builder()
.config(configuration.clone())
.supergraph_sdl(schema)
.notify(notify)
.build()?;
let plugin = P::new(init).await?;
Ok(Box::new(plugin) as Box<dyn DynPlugin>)
})
},
schema_factory: |gen| gen.subschema_for::<<P as PluginUnstable>::Config>(),
type_id: TypeId::of::<P>(),
}
}
/// Create a plugin factory.
#[allow(dead_code)]
pub(crate) fn new_private<P: PluginPrivate>(group: &str, name: &str) -> PluginFactory {
let plugin_factory_name = if group.is_empty() {
name.to_string()
} else {
format!("{group}.{name}")
};
tracing::debug!(%plugin_factory_name, "creating plugin factory");
PluginFactory {
name: plugin_factory_name,
instance_factory: |configuration, schema, notify| {
Box::pin(async move {
let init = PluginInit::try_builder()
.config(configuration.clone())
.supergraph_sdl(schema)
.notify(notify)
.build()?;
let plugin = P::new(init).await?;
Ok(Box::new(plugin) as Box<dyn DynPlugin>)
})
},
schema_factory: |gen| gen.subschema_for::<<P as PluginPrivate>::Config>(),
type_id: TypeId::of::<P>(),
}
}
pub(crate) async fn create_instance(
&self,
configuration: &serde_json::Value,
supergraph_sdl: Arc<String>,
notify: Notify<String, graphql::Response>,
) -> Result<Box<dyn DynPlugin>, BoxError> {
(self.instance_factory)(configuration, supergraph_sdl, notify).await
}
#[cfg(test)]
pub(crate) async fn create_instance_without_schema(
&self,
configuration: &serde_json::Value,
) -> Result<Box<dyn DynPlugin>, BoxError> {
(self.instance_factory)(configuration, Default::default(), Default::default()).await
}
pub(crate) fn create_schema(&self, gen: &mut SchemaGenerator) -> schemars::schema::Schema {
(self.schema_factory)(gen)
}
}
// If we wanted to create a custom subset of plugins, this is where we would do it
/// Get a copy of the registered plugin factories.
pub(crate) fn plugins() -> impl Iterator<Item = &'static Lazy<PluginFactory>> {
PLUGINS.iter()
}
/// All router plugins must implement the Plugin trait.
///
/// This trait defines lifecycle hooks that enable hooking into Apollo Router services.
/// The trait also provides a default implementations for each hook, which returns the associated service unmodified.
/// For more information about the plugin lifecycle please check this documentation <https://www.apollographql.com/docs/router/customizations/native/#plugin-lifecycle>
#[async_trait]
pub trait Plugin: Send + Sync + 'static {
/// The configuration for this plugin.
/// Typically a `struct` with `#[derive(serde::Deserialize)]`.
///
/// If a plugin is [registered][register_plugin()!],
/// it can be enabled through the `plugins` section of Router YAMLÂ configuration
/// by having a sub-section named after the plugin.
/// The contents of this section are deserialized into this `Config` type
/// and passed to [`Plugin::new`] as part of [`PluginInit`].
type Config: JsonSchema + DeserializeOwned + Send;
/// This is invoked once after the router starts and compiled-in
/// plugins are registered.
async fn new(init: PluginInit<Self::Config>) -> Result<Self, BoxError>
where
Self: Sized;
/// This function is EXPERIMENTAL and its signature is subject to change.
///
/// This service runs at the very beginning and very end of the request lifecycle.
/// It's the entrypoint of every requests and also the last hook before sending the response.
/// Define supergraph_service if your customization needs to interact at the earliest or latest point possible.
/// For example, this is a good opportunity to perform JWT verification before allowing a request to proceed further.
fn router_service(&self, service: router::BoxService) -> router::BoxService {
service
}
/// This service runs after the HTTP request payload has been deserialized into a GraphQL request,
/// and before the GraphQL response payload is serialized into a raw HTTP response.
/// Define supergraph_service if your customization needs to interact at the earliest or latest point possible, yet operates on GraphQL payloads.
fn supergraph_service(&self, service: supergraph::BoxService) -> supergraph::BoxService {
service
}
/// This service handles initiating the execution of a query plan after it's been generated.
/// Define `execution_service` if your customization includes logic to govern execution (for example, if you want to block a particular query based on a policy decision).
fn execution_service(&self, service: execution::BoxService) -> execution::BoxService {
service
}
/// This service handles communication between the Apollo Router and your subgraphs.
/// Define `subgraph_service` to configure this communication (for example, to dynamically add headers to pass to a subgraph).
/// The `_subgraph_name` parameter is useful if you need to apply a customization only specific subgraphs.
fn subgraph_service(
&self,
_subgraph_name: &str,
service: subgraph::BoxService,
) -> subgraph::BoxService {
service
}
/// Return the name of the plugin.
fn name(&self) -> &'static str
where
Self: Sized,
{
get_type_of(self)
}
/// Return one or several `Endpoint`s and `ListenAddr` and the router will serve your custom web Endpoint(s).
///
/// This method is experimental and subject to change post 1.0
fn web_endpoints(&self) -> MultiMap<ListenAddr, Endpoint> {
MultiMap::new()
}
}
/// Plugin trait for unstable features
///
/// This trait defines lifecycle hooks that enable hooking into Apollo Router services. The hooks that are not already defined
/// in the [Plugin] trait are not considered stable and may change at any moment.
/// The trait also provides a default implementations for each hook, which returns the associated service unmodified.
/// For more information about the plugin lifecycle please check this documentation <https://www.apollographql.com/docs/router/customizations/native/#plugin-lifecycle>
#[async_trait]
pub trait PluginUnstable: Send + Sync + 'static {
/// The configuration for this plugin.
/// Typically a `struct` with `#[derive(serde::Deserialize)]`.
///
/// If a plugin is [registered][register_plugin()!],
/// it can be enabled through the `plugins` section of Router YAMLÂ configuration
/// by having a sub-section named after the plugin.
/// The contents of this section are deserialized into this `Config` type
/// and passed to [`Plugin::new`] as part of [`PluginInit`].
type Config: JsonSchema + DeserializeOwned + Send;
/// This is invoked once after the router starts and compiled-in
/// plugins are registered.
async fn new(init: PluginInit<Self::Config>) -> Result<Self, BoxError>
where
Self: Sized;
/// This function is EXPERIMENTAL and its signature is subject to change.
///
/// This service runs at the very beginning and very end of the request lifecycle.
/// It's the entrypoint of every requests and also the last hook before sending the response.
/// Define supergraph_service if your customization needs to interact at the earliest or latest point possible.
/// For example, this is a good opportunity to perform JWT verification before allowing a request to proceed further.
fn router_service(&self, service: router::BoxService) -> router::BoxService {
service
}
/// This service runs after the HTTP request payload has been deserialized into a GraphQL request,
/// and before the GraphQL response payload is serialized into a raw HTTP response.
/// Define supergraph_service if your customization needs to interact at the earliest or latest point possible, yet operates on GraphQL payloads.
fn supergraph_service(&self, service: supergraph::BoxService) -> supergraph::BoxService {
service
}
/// This service handles initiating the execution of a query plan after it's been generated.
/// Define `execution_service` if your customization includes logic to govern execution (for example, if you want to block a particular query based on a policy decision).
fn execution_service(&self, service: execution::BoxService) -> execution::BoxService {
service
}
/// This service handles communication between the Apollo Router and your subgraphs.
/// Define `subgraph_service` to configure this communication (for example, to dynamically add headers to pass to a subgraph).
/// The `_subgraph_name` parameter is useful if you need to apply a customization only specific subgraphs.
fn subgraph_service(
&self,
_subgraph_name: &str,
service: subgraph::BoxService,
) -> subgraph::BoxService {
service
}
/// Return the name of the plugin.
fn name(&self) -> &'static str
where
Self: Sized,
{
get_type_of(self)
}
/// Return one or several `Endpoint`s and `ListenAddr` and the router will serve your custom web Endpoint(s).
///
/// This method is experimental and subject to change post 1.0
fn web_endpoints(&self) -> MultiMap<ListenAddr, Endpoint> {
MultiMap::new()
}
/// test
fn unstable_method(&self);
}
#[async_trait]
impl<P> PluginUnstable for P
where
P: Plugin,
{
type Config = <P as Plugin>::Config;
async fn new(init: PluginInit<Self::Config>) -> Result<Self, BoxError>
where
Self: Sized,
{
Plugin::new(init).await
}
fn router_service(&self, service: router::BoxService) -> router::BoxService {
Plugin::router_service(self, service)
}
fn supergraph_service(&self, service: supergraph::BoxService) -> supergraph::BoxService {
Plugin::supergraph_service(self, service)
}
fn execution_service(&self, service: execution::BoxService) -> execution::BoxService {
Plugin::execution_service(self, service)
}
fn subgraph_service(
&self,
subgraph_name: &str,
service: subgraph::BoxService,
) -> subgraph::BoxService {
Plugin::subgraph_service(self, subgraph_name, service)
}
/// Return the name of the plugin.
fn name(&self) -> &'static str
where
Self: Sized,
{
Plugin::name(self)
}
fn web_endpoints(&self) -> MultiMap<ListenAddr, Endpoint> {
Plugin::web_endpoints(self)
}
fn unstable_method(&self) {
todo!()
}
}
/// Internal Plugin trait
///
/// This trait defines lifecycle hooks that enable hooking into Apollo Router services. The hooks that are not already defined
/// in the [Plugin] or [PluginUnstable] traits are internal hooks not yet open to public usage. This allows testing of new plugin
/// hooks without committing to their API right away.
/// The trait also provides a default implementations for each hook, which returns the associated service unmodified.
/// For more information about the plugin lifecycle please check this documentation <https://www.apollographql.com/docs/router/customizations/native/#plugin-lifecycle>
#[async_trait]
pub(crate) trait PluginPrivate: Send + Sync + 'static {
/// The configuration for this plugin.
/// Typically a `struct` with `#[derive(serde::Deserialize)]`.
///
/// If a plugin is [registered][register_plugin()!],
/// it can be enabled through the `plugins` section of Router YAMLÂ configuration
/// by having a sub-section named after the plugin.
/// The contents of this section are deserialized into this `Config` type
/// and passed to [`Plugin::new`] as part of [`PluginInit`].
type Config: JsonSchema + DeserializeOwned + Send;
/// This is invoked once after the router starts and compiled-in
/// plugins are registered.
async fn new(init: PluginInit<Self::Config>) -> Result<Self, BoxError>
where
Self: Sized;
/// This function is EXPERIMENTAL and its signature is subject to change.
///
/// This service runs at the very beginning and very end of the request lifecycle.
/// It's the entrypoint of every requests and also the last hook before sending the response.
/// Define supergraph_service if your customization needs to interact at the earliest or latest point possible.
/// For example, this is a good opportunity to perform JWT verification before allowing a request to proceed further.
fn router_service(&self, service: router::BoxService) -> router::BoxService {
service
}
/// This service runs after the HTTP request payload has been deserialized into a GraphQL request,
/// and before the GraphQL response payload is serialized into a raw HTTP response.
/// Define supergraph_service if your customization needs to interact at the earliest or latest point possible, yet operates on GraphQL payloads.
fn supergraph_service(&self, service: supergraph::BoxService) -> supergraph::BoxService {
service
}
/// This service handles initiating the execution of a query plan after it's been generated.
/// Define `execution_service` if your customization includes logic to govern execution (for example, if you want to block a particular query based on a policy decision).
fn execution_service(&self, service: execution::BoxService) -> execution::BoxService {
service
}
/// This service handles communication between the Apollo Router and your subgraphs.
/// Define `subgraph_service` to configure this communication (for example, to dynamically add headers to pass to a subgraph).
/// The `_subgraph_name` parameter is useful if you need to apply a customization only specific subgraphs.
fn subgraph_service(
&self,
_subgraph_name: &str,
service: subgraph::BoxService,
) -> subgraph::BoxService {
service
}
/// Return the name of the plugin.
fn name(&self) -> &'static str
where
Self: Sized,
{
get_type_of(self)
}
/// Return one or several `Endpoint`s and `ListenAddr` and the router will serve your custom web Endpoint(s).
///
/// This method is experimental and subject to change post 1.0
fn web_endpoints(&self) -> MultiMap<ListenAddr, Endpoint> {
MultiMap::new()
}
}
#[async_trait]
impl<P> PluginPrivate for P
where
P: PluginUnstable,
{
type Config = <P as PluginUnstable>::Config;
async fn new(init: PluginInit<Self::Config>) -> Result<Self, BoxError>
where
Self: Sized,
{
PluginUnstable::new(init).await
}
fn router_service(&self, service: router::BoxService) -> router::BoxService {
PluginUnstable::router_service(self, service)
}
fn supergraph_service(&self, service: supergraph::BoxService) -> supergraph::BoxService {
PluginUnstable::supergraph_service(self, service)
}
fn execution_service(&self, service: execution::BoxService) -> execution::BoxService {
PluginUnstable::execution_service(self, service)
}
fn subgraph_service(
&self,
subgraph_name: &str,
service: subgraph::BoxService,
) -> subgraph::BoxService {
PluginUnstable::subgraph_service(self, subgraph_name, service)
}
/// Return the name of the plugin.
fn name(&self) -> &'static str
where
Self: Sized,
{
PluginUnstable::name(self)
}
fn web_endpoints(&self) -> MultiMap<ListenAddr, Endpoint> {
PluginUnstable::web_endpoints(self)
}
}
fn get_type_of<T>(_: &T) -> &'static str {
std::any::type_name::<T>()
}
/// All router plugins must implement the DynPlugin trait.
///
/// This trait defines lifecycle hooks that enable hooking into Apollo Router services.
/// The trait also provides a default implementations for each hook, which returns the associated service unmodified.
/// For more information about the plugin lifecycle please check this documentation <https://www.apollographql.com/docs/router/customizations/native/#plugin-lifecycle>
#[async_trait]
pub(crate) trait DynPlugin: Send + Sync + 'static {
/// This service runs at the very beginning and very end of the request lifecycle.
/// It's the entrypoint of every requests and also the last hook before sending the response.
/// Define supergraph_service if your customization needs to interact at the earliest or latest point possible.
/// For example, this is a good opportunity to perform JWT verification before allowing a request to proceed further.
fn router_service(&self, service: router::BoxService) -> router::BoxService;
/// This service runs after the HTTP request payload has been deserialized into a GraphQL request,
/// and before the GraphQL response payload is serialized into a raw HTTP response.
/// Define supergraph_service if your customization needs to interact at the earliest or latest point possible, yet operates on GraphQL payloads.
fn supergraph_service(&self, service: supergraph::BoxService) -> supergraph::BoxService;
/// This service handles initiating the execution of a query plan after it's been generated.
/// Define `execution_service` if your customization includes logic to govern execution (for example, if you want to block a particular query based on a policy decision).
fn execution_service(&self, service: execution::BoxService) -> execution::BoxService;
/// This service handles communication between the Apollo Router and your subgraphs.
/// Define `subgraph_service` to configure this communication (for example, to dynamically add headers to pass to a subgraph).
/// The `_subgraph_name` parameter is useful if you need to apply a customization only on specific subgraphs.
fn subgraph_service(
&self,
_subgraph_name: &str,
service: subgraph::BoxService,
) -> subgraph::BoxService;
/// Return the name of the plugin.
fn name(&self) -> &'static str;
/// Return one or several `Endpoint`s and `ListenAddr` and the router will serve your custom web Endpoint(s).
fn web_endpoints(&self) -> MultiMap<ListenAddr, Endpoint>;
/// Support downcasting
fn as_any(&self) -> &dyn std::any::Any;
/// Support downcasting
fn as_any_mut(&mut self) -> &mut dyn std::any::Any;
}
#[async_trait]
impl<T> DynPlugin for T
where
T: PluginPrivate,
for<'de> <T as PluginPrivate>::Config: Deserialize<'de>,
{
fn router_service(&self, service: router::BoxService) -> router::BoxService {
self.router_service(service)
}
fn supergraph_service(&self, service: supergraph::BoxService) -> supergraph::BoxService {
self.supergraph_service(service)
}
fn execution_service(&self, service: execution::BoxService) -> execution::BoxService {
self.execution_service(service)
}
fn subgraph_service(&self, name: &str, service: subgraph::BoxService) -> subgraph::BoxService {
self.subgraph_service(name, service)
}
fn name(&self) -> &'static str {
self.name()
}
/// Return one or several `Endpoint`s and `ListenAddr` and the router will serve your custom web Endpoint(s).
fn web_endpoints(&self) -> MultiMap<ListenAddr, Endpoint> {
self.web_endpoints()
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
}
/// Register a plugin with a group and a name
/// Grouping prevent name clashes for plugins, so choose something unique, like your domain name.
/// Plugins will appear in the configuration as a layer property called: {group}.{name}
#[macro_export]
macro_rules! register_plugin {
($group: literal, $name: literal, $plugin_type: ident < $generic: ident >) => {
// Artificial scope to avoid naming collisions
const _: () = {
use $crate::_private::once_cell::sync::Lazy;
use $crate::_private::PluginFactory;
use $crate::_private::PLUGINS;
#[$crate::_private::linkme::distributed_slice(PLUGINS)]
#[linkme(crate = $crate::_private::linkme)]
static REGISTER_PLUGIN: Lazy<PluginFactory> = Lazy::new(|| {
$crate::plugin::PluginFactory::new::<$plugin_type<$generic>>($group, $name)
});
};
};
($group: literal, $name: literal, $plugin_type: ident) => {
// Artificial scope to avoid naming collisions
const _: () = {
use $crate::_private::once_cell::sync::Lazy;
use $crate::_private::PluginFactory;
use $crate::_private::PLUGINS;
#[$crate::_private::linkme::distributed_slice(PLUGINS)]
#[linkme(crate = $crate::_private::linkme)]
static REGISTER_PLUGIN: Lazy<PluginFactory> =
Lazy::new(|| $crate::plugin::PluginFactory::new::<$plugin_type>($group, $name));
};
};
}
/// Register a private plugin with a group and a name
/// Grouping prevent name clashes for plugins, so choose something unique, like your domain name.
/// Plugins will appear in the configuration as a layer property called: {group}.{name}
#[macro_export]
macro_rules! register_private_plugin {
($group: literal, $name: literal, $plugin_type: ident < $generic: ident >) => {
// Artificial scope to avoid naming collisions
const _: () = {
use $crate::_private::once_cell::sync::Lazy;
use $crate::_private::PluginFactory;
use $crate::_private::PLUGINS;
#[$crate::_private::linkme::distributed_slice(PLUGINS)]
#[linkme(crate = $crate::_private::linkme)]
static REGISTER_PLUGIN: Lazy<PluginFactory> = Lazy::new(|| {
$crate::plugin::PluginFactory::new_private::<$plugin_type<$generic>>($group, $name)
});
};
};
($group: literal, $name: literal, $plugin_type: ident) => {
// Artificial scope to avoid naming collisions
const _: () = {
use $crate::_private::once_cell::sync::Lazy;
use $crate::_private::PluginFactory;
use $crate::_private::PLUGINS;
#[$crate::_private::linkme::distributed_slice(PLUGINS)]
#[linkme(crate = $crate::_private::linkme)]
static REGISTER_PLUGIN: Lazy<PluginFactory> = Lazy::new(|| {
$crate::plugin::PluginFactory::new_private::<$plugin_type>($group, $name)
});
};
};
}
/// Handler represents a [`Plugin`] endpoint.
#[derive(Clone)]
pub(crate) struct Handler {
service: Buffer<router::BoxService, router::Request>,
}
impl Handler {
pub(crate) fn new(service: router::BoxService) -> Self {
Self {
service: ServiceBuilder::new().buffered().service(service),
}
}
}
impl Service<router::Request> for Handler {
type Response = router::Response;
type Error = BoxError;
type Future = ResponseFuture<BoxFuture<'static, Result<Self::Response, Self::Error>>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.service.poll_ready(cx)
}
fn call(&mut self, req: router::Request) -> Self::Future {
self.service.call(req)
}
}
impl From<router::BoxService> for Handler {
fn from(original: router::BoxService) -> Self {
Self::new(original)
}
}