Skip to content
This repository was archived by the owner on Jul 16, 2024. It is now read-only.

Commit 5238aca

Browse files
authored
Merge pull request #25 from ahdark-services/refactor/settings
Refactor(settings): use settings as system service instead of database repository, and use etcd instead of database to store configurations.
2 parents 1474e5c + f095048 commit 5238aca

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

73 files changed

+4522
-1698
lines changed

.env

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,10 @@ RABBITMQ_PORT=5672
1515
RABBITMQ_USERNAME=payment
1616
RABBITMQ_PASSWORD=payment
1717

18+
ETCD_ENDPOINTS=localhost:2379
19+
1820
TRACE_EXPORTER=otlp-grpc
19-
TRACE_OTLP_ENDPOINT=http://localhost:4317
21+
TRACE_OTLP_ENDPOINT=localhost:4317
2022
TRACE_OTLP_INSECURE=true
2123

2224
METRICS_EXPORTER=prometheus

.env.docker

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ DB_NAME=payment
1212
REDIS_MODE=standalone
1313
REDIS_HOST=redis
1414

15+
ETCD_ENDPOINTS=etcd:2379
16+
1517
RABBITMQ_HOST=mq
1618
RABBITMQ_PORT=5672
1719
RABBITMQ_USERNAME=payment
@@ -22,7 +24,7 @@ CONSUL_ADDRESS=consul:8500
2224
JWT_SIGNING_KEY=123456
2325

2426
TRACE_EXPORTER=otlp-grpc
25-
TRACE_OTLP_ENDPOINT=http://jaeger:4317
27+
TRACE_OTLP_ENDPOINT=jaeger:4317
2628
TRACE_OTLP_INSECURE=true
2729

2830
METRICS_EXPORTER=prometheus

.github/workflows/build.yaml

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,24 @@ jobs:
2222
with:
2323
go-version: '1.20'
2424

25+
- name: Cache Go build paths
26+
id: go-cache-paths
27+
run: |
28+
echo "::set-output name=go-build::$(go env GOCACHE)"
29+
echo "::set-output name=go-mod::$(go env GOMODCACHE)"
30+
31+
- name: Go Build Cache
32+
uses: actions/cache@v2
33+
with:
34+
path: ${{ steps.go-cache-paths.outputs.go-build }}
35+
key: ${{ runner.os }}-go-build-${{ hashFiles('**/go.sum') }}
36+
37+
- name: Go Mod Cache
38+
uses: actions/cache@v2
39+
with:
40+
path: ${{ steps.go-cache-paths.outputs.go-mod }}
41+
key: ${{ runner.os }}-go-mod-${{ hashFiles('**/go.sum') }}
42+
2543
- name: Download dependencies
2644
run: |
2745
sudo apt install -y make

.github/workflows/test.yaml

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,24 @@ jobs:
2727
with:
2828
go-version: '1.20'
2929

30+
- name: Cache Go build paths
31+
id: go-cache-paths
32+
run: |
33+
echo "::set-output name=go-build::$(go env GOCACHE)"
34+
echo "::set-output name=go-mod::$(go env GOMODCACHE)"
35+
36+
- name: Go Build Cache
37+
uses: actions/cache@v2
38+
with:
39+
path: ${{ steps.go-cache-paths.outputs.go-build }}
40+
key: ${{ runner.os }}-go-build-${{ hashFiles('**/go.sum') }}
41+
42+
- name: Go Mod Cache
43+
uses: actions/cache@v2
44+
with:
45+
path: ${{ steps.go-cache-paths.outputs.go-mod }}
46+
key: ${{ runner.os }}-go-mod-${{ hashFiles('**/go.sum') }}
47+
3048
- name: Download dependencies
3149
run: |
3250
go mod download

.idea/dataSources.xml

Lines changed: 15 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

.idea/kubernetes-settings.xml

Lines changed: 6 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

bootstrap/appentry.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"github.com/ahdark-services/nextpayt/internal/consul"
1010
"github.com/ahdark-services/nextpayt/internal/currency_rate_api"
1111
"github.com/ahdark-services/nextpayt/internal/dcron"
12+
"github.com/ahdark-services/nextpayt/internal/etcd"
1213
"github.com/ahdark-services/nextpayt/internal/jwt"
1314
"github.com/ahdark-services/nextpayt/internal/limiter"
1415
"github.com/ahdark-services/nextpayt/internal/log"
@@ -31,6 +32,7 @@ func AppEntries() []fx.Option {
3132
jwt.Module(),
3233

3334
redis.Module(),
35+
etcd.Module(),
3436
cache.Module(),
3537
limiter.Module(),
3638
dcron.Module(),

conf/0module.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,5 +18,6 @@ func Module() fx.Option {
1818
fx.Provide(LoadEnvFn("RABBITMQ", RabbitMQConfig{})),
1919
fx.Provide(LoadEnvFn("JWT", JWTConfig{})),
2020
fx.Provide(LoadEnvFn("SERVER", ServerConfig{})),
21+
fx.Provide(LoadEnvFn("ETCD", EtcdConfig{})),
2122
)
2223
}

conf/etcd.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package conf
2+
3+
type EtcdConfig struct {
4+
Endpoints []string `envconfig:"ETCD_ENDPOINTS" default:"localhost:2379"`
5+
Username string `envconfig:"ETCD_USERNAME" default:""`
6+
Password string `envconfig:"ETCD_PASSWORD" default:""`
7+
8+
Namespace string `envconfig:"ETCD_NAMESPACE" default:"nextpayt"` // Namespace for etcd keys
9+
10+
// TLS
11+
CACert string `envconfig:"ETCD_CA_CERT" default:""` // CA certificate path
12+
ClientCert string `envconfig:"ETCD_CLIENT_CERT" default:""` // Client certificate path
13+
ClientKey string `envconfig:"ETCD_CLIENT_KEY" default:""` // Client key path
14+
}

constant/setting.go

Lines changed: 44 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,48 @@
11
package constant
22

33
const (
4-
SettingAdminUserName = "admin_user_name"
5-
SettingAdminUserPassword = "admin_user_password"
6-
7-
SettingUserDashboardEndpoint = "user_dashboard_endpoint"
8-
SettingAdminDashboardEndpoint = "admin_dashboard_endpoint"
9-
SettingCashierEndpoint = "cashier_endpoint"
10-
SettingClientAPIEndpoint = "client_api_endpoint"
11-
SettingCashierAPIEndpoint = "cashier_api_endpoint"
12-
SettingPublicAPIEndpoint = "public_api_endpoint"
13-
SettingExternalAPIEndpoint = "external_api_endpoint"
14-
15-
SettingEmailSmtpHost = "email_smtp_host"
16-
SettingEmailSmtpPort = "email_smtp_port"
17-
SettingEmailSmtpUsername = "email_smtp_username"
18-
SettingEmailSmtpPassword = "email_smtp_password"
19-
SettingEmailSmtpEncryption = "email_smtp_encryption"
20-
SettingEmailSmtpSkipVerify = "email_smtp_skip_verify"
21-
SettingEmailFromName = "email_from_name"
22-
SettingEmailFromAddress = "email_from_address"
23-
SettingEmailSubjectPrefix = "email_subject_prefix"
24-
SettingEmailTemplateValidateCode = "email_template_validate_code"
25-
26-
SettingUserDefaultAllowLogin = "user_default_allow_login"
27-
SettingUserDefaultAllowPay = "user_default_allow_pay"
28-
SettingUserDefaultAllowSettle = "user_default_allow_settle"
29-
SettingUserDefaultGroupId = "user_default_group_id"
30-
31-
SettingApplicationAllowCreate = "application_allow_create"
32-
33-
SettingAuthRegisterEnabled = "auth_register_enabled"
34-
SettingJWTExpire = "jwt_expire"
35-
36-
SettingPaymentMinUSDAmount = "payment_min_usd_amount"
37-
SettingPaymentMaxUSDAmount = "payment_max_usd_amount"
38-
SettingPaymentOrderExpire = "payment_order_expire"
39-
SettingPaymentEPaySubmitFrequencyPerHour = "payment_frequency_epay_submit_per_hour"
40-
SettingPaymentEPaySubmitFrequencyPerMinute = "payment_frequency_epay_submit_per_minute"
41-
SettingPaymentEPaySubmitFrequencyPerSecond = "payment_frequency_epay_submit_per_second"
42-
SettingPaymentRequestConsistentDomain = "payment_request_consistent_domain"
43-
SettingPaymentDefaultEPayCurrencyID = "payment_default_epay_currency_id"
44-
45-
SettingCurrencyDefaultCurrencyID = "currency_default_currency_id"
46-
SettingCurrencyAPIAPIKey = "currency_api_api_key"
47-
SettingCurrencyAPICacheDuration = "currency_api_cache_duration"
4+
SettingAdminUserName = "manage:admin_user_name"
5+
SettingAdminUserPassword = "manage:admin_user_password"
6+
7+
SettingUserDashboardEndpoint = "endpoint:user_dashboard"
8+
SettingAdminDashboardEndpoint = "endpoint:admin_dashboard"
9+
SettingCashierEndpoint = "endpoint:cashier"
10+
SettingClientAPIEndpoint = "endpoint:client_api"
11+
SettingCashierAPIEndpoint = "endpoint:cashier_api"
12+
SettingPublicAPIEndpoint = "endpoint:public_api"
13+
SettingExternalAPIEndpoint = "endpoint:external_api"
14+
15+
SettingEmailSmtpHost = "email:smtp_host"
16+
SettingEmailSmtpPort = "email:smtp_port"
17+
SettingEmailSmtpUsername = "email:smtp_username"
18+
SettingEmailSmtpPassword = "email:smtp_password"
19+
SettingEmailSmtpEncryption = "email:smtp_encryption"
20+
SettingEmailSmtpSkipVerify = "email:smtp_skip_verify"
21+
SettingEmailFromName = "email:from_name"
22+
SettingEmailFromAddress = "email:from_address"
23+
SettingEmailSubjectPrefix = "email:subject_prefix"
24+
SettingEmailTemplateValidateCode = "email:template_validate_code"
25+
26+
SettingUserDefaultAllowLogin = "user:default:allow_login"
27+
SettingUserDefaultAllowPay = "user:default:allow_pay"
28+
SettingUserDefaultAllowSettle = "user:default:allow_settle"
29+
SettingUserDefaultGroupId = "user:default:group_id"
30+
31+
SettingApplicationAllowCreate = "application:allow_create"
32+
33+
SettingAuthRegisterEnabled = "auth:register_enabled"
34+
SettingJWTExpire = "auth:jwt_expire"
35+
36+
SettingPaymentMinUSDAmount = "payment:min_usd_amount"
37+
SettingPaymentMaxUSDAmount = "payment:max_usd_amount"
38+
SettingPaymentOrderExpire = "payment:order_expire"
39+
SettingPaymentEPaySubmitFrequencyPerHour = "payment:frequency_epay:submit_per_hour"
40+
SettingPaymentEPaySubmitFrequencyPerMinute = "payment:frequency_epay:submit_per_minute"
41+
SettingPaymentEPaySubmitFrequencyPerSecond = "payment:frequency_epay:submit_per_second"
42+
SettingPaymentRequestConsistentDomain = "payment:request_consistent_domain"
43+
SettingPaymentDefaultEPayCurrencyID = "payment:default_epay_currency_id"
44+
45+
SettingCurrencyDefaultCurrencyID = "currency:default_currency_id"
46+
SettingCurrencyAPIAPIKey = "currency:api_api_key"
47+
SettingCurrencyAPICacheDuration = "currency:api_cache_duration"
4848
)

database/0module.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ func Module() fx.Option {
2323
fx.Provide(repo.NewPaymentChannelPaymentGroupMany2ManyRepo),
2424
fx.Provide(repo.NewPaymentGroupRepo),
2525
fx.Provide(repo.NewPaymentTypeRepo),
26-
fx.Provide(repo.NewSettingRepo),
2726
fx.Provide(repo.NewSettlementRepo),
2827
fx.Provide(repo.NewUnifiedOrderRepo),
2928
fx.Provide(repo.NewUnifiedOrderAssociationRepo),

database/cmd/migrate/main.go

Lines changed: 67 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ package main
22

33
import (
44
"context"
5+
"github.com/ahdark-services/nextpayt/internal/etcd"
6+
"go.etcd.io/etcd/client/v3/namespace"
57
"os"
68

79
"github.com/joho/godotenv"
@@ -15,21 +17,17 @@ import (
1517

1618
var ctx = context.Background()
1719

18-
func main() {
19-
if err := godotenv.Load(".env"); err != nil {
20-
logrus.WithContext(ctx).WithError(err).Warn("load .env failed")
21-
}
22-
20+
func databaseMigrate() error {
2321
var e conf.DatabaseConfig
2422
if err := envconfig.Process("DB", &e); err != nil {
2523
logrus.WithContext(ctx).WithError(err).Fatal("process env failed")
26-
return
24+
return err
2725
}
2826

2927
db, err := instance.NewDBInstance(ctx, &e)
3028
if err != nil {
3129
logrus.WithContext(ctx).WithError(err).Fatal("new database instance failed")
32-
return
30+
return err
3331
}
3432

3533
if err := db.WithContext(ctx).AutoMigrate(
@@ -53,29 +51,11 @@ func main() {
5351
&dao.UserGroupPaymentAssociation{},
5452
); err != nil {
5553
logrus.WithContext(ctx).WithError(err).Fatal("auto migrate failed")
56-
return
54+
return err
5755
}
5856

5957
logrus.WithContext(ctx).Info("auto migrate success")
6058

61-
// create default settings
62-
for k, v := range dao.DefaultSettings {
63-
// check name exists
64-
if err := db.Model(&dao.Setting{}).Where("name = ?", k).First(&dao.Setting{}).Error; err == nil {
65-
logrus.WithContext(ctx).WithField("name", k).Debug("setting is exists")
66-
continue
67-
}
68-
69-
// create default setting
70-
if err := db.Create(&dao.Setting{
71-
Name: k,
72-
Value: v,
73-
}).Error; err != nil {
74-
logrus.WithContext(ctx).WithError(err).Fatalf("create default setting failed: %s", k)
75-
continue
76-
}
77-
}
78-
7959
// create default payment types if not exists
8060
if err := db.Model(&dao.PaymentType{}).First(&dao.PaymentType{}).Error; err != nil {
8161
logrus.WithContext(ctx).Info("create default payment types")
@@ -92,7 +72,7 @@ func main() {
9272
logrus.WithContext(ctx).Info("create default organization group")
9373
if err := db.Create(&dao.DefaultUserGroup).Error; err != nil {
9474
logrus.WithContext(ctx).WithError(err).Fatalf("create default organization group failed: %s", dao.DefaultUserGroup.Name)
95-
return
75+
return err
9676
}
9777
}
9878

@@ -102,12 +82,71 @@ func main() {
10282
for _, currency := range dao.DefaultCurrencies {
10383
if err := db.Create(&currency).Error; err != nil {
10484
logrus.WithContext(ctx).WithError(err).Fatalf("create default currency failed: %s", currency.Name)
105-
return
85+
return err
10686
}
10787
}
10888
}
10989

11090
logrus.WithContext(ctx).Info("create default data success")
11191

92+
return nil
93+
}
94+
95+
func etcdMigrate() error {
96+
var e conf.EtcdConfig
97+
if err := envconfig.Process("ETCD", &e); err != nil {
98+
logrus.WithContext(ctx).WithError(err).Fatal("process env failed")
99+
return err
100+
}
101+
102+
client, err := etcd.NewEtcdClient(ctx, &e)
103+
if err != nil {
104+
logrus.WithContext(ctx).WithError(err).Fatal("new etcd client failed")
105+
return err
106+
}
107+
kv := namespace.NewKV(client, "settings:")
108+
//client.Delete(ctx, "", clientv3.WithPrefix())
109+
110+
// create default settings
111+
for k, v := range dao.DefaultSettings {
112+
// check if exists
113+
resp, err := kv.Get(ctx, k)
114+
if err != nil {
115+
logrus.WithContext(ctx).WithError(err).Fatalf("get setting failed: %s", k)
116+
continue
117+
}
118+
119+
if len(resp.Kvs) > 0 {
120+
logrus.WithContext(ctx).Infof("setting exists: %s", k)
121+
continue
122+
}
123+
124+
// create
125+
if _, err := kv.Put(ctx, k, v); err != nil {
126+
logrus.WithContext(ctx).WithError(err).Fatalf("create setting failed: %s", k)
127+
continue
128+
}
129+
130+
logrus.WithContext(ctx).Infof("create setting success: %s", k)
131+
}
132+
133+
return nil
134+
}
135+
136+
func main() {
137+
if err := godotenv.Load(".env"); err != nil {
138+
logrus.WithContext(ctx).WithError(err).Warn("load .env failed")
139+
}
140+
141+
if err := databaseMigrate(); err != nil {
142+
logrus.WithContext(ctx).WithError(err).Fatal("database migrate failed")
143+
return
144+
}
145+
146+
if err := etcdMigrate(); err != nil {
147+
logrus.WithContext(ctx).WithError(err).Fatal("etcd migrate failed")
148+
return
149+
}
150+
112151
os.Exit(0)
113152
}

0 commit comments

Comments
 (0)