forked from coinbase/chainstorage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
1275 lines (1063 loc) · 42 KB
/
config.go
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
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package config
import (
"bytes"
"encoding/json"
"fmt"
"io"
"math"
"os"
"reflect"
"runtime"
"strconv"
"strings"
"time"
"github.com/go-playground/validator/v10"
"github.com/mitchellh/mapstructure"
"github.com/spf13/viper"
"golang.org/x/xerrors"
"github.com/coinbase/chainstorage/config"
"github.com/coinbase/chainstorage/internal/utils/utils"
"github.com/coinbase/chainstorage/protos/coinbase/c3/common"
api "github.com/coinbase/chainstorage/protos/coinbase/chainstorage"
)
type (
Config struct {
ConfigName string `mapstructure:"config_name" validate:"required"`
StorageType StorageType `mapstructure:"storage_type"`
Chain ChainConfig `mapstructure:"chain"`
AWS AwsConfig `mapstructure:"aws"`
GCP *GcpConfig `mapstructure:"gcp"`
Cadence CadenceConfig `mapstructure:"cadence"`
Workflows WorkflowsConfig `mapstructure:"workflows"`
Api ApiConfig `mapstructure:"api"`
SDK SDKConfig `mapstructure:"sdk"`
Server ServerConfig `mapstructure:"server"`
Cron CronConfig `mapstructure:"cron"`
SLA SLAConfig `mapstructure:"sla"`
FunctionalTest FunctionalTestConfig `mapstructure:"functional_test"`
StatsD *StatsDConfig `mapstructure:"statsd"`
namespace string
env Env
}
StorageType struct {
BlobStorageType BlobStorageType `mapstructure:"blob"`
MetaStorageType MetaStorageType `mapstructure:"meta"`
DLQType DLQType `mapstructure:"dlq"`
}
BlobStorageType int32
MetaStorageType int32
DLQType int32
ChainConfig struct {
Blockchain common.Blockchain `mapstructure:"blockchain" validate:"required"`
Network common.Network `mapstructure:"network" validate:"required"`
Sidechain api.SideChain `mapstructure:"sidechain"`
BlockTag BlockTagConfig `mapstructure:"block_tag"`
EventTag EventTagConfig `mapstructure:"event_tag"`
Client ClientConfig `mapstructure:"client"`
Feature FeatureConfig `mapstructure:"feature"`
BlockStartHeight uint64 `mapstructure:"block_start_height"`
// IrreversibleDistance is the maximum distance between the current block height and the last irreversible block height, also
// known as the max reorg distance, finalization depth. This does not have a default value and must be set by the onboarding user.
IrreversibleDistance uint64 `mapstructure:"irreversible_distance" validate:"required"`
Rosetta RosettaConfig `mapstructure:"rosetta"`
BlockTime time.Duration `mapstructure:"block_time" validate:"required"`
}
ClientConfig struct {
Master JSONRPCConfig `mapstructure:"master"`
Slave JSONRPCConfig `mapstructure:"slave"`
Validator JSONRPCConfig `mapstructure:"validator"`
Consensus JSONRPCConfig `mapstructure:"consensus"`
Retry ClientRetryConfig `mapstructure:"retry"`
HttpTimeout time.Duration `mapstructure:"http_timeout"`
}
JSONRPCConfig struct {
EndpointGroup EndpointGroup `mapstructure:"endpoint_group"`
}
ClientRetryConfig struct {
MaxAttempts int `mapstructure:"max_attempts"`
}
FeatureConfig struct {
RosettaParser bool `mapstructure:"rosetta_parser"`
DefaultStableEvent bool `mapstructure:"default_stable_event"`
TransactionIndexing bool `mapstructure:"transaction_indexing"`
BlockValidationEnabled bool `mapstructure:"block_validation_enabled"`
BlockValidationMuted bool `mapstructure:"block_validation_muted"`
VerifiedAccountStateEnabled bool `mapstructure:"verified_account_state_enabled"`
}
BlockTagConfig struct {
Stable uint32 `mapstructure:"stable"`
Latest uint32 `mapstructure:"latest"`
}
EventTagConfig struct {
Stable uint32 `mapstructure:"stable"`
Latest uint32 `mapstructure:"latest"`
}
AccountConfig struct {
User string `json:"user"`
Password string `json:"password"`
Role string `json:"role"`
}
AwsConfig struct {
Region string `mapstructure:"region" validate:"required"`
Bucket string `mapstructure:"bucket" validate:"required"`
DynamoDB DynamoDBConfig `mapstructure:"dynamodb" validate:"required"`
IsLocalStack bool `mapstructure:"local_stack"`
IsResetLocal bool `mapstructure:"reset_local"`
PresignedUrlExpiration time.Duration `mapstructure:"presigned_url_expiration" validate:"required"`
DLQ SQSConfig `mapstructure:"dlq"`
Storage StorageConfig `mapstructure:"storage"`
AWSAccount AWSAccount `mapstructure:"aws_account" validate:"required"`
}
GcpConfig struct {
Project string `mapstructure:"project" validate:"required"`
Bucket string `mapstructure:"bucket"`
PresignedUrlExpiration time.Duration `mapstructure:"presigned_url_expiration" validate:"required"`
}
DynamoDBConfig struct {
BlockTable string `mapstructure:"block_table" validate:"required"`
EventTable string `mapstructure:"event_table"`
EventTableHeightIndex string `mapstructure:"event_table_height_index"`
VersionedEventTable string `mapstructure:"versioned_event_table" validate:"required"`
VersionedEventTableBlockIndex string `mapstructure:"versioned_event_table_block_index" validate:"required"`
TransactionTable string `mapstructure:"transaction_table"`
Arn string `mapstructure:"arn"`
}
SQSConfig struct {
Name string `mapstructure:"name" validate:"required"`
VisibilityTimeoutSecs int64 `mapstructure:"visibility_timeout_secs"`
DelaySecs int64 `mapstructure:"delay_secs"`
OwnerAccountId string `mapstructure:"owner_account_id"`
}
CadenceConfig struct {
Address string `mapstructure:"address" validate:"required"`
Domain string `mapstructure:"domain" validate:"required"`
RetentionPeriod int32 `mapstructure:"retention_period" validate:"required"`
TLSConfig CadenceTLSConfig `mapstructure:"tls" validate:"required"`
}
CadenceTLSConfig struct {
Enabled bool `mapstructure:"enabled"`
ValidateHostname bool `mapstructure:"validate_hostname"`
CertificateAuthority string `mapstructure:"certificate_authority"`
ClientCertificate string `mapstructure:"client_certificate"`
ClientPrivateKey string `mapstructure:"client_private_key"`
}
WorkflowsConfig struct {
Workers []WorkerConfig `mapstructure:"workers"`
Backfiller BackfillerWorkflowConfig `mapstructure:"backfiller"`
Poller PollerWorkflowConfig `mapstructure:"poller"`
Benchmarker BenchmarkerWorkflowConfig `mapstructure:"benchmarker"`
Monitor MonitorWorkflowConfig `mapstructure:"monitor"`
Streamer StreamerWorkflowConfig `mapstructure:"streamer"`
CrossValidator CrossValidatorWorkflowConfig `mapstructure:"cross_validator"`
EventBackfiller EventBackfillerWorkflowConfig `mapstructure:"event_backfiller"`
}
WorkerConfig struct {
TaskList string `mapstructure:"task_list"`
}
WorkflowConfig struct {
WorkflowIdentity string `mapstructure:"workflow_identity" validate:"required"`
Enabled bool `mapstructure:"enabled"`
TaskList string `mapstructure:"task_list" validate:"required"`
WorkflowDecisionTimeout time.Duration `mapstructure:"workflow_decision_timeout" validate:"required"`
WorkflowExecutionTimeout time.Duration `mapstructure:"workflow_execution_timeout" validate:"required"`
ActivityScheduleToStartTimeout time.Duration `mapstructure:"activity_schedule_to_start_timeout" validate:"required"`
ActivityStartToCloseTimeout time.Duration `mapstructure:"activity_start_to_close_timeout" validate:"required"`
ActivityHeartbeatTimeout time.Duration `mapstructure:"activity_heartbeat_timeout"`
ActivityRetryMaximumAttempts int32 `mapstructure:"activity_retry_maximum_attempts" validate:"required"`
BlockTag BlockTagConfig `mapstructure:"block_tag"`
EventTag EventTagConfig `mapstructure:"event_tag"`
Storage StorageConfig `mapstructure:"storage"`
IrreversibleDistance uint64 `mapstructure:"irreversible_distance" validate:"required"`
FailoverEnabled bool `mapstructure:"failover_enabled"`
ConsensusFailoverEnabled bool `mapstructure:"consensus_failover_enabled"`
SLA SLAConfig `mapstructure:"sla"`
}
BackfillerWorkflowConfig struct {
WorkflowConfig `mapstructure:",squash"`
BatchSize uint64 `mapstructure:"batch_size" validate:"required"`
MiniBatchSize uint64 `mapstructure:"mini_batch_size" validate:"required"`
CheckpointSize uint64 `mapstructure:"checkpoint_size" validate:"required,gtfield=BatchSize"`
MaxReprocessedPerBatch uint64 `mapstructure:"max_reprocessed_per_batch"`
NumConcurrentExtractors int `mapstructure:"num_concurrent_extractors" validate:"required"`
}
EventBackfillerWorkflowConfig struct {
WorkflowConfig `mapstructure:",squash"`
BatchSize uint64 `mapstructure:"batch_size" validate:"required"`
CheckpointSize uint64 `mapstructure:"checkpoint_size" validate:"required,gtfield=BatchSize"`
}
PollerWorkflowConfig struct {
WorkflowConfig `mapstructure:",squash"`
MaxBlocksToSyncPerCycle uint64 `mapstructure:"max_blocks_to_sync_per_cycle" validate:"required"`
CheckpointSize uint64 `mapstructure:"checkpoint_size" validate:"required"`
BackoffInterval time.Duration `mapstructure:"backoff_interval"`
Parallelism int `mapstructure:"parallelism" validate:"required"`
SessionCreationTimeout time.Duration `mapstructure:"session_creation_timeout" validate:"required"`
SessionEnabled bool `mapstructure:"session_enabled"`
FastSync bool `mapstructure:"fast_sync"`
NumBlocksToSkip uint64 `mapstructure:"num_blocks_to_skip"`
TransactionsWriteParallelism int `mapstructure:"transactions_write_parallelism"`
ConsensusValidation bool `mapstructure:"consensus_validation"`
ConsensusValidationMuted bool `mapstructure:"consensus_validation_muted"`
LivenessCheckEnabled bool `mapstructure:"liveness_check_enabled"`
// LivenessCheckViolationLimit is threshold for liveness check violations before poller failover is triggered.
// time to trigger failover = LivenessCheckInterval * LivenessCheckViolationLimit
LivenessCheckViolationLimit uint64 `mapstructure:"liveness_check_violation_limit"`
// LivenessCheckInterval is the interval between liveness checks.
LivenessCheckInterval time.Duration `mapstructure:"liveness_check_interval"`
}
BenchmarkerWorkflowConfig struct {
WorkflowConfig `mapstructure:",squash"`
ChildWorkflowExecutionStartToCloseTimeout time.Duration `mapstructure:"child_workflow_execution_start_to_close_timeout" validate:"required"`
}
MonitorWorkflowConfig struct {
WorkflowConfig `mapstructure:",squash"`
BatchSize uint64 `mapstructure:"batch_size" validate:"required"`
CheckpointSize uint64 `mapstructure:"checkpoint_size" validate:"required"`
BackoffInterval time.Duration `mapstructure:"backoff_interval"`
Parallelism int `mapstructure:"parallelism" validate:"required,gt=0"`
BlockGapLimit uint64 `mapstructure:"block_gap_limit" validate:"required"`
EventGapLimit int64 `mapstructure:"event_gap_limit" validate:"required"`
}
CrossValidatorWorkflowConfig struct {
WorkflowConfig `mapstructure:",squash"`
BatchSize uint64 `mapstructure:"batch_size" validate:"required"`
CheckpointSize uint64 `mapstructure:"checkpoint_size" validate:"required"`
BackoffInterval time.Duration `mapstructure:"backoff_interval"`
Parallelism int `mapstructure:"parallelism" validate:"required,gt=0"`
ValidationStartHeight uint64 `mapstructure:"validation_start_height"`
ValidationPercentage int `mapstructure:"validation_percentage" validate:"min=0,max=100"`
}
StreamerWorkflowConfig struct {
WorkflowConfig `mapstructure:",squash"`
BatchSize uint64 `mapstructure:"batch_size" validate:"required"`
CheckpointSize uint64 `mapstructure:"checkpoint_size" validate:"required"`
BackoffInterval time.Duration `mapstructure:"backoff_interval"`
}
RosettaConfig struct {
Blockchain string `mapstructure:"blockchain"`
Network string `mapstructure:"network" validate:"required_with=Blockchain"`
BlockNotFoundErrorCodes []int32 `mapstructure:"block_not_found_error_codes"`
EnableRawBlockApi bool `mapstructure:"enable_raw_block_api"`
FromRosetta bool `mapstructure:"from_rosetta"`
}
EndpointGroup struct {
Endpoints []Endpoint `json:"endpoints"`
EndpointsFailover []Endpoint `json:"endpoints_failover"`
UseFailover bool `json:"use_failover"`
EndpointConfig EndpointConfig `json:"endpoint_config"`
EndpointConfigFailover EndpointConfig `json:"endpoint_config_failover"`
}
// endpointGroup must be in sync with EndpointGroup
endpointGroup struct {
Endpoints []Endpoint `json:"endpoints"`
EndpointsFailover []Endpoint `json:"endpoints_failover"`
UseFailover bool `json:"use_failover"`
EndpointConfig EndpointConfig `json:"endpoint_config"`
EndpointConfigFailover EndpointConfig `json:"endpoint_config_failover"`
}
Endpoint struct {
Name string `json:"name"`
ProviderID string `json:"provider_id"`
Url string `json:"url"`
User string `json:"user"`
Password string `json:"password"`
Weight uint8 `json:"weight"`
ExtraUrls map[string]string `json:"extra_urls"`
RPS int `json:"rps"`
}
EndpointConfig struct {
StickySession StickySessionConfig `json:"sticky_session"`
Headers map[string]string `json:"headers"`
}
StickySessionConfig struct {
// The CookieHash method consistently maps a cookie value to a specific node.
CookieHash string `json:"cookie_hash"`
// The CookiePassive method persists the cookie value provided by the server.
CookiePassive bool `json:"cookie_passive"`
// The HeaderHash method consistently maps a header value to a specific node.
HeaderHash string `json:"header_hash"`
}
ApiConfig struct {
MaxNumBlocks uint64 `mapstructure:"max_num_blocks" validate:"required"`
MaxNumBlockFiles uint64 `mapstructure:"max_num_block_files" validate:"required"`
NumWorkers uint64 `mapstructure:"num_workers" validate:"required"`
StreamingInterval time.Duration `mapstructure:"streaming_interval" validate:"required"`
StreamingBatchSize uint64 `mapstructure:"streaming_batch_size" validate:"required"`
StreamingMaxNoEventTime time.Duration `mapstructure:"streaming_max_no_event_time" validate:"required"`
Auth AuthConfig `mapstructure:"auth"`
RateLimit RateLimitConfig `mapstructure:"rate_limit"`
}
SDKConfig struct {
ChainstorageAddress string `mapstructure:"chainstorage_address" validate:"required"`
NumWorkers uint64 `mapstructure:"num_workers" validate:"required"`
Restful bool `mapstructure:"restful"`
AuthHeader string `mapstructure:"auth_header"`
AuthToken string `mapstructure:"auth_token"`
}
ServerConfig struct {
BindAddress string `mapstructure:"bind_address" validate:"required"`
}
CronConfig struct {
BlockRangeSize uint64 `mapstructure:"block_range_size" validate:"required"`
DisableDLQProcessor bool `mapstructure:"disable_dlq_processor"`
DisablePollingCanary bool `mapstructure:"disable_polling_canary"`
DisableStreamingCanary bool `mapstructure:"disable_streaming_canary"`
DisableNodeCanary bool `mapstructure:"disable_node_canary"`
DisableWorkflowStatus bool `mapstructure:"disable_workflow_status"`
}
StorageConfig struct {
DataCompression api.Compression `mapstructure:"data_compression"`
}
SLAConfig struct {
Tier int `mapstructure:"tier" validate:"required"` // 1 for high urgency; 2 for low urgency; 3 for work in progress.
BlockHeightDelta uint64 `mapstructure:"block_height_delta" validate:"required"`
BlockTimeDelta time.Duration `mapstructure:"block_time_delta" validate:"required"`
TimeSinceLastBlock time.Duration `mapstructure:"time_since_last_block" validate:"required"`
EventHeightDelta uint64 `mapstructure:"event_height_delta" validate:"required"`
EventTimeDelta time.Duration `mapstructure:"event_time_delta" validate:"required"`
TimeSinceLastEvent time.Duration `mapstructure:"time_since_last_event" validate:"required"`
OutOfSyncNodeDistance uint64 `mapstructure:"out_of_sync_node_distance" validate:"required"`
OutOfSyncValidatorNodeDistance uint64 `mapstructure:"out_of_sync_validator_node_distance"` // If not set, use OutOfSyncNodeDistance.
ExpectedWorkflows []string `mapstructure:"expected_workflows"`
}
FunctionalTestConfig struct {
SkipFunctionalTest []FunctionalTest `json:"skip_functional_test"`
}
FunctionalTest struct {
ConfigName string `json:"config_name"`
}
AuthConfig struct {
Clients []AuthClient `json:"clients"`
DefaultRPS int `json:"default_rps"`
}
// authConfig must be in sync with AuthConfig.
authConfig struct {
Clients []AuthClient `json:"clients"`
DefaultRPS int `json:"default_rps"`
}
AuthClient struct {
ClientID string `json:"client_id"`
Token string `json:"token"`
RPS int `json:"rps"`
}
RateLimitConfig struct {
GlobalRPS int `mapstructure:"global_rps"`
PerClientRPS int `mapstructure:"per_client_rps"`
}
StatsDConfig struct {
Address string `mapstructure:"address" validate:"required"`
Prefix string `mapstructure:"prefix"`
}
ConfigOption func(options *configOptions)
Env string
AWSAccount string
BaseWorkflowConfig interface {
Base() *WorkflowConfig
}
configOptions struct {
Namespace string `validate:"required"`
Blockchain common.Blockchain `validate:"required"`
Network common.Network `validate:"required"`
Env Env `validate:"required,oneof=production development local"`
Sidechain api.SideChain
}
// derivedConfig defines a callback where a config struct can override its fields based on the global config.
// For example, WorkflowConfig implements this interface to copy the global tag into its own struct.
derivedConfig interface {
DeriveConfig(cfg *Config)
}
)
var (
_ derivedConfig = (*WorkflowConfig)(nil)
_ derivedConfig = (*AwsConfig)(nil)
_ derivedConfig = (*CadenceConfig)(nil)
_ derivedConfig = (*SDKConfig)(nil)
AWSAccountEnvMap = map[AWSAccount]Env{
"": EnvLocal,
AWSAccountDevelopment: EnvDevelopment,
AWSAccountProduction: EnvProduction,
}
AWSAccountShortMap = map[AWSAccount]string{
AWSAccountDevelopment: "dev",
AWSAccountProduction: "prod",
}
BlobStorageType_value = map[string]int32{
"UNSPECIFIED": 0,
"S3": 1,
"GCS": 2,
}
MetaStorageType_value = map[string]int32{
"UNSPECIFIED": 0,
"DYNAMODB": 1,
"FIRESTORE": 2,
}
DLQType_value = map[string]int32{
"UNSPECIFIED": 0,
"SQS": 1,
}
)
const (
EnvVarNamespace = "CHAINSTORAGE_NAMESPACE"
EnvVarConfigName = "CHAINSTORAGE_CONFIG"
EnvVarEnvironment = "CHAINSTORAGE_ENVIRONMENT"
EnvVarConfigRoot = "CHAINSTORAGE_CONFIG_ROOT"
EnvVarConfigPath = "CHAINSTORAGE_CONFIG_PATH"
EnvVarTestType = "TEST_TYPE"
EnvVarCI = "CI"
CurrentFileName = "/internal/config/config.go"
DefaultNamespace = "chainstorage"
DefaultConfigName = "ethereum-mainnet"
EnvBase Env = "base"
EnvLocal Env = "local"
EnvDevelopment Env = "development"
EnvProduction Env = "production"
envSecrets Env = "secrets" // secrets.yml is merged into the env-specific config
BlobStorageType_UNSPECIFIED BlobStorageType = 0
BlobStorageType_S3 BlobStorageType = 1
BlobStorageType_GCS BlobStorageType = 2
MetaStorageType_UNSPECIFIED MetaStorageType = 0
MetaStorageType_DYNAMODB MetaStorageType = 1
MetaStorageType_FIRESTORE MetaStorageType = 2
DLQType_UNSPECIFIED DLQType = 0
DLQType_SQS DLQType = 1
AWSAccountDevelopment AWSAccount = "development"
AWSAccountProduction AWSAccount = "production"
placeholderPassword = "<placeholder>"
tagBlockchain = "blockchain"
tagNetwork = "network"
tagTier = "tier"
s3BucketFormat = "example-chainstorage-%v-%v"
cadenceAddressLocal = "localhost:7233"
chainstorageAddressLocal = "http://localhost:9090"
tagSidechain = "sidechain"
)
func New(opts ...ConfigOption) (*Config, error) {
validate := validator.New()
// Get configname, such as "ethereum-mainnet"
configName := getConfigName()
// Get "blockchain", "network" "env"
configOpts, err := getConfigOptions(configName, opts...)
if err != nil {
return nil, xerrors.Errorf("failed to get config options %w", err)
}
if err := validate.Struct(configOpts); err != nil {
return nil, xerrors.Errorf("failed to validate config options: %w", err)
}
// Get data in base.yml for the target blockchain-network-env
configReader, err := getConfigData(configOpts.Namespace, EnvBase, configOpts.Blockchain, configOpts.Network, configOpts.Sidechain)
if err != nil {
return nil, xerrors.Errorf("failed to locate config file: %w", err)
}
cfg := Config{
namespace: configOpts.Namespace,
env: configOpts.Env,
}
v := viper.New()
// First, read the data in base.yml
v.SetConfigName(string(EnvBase))
v.SetConfigType("yaml")
v.AutomaticEnv()
v.AllowEmptyEnv(true)
// All env set by codeflow has the prefix of CHAINSTORAGE
v.SetEnvPrefix("CHAINSTORAGE")
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
// Set default values.
// Note that the default values may be overridden by environment variable or config file.
if cfg.Env() == EnvLocal {
v.SetDefault("aws.local_stack", true)
}
if cfg.IsTest() {
v.SetDefault("aws.local_stack", true)
v.SetDefault("aws.reset_local", true)
}
// Read the data in base.yml
if err := v.ReadConfig(configReader); err != nil {
return nil, xerrors.Errorf("failed to read config: %w", err)
}
// Merge in the env-specific config, such as development.yml
if err := mergeInConfig(v, configOpts, configOpts.Env); err != nil {
return nil, xerrors.Errorf("failed to merge in %v config: %w", configOpts.Env, err)
}
// Merge in .secrets.yml. Note that this is a no-op for development and production env.
if err := mergeInConfig(v, configOpts, envSecrets); err != nil {
return nil, xerrors.Errorf("failed to merge in %v config: %w", envSecrets, err)
}
if err := v.Unmarshal(&cfg, viper.DecodeHook(mapstructure.ComposeDecodeHookFunc(
mapstructure.TextUnmarshallerHookFunc(),
mapstructure.StringToTimeDurationHookFunc(),
mapstructure.StringToSliceHookFunc(","),
stringToBlobStorageTypeHookFunc(),
stringToMetaStorageTypeHookFunc(),
stringToDLQTypeHookFunc(),
stringToBlockchainHookFunc(),
stringToNetworkHookFunc(),
stringToCompressionHookFunc(),
stringToSidechainHookFunc(),
))); err != nil {
return nil, xerrors.Errorf("failed to unmarshal config: %w", err)
}
cfg.setDerivedConfigs(reflect.ValueOf(&cfg))
if err := validate.Struct(&cfg); err != nil {
return nil, xerrors.Errorf("failed to validate config: %w", err)
}
if cfg.Chain.Blockchain != common.Blockchain_BLOCKCHAIN_ETHEREUM || cfg.Chain.Network != common.Network_NETWORK_ETHEREUM_MAINNET {
// Zero-value blockTag is reserved as an alias of the stable blockTag.
// Other than ethereum/mainnet (whose tags actually started from zero), do not allow zero-value blockTag.
if cfg.Chain.BlockTag.Stable == 0 {
return nil, xerrors.New("stable block tag cannot be zero")
}
if cfg.Chain.BlockTag.Latest == 0 {
return nil, xerrors.New("latest block tag cannot be zero")
}
}
return &cfg, nil
}
func GetEnv() Env {
awsAccount := AWSAccount(os.Getenv(EnvVarEnvironment))
env, ok := AWSAccountEnvMap[awsAccount]
if !ok {
return EnvLocal
}
return env
}
func getConfigName() string {
configName, ok := os.LookupEnv(EnvVarConfigName)
if !ok {
configName = DefaultConfigName
}
return configName
}
func GetConfigRoot() string {
return os.Getenv(EnvVarConfigRoot)
}
func GetConfigPath() string {
return os.Getenv(EnvVarConfigPath)
}
func mergeInConfig(v *viper.Viper, configOpts *configOptions, env Env) error {
// Merge in the env-specific config if available.
if configReader, err := getConfigData(configOpts.Namespace, env, configOpts.Blockchain, configOpts.Network, configOpts.Sidechain); err == nil {
v.SetConfigName(string(env))
if err := v.MergeConfig(configReader); err != nil {
return xerrors.Errorf("failed to merge config %v: %w", env, err)
}
}
return nil
}
func (c *Config) Namespace() string {
return c.namespace
}
func (c *Config) Env() Env {
return c.env
}
func (c *Config) Blockchain() common.Blockchain {
return c.Chain.Blockchain
}
func (c *Config) Network() common.Network {
return c.Chain.Network
}
func (c *Config) Sidechain() api.SideChain {
return c.Chain.Sidechain
}
func (c *Config) Tier() int {
return c.SLA.Tier
}
func (c *Config) GetCommonTags() map[string]string {
return map[string]string{
tagBlockchain: c.Blockchain().GetName(),
tagNetwork: c.Network().GetName(),
tagTier: strconv.Itoa(c.Tier()),
tagSidechain: c.Sidechain().GetName(),
}
}
func (c *Config) AwsEnv() string {
shortEnv := "dev"
if val, exists := AWSAccountShortMap[c.AWS.AWSAccount]; exists {
shortEnv = val
}
return shortEnv
}
func (c *Config) normalizeResourceName(name string) string {
return strings.ReplaceAll(name, "_", "-")
}
func (c *Config) IsTest() bool {
return os.Getenv(EnvVarTestType) != ""
}
func (c *Config) IsIntegrationTest() bool {
return os.Getenv(EnvVarTestType) == "integration"
}
func (c *Config) IsFunctionalTest() bool {
return os.Getenv(EnvVarTestType) == "functional"
}
func (c *Config) IsCI() bool {
return os.Getenv(EnvVarCI) != ""
}
func (c *Config) GetEffectiveBlockTag(tag uint32) uint32 {
return c.Chain.BlockTag.GetEffectiveBlockTag(tag)
}
func (c *Config) GetStableBlockTag() uint32 {
return c.Chain.BlockTag.Stable
}
func (c *Config) GetLatestBlockTag() uint32 {
return c.Chain.BlockTag.Latest
}
func (c *Config) IsRosetta() bool {
return c.Chain.Rosetta.Blockchain != "" && c.Chain.Rosetta.Network != ""
}
// setDerivedConfigs recursively calls DeriveConfig on all the derivedConfig.
func (c *Config) setDerivedConfigs(v reflect.Value) {
if v.CanInterface() {
if oc, ok := v.Interface().(derivedConfig); ok {
oc.DeriveConfig(c)
return
}
}
elem := v.Elem()
for i := 0; i < elem.NumField(); i++ {
field := elem.Field(i)
if field.Kind() == reflect.Struct {
c.setDerivedConfigs(field.Addr())
}
}
}
func (c *Config) GetLatestEventTag() uint32 {
return c.Chain.EventTag.Latest
}
func (c *Config) GetStableEventTag() uint32 {
return c.Chain.EventTag.Stable
}
func (c *Config) GetEffectiveEventTag(eventTag uint32) uint32 {
return c.Chain.EventTag.GetEffectiveEventTag(eventTag)
}
func (c *Config) GetChainMetadataHelper(req *api.GetChainMetadataRequest) (*api.GetChainMetadataResponse, error) {
return &api.GetChainMetadataResponse{
LatestBlockTag: c.GetLatestBlockTag(),
StableBlockTag: c.GetStableBlockTag(),
LatestEventTag: c.GetLatestEventTag(),
StableEventTag: c.GetStableEventTag(),
BlockStartHeight: c.Chain.BlockStartHeight,
IrreversibleDistance: c.Chain.IrreversibleDistance,
BlockTime: c.Chain.BlockTime.String(),
}, nil
}
func WithNamespace(namespace string) ConfigOption {
return func(opts *configOptions) {
opts.Namespace = namespace
}
}
func WithBlockchain(blockchain common.Blockchain) ConfigOption {
return func(opts *configOptions) {
opts.Blockchain = blockchain
}
}
func WithNetwork(network common.Network) ConfigOption {
return func(opts *configOptions) {
opts.Network = network
}
}
func WithSidechain(sidechain api.SideChain) ConfigOption {
return func(opts *configOptions) {
opts.Sidechain = sidechain
}
}
func WithEnvironment(env Env) ConfigOption {
return func(opts *configOptions) {
opts.Env = env
}
}
func getConfigOptions(configName string, opts ...ConfigOption) (*configOptions, error) {
configOpts := &configOptions{}
for _, opt := range opts {
opt(configOpts)
}
if configOpts.Namespace == "" {
namespace := os.Getenv(EnvVarNamespace)
if namespace == "" {
namespace = DefaultNamespace
}
configOpts.Namespace = namespace
}
if configOpts.Env == "" {
configOpts.Env = GetEnv()
}
if configOpts.Blockchain == common.Blockchain_BLOCKCHAIN_UNKNOWN && configOpts.Network == common.Network_NETWORK_UNKNOWN {
blockchain, network, sidechain, err := ParseConfigName(configName)
if err != nil {
return nil, xerrors.Errorf("failed to parse config name: %w", err)
}
configOpts.Blockchain = blockchain
configOpts.Network = network
configOpts.Sidechain = sidechain
}
return configOpts, nil
}
func ParseConfigName(configName string) (common.Blockchain, common.Network, api.SideChain, error) {
// Normalize the config name by replacing "-" with "_".
configName = strings.ReplaceAll(configName, "-", "_")
splitString := strings.Split(configName, "_")
if len(splitString) < 2 || len(splitString) > 3 {
return common.Blockchain_BLOCKCHAIN_UNKNOWN, common.Network_NETWORK_UNKNOWN, api.SideChain_SIDECHAIN_NONE, xerrors.Errorf("config name is invalid: %v", configName)
}
blockchainName := splitString[0]
blockchain, err := utils.ParseBlockchain(blockchainName)
if err != nil {
return common.Blockchain_BLOCKCHAIN_UNKNOWN, common.Network_NETWORK_UNKNOWN, api.SideChain_SIDECHAIN_NONE, xerrors.Errorf("failed to parse blockchain from config name %v: %w", configName, err)
}
networkName := fmt.Sprintf("%v_%v", splitString[0], splitString[1])
network, err := utils.ParseNetwork(networkName)
if err != nil {
return common.Blockchain_BLOCKCHAIN_UNKNOWN, common.Network_NETWORK_UNKNOWN, api.SideChain_SIDECHAIN_NONE, xerrors.Errorf("failed to parse network from config name %v: %w", configName, err)
}
if len(splitString) == 3 {
sidechainName := fmt.Sprintf("%v_%v_%v", splitString[0], splitString[1], splitString[2])
sidechain, err := utils.ParseSidechain(sidechainName)
if err != nil {
return common.Blockchain_BLOCKCHAIN_UNKNOWN, common.Network_NETWORK_UNKNOWN, api.SideChain_SIDECHAIN_NONE, xerrors.Errorf("failed to parse sidechain from config name %v: %w", configName, err)
}
return blockchain, network, sidechain, nil
}
return blockchain, network, api.SideChain_SIDECHAIN_NONE, nil
}
func getConfigData(namespace string, env Env, blockchain common.Blockchain, network common.Network, sidechain api.SideChain) (io.Reader, error) {
blockchainName := blockchain.GetName()
networkName := strings.TrimPrefix(network.GetName(), blockchainName+"-")
sidechainName := strings.TrimPrefix(sidechain.GetName(), blockchainName+"-"+networkName+"-")
configRoot := GetConfigRoot()
if env == envSecrets {
// .secrets.yml is intentionally not embedded in config.Store.
// Read it from the file system instead.
// If configRoot is not set, use the default path.
if len(configRoot) == 0 {
_, filename, _, ok := runtime.Caller(0)
if !ok {
return nil, xerrors.Errorf("failed to recover the filename information")
}
rootDir := strings.TrimSuffix(filename, CurrentFileName)
configRoot = fmt.Sprintf("%v/config", rootDir)
}
configPath := fmt.Sprintf("%v/%v/%v/%v/.secrets.yml", configRoot, namespace, blockchainName, networkName)
if sidechain != api.SideChain_SIDECHAIN_NONE {
configPath = fmt.Sprintf("%v/%v/%v/%v/%v/.secrets.yml", configRoot, namespace, blockchainName, networkName, sidechainName)
}
reader, err := os.Open(configPath)
if err != nil {
return nil, xerrors.Errorf("failed to read config file %v: %w", configPath, err)
}
return reader, nil
}
configPath := GetConfigPath()
// If configPath is not set, try to construct the file system path from configRoot.
if len(configPath) == 0 && len(configRoot) > 0 {
configPath = fmt.Sprintf("%v/%v/%v/%v/%v.yml", configRoot, namespace, blockchainName, networkName, env)
if sidechain != api.SideChain_SIDECHAIN_NONE {
configPath = fmt.Sprintf("%v/%v/%v/%v/%v/%v.yml", configRoot, namespace, blockchainName, networkName, sidechainName, env)
}
}
// If either configRoot or configPath is set, read the config from the file system.
if len(configPath) > 0 {
reader, err := os.Open(configPath)
if err != nil {
return nil, xerrors.Errorf("failed to read config file %v: %w", configPath, err)
}
return reader, nil
}
// Read the config from the embedded config.Store.
configPath = fmt.Sprintf("%v/%v/%v/%v.yml", namespace, blockchainName, networkName, env)
if sidechain != api.SideChain_SIDECHAIN_NONE {
configPath = fmt.Sprintf("%v/%v/%v/%v/%v.yml", namespace, blockchainName, networkName, sidechainName, env)
}
data, err := config.Store.ReadFile(configPath)
if err != nil {
return nil, xerrors.Errorf("failed to read config file %v: %w", configPath, err)
}
return bytes.NewBuffer(data), nil
}
func keysWithoutUnspecified[V interface{}](m map[string]V) []string {
var keys []string
for k := range m {
if k != "UNSPECIFIED" {
keys = append(keys, k)
}
}
return keys
}
func stringToBlobStorageTypeHookFunc() mapstructure.DecodeHookFunc {
return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) {
if f.Kind() != reflect.String {
return data, nil
}
if t != reflect.TypeOf(BlobStorageType_UNSPECIFIED) {
return data, nil
}
v, ok := BlobStorageType_value[data.(string)]
if !ok {
return nil, xerrors.Errorf(
"invalid blob storage type: %v, possible values are: %v",
data, strings.Join(keysWithoutUnspecified(BlobStorageType_value), ", "))
}
return v, nil
}
}
func stringToMetaStorageTypeHookFunc() mapstructure.DecodeHookFunc {
return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) {
if f.Kind() != reflect.String {
return data, nil
}
if t != reflect.TypeOf(MetaStorageType_UNSPECIFIED) {
return data, nil
}
v, ok := MetaStorageType_value[data.(string)]
if !ok {
return nil, xerrors.Errorf(
"invalid blob storage type: %v, possible values are: %v",
data, strings.Join(keysWithoutUnspecified(MetaStorageType_value), ", "))
}
return v, nil
}
}
func stringToDLQTypeHookFunc() mapstructure.DecodeHookFunc {
return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) {
if f.Kind() != reflect.String {
return data, nil
}
if t != reflect.TypeOf(DLQType_UNSPECIFIED) {
return data, nil
}
v, ok := DLQType_value[data.(string)]
if !ok {
return nil, xerrors.Errorf(
"invalid dlq type: %v, possible values are: %v",
data, strings.Join(keysWithoutUnspecified(DLQType_value), ", "))
}
return v, nil
}
}
func stringToBlockchainHookFunc() mapstructure.DecodeHookFunc {
return func(f reflect.Type, t reflect.Type, data any) (any, error) {
if f.Kind() != reflect.String {
return data, nil
}
if t != reflect.TypeOf(common.Blockchain_BLOCKCHAIN_UNKNOWN) {
return data, nil
}