Skip to main content

iota_graphql_rpc/
config.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use 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/// The combination of all configurations for the GraphQL service.
22#[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/// Configuration for connections for the RPC, passed in as command-line
34/// arguments. This configures specific connections between this service and
35/// other services, and might differ from instance to instance of the GraphQL
36/// service.
37#[GraphQLConfig]
38#[derive(clap::Args, Clone, Eq, PartialEq)]
39pub struct ConnectionConfig {
40    /// Port to bind the server to
41    #[arg(short, long, default_value_t = ConnectionConfig::default().port)]
42    pub port: u16,
43    /// Host to bind the server to
44    #[arg(long, default_value_t = ConnectionConfig::default().host)]
45    pub host: String,
46    /// DB URL for data fetching
47    #[arg(short, long, default_value = DEFAULT_DB_URL)]
48    pub db_url: DbUrl,
49    /// Pool size for DB connections
50    #[arg(long, default_value_t = ConnectionConfig::default().db_pool_size)]
51    pub db_pool_size: u32,
52    /// Host to bind the prom server to
53    #[arg(long, default_value_t = ConnectionConfig::default().prom_host)]
54    pub prom_host: String,
55    /// Port to bind the prom server to
56    #[arg(long, default_value_t = ConnectionConfig::default().prom_port)]
57    pub prom_port: u16,
58    /// Skip checking whether the service is compatible with the DB it is about
59    /// to connect to, on start-up.
60    #[arg(long, default_value_t = ConnectionConfig::default().skip_migration_consistency_check)]
61    pub skip_migration_consistency_check: bool,
62    /// Maximum number of checkpoints to look back for consistent view queries.
63    /// Directly influences the `availableRange` size. Larger values let
64    /// pagination cursors stay valid for longer, downside is that older cursors
65    /// have higher DB cost.
66    #[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/// CLI options that control the archival fallback used when Postgres data has
75/// been pruned.
76#[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/// Configuration on features supported by the GraphQL service, passed in a
138/// TOML-based file. These configurations are shared across fleets of the
139/// service, i.e. all testnet services will have the same `ServiceConfig`.
140#[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    /// Maximum depth of nodes in the requests.
159    pub max_query_depth: u32,
160    /// Maximum number of nodes in the requests.
161    pub max_query_nodes: u32,
162    /// Maximum number of output nodes allowed in the response.
163    pub max_output_nodes: u32,
164    /// Maximum number of introspection fields and list items allowed in the
165    /// response.
166    pub max_introspection_output_nodes: u32,
167    /// Maximum size in bytes allowed for the `txBytes` and `signatures` fields
168    /// of a GraphQL mutation request in the `executeTransactionBlock` node,
169    /// and for the `txBytes` of a `dryRunTransactionBlock` node.
170    pub max_tx_payload_size: u32,
171    /// Maximum size in bytes of the JSON payload of a GraphQL read request
172    /// (excluding `max_tx_payload_size`).
173    pub max_query_payload_size: u32,
174    /// Queries whose EXPLAIN cost are more than this will be logged. Given in
175    /// the units used by the database (where 1.0 is roughly the cost of a
176    /// sequential page access).
177    pub max_db_query_cost: u32,
178    /// Paginated queries will return this many elements if a page size is not
179    /// provided.
180    pub default_page_size: u32,
181    /// Paginated queries can return at most this many elements.
182    pub max_page_size: u32,
183    /// Time (in milliseconds) to wait for a transaction to be executed and the
184    /// results returned from GraphQL. If the transaction takes longer than
185    /// this time to execute, the request will return a timeout error, but
186    /// the transaction may continue executing.
187    pub mutation_timeout_ms: u32,
188    /// Time (in milliseconds) to wait for a read request from the GraphQL
189    /// service. Requests that take longer than this time to return a result
190    /// will return a timeout error.
191    pub request_timeout_ms: u32,
192    /// Maximum amount of nesting among type arguments (type arguments nest when
193    /// a type argument is itself generic and has arguments).
194    pub max_type_argument_depth: u32,
195    /// Maximum number of type parameters a type can have.
196    pub max_type_argument_width: u32,
197    /// Maximum number of datatypes processed and nodes in each type tag during resolution.
198    pub max_type_nodes: u32,
199    /// Maximum deph of a move value.
200    pub max_move_value_depth: u32,
201    /// Maximum cumulative number of layout and type-tag nodes constructed or
202    /// copied.
203    pub max_type_resolution_work: u32,
204    /// Maximum number of transaction ids that can be passed to a
205    /// `TransactionBlockFilter` or to `transactions_by_digests`.
206    pub max_transaction_ids: u32,
207    /// Maximum number of checkpoints a subscription may replay from the
208    /// database when resuming from `startAfter`, measured as the difference
209    /// between the sequence number of the latest indexed checkpoint and that
210    /// of the checkpoint containing the `startAfter` digest. A digest further
211    /// behind is rejected.
212    pub max_subscription_recovery_checkpoints: NonZeroU32,
213    /// Maximum number of subscriptions that may be active at the same time
214    /// across all connections.
215    pub max_active_subscriptions: NonZeroU32,
216}
217
218#[GraphQLConfig]
219#[derive(Copy)]
220pub struct BackgroundTasksConfig {
221    /// How often the watermark task checks the indexer database to update the
222    /// checkpoint and epoch watermarks.
223    pub watermark_update_ms: u64,
224}
225
226/// The Version of the service. `year.month` represents the major release.
227/// New `patch` versions represent backwards compatible fixes for their major
228/// release. The `full` version is `year.month.patch-sha`.
229#[derive(Copy, Clone, Debug)]
230pub struct Version {
231    /// The year of this release.
232    pub year: &'static str,
233    /// The month of this release.
234    pub month: &'static str,
235    /// The patch is a positive number incremented for every compatible release
236    /// on top of the major.month release.
237    pub patch: &'static str,
238    /// The commit sha for this release.
239    pub sha: &'static str,
240    /// The full version string.
241    /// Note that this extra field is used only for the uptime_metric function
242    /// which requires a &'static str.
243    pub full: &'static str,
244}
245
246impl Version {
247    /// Use for testing when you need the Version obj and a year.month &str
248    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            // note that this full field is needed for metrics but not for testing
255            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    /// The title to display at the top of the web-based GraphiQL IDE.
271    #[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    // Add experimental flags here, to provide access to them through-out the GraphQL
279    // implementation.
280    #[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    /// RPC URL for the fullnode to send transactions to execute and dry-run.
301    #[arg(long)]
302    pub(crate) node_rpc_url: Option<String>,
303}
304
305/// The enabled features and service limits configured by the server.
306#[Object]
307impl ServiceConfig {
308    /// Check whether `feature` is enabled on this GraphQL service.
309    async fn is_enabled(&self, feature: FunctionalGroup) -> bool {
310        !self.disabled_features.contains(&feature)
311    }
312
313    /// List the available versions for this GraphQL service.
314    async fn available_versions(&self) -> Vec<String> {
315        self.versions.versions.clone()
316    }
317
318    /// List of all features that are enabled on this GraphQL service.
319    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    /// The maximum depth a GraphQL query can be to be accepted by this service.
328    pub async fn max_query_depth(&self) -> Result<i32> {
329        try_into_int(self.limits.max_query_depth).extend()
330    }
331
332    /// The maximum number of nodes (field names) the service will accept in a
333    /// single query.
334    pub async fn max_query_nodes(&self) -> Result<i32> {
335        try_into_int(self.limits.max_query_nodes).extend()
336    }
337
338    /// The maximum number of output nodes in a GraphQL response.
339    ///
340    /// Non-connection nodes have a count of 1, while connection nodes are
341    /// counted as the specified 'first' or 'last' number of items, or the
342    /// default_page_size as set by the server if those arguments are not
343    /// set.
344    ///
345    /// Counts accumulate multiplicatively down the query tree. For example, if
346    /// a query starts with a connection of first: 10 and has a field to a
347    /// connection with last: 20, the count at the second level would be 200
348    /// nodes. This is then summed to the count of 10 nodes at the first
349    /// level, for a total of 210 nodes.
350    pub async fn max_output_nodes(&self) -> Result<i32> {
351        try_into_int(self.limits.max_output_nodes).extend()
352    }
353
354    /// The maximum number of introspection fields and list items in a GraphQL
355    /// response.
356    ///
357    /// The service counts each field and each list item of `__schema` and
358    /// `__type` as it resolves them, and fails the request above this limit.
359    pub async fn max_introspection_output_nodes(&self) -> Result<i32> {
360        try_into_int(self.limits.max_introspection_output_nodes).extend()
361    }
362
363    /// Maximum estimated cost of a database query used to serve a GraphQL
364    /// request.  This is measured in the same units that the database uses
365    /// in EXPLAIN queries.
366    async fn max_db_query_cost(&self) -> Result<i32> {
367        try_into_int(self.limits.max_db_query_cost).extend()
368    }
369
370    /// Default number of elements allowed on a single page of a connection.
371    async fn default_page_size(&self) -> Result<i32> {
372        try_into_int(self.limits.default_page_size).extend()
373    }
374
375    /// Maximum number of elements allowed on a single page of a connection.
376    async fn max_page_size(&self) -> Result<i32> {
377        try_into_int(self.limits.max_page_size).extend()
378    }
379
380    /// Maximum time in milliseconds spent waiting for a response from fullnode
381    /// after issuing a transaction to execute. Note that the transaction
382    /// may still succeed even in the case of a timeout. Transactions are
383    /// idempotent, so a transaction that times out should be resubmitted
384    /// until the network returns a definite response (success or failure, not
385    /// timeout).
386    async fn mutation_timeout_ms(&self) -> Result<i32> {
387        try_into_int(self.limits.mutation_timeout_ms).extend()
388    }
389
390    /// Maximum time in milliseconds that will be spent to serve one query
391    /// request.
392    async fn request_timeout_ms(&self) -> Result<i32> {
393        try_into_int(self.limits.request_timeout_ms).extend()
394    }
395
396    /// The maximum bytes allowed for transactions in queries.
397    ///
398    /// This corresponds to the `txBytes` and `signatures` fields of the GraphQL
399    /// mutation `executeTransactionBlock` node, or the `txBytes` of a
400    /// `dryRunTransactionBlock`.
401    ///
402    /// By default, this is set to the value of the maximum transaction bytes
403    /// (including the signatures) allowed by the protocol, plus the Base64
404    /// overhead (roughly 1/3 of the original string).
405    async fn max_transaction_payload_size(&self) -> Result<i32> {
406        try_into_int(self.limits.max_tx_payload_size).extend()
407    }
408
409    /// The maximum bytes allowed for the read part of GraphQL queries.
410    ///
411    /// In case of mutations or `dryRunTransactionBlocks` the `txBytes` and
412    /// `signatures` are not included in this limit.
413    async fn max_query_payload_size(&self) -> Result<i32> {
414        try_into_int(self.limits.max_query_payload_size).extend()
415    }
416
417    /// Maximum nesting allowed in type arguments in Move Types resolved by this
418    /// service.
419    async fn max_type_argument_depth(&self) -> Result<i32> {
420        try_into_int(self.limits.max_type_argument_depth).extend()
421    }
422
423    /// Maximum number of type arguments passed into a generic instantiation of
424    /// a Move Type resolved by this service.
425    async fn max_type_argument_width(&self) -> Result<i32> {
426        try_into_int(self.limits.max_type_argument_width).extend()
427    }
428
429    /// Maximum number of datatypes processed and nodes in each type tag during
430    /// resolution.
431    async fn max_type_nodes(&self) -> Result<i32> {
432        try_into_int(self.limits.max_type_nodes).extend()
433    }
434
435    /// Maximum nesting allowed in struct fields when calculating the layout of
436    /// a single Move Type.
437    async fn max_move_value_depth(&self) -> Result<i32> {
438        try_into_int(self.limits.max_move_value_depth).extend()
439    }
440
441    /// Maximum cumulative number of layout and type-tag nodes constructed or
442    /// copied.
443    async fn max_type_resolution_work(&self) -> Result<i32> {
444        try_into_int(self.limits.max_type_resolution_work).extend()
445    }
446
447    /// Maximum number of transaction ids that can be passed to a
448    /// `TransactionBlockFilter`.
449    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    /// Extract limits for the package resolver.
538    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, // Set to 100ms for testing
553        }
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        // Picked so that TS SDK shim layer queries all pass limit.
595        // TODO: calculate proper cost limits
596        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            // This default was picked as the sum of pre- and post- quorum timeouts from
606            // [`iota_core::authority_aggregator::TimeoutConfig`], with a 10% buffer.
607            //
608            // <https://github.com/iotaledger/iota/blob/eaf05fe5d293c06e3a2dfc22c87ba2aef419d8ea/crates/iota-core/src/authority_aggregator.rs#L84-L85>
609            mutation_timeout_ms: 74_000,
610            request_timeout_ms: 40_000,
611            // The following limits reflect the max values set in ProtocolConfig, at time of
612            // writing. <https://github.com/iotaledger/iota/blob/333f87061f0656607b1928aba423fa14ca16899e/crates/iota-protocol-config/src/lib.rs#L1580>
613            max_type_argument_depth: 16,
614            // <https://github.com/iotaledger/iota/blob/4b934f87acae862cecbcbefb3da34cabb79805aa/crates/iota-protocol-config/src/lib.rs#L1618>
615            max_type_argument_width: 32,
616            // <https://github.com/iotaledger/iota/blob/4b934f87acae862cecbcbefb3da34cabb79805aa/crates/iota-protocol-config/src/lib.rs#L1622>
617            max_type_nodes: 256,
618            // <https://github.com/iotaledger/iota/blob/4b934f87acae862cecbcbefb3da34cabb79805aa/crates/iota-protocol-config/src/lib.rs#L1988>
619            max_move_value_depth: 128,
620            max_type_resolution_work: iota_package_resolver::DEFAULT_MAX_TYPE_RESOLUTION_WORK
621                as u32,
622            // Filter-specific limits, such as the number of transaction ids that can be specified
623            // for the `TransactionBlockFilter`.
624            max_transaction_ids: 1000,
625            // Protocol limit for max transaction bytes allowed + base64
626            // overhead (roughly 1/3 of the original string). This is rounded up.
627            //
628            // <https://github.com/iotaledger/iota/blob/29c410ac809dd7c71dbf0237a96f08d72b406e52/crates/iota-protocol-config/src/lib.rs#L1566>
629            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        // When reading partially, the other parts will come from the default
844        // implementation.
845        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}