This repository has been archived by the owner on Apr 2, 2024. It is now read-only.
generated from mrz1836/go-template
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
client_options.go
685 lines (595 loc) · 21.1 KB
/
client_options.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
package bux
import (
"database/sql"
"net/http"
"net/url"
"strings"
"time"
"github.com/BuxOrg/bux/chainstate"
"github.com/BuxOrg/bux/cluster"
"github.com/BuxOrg/bux/logging"
"github.com/BuxOrg/bux/metrics"
"github.com/BuxOrg/bux/notifications"
"github.com/BuxOrg/bux/taskmanager"
"github.com/BuxOrg/bux/utils"
"github.com/bitcoin-sv/go-broadcast-client/broadcast"
"github.com/bitcoin-sv/go-paymail"
"github.com/bitcoin-sv/go-paymail/server"
"github.com/coocood/freecache"
"github.com/go-redis/redis/v8"
"github.com/mrz1836/go-cache"
"github.com/mrz1836/go-cachestore"
"github.com/mrz1836/go-datastore"
"github.com/newrelic/go-agent/v3/newrelic"
"github.com/rs/zerolog"
"github.com/tonicpow/go-minercraft/v2"
taskq "github.com/vmihailenco/taskq/v3"
"go.mongodb.org/mongo-driver/mongo"
)
// ClientOps allow functional options to be supplied that overwrite default client options.
type ClientOps func(c *clientOptions)
// defaultClientOptions will return an clientOptions struct with the default settings
//
// Useful for starting with the default and then modifying as needed
func defaultClientOptions() *clientOptions {
defaultLogger := logging.GetDefaultLogger()
dWarnLogger := defaultLogger.Level(zerolog.WarnLevel)
datastoreLogger := logging.CreateGormLoggerAdapter(&dWarnLogger, "datastore")
// Set the default options
return &clientOptions{
// By default check input utxos (unless disabled by the user)
iuc: true,
// Blank chainstate config
chainstate: &chainstateOptions{
ClientInterface: nil,
options: []chainstate.ClientOps{},
broadcasting: true, // Enabled by default for new users
broadcastInstant: true, // Enabled by default for new users
paymailP2P: true, // Enabled by default for new users
syncOnChain: true, // Enabled by default for new users
},
cluster: &clusterOptions{
options: []cluster.ClientOps{},
},
// Blank cache config
cacheStore: &cacheStoreOptions{
ClientInterface: nil,
options: []cachestore.ClientOps{},
},
// Blank Datastore config
dataStore: &dataStoreOptions{
ClientInterface: nil,
options: []datastore.ClientOps{datastore.WithLogger(&datastore.DatabaseLogWrapper{GormLoggerInterface: datastoreLogger})},
},
// Default http client
httpClient: &http.Client{
Timeout: defaultHTTPTimeout,
},
// Blank model options (use the Base models)
models: &modelOptions{
modelNames: modelNames(BaseModels...),
models: BaseModels,
migrateModelNames: nil,
migrateModels: nil,
},
// Blank NewRelic config
newRelic: &newRelicOptions{},
// Blank notifications config
notifications: ¬ificationsOptions{
ClientInterface: nil,
webhookEndpoint: "",
},
// Blank Paymail config
paymail: &paymailOptions{
client: nil,
serverConfig: &PaymailServerOptions{
Configuration: nil,
options: []server.ConfigOps{},
},
},
// Blank TaskManager config
taskManager: &taskManagerOptions{
TaskEngine: nil,
cronCustomPeriods: map[string]time.Duration{},
},
// Default user agent
userAgent: defaultUserAgent,
}
}
// modelNames will take a list of models and return the list of names
func modelNames(models ...interface{}) (names []string) {
for _, modelInterface := range models {
names = append(names, modelInterface.(ModelInterface).Name())
}
return
}
// modelExists will return true if the model is found
func (o *clientOptions) modelExists(modelName, list string) bool {
m := o.models.modelNames
if list == migrateList {
m = o.models.migrateModelNames
}
for _, name := range m {
if strings.EqualFold(name, modelName) {
return true
}
}
return false
}
// addModel will add the model if it does not exist already (load once)
func (o *clientOptions) addModel(model interface{}, list string) {
name := model.(ModelInterface).Name()
if !o.modelExists(name, list) {
if list == migrateList {
o.models.migrateModelNames = append(o.models.migrateModelNames, name)
o.models.migrateModels = append(o.models.migrateModels, model)
return
}
o.models.modelNames = append(o.models.modelNames, name)
o.models.models = append(o.models.models, model)
}
}
// addModels will add the models if they do not exist already (load once)
func (o *clientOptions) addModels(list string, models ...interface{}) {
for _, modelInterface := range models {
o.addModel(modelInterface, list)
}
}
// DefaultModelOptions will set any default model options (from Client options->model)
func (c *Client) DefaultModelOptions(opts ...ModelOps) []ModelOps {
// Set the Client from the bux.Client onto the model
opts = append(opts, WithClient(c))
// Set the encryption key (if found)
opts = append(opts, WithEncryptionKey(c.options.encryptionKey))
// Return the new options
return opts
}
// -----------------------------------------------------------------
// GENERAL
// -----------------------------------------------------------------
// WithUserAgent will overwrite the default useragent
func WithUserAgent(userAgent string) ClientOps {
return func(c *clientOptions) {
if len(userAgent) > 0 {
c.userAgent = userAgent
}
}
}
// WithNewRelic will set the NewRelic application client
func WithNewRelic(app *newrelic.Application) ClientOps {
return func(c *clientOptions) {
// Disregard if the app is nil
if app == nil {
return
}
// Set the app
c.newRelic.app = app
// Enable New relic on other services
c.cacheStore.options = append(c.cacheStore.options, cachestore.WithNewRelic())
c.chainstate.options = append(c.chainstate.options, chainstate.WithNewRelic())
c.dataStore.options = append(c.dataStore.options, datastore.WithNewRelic())
c.taskManager.options = append(c.taskManager.options, taskmanager.WithNewRelic())
// c.notifications.options = append(c.notifications.options, notifications.WithNewRelic())
// Enable the service
c.newRelic.enabled = true
}
}
// WithDebugging will set debugging in any applicable configuration
func WithDebugging() ClientOps {
return func(c *clientOptions) {
c.debug = true
// Enable debugging on other services
c.cacheStore.options = append(c.cacheStore.options, cachestore.WithDebugging())
c.chainstate.options = append(c.chainstate.options, chainstate.WithDebugging())
c.dataStore.options = append(c.dataStore.options, datastore.WithDebugging())
c.notifications.options = append(c.notifications.options, notifications.WithDebugging())
}
}
// WithEncryption will set the encryption key and encrypt values using this key
func WithEncryption(key string) ClientOps {
return func(c *clientOptions) {
if len(key) > 0 {
c.encryptionKey = key
}
}
}
// WithModels will add additional models (will NOT migrate using datastore)
//
// Pointers of structs (IE: &models.Xpub{})
func WithModels(models ...interface{}) ClientOps {
return func(c *clientOptions) {
if len(models) > 0 {
c.addModels(modelList, models...)
}
}
}
// WithIUCDisabled will disable checking the input utxos
func WithIUCDisabled() ClientOps {
return func(c *clientOptions) {
c.iuc = false
}
}
// WithHTTPClient will set the custom http interface
func WithHTTPClient(httpClient HTTPInterface) ClientOps {
return func(c *clientOptions) {
if httpClient != nil {
c.httpClient = httpClient
}
}
}
// WithLogger will set the custom logger interface
func WithLogger(customLogger *zerolog.Logger) ClientOps {
return func(c *clientOptions) {
if customLogger != nil {
c.logger = customLogger
// Enable the logger on all bux services
chainstateLogger := customLogger.With().Str("subservice", "chainstate").Logger()
taskManagerLogger := customLogger.With().Str("subservice", "taskManager").Logger()
notificationsLogger := customLogger.With().Str("subservice", "notifications").Logger()
c.chainstate.options = append(c.chainstate.options, chainstate.WithLogger(&chainstateLogger))
c.taskManager.options = append(c.taskManager.options, taskmanager.WithLogger(&taskManagerLogger))
c.notifications.options = append(c.notifications.options, notifications.WithLogger(¬ificationsLogger))
// Enable the logger on all external services
var datastoreLogger *logging.GormLoggerAdapter
if customLogger.GetLevel() == zerolog.InfoLevel {
warnLvlLogger := customLogger.Level(zerolog.WarnLevel)
datastoreLogger = logging.CreateGormLoggerAdapter(&warnLvlLogger, "datastore")
} else {
datastoreLogger = logging.CreateGormLoggerAdapter(customLogger, "datastore")
}
c.dataStore.options = append(c.dataStore.options, datastore.WithLogger(&datastore.DatabaseLogWrapper{GormLoggerInterface: datastoreLogger}))
cachestoreLogger := logging.CreateGormLoggerAdapter(customLogger, "cachestore")
c.cacheStore.options = append(c.cacheStore.options, cachestore.WithLogger(cachestoreLogger))
}
}
}
// -----------------------------------------------------------------
// METRICS
// -----------------------------------------------------------------
// WithMetrics will set the metrics with a collector interface
func WithMetrics(collector metrics.Collector) ClientOps {
return func(c *clientOptions) {
if collector != nil {
c.metrics = metrics.NewMetrics(collector)
}
}
}
// -----------------------------------------------------------------
// CACHESTORE
// -----------------------------------------------------------------
// WithCustomCachestore will set the cachestore
func WithCustomCachestore(cacheStore cachestore.ClientInterface) ClientOps {
return func(c *clientOptions) {
if cacheStore != nil {
c.cacheStore.ClientInterface = cacheStore
}
}
}
// WithFreeCache will set the cache client for both Read & Write clients
func WithFreeCache() ClientOps {
return func(c *clientOptions) {
c.cacheStore.options = append(c.cacheStore.options, cachestore.WithFreeCache())
}
}
// WithFreeCacheConnection will set the cache client to an active FreeCache connection
func WithFreeCacheConnection(client *freecache.Cache) ClientOps {
return func(c *clientOptions) {
if client != nil {
c.cacheStore.options = append(
c.cacheStore.options,
cachestore.WithFreeCacheConnection(client),
)
}
}
}
// WithRedis will set the redis cache client for both Read & Write clients
//
// This will load new redis connections using the given parameters
func WithRedis(config *cachestore.RedisConfig) ClientOps {
return func(c *clientOptions) {
if config != nil {
c.cacheStore.options = append(c.cacheStore.options, cachestore.WithRedis(config))
}
}
}
// WithRedisConnection will set the cache client to an active redis connection
func WithRedisConnection(activeClient *cache.Client) ClientOps {
return func(c *clientOptions) {
if activeClient != nil {
c.cacheStore.options = append(
c.cacheStore.options,
cachestore.WithRedisConnection(activeClient),
)
}
}
}
// -----------------------------------------------------------------
// DATASTORE
// -----------------------------------------------------------------
// WithCustomDatastore will set the datastore
func WithCustomDatastore(dataStore datastore.ClientInterface) ClientOps {
return func(c *clientOptions) {
if dataStore != nil {
c.dataStore.ClientInterface = dataStore
}
}
}
// WithAutoMigrate will enable auto migrate database mode (given models)
//
// Pointers of structs (IE: &models.Xpub{})
func WithAutoMigrate(migrateModels ...interface{}) ClientOps {
return func(c *clientOptions) {
if len(migrateModels) > 0 {
c.addModels(modelList, migrateModels...)
c.addModels(migrateList, migrateModels...)
}
}
}
// WithMigrationDisabled will disable all migrations from running in the Datastore
func WithMigrationDisabled() ClientOps {
return func(c *clientOptions) {
c.dataStore.migrationDisabled = true
}
}
// WithSQLite will set the Datastore to use SQLite
func WithSQLite(config *datastore.SQLiteConfig) ClientOps {
return func(c *clientOptions) {
if config != nil {
c.dataStore.options = append(c.dataStore.options, datastore.WithSQLite(config))
}
}
}
// WithSQL will set the datastore to use the SQL config
func WithSQL(engine datastore.Engine, config *datastore.SQLConfig) ClientOps {
return func(c *clientOptions) {
if config != nil && !engine.IsEmpty() {
c.dataStore.options = append(
c.dataStore.options,
datastore.WithSQL(engine, []*datastore.SQLConfig{config}),
)
}
}
}
// WithSQLConfigs will load multiple connections (replica & master)
func WithSQLConfigs(engine datastore.Engine, configs []*datastore.SQLConfig) ClientOps {
return func(c *clientOptions) {
if len(configs) > 0 && !engine.IsEmpty() {
c.dataStore.options = append(
c.dataStore.options,
datastore.WithSQL(engine, configs),
)
}
}
}
// WithSQLConnection will set the Datastore to an existing connection for MySQL or PostgreSQL
func WithSQLConnection(engine datastore.Engine, sqlDB *sql.DB, tablePrefix string) ClientOps {
return func(c *clientOptions) {
if sqlDB != nil && !engine.IsEmpty() {
c.dataStore.options = append(
c.dataStore.options,
datastore.WithSQLConnection(engine, sqlDB, tablePrefix),
)
}
}
}
// WithMongoDB will set the Datastore to use MongoDB
func WithMongoDB(config *datastore.MongoDBConfig) ClientOps {
return func(c *clientOptions) {
if config != nil {
c.dataStore.options = append(c.dataStore.options, datastore.WithMongo(config))
}
}
}
// WithMongoConnection will set the Datastore to an existing connection for MongoDB
func WithMongoConnection(database *mongo.Database, tablePrefix string) ClientOps {
return func(c *clientOptions) {
if database != nil {
c.dataStore.options = append(
c.dataStore.options,
datastore.WithMongoConnection(database, tablePrefix),
)
}
}
}
// -----------------------------------------------------------------
// PAYMAIL
// -----------------------------------------------------------------
// WithPaymailClient will set a custom paymail client
func WithPaymailClient(client paymail.ClientInterface) ClientOps {
return func(c *clientOptions) {
if client != nil {
c.paymail.client = client
}
}
}
// WithPaymailSupport will set the configuration for Paymail support (as a server)
func WithPaymailSupport(domains []string, defaultFromPaymail string, domainValidation, senderValidation bool) ClientOps {
return func(c *clientOptions) {
// Add generic capabilities
c.paymail.serverConfig.options = append(c.paymail.serverConfig.options, server.WithP2PCapabilities())
// Add each domain
for _, domain := range domains {
c.paymail.serverConfig.options = append(c.paymail.serverConfig.options, server.WithDomain(domain))
}
// Set the sender validation
if senderValidation {
c.paymail.serverConfig.options = append(c.paymail.serverConfig.options, server.WithSenderValidation())
}
// Domain validation
if !domainValidation {
c.paymail.serverConfig.options = append(c.paymail.serverConfig.options, server.WithDomainValidationDisabled())
}
// Add default values
if len(defaultFromPaymail) > 0 {
c.paymail.serverConfig.DefaultFromPaymail = defaultFromPaymail
}
// Add the paymail_address model in bux
c.addModels(migrateList, newPaymail(""))
}
}
// WithPaymailBeefSupport will enable Paymail BEEF format support (as a server) and create a Pulse client for Merkle Roots verification.
func WithPaymailBeefSupport(pulseURL, pulseAuthToken string) ClientOps {
return func(c *clientOptions) {
_, err := url.ParseRequestURI(pulseURL)
if err != nil {
panic(err)
}
c.chainstate.options = append(c.chainstate.options, chainstate.WithConnectionToPulse(pulseURL, pulseAuthToken))
c.paymail.serverConfig.options = append(c.paymail.serverConfig.options, server.WithBeefCapabilities())
}
}
// WithPaymailServerConfig will set the custom server configuration for Paymail
//
// This will allow overriding the Configuration.actions (paymail service provider)
func WithPaymailServerConfig(config *server.Configuration, defaultFromPaymail string) ClientOps {
return func(c *clientOptions) {
if config != nil {
c.paymail.serverConfig.Configuration = config
}
if len(defaultFromPaymail) > 0 {
c.paymail.serverConfig.DefaultFromPaymail = defaultFromPaymail
}
// Add the paymail_address model in bux
c.addModels(migrateList, newPaymail(""))
}
}
// -----------------------------------------------------------------
// TASK MANAGER
// -----------------------------------------------------------------
// WithTaskqConfig will set the task manager to use TaskQ & in-memory
func WithTaskqConfig(config *taskq.QueueOptions) ClientOps {
return func(c *clientOptions) {
if config != nil {
c.taskManager.options = append(
c.taskManager.options,
taskmanager.WithTaskqConfig(config),
)
}
}
}
// WithCronCustomPeriod will set the custom cron jobs period which will override the default
func WithCronCustomPeriod(cronJobName string, period time.Duration) ClientOps {
return func(c *clientOptions) {
if c.taskManager != nil {
c.taskManager.cronCustomPeriods[cronJobName] = period
}
}
}
// -----------------------------------------------------------------
// CLUSTER
// -----------------------------------------------------------------
// WithClusterRedis will set the cluster coordinator to use redis
func WithClusterRedis(redisOptions *redis.Options) ClientOps {
return func(c *clientOptions) {
if redisOptions != nil {
c.cluster.options = append(c.cluster.options, cluster.WithRedis(redisOptions))
}
}
}
// WithClusterKeyPrefix will set the cluster key prefix to use for all keys in the cluster coordinator
func WithClusterKeyPrefix(prefix string) ClientOps {
return func(c *clientOptions) {
if prefix != "" {
c.cluster.options = append(c.cluster.options, cluster.WithKeyPrefix(prefix))
}
}
}
// WithClusterClient will set the cluster options on the client
func WithClusterClient(clusterClient cluster.ClientInterface) ClientOps {
return func(c *clientOptions) {
if clusterClient != nil {
c.cluster.ClientInterface = clusterClient
}
}
}
// -----------------------------------------------------------------
// CHAIN-STATE
// -----------------------------------------------------------------
// WithCustomChainstate will set the chainstate
func WithCustomChainstate(chainState chainstate.ClientInterface) ClientOps {
return func(c *clientOptions) {
if chainState != nil {
c.chainstate.ClientInterface = chainState
}
}
}
// WithChainstateOptions will set chainstate defaults
func WithChainstateOptions(broadcasting, broadcastInstant, paymailP2P, syncOnChain bool) ClientOps {
return func(c *clientOptions) {
c.chainstate.broadcasting = broadcasting
c.chainstate.broadcastInstant = broadcastInstant
c.chainstate.paymailP2P = paymailP2P
c.chainstate.syncOnChain = syncOnChain
}
}
// WithExcludedProviders will set a list of excluded providers
func WithExcludedProviders(providers []string) ClientOps {
return func(c *clientOptions) {
if len(providers) > 0 {
c.chainstate.options = append(c.chainstate.options, chainstate.WithExcludedProviders(providers))
}
}
}
// -----------------------------------------------------------------
// NOTIFICATIONS
// -----------------------------------------------------------------
// WithNotifications will set the notifications config
func WithNotifications(webhookEndpoint string) ClientOps {
return func(c *clientOptions) {
if len(webhookEndpoint) > 0 {
c.notifications.webhookEndpoint = webhookEndpoint
}
}
}
// WithCustomNotifications will set a custom notifications interface
func WithCustomNotifications(customNotifications notifications.ClientInterface) ClientOps {
return func(c *clientOptions) {
if customNotifications != nil {
c.notifications.ClientInterface = customNotifications
}
}
}
// WithFeeQuotes will find the lowest fee instead of using the fee set by the WithFeeUnit function
func WithFeeQuotes(enabled bool) ClientOps {
return func(c *clientOptions) {
c.chainstate.options = append(c.chainstate.options, chainstate.WithFeeQuotes(enabled))
}
}
// WithFeeUnit will set the fee unit to use for broadcasting
func WithFeeUnit(feeUnit *utils.FeeUnit) ClientOps {
return func(c *clientOptions) {
c.chainstate.options = append(c.chainstate.options, chainstate.WithFeeUnit(feeUnit))
}
}
// WithMAPI will specify Arc as an API for minercraft client
func WithMAPI() ClientOps {
return func(c *clientOptions) {
c.chainstate.options = append(c.chainstate.options, chainstate.WithMAPI())
}
}
// WithMinercraft will set custom minercraft client
func WithMinercraft(minercraft minercraft.ClientInterface) ClientOps {
return func(c *clientOptions) {
if minercraft != nil {
c.chainstate.options = append(c.chainstate.options, chainstate.WithMinercraft(minercraft))
}
}
}
// WithMinercraftAPIs set custom MinerAPIs for minercraft
func WithMinercraftAPIs(miners []*minercraft.MinerAPIs) ClientOps {
return func(c *clientOptions) {
c.chainstate.options = append(c.chainstate.options, chainstate.WithMinercraftAPIs(miners))
}
}
// WithBroadcastClient will set broadcast client
func WithBroadcastClient(broadcastClient broadcast.Client) ClientOps {
return func(c *clientOptions) {
c.chainstate.options = append(c.chainstate.options, chainstate.WithBroadcastClient(broadcastClient))
}
}
// WithCallback set callback settings
func WithCallback(callbackURL string, callbackToken string) ClientOps {
return func(c *clientOptions) {
c.chainstate.options = append(c.chainstate.options, chainstate.WithCallback(callbackURL, callbackToken))
}
}