1use std::{collections::BTreeSet, fmt::Display, num::NonZeroU32};
6
7use async_graphql::*;
8use iota_graphql_config::GraphQLConfig;
9use iota_indexer::db::DbUrl;
10use iota_names::config::IotaNamesConfig;
11use serde::{Deserialize, Serialize};
12use url::Url;
13
14use crate::{functional_group::FunctionalGroup, types::int::try_into_int};
15
16const DEFAULT_DB_URL: &str = "postgres://postgres:postgrespw@localhost:5432/iota_indexer";
17
18pub(crate) const DEFAULT_PAGE_SIZE: u32 = 20;
19pub(crate) const MAX_PAGE_SIZE: u32 = 50;
20
21#[GraphQLConfig]
23#[derive(Default)]
24pub struct ServerConfig {
25 pub service: ServiceConfig,
26 pub connection: ConnectionConfig,
27 pub internal_features: InternalFeatureConfig,
28 pub tx_exec_full_node: TxExecFullNodeConfig,
29 pub ide: Ide,
30 pub historic_fallback: HistoricFallbackOptions,
31}
32
33#[GraphQLConfig]
38#[derive(clap::Args, Clone, Eq, PartialEq)]
39pub struct ConnectionConfig {
40 #[arg(short, long, default_value_t = ConnectionConfig::default().port)]
42 pub port: u16,
43 #[arg(long, default_value_t = ConnectionConfig::default().host)]
45 pub host: String,
46 #[arg(short, long, default_value = DEFAULT_DB_URL)]
48 pub db_url: DbUrl,
49 #[arg(long, default_value_t = ConnectionConfig::default().db_pool_size)]
51 pub db_pool_size: u32,
52 #[arg(long, default_value_t = ConnectionConfig::default().prom_host)]
54 pub prom_host: String,
55 #[arg(long, default_value_t = ConnectionConfig::default().prom_port)]
57 pub prom_port: u16,
58 #[arg(long, default_value_t = ConnectionConfig::default().skip_migration_consistency_check)]
61 pub skip_migration_consistency_check: bool,
62 #[arg(
67 long,
68 default_value_t = ConnectionConfig::default().max_available_range,
69 env = "MAX_AVAILABLE_RANGE",
70 )]
71 pub max_available_range: u64,
72}
73
74#[GraphQLConfig]
77#[derive(clap::Args, Debug, Clone)]
78pub struct HistoricFallbackOptions {
79 #[arg(
80 long,
81 help = "Experimental: REST KV store URL for historic fallback. Depends on the iota-rest-kv API which is still being finalized."
82 )]
83 pub fallback_kv_url: Option<Url>,
84
85 #[arg(
86 long,
87 default_value_t = HistoricFallbackOptions::DEFAULT_MULTI_FETCH_BATCH_SIZE,
88 env = "FALLBACK_KV_MULTI_FETCH_BATCH_SIZE",
89 help = "Experimental: Maximum number of keys per batch request to fallback KV store."
90 )]
91 pub fallback_kv_multi_fetch_batch_size: usize,
92
93 #[arg(
94 long,
95 default_value_t = HistoricFallbackOptions::DEFAULT_CONCURRENT_FETCHES,
96 env = "FALLBACK_KV_CONCURRENT_FETCHES",
97 help = "Experimental: Maximum number of concurrent batch requests to fallback KV store."
98 )]
99 pub fallback_kv_concurrent_fetches: usize,
100
101 #[arg(
102 long,
103 default_value_t = HistoricFallbackOptions::DEFAULT_CACHE_SIZE,
104 env = "FALLBACK_KV_CACHE_SIZE",
105 help = "Experimental: Cache size for historic fallback."
106 )]
107 pub fallback_kv_cache_size: u64,
108
109 #[arg(
110 long,
111 default_value_t = HistoricFallbackOptions::DEFAULT_MAX_RESPONSE_SIZE_BYTES,
112 env = "FALLBACK_KV_MAX_RESPONSE_SIZE_BYTES",
113 help = "Experimental: Maximum size in bytes of a single response body accepted from the fallback KV store. Larger responses are rejected."
114 )]
115 pub fallback_kv_max_response_size_bytes: usize,
116}
117
118impl HistoricFallbackOptions {
119 pub const DEFAULT_MULTI_FETCH_BATCH_SIZE: usize = 100;
120 pub const DEFAULT_CONCURRENT_FETCHES: usize = 10;
121 pub const DEFAULT_CACHE_SIZE: u64 = 100_000;
122 pub const DEFAULT_MAX_RESPONSE_SIZE_BYTES: usize = 128 * 1024 * 1024;
123}
124
125impl Default for HistoricFallbackOptions {
126 fn default() -> Self {
127 Self {
128 fallback_kv_url: None,
129 fallback_kv_multi_fetch_batch_size: Self::DEFAULT_MULTI_FETCH_BATCH_SIZE,
130 fallback_kv_concurrent_fetches: Self::DEFAULT_CONCURRENT_FETCHES,
131 fallback_kv_cache_size: Self::DEFAULT_CACHE_SIZE,
132 fallback_kv_max_response_size_bytes: Self::DEFAULT_MAX_RESPONSE_SIZE_BYTES,
133 }
134 }
135}
136
137#[GraphQLConfig]
141#[derive(Default)]
142pub struct ServiceConfig {
143 pub versions: Versions,
144 pub limits: Limits,
145 pub disabled_features: BTreeSet<FunctionalGroup>,
146 pub experiments: Experiments,
147 pub iota_names: IotaNamesConfig,
148 pub background_tasks: BackgroundTasksConfig,
149}
150
151#[GraphQLConfig]
152pub struct Versions {
153 versions: Vec<String>,
154}
155
156#[GraphQLConfig]
157pub struct Limits {
158 pub max_query_depth: u32,
160 pub max_query_nodes: u32,
162 pub max_output_nodes: u32,
164 pub max_introspection_output_nodes: u32,
167 pub max_tx_payload_size: u32,
171 pub max_query_payload_size: u32,
174 pub max_db_query_cost: u32,
178 pub default_page_size: u32,
181 pub max_page_size: u32,
183 pub mutation_timeout_ms: u32,
188 pub request_timeout_ms: u32,
192 pub max_type_argument_depth: u32,
195 pub max_type_argument_width: u32,
197 pub max_type_nodes: u32,
199 pub max_move_value_depth: u32,
201 pub max_type_resolution_work: u32,
204 pub max_transaction_ids: u32,
207 pub max_subscription_recovery_checkpoints: NonZeroU32,
213 pub max_active_subscriptions: NonZeroU32,
216}
217
218#[GraphQLConfig]
219#[derive(Copy)]
220pub struct BackgroundTasksConfig {
221 pub watermark_update_ms: u64,
224}
225
226#[derive(Copy, Clone, Debug)]
230pub struct Version {
231 pub year: &'static str,
233 pub month: &'static str,
235 pub patch: &'static str,
238 pub sha: &'static str,
240 pub full: &'static str,
244}
245
246impl Version {
247 pub fn for_testing() -> Self {
249 Self {
250 year: env!("CARGO_PKG_VERSION_MAJOR"),
251 month: env!("CARGO_PKG_VERSION_MINOR"),
252 patch: env!("CARGO_PKG_VERSION_PATCH"),
253 sha: "testing-no-sha",
254 full: const_str::concat!(
256 env!("CARGO_PKG_VERSION_MAJOR"),
257 ".",
258 env!("CARGO_PKG_VERSION_MINOR"),
259 ".",
260 env!("CARGO_PKG_VERSION_PATCH"),
261 "-testing-no-sha"
262 ),
263 }
264 }
265}
266
267#[GraphQLConfig]
268#[derive(clap::Args)]
269pub struct Ide {
270 #[arg(short, long, default_value_t = Ide::default().ide_title)]
272 pub(crate) ide_title: String,
273}
274
275#[GraphQLConfig]
276#[derive(Default)]
277pub struct Experiments {
278 #[cfg(test)]
281 test_flag: bool,
282}
283
284#[GraphQLConfig]
285pub struct InternalFeatureConfig {
286 pub(crate) query_limits_checker: bool,
287 pub(crate) directive_checker: bool,
288 pub(crate) feature_gate: bool,
289 pub(crate) logger: bool,
290 pub(crate) query_timeout: bool,
291 pub(crate) metrics: bool,
292 pub(crate) tracing: bool,
293 pub(crate) apollo_tracing: bool,
294 pub(crate) open_telemetry: bool,
295}
296
297#[GraphQLConfig]
298#[derive(clap::Args, Default)]
299pub struct TxExecFullNodeConfig {
300 #[arg(long)]
302 pub(crate) node_rpc_url: Option<String>,
303}
304
305#[Object]
307impl ServiceConfig {
308 async fn is_enabled(&self, feature: FunctionalGroup) -> bool {
310 !self.disabled_features.contains(&feature)
311 }
312
313 async fn available_versions(&self) -> Vec<String> {
315 self.versions.versions.clone()
316 }
317
318 async fn enabled_features(&self) -> Vec<FunctionalGroup> {
320 FunctionalGroup::all()
321 .iter()
322 .filter(|g| !self.disabled_features.contains(g))
323 .copied()
324 .collect()
325 }
326
327 pub async fn max_query_depth(&self) -> Result<i32> {
329 try_into_int(self.limits.max_query_depth).extend()
330 }
331
332 pub async fn max_query_nodes(&self) -> Result<i32> {
335 try_into_int(self.limits.max_query_nodes).extend()
336 }
337
338 pub async fn max_output_nodes(&self) -> Result<i32> {
351 try_into_int(self.limits.max_output_nodes).extend()
352 }
353
354 pub async fn max_introspection_output_nodes(&self) -> Result<i32> {
360 try_into_int(self.limits.max_introspection_output_nodes).extend()
361 }
362
363 async fn max_db_query_cost(&self) -> Result<i32> {
367 try_into_int(self.limits.max_db_query_cost).extend()
368 }
369
370 async fn default_page_size(&self) -> Result<i32> {
372 try_into_int(self.limits.default_page_size).extend()
373 }
374
375 async fn max_page_size(&self) -> Result<i32> {
377 try_into_int(self.limits.max_page_size).extend()
378 }
379
380 async fn mutation_timeout_ms(&self) -> Result<i32> {
387 try_into_int(self.limits.mutation_timeout_ms).extend()
388 }
389
390 async fn request_timeout_ms(&self) -> Result<i32> {
393 try_into_int(self.limits.request_timeout_ms).extend()
394 }
395
396 async fn max_transaction_payload_size(&self) -> Result<i32> {
406 try_into_int(self.limits.max_tx_payload_size).extend()
407 }
408
409 async fn max_query_payload_size(&self) -> Result<i32> {
414 try_into_int(self.limits.max_query_payload_size).extend()
415 }
416
417 async fn max_type_argument_depth(&self) -> Result<i32> {
420 try_into_int(self.limits.max_type_argument_depth).extend()
421 }
422
423 async fn max_type_argument_width(&self) -> Result<i32> {
426 try_into_int(self.limits.max_type_argument_width).extend()
427 }
428
429 async fn max_type_nodes(&self) -> Result<i32> {
432 try_into_int(self.limits.max_type_nodes).extend()
433 }
434
435 async fn max_move_value_depth(&self) -> Result<i32> {
438 try_into_int(self.limits.max_move_value_depth).extend()
439 }
440
441 async fn max_type_resolution_work(&self) -> Result<i32> {
444 try_into_int(self.limits.max_type_resolution_work).extend()
445 }
446
447 async fn max_transaction_ids(&self) -> Result<i32> {
450 try_into_int(self.limits.max_transaction_ids).extend()
451 }
452}
453
454impl ConnectionConfig {
455 pub fn new(
456 port: Option<u16>,
457 host: Option<String>,
458 db_url: Option<String>,
459 db_pool_size: Option<u32>,
460 prom_host: Option<String>,
461 prom_port: Option<u16>,
462 skip_migration_consistency_check: Option<bool>,
463 max_available_range: Option<u64>,
464 ) -> Self {
465 let default = Self::default();
466 Self {
467 port: port.unwrap_or(default.port),
468 host: host.unwrap_or(default.host),
469 db_url: db_url.map_or(default.db_url, DbUrl::from),
470 db_pool_size: db_pool_size.unwrap_or(default.db_pool_size),
471 prom_host: prom_host.unwrap_or(default.prom_host),
472 prom_port: prom_port.unwrap_or(default.prom_port),
473 skip_migration_consistency_check: skip_migration_consistency_check
474 .unwrap_or(default.skip_migration_consistency_check),
475 max_available_range: max_available_range.unwrap_or(default.max_available_range),
476 }
477 }
478
479 pub fn ci_integration_test_cfg() -> Self {
480 Self {
481 db_url: "postgres://postgres:postgrespw@localhost:5432/iota_graphql_rpc_e2e_tests"
482 .to_string()
483 .into(),
484 ..Default::default()
485 }
486 }
487
488 pub fn ci_integration_test_cfg_with_db_name(
489 db_name: String,
490 port: u16,
491 prom_port: u16,
492 ) -> Self {
493 Self {
494 db_url: format!("postgres://postgres:postgrespw@localhost:5432/{db_name}").into(),
495 port,
496 prom_port,
497 ..Default::default()
498 }
499 }
500
501 pub fn db_name(&self) -> String {
502 self.db_url
503 .as_str()
504 .split('/')
505 .next_back()
506 .unwrap()
507 .to_string()
508 }
509
510 pub fn db_url(&self) -> String {
511 self.db_url.as_str().to_string()
512 }
513
514 pub fn db_pool_size(&self) -> u32 {
515 self.db_pool_size
516 }
517
518 pub fn server_address(&self) -> String {
519 format!("{}:{}", self.host, self.port)
520 }
521}
522
523impl ServiceConfig {
524 pub fn read(contents: &str) -> Result<Self, toml::de::Error> {
525 toml::de::from_str::<Self>(contents)
526 }
527
528 pub fn test_defaults() -> Self {
529 Self {
530 background_tasks: BackgroundTasksConfig::test_defaults(),
531 ..Default::default()
532 }
533 }
534}
535
536impl Limits {
537 pub fn package_resolver_limits(&self) -> iota_package_resolver::Limits {
539 iota_package_resolver::Limits {
540 max_type_argument_depth: self.max_type_argument_depth as usize,
541 max_type_argument_width: self.max_type_argument_width as usize,
542 max_type_nodes: self.max_type_nodes as usize,
543 max_move_value_depth: self.max_move_value_depth as usize,
544 max_type_resolution_work: self.max_type_resolution_work as usize,
545 }
546 }
547}
548
549impl BackgroundTasksConfig {
550 pub fn test_defaults() -> Self {
551 Self {
552 watermark_update_ms: 100, }
554 }
555}
556
557impl Default for Versions {
558 fn default() -> Self {
559 Self {
560 versions: vec![format!(
561 "{}.{}",
562 env!("CARGO_PKG_VERSION_MAJOR"),
563 env!("CARGO_PKG_VERSION_MINOR")
564 )],
565 }
566 }
567}
568
569impl Default for Ide {
570 fn default() -> Self {
571 Self {
572 ide_title: "IOTA GraphQL IDE".to_string(),
573 }
574 }
575}
576
577impl Default for ConnectionConfig {
578 fn default() -> Self {
579 Self {
580 port: 8000,
581 host: "127.0.0.1".to_string(),
582 db_url: DEFAULT_DB_URL.to_string().into(),
583 db_pool_size: 10,
584 prom_host: "0.0.0.0".to_string(),
585 prom_port: 9184,
586 skip_migration_consistency_check: false,
587 max_available_range: 9_000,
588 }
589 }
590}
591
592impl Default for Limits {
593 fn default() -> Self {
594 Self {
597 max_query_depth: 20,
598 max_query_nodes: 300,
599 max_output_nodes: 100_000,
600 max_introspection_output_nodes: 25_000,
601 max_query_payload_size: 5_000,
602 max_db_query_cost: 20_000,
603 default_page_size: DEFAULT_PAGE_SIZE,
604 max_page_size: MAX_PAGE_SIZE,
605 mutation_timeout_ms: 74_000,
610 request_timeout_ms: 40_000,
611 max_type_argument_depth: 16,
614 max_type_argument_width: 32,
616 max_type_nodes: 256,
618 max_move_value_depth: 128,
620 max_type_resolution_work: iota_package_resolver::DEFAULT_MAX_TYPE_RESOLUTION_WORK
621 as u32,
622 max_transaction_ids: 1000,
625 max_tx_payload_size: (128u32 * 1024u32 * 4u32).div_ceil(3),
630 max_subscription_recovery_checkpoints: NonZeroU32::new(20_000)
631 .expect("value must be non zero"),
632 max_active_subscriptions: NonZeroU32::new(1000).expect("value must be non zero"),
633 }
634 }
635}
636
637impl Default for InternalFeatureConfig {
638 fn default() -> Self {
639 Self {
640 query_limits_checker: true,
641 directive_checker: true,
642 feature_gate: true,
643 logger: true,
644 query_timeout: true,
645 metrics: true,
646 tracing: false,
647 apollo_tracing: false,
648 open_telemetry: false,
649 }
650 }
651}
652
653impl Default for BackgroundTasksConfig {
654 fn default() -> Self {
655 Self {
656 watermark_update_ms: 500,
657 }
658 }
659}
660
661impl Display for Version {
662 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
663 write!(f, "{}", self.full)
664 }
665}
666
667#[cfg(test)]
668mod tests {
669 use super::*;
670
671 #[test]
672 fn test_read_empty_service_config() {
673 let actual = ServiceConfig::read("").unwrap();
674 let expect = ServiceConfig::default();
675 assert_eq!(actual, expect);
676 }
677
678 #[test]
679 fn test_read_limits_in_service_config() {
680 let actual = ServiceConfig::read(
681 r#" [limits]
682 max-query-depth = 100
683 max-query-nodes = 300
684 max-output-nodes = 200000
685 max-introspection-output-nodes = 50000
686 max-tx-payload-size = 174763
687 max-query-payload-size = 2000
688 max-db-query-cost = 50
689 default-page-size = 20
690 max-page-size = 50
691 mutation-timeout-ms = 74000
692 request-timeout-ms = 27000
693 max-type-argument-depth = 32
694 max-type-argument-width = 64
695 max-type-nodes = 128
696 max-move-value-depth = 256
697 max-type-resolution-work = 5000
698 max-transaction-ids = 11
699 max-subscription-recovery-checkpoints = 500
700 max-active-subscriptions = 20
701 "#,
702 )
703 .unwrap();
704
705 let expect = ServiceConfig {
706 limits: Limits {
707 max_query_depth: 100,
708 max_query_nodes: 300,
709 max_output_nodes: 200000,
710 max_introspection_output_nodes: 50000,
711 max_tx_payload_size: 174763,
712 max_query_payload_size: 2000,
713 max_db_query_cost: 50,
714 default_page_size: 20,
715 max_page_size: 50,
716 mutation_timeout_ms: 74_000,
717 request_timeout_ms: 27_000,
718 max_type_argument_depth: 32,
719 max_type_argument_width: 64,
720 max_type_nodes: 128,
721 max_move_value_depth: 256,
722 max_type_resolution_work: 5000,
723 max_transaction_ids: 11,
724 max_subscription_recovery_checkpoints: NonZeroU32::new(500).unwrap(),
725 max_active_subscriptions: NonZeroU32::new(20).unwrap(),
726 },
727 ..Default::default()
728 };
729
730 assert_eq!(actual, expect)
731 }
732
733 #[test]
734 fn test_read_enabled_features_in_service_config() {
735 let actual = ServiceConfig::read(
736 r#" disabled-features = [
737 "coins",
738 ]
739 "#,
740 )
741 .unwrap();
742
743 use FunctionalGroup as G;
744 let expect = ServiceConfig {
745 disabled_features: BTreeSet::from([G::Coins]),
746 ..Default::default()
747 };
748
749 assert_eq!(actual, expect)
750 }
751
752 #[test]
753 fn test_read_experiments_in_service_config() {
754 let actual = ServiceConfig::read(
755 r#" [experiments]
756 test-flag = true
757 "#,
758 )
759 .unwrap();
760
761 let expect = ServiceConfig {
762 experiments: Experiments { test_flag: true },
763 ..Default::default()
764 };
765
766 assert_eq!(actual, expect)
767 }
768
769 #[test]
770 fn test_read_everything_in_service_config() {
771 let actual = ServiceConfig::read(
772 r#" disabled-features = ["analytics"]
773
774 [limits]
775 max-query-depth = 42
776 max-query-nodes = 320
777 max-output-nodes = 200000
778 max-introspection-output-nodes = 40000
779 max-tx-payload-size = 181017
780 max-query-payload-size = 200
781 max-db-query-cost = 20
782 default-page-size = 10
783 max-page-size = 20
784 mutation-timeout-ms = 74000
785 request-timeout-ms = 30000
786 max-type-argument-depth = 32
787 max-type-argument-width = 64
788 max-type-nodes = 128
789 max-move-value-depth = 256
790 max-type-resolution-work = 4200
791 max-transaction-ids = 42
792 max-subscription-recovery-checkpoints = 4200
793 max-active-subscriptions = 42
794
795 [experiments]
796 test-flag = true
797 "#,
798 )
799 .unwrap();
800
801 let expect = ServiceConfig {
802 limits: Limits {
803 max_query_depth: 42,
804 max_query_nodes: 320,
805 max_output_nodes: 200000,
806 max_introspection_output_nodes: 40000,
807 max_tx_payload_size: 181017,
808 max_query_payload_size: 200,
809 max_db_query_cost: 20,
810 default_page_size: 10,
811 max_page_size: 20,
812 mutation_timeout_ms: 74_000,
813 request_timeout_ms: 30_000,
814 max_type_argument_depth: 32,
815 max_type_argument_width: 64,
816 max_type_nodes: 128,
817 max_move_value_depth: 256,
818 max_type_resolution_work: 4200,
819 max_transaction_ids: 42,
820 max_subscription_recovery_checkpoints: NonZeroU32::new(4200).unwrap(),
821 max_active_subscriptions: NonZeroU32::new(42).unwrap(),
822 },
823 disabled_features: BTreeSet::from([FunctionalGroup::Analytics]),
824 experiments: Experiments { test_flag: true },
825 ..Default::default()
826 };
827
828 assert_eq!(actual, expect);
829 }
830
831 #[test]
832 fn test_read_partial_in_service_config() {
833 let actual = ServiceConfig::read(
834 r#" disabled-features = ["analytics"]
835
836 [limits]
837 max-query-depth = 42
838 max-query-nodes = 320
839 "#,
840 )
841 .unwrap();
842
843 let expect = ServiceConfig {
846 limits: Limits {
847 max_query_depth: 42,
848 max_query_nodes: 320,
849 ..Default::default()
850 },
851 disabled_features: BTreeSet::from([FunctionalGroup::Analytics]),
852 ..Default::default()
853 };
854
855 assert_eq!(actual, expect);
856 }
857
858 #[test]
859 fn test_server_config_debug_hides_db_password() {
860 let config = ServerConfig {
861 connection: ConnectionConfig {
862 db_url: "postgres://user:hunter2@localhost:5432/iota_indexer"
863 .to_string()
864 .into(),
865 ..Default::default()
866 },
867 ..Default::default()
868 };
869
870 let printed = format!("{config:#?}");
871 assert!(!printed.contains("hunter2"), "{printed}");
872 assert!(printed.contains("****"), "{printed}");
873 }
874}