Merge pull request 'discovery-216' (#220) from discovery-216 into main
Some checks failed
ci/woodpecker/push/fx_ingestor Pipeline is pending
ci/woodpecker/push/fx_oracle Pipeline is pending
ci/woodpecker/push/ledger Pipeline is pending
ci/woodpecker/push/mntx_gateway Pipeline is pending
ci/woodpecker/push/nats Pipeline is pending
ci/woodpecker/push/notification Pipeline is pending
ci/woodpecker/push/payments_orchestrator Pipeline is pending
ci/woodpecker/push/billing_fees Pipeline was successful
ci/woodpecker/push/bff Pipeline was successful
ci/woodpecker/push/db Pipeline was successful
ci/woodpecker/push/chain_gateway Pipeline was successful
ci/woodpecker/push/discovery Pipeline failed
ci/woodpecker/push/frontend Pipeline failed
Some checks failed
ci/woodpecker/push/fx_ingestor Pipeline is pending
ci/woodpecker/push/fx_oracle Pipeline is pending
ci/woodpecker/push/ledger Pipeline is pending
ci/woodpecker/push/mntx_gateway Pipeline is pending
ci/woodpecker/push/nats Pipeline is pending
ci/woodpecker/push/notification Pipeline is pending
ci/woodpecker/push/payments_orchestrator Pipeline is pending
ci/woodpecker/push/billing_fees Pipeline was successful
ci/woodpecker/push/bff Pipeline was successful
ci/woodpecker/push/db Pipeline was successful
ci/woodpecker/push/chain_gateway Pipeline was successful
ci/woodpecker/push/discovery Pipeline failed
ci/woodpecker/push/frontend Pipeline failed
Reviewed-on: #220
This commit was merged in pull request #220.
This commit is contained in:
72
.woodpecker/discovery.yml
Normal file
72
.woodpecker/discovery.yml
Normal file
@@ -0,0 +1,72 @@
|
||||
matrix:
|
||||
include:
|
||||
- DISCOVERY_IMAGE_PATH: discovery/service
|
||||
DISCOVERY_DOCKERFILE: ci/prod/compose/discovery.dockerfile
|
||||
DISCOVERY_ENV: prod
|
||||
|
||||
when:
|
||||
- event: push
|
||||
branch: main
|
||||
|
||||
steps:
|
||||
- name: version
|
||||
image: alpine:latest
|
||||
commands:
|
||||
- set -euo pipefail 2>/dev/null || set -eu
|
||||
- apk add --no-cache git
|
||||
- GIT_REV="$(git rev-parse --short HEAD)"
|
||||
- BUILD_BRANCH="$(git rev-parse --abbrev-ref HEAD)"
|
||||
- APP_V="$(cat version)"
|
||||
- BUILD_DATE="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
- BUILD_USER="${WOODPECKER_MACHINE:-woodpecker}"
|
||||
- printf "GIT_REV=%s\nBUILD_BRANCH=%s\nAPP_V=%s\nBUILD_DATE=%s\nBUILD_USER=%s\n" \
|
||||
"$GIT_REV" "$BUILD_BRANCH" "$APP_V" "$BUILD_DATE" "$BUILD_USER" | tee .env.version
|
||||
|
||||
- name: proto
|
||||
image: golang:alpine
|
||||
depends_on: [ version ]
|
||||
commands:
|
||||
- set -eu
|
||||
- apk add --no-cache bash git build-base protoc protobuf-dev
|
||||
- go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
|
||||
- go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
|
||||
- export PATH="$(go env GOPATH)/bin:$PATH"
|
||||
- bash ci/scripts/proto/generate.sh
|
||||
|
||||
- name: secrets
|
||||
image: alpine:latest
|
||||
depends_on: [ version ]
|
||||
environment:
|
||||
VAULT_ADDR: { from_secret: VAULT_ADDR }
|
||||
VAULT_ROLE_ID: { from_secret: VAULT_APP_ROLE }
|
||||
VAULT_SECRET_ID: { from_secret: VAULT_SECRET_ID }
|
||||
commands:
|
||||
- set -euo pipefail
|
||||
- apk add --no-cache bash coreutils openssh-keygen curl sed python3
|
||||
- mkdir -p secrets
|
||||
- ./ci/vlt kv_to_file kv ops/deploy/ssh_key private_b64 secrets/SSH_KEY.b64 600
|
||||
- base64 -d secrets/SSH_KEY.b64 > secrets/SSH_KEY
|
||||
- chmod 600 secrets/SSH_KEY
|
||||
- ssh-keygen -y -f secrets/SSH_KEY >/dev/null
|
||||
- ./ci/vlt kv_get kv registry user > secrets/REGISTRY_USER
|
||||
- ./ci/vlt kv_get kv registry password > secrets/REGISTRY_PASSWORD
|
||||
|
||||
- name: build-image
|
||||
image: gcr.io/kaniko-project/executor:debug
|
||||
depends_on: [ proto, secrets ]
|
||||
commands:
|
||||
- sh ci/scripts/discovery/build-image.sh
|
||||
|
||||
- name: deploy
|
||||
image: alpine:latest
|
||||
depends_on: [ secrets, build-image ]
|
||||
environment:
|
||||
VAULT_ADDR: { from_secret: VAULT_ADDR }
|
||||
VAULT_ROLE_ID: { from_secret: VAULT_APP_ROLE }
|
||||
VAULT_SECRET_ID: { from_secret: VAULT_SECRET_ID }
|
||||
commands:
|
||||
- set -euo pipefail
|
||||
- apk add --no-cache bash openssh-client rsync coreutils curl sed python3
|
||||
- mkdir -p /root/.ssh
|
||||
- install -m 600 secrets/SSH_KEY /root/.ssh/id_rsa
|
||||
- sh ci/scripts/discovery/deploy.sh
|
||||
@@ -26,6 +26,7 @@ type Imp struct {
|
||||
config *config
|
||||
app *grpcapp.App[storage.Repository]
|
||||
oracleClient oracleclient.Client
|
||||
service *fees.Service
|
||||
}
|
||||
|
||||
type config struct {
|
||||
@@ -65,6 +66,9 @@ func Create(logger mlogger.Logger, file string, debug bool) (*Imp, error) {
|
||||
|
||||
func (i *Imp) Shutdown() {
|
||||
if i.app == nil {
|
||||
if i.service != nil {
|
||||
i.service.Shutdown()
|
||||
}
|
||||
if i.oracleClient != nil {
|
||||
_ = i.oracleClient.Close()
|
||||
}
|
||||
@@ -76,6 +80,10 @@ func (i *Imp) Shutdown() {
|
||||
timeout = i.config.Runtime.ShutdownTimeout()
|
||||
}
|
||||
|
||||
if i.service != nil {
|
||||
i.service.Shutdown()
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
i.app.Shutdown(ctx)
|
||||
cancel()
|
||||
@@ -121,7 +129,9 @@ func (i *Imp) Start() error {
|
||||
if oracleClient != nil {
|
||||
opts = append(opts, fees.WithOracleClient(oracleClient))
|
||||
}
|
||||
return fees.NewService(logger, repo, producer, opts...), nil
|
||||
svc := fees.NewService(logger, repo, producer, opts...)
|
||||
i.service = svc
|
||||
return svc, nil
|
||||
}
|
||||
|
||||
app, err := grpcapp.NewApp(i.logger, "billing_fees", cfg.Config, i.debug, repoFactory, serviceFactory)
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/tech/sendico/billing/fees/internal/appversion"
|
||||
internalcalculator "github.com/tech/sendico/billing/fees/internal/service/fees/internal/calculator"
|
||||
"github.com/tech/sendico/billing/fees/internal/service/fees/internal/resolver"
|
||||
"github.com/tech/sendico/billing/fees/storage"
|
||||
@@ -15,9 +16,11 @@ import (
|
||||
oracleclient "github.com/tech/sendico/fx/oracle/client"
|
||||
"github.com/tech/sendico/pkg/api/routers"
|
||||
clockpkg "github.com/tech/sendico/pkg/clock"
|
||||
"github.com/tech/sendico/pkg/discovery"
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
msg "github.com/tech/sendico/pkg/messaging"
|
||||
"github.com/tech/sendico/pkg/mlogger"
|
||||
"github.com/tech/sendico/pkg/mservice"
|
||||
feesv1 "github.com/tech/sendico/pkg/proto/billing/fees/v1"
|
||||
tracev1 "github.com/tech/sendico/pkg/proto/common/trace/v1"
|
||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||
@@ -36,6 +39,7 @@ type Service struct {
|
||||
calculator Calculator
|
||||
oracle oracleclient.Client
|
||||
resolver FeeResolver
|
||||
announcer *discovery.Announcer
|
||||
feesv1.UnimplementedFeeEngineServer
|
||||
}
|
||||
|
||||
@@ -62,6 +66,8 @@ func NewService(logger mlogger.Logger, repo storage.Repository, producer msg.Pro
|
||||
svc.resolver = resolver.New(repo.Plans(), svc.logger)
|
||||
}
|
||||
|
||||
svc.startDiscoveryAnnouncer()
|
||||
|
||||
return svc
|
||||
}
|
||||
|
||||
@@ -71,6 +77,28 @@ func (s *Service) Register(router routers.GRPC) error {
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) Shutdown() {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
if s.announcer != nil {
|
||||
s.announcer.Stop()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) startDiscoveryAnnouncer() {
|
||||
if s == nil || s.producer == nil {
|
||||
return
|
||||
}
|
||||
announce := discovery.Announcement{
|
||||
Service: "BILLING_FEES",
|
||||
Operations: []string{"fee.calc"},
|
||||
Version: appversion.Create().Short(),
|
||||
}
|
||||
s.announcer = discovery.NewAnnouncer(s.logger, s.producer, string(mservice.FeePlans), announce)
|
||||
s.announcer.Start()
|
||||
}
|
||||
|
||||
func (s *Service) QuoteFees(ctx context.Context, req *feesv1.QuoteFeesRequest) (resp *feesv1.QuoteFeesResponse, err error) {
|
||||
var (
|
||||
meta *feesv1.RequestMeta
|
||||
|
||||
3
api/discovery/.gitignore
vendored
Normal file
3
api/discovery/.gitignore
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
internal/generated
|
||||
.gocache
|
||||
app
|
||||
17
api/discovery/config.yml
Normal file
17
api/discovery/config.yml
Normal file
@@ -0,0 +1,17 @@
|
||||
runtime:
|
||||
shutdown_timeout_seconds: 15
|
||||
|
||||
metrics:
|
||||
address: ":9405"
|
||||
|
||||
messaging:
|
||||
driver: NATS
|
||||
settings:
|
||||
url_env: NATS_URL
|
||||
host_env: NATS_HOST
|
||||
port_env: NATS_PORT
|
||||
username_env: NATS_USER
|
||||
password_env: NATS_PASSWORD
|
||||
broker_name: Discovery Service
|
||||
max_reconnects: 10
|
||||
reconnect_wait: 5
|
||||
51
api/discovery/go.mod
Normal file
51
api/discovery/go.mod
Normal file
@@ -0,0 +1,51 @@
|
||||
module github.com/tech/sendico/discovery
|
||||
|
||||
go 1.25.3
|
||||
|
||||
replace github.com/tech/sendico/pkg => ../pkg
|
||||
|
||||
require (
|
||||
github.com/go-chi/chi/v5 v5.2.3
|
||||
github.com/prometheus/client_golang v1.23.2
|
||||
github.com/tech/sendico/pkg v0.1.0
|
||||
go.uber.org/zap v1.27.1
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/bmatcuk/doublestar/v4 v4.9.1 // indirect
|
||||
github.com/casbin/casbin/v2 v2.135.0 // indirect
|
||||
github.com/casbin/govaluate v1.10.0 // indirect
|
||||
github.com/casbin/mongodb-adapter/v3 v3.7.0 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/golang/snappy v1.0.0 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/klauspost/compress v1.18.2 // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||
github.com/montanaflynn/stats v0.7.1 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/nats-io/nats.go v1.48.0 // indirect
|
||||
github.com/nats-io/nkeys v0.4.12 // indirect
|
||||
github.com/nats-io/nuid v1.0.1 // indirect
|
||||
github.com/prometheus/client_model v0.6.2 // indirect
|
||||
github.com/prometheus/common v0.67.4 // indirect
|
||||
github.com/prometheus/procfs v0.19.2 // indirect
|
||||
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
|
||||
github.com/xdg-go/scram v1.2.0 // indirect
|
||||
github.com/xdg-go/stringprep v1.0.4 // indirect
|
||||
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
|
||||
go.mongodb.org/mongo-driver v1.17.6 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.yaml.in/yaml/v2 v2.4.3 // indirect
|
||||
golang.org/x/crypto v0.46.0 // indirect
|
||||
golang.org/x/net v0.48.0 // indirect
|
||||
golang.org/x/sync v0.19.0 // indirect
|
||||
golang.org/x/sys v0.39.0 // indirect
|
||||
golang.org/x/text v0.32.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect
|
||||
google.golang.org/grpc v1.78.0 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
)
|
||||
225
api/discovery/go.sum
Normal file
225
api/discovery/go.sum
Normal file
@@ -0,0 +1,225 @@
|
||||
dario.cat/mergo v1.0.1 h1:Ra4+bf83h2ztPIQYNP99R6m+Y7KfnARDfID+a+vLl4s=
|
||||
dario.cat/mergo v1.0.1/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk=
|
||||
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0=
|
||||
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
|
||||
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
|
||||
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/bmatcuk/doublestar/v4 v4.6.1/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc=
|
||||
github.com/bmatcuk/doublestar/v4 v4.9.1 h1:X8jg9rRZmJd4yRy7ZeNDRnM+T3ZfHv15JiBJ/avrEXE=
|
||||
github.com/bmatcuk/doublestar/v4 v4.9.1/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc=
|
||||
github.com/casbin/casbin/v2 v2.135.0 h1:6BLkMQiGotYyS5yYeWgW19vxqugUlvHFkFiLnLR/bxk=
|
||||
github.com/casbin/casbin/v2 v2.135.0/go.mod h1:FmcfntdXLTcYXv/hxgNntcRPqAbwOG9xsism0yXT+18=
|
||||
github.com/casbin/govaluate v1.3.0/go.mod h1:G/UnbIjZk/0uMNaLwZZmFQrR72tYRZWQkO70si/iR7A=
|
||||
github.com/casbin/govaluate v1.10.0 h1:ffGw51/hYH3w3rZcxO/KcaUIDOLP84w7nsidMVgaDG0=
|
||||
github.com/casbin/govaluate v1.10.0/go.mod h1:G/UnbIjZk/0uMNaLwZZmFQrR72tYRZWQkO70si/iR7A=
|
||||
github.com/casbin/mongodb-adapter/v3 v3.7.0 h1:w9c3bea1BGK4eZTAmk17JkY52yv/xSZDSHKji8q+z6E=
|
||||
github.com/casbin/mongodb-adapter/v3 v3.7.0/go.mod h1:F1mu4ojoJVE/8VhIMxMedhjfwRDdIXgANYs6Sd0MgVA=
|
||||
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
|
||||
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I=
|
||||
github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo=
|
||||
github.com/containerd/platforms v0.2.1 h1:zvwtM3rz2YHPQsF2CHYM8+KtB5dvhISiXh5ZpSBQv6A=
|
||||
github.com/containerd/platforms v0.2.1/go.mod h1:XHCb+2/hzowdiut9rkudds9bE5yJ7npe7dG/wG+uFPw=
|
||||
github.com/cpuguy83/dockercfg v0.3.2 h1:DlJTyZGBDlXqUZ2Dk2Q3xHs/FtnooJJVaad2S9GKorA=
|
||||
github.com/cpuguy83/dockercfg v0.3.2/go.mod h1:sugsbF4//dDlL/i+S+rtpIWp+5h0BHJHfjj5/jFyUJc=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
|
||||
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
|
||||
github.com/docker/docker v27.3.1+incompatible h1:KttF0XoteNTicmUtBO0L2tP+J7FGRFTjaEF4k6WdhfI=
|
||||
github.com/docker/docker v27.3.1+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
|
||||
github.com/docker/go-connections v0.5.0 h1:USnMq7hx7gwdVZq1L49hLXaFtUdTADjXGp+uj1Br63c=
|
||||
github.com/docker/go-connections v0.5.0/go.mod h1:ov60Kzw0kKElRwhNs9UlUHAE/F9Fe6GLaXnqyDdmEXc=
|
||||
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
|
||||
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
|
||||
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
|
||||
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
|
||||
github.com/go-chi/chi/v5 v5.2.3 h1:WQIt9uxdsAbgIYgid+BpYc+liqQZGMHRaUwp0JUcvdE=
|
||||
github.com/go-chi/chi/v5 v5.2.3/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
|
||||
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
|
||||
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
|
||||
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
|
||||
github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4=
|
||||
github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc=
|
||||
github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs=
|
||||
github.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/klauspost/compress v1.18.2 h1:iiPHWW0YrcFgpBYhsA6D1+fqHssJscY/Tm/y2Uqnapk=
|
||||
github.com/klauspost/compress v1.18.2/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
|
||||
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
||||
github.com/lufia/plan9stats v0.0.0-20250827001030-24949be3fa54 h1:mFWunSatvkQQDhpdyuFAYwyAan3hzCuma+Pz8sqvOfg=
|
||||
github.com/lufia/plan9stats v0.0.0-20250827001030-24949be3fa54/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg=
|
||||
github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
|
||||
github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
|
||||
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
|
||||
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
|
||||
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
|
||||
github.com/moby/patternmatcher v0.6.0 h1:GmP9lR19aU5GqSSFko+5pRqHi+Ohk1O69aFiKkVGiPk=
|
||||
github.com/moby/patternmatcher v0.6.0/go.mod h1:hDPoyOpDY7OrrMDLaYoY3hf52gNCR/YOUYxkhApJIxc=
|
||||
github.com/moby/sys/sequential v0.6.0 h1:qrx7XFUd/5DxtqcoH1h438hF5TmOvzC/lspjy7zgvCU=
|
||||
github.com/moby/sys/sequential v0.6.0/go.mod h1:uyv8EUTrca5PnDsdMGXhZe6CCe8U/UiTWd+lL+7b/Ko=
|
||||
github.com/moby/sys/user v0.3.0 h1:9ni5DlcW5an3SvRSx4MouotOygvzaXbaSrc/wGDFWPo=
|
||||
github.com/moby/sys/user v0.3.0/go.mod h1:bG+tYYYJgaMtRKgEmuueC0hJEAZWwtIbZTB+85uoHjs=
|
||||
github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/g=
|
||||
github.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28=
|
||||
github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0=
|
||||
github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y=
|
||||
github.com/montanaflynn/stats v0.7.1 h1:etflOAAHORrCC44V+aR6Ftzort912ZU+YLiSTuV8eaE=
|
||||
github.com/montanaflynn/stats v0.7.1/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow=
|
||||
github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=
|
||||
github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||
github.com/nats-io/nats.go v1.48.0 h1:pSFyXApG+yWU/TgbKCjmm5K4wrHu86231/w84qRVR+U=
|
||||
github.com/nats-io/nats.go v1.48.0/go.mod h1:iRWIPokVIFbVijxuMQq4y9ttaBTMe0SFdlZfMDd+33g=
|
||||
github.com/nats-io/nkeys v0.4.12 h1:nssm7JKOG9/x4J8II47VWCL1Ds29avyiQDRn0ckMvDc=
|
||||
github.com/nats-io/nkeys v0.4.12/go.mod h1:MT59A1HYcjIcyQDJStTfaOY6vhy9XTUjOFo+SVsvpBg=
|
||||
github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=
|
||||
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
|
||||
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
|
||||
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
|
||||
github.com/opencontainers/image-spec v1.1.0 h1:8SG7/vwALn54lVB/0yZ/MMwhFrPYtpEHQb2IpWsCzug=
|
||||
github.com/opencontainers/image-spec v1.1.0/go.mod h1:W4s4sFTMaBeK1BQLXbG4AdM2szdn85PY75RI83NrTrM=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=
|
||||
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
|
||||
github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
|
||||
github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
|
||||
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
|
||||
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
|
||||
github.com/prometheus/common v0.67.4 h1:yR3NqWO1/UyO1w2PhUvXlGQs/PtFmoveVO0KZ4+Lvsc=
|
||||
github.com/prometheus/common v0.67.4/go.mod h1:gP0fq6YjjNCLssJCQp0yk4M8W6ikLURwkdd/YKtTbyI=
|
||||
github.com/prometheus/procfs v0.19.2 h1:zUMhqEW66Ex7OXIiDkll3tl9a1ZdilUOd/F6ZXw4Vws=
|
||||
github.com/prometheus/procfs v0.19.2/go.mod h1:M0aotyiemPhBCM0z5w87kL22CxfcH05ZpYlu+b4J7mw=
|
||||
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
|
||||
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
|
||||
github.com/shirou/gopsutil/v3 v3.24.5 h1:i0t8kL+kQTvpAYToeuiVk3TgDeKOFioZO3Ztz/iZ9pI=
|
||||
github.com/shirou/gopsutil/v3 v3.24.5/go.mod h1:bsoOS1aStSs9ErQ1WWfxllSeS1K5D+U30r2NfcubMVk=
|
||||
github.com/shoenig/go-m1cpu v0.1.6 h1:nxdKQNcEB6vzgA2E2bvzKIYRuNj7XNJ4S/aRSwKzFtM=
|
||||
github.com/shoenig/go-m1cpu v0.1.6/go.mod h1:1JJMcUBvfNwpq05QDQVAnx3gUHr9IYF7GNg9SUEw2VQ=
|
||||
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
|
||||
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/testcontainers/testcontainers-go v0.33.0 h1:zJS9PfXYT5O0ZFXM2xxXfk4J5UMw/kRiISng037Gxdw=
|
||||
github.com/testcontainers/testcontainers-go v0.33.0/go.mod h1:W80YpTa8D5C3Yy16icheD01UTDu+LmXIA2Keo+jWtT8=
|
||||
github.com/testcontainers/testcontainers-go/modules/mongodb v0.33.0 h1:iXVA84s5hKMS5gn01GWOYHE3ymy/2b+0YkpFeTxB2XY=
|
||||
github.com/testcontainers/testcontainers-go/modules/mongodb v0.33.0/go.mod h1:R6tMjTojRiaoo89fh/hf7tOmfzohdqSU17R9DwSVSog=
|
||||
github.com/tklauser/go-sysconf v0.3.15 h1:VE89k0criAymJ/Os65CSn1IXaol+1wrsFHEB8Ol49K4=
|
||||
github.com/tklauser/go-sysconf v0.3.15/go.mod h1:Dmjwr6tYFIseJw7a3dRLJfsHAMXZ3nEnL/aZY+0IuI4=
|
||||
github.com/tklauser/numcpus v0.10.0 h1:18njr6LDBk1zuna922MgdjQuJFjrdppsZG60sHGfjso=
|
||||
github.com/tklauser/numcpus v0.10.0/go.mod h1:BiTKazU708GQTYF4mB+cmlpT2Is1gLk7XVuEeem8LsQ=
|
||||
github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=
|
||||
github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI=
|
||||
github.com/xdg-go/scram v1.2.0 h1:bYKF2AEwG5rqd1BumT4gAnvwU/M9nBp2pTSxeZw7Wvs=
|
||||
github.com/xdg-go/scram v1.2.0/go.mod h1:3dlrS0iBaWKYVt2ZfA4cj48umJZ+cAEbR6/SjLA88I8=
|
||||
github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8=
|
||||
github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM=
|
||||
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zUTJ0trRztfwgjqKnBWNtSRkbmwM=
|
||||
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
|
||||
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
|
||||
go.mongodb.org/mongo-driver v1.17.6 h1:87JUG1wZfWsr6rIz3ZmpH90rL5tea7O3IHuSwHUpsss=
|
||||
go.mongodb.org/mongo-driver v1.17.6/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.56.0 h1:UP6IpuHFkUgOQL9FFQFrZ+5LiwhhYRbi7VZSIx6Nj5s=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.56.0/go.mod h1:qxuZLtbq5QDtdeSHsS7bcf6EH6uO6jUAgk764zd3rhM=
|
||||
go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8=
|
||||
go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM=
|
||||
go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA=
|
||||
go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI=
|
||||
go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E=
|
||||
go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.38.0/go.mod h1:dg9PBnW9XdQ1Hd6ZnRz689CbtrUp0wMMs9iPcgT9EZA=
|
||||
go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE=
|
||||
go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||
go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=
|
||||
go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
|
||||
go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=
|
||||
go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
|
||||
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
|
||||
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
|
||||
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
||||
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
|
||||
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
|
||||
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
|
||||
gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=
|
||||
google.golang.org/grpc v1.78.0 h1:K1XZG/yGDJnzMdd/uZHAkVqJE+xIDOcmdSFZkBUicNc=
|
||||
google.golang.org/grpc v1.78.0/go.mod h1:I47qjTo4OKbMkjA/aOOwxDIiPSBofUtQUI5EfpWvW7U=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
27
api/discovery/internal/appversion/version.go
Normal file
27
api/discovery/internal/appversion/version.go
Normal file
@@ -0,0 +1,27 @@
|
||||
package appversion
|
||||
|
||||
import (
|
||||
"github.com/tech/sendico/pkg/version"
|
||||
vf "github.com/tech/sendico/pkg/version/factory"
|
||||
)
|
||||
|
||||
// Build information. Populated at build-time.
|
||||
var (
|
||||
Version string
|
||||
Revision string
|
||||
Branch string
|
||||
BuildUser string
|
||||
BuildDate string
|
||||
)
|
||||
|
||||
func Create() version.Printer {
|
||||
vi := version.Info{
|
||||
Program: "Sendico Discovery Service",
|
||||
Revision: Revision,
|
||||
Branch: Branch,
|
||||
BuildUser: BuildUser,
|
||||
BuildDate: BuildDate,
|
||||
Version: Version,
|
||||
}
|
||||
return vf.Create(&vi)
|
||||
}
|
||||
47
api/discovery/internal/server/internal/config.go
Normal file
47
api/discovery/internal/server/internal/config.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package serverimp
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
msg "github.com/tech/sendico/pkg/messaging"
|
||||
"github.com/tech/sendico/pkg/server/grpcapp"
|
||||
"go.uber.org/zap"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
const defaultMetricsAddress = ":9405"
|
||||
|
||||
type config struct {
|
||||
Runtime *grpcapp.RuntimeConfig `yaml:"runtime"`
|
||||
Messaging *msg.Config `yaml:"messaging"`
|
||||
Metrics *metricsConfig `yaml:"metrics"`
|
||||
}
|
||||
|
||||
type metricsConfig struct {
|
||||
Address string `yaml:"address"`
|
||||
}
|
||||
|
||||
func (i *Imp) loadConfig() (*config, error) {
|
||||
data, err := os.ReadFile(i.file)
|
||||
if err != nil {
|
||||
i.logger.Error("Could not read configuration file", zap.String("config_file", i.file), zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cfg := &config{}
|
||||
if err := yaml.Unmarshal(data, cfg); err != nil {
|
||||
i.logger.Error("Failed to parse configuration", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if cfg.Runtime == nil {
|
||||
cfg.Runtime = &grpcapp.RuntimeConfig{ShutdownTimeoutSeconds: 15}
|
||||
}
|
||||
|
||||
if cfg.Metrics != nil && strings.TrimSpace(cfg.Metrics.Address) == "" {
|
||||
cfg.Metrics.Address = defaultMetricsAddress
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
58
api/discovery/internal/server/internal/discovery.go
Normal file
58
api/discovery/internal/server/internal/discovery.go
Normal file
@@ -0,0 +1,58 @@
|
||||
package serverimp
|
||||
|
||||
import (
|
||||
"github.com/tech/sendico/discovery/internal/appversion"
|
||||
"github.com/tech/sendico/pkg/discovery"
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
msg "github.com/tech/sendico/pkg/messaging"
|
||||
msgproducer "github.com/tech/sendico/pkg/messaging/producer"
|
||||
"github.com/tech/sendico/pkg/mservice"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func (i *Imp) startDiscovery(cfg *config) error {
|
||||
if cfg == nil || cfg.Messaging == nil || cfg.Messaging.Driver == "" {
|
||||
return merrors.InvalidArgument("discovery service: messaging configuration is required", "messaging")
|
||||
}
|
||||
|
||||
broker, err := msg.CreateMessagingBroker(i.logger.Named("discovery_bus"), cfg.Messaging)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
i.logger.Info("Discovery messaging broker ready", zap.String("messaging_driver", string(cfg.Messaging.Driver)))
|
||||
producer := msgproducer.NewProducer(i.logger.Named("discovery_producer"), broker)
|
||||
|
||||
registry := discovery.NewRegistry()
|
||||
svc, err := discovery.NewRegistryService(i.logger, broker, producer, registry, string(mservice.Discovery))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
svc.Start()
|
||||
i.registrySvc = svc
|
||||
|
||||
announce := discovery.Announcement{
|
||||
Service: "DISCOVERY",
|
||||
InstanceID: discovery.InstanceID(),
|
||||
Operations: []string{"discovery.lookup"},
|
||||
Version: appversion.Create().Short(),
|
||||
}
|
||||
i.announcer = discovery.NewAnnouncer(i.logger, producer, string(mservice.Discovery), announce)
|
||||
i.announcer.Start()
|
||||
|
||||
i.logger.Info("Discovery registry service started", zap.String("messaging_driver", string(cfg.Messaging.Driver)))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i *Imp) stopDiscovery() {
|
||||
if i == nil {
|
||||
return
|
||||
}
|
||||
if i.announcer != nil {
|
||||
i.announcer.Stop()
|
||||
i.announcer = nil
|
||||
}
|
||||
if i.registrySvc != nil {
|
||||
i.registrySvc.Stop()
|
||||
i.registrySvc = nil
|
||||
}
|
||||
}
|
||||
85
api/discovery/internal/server/internal/metrics.go
Normal file
85
api/discovery/internal/server/internal/metrics.go
Normal file
@@ -0,0 +1,85 @@
|
||||
package serverimp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
"github.com/tech/sendico/pkg/api/routers"
|
||||
"github.com/tech/sendico/pkg/api/routers/health"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func (i *Imp) startMetrics(cfg *metricsConfig) {
|
||||
if i == nil {
|
||||
return
|
||||
}
|
||||
address := ""
|
||||
if cfg != nil {
|
||||
address = strings.TrimSpace(cfg.Address)
|
||||
}
|
||||
if address == "" {
|
||||
i.logger.Info("Metrics endpoint disabled")
|
||||
return
|
||||
}
|
||||
|
||||
listener, err := net.Listen("tcp", address)
|
||||
if err != nil {
|
||||
i.logger.Error("Failed to bind metrics listener", zap.String("address", address), zap.Error(err))
|
||||
return
|
||||
}
|
||||
|
||||
router := chi.NewRouter()
|
||||
router.Handle("/metrics", promhttp.Handler())
|
||||
|
||||
var healthRouter routers.Health
|
||||
if hr, err := routers.NewHealthRouter(i.logger.Named("metrics"), router, ""); err != nil {
|
||||
i.logger.Warn("Failed to initialise health router", zap.Error(err))
|
||||
} else {
|
||||
hr.SetStatus(health.SSStarting)
|
||||
healthRouter = hr
|
||||
}
|
||||
|
||||
i.metricsHealth = healthRouter
|
||||
i.metricsSrv = &http.Server{
|
||||
Addr: address,
|
||||
Handler: router,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
}
|
||||
|
||||
if healthRouter != nil {
|
||||
healthRouter.SetStatus(health.SSRunning)
|
||||
}
|
||||
|
||||
go func() {
|
||||
i.logger.Info("Prometheus endpoint listening", zap.String("address", address))
|
||||
if err := i.metricsSrv.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
i.logger.Error("Prometheus endpoint stopped unexpectedly", zap.Error(err))
|
||||
if healthRouter != nil {
|
||||
healthRouter.SetStatus(health.SSTerminating)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (i *Imp) shutdownMetrics(ctx context.Context) {
|
||||
if i.metricsHealth != nil {
|
||||
i.metricsHealth.SetStatus(health.SSTerminating)
|
||||
i.metricsHealth.Finish()
|
||||
i.metricsHealth = nil
|
||||
}
|
||||
if i.metricsSrv == nil {
|
||||
return
|
||||
}
|
||||
if err := i.metricsSrv.Shutdown(ctx); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
i.logger.Warn("Failed to stop metrics server", zap.Error(err))
|
||||
} else {
|
||||
i.logger.Info("Metrics server stopped")
|
||||
}
|
||||
i.metricsSrv = nil
|
||||
}
|
||||
109
api/discovery/internal/server/internal/serverimp.go
Normal file
109
api/discovery/internal/server/internal/serverimp.go
Normal file
@@ -0,0 +1,109 @@
|
||||
package serverimp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/tech/sendico/pkg/mlogger"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func Create(logger mlogger.Logger, file string, debug bool) (*Imp, error) {
|
||||
return &Imp{
|
||||
logger: logger.Named("server"),
|
||||
file: file,
|
||||
debug: debug,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (i *Imp) Start() error {
|
||||
i.initStopChannels()
|
||||
defer i.closeDone()
|
||||
|
||||
i.logger.Info("Starting discovery service", zap.String("config_file", i.file), zap.Bool("debug", i.debug))
|
||||
|
||||
cfg, err := i.loadConfig()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
i.config = cfg
|
||||
|
||||
messagingDriver := "none"
|
||||
if cfg.Messaging != nil {
|
||||
messagingDriver = string(cfg.Messaging.Driver)
|
||||
}
|
||||
metricsAddress := ""
|
||||
if cfg.Metrics != nil {
|
||||
metricsAddress = strings.TrimSpace(cfg.Metrics.Address)
|
||||
}
|
||||
if metricsAddress == "" {
|
||||
metricsAddress = "disabled"
|
||||
}
|
||||
i.logger.Info("Discovery config loaded", zap.String("messaging_driver", messagingDriver), zap.String("metrics_address", metricsAddress))
|
||||
|
||||
i.startMetrics(cfg.Metrics)
|
||||
|
||||
if err := i.startDiscovery(cfg); err != nil {
|
||||
i.stopDiscovery()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), i.shutdownTimeout())
|
||||
i.shutdownMetrics(ctx)
|
||||
cancel()
|
||||
return err
|
||||
}
|
||||
|
||||
i.logger.Info("Discovery service ready", zap.String("messaging_driver", messagingDriver))
|
||||
|
||||
<-i.stopCh
|
||||
i.logger.Info("Discovery service stop signal received")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i *Imp) Shutdown() {
|
||||
timeout := i.shutdownTimeout()
|
||||
i.logger.Info("Stopping discovery service", zap.Duration("timeout", timeout))
|
||||
|
||||
i.stopDiscovery()
|
||||
i.signalStop()
|
||||
|
||||
if i.doneCh != nil {
|
||||
<-i.doneCh
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
i.shutdownMetrics(ctx)
|
||||
cancel()
|
||||
|
||||
i.logger.Info("Discovery service stopped")
|
||||
}
|
||||
|
||||
func (i *Imp) initStopChannels() {
|
||||
if i.stopCh == nil {
|
||||
i.stopCh = make(chan struct{})
|
||||
}
|
||||
if i.doneCh == nil {
|
||||
i.doneCh = make(chan struct{})
|
||||
}
|
||||
}
|
||||
|
||||
func (i *Imp) signalStop() {
|
||||
i.stopOnce.Do(func() {
|
||||
if i.stopCh != nil {
|
||||
close(i.stopCh)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (i *Imp) closeDone() {
|
||||
i.doneOnce.Do(func() {
|
||||
if i.doneCh != nil {
|
||||
close(i.doneCh)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (i *Imp) shutdownTimeout() time.Duration {
|
||||
if i.config != nil && i.config.Runtime != nil {
|
||||
return i.config.Runtime.ShutdownTimeout()
|
||||
}
|
||||
return 15 * time.Second
|
||||
}
|
||||
28
api/discovery/internal/server/internal/types.go
Normal file
28
api/discovery/internal/server/internal/types.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package serverimp
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync"
|
||||
|
||||
"github.com/tech/sendico/pkg/api/routers"
|
||||
"github.com/tech/sendico/pkg/discovery"
|
||||
"github.com/tech/sendico/pkg/mlogger"
|
||||
)
|
||||
|
||||
type Imp struct {
|
||||
logger mlogger.Logger
|
||||
file string
|
||||
debug bool
|
||||
|
||||
config *config
|
||||
registrySvc *discovery.RegistryService
|
||||
announcer *discovery.Announcer
|
||||
|
||||
metricsSrv *http.Server
|
||||
metricsHealth routers.Health
|
||||
|
||||
stopOnce sync.Once
|
||||
doneOnce sync.Once
|
||||
stopCh chan struct{}
|
||||
doneCh chan struct{}
|
||||
}
|
||||
11
api/discovery/internal/server/server.go
Normal file
11
api/discovery/internal/server/server.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
serverimp "github.com/tech/sendico/discovery/internal/server/internal"
|
||||
"github.com/tech/sendico/pkg/mlogger"
|
||||
"github.com/tech/sendico/pkg/server"
|
||||
)
|
||||
|
||||
func Create(logger mlogger.Logger, file string, debug bool) (server.Application, error) {
|
||||
return serverimp.Create(logger, file, debug)
|
||||
}
|
||||
17
api/discovery/main.go
Normal file
17
api/discovery/main.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/tech/sendico/discovery/internal/appversion"
|
||||
si "github.com/tech/sendico/discovery/internal/server"
|
||||
"github.com/tech/sendico/pkg/mlogger"
|
||||
"github.com/tech/sendico/pkg/server"
|
||||
smain "github.com/tech/sendico/pkg/server/main"
|
||||
)
|
||||
|
||||
func factory(logger mlogger.Logger, file string, debug bool) (server.Application, error) {
|
||||
return si.Create(logger, file, debug)
|
||||
}
|
||||
|
||||
func main() {
|
||||
smain.RunServer("main", appversion.Create(), factory)
|
||||
}
|
||||
@@ -49,6 +49,18 @@ metrics:
|
||||
enabled: true
|
||||
address: ":9102"
|
||||
|
||||
messaging:
|
||||
driver: NATS
|
||||
settings:
|
||||
url_env: NATS_URL
|
||||
host_env: NATS_HOST
|
||||
port_env: NATS_PORT
|
||||
username_env: NATS_USER
|
||||
password_env: NATS_PASSWORD
|
||||
broker_name: FX Ingestor
|
||||
max_reconnects: 10
|
||||
reconnect_wait: 5
|
||||
|
||||
database:
|
||||
driver: mongodb
|
||||
settings:
|
||||
|
||||
@@ -12,7 +12,10 @@ import (
|
||||
mongostorage "github.com/tech/sendico/fx/storage/mongo"
|
||||
"github.com/tech/sendico/pkg/api/routers/health"
|
||||
"github.com/tech/sendico/pkg/db"
|
||||
"github.com/tech/sendico/pkg/discovery"
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
msg "github.com/tech/sendico/pkg/messaging"
|
||||
msgproducer "github.com/tech/sendico/pkg/messaging/producer"
|
||||
"github.com/tech/sendico/pkg/mlogger"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
@@ -68,6 +71,24 @@ func (a *App) Run(ctx context.Context) error {
|
||||
return err
|
||||
}
|
||||
|
||||
var announcer *discovery.Announcer
|
||||
if cfg := a.cfg.Messaging; cfg != nil && cfg.Driver != "" {
|
||||
broker, err := msg.CreateMessagingBroker(a.logger.Named("discovery_bus"), cfg)
|
||||
if err != nil {
|
||||
a.logger.Warn("Failed to initialize discovery broker", zap.Error(err))
|
||||
} else {
|
||||
producer := msgproducer.NewProducer(a.logger.Named("discovery_producer"), broker)
|
||||
announce := discovery.Announcement{
|
||||
Service: "FX_INGESTOR",
|
||||
Operations: []string{"fx.ingest"},
|
||||
Version: appversion.Create().Short(),
|
||||
}
|
||||
announcer = discovery.NewAnnouncer(a.logger, producer, "fx_ingestor", announce)
|
||||
announcer.Start()
|
||||
defer announcer.Stop()
|
||||
}
|
||||
}
|
||||
|
||||
a.logger.Info("Starting FX ingestor service", zap.String("version", appversion.Create().Info()))
|
||||
metricsSrv.SetStatus(health.SSRunning)
|
||||
|
||||
|
||||
@@ -8,16 +8,18 @@ import (
|
||||
mmodel "github.com/tech/sendico/fx/ingestor/internal/model"
|
||||
"github.com/tech/sendico/pkg/db"
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
"github.com/tech/sendico/pkg/messaging"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
const defaultPollInterval = 30 * time.Second
|
||||
|
||||
type Config struct {
|
||||
PollIntervalSeconds int `yaml:"poll_interval_seconds"`
|
||||
Market MarketConfig `yaml:"market"`
|
||||
Database *db.Config `yaml:"database"`
|
||||
Metrics *MetricsConfig `yaml:"metrics"`
|
||||
PollIntervalSeconds int `yaml:"poll_interval_seconds"`
|
||||
Market MarketConfig `yaml:"market"`
|
||||
Database *db.Config `yaml:"database"`
|
||||
Metrics *MetricsConfig `yaml:"metrics"`
|
||||
Messaging *messaging.Config `yaml:"messaging"`
|
||||
|
||||
pairs []Pair
|
||||
pairsBySource map[mmodel.Driver][]PairConfig
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"github.com/tech/sendico/fx/ingestor/internal/app"
|
||||
"github.com/tech/sendico/fx/ingestor/internal/appversion"
|
||||
"github.com/tech/sendico/fx/ingestor/internal/signalctx"
|
||||
"github.com/tech/sendico/pkg/discovery"
|
||||
lf "github.com/tech/sendico/pkg/mlogger/factory"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
@@ -25,6 +26,7 @@ func main() {
|
||||
flag.Parse()
|
||||
|
||||
logger := lf.NewLogger(*debugFlag).Named("fx_ingestor")
|
||||
logger = logger.With(zap.String("instance_id", discovery.InstanceID()))
|
||||
defer logger.Sync()
|
||||
|
||||
av := appversion.Create()
|
||||
|
||||
@@ -22,8 +22,9 @@ type Imp struct {
|
||||
file string
|
||||
debug bool
|
||||
|
||||
config *grpcapp.Config
|
||||
app *grpcapp.App[storage.Repository]
|
||||
config *grpcapp.Config
|
||||
app *grpcapp.App[storage.Repository]
|
||||
service *oracle.Service
|
||||
}
|
||||
|
||||
func Create(logger mlogger.Logger, file string, debug bool) (*Imp, error) {
|
||||
@@ -38,6 +39,9 @@ func (i *Imp) Shutdown() {
|
||||
if i.app == nil {
|
||||
return
|
||||
}
|
||||
if i.service != nil {
|
||||
i.service.Shutdown()
|
||||
}
|
||||
timeout := 15 * time.Second
|
||||
if i.config != nil && i.config.Runtime != nil {
|
||||
timeout = i.config.Runtime.ShutdownTimeout()
|
||||
@@ -59,10 +63,12 @@ func (i *Imp) Start() error {
|
||||
}
|
||||
|
||||
serviceFactory := func(logger mlogger.Logger, repo storage.Repository, producer msg.Producer) (grpcapp.Service, error) {
|
||||
return oracle.NewService(logger, repo, producer), nil
|
||||
svc := oracle.NewService(logger, repo, producer)
|
||||
i.service = svc
|
||||
return svc, nil
|
||||
}
|
||||
|
||||
app, err := grpcapp.NewApp(i.logger, "fx_oracle", cfg, i.debug, repoFactory, serviceFactory)
|
||||
app, err := grpcapp.NewApp(i.logger, "fx", cfg, i.debug, repoFactory, serviceFactory)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -6,10 +6,12 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/tech/sendico/fx/oracle/internal/appversion"
|
||||
"github.com/tech/sendico/fx/storage"
|
||||
"github.com/tech/sendico/fx/storage/model"
|
||||
"github.com/tech/sendico/pkg/api/routers"
|
||||
"github.com/tech/sendico/pkg/api/routers/gsresponse"
|
||||
"github.com/tech/sendico/pkg/discovery"
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
pmessaging "github.com/tech/sendico/pkg/messaging"
|
||||
"github.com/tech/sendico/pkg/mlogger"
|
||||
@@ -36,19 +38,22 @@ var (
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
logger mlogger.Logger
|
||||
storage storage.Repository
|
||||
producer pmessaging.Producer
|
||||
logger mlogger.Logger
|
||||
storage storage.Repository
|
||||
producer pmessaging.Producer
|
||||
announcer *discovery.Announcer
|
||||
oraclev1.UnimplementedOracleServer
|
||||
}
|
||||
|
||||
func NewService(logger mlogger.Logger, repo storage.Repository, prod pmessaging.Producer) *Service {
|
||||
initMetrics()
|
||||
return &Service{
|
||||
svc := &Service{
|
||||
logger: logger.Named("oracle"),
|
||||
storage: repo,
|
||||
producer: prod,
|
||||
}
|
||||
svc.startDiscoveryAnnouncer()
|
||||
return svc
|
||||
}
|
||||
|
||||
func (s *Service) Register(router routers.GRPC) error {
|
||||
@@ -57,6 +62,28 @@ func (s *Service) Register(router routers.GRPC) error {
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) Shutdown() {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
if s.announcer != nil {
|
||||
s.announcer.Stop()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) startDiscoveryAnnouncer() {
|
||||
if s == nil || s.producer == nil {
|
||||
return
|
||||
}
|
||||
announce := discovery.Announcement{
|
||||
Service: "FX_ORACLE",
|
||||
Operations: []string{"fx.quote"},
|
||||
Version: appversion.Create().Short(),
|
||||
}
|
||||
s.announcer = discovery.NewAnnouncer(s.logger, s.producer, string(mservice.FXOracle), announce)
|
||||
s.announcer.Start()
|
||||
}
|
||||
|
||||
func (s *Service) GetQuote(ctx context.Context, req *oraclev1.GetQuoteRequest) (*oraclev1.GetQuoteResponse, error) {
|
||||
start := time.Now()
|
||||
responder := s.getQuoteResponder(ctx, req)
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
chainv1 "github.com/tech/sendico/pkg/proto/gateway/chain/v1"
|
||||
unifiedv1 "github.com/tech/sendico/pkg/proto/gateway/unified/v1"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
@@ -75,7 +76,7 @@ func New(ctx context.Context, cfg Config, opts ...grpc.DialOption) (Client, erro
|
||||
return &chainGatewayClient{
|
||||
cfg: cfg,
|
||||
conn: conn,
|
||||
client: chainv1.NewChainGatewayServiceClient(conn),
|
||||
client: unifiedv1.NewUnifiedGatewayServiceClient(conn),
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
258
api/gateway/chain/client/rail_gateway.go
Normal file
258
api/gateway/chain/client/rail_gateway.go
Normal file
@@ -0,0 +1,258 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
"github.com/tech/sendico/pkg/payments/rail"
|
||||
moneyv1 "github.com/tech/sendico/pkg/proto/common/money/v1"
|
||||
chainv1 "github.com/tech/sendico/pkg/proto/gateway/chain/v1"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// RailGatewayConfig defines metadata for the rail gateway adapter.
|
||||
type RailGatewayConfig struct {
|
||||
Rail string
|
||||
Network string
|
||||
Capabilities rail.RailCapabilities
|
||||
}
|
||||
|
||||
type chainRailGateway struct {
|
||||
client Client
|
||||
rail string
|
||||
network string
|
||||
capabilities rail.RailCapabilities
|
||||
}
|
||||
|
||||
// NewRailGateway wraps a chain gateway client into a rail gateway adapter.
|
||||
func NewRailGateway(client Client, cfg RailGatewayConfig) rail.RailGateway {
|
||||
railName := strings.ToUpper(strings.TrimSpace(cfg.Rail))
|
||||
if railName == "" {
|
||||
railName = "CRYPTO"
|
||||
}
|
||||
return &chainRailGateway{
|
||||
client: client,
|
||||
rail: railName,
|
||||
network: strings.ToUpper(strings.TrimSpace(cfg.Network)),
|
||||
capabilities: cfg.Capabilities,
|
||||
}
|
||||
}
|
||||
|
||||
func (g *chainRailGateway) Rail() string {
|
||||
return g.rail
|
||||
}
|
||||
|
||||
func (g *chainRailGateway) Network() string {
|
||||
return g.network
|
||||
}
|
||||
|
||||
func (g *chainRailGateway) Capabilities() rail.RailCapabilities {
|
||||
return g.capabilities
|
||||
}
|
||||
|
||||
func (g *chainRailGateway) Send(ctx context.Context, req rail.TransferRequest) (rail.RailResult, error) {
|
||||
if g.client == nil {
|
||||
return rail.RailResult{}, merrors.Internal("chain gateway: client is required")
|
||||
}
|
||||
orgRef := strings.TrimSpace(req.OrganizationRef)
|
||||
if orgRef == "" {
|
||||
return rail.RailResult{}, merrors.InvalidArgument("chain gateway: organization_ref is required")
|
||||
}
|
||||
source := strings.TrimSpace(req.FromAccountID)
|
||||
if source == "" {
|
||||
return rail.RailResult{}, merrors.InvalidArgument("chain gateway: from_account_id is required")
|
||||
}
|
||||
destRef := strings.TrimSpace(req.ToAccountID)
|
||||
if destRef == "" {
|
||||
return rail.RailResult{}, merrors.InvalidArgument("chain gateway: to_account_id is required")
|
||||
}
|
||||
currency := strings.TrimSpace(req.Currency)
|
||||
amountValue := strings.TrimSpace(req.Amount)
|
||||
if currency == "" || amountValue == "" {
|
||||
return rail.RailResult{}, merrors.InvalidArgument("chain gateway: amount is required")
|
||||
}
|
||||
reqNetwork := strings.TrimSpace(req.Network)
|
||||
if g.network != "" && reqNetwork != "" && !strings.EqualFold(g.network, reqNetwork) {
|
||||
return rail.RailResult{}, merrors.InvalidArgument("chain gateway: network mismatch")
|
||||
}
|
||||
if strings.TrimSpace(req.IdempotencyKey) == "" {
|
||||
return rail.RailResult{}, merrors.InvalidArgument("chain gateway: idempotency_key is required")
|
||||
}
|
||||
|
||||
dest, err := g.resolveDestination(ctx, destRef, strings.TrimSpace(req.DestinationMemo))
|
||||
if err != nil {
|
||||
return rail.RailResult{}, err
|
||||
}
|
||||
|
||||
fees := toServiceFees(req.Fees)
|
||||
if len(fees) == 0 && req.Fee != nil {
|
||||
if amt := moneyFromRail(req.Fee); amt != nil {
|
||||
fees = []*chainv1.ServiceFeeBreakdown{{
|
||||
FeeCode: "fee",
|
||||
Amount: amt,
|
||||
}}
|
||||
}
|
||||
}
|
||||
|
||||
resp, err := g.client.SubmitTransfer(ctx, &chainv1.SubmitTransferRequest{
|
||||
IdempotencyKey: strings.TrimSpace(req.IdempotencyKey),
|
||||
OrganizationRef: orgRef,
|
||||
SourceWalletRef: source,
|
||||
Destination: dest,
|
||||
Amount: &moneyv1.Money{
|
||||
Currency: currency,
|
||||
Amount: amountValue,
|
||||
},
|
||||
Fees: fees,
|
||||
Metadata: cloneMetadata(req.Metadata),
|
||||
ClientReference: strings.TrimSpace(req.ClientReference),
|
||||
})
|
||||
if err != nil {
|
||||
return rail.RailResult{}, err
|
||||
}
|
||||
if resp == nil || resp.GetTransfer() == nil {
|
||||
return rail.RailResult{}, merrors.Internal("chain gateway: missing transfer response")
|
||||
}
|
||||
|
||||
transfer := resp.GetTransfer()
|
||||
return rail.RailResult{
|
||||
ReferenceID: strings.TrimSpace(transfer.GetTransferRef()),
|
||||
Status: statusFromTransfer(transfer.GetStatus()),
|
||||
FinalAmount: railMoneyFromProto(transfer.GetNetAmount()),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (g *chainRailGateway) Observe(ctx context.Context, referenceID string) (rail.ObserveResult, error) {
|
||||
if g.client == nil {
|
||||
return rail.ObserveResult{}, merrors.Internal("chain gateway: client is required")
|
||||
}
|
||||
ref := strings.TrimSpace(referenceID)
|
||||
if ref == "" {
|
||||
return rail.ObserveResult{}, merrors.InvalidArgument("chain gateway: reference_id is required")
|
||||
}
|
||||
resp, err := g.client.GetTransfer(ctx, &chainv1.GetTransferRequest{TransferRef: ref})
|
||||
if err != nil {
|
||||
return rail.ObserveResult{}, err
|
||||
}
|
||||
if resp == nil || resp.GetTransfer() == nil {
|
||||
return rail.ObserveResult{}, merrors.Internal("chain gateway: missing transfer response")
|
||||
}
|
||||
transfer := resp.GetTransfer()
|
||||
return rail.ObserveResult{
|
||||
ReferenceID: ref,
|
||||
Status: statusFromTransfer(transfer.GetStatus()),
|
||||
FinalAmount: railMoneyFromProto(transfer.GetNetAmount()),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (g *chainRailGateway) resolveDestination(ctx context.Context, destRef, memo string) (*chainv1.TransferDestination, error) {
|
||||
managed, err := g.isManagedWallet(ctx, destRef)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if managed {
|
||||
return &chainv1.TransferDestination{
|
||||
Destination: &chainv1.TransferDestination_ManagedWalletRef{ManagedWalletRef: destRef},
|
||||
}, nil
|
||||
}
|
||||
return &chainv1.TransferDestination{
|
||||
Destination: &chainv1.TransferDestination_ExternalAddress{ExternalAddress: destRef},
|
||||
Memo: memo,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (g *chainRailGateway) isManagedWallet(ctx context.Context, walletRef string) (bool, error) {
|
||||
resp, err := g.client.GetManagedWallet(ctx, &chainv1.GetManagedWalletRequest{WalletRef: walletRef})
|
||||
if err != nil {
|
||||
if status.Code(err) == codes.NotFound {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
if resp == nil || resp.GetWallet() == nil {
|
||||
return false, nil
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func statusFromTransfer(status chainv1.TransferStatus) string {
|
||||
switch status {
|
||||
case chainv1.TransferStatus_TRANSFER_CONFIRMED:
|
||||
return rail.TransferStatusSuccess
|
||||
case chainv1.TransferStatus_TRANSFER_FAILED:
|
||||
return rail.TransferStatusFailed
|
||||
case chainv1.TransferStatus_TRANSFER_CANCELLED:
|
||||
return rail.TransferStatusRejected
|
||||
case chainv1.TransferStatus_TRANSFER_SIGNING,
|
||||
chainv1.TransferStatus_TRANSFER_PENDING,
|
||||
chainv1.TransferStatus_TRANSFER_SUBMITTED:
|
||||
return rail.TransferStatusPending
|
||||
default:
|
||||
return rail.TransferStatusPending
|
||||
}
|
||||
}
|
||||
|
||||
func toServiceFees(fees []rail.FeeBreakdown) []*chainv1.ServiceFeeBreakdown {
|
||||
if len(fees) == 0 {
|
||||
return nil
|
||||
}
|
||||
result := make([]*chainv1.ServiceFeeBreakdown, 0, len(fees))
|
||||
for _, fee := range fees {
|
||||
amount := moneyFromRail(fee.Amount)
|
||||
if amount == nil {
|
||||
continue
|
||||
}
|
||||
result = append(result, &chainv1.ServiceFeeBreakdown{
|
||||
FeeCode: strings.TrimSpace(fee.FeeCode),
|
||||
Amount: amount,
|
||||
Description: strings.TrimSpace(fee.Description),
|
||||
})
|
||||
}
|
||||
if len(result) == 0 {
|
||||
return nil
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func moneyFromRail(m *rail.Money) *moneyv1.Money {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
currency := strings.TrimSpace(m.GetCurrency())
|
||||
amount := strings.TrimSpace(m.GetAmount())
|
||||
if currency == "" || amount == "" {
|
||||
return nil
|
||||
}
|
||||
return &moneyv1.Money{
|
||||
Currency: currency,
|
||||
Amount: amount,
|
||||
}
|
||||
}
|
||||
|
||||
func railMoneyFromProto(m *moneyv1.Money) *rail.Money {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
currency := strings.TrimSpace(m.GetCurrency())
|
||||
amount := strings.TrimSpace(m.GetAmount())
|
||||
if currency == "" || amount == "" {
|
||||
return nil
|
||||
}
|
||||
return &rail.Money{
|
||||
Currency: currency,
|
||||
Amount: amount,
|
||||
}
|
||||
}
|
||||
|
||||
func cloneMetadata(input map[string]string) map[string]string {
|
||||
if len(input) == 0 {
|
||||
return nil
|
||||
}
|
||||
result := make(map[string]string, len(input))
|
||||
for key, value := range input {
|
||||
result[key] = value
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -8,7 +8,7 @@ grpc:
|
||||
enable_health: true
|
||||
|
||||
metrics:
|
||||
address: ":9403"
|
||||
address: ":9406"
|
||||
|
||||
database:
|
||||
driver: mongodb
|
||||
|
||||
@@ -22,7 +22,7 @@ require (
|
||||
|
||||
require (
|
||||
github.com/Microsoft/go-winio v0.6.2 // indirect
|
||||
github.com/ProjectZKM/Ziren/crates/go-runtime/zkvm_runtime v0.0.0-20251229120209-a0d175451f7b // indirect
|
||||
github.com/ProjectZKM/Ziren/crates/go-runtime/zkvm_runtime v0.0.0-20260104020744-7268a54d0358 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/bits-and-blooms/bitset v1.24.4 // indirect
|
||||
github.com/bmatcuk/doublestar/v4 v4.9.1 // indirect
|
||||
|
||||
@@ -6,8 +6,8 @@ github.com/DataDog/zstd v1.4.5 h1:EndNeuB0l9syBZhut0wns3gV1hL8zX8LIu6ZiVHWLIQ=
|
||||
github.com/DataDog/zstd v1.4.5/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo=
|
||||
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
|
||||
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
||||
github.com/ProjectZKM/Ziren/crates/go-runtime/zkvm_runtime v0.0.0-20251229120209-a0d175451f7b h1:g/wCbvJGhOAqfGBjWnqtD6CVsXdr3G4GCbjLR6z9kNw=
|
||||
github.com/ProjectZKM/Ziren/crates/go-runtime/zkvm_runtime v0.0.0-20251229120209-a0d175451f7b/go.mod h1:ioLG6R+5bUSO1oeGSDxOV3FADARuMoytZCSX6MEMQkI=
|
||||
github.com/ProjectZKM/Ziren/crates/go-runtime/zkvm_runtime v0.0.0-20260104020744-7268a54d0358 h1:B6uGMdZ4maUTJm+LYgBwEIDuJxgOUACw8K0Yg6jpNbY=
|
||||
github.com/ProjectZKM/Ziren/crates/go-runtime/zkvm_runtime v0.0.0-20260104020744-7268a54d0358/go.mod h1:ioLG6R+5bUSO1oeGSDxOV3FADARuMoytZCSX6MEMQkI=
|
||||
github.com/VictoriaMetrics/fastcache v1.13.0 h1:AW4mheMR5Vd9FkAPUv+NH6Nhw+fmbTMGMsNAoA/+4G0=
|
||||
github.com/VictoriaMetrics/fastcache v1.13.0/go.mod h1:hHXhl4DA2fTL2HTZDJFXWgW0LNjo6B+4aj2Wmng3TjU=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
|
||||
@@ -36,6 +36,7 @@ type Imp struct {
|
||||
app *grpcapp.App[storage.Repository]
|
||||
|
||||
rpcClients *rpcclient.Clients
|
||||
service *gatewayservice.Service
|
||||
}
|
||||
|
||||
type config struct {
|
||||
@@ -100,6 +101,10 @@ func (i *Imp) Shutdown() {
|
||||
timeout = i.config.Runtime.ShutdownTimeout()
|
||||
}
|
||||
|
||||
if i.service != nil {
|
||||
i.service.Shutdown()
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
@@ -151,7 +156,9 @@ func (i *Imp) Start() error {
|
||||
gatewayservice.WithDriverRegistry(driverRegistry),
|
||||
gatewayservice.WithSettings(cfg.Settings),
|
||||
}
|
||||
return gatewayservice.NewService(logger, repo, producer, opts...), nil
|
||||
svc := gatewayservice.NewService(logger, repo, producer, opts...)
|
||||
i.service = svc
|
||||
return svc, nil
|
||||
}
|
||||
|
||||
app, err := grpcapp.NewApp(i.logger, "chain", cfg.Config, i.debug, repoFactory, serviceFactory)
|
||||
|
||||
@@ -3,6 +3,7 @@ package gateway
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/tech/sendico/gateway/chain/internal/appversion"
|
||||
"github.com/tech/sendico/gateway/chain/internal/keymanager"
|
||||
"github.com/tech/sendico/gateway/chain/internal/service/gateway/commands"
|
||||
"github.com/tech/sendico/gateway/chain/internal/service/gateway/commands/transfer"
|
||||
@@ -14,10 +15,12 @@ import (
|
||||
"github.com/tech/sendico/pkg/api/routers"
|
||||
"github.com/tech/sendico/pkg/api/routers/gsresponse"
|
||||
clockpkg "github.com/tech/sendico/pkg/clock"
|
||||
"github.com/tech/sendico/pkg/discovery"
|
||||
msg "github.com/tech/sendico/pkg/messaging"
|
||||
"github.com/tech/sendico/pkg/mlogger"
|
||||
"github.com/tech/sendico/pkg/mservice"
|
||||
chainv1 "github.com/tech/sendico/pkg/proto/gateway/chain/v1"
|
||||
unifiedv1 "github.com/tech/sendico/pkg/proto/gateway/unified/v1"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
@@ -31,7 +34,7 @@ var (
|
||||
errStorageUnavailable = serviceError("chain_gateway: storage not initialised")
|
||||
)
|
||||
|
||||
// Service implements the ChainGatewayService RPC contract.
|
||||
// Service implements the UnifiedGatewayService RPC contract for chain operations.
|
||||
type Service struct {
|
||||
logger mlogger.Logger
|
||||
storage storage.Repository
|
||||
@@ -47,8 +50,9 @@ type Service struct {
|
||||
networkRegistry *rpcclient.Registry
|
||||
drivers *drivers.Registry
|
||||
commands commands.Registry
|
||||
announcers []*discovery.Announcer
|
||||
|
||||
chainv1.UnimplementedChainGatewayServiceServer
|
||||
unifiedv1.UnimplementedUnifiedGatewayServiceServer
|
||||
}
|
||||
|
||||
// NewService constructs the chain gateway service skeleton.
|
||||
@@ -83,6 +87,7 @@ func NewService(logger mlogger.Logger, repo storage.Repository, producer msg.Pro
|
||||
Wallet: commandsWalletDeps(svc),
|
||||
Transfer: commandsTransferDeps(svc),
|
||||
})
|
||||
svc.startDiscoveryAnnouncers()
|
||||
|
||||
return svc
|
||||
}
|
||||
@@ -90,10 +95,21 @@ func NewService(logger mlogger.Logger, repo storage.Repository, producer msg.Pro
|
||||
// Register wires the service onto the provided gRPC router.
|
||||
func (s *Service) Register(router routers.GRPC) error {
|
||||
return router.Register(func(reg grpc.ServiceRegistrar) {
|
||||
chainv1.RegisterChainGatewayServiceServer(reg, s)
|
||||
unifiedv1.RegisterUnifiedGatewayServiceServer(reg, s)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) Shutdown() {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
for _, announcer := range s.announcers {
|
||||
if announcer != nil {
|
||||
announcer.Stop()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) CreateManagedWallet(ctx context.Context, req *chainv1.CreateManagedWalletRequest) (*chainv1.CreateManagedWalletResponse, error) {
|
||||
return executeUnary(ctx, s, "CreateManagedWallet", s.commands.CreateManagedWallet.Execute, req)
|
||||
}
|
||||
@@ -174,3 +190,30 @@ func executeUnary[TReq any, TResp any](ctx context.Context, svc *Service, method
|
||||
observeRPC(method, err, svc.clock.Now().Sub(start))
|
||||
return resp, err
|
||||
}
|
||||
|
||||
func (s *Service) startDiscoveryAnnouncers() {
|
||||
if s == nil || s.producer == nil || len(s.networks) == 0 {
|
||||
return
|
||||
}
|
||||
version := appversion.Create().Short()
|
||||
for _, network := range s.networks {
|
||||
currencies := []string{shared.NativeCurrency(network)}
|
||||
for _, token := range network.TokenConfigs {
|
||||
if token.Symbol != "" {
|
||||
currencies = append(currencies, token.Symbol)
|
||||
}
|
||||
}
|
||||
announce := discovery.Announcement{
|
||||
Service: "CRYPTO_RAIL_GATEWAY",
|
||||
Rail: "CRYPTO",
|
||||
Network: network.Name,
|
||||
Operations: []string{"balance.read", "payin.crypto", "payout.crypto", "fee.send"},
|
||||
Currencies: currencies,
|
||||
InvokeURI: discovery.DefaultInvokeURI(string(mservice.ChainGateway)),
|
||||
Version: version,
|
||||
}
|
||||
announcer := discovery.NewAnnouncer(s.logger, s.producer, string(mservice.ChainGateway), announce)
|
||||
announcer.Start()
|
||||
s.announcers = append(s.announcers, announcer)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
This service now supports Monetix “payout by card”.
|
||||
|
||||
## Runtime entry points
|
||||
- gRPC: `MntxGatewayService.CreateCardPayout` and `GetCardPayoutStatus`.
|
||||
- gRPC: `MntxGatewayService.CreateCardPayout`, `CreateCardTokenPayout`, `GetCardPayoutStatus`, `ListGatewayInstances`.
|
||||
- Callback HTTP server (default): `:8084/monetix/callback` for Monetix payout status notifications.
|
||||
- Metrics: Prometheus on `:9404/metrics`.
|
||||
|
||||
@@ -13,6 +13,7 @@ This service now supports Monetix “payout by card”.
|
||||
- `MONETIX_PROJECT_ID` – integer project ID
|
||||
- `MONETIX_SECRET_KEY` – signature secret
|
||||
- Optional: `allowed_currencies`, `require_customer_address`, `request_timeout_seconds`
|
||||
- Gateway descriptor: `gateway.id`, optional `gateway.currencies`, `gateway.limits`
|
||||
- Callback server: `MNTX_GATEWAY_HTTP_PORT` (exposed as 8084), `http.callback.path`, optional `allowed_cidrs`
|
||||
|
||||
## Outbound request (CreateCardPayout)
|
||||
@@ -39,7 +40,8 @@ Signature: HMAC-SHA256 over the JSON body (without `signature`), using `MONETIX_
|
||||
- `sendico_mntx_gateway_card_payout_requests_total{outcome}`
|
||||
- `sendico_mntx_gateway_card_payout_request_latency_seconds{outcome}`
|
||||
- `sendico_mntx_gateway_card_payout_callbacks_total{status}`
|
||||
- Existing RPC/payout counters remain for compatibility.
|
||||
- `sendico_mntx_gateway_rpc_requests_total{method,status}`
|
||||
- `sendico_mntx_gateway_rpc_latency_seconds{method}`
|
||||
|
||||
## Notes / PCI
|
||||
- PAN is only logged in masked form; do not persist raw PAN.
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
mntxv1 "github.com/tech/sendico/pkg/proto/gateway/mntx/v1"
|
||||
unifiedv1 "github.com/tech/sendico/pkg/proto/gateway/unified/v1"
|
||||
"go.uber.org/zap"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
@@ -17,12 +18,13 @@ type Client interface {
|
||||
CreateCardPayout(ctx context.Context, req *mntxv1.CardPayoutRequest) (*mntxv1.CardPayoutResponse, error)
|
||||
CreateCardTokenPayout(ctx context.Context, req *mntxv1.CardTokenPayoutRequest) (*mntxv1.CardTokenPayoutResponse, error)
|
||||
GetCardPayoutStatus(ctx context.Context, req *mntxv1.GetCardPayoutStatusRequest) (*mntxv1.GetCardPayoutStatusResponse, error)
|
||||
ListGatewayInstances(ctx context.Context, req *mntxv1.ListGatewayInstancesRequest) (*mntxv1.ListGatewayInstancesResponse, error)
|
||||
Close() error
|
||||
}
|
||||
|
||||
type gatewayClient struct {
|
||||
conn *grpc.ClientConn
|
||||
client mntxv1.MntxGatewayServiceClient
|
||||
client unifiedv1.UnifiedGatewayServiceClient
|
||||
cfg Config
|
||||
logger *zap.Logger
|
||||
}
|
||||
@@ -47,7 +49,7 @@ func New(ctx context.Context, cfg Config, opts ...grpc.DialOption) (Client, erro
|
||||
|
||||
return &gatewayClient{
|
||||
conn: conn,
|
||||
client: mntxv1.NewMntxGatewayServiceClient(conn),
|
||||
client: unifiedv1.NewUnifiedGatewayServiceClient(conn),
|
||||
cfg: cfg,
|
||||
logger: cfg.Logger,
|
||||
}, nil
|
||||
@@ -96,3 +98,9 @@ func (g *gatewayClient) GetCardPayoutStatus(ctx context.Context, req *mntxv1.Get
|
||||
defer cancel()
|
||||
return g.client.GetCardPayoutStatus(ctx, req)
|
||||
}
|
||||
|
||||
func (g *gatewayClient) ListGatewayInstances(ctx context.Context, req *mntxv1.ListGatewayInstancesRequest) (*mntxv1.ListGatewayInstancesResponse, error) {
|
||||
ctx, cancel := g.callContext(ctx, "ListGatewayInstances")
|
||||
defer cancel()
|
||||
return g.client.ListGatewayInstances(ctx, req)
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ type Fake struct {
|
||||
CreateCardPayoutFn func(ctx context.Context, req *mntxv1.CardPayoutRequest) (*mntxv1.CardPayoutResponse, error)
|
||||
CreateCardTokenPayoutFn func(ctx context.Context, req *mntxv1.CardTokenPayoutRequest) (*mntxv1.CardTokenPayoutResponse, error)
|
||||
GetCardPayoutStatusFn func(ctx context.Context, req *mntxv1.GetCardPayoutStatusRequest) (*mntxv1.GetCardPayoutStatusResponse, error)
|
||||
ListGatewayInstancesFn func(ctx context.Context, req *mntxv1.ListGatewayInstancesRequest) (*mntxv1.ListGatewayInstancesResponse, error)
|
||||
}
|
||||
|
||||
func (f *Fake) CreateCardPayout(ctx context.Context, req *mntxv1.CardPayoutRequest) (*mntxv1.CardPayoutResponse, error) {
|
||||
@@ -34,4 +35,11 @@ func (f *Fake) GetCardPayoutStatus(ctx context.Context, req *mntxv1.GetCardPayou
|
||||
return &mntxv1.GetCardPayoutStatusResponse{}, nil
|
||||
}
|
||||
|
||||
func (f *Fake) ListGatewayInstances(ctx context.Context, req *mntxv1.ListGatewayInstancesRequest) (*mntxv1.ListGatewayInstancesResponse, error) {
|
||||
if f.ListGatewayInstancesFn != nil {
|
||||
return f.ListGatewayInstancesFn(ctx, req)
|
||||
}
|
||||
return &mntxv1.ListGatewayInstancesResponse{}, nil
|
||||
}
|
||||
|
||||
func (f *Fake) Close() error { return nil }
|
||||
|
||||
@@ -32,6 +32,14 @@ monetix:
|
||||
status_success: "success"
|
||||
status_processing: "processing"
|
||||
|
||||
gateway:
|
||||
id: "monetix"
|
||||
is_enabled: true
|
||||
network: "VISA_DIRECT"
|
||||
currencies: ["RUB"]
|
||||
limits:
|
||||
min_amount: "0"
|
||||
|
||||
http:
|
||||
callback:
|
||||
address: ":8084"
|
||||
|
||||
@@ -6,9 +6,7 @@ replace github.com/tech/sendico/pkg => ../../pkg
|
||||
|
||||
require (
|
||||
github.com/go-chi/chi/v5 v5.2.3
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/prometheus/client_golang v1.23.2
|
||||
github.com/shopspring/decimal v1.4.0
|
||||
github.com/tech/sendico/pkg v0.1.0
|
||||
go.uber.org/zap v1.27.1
|
||||
google.golang.org/grpc v1.78.0
|
||||
@@ -24,6 +22,7 @@ require (
|
||||
github.com/casbin/mongodb-adapter/v3 v3.7.0 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/golang/snappy v1.0.0 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/klauspost/compress v1.18.2 // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
|
||||
@@ -125,8 +125,6 @@ github.com/shirou/gopsutil/v3 v3.24.5 h1:i0t8kL+kQTvpAYToeuiVk3TgDeKOFioZO3Ztz/i
|
||||
github.com/shirou/gopsutil/v3 v3.24.5/go.mod h1:bsoOS1aStSs9ErQ1WWfxllSeS1K5D+U30r2NfcubMVk=
|
||||
github.com/shoenig/go-m1cpu v0.1.6 h1:nxdKQNcEB6vzgA2E2bvzKIYRuNj7XNJ4S/aRSwKzFtM=
|
||||
github.com/shoenig/go-m1cpu v0.1.6/go.mod h1:1JJMcUBvfNwpq05QDQVAnx3gUHr9IYF7GNg9SUEw2VQ=
|
||||
github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k=
|
||||
github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=
|
||||
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
|
||||
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
|
||||
|
||||
@@ -12,12 +12,14 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/tech/sendico/gateway/mntx/internal/appversion"
|
||||
mntxservice "github.com/tech/sendico/gateway/mntx/internal/service/gateway"
|
||||
"github.com/tech/sendico/gateway/mntx/internal/service/monetix"
|
||||
"github.com/tech/sendico/pkg/api/routers"
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
msg "github.com/tech/sendico/pkg/messaging"
|
||||
"github.com/tech/sendico/pkg/mlogger"
|
||||
gatewayv1 "github.com/tech/sendico/pkg/proto/common/gateway/v1"
|
||||
"github.com/tech/sendico/pkg/server/grpcapp"
|
||||
"go.uber.org/zap"
|
||||
"gopkg.in/yaml.v3"
|
||||
@@ -28,14 +30,16 @@ type Imp struct {
|
||||
file string
|
||||
debug bool
|
||||
|
||||
config *config
|
||||
app *grpcapp.App[struct{}]
|
||||
http *http.Server
|
||||
config *config
|
||||
app *grpcapp.App[struct{}]
|
||||
http *http.Server
|
||||
service *mntxservice.Service
|
||||
}
|
||||
|
||||
type config struct {
|
||||
*grpcapp.Config `yaml:",inline"`
|
||||
Monetix monetixConfig `yaml:"monetix"`
|
||||
Gateway gatewayConfig `yaml:"gateway"`
|
||||
HTTP httpConfig `yaml:"http"`
|
||||
}
|
||||
|
||||
@@ -53,6 +57,33 @@ type monetixConfig struct {
|
||||
StatusProcessing string `yaml:"status_processing"`
|
||||
}
|
||||
|
||||
type gatewayConfig struct {
|
||||
ID string `yaml:"id"`
|
||||
Network string `yaml:"network"`
|
||||
Currencies []string `yaml:"currencies"`
|
||||
IsEnabled *bool `yaml:"is_enabled"`
|
||||
Limits limitsConfig `yaml:"limits"`
|
||||
}
|
||||
|
||||
type limitsConfig struct {
|
||||
MinAmount string `yaml:"min_amount"`
|
||||
MaxAmount string `yaml:"max_amount"`
|
||||
PerTxMaxFee string `yaml:"per_tx_max_fee"`
|
||||
PerTxMinAmount string `yaml:"per_tx_min_amount"`
|
||||
PerTxMaxAmount string `yaml:"per_tx_max_amount"`
|
||||
VolumeLimit map[string]string `yaml:"volume_limit"`
|
||||
VelocityLimit map[string]int `yaml:"velocity_limit"`
|
||||
CurrencyLimits map[string]limitsOverrideCfg `yaml:"currency_limits"`
|
||||
}
|
||||
|
||||
type limitsOverrideCfg struct {
|
||||
MaxVolume string `yaml:"max_volume"`
|
||||
MinAmount string `yaml:"min_amount"`
|
||||
MaxAmount string `yaml:"max_amount"`
|
||||
MaxFee string `yaml:"max_fee"`
|
||||
MaxOps int `yaml:"max_ops"`
|
||||
}
|
||||
|
||||
type httpConfig struct {
|
||||
Callback callbackConfig `yaml:"callback"`
|
||||
}
|
||||
@@ -86,6 +117,9 @@ func (i *Imp) Shutdown() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
if i.service != nil {
|
||||
i.service.Shutdown()
|
||||
}
|
||||
if i.http != nil {
|
||||
_ = i.http.Shutdown(ctx)
|
||||
i.http = nil
|
||||
@@ -131,6 +165,17 @@ func (i *Imp) Start() error {
|
||||
zap.String("status_processing", monetixCfg.ProcessingStatus()),
|
||||
)
|
||||
|
||||
gatewayDescriptor := resolveGatewayDescriptor(cfg.Gateway, monetixCfg)
|
||||
if gatewayDescriptor != nil {
|
||||
i.logger.Info("Gateway descriptor resolved",
|
||||
zap.String("id", gatewayDescriptor.GetId()),
|
||||
zap.String("rail", gatewayDescriptor.GetRail().String()),
|
||||
zap.String("network", gatewayDescriptor.GetNetwork()),
|
||||
zap.Int("currencies", len(gatewayDescriptor.GetCurrencies())),
|
||||
zap.Bool("enabled", gatewayDescriptor.GetIsEnabled()),
|
||||
)
|
||||
}
|
||||
|
||||
i.logger.Info("Callback configuration resolved",
|
||||
zap.String("address", callbackCfg.Address),
|
||||
zap.String("path", callbackCfg.Path),
|
||||
@@ -142,8 +187,10 @@ func (i *Imp) Start() error {
|
||||
svc := mntxservice.NewService(logger,
|
||||
mntxservice.WithProducer(producer),
|
||||
mntxservice.WithMonetixConfig(monetixCfg),
|
||||
mntxservice.WithGatewayDescriptor(gatewayDescriptor),
|
||||
mntxservice.WithHTTPClient(&http.Client{Timeout: monetixCfg.Timeout()}),
|
||||
)
|
||||
i.service = svc
|
||||
|
||||
if err := i.startHTTPCallbackServer(svc, callbackCfg); err != nil {
|
||||
return nil, err
|
||||
@@ -243,6 +290,129 @@ func (i *Imp) resolveMonetixConfig(cfg monetixConfig) (monetix.Config, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
func resolveGatewayDescriptor(cfg gatewayConfig, monetixCfg monetix.Config) *gatewayv1.GatewayInstanceDescriptor {
|
||||
id := strings.TrimSpace(cfg.ID)
|
||||
if id == "" {
|
||||
id = "monetix"
|
||||
}
|
||||
|
||||
network := strings.ToUpper(strings.TrimSpace(cfg.Network))
|
||||
currencies := normalizeCurrencies(cfg.Currencies)
|
||||
if len(currencies) == 0 {
|
||||
currencies = normalizeCurrencies(monetixCfg.AllowedCurrencies)
|
||||
}
|
||||
|
||||
enabled := true
|
||||
if cfg.IsEnabled != nil {
|
||||
enabled = *cfg.IsEnabled
|
||||
}
|
||||
|
||||
limits := buildGatewayLimits(cfg.Limits)
|
||||
if limits == nil {
|
||||
limits = &gatewayv1.Limits{MinAmount: "0"}
|
||||
}
|
||||
|
||||
version := strings.TrimSpace(appversion.Version)
|
||||
|
||||
return &gatewayv1.GatewayInstanceDescriptor{
|
||||
Id: id,
|
||||
Rail: gatewayv1.Rail_RAIL_CARD_PAYOUT,
|
||||
Network: network,
|
||||
Currencies: currencies,
|
||||
Capabilities: &gatewayv1.RailCapabilities{
|
||||
CanPayOut: true,
|
||||
CanPayIn: false,
|
||||
CanReadBalance: false,
|
||||
CanSendFee: false,
|
||||
RequiresObserveConfirm: false,
|
||||
},
|
||||
Limits: limits,
|
||||
Version: version,
|
||||
IsEnabled: enabled,
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeCurrencies(values []string) []string {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
result := make([]string, 0, len(values))
|
||||
for _, value := range values {
|
||||
clean := strings.ToUpper(strings.TrimSpace(value))
|
||||
if clean == "" || seen[clean] {
|
||||
continue
|
||||
}
|
||||
seen[clean] = true
|
||||
result = append(result, clean)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func buildGatewayLimits(cfg limitsConfig) *gatewayv1.Limits {
|
||||
hasValue := strings.TrimSpace(cfg.MinAmount) != "" ||
|
||||
strings.TrimSpace(cfg.MaxAmount) != "" ||
|
||||
strings.TrimSpace(cfg.PerTxMaxFee) != "" ||
|
||||
strings.TrimSpace(cfg.PerTxMinAmount) != "" ||
|
||||
strings.TrimSpace(cfg.PerTxMaxAmount) != "" ||
|
||||
len(cfg.VolumeLimit) > 0 ||
|
||||
len(cfg.VelocityLimit) > 0 ||
|
||||
len(cfg.CurrencyLimits) > 0
|
||||
if !hasValue {
|
||||
return nil
|
||||
}
|
||||
|
||||
limits := &gatewayv1.Limits{
|
||||
MinAmount: strings.TrimSpace(cfg.MinAmount),
|
||||
MaxAmount: strings.TrimSpace(cfg.MaxAmount),
|
||||
PerTxMaxFee: strings.TrimSpace(cfg.PerTxMaxFee),
|
||||
PerTxMinAmount: strings.TrimSpace(cfg.PerTxMinAmount),
|
||||
PerTxMaxAmount: strings.TrimSpace(cfg.PerTxMaxAmount),
|
||||
}
|
||||
|
||||
if len(cfg.VolumeLimit) > 0 {
|
||||
limits.VolumeLimit = map[string]string{}
|
||||
for key, value := range cfg.VolumeLimit {
|
||||
bucket := strings.TrimSpace(key)
|
||||
amount := strings.TrimSpace(value)
|
||||
if bucket == "" || amount == "" {
|
||||
continue
|
||||
}
|
||||
limits.VolumeLimit[bucket] = amount
|
||||
}
|
||||
}
|
||||
|
||||
if len(cfg.VelocityLimit) > 0 {
|
||||
limits.VelocityLimit = map[string]int32{}
|
||||
for key, value := range cfg.VelocityLimit {
|
||||
bucket := strings.TrimSpace(key)
|
||||
if bucket == "" {
|
||||
continue
|
||||
}
|
||||
limits.VelocityLimit[bucket] = int32(value)
|
||||
}
|
||||
}
|
||||
|
||||
if len(cfg.CurrencyLimits) > 0 {
|
||||
limits.CurrencyLimits = map[string]*gatewayv1.LimitsOverride{}
|
||||
for key, override := range cfg.CurrencyLimits {
|
||||
currency := strings.ToUpper(strings.TrimSpace(key))
|
||||
if currency == "" {
|
||||
continue
|
||||
}
|
||||
limits.CurrencyLimits[currency] = &gatewayv1.LimitsOverride{
|
||||
MaxVolume: strings.TrimSpace(override.MaxVolume),
|
||||
MinAmount: strings.TrimSpace(override.MinAmount),
|
||||
MaxAmount: strings.TrimSpace(override.MaxAmount),
|
||||
MaxFee: strings.TrimSpace(override.MaxFee),
|
||||
MaxOps: int32(override.MaxOps),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return limits
|
||||
}
|
||||
|
||||
type callbackRuntimeConfig struct {
|
||||
Address string
|
||||
Path string
|
||||
|
||||
63
api/gateway/mntx/internal/service/gateway/instances.go
Normal file
63
api/gateway/mntx/internal/service/gateway/instances.go
Normal file
@@ -0,0 +1,63 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/tech/sendico/pkg/api/routers/gsresponse"
|
||||
gatewayv1 "github.com/tech/sendico/pkg/proto/common/gateway/v1"
|
||||
mntxv1 "github.com/tech/sendico/pkg/proto/gateway/mntx/v1"
|
||||
)
|
||||
|
||||
// ListGatewayInstances exposes the Monetix gateway instance descriptors.
|
||||
func (s *Service) ListGatewayInstances(ctx context.Context, req *mntxv1.ListGatewayInstancesRequest) (*mntxv1.ListGatewayInstancesResponse, error) {
|
||||
return executeUnary(ctx, s, "ListGatewayInstances", s.handleListGatewayInstances, req)
|
||||
}
|
||||
|
||||
func (s *Service) handleListGatewayInstances(_ context.Context, _ *mntxv1.ListGatewayInstancesRequest) gsresponse.Responder[mntxv1.ListGatewayInstancesResponse] {
|
||||
items := make([]*gatewayv1.GatewayInstanceDescriptor, 0, 1)
|
||||
if s.gatewayDescriptor != nil {
|
||||
items = append(items, cloneGatewayDescriptor(s.gatewayDescriptor))
|
||||
}
|
||||
return gsresponse.Success(&mntxv1.ListGatewayInstancesResponse{Items: items})
|
||||
}
|
||||
|
||||
func cloneGatewayDescriptor(src *gatewayv1.GatewayInstanceDescriptor) *gatewayv1.GatewayInstanceDescriptor {
|
||||
if src == nil {
|
||||
return nil
|
||||
}
|
||||
cp := *src
|
||||
if src.Currencies != nil {
|
||||
cp.Currencies = append([]string(nil), src.Currencies...)
|
||||
}
|
||||
if src.Capabilities != nil {
|
||||
cap := *src.Capabilities
|
||||
cp.Capabilities = &cap
|
||||
}
|
||||
if src.Limits != nil {
|
||||
limits := *src.Limits
|
||||
if src.Limits.VolumeLimit != nil {
|
||||
limits.VolumeLimit = map[string]string{}
|
||||
for key, value := range src.Limits.VolumeLimit {
|
||||
limits.VolumeLimit[key] = value
|
||||
}
|
||||
}
|
||||
if src.Limits.VelocityLimit != nil {
|
||||
limits.VelocityLimit = map[string]int32{}
|
||||
for key, value := range src.Limits.VelocityLimit {
|
||||
limits.VelocityLimit[key] = value
|
||||
}
|
||||
}
|
||||
if src.Limits.CurrencyLimits != nil {
|
||||
limits.CurrencyLimits = map[string]*gatewayv1.LimitsOverride{}
|
||||
for key, value := range src.Limits.CurrencyLimits {
|
||||
if value == nil {
|
||||
continue
|
||||
}
|
||||
clone := *value
|
||||
limits.CurrencyLimits[key] = &clone
|
||||
}
|
||||
}
|
||||
cp.Limits = &limits
|
||||
}
|
||||
return &cp
|
||||
}
|
||||
@@ -2,15 +2,12 @@ package gateway
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/promauto"
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
moneyv1 "github.com/tech/sendico/pkg/proto/common/money/v1"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -18,11 +15,6 @@ var (
|
||||
|
||||
rpcLatency *prometheus.HistogramVec
|
||||
rpcStatus *prometheus.CounterVec
|
||||
|
||||
payoutCounter *prometheus.CounterVec
|
||||
payoutAmountTotal *prometheus.CounterVec
|
||||
payoutErrorCount *prometheus.CounterVec
|
||||
payoutMissedAmounts *prometheus.CounterVec
|
||||
)
|
||||
|
||||
func initMetrics() {
|
||||
@@ -42,33 +34,6 @@ func initMetrics() {
|
||||
Help: "Total number of RPC invocations grouped by method and status.",
|
||||
}, []string{"method", "status"})
|
||||
|
||||
payoutCounter = promauto.NewCounterVec(prometheus.CounterOpts{
|
||||
Namespace: "sendico",
|
||||
Subsystem: "mntx_gateway",
|
||||
Name: "payouts_total",
|
||||
Help: "Total payouts processed grouped by outcome.",
|
||||
}, []string{"status"})
|
||||
|
||||
payoutAmountTotal = promauto.NewCounterVec(prometheus.CounterOpts{
|
||||
Namespace: "sendico",
|
||||
Subsystem: "mntx_gateway",
|
||||
Name: "payout_amount_total",
|
||||
Help: "Total payout amount grouped by outcome and currency.",
|
||||
}, []string{"status", "currency"})
|
||||
|
||||
payoutErrorCount = promauto.NewCounterVec(prometheus.CounterOpts{
|
||||
Namespace: "sendico",
|
||||
Subsystem: "mntx_gateway",
|
||||
Name: "payout_errors_total",
|
||||
Help: "Payout failures grouped by reason.",
|
||||
}, []string{"reason"})
|
||||
|
||||
payoutMissedAmounts = promauto.NewCounterVec(prometheus.CounterOpts{
|
||||
Namespace: "sendico",
|
||||
Subsystem: "mntx_gateway",
|
||||
Name: "payout_missed_amount_total",
|
||||
Help: "Total payout volume that failed grouped by reason and currency.",
|
||||
}, []string{"reason", "currency"})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -81,71 +46,6 @@ func observeRPC(method string, err error, duration time.Duration) {
|
||||
}
|
||||
}
|
||||
|
||||
func observePayoutSuccess(amount *moneyv1.Money) {
|
||||
if payoutCounter != nil {
|
||||
payoutCounter.WithLabelValues("processed").Inc()
|
||||
}
|
||||
value, currency := monetaryValue(amount)
|
||||
if value > 0 && payoutAmountTotal != nil {
|
||||
payoutAmountTotal.WithLabelValues("processed", currency).Add(value)
|
||||
}
|
||||
}
|
||||
|
||||
func observePayoutError(reason string, amount *moneyv1.Money) {
|
||||
reason = reasonLabel(reason)
|
||||
if payoutCounter != nil {
|
||||
payoutCounter.WithLabelValues("failed").Inc()
|
||||
}
|
||||
if payoutErrorCount != nil {
|
||||
payoutErrorCount.WithLabelValues(reason).Inc()
|
||||
}
|
||||
value, currency := monetaryValue(amount)
|
||||
if value <= 0 {
|
||||
return
|
||||
}
|
||||
if payoutAmountTotal != nil {
|
||||
payoutAmountTotal.WithLabelValues("failed", currency).Add(value)
|
||||
}
|
||||
if payoutMissedAmounts != nil {
|
||||
payoutMissedAmounts.WithLabelValues(reason, currency).Add(value)
|
||||
}
|
||||
}
|
||||
|
||||
func monetaryValue(amount *moneyv1.Money) (float64, string) {
|
||||
if amount == nil {
|
||||
return 0, "unknown"
|
||||
}
|
||||
val := strings.TrimSpace(amount.Amount)
|
||||
if val == "" {
|
||||
return 0, currencyLabel(amount.Currency)
|
||||
}
|
||||
dec, err := decimal.NewFromString(val)
|
||||
if err != nil {
|
||||
return 0, currencyLabel(amount.Currency)
|
||||
}
|
||||
f, _ := dec.Float64()
|
||||
if f < 0 {
|
||||
return 0, currencyLabel(amount.Currency)
|
||||
}
|
||||
return f, currencyLabel(amount.Currency)
|
||||
}
|
||||
|
||||
func currencyLabel(code string) string {
|
||||
code = strings.ToUpper(strings.TrimSpace(code))
|
||||
if code == "" {
|
||||
return "unknown"
|
||||
}
|
||||
return code
|
||||
}
|
||||
|
||||
func reasonLabel(reason string) string {
|
||||
reason = strings.TrimSpace(reason)
|
||||
if reason == "" {
|
||||
return "unknown"
|
||||
}
|
||||
return strings.ToLower(reason)
|
||||
}
|
||||
|
||||
func statusLabel(err error) string {
|
||||
switch {
|
||||
case err == nil:
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"github.com/tech/sendico/gateway/mntx/internal/service/monetix"
|
||||
"github.com/tech/sendico/pkg/clock"
|
||||
msg "github.com/tech/sendico/pkg/messaging"
|
||||
gatewayv1 "github.com/tech/sendico/pkg/proto/common/gateway/v1"
|
||||
)
|
||||
|
||||
// Option configures optional service dependencies.
|
||||
@@ -42,3 +43,12 @@ func WithMonetixConfig(cfg monetix.Config) Option {
|
||||
s.config = cfg
|
||||
}
|
||||
}
|
||||
|
||||
// WithGatewayDescriptor sets the self-declared gateway instance descriptor.
|
||||
func WithGatewayDescriptor(descriptor *gatewayv1.GatewayInstanceDescriptor) Option {
|
||||
return func(s *Service) {
|
||||
if descriptor != nil {
|
||||
s.gatewayDescriptor = descriptor
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/tech/sendico/pkg/api/routers/gsresponse"
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
"github.com/tech/sendico/pkg/mservice"
|
||||
mntxv1 "github.com/tech/sendico/pkg/proto/gateway/mntx/v1"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func (s *Service) GetPayout(ctx context.Context, req *mntxv1.GetPayoutRequest) (*mntxv1.GetPayoutResponse, error) {
|
||||
return executeUnary(ctx, s, "GetPayout", s.handleGetPayout, req)
|
||||
}
|
||||
|
||||
func (s *Service) handleGetPayout(_ context.Context, req *mntxv1.GetPayoutRequest) gsresponse.Responder[mntxv1.GetPayoutResponse] {
|
||||
ref := strings.TrimSpace(req.GetPayoutRef())
|
||||
log := s.logger.Named("payout")
|
||||
log.Info("Get payout request received", zap.String("payout_ref", ref))
|
||||
if ref == "" {
|
||||
log.Warn("Get payout request missing payout_ref")
|
||||
return gsresponse.InvalidArgument[mntxv1.GetPayoutResponse](s.logger, mservice.MntxGateway, merrors.InvalidArgument("payout_ref is required", "payout_ref"))
|
||||
}
|
||||
|
||||
payout, ok := s.store.Get(ref)
|
||||
if !ok {
|
||||
log.Warn("Payout not found", zap.String("payout_ref", ref))
|
||||
return gsresponse.NotFound[mntxv1.GetPayoutResponse](s.logger, mservice.MntxGateway, merrors.NoData(fmt.Sprintf("payout %s not found", ref)))
|
||||
}
|
||||
|
||||
log.Info("Payout retrieved", zap.String("payout_ref", ref), zap.String("status", payout.GetStatus().String()))
|
||||
return gsresponse.Success(&mntxv1.GetPayoutResponse{Payout: payout})
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
mntxv1 "github.com/tech/sendico/pkg/proto/gateway/mntx/v1"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
type payoutStore struct {
|
||||
mu sync.RWMutex
|
||||
payouts map[string]*mntxv1.Payout
|
||||
}
|
||||
|
||||
func newPayoutStore() *payoutStore {
|
||||
return &payoutStore{
|
||||
payouts: make(map[string]*mntxv1.Payout),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *payoutStore) Save(p *mntxv1.Payout) {
|
||||
if p == nil {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.payouts[p.GetPayoutRef()] = clonePayout(p)
|
||||
}
|
||||
|
||||
func (s *payoutStore) Get(ref string) (*mntxv1.Payout, bool) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
p, ok := s.payouts[ref]
|
||||
return clonePayout(p), ok
|
||||
}
|
||||
|
||||
func clonePayout(p *mntxv1.Payout) *mntxv1.Payout {
|
||||
if p == nil {
|
||||
return nil
|
||||
}
|
||||
cloned := proto.Clone(p)
|
||||
if cp, ok := cloned.(*mntxv1.Payout); ok {
|
||||
return cp
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,144 +0,0 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/tech/sendico/pkg/api/routers/gsresponse"
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
messaging "github.com/tech/sendico/pkg/messaging/envelope"
|
||||
"github.com/tech/sendico/pkg/model"
|
||||
nm "github.com/tech/sendico/pkg/model/notification"
|
||||
"github.com/tech/sendico/pkg/mservice"
|
||||
mntxv1 "github.com/tech/sendico/pkg/proto/gateway/mntx/v1"
|
||||
"go.uber.org/zap"
|
||||
"google.golang.org/protobuf/encoding/protojson"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
|
||||
func (s *Service) SubmitPayout(ctx context.Context, req *mntxv1.SubmitPayoutRequest) (*mntxv1.SubmitPayoutResponse, error) {
|
||||
return executeUnary(ctx, s, "SubmitPayout", s.handleSubmitPayout, req)
|
||||
}
|
||||
|
||||
func (s *Service) handleSubmitPayout(_ context.Context, req *mntxv1.SubmitPayoutRequest) gsresponse.Responder[mntxv1.SubmitPayoutResponse] {
|
||||
log := s.logger.Named("payout")
|
||||
log.Info("Submit payout request received",
|
||||
zap.String("idempotency_key", strings.TrimSpace(req.GetIdempotencyKey())),
|
||||
zap.String("organization_ref", strings.TrimSpace(req.GetOrganizationRef())),
|
||||
zap.String("currency", strings.TrimSpace(req.GetAmount().GetCurrency())),
|
||||
zap.String("amount", strings.TrimSpace(req.GetAmount().GetAmount())),
|
||||
)
|
||||
|
||||
payout, err := s.buildPayout(req)
|
||||
if err != nil {
|
||||
log.Warn("Submit payout validation failed", zap.Error(err))
|
||||
return gsresponse.Auto[mntxv1.SubmitPayoutResponse](s.logger, mservice.MntxGateway, err)
|
||||
}
|
||||
|
||||
s.store.Save(payout)
|
||||
s.emitEvent(payout, nm.NAPending)
|
||||
go s.completePayout(payout, strings.TrimSpace(req.GetSimulatedFailureReason()))
|
||||
|
||||
log.Info("Payout accepted", zap.String("payout_ref", payout.GetPayoutRef()), zap.String("status", payout.GetStatus().String()))
|
||||
return gsresponse.Success(&mntxv1.SubmitPayoutResponse{Payout: payout})
|
||||
}
|
||||
|
||||
func (s *Service) buildPayout(req *mntxv1.SubmitPayoutRequest) (*mntxv1.Payout, error) {
|
||||
if req == nil {
|
||||
return nil, newPayoutError("invalid_request", merrors.InvalidArgument("request cannot be empty"))
|
||||
}
|
||||
|
||||
idempotencyKey := strings.TrimSpace(req.IdempotencyKey)
|
||||
if idempotencyKey == "" {
|
||||
return nil, newPayoutError("missing_idempotency_key", merrors.InvalidArgument("idempotency_key is required", "idempotency_key"))
|
||||
}
|
||||
|
||||
orgRef := strings.TrimSpace(req.OrganizationRef)
|
||||
if orgRef == "" {
|
||||
return nil, newPayoutError("missing_organization_ref", merrors.InvalidArgument("organization_ref is required", "organization_ref"))
|
||||
}
|
||||
|
||||
if err := validateAmount(req.Amount); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := validateDestination(req.Destination); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if reason := strings.TrimSpace(req.SimulatedFailureReason); reason != "" {
|
||||
return nil, newPayoutError(normalizeReason(reason), merrors.InvalidArgument("simulated payout failure requested"))
|
||||
}
|
||||
|
||||
now := timestamppb.New(s.clock.Now())
|
||||
payout := &mntxv1.Payout{
|
||||
PayoutRef: newPayoutRef(),
|
||||
IdempotencyKey: idempotencyKey,
|
||||
OrganizationRef: orgRef,
|
||||
Destination: req.Destination,
|
||||
Amount: req.Amount,
|
||||
Description: strings.TrimSpace(req.Description),
|
||||
Metadata: req.Metadata,
|
||||
Status: mntxv1.PayoutStatus_PAYOUT_STATUS_PENDING,
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
|
||||
return payout, nil
|
||||
}
|
||||
|
||||
func (s *Service) completePayout(original *mntxv1.Payout, simulatedFailure string) {
|
||||
log := s.logger.Named("payout")
|
||||
outcome := clonePayout(original)
|
||||
if outcome == nil {
|
||||
return
|
||||
}
|
||||
|
||||
// Simulate async processing delay for realism.
|
||||
time.Sleep(150 * time.Millisecond)
|
||||
|
||||
outcome.UpdatedAt = timestamppb.New(s.clock.Now())
|
||||
|
||||
if simulatedFailure != "" {
|
||||
outcome.Status = mntxv1.PayoutStatus_PAYOUT_STATUS_FAILED
|
||||
outcome.FailureReason = simulatedFailure
|
||||
observePayoutError(simulatedFailure, outcome.Amount)
|
||||
s.store.Save(outcome)
|
||||
s.emitEvent(outcome, nm.NAUpdated)
|
||||
log.Info("Payout completed", zap.String("payout_ref", outcome.GetPayoutRef()), zap.String("status", outcome.GetStatus().String()), zap.String("failure_reason", simulatedFailure))
|
||||
return
|
||||
}
|
||||
|
||||
outcome.Status = mntxv1.PayoutStatus_PAYOUT_STATUS_PROCESSED
|
||||
observePayoutSuccess(outcome.Amount)
|
||||
s.store.Save(outcome)
|
||||
s.emitEvent(outcome, nm.NAUpdated)
|
||||
log.Info("Payout completed", zap.String("payout_ref", outcome.GetPayoutRef()), zap.String("status", outcome.GetStatus().String()))
|
||||
}
|
||||
|
||||
func (s *Service) emitEvent(payout *mntxv1.Payout, action nm.NotificationAction) {
|
||||
if payout == nil || s.producer == nil {
|
||||
return
|
||||
}
|
||||
|
||||
payload, err := protojson.Marshal(&mntxv1.PayoutStatusChangedEvent{Payout: payout})
|
||||
if err != nil {
|
||||
s.logger.Warn("Failed to marshal payout event", zapError(err))
|
||||
return
|
||||
}
|
||||
|
||||
env := messaging.CreateEnvelope(string(mservice.MntxGateway), model.NewNotification(mservice.MntxGateway, action))
|
||||
if _, err := env.Wrap(payload); err != nil {
|
||||
s.logger.Warn("Failed to wrap payout event payload", zapError(err))
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.producer.SendMessage(env); err != nil {
|
||||
s.logger.Warn("Failed to publish payout event", zapError(err))
|
||||
}
|
||||
}
|
||||
|
||||
func zapError(err error) zap.Field {
|
||||
return zap.Error(err)
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
moneyv1 "github.com/tech/sendico/pkg/proto/common/money/v1"
|
||||
mntxv1 "github.com/tech/sendico/pkg/proto/gateway/mntx/v1"
|
||||
)
|
||||
|
||||
func validateAmount(amount *moneyv1.Money) error {
|
||||
if amount == nil {
|
||||
return newPayoutError("missing_amount", merrors.InvalidArgument("amount is required", "amount"))
|
||||
}
|
||||
|
||||
if strings.TrimSpace(amount.Currency) == "" {
|
||||
return newPayoutError("missing_currency", merrors.InvalidArgument("amount currency is required", "amount.currency"))
|
||||
}
|
||||
|
||||
val := strings.TrimSpace(amount.Amount)
|
||||
if val == "" {
|
||||
return newPayoutError("missing_amount_value", merrors.InvalidArgument("amount value is required", "amount.amount"))
|
||||
}
|
||||
dec, err := decimal.NewFromString(val)
|
||||
if err != nil {
|
||||
return newPayoutError("invalid_amount", merrors.InvalidArgument("amount must be a decimal value", "amount.amount"))
|
||||
}
|
||||
if dec.Sign() <= 0 {
|
||||
return newPayoutError("non_positive_amount", merrors.InvalidArgument("amount must be positive", "amount.amount"))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateDestination(dest *mntxv1.PayoutDestination) error {
|
||||
if dest == nil {
|
||||
return newPayoutError("missing_destination", merrors.InvalidArgument("destination is required", "destination"))
|
||||
}
|
||||
|
||||
if bank := dest.GetBankAccount(); bank != nil {
|
||||
return validateBankAccount(bank)
|
||||
}
|
||||
|
||||
if card := dest.GetCard(); card != nil {
|
||||
return validateCardDestination(card)
|
||||
}
|
||||
|
||||
return newPayoutError("invalid_destination", merrors.InvalidArgument("destination must include bank_account or card", "destination"))
|
||||
}
|
||||
|
||||
func validateBankAccount(dest *mntxv1.BankAccount) error {
|
||||
if dest == nil {
|
||||
return newPayoutError("missing_destination", merrors.InvalidArgument("destination is required", "destination"))
|
||||
}
|
||||
iban := strings.TrimSpace(dest.Iban)
|
||||
holder := strings.TrimSpace(dest.AccountHolder)
|
||||
|
||||
if iban == "" && holder == "" {
|
||||
return newPayoutError("invalid_destination", merrors.InvalidArgument("destination must include iban or account_holder", "destination"))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateCardDestination(card *mntxv1.CardDestination) error {
|
||||
if card == nil {
|
||||
return newPayoutError("missing_destination", merrors.InvalidArgument("destination.card is required", "destination.card"))
|
||||
}
|
||||
|
||||
pan := strings.TrimSpace(card.GetPan())
|
||||
token := strings.TrimSpace(card.GetToken())
|
||||
if pan == "" && token == "" {
|
||||
return newPayoutError("invalid_card_destination", merrors.InvalidArgument("card destination must include pan or token", "destination.card"))
|
||||
}
|
||||
|
||||
if strings.TrimSpace(card.GetCardholderName()) == "" {
|
||||
return newPayoutError("missing_cardholder_name", merrors.InvalidArgument("cardholder_name is required", "destination.card.cardholder_name"))
|
||||
}
|
||||
|
||||
month := strings.TrimSpace(card.GetExpMonth())
|
||||
year := strings.TrimSpace(card.GetExpYear())
|
||||
if pan != "" {
|
||||
if err := validateExpiry(month, year); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateExpiry(month, year string) error {
|
||||
if month == "" || year == "" {
|
||||
return newPayoutError("missing_expiry", merrors.InvalidArgument("exp_month and exp_year are required for card payouts", "destination.card.expiry"))
|
||||
}
|
||||
|
||||
m, err := strconv.Atoi(month)
|
||||
if err != nil || m < 1 || m > 12 {
|
||||
return newPayoutError("invalid_expiry_month", merrors.InvalidArgument("exp_month must be between 01 and 12", "destination.card.exp_month"))
|
||||
}
|
||||
|
||||
if _, err := strconv.Atoi(year); err != nil || len(year) < 2 {
|
||||
return newPayoutError("invalid_expiry_year", merrors.InvalidArgument("exp_year must be numeric", "destination.card.exp_year"))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -5,30 +5,34 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/tech/sendico/gateway/mntx/internal/appversion"
|
||||
"github.com/tech/sendico/gateway/mntx/internal/service/monetix"
|
||||
"github.com/tech/sendico/pkg/api/routers"
|
||||
"github.com/tech/sendico/pkg/api/routers/gsresponse"
|
||||
clockpkg "github.com/tech/sendico/pkg/clock"
|
||||
"github.com/tech/sendico/pkg/discovery"
|
||||
msg "github.com/tech/sendico/pkg/messaging"
|
||||
"github.com/tech/sendico/pkg/mlogger"
|
||||
"github.com/tech/sendico/pkg/mservice"
|
||||
gatewayv1 "github.com/tech/sendico/pkg/proto/common/gateway/v1"
|
||||
mntxv1 "github.com/tech/sendico/pkg/proto/gateway/mntx/v1"
|
||||
unifiedv1 "github.com/tech/sendico/pkg/proto/gateway/unified/v1"
|
||||
"go.uber.org/zap"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
logger mlogger.Logger
|
||||
clock clockpkg.Clock
|
||||
producer msg.Producer
|
||||
store *payoutStore
|
||||
cardStore *cardPayoutStore
|
||||
config monetix.Config
|
||||
httpClient *http.Client
|
||||
card *cardPayoutProcessor
|
||||
logger mlogger.Logger
|
||||
clock clockpkg.Clock
|
||||
producer msg.Producer
|
||||
cardStore *cardPayoutStore
|
||||
config monetix.Config
|
||||
httpClient *http.Client
|
||||
card *cardPayoutProcessor
|
||||
gatewayDescriptor *gatewayv1.GatewayInstanceDescriptor
|
||||
announcer *discovery.Announcer
|
||||
|
||||
mntxv1.UnimplementedMntxGatewayServiceServer
|
||||
unifiedv1.UnimplementedUnifiedGatewayServiceServer
|
||||
}
|
||||
|
||||
type payoutFailure interface {
|
||||
@@ -58,7 +62,6 @@ func NewService(logger mlogger.Logger, opts ...Option) *Service {
|
||||
svc := &Service{
|
||||
logger: logger.Named("service"),
|
||||
clock: clockpkg.NewSystem(),
|
||||
store: newPayoutStore(),
|
||||
cardStore: newCardPayoutStore(),
|
||||
config: monetix.DefaultConfig(),
|
||||
}
|
||||
@@ -86,6 +89,7 @@ func NewService(logger mlogger.Logger, opts ...Option) *Service {
|
||||
}
|
||||
|
||||
svc.card = newCardPayoutProcessor(svc.logger, svc.config, svc.clock, svc.cardStore, svc.httpClient, svc.producer)
|
||||
svc.startDiscoveryAnnouncer()
|
||||
|
||||
return svc
|
||||
}
|
||||
@@ -93,10 +97,19 @@ func NewService(logger mlogger.Logger, opts ...Option) *Service {
|
||||
// Register wires the service onto the provided gRPC router.
|
||||
func (s *Service) Register(router routers.GRPC) error {
|
||||
return router.Register(func(reg grpc.ServiceRegistrar) {
|
||||
mntxv1.RegisterMntxGatewayServiceServer(reg, s)
|
||||
unifiedv1.RegisterUnifiedGatewayServiceServer(reg, s)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) Shutdown() {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
if s.announcer != nil {
|
||||
s.announcer.Stop()
|
||||
}
|
||||
}
|
||||
|
||||
func executeUnary[TReq any, TResp any](ctx context.Context, svc *Service, method string, handler func(context.Context, *TReq) gsresponse.Responder[TResp], req *TReq) (*TResp, error) {
|
||||
log := svc.logger.Named("rpc")
|
||||
log.Info("RPC request started", zap.String("method", method))
|
||||
@@ -114,10 +127,6 @@ func executeUnary[TReq any, TResp any](ctx context.Context, svc *Service, method
|
||||
return resp, err
|
||||
}
|
||||
|
||||
func newPayoutRef() string {
|
||||
return "pyt_" + strings.ReplaceAll(uuid.New().String(), "-", "")
|
||||
}
|
||||
|
||||
func normalizeReason(reason string) string {
|
||||
return strings.ToLower(strings.TrimSpace(reason))
|
||||
}
|
||||
@@ -128,3 +137,60 @@ func newPayoutError(reason string, err error) error {
|
||||
err: err,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) startDiscoveryAnnouncer() {
|
||||
if s == nil || s.producer == nil {
|
||||
return
|
||||
}
|
||||
announce := discovery.Announcement{
|
||||
Service: "CARD_PAYOUT_RAIL_GATEWAY",
|
||||
Rail: "CARD_PAYOUT",
|
||||
Operations: []string{"payout.card"},
|
||||
InvokeURI: discovery.DefaultInvokeURI(string(mservice.MntxGateway)),
|
||||
Version: appversion.Create().Short(),
|
||||
}
|
||||
if s.gatewayDescriptor != nil {
|
||||
if id := strings.TrimSpace(s.gatewayDescriptor.GetId()); id != "" {
|
||||
announce.ID = id
|
||||
}
|
||||
announce.Network = strings.TrimSpace(s.gatewayDescriptor.GetNetwork())
|
||||
announce.Currencies = append([]string(nil), s.gatewayDescriptor.GetCurrencies()...)
|
||||
announce.Limits = limitsFromDescriptor(s.gatewayDescriptor.GetLimits())
|
||||
}
|
||||
s.announcer = discovery.NewAnnouncer(s.logger, s.producer, string(mservice.MntxGateway), announce)
|
||||
s.announcer.Start()
|
||||
}
|
||||
|
||||
func limitsFromDescriptor(src *gatewayv1.Limits) *discovery.Limits {
|
||||
if src == nil {
|
||||
return nil
|
||||
}
|
||||
limits := &discovery.Limits{
|
||||
MinAmount: strings.TrimSpace(src.GetMinAmount()),
|
||||
MaxAmount: strings.TrimSpace(src.GetMaxAmount()),
|
||||
VolumeLimit: map[string]string{},
|
||||
VelocityLimit: map[string]int{},
|
||||
}
|
||||
for key, value := range src.GetVolumeLimit() {
|
||||
k := strings.TrimSpace(key)
|
||||
v := strings.TrimSpace(value)
|
||||
if k == "" || v == "" {
|
||||
continue
|
||||
}
|
||||
limits.VolumeLimit[k] = v
|
||||
}
|
||||
for key, value := range src.GetVelocityLimit() {
|
||||
k := strings.TrimSpace(key)
|
||||
if k == "" {
|
||||
continue
|
||||
}
|
||||
limits.VelocityLimit[k] = int(value)
|
||||
}
|
||||
if len(limits.VolumeLimit) == 0 {
|
||||
limits.VolumeLimit = nil
|
||||
}
|
||||
if len(limits.VelocityLimit) == 0 {
|
||||
limits.VelocityLimit = nil
|
||||
}
|
||||
return limits
|
||||
}
|
||||
|
||||
1
api/gateway/tgsettle/.gitignore
vendored
Normal file
1
api/gateway/tgsettle/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
/mntx-gateway
|
||||
40
api/gateway/tgsettle/config.yml
Normal file
40
api/gateway/tgsettle/config.yml
Normal file
@@ -0,0 +1,40 @@
|
||||
runtime:
|
||||
shutdown_timeout_seconds: 15
|
||||
|
||||
grpc:
|
||||
network: tcp
|
||||
address: ":50080"
|
||||
enable_reflection: true
|
||||
enable_health: true
|
||||
|
||||
metrics:
|
||||
address: ":9406"
|
||||
|
||||
database:
|
||||
driver: mongodb
|
||||
settings:
|
||||
host_env: TGSETTLE_GATEWAY_MONGO_HOST
|
||||
port_env: TGSETTLE_GATEWAY_MONGO_PORT
|
||||
database_env: TGSETTLE_GATEWAY_MONGO_DATABASE
|
||||
user_env: TGSETTLE_GATEWAY_MONGO_USER
|
||||
password_env: TGSETTLE_GATEWAY_MONGO_PASSWORD
|
||||
auth_source_env: TGSETTLE_GATEWAY_MONGO_AUTH_SOURCE
|
||||
replica_set_env: TGSETTLE_GATEWAY_MONGO_REPLICA_SET
|
||||
|
||||
messaging:
|
||||
driver: NATS
|
||||
settings:
|
||||
url_env: NATS_URL
|
||||
host_env: NATS_HOST
|
||||
port_env: NATS_PORT
|
||||
username_env: NATS_USER
|
||||
password_env: NATS_PASSWORD
|
||||
broker_name: TGSettle Gateway Service
|
||||
max_reconnects: 10
|
||||
reconnect_wait: 5
|
||||
|
||||
gateway:
|
||||
rail: "provider_settlement"
|
||||
target_chat_id_env: TGSETTLE_GATEWAY_CHAT_ID
|
||||
timeout_seconds: 120
|
||||
accepted_user_ids: []
|
||||
51
api/gateway/tgsettle/go.mod
Normal file
51
api/gateway/tgsettle/go.mod
Normal file
@@ -0,0 +1,51 @@
|
||||
module github.com/tech/sendico/gateway/tgsettle
|
||||
|
||||
go 1.25.3
|
||||
|
||||
replace github.com/tech/sendico/pkg => ../../pkg
|
||||
|
||||
require (
|
||||
github.com/tech/sendico/pkg v0.1.0
|
||||
go.mongodb.org/mongo-driver v1.17.6
|
||||
go.uber.org/zap v1.27.1
|
||||
google.golang.org/grpc v1.78.0
|
||||
google.golang.org/protobuf v1.36.11
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/bmatcuk/doublestar/v4 v4.9.1 // indirect
|
||||
github.com/casbin/casbin/v2 v2.135.0 // indirect
|
||||
github.com/casbin/govaluate v1.10.0 // indirect
|
||||
github.com/casbin/mongodb-adapter/v3 v3.7.0 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/go-chi/chi/v5 v5.2.3 // indirect
|
||||
github.com/golang/snappy v1.0.0 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/klauspost/compress v1.18.2 // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||
github.com/montanaflynn/stats v0.7.1 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/nats-io/nats.go v1.48.0 // indirect
|
||||
github.com/nats-io/nkeys v0.4.12 // indirect
|
||||
github.com/nats-io/nuid v1.0.1 // indirect
|
||||
github.com/prometheus/client_golang v1.23.2 // indirect
|
||||
github.com/prometheus/client_model v0.6.2 // indirect
|
||||
github.com/prometheus/common v0.67.4 // indirect
|
||||
github.com/prometheus/procfs v0.19.2 // indirect
|
||||
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
|
||||
github.com/xdg-go/scram v1.2.0 // indirect
|
||||
github.com/xdg-go/stringprep v1.0.4 // indirect
|
||||
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.yaml.in/yaml/v2 v2.4.3 // indirect
|
||||
golang.org/x/crypto v0.46.0 // indirect
|
||||
golang.org/x/net v0.48.0 // indirect
|
||||
golang.org/x/sync v0.19.0 // indirect
|
||||
golang.org/x/sys v0.39.0 // indirect
|
||||
golang.org/x/text v0.32.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect
|
||||
)
|
||||
225
api/gateway/tgsettle/go.sum
Normal file
225
api/gateway/tgsettle/go.sum
Normal file
@@ -0,0 +1,225 @@
|
||||
dario.cat/mergo v1.0.1 h1:Ra4+bf83h2ztPIQYNP99R6m+Y7KfnARDfID+a+vLl4s=
|
||||
dario.cat/mergo v1.0.1/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk=
|
||||
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0=
|
||||
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
|
||||
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
|
||||
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/bmatcuk/doublestar/v4 v4.6.1/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc=
|
||||
github.com/bmatcuk/doublestar/v4 v4.9.1 h1:X8jg9rRZmJd4yRy7ZeNDRnM+T3ZfHv15JiBJ/avrEXE=
|
||||
github.com/bmatcuk/doublestar/v4 v4.9.1/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc=
|
||||
github.com/casbin/casbin/v2 v2.135.0 h1:6BLkMQiGotYyS5yYeWgW19vxqugUlvHFkFiLnLR/bxk=
|
||||
github.com/casbin/casbin/v2 v2.135.0/go.mod h1:FmcfntdXLTcYXv/hxgNntcRPqAbwOG9xsism0yXT+18=
|
||||
github.com/casbin/govaluate v1.3.0/go.mod h1:G/UnbIjZk/0uMNaLwZZmFQrR72tYRZWQkO70si/iR7A=
|
||||
github.com/casbin/govaluate v1.10.0 h1:ffGw51/hYH3w3rZcxO/KcaUIDOLP84w7nsidMVgaDG0=
|
||||
github.com/casbin/govaluate v1.10.0/go.mod h1:G/UnbIjZk/0uMNaLwZZmFQrR72tYRZWQkO70si/iR7A=
|
||||
github.com/casbin/mongodb-adapter/v3 v3.7.0 h1:w9c3bea1BGK4eZTAmk17JkY52yv/xSZDSHKji8q+z6E=
|
||||
github.com/casbin/mongodb-adapter/v3 v3.7.0/go.mod h1:F1mu4ojoJVE/8VhIMxMedhjfwRDdIXgANYs6Sd0MgVA=
|
||||
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
|
||||
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/containerd/log v0.1.0 h1:TCJt7ioM2cr/tfR8GPbGf9/VRAX8D2B4PjzCpfX540I=
|
||||
github.com/containerd/log v0.1.0/go.mod h1:VRRf09a7mHDIRezVKTRCrOq78v577GXq3bSa3EhrzVo=
|
||||
github.com/containerd/platforms v0.2.1 h1:zvwtM3rz2YHPQsF2CHYM8+KtB5dvhISiXh5ZpSBQv6A=
|
||||
github.com/containerd/platforms v0.2.1/go.mod h1:XHCb+2/hzowdiut9rkudds9bE5yJ7npe7dG/wG+uFPw=
|
||||
github.com/cpuguy83/dockercfg v0.3.2 h1:DlJTyZGBDlXqUZ2Dk2Q3xHs/FtnooJJVaad2S9GKorA=
|
||||
github.com/cpuguy83/dockercfg v0.3.2/go.mod h1:sugsbF4//dDlL/i+S+rtpIWp+5h0BHJHfjj5/jFyUJc=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
|
||||
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
|
||||
github.com/docker/docker v27.3.1+incompatible h1:KttF0XoteNTicmUtBO0L2tP+J7FGRFTjaEF4k6WdhfI=
|
||||
github.com/docker/docker v27.3.1+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
|
||||
github.com/docker/go-connections v0.5.0 h1:USnMq7hx7gwdVZq1L49hLXaFtUdTADjXGp+uj1Br63c=
|
||||
github.com/docker/go-connections v0.5.0/go.mod h1:ov60Kzw0kKElRwhNs9UlUHAE/F9Fe6GLaXnqyDdmEXc=
|
||||
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
|
||||
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
|
||||
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
|
||||
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
|
||||
github.com/go-chi/chi/v5 v5.2.3 h1:WQIt9uxdsAbgIYgid+BpYc+liqQZGMHRaUwp0JUcvdE=
|
||||
github.com/go-chi/chi/v5 v5.2.3/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
|
||||
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
|
||||
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
|
||||
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
|
||||
github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4=
|
||||
github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc=
|
||||
github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs=
|
||||
github.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/klauspost/compress v1.18.2 h1:iiPHWW0YrcFgpBYhsA6D1+fqHssJscY/Tm/y2Uqnapk=
|
||||
github.com/klauspost/compress v1.18.2/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
|
||||
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
||||
github.com/lufia/plan9stats v0.0.0-20250827001030-24949be3fa54 h1:mFWunSatvkQQDhpdyuFAYwyAan3hzCuma+Pz8sqvOfg=
|
||||
github.com/lufia/plan9stats v0.0.0-20250827001030-24949be3fa54/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg=
|
||||
github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
|
||||
github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
|
||||
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
|
||||
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
|
||||
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
|
||||
github.com/moby/patternmatcher v0.6.0 h1:GmP9lR19aU5GqSSFko+5pRqHi+Ohk1O69aFiKkVGiPk=
|
||||
github.com/moby/patternmatcher v0.6.0/go.mod h1:hDPoyOpDY7OrrMDLaYoY3hf52gNCR/YOUYxkhApJIxc=
|
||||
github.com/moby/sys/sequential v0.6.0 h1:qrx7XFUd/5DxtqcoH1h438hF5TmOvzC/lspjy7zgvCU=
|
||||
github.com/moby/sys/sequential v0.6.0/go.mod h1:uyv8EUTrca5PnDsdMGXhZe6CCe8U/UiTWd+lL+7b/Ko=
|
||||
github.com/moby/sys/user v0.3.0 h1:9ni5DlcW5an3SvRSx4MouotOygvzaXbaSrc/wGDFWPo=
|
||||
github.com/moby/sys/user v0.3.0/go.mod h1:bG+tYYYJgaMtRKgEmuueC0hJEAZWwtIbZTB+85uoHjs=
|
||||
github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/g=
|
||||
github.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28=
|
||||
github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0=
|
||||
github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y=
|
||||
github.com/montanaflynn/stats v0.7.1 h1:etflOAAHORrCC44V+aR6Ftzort912ZU+YLiSTuV8eaE=
|
||||
github.com/montanaflynn/stats v0.7.1/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow=
|
||||
github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=
|
||||
github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||
github.com/nats-io/nats.go v1.48.0 h1:pSFyXApG+yWU/TgbKCjmm5K4wrHu86231/w84qRVR+U=
|
||||
github.com/nats-io/nats.go v1.48.0/go.mod h1:iRWIPokVIFbVijxuMQq4y9ttaBTMe0SFdlZfMDd+33g=
|
||||
github.com/nats-io/nkeys v0.4.12 h1:nssm7JKOG9/x4J8II47VWCL1Ds29avyiQDRn0ckMvDc=
|
||||
github.com/nats-io/nkeys v0.4.12/go.mod h1:MT59A1HYcjIcyQDJStTfaOY6vhy9XTUjOFo+SVsvpBg=
|
||||
github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=
|
||||
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
|
||||
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
|
||||
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
|
||||
github.com/opencontainers/image-spec v1.1.0 h1:8SG7/vwALn54lVB/0yZ/MMwhFrPYtpEHQb2IpWsCzug=
|
||||
github.com/opencontainers/image-spec v1.1.0/go.mod h1:W4s4sFTMaBeK1BQLXbG4AdM2szdn85PY75RI83NrTrM=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=
|
||||
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
|
||||
github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
|
||||
github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
|
||||
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
|
||||
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
|
||||
github.com/prometheus/common v0.67.4 h1:yR3NqWO1/UyO1w2PhUvXlGQs/PtFmoveVO0KZ4+Lvsc=
|
||||
github.com/prometheus/common v0.67.4/go.mod h1:gP0fq6YjjNCLssJCQp0yk4M8W6ikLURwkdd/YKtTbyI=
|
||||
github.com/prometheus/procfs v0.19.2 h1:zUMhqEW66Ex7OXIiDkll3tl9a1ZdilUOd/F6ZXw4Vws=
|
||||
github.com/prometheus/procfs v0.19.2/go.mod h1:M0aotyiemPhBCM0z5w87kL22CxfcH05ZpYlu+b4J7mw=
|
||||
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
|
||||
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
|
||||
github.com/shirou/gopsutil/v3 v3.24.5 h1:i0t8kL+kQTvpAYToeuiVk3TgDeKOFioZO3Ztz/iZ9pI=
|
||||
github.com/shirou/gopsutil/v3 v3.24.5/go.mod h1:bsoOS1aStSs9ErQ1WWfxllSeS1K5D+U30r2NfcubMVk=
|
||||
github.com/shoenig/go-m1cpu v0.1.6 h1:nxdKQNcEB6vzgA2E2bvzKIYRuNj7XNJ4S/aRSwKzFtM=
|
||||
github.com/shoenig/go-m1cpu v0.1.6/go.mod h1:1JJMcUBvfNwpq05QDQVAnx3gUHr9IYF7GNg9SUEw2VQ=
|
||||
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
|
||||
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/testcontainers/testcontainers-go v0.33.0 h1:zJS9PfXYT5O0ZFXM2xxXfk4J5UMw/kRiISng037Gxdw=
|
||||
github.com/testcontainers/testcontainers-go v0.33.0/go.mod h1:W80YpTa8D5C3Yy16icheD01UTDu+LmXIA2Keo+jWtT8=
|
||||
github.com/testcontainers/testcontainers-go/modules/mongodb v0.33.0 h1:iXVA84s5hKMS5gn01GWOYHE3ymy/2b+0YkpFeTxB2XY=
|
||||
github.com/testcontainers/testcontainers-go/modules/mongodb v0.33.0/go.mod h1:R6tMjTojRiaoo89fh/hf7tOmfzohdqSU17R9DwSVSog=
|
||||
github.com/tklauser/go-sysconf v0.3.15 h1:VE89k0criAymJ/Os65CSn1IXaol+1wrsFHEB8Ol49K4=
|
||||
github.com/tklauser/go-sysconf v0.3.15/go.mod h1:Dmjwr6tYFIseJw7a3dRLJfsHAMXZ3nEnL/aZY+0IuI4=
|
||||
github.com/tklauser/numcpus v0.10.0 h1:18njr6LDBk1zuna922MgdjQuJFjrdppsZG60sHGfjso=
|
||||
github.com/tklauser/numcpus v0.10.0/go.mod h1:BiTKazU708GQTYF4mB+cmlpT2Is1gLk7XVuEeem8LsQ=
|
||||
github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=
|
||||
github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI=
|
||||
github.com/xdg-go/scram v1.2.0 h1:bYKF2AEwG5rqd1BumT4gAnvwU/M9nBp2pTSxeZw7Wvs=
|
||||
github.com/xdg-go/scram v1.2.0/go.mod h1:3dlrS0iBaWKYVt2ZfA4cj48umJZ+cAEbR6/SjLA88I8=
|
||||
github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8=
|
||||
github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM=
|
||||
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zUTJ0trRztfwgjqKnBWNtSRkbmwM=
|
||||
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
|
||||
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
|
||||
go.mongodb.org/mongo-driver v1.17.6 h1:87JUG1wZfWsr6rIz3ZmpH90rL5tea7O3IHuSwHUpsss=
|
||||
go.mongodb.org/mongo-driver v1.17.6/go.mod h1:Hy04i7O2kC4RS06ZrhPRqj/u4DTYkFDAAccj+rVKqgQ=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.56.0 h1:UP6IpuHFkUgOQL9FFQFrZ+5LiwhhYRbi7VZSIx6Nj5s=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.56.0/go.mod h1:qxuZLtbq5QDtdeSHsS7bcf6EH6uO6jUAgk764zd3rhM=
|
||||
go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8=
|
||||
go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM=
|
||||
go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA=
|
||||
go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI=
|
||||
go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E=
|
||||
go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.38.0/go.mod h1:dg9PBnW9XdQ1Hd6ZnRz689CbtrUp0wMMs9iPcgT9EZA=
|
||||
go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE=
|
||||
go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||
go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=
|
||||
go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
|
||||
go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=
|
||||
go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
|
||||
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
|
||||
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
|
||||
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
||||
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
|
||||
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
|
||||
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
|
||||
gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=
|
||||
google.golang.org/grpc v1.78.0 h1:K1XZG/yGDJnzMdd/uZHAkVqJE+xIDOcmdSFZkBUicNc=
|
||||
google.golang.org/grpc v1.78.0/go.mod h1:I47qjTo4OKbMkjA/aOOwxDIiPSBofUtQUI5EfpWvW7U=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
27
api/gateway/tgsettle/internal/appversion/version.go
Normal file
27
api/gateway/tgsettle/internal/appversion/version.go
Normal file
@@ -0,0 +1,27 @@
|
||||
package appversion
|
||||
|
||||
import (
|
||||
"github.com/tech/sendico/pkg/version"
|
||||
vf "github.com/tech/sendico/pkg/version/factory"
|
||||
)
|
||||
|
||||
// Build information. Populated at build-time.
|
||||
var (
|
||||
Version string
|
||||
Revision string
|
||||
Branch string
|
||||
BuildUser string
|
||||
BuildDate string
|
||||
)
|
||||
|
||||
func Create() version.Printer {
|
||||
info := version.Info{
|
||||
Program: "Sendico Payment Gateway Service",
|
||||
Revision: Revision,
|
||||
Branch: Branch,
|
||||
BuildUser: BuildUser,
|
||||
BuildDate: BuildDate,
|
||||
Version: Version,
|
||||
}
|
||||
return vf.Create(&info)
|
||||
}
|
||||
136
api/gateway/tgsettle/internal/server/internal/serverimp.go
Normal file
136
api/gateway/tgsettle/internal/server/internal/serverimp.go
Normal file
@@ -0,0 +1,136 @@
|
||||
package serverimp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/tech/sendico/gateway/tgsettle/internal/service/gateway"
|
||||
"github.com/tech/sendico/gateway/tgsettle/storage"
|
||||
gatewaymongo "github.com/tech/sendico/gateway/tgsettle/storage/mongo"
|
||||
"github.com/tech/sendico/pkg/api/routers"
|
||||
"github.com/tech/sendico/pkg/db"
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
msg "github.com/tech/sendico/pkg/messaging"
|
||||
mb "github.com/tech/sendico/pkg/messaging/broker"
|
||||
"github.com/tech/sendico/pkg/mlogger"
|
||||
"github.com/tech/sendico/pkg/server/grpcapp"
|
||||
"go.uber.org/zap"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
type Imp struct {
|
||||
logger mlogger.Logger
|
||||
file string
|
||||
debug bool
|
||||
|
||||
config *config
|
||||
app *grpcapp.App[storage.Repository]
|
||||
service *gateway.Service
|
||||
}
|
||||
|
||||
type config struct {
|
||||
*grpcapp.Config `yaml:",inline"`
|
||||
Gateway gatewayConfig `yaml:"gateway"`
|
||||
}
|
||||
|
||||
type gatewayConfig struct {
|
||||
Rail string `yaml:"rail"`
|
||||
TargetChatIDEnv string `yaml:"target_chat_id_env"`
|
||||
TimeoutSeconds int32 `yaml:"timeout_seconds"`
|
||||
AcceptedUserIDs []string `yaml:"accepted_user_ids"`
|
||||
}
|
||||
|
||||
func Create(logger mlogger.Logger, file string, debug bool) (*Imp, error) {
|
||||
return &Imp{
|
||||
logger: logger.Named("server"),
|
||||
file: file,
|
||||
debug: debug,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (i *Imp) Shutdown() {
|
||||
if i.app == nil {
|
||||
return
|
||||
}
|
||||
timeout := 15 * time.Second
|
||||
if i.config != nil && i.config.Runtime != nil {
|
||||
timeout = i.config.Runtime.ShutdownTimeout()
|
||||
}
|
||||
if i.service != nil {
|
||||
i.service.Shutdown()
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
i.app.Shutdown(ctx)
|
||||
}
|
||||
|
||||
func (i *Imp) Start() error {
|
||||
cfg, err := i.loadConfig()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
i.config = cfg
|
||||
|
||||
var broker mb.Broker
|
||||
if cfg.Messaging != nil && cfg.Messaging.Driver != "" {
|
||||
broker, err = msg.CreateMessagingBroker(i.logger, cfg.Messaging)
|
||||
if err != nil {
|
||||
i.logger.Warn("Failed to create messaging broker", zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
repoFactory := func(logger mlogger.Logger, conn *db.MongoConnection) (storage.Repository, error) {
|
||||
return gatewaymongo.New(logger, conn)
|
||||
}
|
||||
|
||||
serviceFactory := func(logger mlogger.Logger, repo storage.Repository, producer msg.Producer) (grpcapp.Service, error) {
|
||||
gwCfg := gateway.Config{
|
||||
Rail: cfg.Gateway.Rail,
|
||||
TargetChatIDEnv: cfg.Gateway.TargetChatIDEnv,
|
||||
TimeoutSeconds: cfg.Gateway.TimeoutSeconds,
|
||||
AcceptedUserIDs: cfg.Gateway.AcceptedUserIDs,
|
||||
}
|
||||
svc := gateway.NewService(logger, repo, producer, broker, gwCfg)
|
||||
i.service = svc
|
||||
return svc, nil
|
||||
}
|
||||
|
||||
app, err := grpcapp.NewApp(i.logger, "tgsettle_gateway", cfg.Config, i.debug, repoFactory, serviceFactory)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
i.app = app
|
||||
return i.app.Start()
|
||||
}
|
||||
|
||||
func (i *Imp) loadConfig() (*config, error) {
|
||||
data, err := os.ReadFile(i.file)
|
||||
if err != nil {
|
||||
i.logger.Error("Could not read configuration file", zap.String("config_file", i.file), zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
cfg := &config{Config: &grpcapp.Config{}}
|
||||
if err := yaml.Unmarshal(data, cfg); err != nil {
|
||||
i.logger.Error("Failed to parse configuration", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
if cfg.Runtime == nil {
|
||||
cfg.Runtime = &grpcapp.RuntimeConfig{ShutdownTimeoutSeconds: 15}
|
||||
}
|
||||
if cfg.GRPC == nil {
|
||||
cfg.GRPC = &routers.GRPCConfig{
|
||||
Network: "tcp",
|
||||
Address: ":50080",
|
||||
EnableReflection: true,
|
||||
EnableHealth: true,
|
||||
}
|
||||
}
|
||||
if cfg.Metrics == nil {
|
||||
cfg.Metrics = &grpcapp.MetricsConfig{Address: ":9406"}
|
||||
}
|
||||
if cfg.Gateway.Rail == "" {
|
||||
return nil, merrors.InvalidArgument("gateway rail is required", "gateway.rail")
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
11
api/gateway/tgsettle/internal/server/server.go
Normal file
11
api/gateway/tgsettle/internal/server/server.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
serverimp "github.com/tech/sendico/gateway/tgsettle/internal/server/internal"
|
||||
"github.com/tech/sendico/pkg/mlogger"
|
||||
"github.com/tech/sendico/pkg/server"
|
||||
)
|
||||
|
||||
func Create(logger mlogger.Logger, file string, debug bool) (server.Application, error) {
|
||||
return serverimp.Create(logger, file, debug)
|
||||
}
|
||||
541
api/gateway/tgsettle/internal/service/gateway/service.go
Normal file
541
api/gateway/tgsettle/internal/service/gateway/service.go
Normal file
@@ -0,0 +1,541 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/tech/sendico/gateway/tgsettle/storage"
|
||||
storagemodel "github.com/tech/sendico/gateway/tgsettle/storage/model"
|
||||
"github.com/tech/sendico/pkg/api/routers"
|
||||
"github.com/tech/sendico/pkg/discovery"
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
msg "github.com/tech/sendico/pkg/messaging"
|
||||
mb "github.com/tech/sendico/pkg/messaging/broker"
|
||||
cons "github.com/tech/sendico/pkg/messaging/consumer"
|
||||
confirmations "github.com/tech/sendico/pkg/messaging/notifications/confirmations"
|
||||
paymentgateway "github.com/tech/sendico/pkg/messaging/notifications/paymentgateway"
|
||||
np "github.com/tech/sendico/pkg/messaging/notifications/processor"
|
||||
"github.com/tech/sendico/pkg/mlogger"
|
||||
"github.com/tech/sendico/pkg/model"
|
||||
"github.com/tech/sendico/pkg/mservice"
|
||||
paymenttypes "github.com/tech/sendico/pkg/payments/types"
|
||||
moneyv1 "github.com/tech/sendico/pkg/proto/common/money/v1"
|
||||
chainv1 "github.com/tech/sendico/pkg/proto/gateway/chain/v1"
|
||||
unifiedv1 "github.com/tech/sendico/pkg/proto/gateway/unified/v1"
|
||||
"github.com/tech/sendico/pkg/server/grpcapp"
|
||||
"go.uber.org/zap"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultConfirmationTimeoutSeconds = 120
|
||||
executedStatus = "executed"
|
||||
)
|
||||
|
||||
const (
|
||||
metadataPaymentIntentID = "payment_intent_id"
|
||||
metadataQuoteRef = "quote_ref"
|
||||
metadataTargetChatID = "target_chat_id"
|
||||
metadataOutgoingLeg = "outgoing_leg"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Rail string
|
||||
TargetChatIDEnv string
|
||||
TimeoutSeconds int32
|
||||
AcceptedUserIDs []string
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
logger mlogger.Logger
|
||||
repo storage.Repository
|
||||
producer msg.Producer
|
||||
broker mb.Broker
|
||||
cfg Config
|
||||
rail string
|
||||
chatID string
|
||||
announcer *discovery.Announcer
|
||||
|
||||
mu sync.Mutex
|
||||
pending map[string]*model.PaymentGatewayIntent
|
||||
consumers []msg.Consumer
|
||||
|
||||
unifiedv1.UnimplementedUnifiedGatewayServiceServer
|
||||
}
|
||||
|
||||
func NewService(logger mlogger.Logger, repo storage.Repository, producer msg.Producer, broker mb.Broker, cfg Config) *Service {
|
||||
if logger != nil {
|
||||
logger = logger.Named("tgsettle_gateway")
|
||||
}
|
||||
svc := &Service{
|
||||
logger: logger,
|
||||
repo: repo,
|
||||
producer: producer,
|
||||
broker: broker,
|
||||
cfg: cfg,
|
||||
rail: strings.TrimSpace(cfg.Rail),
|
||||
pending: map[string]*model.PaymentGatewayIntent{},
|
||||
}
|
||||
svc.chatID = strings.TrimSpace(readEnv(cfg.TargetChatIDEnv))
|
||||
svc.startConsumers()
|
||||
svc.startAnnouncer()
|
||||
return svc
|
||||
}
|
||||
|
||||
func (s *Service) Register(router routers.GRPC) error {
|
||||
return router.Register(func(reg grpc.ServiceRegistrar) {
|
||||
unifiedv1.RegisterUnifiedGatewayServiceServer(reg, s)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) Shutdown() {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
if s.announcer != nil {
|
||||
s.announcer.Stop()
|
||||
}
|
||||
for _, consumer := range s.consumers {
|
||||
if consumer != nil {
|
||||
consumer.Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) startConsumers() {
|
||||
if s == nil || s.broker == nil {
|
||||
if s != nil && s.logger != nil {
|
||||
s.logger.Warn("Messaging broker not configured; confirmation flow disabled")
|
||||
}
|
||||
return
|
||||
}
|
||||
resultProcessor := confirmations.NewConfirmationResultProcessor(s.logger, string(mservice.PaymentGateway), s.rail, s.onConfirmationResult)
|
||||
s.consumeProcessor(resultProcessor)
|
||||
}
|
||||
|
||||
func (s *Service) consumeProcessor(processor np.EnvelopeProcessor) {
|
||||
consumer, err := cons.NewConsumer(s.logger, s.broker, processor.GetSubject())
|
||||
if err != nil {
|
||||
s.logger.Warn("Failed to create messaging consumer", zap.Error(err), zap.String("event", processor.GetSubject().ToString()))
|
||||
return
|
||||
}
|
||||
s.consumers = append(s.consumers, consumer)
|
||||
go func() {
|
||||
if err := consumer.ConsumeMessages(processor.Process); err != nil {
|
||||
s.logger.Warn("Messaging consumer stopped", zap.Error(err), zap.String("event", processor.GetSubject().ToString()))
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (s *Service) SubmitTransfer(ctx context.Context, req *chainv1.SubmitTransferRequest) (*chainv1.SubmitTransferResponse, error) {
|
||||
if req == nil {
|
||||
return nil, merrors.InvalidArgument("submit_transfer: request is required")
|
||||
}
|
||||
idempotencyKey := strings.TrimSpace(req.GetIdempotencyKey())
|
||||
if idempotencyKey == "" {
|
||||
return nil, merrors.InvalidArgument("submit_transfer: idempotency_key is required")
|
||||
}
|
||||
amount := req.GetAmount()
|
||||
if amount == nil || strings.TrimSpace(amount.GetAmount()) == "" || strings.TrimSpace(amount.GetCurrency()) == "" {
|
||||
return nil, merrors.InvalidArgument("submit_transfer: amount is required")
|
||||
}
|
||||
intent, err := intentFromSubmitTransfer(req, s.rail, s.chatID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if s.repo == nil || s.repo.Payments() == nil {
|
||||
return nil, merrors.Internal("payment gateway storage unavailable")
|
||||
}
|
||||
existing, err := s.repo.Payments().FindByIdempotencyKey(ctx, idempotencyKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if existing != nil {
|
||||
return &chainv1.SubmitTransferResponse{Transfer: transferFromExecution(existing, req)}, nil
|
||||
}
|
||||
if err := s.onIntent(ctx, intent); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &chainv1.SubmitTransferResponse{Transfer: transferFromRequest(req)}, nil
|
||||
}
|
||||
|
||||
func (s *Service) GetTransfer(ctx context.Context, req *chainv1.GetTransferRequest) (*chainv1.GetTransferResponse, error) {
|
||||
if req == nil {
|
||||
return nil, merrors.InvalidArgument("get_transfer: request is required")
|
||||
}
|
||||
transferRef := strings.TrimSpace(req.GetTransferRef())
|
||||
if transferRef == "" {
|
||||
return nil, merrors.InvalidArgument("get_transfer: transfer_ref is required")
|
||||
}
|
||||
if s.repo == nil || s.repo.Payments() == nil {
|
||||
return nil, merrors.Internal("payment gateway storage unavailable")
|
||||
}
|
||||
existing, err := s.repo.Payments().FindByIdempotencyKey(ctx, transferRef)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if existing != nil {
|
||||
return &chainv1.GetTransferResponse{Transfer: transferFromExecution(existing, nil)}, nil
|
||||
}
|
||||
if s.hasPending(transferRef) {
|
||||
return &chainv1.GetTransferResponse{Transfer: transferPending(transferRef)}, nil
|
||||
}
|
||||
return nil, status.Error(codes.NotFound, "transfer not found")
|
||||
}
|
||||
|
||||
func (s *Service) onIntent(ctx context.Context, intent *model.PaymentGatewayIntent) error {
|
||||
if intent == nil {
|
||||
return merrors.InvalidArgument("payment gateway intent is nil", "intent")
|
||||
}
|
||||
intent = normalizeIntent(intent)
|
||||
if intent.IdempotencyKey == "" {
|
||||
return merrors.InvalidArgument("idempotency_key is required", "idempotency_key")
|
||||
}
|
||||
if intent.PaymentIntentID == "" {
|
||||
return merrors.InvalidArgument("payment_intent_id is required", "payment_intent_id")
|
||||
}
|
||||
if intent.RequestedMoney == nil || strings.TrimSpace(intent.RequestedMoney.Amount) == "" || strings.TrimSpace(intent.RequestedMoney.Currency) == "" {
|
||||
return merrors.InvalidArgument("requested_money is required", "requested_money")
|
||||
}
|
||||
if s.repo == nil || s.repo.Payments() == nil {
|
||||
return merrors.Internal("payment gateway storage unavailable")
|
||||
}
|
||||
|
||||
existing, err := s.repo.Payments().FindByIdempotencyKey(ctx, intent.IdempotencyKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if existing != nil {
|
||||
s.logger.Info("Payment gateway intent already executed", zap.String("idempotency_key", intent.IdempotencyKey))
|
||||
return nil
|
||||
}
|
||||
|
||||
confirmReq, err := s.buildConfirmationRequest(intent)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.sendConfirmationRequest(confirmReq); err != nil {
|
||||
return err
|
||||
}
|
||||
s.trackIntent(confirmReq.RequestID, intent)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) onConfirmationResult(ctx context.Context, result *model.ConfirmationResult) error {
|
||||
if result == nil {
|
||||
return merrors.InvalidArgument("confirmation result is nil", "result")
|
||||
}
|
||||
requestID := strings.TrimSpace(result.RequestID)
|
||||
if requestID == "" {
|
||||
return merrors.InvalidArgument("confirmation request_id is required", "request_id")
|
||||
}
|
||||
intent := s.lookupIntent(requestID)
|
||||
if intent == nil {
|
||||
s.logger.Warn("Confirmation result ignored: intent not found", zap.String("request_id", requestID))
|
||||
return nil
|
||||
}
|
||||
|
||||
if result.RawReply != nil && s.repo != nil && s.repo.TelegramConfirmations() != nil {
|
||||
_ = s.repo.TelegramConfirmations().Upsert(ctx, &storagemodel.TelegramConfirmation{
|
||||
RequestID: requestID,
|
||||
PaymentIntentID: intent.PaymentIntentID,
|
||||
QuoteRef: intent.QuoteRef,
|
||||
RawReply: result.RawReply,
|
||||
})
|
||||
}
|
||||
|
||||
if result.Status == model.ConfirmationStatusConfirmed || result.Status == model.ConfirmationStatusClarified {
|
||||
exec := &storagemodel.PaymentExecution{
|
||||
IdempotencyKey: intent.IdempotencyKey,
|
||||
PaymentIntentID: intent.PaymentIntentID,
|
||||
ExecutedMoney: result.Money,
|
||||
QuoteRef: intent.QuoteRef,
|
||||
Status: executedStatus,
|
||||
}
|
||||
if err := s.repo.Payments().InsertExecution(ctx, exec); err != nil && err != storage.ErrDuplicate {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
s.publishExecution(intent, result)
|
||||
s.removeIntent(requestID)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) buildConfirmationRequest(intent *model.PaymentGatewayIntent) (*model.ConfirmationRequest, error) {
|
||||
targetChatID := strings.TrimSpace(intent.TargetChatID)
|
||||
if targetChatID == "" {
|
||||
targetChatID = s.chatID
|
||||
}
|
||||
if targetChatID == "" {
|
||||
return nil, merrors.InvalidArgument("target_chat_id is required", "target_chat_id")
|
||||
}
|
||||
rail := strings.TrimSpace(intent.OutgoingLeg)
|
||||
if rail == "" {
|
||||
rail = s.rail
|
||||
}
|
||||
timeout := s.cfg.TimeoutSeconds
|
||||
if timeout <= 0 {
|
||||
timeout = int32(defaultConfirmationTimeoutSeconds)
|
||||
}
|
||||
return &model.ConfirmationRequest{
|
||||
RequestID: intent.IdempotencyKey,
|
||||
TargetChatID: targetChatID,
|
||||
RequestedMoney: intent.RequestedMoney,
|
||||
PaymentIntentID: intent.PaymentIntentID,
|
||||
QuoteRef: intent.QuoteRef,
|
||||
AcceptedUserIDs: s.cfg.AcceptedUserIDs,
|
||||
TimeoutSeconds: timeout,
|
||||
SourceService: string(mservice.PaymentGateway),
|
||||
Rail: rail,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Service) sendConfirmationRequest(request *model.ConfirmationRequest) error {
|
||||
if request == nil {
|
||||
return merrors.InvalidArgument("confirmation request is nil", "request")
|
||||
}
|
||||
if s.producer == nil {
|
||||
return merrors.Internal("messaging producer is not configured")
|
||||
}
|
||||
env := confirmations.ConfirmationRequest(string(mservice.PaymentGateway), request)
|
||||
if err := s.producer.SendMessage(env); err != nil {
|
||||
s.logger.Warn("Failed to publish confirmation request", zap.Error(err), zap.String("request_id", request.RequestID))
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) publishExecution(intent *model.PaymentGatewayIntent, result *model.ConfirmationResult) {
|
||||
if s == nil || intent == nil || result == nil || s.producer == nil {
|
||||
return
|
||||
}
|
||||
exec := &model.PaymentGatewayExecution{
|
||||
PaymentIntentID: intent.PaymentIntentID,
|
||||
IdempotencyKey: intent.IdempotencyKey,
|
||||
QuoteRef: intent.QuoteRef,
|
||||
ExecutedMoney: result.Money,
|
||||
Status: result.Status,
|
||||
RequestID: result.RequestID,
|
||||
RawReply: result.RawReply,
|
||||
}
|
||||
env := paymentgateway.PaymentGatewayExecution(string(mservice.PaymentGateway), exec)
|
||||
if err := s.producer.SendMessage(env); err != nil {
|
||||
s.logger.Warn("Failed to publish gateway execution result", zap.Error(err), zap.String("request_id", result.RequestID))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) trackIntent(requestID string, intent *model.PaymentGatewayIntent) {
|
||||
if s == nil || intent == nil {
|
||||
return
|
||||
}
|
||||
requestID = strings.TrimSpace(requestID)
|
||||
if requestID == "" {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.pending[requestID] = intent
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
func (s *Service) lookupIntent(requestID string) *model.PaymentGatewayIntent {
|
||||
requestID = strings.TrimSpace(requestID)
|
||||
if requestID == "" {
|
||||
return nil
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.pending[requestID]
|
||||
}
|
||||
|
||||
func (s *Service) removeIntent(requestID string) {
|
||||
requestID = strings.TrimSpace(requestID)
|
||||
if requestID == "" {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
delete(s.pending, requestID)
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
func (s *Service) hasPending(requestID string) bool {
|
||||
requestID = strings.TrimSpace(requestID)
|
||||
if requestID == "" {
|
||||
return false
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
_, ok := s.pending[requestID]
|
||||
return ok
|
||||
}
|
||||
|
||||
func (s *Service) startAnnouncer() {
|
||||
if s == nil || s.producer == nil {
|
||||
return
|
||||
}
|
||||
caps := []string{"telegram_confirmation", "money_persistence", "observe.confirm", "payout.fiat"}
|
||||
if s.rail != "" {
|
||||
caps = append(caps, "confirmations."+strings.ToLower(string(mservice.PaymentGateway))+"."+strings.ToLower(s.rail))
|
||||
}
|
||||
announce := discovery.Announcement{
|
||||
Service: string(mservice.PaymentGateway),
|
||||
Rail: s.rail,
|
||||
Operations: caps,
|
||||
InvokeURI: discovery.DefaultInvokeURI(string(mservice.PaymentGateway)),
|
||||
}
|
||||
s.announcer = discovery.NewAnnouncer(s.logger, s.producer, string(mservice.PaymentGateway), announce)
|
||||
s.announcer.Start()
|
||||
}
|
||||
|
||||
func normalizeIntent(intent *model.PaymentGatewayIntent) *model.PaymentGatewayIntent {
|
||||
if intent == nil {
|
||||
return nil
|
||||
}
|
||||
cp := *intent
|
||||
cp.PaymentIntentID = strings.TrimSpace(cp.PaymentIntentID)
|
||||
cp.IdempotencyKey = strings.TrimSpace(cp.IdempotencyKey)
|
||||
cp.OutgoingLeg = strings.TrimSpace(cp.OutgoingLeg)
|
||||
cp.QuoteRef = strings.TrimSpace(cp.QuoteRef)
|
||||
cp.TargetChatID = strings.TrimSpace(cp.TargetChatID)
|
||||
if cp.RequestedMoney != nil {
|
||||
cp.RequestedMoney.Amount = strings.TrimSpace(cp.RequestedMoney.Amount)
|
||||
cp.RequestedMoney.Currency = strings.TrimSpace(cp.RequestedMoney.Currency)
|
||||
}
|
||||
return &cp
|
||||
}
|
||||
|
||||
func intentFromSubmitTransfer(req *chainv1.SubmitTransferRequest, defaultRail, defaultChatID string) (*model.PaymentGatewayIntent, error) {
|
||||
if req == nil {
|
||||
return nil, merrors.InvalidArgument("submit_transfer: request is required")
|
||||
}
|
||||
idempotencyKey := strings.TrimSpace(req.GetIdempotencyKey())
|
||||
if idempotencyKey == "" {
|
||||
return nil, merrors.InvalidArgument("submit_transfer: idempotency_key is required")
|
||||
}
|
||||
amount := req.GetAmount()
|
||||
if amount == nil {
|
||||
return nil, merrors.InvalidArgument("submit_transfer: amount is required")
|
||||
}
|
||||
requestedMoney := &paymenttypes.Money{
|
||||
Amount: strings.TrimSpace(amount.GetAmount()),
|
||||
Currency: strings.TrimSpace(amount.GetCurrency()),
|
||||
}
|
||||
if requestedMoney.Amount == "" || requestedMoney.Currency == "" {
|
||||
return nil, merrors.InvalidArgument("submit_transfer: amount is required")
|
||||
}
|
||||
metadata := req.GetMetadata()
|
||||
paymentIntentID := strings.TrimSpace(req.GetClientReference())
|
||||
if paymentIntentID == "" {
|
||||
paymentIntentID = strings.TrimSpace(metadata[metadataPaymentIntentID])
|
||||
}
|
||||
if paymentIntentID == "" {
|
||||
return nil, merrors.InvalidArgument("submit_transfer: payment_intent_id is required")
|
||||
}
|
||||
quoteRef := strings.TrimSpace(metadata[metadataQuoteRef])
|
||||
targetChatID := strings.TrimSpace(metadata[metadataTargetChatID])
|
||||
outgoingLeg := strings.TrimSpace(metadata[metadataOutgoingLeg])
|
||||
if outgoingLeg == "" {
|
||||
outgoingLeg = strings.TrimSpace(defaultRail)
|
||||
}
|
||||
if targetChatID == "" {
|
||||
targetChatID = strings.TrimSpace(defaultChatID)
|
||||
}
|
||||
return &model.PaymentGatewayIntent{
|
||||
PaymentIntentID: paymentIntentID,
|
||||
IdempotencyKey: idempotencyKey,
|
||||
OutgoingLeg: outgoingLeg,
|
||||
QuoteRef: quoteRef,
|
||||
RequestedMoney: requestedMoney,
|
||||
TargetChatID: targetChatID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func transferFromRequest(req *chainv1.SubmitTransferRequest) *chainv1.Transfer {
|
||||
if req == nil {
|
||||
return nil
|
||||
}
|
||||
amount := req.GetAmount()
|
||||
return &chainv1.Transfer{
|
||||
TransferRef: strings.TrimSpace(req.GetIdempotencyKey()),
|
||||
IdempotencyKey: strings.TrimSpace(req.GetIdempotencyKey()),
|
||||
OrganizationRef: strings.TrimSpace(req.GetOrganizationRef()),
|
||||
SourceWalletRef: strings.TrimSpace(req.GetSourceWalletRef()),
|
||||
Destination: req.GetDestination(),
|
||||
RequestedAmount: amount,
|
||||
Status: chainv1.TransferStatus_TRANSFER_SUBMITTED,
|
||||
}
|
||||
}
|
||||
|
||||
func transferFromExecution(exec *storagemodel.PaymentExecution, req *chainv1.SubmitTransferRequest) *chainv1.Transfer {
|
||||
if exec == nil {
|
||||
return nil
|
||||
}
|
||||
var requested *moneyv1.Money
|
||||
if req != nil && req.GetAmount() != nil {
|
||||
requested = req.GetAmount()
|
||||
}
|
||||
net := moneyFromPayment(exec.ExecutedMoney)
|
||||
status := chainv1.TransferStatus_TRANSFER_CONFIRMED
|
||||
if strings.TrimSpace(exec.Status) != "" && !strings.EqualFold(exec.Status, executedStatus) {
|
||||
status = chainv1.TransferStatus_TRANSFER_PENDING
|
||||
}
|
||||
transfer := &chainv1.Transfer{
|
||||
TransferRef: strings.TrimSpace(exec.IdempotencyKey),
|
||||
IdempotencyKey: strings.TrimSpace(exec.IdempotencyKey),
|
||||
RequestedAmount: requested,
|
||||
NetAmount: net,
|
||||
Status: status,
|
||||
}
|
||||
if req != nil {
|
||||
transfer.OrganizationRef = strings.TrimSpace(req.GetOrganizationRef())
|
||||
transfer.SourceWalletRef = strings.TrimSpace(req.GetSourceWalletRef())
|
||||
transfer.Destination = req.GetDestination()
|
||||
}
|
||||
if !exec.ExecutedAt.IsZero() {
|
||||
ts := timestamppb.New(exec.ExecutedAt)
|
||||
transfer.CreatedAt = ts
|
||||
transfer.UpdatedAt = ts
|
||||
}
|
||||
return transfer
|
||||
}
|
||||
|
||||
func transferPending(requestID string) *chainv1.Transfer {
|
||||
ref := strings.TrimSpace(requestID)
|
||||
if ref == "" {
|
||||
return nil
|
||||
}
|
||||
return &chainv1.Transfer{
|
||||
TransferRef: ref,
|
||||
IdempotencyKey: ref,
|
||||
Status: chainv1.TransferStatus_TRANSFER_SUBMITTED,
|
||||
}
|
||||
}
|
||||
|
||||
func moneyFromPayment(m *paymenttypes.Money) *moneyv1.Money {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
currency := strings.TrimSpace(m.Currency)
|
||||
amount := strings.TrimSpace(m.Amount)
|
||||
if currency == "" || amount == "" {
|
||||
return nil
|
||||
}
|
||||
return &moneyv1.Money{
|
||||
Currency: currency,
|
||||
Amount: amount,
|
||||
}
|
||||
}
|
||||
|
||||
func readEnv(env string) string {
|
||||
if strings.TrimSpace(env) == "" {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(os.Getenv(env))
|
||||
}
|
||||
|
||||
var _ grpcapp.Service = (*Service)(nil)
|
||||
289
api/gateway/tgsettle/internal/service/gateway/service_test.go
Normal file
289
api/gateway/tgsettle/internal/service/gateway/service_test.go
Normal file
@@ -0,0 +1,289 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/tech/sendico/gateway/tgsettle/storage"
|
||||
storagemodel "github.com/tech/sendico/gateway/tgsettle/storage/model"
|
||||
envelope "github.com/tech/sendico/pkg/messaging/envelope"
|
||||
"github.com/tech/sendico/pkg/model"
|
||||
notification "github.com/tech/sendico/pkg/model/notification"
|
||||
"github.com/tech/sendico/pkg/mservice"
|
||||
mloggerfactory "github.com/tech/sendico/pkg/mlogger/factory"
|
||||
paymenttypes "github.com/tech/sendico/pkg/payments/types"
|
||||
)
|
||||
|
||||
type fakePaymentsStore struct {
|
||||
mu sync.Mutex
|
||||
executions map[string]*storagemodel.PaymentExecution
|
||||
}
|
||||
|
||||
func (f *fakePaymentsStore) FindByIdempotencyKey(_ context.Context, key string) (*storagemodel.PaymentExecution, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.executions[key], nil
|
||||
}
|
||||
|
||||
func (f *fakePaymentsStore) InsertExecution(_ context.Context, exec *storagemodel.PaymentExecution) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.executions == nil {
|
||||
f.executions = map[string]*storagemodel.PaymentExecution{}
|
||||
}
|
||||
if _, ok := f.executions[exec.IdempotencyKey]; ok {
|
||||
return storage.ErrDuplicate
|
||||
}
|
||||
f.executions[exec.IdempotencyKey] = exec
|
||||
return nil
|
||||
}
|
||||
|
||||
type fakeTelegramStore struct {
|
||||
mu sync.Mutex
|
||||
records map[string]*storagemodel.TelegramConfirmation
|
||||
}
|
||||
|
||||
func (f *fakeTelegramStore) Upsert(_ context.Context, record *storagemodel.TelegramConfirmation) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if f.records == nil {
|
||||
f.records = map[string]*storagemodel.TelegramConfirmation{}
|
||||
}
|
||||
f.records[record.RequestID] = record
|
||||
return nil
|
||||
}
|
||||
|
||||
type fakeRepo struct {
|
||||
payments *fakePaymentsStore
|
||||
tg *fakeTelegramStore
|
||||
}
|
||||
|
||||
func (f *fakeRepo) Payments() storage.PaymentsStore {
|
||||
return f.payments
|
||||
}
|
||||
|
||||
func (f *fakeRepo) TelegramConfirmations() storage.TelegramConfirmationsStore {
|
||||
return f.tg
|
||||
}
|
||||
|
||||
type captureProducer struct {
|
||||
mu sync.Mutex
|
||||
confirmationRequests []*model.ConfirmationRequest
|
||||
executions []*model.PaymentGatewayExecution
|
||||
}
|
||||
|
||||
func (c *captureProducer) SendMessage(env envelope.Envelope) error {
|
||||
_, _ = env.Serialize()
|
||||
switch env.GetSignature().ToString() {
|
||||
case model.NewNotification(mservice.Notifications, notification.NAConfirmationRequest).ToString():
|
||||
var req model.ConfirmationRequest
|
||||
if err := json.Unmarshal(env.GetData(), &req); err == nil {
|
||||
c.mu.Lock()
|
||||
c.confirmationRequests = append(c.confirmationRequests, &req)
|
||||
c.mu.Unlock()
|
||||
}
|
||||
case model.NewNotification(mservice.PaymentGateway, notification.NAPaymentGatewayExecution).ToString():
|
||||
var exec model.PaymentGatewayExecution
|
||||
if err := json.Unmarshal(env.GetData(), &exec); err == nil {
|
||||
c.mu.Lock()
|
||||
c.executions = append(c.executions, &exec)
|
||||
c.mu.Unlock()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *captureProducer) Reset() {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.confirmationRequests = nil
|
||||
c.executions = nil
|
||||
}
|
||||
|
||||
func TestOnIntentCreatesConfirmationRequest(t *testing.T) {
|
||||
logger := mloggerfactory.NewLogger(false)
|
||||
repo := &fakeRepo{payments: &fakePaymentsStore{}, tg: &fakeTelegramStore{}}
|
||||
prod := &captureProducer{}
|
||||
t.Setenv("PGS_CHAT_ID", "-100")
|
||||
svc := NewService(logger, repo, prod, nil, Config{
|
||||
Rail: "card",
|
||||
TargetChatIDEnv: "PGS_CHAT_ID",
|
||||
TimeoutSeconds: 90,
|
||||
AcceptedUserIDs: []string{"42"},
|
||||
})
|
||||
prod.Reset()
|
||||
|
||||
intent := &model.PaymentGatewayIntent{
|
||||
PaymentIntentID: "pi-1",
|
||||
IdempotencyKey: "idem-1",
|
||||
OutgoingLeg: "card",
|
||||
QuoteRef: "quote-1",
|
||||
RequestedMoney: &paymenttypes.Money{Amount: "10.50", Currency: "USD"},
|
||||
TargetChatID: "",
|
||||
}
|
||||
if err := svc.onIntent(context.Background(), intent); err != nil {
|
||||
t.Fatalf("onIntent error: %v", err)
|
||||
}
|
||||
if len(prod.confirmationRequests) != 1 {
|
||||
t.Fatalf("expected 1 confirmation request, got %d", len(prod.confirmationRequests))
|
||||
}
|
||||
req := prod.confirmationRequests[0]
|
||||
if req.RequestID != "idem-1" || req.PaymentIntentID != "pi-1" || req.QuoteRef != "quote-1" {
|
||||
t.Fatalf("unexpected confirmation request fields: %#v", req)
|
||||
}
|
||||
if req.TargetChatID != "-100" {
|
||||
t.Fatalf("expected target chat id -100, got %q", req.TargetChatID)
|
||||
}
|
||||
if req.RequestedMoney == nil || req.RequestedMoney.Amount != "10.50" || req.RequestedMoney.Currency != "USD" {
|
||||
t.Fatalf("requested money mismatch: %#v", req.RequestedMoney)
|
||||
}
|
||||
if req.TimeoutSeconds != 90 {
|
||||
t.Fatalf("expected timeout 90, got %d", req.TimeoutSeconds)
|
||||
}
|
||||
if req.SourceService != string(mservice.PaymentGateway) || req.Rail != "card" {
|
||||
t.Fatalf("unexpected source/rail: %#v", req)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmationResultPersistsExecutionAndReply(t *testing.T) {
|
||||
logger := mloggerfactory.NewLogger(false)
|
||||
repo := &fakeRepo{payments: &fakePaymentsStore{}, tg: &fakeTelegramStore{}}
|
||||
prod := &captureProducer{}
|
||||
svc := NewService(logger, repo, prod, nil, Config{Rail: "card"})
|
||||
intent := &model.PaymentGatewayIntent{
|
||||
PaymentIntentID: "pi-2",
|
||||
IdempotencyKey: "idem-2",
|
||||
QuoteRef: "quote-2",
|
||||
OutgoingLeg: "card",
|
||||
RequestedMoney: &paymenttypes.Money{Amount: "5", Currency: "EUR"},
|
||||
}
|
||||
svc.trackIntent("idem-2", intent)
|
||||
|
||||
result := &model.ConfirmationResult{
|
||||
RequestID: "idem-2",
|
||||
Money: &paymenttypes.Money{Amount: "5", Currency: "EUR"},
|
||||
Status: model.ConfirmationStatusConfirmed,
|
||||
RawReply: &model.TelegramMessage{ChatID: "1", MessageID: "2", Text: "5 EUR"},
|
||||
}
|
||||
if err := svc.onConfirmationResult(context.Background(), result); err != nil {
|
||||
t.Fatalf("onConfirmationResult error: %v", err)
|
||||
}
|
||||
if repo.payments.executions["idem-2"] == nil {
|
||||
t.Fatalf("expected payment execution to be stored")
|
||||
}
|
||||
if repo.payments.executions["idem-2"].ExecutedMoney == nil || repo.payments.executions["idem-2"].ExecutedMoney.Amount != "5" {
|
||||
t.Fatalf("executed money not stored correctly")
|
||||
}
|
||||
if repo.tg.records["idem-2"] == nil || repo.tg.records["idem-2"].RawReply.Text != "5 EUR" {
|
||||
t.Fatalf("telegram reply not stored correctly")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClarifiedResultPersistsExecution(t *testing.T) {
|
||||
logger := mloggerfactory.NewLogger(false)
|
||||
repo := &fakeRepo{payments: &fakePaymentsStore{}, tg: &fakeTelegramStore{}}
|
||||
prod := &captureProducer{}
|
||||
svc := NewService(logger, repo, prod, nil, Config{Rail: "card"})
|
||||
intent := &model.PaymentGatewayIntent{
|
||||
PaymentIntentID: "pi-clarified",
|
||||
IdempotencyKey: "idem-clarified",
|
||||
QuoteRef: "quote-clarified",
|
||||
OutgoingLeg: "card",
|
||||
RequestedMoney: &paymenttypes.Money{Amount: "12", Currency: "USD"},
|
||||
}
|
||||
svc.trackIntent("idem-clarified", intent)
|
||||
|
||||
result := &model.ConfirmationResult{
|
||||
RequestID: "idem-clarified",
|
||||
Money: &paymenttypes.Money{Amount: "12", Currency: "USD"},
|
||||
Status: model.ConfirmationStatusClarified,
|
||||
RawReply: &model.TelegramMessage{ChatID: "1", MessageID: "3", Text: "12 USD"},
|
||||
}
|
||||
if err := svc.onConfirmationResult(context.Background(), result); err != nil {
|
||||
t.Fatalf("onConfirmationResult error: %v", err)
|
||||
}
|
||||
if repo.payments.executions["idem-clarified"] == nil {
|
||||
t.Fatalf("expected payment execution to be stored")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdempotencyPreventsDuplicateWrites(t *testing.T) {
|
||||
logger := mloggerfactory.NewLogger(false)
|
||||
repo := &fakeRepo{payments: &fakePaymentsStore{executions: map[string]*storagemodel.PaymentExecution{
|
||||
"idem-3": {IdempotencyKey: "idem-3"},
|
||||
}}, tg: &fakeTelegramStore{}}
|
||||
prod := &captureProducer{}
|
||||
svc := NewService(logger, repo, prod, nil, Config{Rail: "card"})
|
||||
intent := &model.PaymentGatewayIntent{
|
||||
PaymentIntentID: "pi-3",
|
||||
IdempotencyKey: "idem-3",
|
||||
OutgoingLeg: "card",
|
||||
QuoteRef: "quote-3",
|
||||
RequestedMoney: &paymenttypes.Money{Amount: "1", Currency: "USD"},
|
||||
TargetChatID: "chat",
|
||||
}
|
||||
if err := svc.onIntent(context.Background(), intent); err != nil {
|
||||
t.Fatalf("onIntent error: %v", err)
|
||||
}
|
||||
if len(prod.confirmationRequests) != 0 {
|
||||
t.Fatalf("expected no confirmation request for duplicate intent")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTimeoutDoesNotPersistExecution(t *testing.T) {
|
||||
logger := mloggerfactory.NewLogger(false)
|
||||
repo := &fakeRepo{payments: &fakePaymentsStore{}, tg: &fakeTelegramStore{}}
|
||||
prod := &captureProducer{}
|
||||
svc := NewService(logger, repo, prod, nil, Config{Rail: "card"})
|
||||
intent := &model.PaymentGatewayIntent{
|
||||
PaymentIntentID: "pi-4",
|
||||
IdempotencyKey: "idem-4",
|
||||
QuoteRef: "quote-4",
|
||||
OutgoingLeg: "card",
|
||||
RequestedMoney: &paymenttypes.Money{Amount: "8", Currency: "USD"},
|
||||
}
|
||||
svc.trackIntent("idem-4", intent)
|
||||
|
||||
result := &model.ConfirmationResult{
|
||||
RequestID: "idem-4",
|
||||
Status: model.ConfirmationStatusTimeout,
|
||||
}
|
||||
if err := svc.onConfirmationResult(context.Background(), result); err != nil {
|
||||
t.Fatalf("onConfirmationResult error: %v", err)
|
||||
}
|
||||
if repo.payments.executions["idem-4"] != nil {
|
||||
t.Fatalf("expected no execution record for timeout")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRejectedDoesNotPersistExecution(t *testing.T) {
|
||||
logger := mloggerfactory.NewLogger(false)
|
||||
repo := &fakeRepo{payments: &fakePaymentsStore{}, tg: &fakeTelegramStore{}}
|
||||
prod := &captureProducer{}
|
||||
svc := NewService(logger, repo, prod, nil, Config{Rail: "card"})
|
||||
intent := &model.PaymentGatewayIntent{
|
||||
PaymentIntentID: "pi-reject",
|
||||
IdempotencyKey: "idem-reject",
|
||||
QuoteRef: "quote-reject",
|
||||
OutgoingLeg: "card",
|
||||
RequestedMoney: &paymenttypes.Money{Amount: "3", Currency: "USD"},
|
||||
}
|
||||
svc.trackIntent("idem-reject", intent)
|
||||
|
||||
result := &model.ConfirmationResult{
|
||||
RequestID: "idem-reject",
|
||||
Status: model.ConfirmationStatusRejected,
|
||||
RawReply: &model.TelegramMessage{ChatID: "1", MessageID: "4", Text: "no"},
|
||||
}
|
||||
if err := svc.onConfirmationResult(context.Background(), result); err != nil {
|
||||
t.Fatalf("onConfirmationResult error: %v", err)
|
||||
}
|
||||
if repo.payments.executions["idem-reject"] != nil {
|
||||
t.Fatalf("expected no execution record for rejection")
|
||||
}
|
||||
if repo.tg.records["idem-reject"] == nil {
|
||||
t.Fatalf("expected raw reply to be stored for rejection")
|
||||
}
|
||||
}
|
||||
17
api/gateway/tgsettle/main.go
Normal file
17
api/gateway/tgsettle/main.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/tech/sendico/gateway/tgsettle/internal/appversion"
|
||||
si "github.com/tech/sendico/gateway/tgsettle/internal/server"
|
||||
"github.com/tech/sendico/pkg/mlogger"
|
||||
"github.com/tech/sendico/pkg/server"
|
||||
smain "github.com/tech/sendico/pkg/server/main"
|
||||
)
|
||||
|
||||
func factory(logger mlogger.Logger, file string, debug bool) (server.Application, error) {
|
||||
return si.Create(logger, file, debug)
|
||||
}
|
||||
|
||||
func main() {
|
||||
smain.RunServer("gateway", appversion.Create(), factory)
|
||||
}
|
||||
28
api/gateway/tgsettle/storage/model/execution.go
Normal file
28
api/gateway/tgsettle/storage/model/execution.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/tech/sendico/pkg/model"
|
||||
paymenttypes "github.com/tech/sendico/pkg/payments/types"
|
||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||
)
|
||||
|
||||
type PaymentExecution struct {
|
||||
ID primitive.ObjectID `bson:"_id,omitempty" json:"id"`
|
||||
IdempotencyKey string `bson:"idempotencyKey,omitempty" json:"idempotency_key,omitempty"`
|
||||
PaymentIntentID string `bson:"paymentIntentId,omitempty" json:"payment_intent_id,omitempty"`
|
||||
ExecutedMoney *paymenttypes.Money `bson:"executedMoney,omitempty" json:"executed_money,omitempty"`
|
||||
QuoteRef string `bson:"quoteRef,omitempty" json:"quote_ref,omitempty"`
|
||||
ExecutedAt time.Time `bson:"executedAt,omitempty" json:"executed_at,omitempty"`
|
||||
Status string `bson:"status,omitempty" json:"status,omitempty"`
|
||||
}
|
||||
|
||||
type TelegramConfirmation struct {
|
||||
ID primitive.ObjectID `bson:"_id,omitempty" json:"id"`
|
||||
RequestID string `bson:"requestId,omitempty" json:"request_id,omitempty"`
|
||||
PaymentIntentID string `bson:"paymentIntentId,omitempty" json:"payment_intent_id,omitempty"`
|
||||
QuoteRef string `bson:"quoteRef,omitempty" json:"quote_ref,omitempty"`
|
||||
RawReply *model.TelegramMessage `bson:"rawReply,omitempty" json:"raw_reply,omitempty"`
|
||||
ReceivedAt time.Time `bson:"receivedAt,omitempty" json:"received_at,omitempty"`
|
||||
}
|
||||
68
api/gateway/tgsettle/storage/mongo/repository.go
Normal file
68
api/gateway/tgsettle/storage/mongo/repository.go
Normal file
@@ -0,0 +1,68 @@
|
||||
package mongo
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/tech/sendico/gateway/tgsettle/storage"
|
||||
"github.com/tech/sendico/gateway/tgsettle/storage/mongo/store"
|
||||
"github.com/tech/sendico/pkg/db"
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
"github.com/tech/sendico/pkg/mlogger"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
type Repository struct {
|
||||
logger mlogger.Logger
|
||||
conn *db.MongoConnection
|
||||
db *mongo.Database
|
||||
|
||||
payments storage.PaymentsStore
|
||||
tg storage.TelegramConfirmationsStore
|
||||
}
|
||||
|
||||
func New(logger mlogger.Logger, conn *db.MongoConnection) (*Repository, error) {
|
||||
if conn == nil {
|
||||
return nil, merrors.InvalidArgument("mongo connection is nil")
|
||||
}
|
||||
client := conn.Client()
|
||||
if client == nil {
|
||||
return nil, merrors.Internal("mongo client is not initialised")
|
||||
}
|
||||
result := &Repository{
|
||||
logger: logger.Named("storage").Named("mongo"),
|
||||
conn: conn,
|
||||
db: conn.Database(),
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := result.conn.Ping(ctx); err != nil {
|
||||
result.logger.Error("Mongo ping failed during repository initialisation", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
paymentsStore, err := store.NewPayments(result.logger, result.db)
|
||||
if err != nil {
|
||||
result.logger.Error("Failed to initialise payments store", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
tgStore, err := store.NewTelegramConfirmations(result.logger, result.db)
|
||||
if err != nil {
|
||||
result.logger.Error("Failed to initialise telegram confirmations store", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
result.payments = paymentsStore
|
||||
result.tg = tgStore
|
||||
result.logger.Info("Payment gateway MongoDB storage initialised")
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (r *Repository) Payments() storage.PaymentsStore {
|
||||
return r.payments
|
||||
}
|
||||
|
||||
func (r *Repository) TelegramConfirmations() storage.TelegramConfirmationsStore {
|
||||
return r.tg
|
||||
}
|
||||
|
||||
var _ storage.Repository = (*Repository)(nil)
|
||||
82
api/gateway/tgsettle/storage/mongo/store/payments.go
Normal file
82
api/gateway/tgsettle/storage/mongo/store/payments.go
Normal file
@@ -0,0 +1,82 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/tech/sendico/gateway/tgsettle/storage"
|
||||
"github.com/tech/sendico/gateway/tgsettle/storage/model"
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
"github.com/tech/sendico/pkg/mlogger"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
const (
|
||||
paymentsCollection = "payments"
|
||||
fieldIdempotencyKey = "idempotencyKey"
|
||||
)
|
||||
|
||||
type Payments struct {
|
||||
logger mlogger.Logger
|
||||
coll *mongo.Collection
|
||||
}
|
||||
|
||||
func NewPayments(logger mlogger.Logger, db *mongo.Database) (*Payments, error) {
|
||||
if db == nil {
|
||||
return nil, merrors.InvalidArgument("mongo database is nil")
|
||||
}
|
||||
p := &Payments{
|
||||
logger: logger.Named("payments"),
|
||||
coll: db.Collection(paymentsCollection),
|
||||
}
|
||||
_, err := p.coll.Indexes().CreateOne(context.Background(), mongo.IndexModel{
|
||||
Keys: bson.D{{Key: fieldIdempotencyKey, Value: 1}},
|
||||
Options: options.Index().SetUnique(true),
|
||||
})
|
||||
if err != nil {
|
||||
p.logger.Error("Failed to create payments idempotency index", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func (p *Payments) FindByIdempotencyKey(ctx context.Context, key string) (*model.PaymentExecution, error) {
|
||||
key = strings.TrimSpace(key)
|
||||
if key == "" {
|
||||
return nil, merrors.InvalidArgument("idempotency key is required", "idempotency_key")
|
||||
}
|
||||
var result model.PaymentExecution
|
||||
err := p.coll.FindOne(ctx, bson.M{fieldIdempotencyKey: key}).Decode(&result)
|
||||
if err == mongo.ErrNoDocuments {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &result, nil
|
||||
}
|
||||
|
||||
func (p *Payments) InsertExecution(ctx context.Context, exec *model.PaymentExecution) error {
|
||||
if exec == nil {
|
||||
return merrors.InvalidArgument("payment execution is nil", "execution")
|
||||
}
|
||||
exec.IdempotencyKey = strings.TrimSpace(exec.IdempotencyKey)
|
||||
exec.PaymentIntentID = strings.TrimSpace(exec.PaymentIntentID)
|
||||
exec.QuoteRef = strings.TrimSpace(exec.QuoteRef)
|
||||
if exec.ExecutedAt.IsZero() {
|
||||
exec.ExecutedAt = time.Now()
|
||||
}
|
||||
if _, err := p.coll.InsertOne(ctx, exec); err != nil {
|
||||
if mongo.IsDuplicateKeyError(err) {
|
||||
return storage.ErrDuplicate
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var _ storage.PaymentsStore = (*Payments)(nil)
|
||||
@@ -0,0 +1,67 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/tech/sendico/gateway/tgsettle/storage"
|
||||
"github.com/tech/sendico/gateway/tgsettle/storage/model"
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
"github.com/tech/sendico/pkg/mlogger"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
const (
|
||||
telegramCollection = "telegram_confirmations"
|
||||
fieldRequestID = "requestId"
|
||||
)
|
||||
|
||||
type TelegramConfirmations struct {
|
||||
logger mlogger.Logger
|
||||
coll *mongo.Collection
|
||||
}
|
||||
|
||||
func NewTelegramConfirmations(logger mlogger.Logger, db *mongo.Database) (*TelegramConfirmations, error) {
|
||||
if db == nil {
|
||||
return nil, merrors.InvalidArgument("mongo database is nil")
|
||||
}
|
||||
t := &TelegramConfirmations{
|
||||
logger: logger.Named("telegram_confirmations"),
|
||||
coll: db.Collection(telegramCollection),
|
||||
}
|
||||
_, err := t.coll.Indexes().CreateOne(context.Background(), mongo.IndexModel{
|
||||
Keys: bson.D{{Key: fieldRequestID, Value: 1}},
|
||||
Options: options.Index().SetUnique(true),
|
||||
})
|
||||
if err != nil {
|
||||
t.logger.Error("Failed to create telegram confirmations request_id index", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
func (t *TelegramConfirmations) Upsert(ctx context.Context, record *model.TelegramConfirmation) error {
|
||||
if record == nil {
|
||||
return merrors.InvalidArgument("telegram confirmation is nil", "record")
|
||||
}
|
||||
record.RequestID = strings.TrimSpace(record.RequestID)
|
||||
record.PaymentIntentID = strings.TrimSpace(record.PaymentIntentID)
|
||||
record.QuoteRef = strings.TrimSpace(record.QuoteRef)
|
||||
if record.RequestID == "" {
|
||||
return merrors.InvalidArgument("request_id is required", "request_id")
|
||||
}
|
||||
if record.ReceivedAt.IsZero() {
|
||||
record.ReceivedAt = time.Now()
|
||||
}
|
||||
update := bson.M{
|
||||
"$set": record,
|
||||
}
|
||||
_, err := t.coll.UpdateOne(ctx, bson.M{fieldRequestID: record.RequestID}, update, options.Update().SetUpsert(true))
|
||||
return err
|
||||
}
|
||||
|
||||
var _ storage.TelegramConfirmationsStore = (*TelegramConfirmations)(nil)
|
||||
24
api/gateway/tgsettle/storage/storage.go
Normal file
24
api/gateway/tgsettle/storage/storage.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/tech/sendico/gateway/tgsettle/storage/model"
|
||||
)
|
||||
|
||||
var ErrDuplicate = errors.New("payment gateway storage: duplicate record")
|
||||
|
||||
type Repository interface {
|
||||
Payments() PaymentsStore
|
||||
TelegramConfirmations() TelegramConfirmationsStore
|
||||
}
|
||||
|
||||
type PaymentsStore interface {
|
||||
FindByIdempotencyKey(ctx context.Context, key string) (*model.PaymentExecution, error)
|
||||
InsertExecution(ctx context.Context, exec *model.PaymentExecution) error
|
||||
}
|
||||
|
||||
type TelegramConfirmationsStore interface {
|
||||
Upsert(ctx context.Context, record *model.TelegramConfirmation) error
|
||||
}
|
||||
@@ -8,6 +8,9 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
"github.com/tech/sendico/pkg/payments/rail"
|
||||
moneyv1 "github.com/tech/sendico/pkg/proto/common/money/v1"
|
||||
unifiedv1 "github.com/tech/sendico/pkg/proto/gateway/unified/v1"
|
||||
ledgerv1 "github.com/tech/sendico/pkg/proto/ledger/v1"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials"
|
||||
@@ -16,6 +19,10 @@ import (
|
||||
|
||||
// Client exposes typed helpers around the ledger gRPC API.
|
||||
type Client interface {
|
||||
ReadBalance(ctx context.Context, accountID string) (*moneyv1.Money, error)
|
||||
CreateTransaction(ctx context.Context, tx rail.LedgerTx) (string, error)
|
||||
HoldBalance(ctx context.Context, accountID string, amount string) error
|
||||
|
||||
CreateAccount(ctx context.Context, req *ledgerv1.CreateAccountRequest) (*ledgerv1.CreateAccountResponse, error)
|
||||
ListAccounts(ctx context.Context, req *ledgerv1.ListAccountsRequest) (*ledgerv1.ListAccountsResponse, error)
|
||||
PostCreditWithCharges(ctx context.Context, req *ledgerv1.PostCreditRequest) (*ledgerv1.PostResponse, error)
|
||||
@@ -75,7 +82,7 @@ func New(ctx context.Context, cfg Config, opts ...grpc.DialOption) (Client, erro
|
||||
return &ledgerClient{
|
||||
cfg: cfg,
|
||||
conn: conn,
|
||||
client: ledgerv1.NewLedgerServiceClient(conn),
|
||||
client: unifiedv1.NewUnifiedGatewayServiceClient(conn),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -95,6 +102,80 @@ func (c *ledgerClient) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *ledgerClient) ReadBalance(ctx context.Context, accountID string) (*moneyv1.Money, error) {
|
||||
if strings.TrimSpace(accountID) == "" {
|
||||
return nil, merrors.InvalidArgument("ledger: account_id is required")
|
||||
}
|
||||
resp, err := c.GetBalance(ctx, &ledgerv1.GetBalanceRequest{LedgerAccountRef: strings.TrimSpace(accountID)})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp == nil || resp.GetBalance() == nil {
|
||||
return nil, merrors.Internal("ledger: balance response missing")
|
||||
}
|
||||
return cloneMoney(resp.GetBalance()), nil
|
||||
}
|
||||
|
||||
func (c *ledgerClient) CreateTransaction(ctx context.Context, tx rail.LedgerTx) (string, error) {
|
||||
orgRef := strings.TrimSpace(tx.OrganizationRef)
|
||||
if orgRef == "" {
|
||||
return "", merrors.InvalidArgument("ledger: organization_ref is required")
|
||||
}
|
||||
accountRef := strings.TrimSpace(tx.LedgerAccountRef)
|
||||
if accountRef == "" {
|
||||
return "", merrors.InvalidArgument("ledger: ledger_account_ref is required")
|
||||
}
|
||||
money := &moneyv1.Money{
|
||||
Currency: strings.TrimSpace(tx.Currency),
|
||||
Amount: strings.TrimSpace(tx.Amount),
|
||||
}
|
||||
if money.GetCurrency() == "" || money.GetAmount() == "" {
|
||||
return "", merrors.InvalidArgument("ledger: amount is required")
|
||||
}
|
||||
|
||||
description := strings.TrimSpace(tx.Description)
|
||||
metadata := ledgerTxMetadata(tx.Metadata, tx)
|
||||
|
||||
switch {
|
||||
case isLedgerRail(tx.FromRail) && !isLedgerRail(tx.ToRail):
|
||||
resp, err := c.PostDebitWithCharges(ctx, &ledgerv1.PostDebitRequest{
|
||||
IdempotencyKey: strings.TrimSpace(tx.IdempotencyKey),
|
||||
OrganizationRef: orgRef,
|
||||
LedgerAccountRef: accountRef,
|
||||
Money: money,
|
||||
Description: description,
|
||||
Charges: tx.Charges,
|
||||
Metadata: metadata,
|
||||
ContraLedgerAccountRef: strings.TrimSpace(tx.ContraLedgerAccountRef),
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimSpace(resp.GetJournalEntryRef()), nil
|
||||
case isLedgerRail(tx.ToRail) && !isLedgerRail(tx.FromRail):
|
||||
resp, err := c.PostCreditWithCharges(ctx, &ledgerv1.PostCreditRequest{
|
||||
IdempotencyKey: strings.TrimSpace(tx.IdempotencyKey),
|
||||
OrganizationRef: orgRef,
|
||||
LedgerAccountRef: accountRef,
|
||||
Money: money,
|
||||
Description: description,
|
||||
Charges: tx.Charges,
|
||||
Metadata: metadata,
|
||||
ContraLedgerAccountRef: strings.TrimSpace(tx.ContraLedgerAccountRef),
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimSpace(resp.GetJournalEntryRef()), nil
|
||||
default:
|
||||
return "", merrors.InvalidArgument("ledger: unsupported transaction direction")
|
||||
}
|
||||
}
|
||||
|
||||
func (c *ledgerClient) HoldBalance(ctx context.Context, accountID string, amount string) error {
|
||||
return merrors.NotImplemented("ledger: hold balance not supported")
|
||||
}
|
||||
|
||||
func (c *ledgerClient) CreateAccount(ctx context.Context, req *ledgerv1.CreateAccountRequest) (*ledgerv1.CreateAccountResponse, error) {
|
||||
ctx, cancel := c.callContext(ctx)
|
||||
defer cancel()
|
||||
@@ -156,3 +237,57 @@ func (c *ledgerClient) callContext(ctx context.Context) (context.Context, contex
|
||||
}
|
||||
return context.WithTimeout(ctx, timeout)
|
||||
}
|
||||
|
||||
func isLedgerRail(value string) bool {
|
||||
return strings.EqualFold(strings.TrimSpace(value), "LEDGER")
|
||||
}
|
||||
|
||||
func cloneMoney(input *moneyv1.Money) *moneyv1.Money {
|
||||
if input == nil {
|
||||
return nil
|
||||
}
|
||||
return &moneyv1.Money{
|
||||
Currency: input.GetCurrency(),
|
||||
Amount: input.GetAmount(),
|
||||
}
|
||||
}
|
||||
|
||||
func cloneMetadata(input map[string]string) map[string]string {
|
||||
if len(input) == 0 {
|
||||
return nil
|
||||
}
|
||||
out := make(map[string]string, len(input))
|
||||
for k, v := range input {
|
||||
out[k] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func ledgerTxMetadata(base map[string]string, tx rail.LedgerTx) map[string]string {
|
||||
meta := cloneMetadata(base)
|
||||
if meta == nil {
|
||||
meta = map[string]string{}
|
||||
}
|
||||
if val := strings.TrimSpace(tx.PaymentPlanID); val != "" {
|
||||
meta["payment_plan_id"] = val
|
||||
}
|
||||
if val := strings.TrimSpace(tx.FromRail); val != "" {
|
||||
meta["from_rail"] = val
|
||||
}
|
||||
if val := strings.TrimSpace(tx.ToRail); val != "" {
|
||||
meta["to_rail"] = val
|
||||
}
|
||||
if val := strings.TrimSpace(tx.ExternalReferenceID); val != "" {
|
||||
meta["external_reference_id"] = val
|
||||
}
|
||||
if val := strings.TrimSpace(tx.FXRateUsed); val != "" {
|
||||
meta["fx_rate_used"] = val
|
||||
}
|
||||
if val := strings.TrimSpace(tx.FeeAmount); val != "" {
|
||||
meta["fee_amount"] = val
|
||||
}
|
||||
if len(meta) == 0 {
|
||||
return nil
|
||||
}
|
||||
return meta
|
||||
}
|
||||
|
||||
@@ -3,13 +3,18 @@ package client
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/tech/sendico/pkg/payments/rail"
|
||||
moneyv1 "github.com/tech/sendico/pkg/proto/common/money/v1"
|
||||
ledgerv1 "github.com/tech/sendico/pkg/proto/ledger/v1"
|
||||
)
|
||||
|
||||
// Fake implements Client for tests.
|
||||
type Fake struct {
|
||||
CreateAccountFn func(ctx context.Context, req *ledgerv1.CreateAccountRequest) (*ledgerv1.CreateAccountResponse, error)
|
||||
ListAccountsFn func(ctx context.Context, req *ledgerv1.ListAccountsRequest) (*ledgerv1.ListAccountsResponse, error)
|
||||
ReadBalanceFn func(ctx context.Context, accountID string) (*moneyv1.Money, error)
|
||||
CreateTransactionFn func(ctx context.Context, tx rail.LedgerTx) (string, error)
|
||||
HoldBalanceFn func(ctx context.Context, accountID string, amount string) error
|
||||
CreateAccountFn func(ctx context.Context, req *ledgerv1.CreateAccountRequest) (*ledgerv1.CreateAccountResponse, error)
|
||||
ListAccountsFn func(ctx context.Context, req *ledgerv1.ListAccountsRequest) (*ledgerv1.ListAccountsResponse, error)
|
||||
PostCreditWithChargesFn func(ctx context.Context, req *ledgerv1.PostCreditRequest) (*ledgerv1.PostResponse, error)
|
||||
PostDebitWithChargesFn func(ctx context.Context, req *ledgerv1.PostDebitRequest) (*ledgerv1.PostResponse, error)
|
||||
TransferInternalFn func(ctx context.Context, req *ledgerv1.TransferRequest) (*ledgerv1.PostResponse, error)
|
||||
@@ -20,6 +25,27 @@ type Fake struct {
|
||||
CloseFn func() error
|
||||
}
|
||||
|
||||
func (f *Fake) ReadBalance(ctx context.Context, accountID string) (*moneyv1.Money, error) {
|
||||
if f.ReadBalanceFn != nil {
|
||||
return f.ReadBalanceFn(ctx, accountID)
|
||||
}
|
||||
return &moneyv1.Money{}, nil
|
||||
}
|
||||
|
||||
func (f *Fake) CreateTransaction(ctx context.Context, tx rail.LedgerTx) (string, error) {
|
||||
if f.CreateTransactionFn != nil {
|
||||
return f.CreateTransactionFn(ctx, tx)
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func (f *Fake) HoldBalance(ctx context.Context, accountID string, amount string) error {
|
||||
if f.HoldBalanceFn != nil {
|
||||
return f.HoldBalanceFn(ctx, accountID, amount)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *Fake) CreateAccount(ctx context.Context, req *ledgerv1.CreateAccountRequest) (*ledgerv1.CreateAccountResponse, error) {
|
||||
if f.CreateAccountFn != nil {
|
||||
return f.CreateAccountFn(ctx, req)
|
||||
|
||||
@@ -16,11 +16,15 @@ import (
|
||||
moneyv1 "github.com/tech/sendico/pkg/proto/common/money/v1"
|
||||
tracev1 "github.com/tech/sendico/pkg/proto/common/trace/v1"
|
||||
|
||||
"github.com/tech/sendico/ledger/internal/appversion"
|
||||
"github.com/tech/sendico/ledger/storage"
|
||||
"github.com/tech/sendico/pkg/api/routers"
|
||||
"github.com/tech/sendico/pkg/discovery"
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
pmessaging "github.com/tech/sendico/pkg/messaging"
|
||||
"github.com/tech/sendico/pkg/mlogger"
|
||||
"github.com/tech/sendico/pkg/mservice"
|
||||
unifiedv1 "github.com/tech/sendico/pkg/proto/gateway/unified/v1"
|
||||
ledgerv1 "github.com/tech/sendico/pkg/proto/ledger/v1"
|
||||
)
|
||||
|
||||
@@ -35,17 +39,18 @@ var (
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
logger mlogger.Logger
|
||||
storage storage.Repository
|
||||
producer pmessaging.Producer
|
||||
fees feesDependency
|
||||
logger mlogger.Logger
|
||||
storage storage.Repository
|
||||
producer pmessaging.Producer
|
||||
fees feesDependency
|
||||
announcer *discovery.Announcer
|
||||
|
||||
outbox struct {
|
||||
once sync.Once
|
||||
cancel context.CancelFunc
|
||||
publisher *outboxPublisher
|
||||
}
|
||||
ledgerv1.UnimplementedLedgerServiceServer
|
||||
unifiedv1.UnimplementedUnifiedGatewayServiceServer
|
||||
}
|
||||
|
||||
type feesDependency struct {
|
||||
@@ -72,12 +77,13 @@ func NewService(logger mlogger.Logger, repo storage.Repository, prod pmessaging.
|
||||
}
|
||||
|
||||
service.startOutboxPublisher()
|
||||
service.startDiscoveryAnnouncer()
|
||||
return service
|
||||
}
|
||||
|
||||
func (s *Service) Register(router routers.GRPC) error {
|
||||
return router.Register(func(reg grpc.ServiceRegistrar) {
|
||||
ledgerv1.RegisterLedgerServiceServer(reg, s)
|
||||
unifiedv1.RegisterUnifiedGatewayServiceServer(reg, s)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -184,11 +190,28 @@ func (s *Service) Shutdown() {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
if s.announcer != nil {
|
||||
s.announcer.Stop()
|
||||
}
|
||||
if s.outbox.cancel != nil {
|
||||
s.outbox.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) startDiscoveryAnnouncer() {
|
||||
if s == nil || s.producer == nil {
|
||||
return
|
||||
}
|
||||
announce := discovery.Announcement{
|
||||
Service: "LEDGER",
|
||||
Operations: []string{"balance.read", "ledger.debit", "ledger.credit"},
|
||||
InvokeURI: discovery.DefaultInvokeURI(string(mservice.Ledger)),
|
||||
Version: appversion.Create().Short(),
|
||||
}
|
||||
s.announcer = discovery.NewAnnouncer(s.logger, s.producer, string(mservice.Ledger), announce)
|
||||
s.announcer.Start()
|
||||
}
|
||||
|
||||
func (s *Service) startOutboxPublisher() {
|
||||
if s.storage == nil || s.producer == nil {
|
||||
return
|
||||
|
||||
@@ -36,6 +36,7 @@ api:
|
||||
message_broker:
|
||||
driver: NATS
|
||||
settings:
|
||||
url_env: NATS_URL
|
||||
host_env: NATS_HOST
|
||||
port_env: NATS_PORT
|
||||
username_env: NATS_USER
|
||||
|
||||
@@ -5,10 +5,10 @@ go 1.25.3
|
||||
replace github.com/tech/sendico/pkg => ../pkg
|
||||
|
||||
require (
|
||||
github.com/amplitude/analytics-go v1.2.0
|
||||
github.com/amplitude/analytics-go v1.3.0
|
||||
github.com/go-chi/chi/v5 v5.2.3
|
||||
github.com/mitchellh/mapstructure v1.5.0
|
||||
github.com/nicksnyder/go-i18n/v2 v2.6.0
|
||||
github.com/nicksnyder/go-i18n/v2 v2.6.1
|
||||
github.com/sendgrid/sendgrid-go v3.16.1+incompatible
|
||||
github.com/tech/sendico/pkg v0.1.0
|
||||
github.com/xhit/go-simple-mail/v2 v2.16.0
|
||||
|
||||
@@ -2,12 +2,12 @@ dario.cat/mergo v1.0.1 h1:Ra4+bf83h2ztPIQYNP99R6m+Y7KfnARDfID+a+vLl4s=
|
||||
dario.cat/mergo v1.0.1/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk=
|
||||
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0=
|
||||
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
|
||||
github.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg=
|
||||
github.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
||||
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
|
||||
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
||||
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
|
||||
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
||||
github.com/amplitude/analytics-go v1.2.0 h1:+WUKyAAKwlmSM8d03QWG+NjnrQIyc6VJRGPNkaa2ckI=
|
||||
github.com/amplitude/analytics-go v1.2.0/go.mod h1:kAQG8OQ6aPOxZrEZ3+/NFCfxdYSyjqXZhgkjWFD3/vo=
|
||||
github.com/amplitude/analytics-go v1.3.0 h1:Lgj31fWThQ6hdDHO0RPxQfy/D7d8K+aqWsBa+IGTxQk=
|
||||
github.com/amplitude/analytics-go v1.3.0/go.mod h1:kAQG8OQ6aPOxZrEZ3+/NFCfxdYSyjqXZhgkjWFD3/vo=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/bmatcuk/doublestar/v4 v4.6.1/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc=
|
||||
@@ -105,8 +105,8 @@ github.com/nats-io/nkeys v0.4.12 h1:nssm7JKOG9/x4J8II47VWCL1Ds29avyiQDRn0ckMvDc=
|
||||
github.com/nats-io/nkeys v0.4.12/go.mod h1:MT59A1HYcjIcyQDJStTfaOY6vhy9XTUjOFo+SVsvpBg=
|
||||
github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=
|
||||
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
|
||||
github.com/nicksnyder/go-i18n/v2 v2.6.0 h1:C/m2NNWNiTB6SK4Ao8df5EWm3JETSTIGNXBpMJTxzxQ=
|
||||
github.com/nicksnyder/go-i18n/v2 v2.6.0/go.mod h1:88sRqr0C6OPyJn0/KRNaEz1uWorjxIKP7rUUcvycecE=
|
||||
github.com/nicksnyder/go-i18n/v2 v2.6.1 h1:JDEJraFsQE17Dut9HFDHzCoAWGEQJom5s0TRd17NIEQ=
|
||||
github.com/nicksnyder/go-i18n/v2 v2.6.1/go.mod h1:Vee0/9RD3Quc/NmwEjzzD7VTZ+Ir7QbXocrkhOzmUKA=
|
||||
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
|
||||
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
|
||||
github.com/opencontainers/image-spec v1.1.0 h1:8SG7/vwALn54lVB/0yZ/MMwhFrPYtpEHQb2IpWsCzug=
|
||||
@@ -189,6 +189,8 @@ go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=
|
||||
go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
|
||||
go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=
|
||||
go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=
|
||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/tech/sendico/notification/interface/api/localizer"
|
||||
"github.com/tech/sendico/pkg/db"
|
||||
"github.com/tech/sendico/pkg/domainprovider"
|
||||
@@ -16,6 +17,7 @@ type API interface {
|
||||
Register() messaging.Register
|
||||
Localizer() localizer.Localizer
|
||||
DomainProvider() domainprovider.DomainProvider
|
||||
Router() *chi.Mux
|
||||
}
|
||||
|
||||
type MicroServiceFactoryT = func(API) (mservice.MicroService, error)
|
||||
|
||||
@@ -27,6 +27,7 @@ type APIImp struct {
|
||||
services Microservices
|
||||
debug bool
|
||||
mw *Middleware
|
||||
router *chi.Mux
|
||||
}
|
||||
|
||||
func (a *APIImp) installMicroservice(srv mservice.MicroService) {
|
||||
@@ -69,6 +70,10 @@ func (a *APIImp) Register() messaging.Register {
|
||||
return a.mw
|
||||
}
|
||||
|
||||
func (a *APIImp) Router() *chi.Mux {
|
||||
return a.router
|
||||
}
|
||||
|
||||
func (a *APIImp) installServices() error {
|
||||
srvf := make([]api.MicroServiceFactoryT, 0)
|
||||
|
||||
@@ -117,6 +122,7 @@ func CreateAPI(logger mlogger.Logger, config *api.Config, l localizer.Localizer,
|
||||
p.config = config
|
||||
p.db = db
|
||||
p.localizer = l
|
||||
p.router = router
|
||||
|
||||
var err error
|
||||
if p.domain, err = domainprovider.CreateDomainProvider(p.logger, config.Mw.DomainEnv, config.Mw.APIProtocolEnv, config.Mw.EndPointEnv); err != nil {
|
||||
|
||||
404
api/notification/internal/server/notificationimp/confirmation.go
Normal file
404
api/notification/internal/server/notificationimp/confirmation.go
Normal file
@@ -0,0 +1,404 @@
|
||||
package notificationimp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/tech/sendico/notification/internal/server/notificationimp/telegram"
|
||||
msg "github.com/tech/sendico/pkg/messaging"
|
||||
confirmations "github.com/tech/sendico/pkg/messaging/notifications/confirmations"
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
"github.com/tech/sendico/pkg/mlogger"
|
||||
"github.com/tech/sendico/pkg/model"
|
||||
"github.com/tech/sendico/pkg/mservice"
|
||||
paymenttypes "github.com/tech/sendico/pkg/payments/types"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultConfirmationTimeout = 120 * time.Second
|
||||
)
|
||||
|
||||
type confirmationManager struct {
|
||||
logger mlogger.Logger
|
||||
tg telegram.Client
|
||||
sender string
|
||||
outbox msg.Producer
|
||||
|
||||
mu sync.Mutex
|
||||
pendingByMessage map[string]*confirmationState
|
||||
pendingByRequest map[string]*confirmationState
|
||||
}
|
||||
|
||||
type confirmationState struct {
|
||||
request model.ConfirmationRequest
|
||||
requestMessageID string
|
||||
targetChatID string
|
||||
callbackSubject string
|
||||
clarified bool
|
||||
timer *time.Timer
|
||||
}
|
||||
|
||||
func newConfirmationManager(logger mlogger.Logger, tg telegram.Client, outbox msg.Producer) *confirmationManager {
|
||||
if logger != nil {
|
||||
logger = logger.Named("confirmations")
|
||||
}
|
||||
return &confirmationManager{
|
||||
logger: logger,
|
||||
tg: tg,
|
||||
outbox: outbox,
|
||||
sender: string(mservice.Notifications),
|
||||
pendingByMessage: map[string]*confirmationState{},
|
||||
pendingByRequest: map[string]*confirmationState{},
|
||||
}
|
||||
}
|
||||
|
||||
func (m *confirmationManager) Stop() {
|
||||
if m == nil {
|
||||
return
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
for _, state := range m.pendingByMessage {
|
||||
if state.timer != nil {
|
||||
state.timer.Stop()
|
||||
}
|
||||
}
|
||||
m.pendingByMessage = map[string]*confirmationState{}
|
||||
m.pendingByRequest = map[string]*confirmationState{}
|
||||
}
|
||||
|
||||
func (m *confirmationManager) HandleRequest(ctx context.Context, request *model.ConfirmationRequest) error {
|
||||
if m == nil {
|
||||
return errors.New("confirmation manager is nil")
|
||||
}
|
||||
if request == nil {
|
||||
return merrors.InvalidArgument("confirmation request is nil", "request")
|
||||
}
|
||||
if m.tg == nil {
|
||||
return merrors.InvalidArgument("telegram client is not configured", "telegram")
|
||||
}
|
||||
|
||||
req := normalizeConfirmationRequest(*request)
|
||||
if req.RequestID == "" {
|
||||
return merrors.InvalidArgument("confirmation request_id is required", "request_id")
|
||||
}
|
||||
if req.TargetChatID == "" {
|
||||
return merrors.InvalidArgument("confirmation target_chat_id is required", "target_chat_id")
|
||||
}
|
||||
if req.RequestedMoney == nil || strings.TrimSpace(req.RequestedMoney.Amount) == "" || strings.TrimSpace(req.RequestedMoney.Currency) == "" {
|
||||
return merrors.InvalidArgument("confirmation requested_money is required", "requested_money")
|
||||
}
|
||||
if req.SourceService == "" {
|
||||
return merrors.InvalidArgument("confirmation source_service is required", "source_service")
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
if _, ok := m.pendingByRequest[req.RequestID]; ok {
|
||||
m.mu.Unlock()
|
||||
m.logger.Info("Confirmation request already pending", zap.String("request_id", req.RequestID))
|
||||
return nil
|
||||
}
|
||||
m.mu.Unlock()
|
||||
|
||||
message := confirmationPrompt(&req)
|
||||
sent, err := m.tg.SendText(ctx, req.TargetChatID, message, "")
|
||||
if err != nil {
|
||||
m.logger.Warn("Failed to send confirmation request to Telegram", zap.Error(err), zap.String("request_id", req.RequestID))
|
||||
return err
|
||||
}
|
||||
if sent == nil || strings.TrimSpace(sent.MessageID) == "" {
|
||||
return merrors.Internal("telegram confirmation message id is missing")
|
||||
}
|
||||
|
||||
state := &confirmationState{
|
||||
request: req,
|
||||
requestMessageID: strings.TrimSpace(sent.MessageID),
|
||||
targetChatID: strings.TrimSpace(req.TargetChatID),
|
||||
callbackSubject: confirmationCallbackSubject(req.SourceService, req.Rail),
|
||||
}
|
||||
timeout := time.Duration(req.TimeoutSeconds) * time.Second
|
||||
if timeout <= 0 {
|
||||
timeout = defaultConfirmationTimeout
|
||||
}
|
||||
state.timer = time.AfterFunc(timeout, func() {
|
||||
m.handleTimeout(state.requestMessageID)
|
||||
})
|
||||
|
||||
m.mu.Lock()
|
||||
m.pendingByMessage[state.requestMessageID] = state
|
||||
m.pendingByRequest[req.RequestID] = state
|
||||
m.mu.Unlock()
|
||||
|
||||
m.logger.Info("Confirmation request sent", zap.String("request_id", req.RequestID), zap.String("message_id", state.requestMessageID), zap.String("callback_subject", state.callbackSubject))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *confirmationManager) HandleUpdate(ctx context.Context, update *telegram.Update) {
|
||||
if m == nil || update == nil || update.Message == nil {
|
||||
return
|
||||
}
|
||||
message := update.Message
|
||||
if message.ReplyToMessage == nil {
|
||||
return
|
||||
}
|
||||
|
||||
replyToID := strconv.FormatInt(message.ReplyToMessage.MessageID, 10)
|
||||
state := m.lookupByMessageID(replyToID)
|
||||
if state == nil {
|
||||
return
|
||||
}
|
||||
|
||||
chatID := strconv.FormatInt(message.Chat.ID, 10)
|
||||
if chatID != state.targetChatID {
|
||||
m.logger.Debug("Telegram reply ignored: chat mismatch", zap.String("expected_chat_id", state.targetChatID), zap.String("chat_id", chatID))
|
||||
return
|
||||
}
|
||||
|
||||
rawReply := message.ToModel()
|
||||
if !state.isUserAllowed(message.From) {
|
||||
m.publishResult(state, &model.ConfirmationResult{
|
||||
RequestID: state.request.RequestID,
|
||||
Status: model.ConfirmationStatusRejected,
|
||||
ParseError: "unauthorized_user",
|
||||
RawReply: rawReply,
|
||||
})
|
||||
m.sendNotice(ctx, state, rawReply, "Only approved users can confirm this payment.")
|
||||
m.removeState(state.requestMessageID)
|
||||
return
|
||||
}
|
||||
|
||||
money, reason, err := parseConfirmationReply(message.Text)
|
||||
if err != nil {
|
||||
m.mu.Lock()
|
||||
state.clarified = true
|
||||
m.mu.Unlock()
|
||||
m.sendNotice(ctx, state, rawReply, clarificationMessage(reason))
|
||||
return
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
clarified := state.clarified
|
||||
m.mu.Unlock()
|
||||
status := model.ConfirmationStatusConfirmed
|
||||
if clarified {
|
||||
status = model.ConfirmationStatusClarified
|
||||
}
|
||||
m.publishResult(state, &model.ConfirmationResult{
|
||||
RequestID: state.request.RequestID,
|
||||
Money: money,
|
||||
RawReply: rawReply,
|
||||
Status: status,
|
||||
})
|
||||
m.removeState(state.requestMessageID)
|
||||
}
|
||||
|
||||
func (m *confirmationManager) lookupByMessageID(messageID string) *confirmationState {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return m.pendingByMessage[strings.TrimSpace(messageID)]
|
||||
}
|
||||
|
||||
func (m *confirmationManager) handleTimeout(messageID string) {
|
||||
state := m.lookupByMessageID(messageID)
|
||||
if state == nil {
|
||||
return
|
||||
}
|
||||
m.publishResult(state, &model.ConfirmationResult{
|
||||
RequestID: state.request.RequestID,
|
||||
Status: model.ConfirmationStatusTimeout,
|
||||
})
|
||||
m.removeState(messageID)
|
||||
}
|
||||
|
||||
func (m *confirmationManager) removeState(messageID string) {
|
||||
messageID = strings.TrimSpace(messageID)
|
||||
if messageID == "" {
|
||||
return
|
||||
}
|
||||
m.mu.Lock()
|
||||
state := m.pendingByMessage[messageID]
|
||||
if state != nil && state.timer != nil {
|
||||
state.timer.Stop()
|
||||
}
|
||||
delete(m.pendingByMessage, messageID)
|
||||
if state != nil {
|
||||
delete(m.pendingByRequest, state.request.RequestID)
|
||||
}
|
||||
m.mu.Unlock()
|
||||
}
|
||||
|
||||
func (m *confirmationManager) publishResult(state *confirmationState, result *model.ConfirmationResult) {
|
||||
if m == nil || state == nil || result == nil {
|
||||
return
|
||||
}
|
||||
if m.outbox == nil {
|
||||
m.logger.Warn("Confirmation result skipped: producer not configured", zap.String("request_id", state.request.RequestID))
|
||||
return
|
||||
}
|
||||
env := confirmations.ConfirmationResult(m.sender, result, state.request.SourceService, state.request.Rail)
|
||||
if err := m.outbox.SendMessage(env); err != nil {
|
||||
m.logger.Warn("Failed to publish confirmation result", zap.Error(err), zap.String("request_id", state.request.RequestID))
|
||||
return
|
||||
}
|
||||
m.logger.Info("Confirmation result published", zap.String("request_id", state.request.RequestID), zap.String("status", string(result.Status)))
|
||||
}
|
||||
|
||||
func (m *confirmationManager) sendNotice(ctx context.Context, state *confirmationState, reply *model.TelegramMessage, text string) {
|
||||
if m == nil || m.tg == nil || state == nil {
|
||||
return
|
||||
}
|
||||
replyID := ""
|
||||
if reply != nil {
|
||||
replyID = reply.MessageID
|
||||
}
|
||||
if _, err := m.tg.SendText(ctx, state.targetChatID, text, replyID); err != nil {
|
||||
m.logger.Warn("Failed to send clarification notice", zap.Error(err), zap.String("request_id", state.request.RequestID))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *confirmationState) isUserAllowed(user *telegram.User) bool {
|
||||
if s == nil {
|
||||
return false
|
||||
}
|
||||
allowed := s.request.AcceptedUserIDs
|
||||
if len(allowed) == 0 {
|
||||
return true
|
||||
}
|
||||
if user == nil {
|
||||
return false
|
||||
}
|
||||
userID := strconv.FormatInt(user.ID, 10)
|
||||
for _, id := range allowed {
|
||||
if id == userID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func confirmationCallbackSubject(sourceService, rail string) string {
|
||||
sourceService = strings.ToLower(strings.TrimSpace(sourceService))
|
||||
if sourceService == "" {
|
||||
sourceService = "unknown"
|
||||
}
|
||||
rail = strings.ToLower(strings.TrimSpace(rail))
|
||||
if rail == "" {
|
||||
rail = "default"
|
||||
}
|
||||
return "confirmations." + sourceService + "." + rail
|
||||
}
|
||||
|
||||
func normalizeConfirmationRequest(request model.ConfirmationRequest) model.ConfirmationRequest {
|
||||
request.RequestID = strings.TrimSpace(request.RequestID)
|
||||
request.TargetChatID = strings.TrimSpace(request.TargetChatID)
|
||||
request.PaymentIntentID = strings.TrimSpace(request.PaymentIntentID)
|
||||
request.QuoteRef = strings.TrimSpace(request.QuoteRef)
|
||||
request.SourceService = strings.TrimSpace(request.SourceService)
|
||||
request.Rail = strings.TrimSpace(request.Rail)
|
||||
request.AcceptedUserIDs = normalizeStringList(request.AcceptedUserIDs)
|
||||
if request.RequestedMoney != nil {
|
||||
request.RequestedMoney.Amount = strings.TrimSpace(request.RequestedMoney.Amount)
|
||||
request.RequestedMoney.Currency = strings.TrimSpace(request.RequestedMoney.Currency)
|
||||
}
|
||||
return request
|
||||
}
|
||||
|
||||
func normalizeStringList(values []string) []string {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
result := make([]string, 0, len(values))
|
||||
seen := map[string]struct{}{}
|
||||
for _, value := range values {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[value]; ok {
|
||||
continue
|
||||
}
|
||||
seen[value] = struct{}{}
|
||||
result = append(result, value)
|
||||
}
|
||||
if len(result) == 0 {
|
||||
return nil
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
var amountPattern = regexp.MustCompile(`^[0-9]+(\.[0-9]+)?$`)
|
||||
var currencyPattern = regexp.MustCompile(`^[A-Za-z]{3,10}$`)
|
||||
|
||||
func parseConfirmationReply(text string) (*paymenttypes.Money, string, error) {
|
||||
text = strings.TrimSpace(text)
|
||||
if text == "" {
|
||||
return nil, "empty", errors.New("empty reply")
|
||||
}
|
||||
parts := strings.Fields(text)
|
||||
if len(parts) < 2 {
|
||||
if len(parts) == 1 && amountPattern.MatchString(parts[0]) {
|
||||
return nil, "missing_currency", errors.New("currency is required")
|
||||
}
|
||||
return nil, "missing_amount", errors.New("amount is required")
|
||||
}
|
||||
if len(parts) > 2 {
|
||||
return nil, "format", errors.New("reply format is invalid")
|
||||
}
|
||||
amount := parts[0]
|
||||
currency := parts[1]
|
||||
if !amountPattern.MatchString(amount) {
|
||||
return nil, "invalid_amount", errors.New("amount format is invalid")
|
||||
}
|
||||
if !currencyPattern.MatchString(currency) {
|
||||
return nil, "invalid_currency", errors.New("currency format is invalid")
|
||||
}
|
||||
return &paymenttypes.Money{
|
||||
Amount: amount,
|
||||
Currency: strings.ToUpper(currency),
|
||||
}, "", nil
|
||||
}
|
||||
|
||||
func confirmationPrompt(req *model.ConfirmationRequest) string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString("Payment confirmation required\n")
|
||||
if req.PaymentIntentID != "" {
|
||||
builder.WriteString("Payment intent: ")
|
||||
builder.WriteString(req.PaymentIntentID)
|
||||
builder.WriteString("\n")
|
||||
}
|
||||
if req.QuoteRef != "" {
|
||||
builder.WriteString("Quote ref: ")
|
||||
builder.WriteString(req.QuoteRef)
|
||||
builder.WriteString("\n")
|
||||
}
|
||||
if req.RequestedMoney != nil {
|
||||
builder.WriteString("Requested: ")
|
||||
builder.WriteString(req.RequestedMoney.Amount)
|
||||
builder.WriteString(" ")
|
||||
builder.WriteString(req.RequestedMoney.Currency)
|
||||
builder.WriteString("\n")
|
||||
}
|
||||
builder.WriteString("Reply with \"<amount> <currency>\" (e.g., 12.34 USD).")
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
func clarificationMessage(reason string) string {
|
||||
switch reason {
|
||||
case "missing_currency":
|
||||
return "Currency code is required. Reply with \"<amount> <currency>\" (e.g., 12.34 USD)."
|
||||
case "missing_amount":
|
||||
return "Amount is required. Reply with \"<amount> <currency>\" (e.g., 12.34 USD)."
|
||||
case "invalid_amount":
|
||||
return "Amount must be a decimal number. Reply with \"<amount> <currency>\" (e.g., 12.34 USD)."
|
||||
case "invalid_currency":
|
||||
return "Currency must be a code like USD or EUR. Reply with \"<amount> <currency>\"."
|
||||
default:
|
||||
return "Reply with \"<amount> <currency>\" (e.g., 12.34 USD)."
|
||||
}
|
||||
}
|
||||
@@ -4,11 +4,14 @@ import (
|
||||
"context"
|
||||
|
||||
"github.com/tech/sendico/notification/interface/api"
|
||||
"github.com/tech/sendico/notification/internal/appversion"
|
||||
mmail "github.com/tech/sendico/notification/internal/server/notificationimp/mail"
|
||||
"github.com/tech/sendico/notification/internal/server/notificationimp/telegram"
|
||||
"github.com/tech/sendico/pkg/discovery"
|
||||
"github.com/tech/sendico/pkg/domainprovider"
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
na "github.com/tech/sendico/pkg/messaging/notifications/account"
|
||||
confirmations "github.com/tech/sendico/pkg/messaging/notifications/confirmations"
|
||||
cnotifications "github.com/tech/sendico/pkg/messaging/notifications/confirmation"
|
||||
ni "github.com/tech/sendico/pkg/messaging/notifications/invitation"
|
||||
snotifications "github.com/tech/sendico/pkg/messaging/notifications/site"
|
||||
@@ -19,10 +22,12 @@ import (
|
||||
)
|
||||
|
||||
type NotificationAPI struct {
|
||||
logger mlogger.Logger
|
||||
client mmail.Client
|
||||
dp domainprovider.DomainProvider
|
||||
tg telegram.Client
|
||||
logger mlogger.Logger
|
||||
client mmail.Client
|
||||
dp domainprovider.DomainProvider
|
||||
tg telegram.Client
|
||||
announcer *discovery.Announcer
|
||||
confirm *confirmationManager
|
||||
}
|
||||
|
||||
func (a *NotificationAPI) Name() mservice.Type {
|
||||
@@ -30,6 +35,12 @@ func (a *NotificationAPI) Name() mservice.Type {
|
||||
}
|
||||
|
||||
func (a *NotificationAPI) Finish(_ context.Context) error {
|
||||
if a.announcer != nil {
|
||||
a.announcer.Stop()
|
||||
}
|
||||
if a.confirm != nil {
|
||||
a.confirm.Stop()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -55,6 +66,7 @@ func CreateAPI(a api.API) (*NotificationAPI, error) {
|
||||
p.logger.Error("Failed to create telegram client", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
p.confirm = newConfirmationManager(p.logger, p.tg, a.Register().Producer())
|
||||
|
||||
db, err := a.DBFactory().NewAccountDB()
|
||||
if err != nil {
|
||||
@@ -75,6 +87,10 @@ func CreateAPI(a api.API) (*NotificationAPI, error) {
|
||||
p.logger.Error("Failed to create confirmation code handler", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
if err := a.Register().Consumer(confirmations.NewConfirmationRequestProcessor(p.logger, p.onConfirmationRequest)); err != nil {
|
||||
p.logger.Error("Failed to register confirmation request handler", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
idb, err := a.DBFactory().NewInvitationsDB()
|
||||
if err != nil {
|
||||
@@ -91,6 +107,18 @@ func CreateAPI(a api.API) (*NotificationAPI, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if router := a.Router(); router != nil {
|
||||
router.Post("/telegram/webhook", p.handleTelegramWebhook)
|
||||
}
|
||||
|
||||
announce := discovery.Announcement{
|
||||
Service: "NOTIFICATIONS",
|
||||
Operations: []string{"notify.send"},
|
||||
Version: appversion.Create().Short(),
|
||||
}
|
||||
p.announcer = discovery.NewAnnouncer(p.logger, a.Register().Producer(), string(mservice.Notifications), announce)
|
||||
p.announcer.Start()
|
||||
|
||||
return p, nil
|
||||
}
|
||||
|
||||
@@ -129,3 +157,10 @@ func (a *NotificationAPI) onCallRequest(ctx context.Context, request *model.Call
|
||||
a.logger.Info("Call request sent via Telegram", zap.String("phone", request.Phone))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *NotificationAPI) onConfirmationRequest(ctx context.Context, request *model.ConfirmationRequest) error {
|
||||
if a.confirm == nil {
|
||||
return merrors.Internal("confirmation manager is not configured")
|
||||
}
|
||||
return a.confirm.HandleRequest(ctx, request)
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ type Client interface {
|
||||
SendDemoRequest(ctx context.Context, request *model.DemoRequest) error
|
||||
SendContactRequest(ctx context.Context, request *model.ContactRequest) error
|
||||
SendCallRequest(ctx context.Context, request *model.CallRequest) error
|
||||
SendText(ctx context.Context, chatID string, text string, replyToMessageID string) (*model.TelegramMessage, error)
|
||||
}
|
||||
|
||||
type client struct {
|
||||
@@ -38,13 +39,14 @@ type client struct {
|
||||
}
|
||||
|
||||
type sendMessagePayload struct {
|
||||
ChatID string `json:"chat_id"`
|
||||
Text string `json:"text"`
|
||||
ParseMode string `json:"parse_mode,omitempty"`
|
||||
ThreadID *int64 `json:"message_thread_id,omitempty"`
|
||||
DisablePreview bool `json:"disable_web_page_preview,omitempty"`
|
||||
DisableNotify bool `json:"disable_notification,omitempty"`
|
||||
ProtectContent bool `json:"protect_content,omitempty"`
|
||||
ChatID string `json:"chat_id"`
|
||||
Text string `json:"text"`
|
||||
ParseMode string `json:"parse_mode,omitempty"`
|
||||
ThreadID *int64 `json:"message_thread_id,omitempty"`
|
||||
ReplyToMessageID *int64 `json:"reply_to_message_id,omitempty"`
|
||||
DisablePreview bool `json:"disable_web_page_preview,omitempty"`
|
||||
DisableNotify bool `json:"disable_notification,omitempty"`
|
||||
ProtectContent bool `json:"protect_content,omitempty"`
|
||||
}
|
||||
|
||||
func NewClient(logger mlogger.Logger, cfg *notconfig.TelegramConfig) (Client, error) {
|
||||
@@ -106,16 +108,40 @@ func (c *client) SendDemoRequest(ctx context.Context, request *model.DemoRequest
|
||||
return c.sendForm(ctx, newDemoRequestTemplate(request))
|
||||
}
|
||||
|
||||
func (c *client) sendMessage(ctx context.Context, payload sendMessagePayload) error {
|
||||
type sendMessageResponse struct {
|
||||
OK bool `json:"ok"`
|
||||
Result *messageResponse `json:"result,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
}
|
||||
|
||||
type messageResponse struct {
|
||||
MessageID int64 `json:"message_id"`
|
||||
Date int64 `json:"date"`
|
||||
Chat messageChat `json:"chat"`
|
||||
From *messageUser `json:"from,omitempty"`
|
||||
Text string `json:"text"`
|
||||
ReplyToMessage *messageResponse `json:"reply_to_message,omitempty"`
|
||||
}
|
||||
|
||||
type messageChat struct {
|
||||
ID int64 `json:"id"`
|
||||
}
|
||||
|
||||
type messageUser struct {
|
||||
ID int64 `json:"id"`
|
||||
Username string `json:"username,omitempty"`
|
||||
}
|
||||
|
||||
func (c *client) sendMessage(ctx context.Context, payload sendMessagePayload) (*model.TelegramMessage, error) {
|
||||
body, err := json.Marshal(&payload)
|
||||
if err != nil {
|
||||
c.logger.Warn("Failed to marshal telegram payload", zap.Error(err))
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.endpoint(), bytes.NewReader(body))
|
||||
if err != nil {
|
||||
c.logger.Warn("Failed to create telegram request", zap.Error(err))
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
@@ -129,26 +155,41 @@ func (c *client) sendMessage(ctx context.Context, payload sendMessagePayload) er
|
||||
if payload.ThreadID != nil {
|
||||
fields = append(fields, zap.Int64("thread_id", *payload.ThreadID))
|
||||
}
|
||||
if payload.ReplyToMessageID != nil {
|
||||
fields = append(fields, zap.Int64("reply_to_message_id", *payload.ReplyToMessageID))
|
||||
}
|
||||
c.logger.Debug("Sending Telegram message", fields...)
|
||||
start := time.Now()
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
c.logger.Warn("Telegram request failed", zap.Error(err))
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 16<<10))
|
||||
if resp.StatusCode >= http.StatusOK && resp.StatusCode < http.StatusMultipleChoices {
|
||||
var parsed sendMessageResponse
|
||||
if err := json.Unmarshal(respBody, &parsed); err != nil {
|
||||
c.logger.Warn("Failed to decode telegram response", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
if !parsed.OK || parsed.Result == nil {
|
||||
msg := "telegram sendMessage response missing result"
|
||||
if parsed.Description != "" {
|
||||
msg = parsed.Description
|
||||
}
|
||||
return nil, merrors.Internal(msg)
|
||||
}
|
||||
c.logger.Debug("Telegram message sent", zap.Int("status_code", resp.StatusCode), zap.Duration("latency", time.Since(start)))
|
||||
return nil
|
||||
return toTelegramMessage(parsed.Result), nil
|
||||
}
|
||||
respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<10))
|
||||
c.logger.Warn("Telegram API returned non-success status",
|
||||
zap.Int("status_code", resp.StatusCode),
|
||||
zap.ByteString("response_body", respBody),
|
||||
zap.String("chat_id", c.chatID))
|
||||
return merrors.Internal(fmt.Sprintf("telegram sendMessage failed with status %d: %s", resp.StatusCode, string(respBody)))
|
||||
return nil, merrors.Internal(fmt.Sprintf("telegram sendMessage failed with status %d: %s", resp.StatusCode, string(respBody)))
|
||||
}
|
||||
|
||||
func (c *client) endpoint() string {
|
||||
@@ -178,5 +219,51 @@ func (c *client) sendForm(ctx context.Context, template messageTemplate) error {
|
||||
ThreadID: c.threadID,
|
||||
DisablePreview: true,
|
||||
}
|
||||
_, err := c.sendMessage(ctx, payload)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *client) SendText(ctx context.Context, chatID string, text string, replyToMessageID string) (*model.TelegramMessage, error) {
|
||||
chatID = strings.TrimSpace(chatID)
|
||||
if chatID == "" {
|
||||
chatID = c.chatID
|
||||
}
|
||||
if chatID == "" {
|
||||
return nil, merrors.InvalidArgument("telegram chat id is empty", "chat_id")
|
||||
}
|
||||
payload := sendMessagePayload{
|
||||
ChatID: chatID,
|
||||
Text: text,
|
||||
ParseMode: c.parseMode.String(),
|
||||
ThreadID: c.threadID,
|
||||
DisablePreview: true,
|
||||
}
|
||||
if replyToMessageID != "" {
|
||||
val, err := strconv.ParseInt(replyToMessageID, 10, 64)
|
||||
if err != nil {
|
||||
return nil, merrors.InvalidArgumentWrap(err, "invalid reply_to_message_id", "reply_to_message_id")
|
||||
}
|
||||
payload.ReplyToMessageID = &val
|
||||
}
|
||||
return c.sendMessage(ctx, payload)
|
||||
}
|
||||
|
||||
func toTelegramMessage(msg *messageResponse) *model.TelegramMessage {
|
||||
if msg == nil {
|
||||
return nil
|
||||
}
|
||||
result := &model.TelegramMessage{
|
||||
ChatID: strconv.FormatInt(msg.Chat.ID, 10),
|
||||
MessageID: strconv.FormatInt(msg.MessageID, 10),
|
||||
Text: msg.Text,
|
||||
SentAt: msg.Date,
|
||||
}
|
||||
if msg.From != nil {
|
||||
result.FromUserID = strconv.FormatInt(msg.From.ID, 10)
|
||||
result.FromUsername = msg.From.Username
|
||||
}
|
||||
if msg.ReplyToMessage != nil {
|
||||
result.ReplyToMessageID = strconv.FormatInt(msg.ReplyToMessage.MessageID, 10)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package telegram
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/tech/sendico/pkg/model"
|
||||
)
|
||||
|
||||
type Update struct {
|
||||
UpdateID int64 `json:"update_id"`
|
||||
Message *Message `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
MessageID int64 `json:"message_id"`
|
||||
Date int64 `json:"date,omitempty"`
|
||||
Chat Chat `json:"chat"`
|
||||
From *User `json:"from,omitempty"`
|
||||
Text string `json:"text,omitempty"`
|
||||
ReplyToMessage *Message `json:"reply_to_message,omitempty"`
|
||||
}
|
||||
|
||||
type Chat struct {
|
||||
ID int64 `json:"id"`
|
||||
}
|
||||
|
||||
type User struct {
|
||||
ID int64 `json:"id"`
|
||||
Username string `json:"username,omitempty"`
|
||||
}
|
||||
|
||||
func (m *Message) ToModel() *model.TelegramMessage {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
result := &model.TelegramMessage{
|
||||
ChatID: strconv.FormatInt(m.Chat.ID, 10),
|
||||
MessageID: strconv.FormatInt(m.MessageID, 10),
|
||||
Text: m.Text,
|
||||
SentAt: m.Date,
|
||||
}
|
||||
if m.From != nil {
|
||||
result.FromUserID = strconv.FormatInt(m.From.ID, 10)
|
||||
result.FromUsername = m.From.Username
|
||||
}
|
||||
if m.ReplyToMessage != nil {
|
||||
result.ReplyToMessageID = strconv.FormatInt(m.ReplyToMessage.MessageID, 10)
|
||||
}
|
||||
return result
|
||||
}
|
||||
30
api/notification/internal/server/notificationimp/webhook.go
Normal file
30
api/notification/internal/server/notificationimp/webhook.go
Normal file
@@ -0,0 +1,30 @@
|
||||
package notificationimp
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/tech/sendico/notification/internal/server/notificationimp/telegram"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
const telegramWebhookMaxBody = 1 << 20
|
||||
|
||||
func (a *NotificationAPI) handleTelegramWebhook(w http.ResponseWriter, r *http.Request) {
|
||||
if a == nil || a.confirm == nil {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
var update telegram.Update
|
||||
dec := json.NewDecoder(io.LimitReader(r.Body, telegramWebhookMaxBody))
|
||||
if err := dec.Decode(&update); err != nil {
|
||||
if a.logger != nil {
|
||||
a.logger.Warn("Failed to decode telegram webhook update", zap.Error(err))
|
||||
}
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
a.confirm.HandleUpdate(r.Context(), &update)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
@@ -51,6 +51,12 @@ gateway:
|
||||
call_timeout_seconds: 3
|
||||
insecure: true
|
||||
|
||||
payment_gateway:
|
||||
address: "sendico_tgsettle_gateway:50080"
|
||||
dial_timeout_seconds: 5
|
||||
call_timeout_seconds: 3
|
||||
insecure: true
|
||||
|
||||
mntx:
|
||||
address: "sendico_mntx_gateway:50075"
|
||||
dial_timeout_seconds: 5
|
||||
@@ -70,3 +76,15 @@ card_gateways:
|
||||
|
||||
fee_ledger_accounts:
|
||||
monetix: "ledger:fees:monetix"
|
||||
|
||||
# gateway_instances:
|
||||
# - id: "crypto-tron"
|
||||
# rail: "CRYPTO"
|
||||
# network: "TRON"
|
||||
# currencies: ["USDT"]
|
||||
# capabilities:
|
||||
# can_pay_out: true
|
||||
# can_send_fee: true
|
||||
# limits:
|
||||
# min_amount: "0"
|
||||
# max_amount: "100000"
|
||||
|
||||
231
api/payments/orchestrator/internal/server/internal/builders.go
Normal file
231
api/payments/orchestrator/internal/server/internal/builders.go
Normal file
@@ -0,0 +1,231 @@
|
||||
package serverimp
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
chainclient "github.com/tech/sendico/gateway/chain/client"
|
||||
"github.com/tech/sendico/payments/orchestrator/internal/service/orchestrator"
|
||||
"github.com/tech/sendico/payments/orchestrator/storage/model"
|
||||
"github.com/tech/sendico/pkg/discovery"
|
||||
"github.com/tech/sendico/pkg/mlogger"
|
||||
"github.com/tech/sendico/pkg/payments/rail"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func buildCardGatewayRoutes(src map[string]cardGatewayRouteConfig) map[string]orchestrator.CardGatewayRoute {
|
||||
if len(src) == 0 {
|
||||
return nil
|
||||
}
|
||||
result := make(map[string]orchestrator.CardGatewayRoute, len(src))
|
||||
for key, route := range src {
|
||||
trimmedKey := strings.TrimSpace(key)
|
||||
if trimmedKey == "" {
|
||||
continue
|
||||
}
|
||||
result[trimmedKey] = orchestrator.CardGatewayRoute{
|
||||
FundingAddress: strings.TrimSpace(route.FundingAddress),
|
||||
FeeAddress: strings.TrimSpace(route.FeeAddress),
|
||||
FeeWalletRef: strings.TrimSpace(route.FeeWalletRef),
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func buildFeeLedgerAccounts(src map[string]string) map[string]string {
|
||||
if len(src) == 0 {
|
||||
return nil
|
||||
}
|
||||
result := make(map[string]string, len(src))
|
||||
for key, account := range src {
|
||||
k := strings.ToLower(strings.TrimSpace(key))
|
||||
v := strings.TrimSpace(account)
|
||||
if k == "" || v == "" {
|
||||
continue
|
||||
}
|
||||
result[k] = v
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func buildGatewayRegistry(logger mlogger.Logger, src []gatewayInstanceConfig, registry *discovery.Registry) orchestrator.GatewayRegistry {
|
||||
static := buildGatewayInstances(logger, src)
|
||||
staticRegistry := orchestrator.NewGatewayRegistry(logger, static)
|
||||
discoveryRegistry := orchestrator.NewDiscoveryGatewayRegistry(logger, registry)
|
||||
return orchestrator.NewCompositeGatewayRegistry(logger, staticRegistry, discoveryRegistry)
|
||||
}
|
||||
|
||||
func buildRailGateways(chainClient chainclient.Client, paymentGatewayClient chainclient.Client, src []gatewayInstanceConfig) map[string]rail.RailGateway {
|
||||
if len(src) == 0 || (chainClient == nil && paymentGatewayClient == nil) {
|
||||
return nil
|
||||
}
|
||||
instances := buildGatewayInstances(nil, src)
|
||||
if len(instances) == 0 {
|
||||
return nil
|
||||
}
|
||||
result := map[string]rail.RailGateway{}
|
||||
for _, inst := range instances {
|
||||
if inst == nil || !inst.IsEnabled {
|
||||
continue
|
||||
}
|
||||
cfg := chainclient.RailGatewayConfig{
|
||||
Rail: string(inst.Rail),
|
||||
Network: inst.Network,
|
||||
Capabilities: rail.RailCapabilities{
|
||||
CanPayIn: inst.Capabilities.CanPayIn,
|
||||
CanPayOut: inst.Capabilities.CanPayOut,
|
||||
CanReadBalance: inst.Capabilities.CanReadBalance,
|
||||
CanSendFee: inst.Capabilities.CanSendFee,
|
||||
RequiresObserveConfirm: inst.Capabilities.RequiresObserveConfirm,
|
||||
},
|
||||
}
|
||||
switch inst.Rail {
|
||||
case model.RailCrypto:
|
||||
if chainClient == nil {
|
||||
continue
|
||||
}
|
||||
result[inst.ID] = chainclient.NewRailGateway(chainClient, cfg)
|
||||
case model.RailProviderSettlement:
|
||||
if paymentGatewayClient == nil {
|
||||
continue
|
||||
}
|
||||
result[inst.ID] = orchestrator.NewProviderSettlementGateway(paymentGatewayClient, cfg)
|
||||
}
|
||||
}
|
||||
if len(result) == 0 {
|
||||
return nil
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func buildGatewayInstances(logger mlogger.Logger, src []gatewayInstanceConfig) []*model.GatewayInstanceDescriptor {
|
||||
if len(src) == 0 {
|
||||
return nil
|
||||
}
|
||||
if logger != nil {
|
||||
logger = logger.Named("gateway_instances")
|
||||
}
|
||||
result := make([]*model.GatewayInstanceDescriptor, 0, len(src))
|
||||
for _, cfg := range src {
|
||||
id := strings.TrimSpace(cfg.ID)
|
||||
if id == "" {
|
||||
if logger != nil {
|
||||
logger.Warn("Gateway instance skipped: missing id")
|
||||
}
|
||||
continue
|
||||
}
|
||||
rail := parseRail(cfg.Rail)
|
||||
if rail == model.RailUnspecified {
|
||||
if logger != nil {
|
||||
logger.Warn("Gateway instance skipped: invalid rail", zap.String("id", id), zap.String("rail", cfg.Rail))
|
||||
}
|
||||
continue
|
||||
}
|
||||
enabled := true
|
||||
if cfg.IsEnabled != nil {
|
||||
enabled = *cfg.IsEnabled
|
||||
}
|
||||
result = append(result, &model.GatewayInstanceDescriptor{
|
||||
ID: id,
|
||||
Rail: rail,
|
||||
Network: strings.ToUpper(strings.TrimSpace(cfg.Network)),
|
||||
Currencies: normalizeCurrencies(cfg.Currencies),
|
||||
Capabilities: model.RailCapabilities{
|
||||
CanPayIn: cfg.Capabilities.CanPayIn,
|
||||
CanPayOut: cfg.Capabilities.CanPayOut,
|
||||
CanReadBalance: cfg.Capabilities.CanReadBalance,
|
||||
CanSendFee: cfg.Capabilities.CanSendFee,
|
||||
RequiresObserveConfirm: cfg.Capabilities.RequiresObserveConfirm,
|
||||
},
|
||||
Limits: buildGatewayLimits(cfg.Limits),
|
||||
Version: strings.TrimSpace(cfg.Version),
|
||||
IsEnabled: enabled,
|
||||
})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func parseRail(value string) model.Rail {
|
||||
switch strings.ToUpper(strings.TrimSpace(value)) {
|
||||
case string(model.RailCrypto):
|
||||
return model.RailCrypto
|
||||
case string(model.RailProviderSettlement):
|
||||
return model.RailProviderSettlement
|
||||
case string(model.RailLedger):
|
||||
return model.RailLedger
|
||||
case string(model.RailCardPayout):
|
||||
return model.RailCardPayout
|
||||
case string(model.RailFiatOnRamp):
|
||||
return model.RailFiatOnRamp
|
||||
default:
|
||||
return model.RailUnspecified
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeCurrencies(values []string) []string {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
result := make([]string, 0, len(values))
|
||||
for _, value := range values {
|
||||
clean := strings.ToUpper(strings.TrimSpace(value))
|
||||
if clean == "" || seen[clean] {
|
||||
continue
|
||||
}
|
||||
seen[clean] = true
|
||||
result = append(result, clean)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func buildGatewayLimits(cfg limitsConfig) model.Limits {
|
||||
limits := model.Limits{
|
||||
MinAmount: strings.TrimSpace(cfg.MinAmount),
|
||||
MaxAmount: strings.TrimSpace(cfg.MaxAmount),
|
||||
PerTxMaxFee: strings.TrimSpace(cfg.PerTxMaxFee),
|
||||
PerTxMinAmount: strings.TrimSpace(cfg.PerTxMinAmount),
|
||||
PerTxMaxAmount: strings.TrimSpace(cfg.PerTxMaxAmount),
|
||||
}
|
||||
|
||||
if len(cfg.VolumeLimit) > 0 {
|
||||
limits.VolumeLimit = map[string]string{}
|
||||
for key, value := range cfg.VolumeLimit {
|
||||
bucket := strings.TrimSpace(key)
|
||||
amount := strings.TrimSpace(value)
|
||||
if bucket == "" || amount == "" {
|
||||
continue
|
||||
}
|
||||
limits.VolumeLimit[bucket] = amount
|
||||
}
|
||||
}
|
||||
|
||||
if len(cfg.VelocityLimit) > 0 {
|
||||
limits.VelocityLimit = map[string]int{}
|
||||
for key, value := range cfg.VelocityLimit {
|
||||
bucket := strings.TrimSpace(key)
|
||||
if bucket == "" {
|
||||
continue
|
||||
}
|
||||
limits.VelocityLimit[bucket] = value
|
||||
}
|
||||
}
|
||||
|
||||
if len(cfg.CurrencyLimits) > 0 {
|
||||
limits.CurrencyLimits = map[string]model.LimitsOverride{}
|
||||
for key, override := range cfg.CurrencyLimits {
|
||||
currency := strings.ToUpper(strings.TrimSpace(key))
|
||||
if currency == "" {
|
||||
continue
|
||||
}
|
||||
limits.CurrencyLimits[currency] = model.LimitsOverride{
|
||||
MaxVolume: strings.TrimSpace(override.MaxVolume),
|
||||
MinAmount: strings.TrimSpace(override.MinAmount),
|
||||
MaxAmount: strings.TrimSpace(override.MaxAmount),
|
||||
MaxFee: strings.TrimSpace(override.MaxFee),
|
||||
MaxOps: override.MaxOps,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return limits
|
||||
}
|
||||
176
api/payments/orchestrator/internal/server/internal/clients.go
Normal file
176
api/payments/orchestrator/internal/server/internal/clients.go
Normal file
@@ -0,0 +1,176 @@
|
||||
package serverimp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
|
||||
oracleclient "github.com/tech/sendico/fx/oracle/client"
|
||||
chainclient "github.com/tech/sendico/gateway/chain/client"
|
||||
mntxclient "github.com/tech/sendico/gateway/mntx/client"
|
||||
ledgerclient "github.com/tech/sendico/ledger/client"
|
||||
feesv1 "github.com/tech/sendico/pkg/proto/billing/fees/v1"
|
||||
"go.uber.org/zap"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
)
|
||||
|
||||
func (i *Imp) initFeesClient(cfg clientConfig) (feesv1.FeeEngineClient, *grpc.ClientConn) {
|
||||
addr := cfg.address()
|
||||
if addr == "" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
dialCtx, cancel := context.WithTimeout(context.Background(), cfg.dialTimeout())
|
||||
defer cancel()
|
||||
|
||||
creds := credentials.NewTLS(&tls.Config{})
|
||||
if cfg.InsecureTransport {
|
||||
creds = insecure.NewCredentials()
|
||||
}
|
||||
|
||||
conn, err := grpc.DialContext(dialCtx, addr, grpc.WithTransportCredentials(creds))
|
||||
if err != nil {
|
||||
i.logger.Warn("Failed to connect to fees service", zap.String("address", addr), zap.Error(err))
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
i.logger.Info("Connected to fees service", zap.String("address", addr))
|
||||
return feesv1.NewFeeEngineClient(conn), conn
|
||||
}
|
||||
|
||||
func (i *Imp) initLedgerClient(cfg clientConfig) ledgerclient.Client {
|
||||
addr := cfg.address()
|
||||
if addr == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), cfg.dialTimeout())
|
||||
defer cancel()
|
||||
|
||||
client, err := ledgerclient.New(ctx, ledgerclient.Config{
|
||||
Address: addr,
|
||||
DialTimeout: cfg.dialTimeout(),
|
||||
CallTimeout: cfg.callTimeout(),
|
||||
Insecure: cfg.InsecureTransport,
|
||||
})
|
||||
if err != nil {
|
||||
i.logger.Warn("Failed to connect to ledger service", zap.String("address", addr), zap.Error(err))
|
||||
return nil
|
||||
}
|
||||
i.logger.Info("Connected to ledger service", zap.String("address", addr))
|
||||
return client
|
||||
}
|
||||
|
||||
func (i *Imp) initGatewayClient(cfg clientConfig) chainclient.Client {
|
||||
addr := cfg.address()
|
||||
if addr == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), cfg.dialTimeout())
|
||||
defer cancel()
|
||||
|
||||
client, err := chainclient.New(ctx, chainclient.Config{
|
||||
Address: addr,
|
||||
DialTimeout: cfg.dialTimeout(),
|
||||
CallTimeout: cfg.callTimeout(),
|
||||
Insecure: cfg.InsecureTransport,
|
||||
})
|
||||
if err != nil {
|
||||
i.logger.Warn("failed to connect to chain gateway service", zap.String("address", addr), zap.Error(err))
|
||||
return nil
|
||||
}
|
||||
i.logger.Info("connected to chain gateway service", zap.String("address", addr))
|
||||
return client
|
||||
}
|
||||
|
||||
func (i *Imp) initPaymentGatewayClient(cfg clientConfig) chainclient.Client {
|
||||
addr := cfg.address()
|
||||
if addr == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), cfg.dialTimeout())
|
||||
defer cancel()
|
||||
|
||||
client, err := chainclient.New(ctx, chainclient.Config{
|
||||
Address: addr,
|
||||
DialTimeout: cfg.dialTimeout(),
|
||||
CallTimeout: cfg.callTimeout(),
|
||||
Insecure: cfg.InsecureTransport,
|
||||
})
|
||||
if err != nil {
|
||||
i.logger.Warn("failed to connect to payment gateway service", zap.String("address", addr), zap.Error(err))
|
||||
return nil
|
||||
}
|
||||
i.logger.Info("connected to payment gateway service", zap.String("address", addr))
|
||||
return client
|
||||
}
|
||||
|
||||
func (i *Imp) initMntxClient(cfg clientConfig) mntxclient.Client {
|
||||
addr := cfg.address()
|
||||
if addr == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), cfg.dialTimeout())
|
||||
defer cancel()
|
||||
|
||||
client, err := mntxclient.New(ctx, mntxclient.Config{
|
||||
Address: addr,
|
||||
DialTimeout: cfg.dialTimeout(),
|
||||
CallTimeout: cfg.callTimeout(),
|
||||
Logger: i.logger.Named("client.mntx"),
|
||||
})
|
||||
if err != nil {
|
||||
i.logger.Warn("Failed to connect to mntx gateway service", zap.String("address", addr), zap.Error(err))
|
||||
return nil
|
||||
}
|
||||
i.logger.Info("Connected to mntx gateway service", zap.String("address", addr))
|
||||
return client
|
||||
}
|
||||
|
||||
func (i *Imp) initOracleClient(cfg clientConfig) oracleclient.Client {
|
||||
addr := cfg.address()
|
||||
if addr == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), cfg.dialTimeout())
|
||||
defer cancel()
|
||||
|
||||
client, err := oracleclient.New(ctx, oracleclient.Config{
|
||||
Address: addr,
|
||||
DialTimeout: cfg.dialTimeout(),
|
||||
CallTimeout: cfg.callTimeout(),
|
||||
Insecure: cfg.InsecureTransport,
|
||||
})
|
||||
if err != nil {
|
||||
i.logger.Warn("Failed to connect to oracle service", zap.String("address", addr), zap.Error(err))
|
||||
return nil
|
||||
}
|
||||
i.logger.Info("Connected to oracle service", zap.String("address", addr))
|
||||
return client
|
||||
}
|
||||
|
||||
func (i *Imp) closeClients() {
|
||||
if i.ledgerClient != nil {
|
||||
_ = i.ledgerClient.Close()
|
||||
}
|
||||
if i.gatewayClient != nil {
|
||||
_ = i.gatewayClient.Close()
|
||||
}
|
||||
if i.paymentGatewayClient != nil {
|
||||
_ = i.paymentGatewayClient.Close()
|
||||
}
|
||||
if i.mntxClient != nil {
|
||||
_ = i.mntxClient.Close()
|
||||
}
|
||||
if i.oracleClient != nil {
|
||||
_ = i.oracleClient.Close()
|
||||
}
|
||||
if i.feesConn != nil {
|
||||
_ = i.feesConn.Close()
|
||||
}
|
||||
}
|
||||
136
api/payments/orchestrator/internal/server/internal/config.go
Normal file
136
api/payments/orchestrator/internal/server/internal/config.go
Normal file
@@ -0,0 +1,136 @@
|
||||
package serverimp
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/tech/sendico/pkg/api/routers"
|
||||
"github.com/tech/sendico/pkg/server/grpcapp"
|
||||
"go.uber.org/zap"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
type config struct {
|
||||
*grpcapp.Config `yaml:",inline"`
|
||||
Fees clientConfig `yaml:"fees"`
|
||||
Ledger clientConfig `yaml:"ledger"`
|
||||
Gateway clientConfig `yaml:"gateway"`
|
||||
PaymentGateway clientConfig `yaml:"payment_gateway"`
|
||||
Mntx clientConfig `yaml:"mntx"`
|
||||
Oracle clientConfig `yaml:"oracle"`
|
||||
CardGateways map[string]cardGatewayRouteConfig `yaml:"card_gateways"`
|
||||
FeeAccounts map[string]string `yaml:"fee_ledger_accounts"`
|
||||
GatewayInstances []gatewayInstanceConfig `yaml:"gateway_instances"`
|
||||
}
|
||||
|
||||
type clientConfig struct {
|
||||
Address string `yaml:"address"`
|
||||
DialTimeoutSecs int `yaml:"dial_timeout_seconds"`
|
||||
CallTimeoutSecs int `yaml:"call_timeout_seconds"`
|
||||
InsecureTransport bool `yaml:"insecure"`
|
||||
}
|
||||
|
||||
type cardGatewayRouteConfig struct {
|
||||
FundingAddress string `yaml:"funding_address"`
|
||||
FeeAddress string `yaml:"fee_address"`
|
||||
FeeWalletRef string `yaml:"fee_wallet_ref"`
|
||||
}
|
||||
|
||||
type gatewayInstanceConfig struct {
|
||||
ID string `yaml:"id"`
|
||||
Rail string `yaml:"rail"`
|
||||
Network string `yaml:"network"`
|
||||
Currencies []string `yaml:"currencies"`
|
||||
Capabilities gatewayCapabilitiesConfig `yaml:"capabilities"`
|
||||
Limits limitsConfig `yaml:"limits"`
|
||||
Version string `yaml:"version"`
|
||||
IsEnabled *bool `yaml:"is_enabled"`
|
||||
}
|
||||
|
||||
type gatewayCapabilitiesConfig struct {
|
||||
CanPayIn bool `yaml:"can_pay_in"`
|
||||
CanPayOut bool `yaml:"can_pay_out"`
|
||||
CanReadBalance bool `yaml:"can_read_balance"`
|
||||
CanSendFee bool `yaml:"can_send_fee"`
|
||||
RequiresObserveConfirm bool `yaml:"requires_observe_confirm"`
|
||||
}
|
||||
|
||||
type limitsConfig struct {
|
||||
MinAmount string `yaml:"min_amount"`
|
||||
MaxAmount string `yaml:"max_amount"`
|
||||
PerTxMaxFee string `yaml:"per_tx_max_fee"`
|
||||
PerTxMinAmount string `yaml:"per_tx_min_amount"`
|
||||
PerTxMaxAmount string `yaml:"per_tx_max_amount"`
|
||||
VolumeLimit map[string]string `yaml:"volume_limit"`
|
||||
VelocityLimit map[string]int `yaml:"velocity_limit"`
|
||||
CurrencyLimits map[string]limitsOverrideCfg `yaml:"currency_limits"`
|
||||
}
|
||||
|
||||
type limitsOverrideCfg struct {
|
||||
MaxVolume string `yaml:"max_volume"`
|
||||
MinAmount string `yaml:"min_amount"`
|
||||
MaxAmount string `yaml:"max_amount"`
|
||||
MaxFee string `yaml:"max_fee"`
|
||||
MaxOps int `yaml:"max_ops"`
|
||||
}
|
||||
|
||||
func (c clientConfig) address() string {
|
||||
return strings.TrimSpace(c.Address)
|
||||
}
|
||||
|
||||
func (c clientConfig) dialTimeout() time.Duration {
|
||||
if c.DialTimeoutSecs <= 0 {
|
||||
return 5 * time.Second
|
||||
}
|
||||
return time.Duration(c.DialTimeoutSecs) * time.Second
|
||||
}
|
||||
|
||||
func (c clientConfig) callTimeout() time.Duration {
|
||||
if c.CallTimeoutSecs <= 0 {
|
||||
return 3 * time.Second
|
||||
}
|
||||
return time.Duration(c.CallTimeoutSecs) * time.Second
|
||||
}
|
||||
|
||||
func (i *Imp) loadConfig() (*config, error) {
|
||||
data, err := os.ReadFile(i.file)
|
||||
if err != nil {
|
||||
i.logger.Error("Could not read configuration file", zap.String("config_file", i.file), zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cfg := &config{Config: &grpcapp.Config{}}
|
||||
if err := yaml.Unmarshal(data, cfg); err != nil {
|
||||
i.logger.Error("Failed to parse configuration", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if cfg.Runtime == nil {
|
||||
cfg.Runtime = &grpcapp.RuntimeConfig{ShutdownTimeoutSeconds: 15}
|
||||
}
|
||||
|
||||
if cfg.GRPC == nil {
|
||||
cfg.GRPC = &routers.GRPCConfig{
|
||||
Network: "tcp",
|
||||
Address: ":50062",
|
||||
EnableReflection: true,
|
||||
EnableHealth: true,
|
||||
}
|
||||
} else {
|
||||
if strings.TrimSpace(cfg.GRPC.Address) == "" {
|
||||
cfg.GRPC.Address = ":50062"
|
||||
}
|
||||
if strings.TrimSpace(cfg.GRPC.Network) == "" {
|
||||
cfg.GRPC.Network = "tcp"
|
||||
}
|
||||
}
|
||||
|
||||
if cfg.Metrics == nil {
|
||||
cfg.Metrics = &grpcapp.MetricsConfig{Address: ":9403"}
|
||||
} else if strings.TrimSpace(cfg.Metrics.Address) == "" {
|
||||
cfg.Metrics.Address = ":9403"
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package serverimp
|
||||
|
||||
import (
|
||||
oracleclient "github.com/tech/sendico/fx/oracle/client"
|
||||
chainclient "github.com/tech/sendico/gateway/chain/client"
|
||||
mntxclient "github.com/tech/sendico/gateway/mntx/client"
|
||||
ledgerclient "github.com/tech/sendico/ledger/client"
|
||||
"github.com/tech/sendico/payments/orchestrator/internal/service/orchestrator"
|
||||
feesv1 "github.com/tech/sendico/pkg/proto/billing/fees/v1"
|
||||
)
|
||||
|
||||
type orchestratorDeps struct {
|
||||
feesClient feesv1.FeeEngineClient
|
||||
ledgerClient ledgerclient.Client
|
||||
gatewayClient chainclient.Client
|
||||
paymentGatewayClient chainclient.Client
|
||||
mntxClient mntxclient.Client
|
||||
oracleClient oracleclient.Client
|
||||
}
|
||||
|
||||
func (i *Imp) initDependencies(cfg *config) *orchestratorDeps {
|
||||
deps := &orchestratorDeps{}
|
||||
if cfg == nil {
|
||||
return deps
|
||||
}
|
||||
|
||||
deps.feesClient, i.feesConn = i.initFeesClient(cfg.Fees)
|
||||
|
||||
deps.ledgerClient = i.initLedgerClient(cfg.Ledger)
|
||||
if deps.ledgerClient != nil {
|
||||
i.ledgerClient = deps.ledgerClient
|
||||
}
|
||||
|
||||
deps.gatewayClient = i.initGatewayClient(cfg.Gateway)
|
||||
if deps.gatewayClient != nil {
|
||||
i.gatewayClient = deps.gatewayClient
|
||||
}
|
||||
|
||||
deps.paymentGatewayClient = i.initPaymentGatewayClient(cfg.PaymentGateway)
|
||||
if deps.paymentGatewayClient != nil {
|
||||
i.paymentGatewayClient = deps.paymentGatewayClient
|
||||
}
|
||||
|
||||
deps.mntxClient = i.initMntxClient(cfg.Mntx)
|
||||
if deps.mntxClient != nil {
|
||||
i.mntxClient = deps.mntxClient
|
||||
}
|
||||
|
||||
deps.oracleClient = i.initOracleClient(cfg.Oracle)
|
||||
if deps.oracleClient != nil {
|
||||
i.oracleClient = deps.oracleClient
|
||||
}
|
||||
|
||||
return deps
|
||||
}
|
||||
|
||||
func (i *Imp) buildServiceOptions(cfg *config, deps *orchestratorDeps) []orchestrator.Option {
|
||||
if cfg == nil || deps == nil {
|
||||
return nil
|
||||
}
|
||||
opts := []orchestrator.Option{}
|
||||
if deps.feesClient != nil {
|
||||
opts = append(opts, orchestrator.WithFeeEngine(deps.feesClient, cfg.Fees.callTimeout()))
|
||||
}
|
||||
if deps.ledgerClient != nil {
|
||||
opts = append(opts, orchestrator.WithLedgerClient(deps.ledgerClient))
|
||||
}
|
||||
if deps.gatewayClient != nil {
|
||||
opts = append(opts, orchestrator.WithChainGatewayClient(deps.gatewayClient))
|
||||
}
|
||||
if deps.paymentGatewayClient != nil {
|
||||
opts = append(opts, orchestrator.WithProviderSettlementGatewayClient(deps.paymentGatewayClient))
|
||||
}
|
||||
if railGateways := buildRailGateways(deps.gatewayClient, deps.paymentGatewayClient, cfg.GatewayInstances); len(railGateways) > 0 {
|
||||
opts = append(opts, orchestrator.WithRailGateways(railGateways))
|
||||
}
|
||||
if deps.mntxClient != nil {
|
||||
opts = append(opts, orchestrator.WithMntxGateway(deps.mntxClient))
|
||||
}
|
||||
if deps.oracleClient != nil {
|
||||
opts = append(opts, orchestrator.WithOracleClient(deps.oracleClient))
|
||||
}
|
||||
if routes := buildCardGatewayRoutes(cfg.CardGateways); len(routes) > 0 {
|
||||
opts = append(opts, orchestrator.WithCardGatewayRoutes(routes))
|
||||
}
|
||||
if feeAccounts := buildFeeLedgerAccounts(cfg.FeeAccounts); len(feeAccounts) > 0 {
|
||||
opts = append(opts, orchestrator.WithFeeLedgerAccounts(feeAccounts))
|
||||
}
|
||||
if registry := buildGatewayRegistry(i.logger, cfg.GatewayInstances, i.discoveryReg); registry != nil {
|
||||
opts = append(opts, orchestrator.WithGatewayRegistry(registry))
|
||||
}
|
||||
return opts
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package serverimp
|
||||
|
||||
import (
|
||||
"github.com/tech/sendico/payments/orchestrator/internal/appversion"
|
||||
"github.com/tech/sendico/pkg/discovery"
|
||||
msg "github.com/tech/sendico/pkg/messaging"
|
||||
msgproducer "github.com/tech/sendico/pkg/messaging/producer"
|
||||
"github.com/tech/sendico/pkg/mservice"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func (i *Imp) initDiscovery(cfg *config) {
|
||||
if cfg == nil || cfg.Messaging == nil || cfg.Messaging.Driver == "" {
|
||||
return
|
||||
}
|
||||
logger := i.logger.Named("discovery")
|
||||
broker, err := msg.CreateMessagingBroker(logger.Named("bus"), cfg.Messaging)
|
||||
if err != nil {
|
||||
i.logger.Warn("Failed to initialise discovery broker", zap.Error(err))
|
||||
return
|
||||
}
|
||||
producer := msgproducer.NewProducer(logger.Named("producer"), broker)
|
||||
registry := discovery.NewRegistry()
|
||||
watcher, err := discovery.NewRegistryWatcher(i.logger, broker, registry)
|
||||
if err != nil {
|
||||
i.logger.Warn("Failed to initialise discovery registry watcher", zap.Error(err))
|
||||
} else if err := watcher.Start(); err != nil {
|
||||
i.logger.Warn("Failed to start discovery registry watcher", zap.Error(err))
|
||||
} else {
|
||||
i.discoveryWatcher = watcher
|
||||
i.discoveryReg = registry
|
||||
i.logger.Info("Discovery registry watcher started")
|
||||
}
|
||||
announce := discovery.Announcement{
|
||||
Service: "PAYMENTS_ORCHESTRATOR",
|
||||
Operations: []string{"payment.quote", "payment.initiate"},
|
||||
Version: appversion.Create().Short(),
|
||||
}
|
||||
i.discoveryAnnouncer = discovery.NewAnnouncer(i.logger, producer, string(mservice.PaymentOrchestrator), announce)
|
||||
i.discoveryAnnouncer.Start()
|
||||
}
|
||||
|
||||
func (i *Imp) stopDiscovery() {
|
||||
if i.discoveryAnnouncer != nil {
|
||||
i.discoveryAnnouncer.Stop()
|
||||
}
|
||||
if i.discoveryWatcher != nil {
|
||||
i.discoveryWatcher.Stop()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package serverimp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (i *Imp) shutdownApp() {
|
||||
if i.app != nil {
|
||||
timeout := 15 * time.Second
|
||||
if i.config != nil && i.config.Runtime != nil {
|
||||
timeout = i.config.Runtime.ShutdownTimeout()
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
i.app.Shutdown(ctx)
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
@@ -1,88 +1,17 @@
|
||||
package serverimp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
oracleclient "github.com/tech/sendico/fx/oracle/client"
|
||||
chainclient "github.com/tech/sendico/gateway/chain/client"
|
||||
mntxclient "github.com/tech/sendico/gateway/mntx/client"
|
||||
ledgerclient "github.com/tech/sendico/ledger/client"
|
||||
"github.com/tech/sendico/payments/orchestrator/internal/service/orchestrator"
|
||||
"github.com/tech/sendico/payments/orchestrator/storage"
|
||||
mongostorage "github.com/tech/sendico/payments/orchestrator/storage/mongo"
|
||||
"github.com/tech/sendico/pkg/api/routers"
|
||||
"github.com/tech/sendico/pkg/db"
|
||||
msg "github.com/tech/sendico/pkg/messaging"
|
||||
mb "github.com/tech/sendico/pkg/messaging/broker"
|
||||
"github.com/tech/sendico/pkg/mlogger"
|
||||
feesv1 "github.com/tech/sendico/pkg/proto/billing/fees/v1"
|
||||
"github.com/tech/sendico/pkg/server/grpcapp"
|
||||
"go.uber.org/zap"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
type Imp struct {
|
||||
logger mlogger.Logger
|
||||
file string
|
||||
debug bool
|
||||
|
||||
config *config
|
||||
app *grpcapp.App[storage.Repository]
|
||||
feesConn *grpc.ClientConn
|
||||
ledgerClient ledgerclient.Client
|
||||
gatewayClient chainclient.Client
|
||||
mntxClient mntxclient.Client
|
||||
oracleClient oracleclient.Client
|
||||
}
|
||||
|
||||
type config struct {
|
||||
*grpcapp.Config `yaml:",inline"`
|
||||
Fees clientConfig `yaml:"fees"`
|
||||
Ledger clientConfig `yaml:"ledger"`
|
||||
Gateway clientConfig `yaml:"gateway"`
|
||||
Mntx clientConfig `yaml:"mntx"`
|
||||
Oracle clientConfig `yaml:"oracle"`
|
||||
CardGateways map[string]cardGatewayRouteConfig `yaml:"card_gateways"`
|
||||
FeeAccounts map[string]string `yaml:"fee_ledger_accounts"`
|
||||
}
|
||||
|
||||
type clientConfig struct {
|
||||
Address string `yaml:"address"`
|
||||
DialTimeoutSecs int `yaml:"dial_timeout_seconds"`
|
||||
CallTimeoutSecs int `yaml:"call_timeout_seconds"`
|
||||
InsecureTransport bool `yaml:"insecure"`
|
||||
}
|
||||
|
||||
type cardGatewayRouteConfig struct {
|
||||
FundingAddress string `yaml:"funding_address"`
|
||||
FeeAddress string `yaml:"fee_address"`
|
||||
FeeWalletRef string `yaml:"fee_wallet_ref"`
|
||||
}
|
||||
|
||||
func (c clientConfig) address() string {
|
||||
return strings.TrimSpace(c.Address)
|
||||
}
|
||||
|
||||
func (c clientConfig) dialTimeout() time.Duration {
|
||||
if c.DialTimeoutSecs <= 0 {
|
||||
return 5 * time.Second
|
||||
}
|
||||
return time.Duration(c.DialTimeoutSecs) * time.Second
|
||||
}
|
||||
|
||||
func (c clientConfig) callTimeout() time.Duration {
|
||||
if c.CallTimeoutSecs <= 0 {
|
||||
return 3 * time.Second
|
||||
}
|
||||
return time.Duration(c.CallTimeoutSecs) * time.Second
|
||||
}
|
||||
|
||||
func Create(logger mlogger.Logger, file string, debug bool) (*Imp, error) {
|
||||
return &Imp{
|
||||
logger: logger.Named("server"),
|
||||
@@ -92,31 +21,12 @@ func Create(logger mlogger.Logger, file string, debug bool) (*Imp, error) {
|
||||
}
|
||||
|
||||
func (i *Imp) Shutdown() {
|
||||
if i.app != nil {
|
||||
timeout := 15 * time.Second
|
||||
if i.config != nil && i.config.Runtime != nil {
|
||||
timeout = i.config.Runtime.ShutdownTimeout()
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
i.app.Shutdown(ctx)
|
||||
cancel()
|
||||
}
|
||||
|
||||
if i.ledgerClient != nil {
|
||||
_ = i.ledgerClient.Close()
|
||||
}
|
||||
if i.gatewayClient != nil {
|
||||
_ = i.gatewayClient.Close()
|
||||
}
|
||||
if i.mntxClient != nil {
|
||||
_ = i.mntxClient.Close()
|
||||
}
|
||||
if i.oracleClient != nil {
|
||||
_ = i.oracleClient.Close()
|
||||
}
|
||||
if i.feesConn != nil {
|
||||
_ = i.feesConn.Close()
|
||||
i.stopDiscovery()
|
||||
if i.service != nil {
|
||||
i.service.Shutdown()
|
||||
}
|
||||
i.shutdownApp()
|
||||
i.closeClients()
|
||||
}
|
||||
|
||||
func (i *Imp) Start() error {
|
||||
@@ -126,59 +36,30 @@ func (i *Imp) Start() error {
|
||||
}
|
||||
i.config = cfg
|
||||
|
||||
i.initDiscovery(cfg)
|
||||
|
||||
repoFactory := func(logger mlogger.Logger, conn *db.MongoConnection) (storage.Repository, error) {
|
||||
return mongostorage.New(logger, conn)
|
||||
}
|
||||
|
||||
feesClient, feesConn := i.initFeesClient(cfg.Fees)
|
||||
if feesConn != nil {
|
||||
i.feesConn = feesConn
|
||||
var broker mb.Broker
|
||||
if cfg.Messaging != nil && cfg.Messaging.Driver != "" {
|
||||
broker, err = msg.CreateMessagingBroker(i.logger, cfg.Messaging)
|
||||
if err != nil {
|
||||
i.logger.Warn("Failed to create messaging broker", zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
ledgerClient := i.initLedgerClient(cfg.Ledger)
|
||||
if ledgerClient != nil {
|
||||
i.ledgerClient = ledgerClient
|
||||
}
|
||||
|
||||
gatewayClient := i.initGatewayClient(cfg.Gateway)
|
||||
if gatewayClient != nil {
|
||||
i.gatewayClient = gatewayClient
|
||||
}
|
||||
|
||||
mntxClient := i.initMntxClient(cfg.Mntx)
|
||||
if mntxClient != nil {
|
||||
i.mntxClient = mntxClient
|
||||
}
|
||||
|
||||
oracleClient := i.initOracleClient(cfg.Oracle)
|
||||
if oracleClient != nil {
|
||||
i.oracleClient = oracleClient
|
||||
}
|
||||
deps := i.initDependencies(cfg)
|
||||
|
||||
serviceFactory := func(logger mlogger.Logger, repo storage.Repository, producer msg.Producer) (grpcapp.Service, error) {
|
||||
opts := []orchestrator.Option{}
|
||||
if feesClient != nil {
|
||||
opts = append(opts, orchestrator.WithFeeEngine(feesClient, cfg.Fees.callTimeout()))
|
||||
opts := i.buildServiceOptions(cfg, deps)
|
||||
if broker != nil {
|
||||
opts = append(opts, orchestrator.WithPaymentGatewayBroker(broker))
|
||||
}
|
||||
if ledgerClient != nil {
|
||||
opts = append(opts, orchestrator.WithLedgerClient(ledgerClient))
|
||||
}
|
||||
if gatewayClient != nil {
|
||||
opts = append(opts, orchestrator.WithChainGatewayClient(gatewayClient))
|
||||
}
|
||||
if mntxClient != nil {
|
||||
opts = append(opts, orchestrator.WithMntxGateway(mntxClient))
|
||||
}
|
||||
if oracleClient != nil {
|
||||
opts = append(opts, orchestrator.WithOracleClient(oracleClient))
|
||||
}
|
||||
if routes := buildCardGatewayRoutes(cfg.CardGateways); len(routes) > 0 {
|
||||
opts = append(opts, orchestrator.WithCardGatewayRoutes(routes))
|
||||
}
|
||||
if feeAccounts := buildFeeLedgerAccounts(cfg.FeeAccounts); len(feeAccounts) > 0 {
|
||||
opts = append(opts, orchestrator.WithFeeLedgerAccounts(feeAccounts))
|
||||
}
|
||||
return orchestrator.NewService(logger, repo, opts...), nil
|
||||
svc := orchestrator.NewService(logger, repo, opts...)
|
||||
i.service = svc
|
||||
return svc, nil
|
||||
}
|
||||
|
||||
app, err := grpcapp.NewApp(i.logger, "payments_orchestrator", cfg.Config, i.debug, repoFactory, serviceFactory)
|
||||
@@ -189,196 +70,3 @@ func (i *Imp) Start() error {
|
||||
|
||||
return i.app.Start()
|
||||
}
|
||||
|
||||
func (i *Imp) initFeesClient(cfg clientConfig) (feesv1.FeeEngineClient, *grpc.ClientConn) {
|
||||
addr := cfg.address()
|
||||
if addr == "" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
dialCtx, cancel := context.WithTimeout(context.Background(), cfg.dialTimeout())
|
||||
defer cancel()
|
||||
|
||||
creds := credentials.NewTLS(&tls.Config{})
|
||||
if cfg.InsecureTransport {
|
||||
creds = insecure.NewCredentials()
|
||||
}
|
||||
|
||||
conn, err := grpc.DialContext(dialCtx, addr, grpc.WithTransportCredentials(creds))
|
||||
if err != nil {
|
||||
i.logger.Warn("Failed to connect to fees service", zap.String("address", addr), zap.Error(err))
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
i.logger.Info("Connected to fees service", zap.String("address", addr))
|
||||
return feesv1.NewFeeEngineClient(conn), conn
|
||||
}
|
||||
|
||||
func (i *Imp) initLedgerClient(cfg clientConfig) ledgerclient.Client {
|
||||
addr := cfg.address()
|
||||
if addr == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), cfg.dialTimeout())
|
||||
defer cancel()
|
||||
|
||||
client, err := ledgerclient.New(ctx, ledgerclient.Config{
|
||||
Address: addr,
|
||||
DialTimeout: cfg.dialTimeout(),
|
||||
CallTimeout: cfg.callTimeout(),
|
||||
Insecure: cfg.InsecureTransport,
|
||||
})
|
||||
if err != nil {
|
||||
i.logger.Warn("Failed to connect to ledger service", zap.String("address", addr), zap.Error(err))
|
||||
return nil
|
||||
}
|
||||
i.logger.Info("Connected to ledger service", zap.String("address", addr))
|
||||
return client
|
||||
}
|
||||
|
||||
func (i *Imp) initGatewayClient(cfg clientConfig) chainclient.Client {
|
||||
addr := cfg.address()
|
||||
if addr == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), cfg.dialTimeout())
|
||||
defer cancel()
|
||||
|
||||
client, err := chainclient.New(ctx, chainclient.Config{
|
||||
Address: addr,
|
||||
DialTimeout: cfg.dialTimeout(),
|
||||
CallTimeout: cfg.callTimeout(),
|
||||
Insecure: cfg.InsecureTransport,
|
||||
})
|
||||
if err != nil {
|
||||
i.logger.Warn("failed to connect to chain gateway service", zap.String("address", addr), zap.Error(err))
|
||||
return nil
|
||||
}
|
||||
i.logger.Info("connected to chain gateway service", zap.String("address", addr))
|
||||
return client
|
||||
}
|
||||
|
||||
func (i *Imp) initMntxClient(cfg clientConfig) mntxclient.Client {
|
||||
addr := cfg.address()
|
||||
if addr == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), cfg.dialTimeout())
|
||||
defer cancel()
|
||||
|
||||
client, err := mntxclient.New(ctx, mntxclient.Config{
|
||||
Address: addr,
|
||||
DialTimeout: cfg.dialTimeout(),
|
||||
CallTimeout: cfg.callTimeout(),
|
||||
Logger: i.logger.Named("client.mntx"),
|
||||
})
|
||||
if err != nil {
|
||||
i.logger.Warn("Failed to connect to mntx gateway service", zap.String("address", addr), zap.Error(err))
|
||||
return nil
|
||||
}
|
||||
i.logger.Info("Connected to mntx gateway service", zap.String("address", addr))
|
||||
return client
|
||||
}
|
||||
|
||||
func (i *Imp) initOracleClient(cfg clientConfig) oracleclient.Client {
|
||||
addr := cfg.address()
|
||||
if addr == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), cfg.dialTimeout())
|
||||
defer cancel()
|
||||
|
||||
client, err := oracleclient.New(ctx, oracleclient.Config{
|
||||
Address: addr,
|
||||
DialTimeout: cfg.dialTimeout(),
|
||||
CallTimeout: cfg.callTimeout(),
|
||||
Insecure: cfg.InsecureTransport,
|
||||
})
|
||||
if err != nil {
|
||||
i.logger.Warn("Failed to connect to oracle service", zap.String("address", addr), zap.Error(err))
|
||||
return nil
|
||||
}
|
||||
i.logger.Info("Connected to oracle service", zap.String("address", addr))
|
||||
return client
|
||||
}
|
||||
|
||||
func (i *Imp) loadConfig() (*config, error) {
|
||||
data, err := os.ReadFile(i.file)
|
||||
if err != nil {
|
||||
i.logger.Error("Could not read configuration file", zap.String("config_file", i.file), zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cfg := &config{Config: &grpcapp.Config{}}
|
||||
if err := yaml.Unmarshal(data, cfg); err != nil {
|
||||
i.logger.Error("Failed to parse configuration", zap.Error(err))
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if cfg.Runtime == nil {
|
||||
cfg.Runtime = &grpcapp.RuntimeConfig{ShutdownTimeoutSeconds: 15}
|
||||
}
|
||||
|
||||
if cfg.GRPC == nil {
|
||||
cfg.GRPC = &routers.GRPCConfig{
|
||||
Network: "tcp",
|
||||
Address: ":50062",
|
||||
EnableReflection: true,
|
||||
EnableHealth: true,
|
||||
}
|
||||
} else {
|
||||
if strings.TrimSpace(cfg.GRPC.Address) == "" {
|
||||
cfg.GRPC.Address = ":50062"
|
||||
}
|
||||
if strings.TrimSpace(cfg.GRPC.Network) == "" {
|
||||
cfg.GRPC.Network = "tcp"
|
||||
}
|
||||
}
|
||||
|
||||
if cfg.Metrics == nil {
|
||||
cfg.Metrics = &grpcapp.MetricsConfig{Address: ":9403"}
|
||||
} else if strings.TrimSpace(cfg.Metrics.Address) == "" {
|
||||
cfg.Metrics.Address = ":9403"
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func buildCardGatewayRoutes(src map[string]cardGatewayRouteConfig) map[string]orchestrator.CardGatewayRoute {
|
||||
if len(src) == 0 {
|
||||
return nil
|
||||
}
|
||||
result := make(map[string]orchestrator.CardGatewayRoute, len(src))
|
||||
for key, route := range src {
|
||||
trimmedKey := strings.TrimSpace(key)
|
||||
if trimmedKey == "" {
|
||||
continue
|
||||
}
|
||||
result[trimmedKey] = orchestrator.CardGatewayRoute{
|
||||
FundingAddress: strings.TrimSpace(route.FundingAddress),
|
||||
FeeAddress: strings.TrimSpace(route.FeeAddress),
|
||||
FeeWalletRef: strings.TrimSpace(route.FeeWalletRef),
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func buildFeeLedgerAccounts(src map[string]string) map[string]string {
|
||||
if len(src) == 0 {
|
||||
return nil
|
||||
}
|
||||
result := make(map[string]string, len(src))
|
||||
for key, account := range src {
|
||||
k := strings.ToLower(strings.TrimSpace(key))
|
||||
v := strings.TrimSpace(account)
|
||||
if k == "" || v == "" {
|
||||
continue
|
||||
}
|
||||
result[k] = v
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
33
api/payments/orchestrator/internal/server/internal/types.go
Normal file
33
api/payments/orchestrator/internal/server/internal/types.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package serverimp
|
||||
|
||||
import (
|
||||
oracleclient "github.com/tech/sendico/fx/oracle/client"
|
||||
chainclient "github.com/tech/sendico/gateway/chain/client"
|
||||
mntxclient "github.com/tech/sendico/gateway/mntx/client"
|
||||
ledgerclient "github.com/tech/sendico/ledger/client"
|
||||
"github.com/tech/sendico/payments/orchestrator/internal/service/orchestrator"
|
||||
"github.com/tech/sendico/payments/orchestrator/storage"
|
||||
"github.com/tech/sendico/pkg/discovery"
|
||||
"github.com/tech/sendico/pkg/mlogger"
|
||||
"github.com/tech/sendico/pkg/server/grpcapp"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
type Imp struct {
|
||||
logger mlogger.Logger
|
||||
file string
|
||||
debug bool
|
||||
|
||||
config *config
|
||||
app *grpcapp.App[storage.Repository]
|
||||
discoveryWatcher *discovery.RegistryWatcher
|
||||
discoveryReg *discovery.Registry
|
||||
discoveryAnnouncer *discovery.Announcer
|
||||
service *orchestrator.Service
|
||||
feesConn *grpc.ClientConn
|
||||
ledgerClient ledgerclient.Client
|
||||
gatewayClient chainclient.Client
|
||||
paymentGatewayClient chainclient.Client
|
||||
mntxClient mntxclient.Client
|
||||
oracleClient oracleclient.Client
|
||||
}
|
||||
@@ -1,702 +0,0 @@
|
||||
package orchestrator
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/tech/sendico/payments/orchestrator/storage/model"
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
moneyv1 "github.com/tech/sendico/pkg/proto/common/money/v1"
|
||||
chainv1 "github.com/tech/sendico/pkg/proto/gateway/chain/v1"
|
||||
mntxv1 "github.com/tech/sendico/pkg/proto/gateway/mntx/v1"
|
||||
orchestratorv1 "github.com/tech/sendico/pkg/proto/payments/orchestrator/v1"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultCardGateway = "monetix"
|
||||
|
||||
stepCodeGasTopUp = "gas_top_up"
|
||||
stepCodeFundingTransfer = "funding_transfer"
|
||||
stepCodeCardPayout = "card_payout"
|
||||
stepCodeFeeTransfer = "fee_transfer"
|
||||
)
|
||||
|
||||
func (s *Service) cardRoute(gateway string) (CardGatewayRoute, error) {
|
||||
if len(s.deps.cardRoutes) == 0 {
|
||||
s.logger.Warn("card routing not configured", zap.String("gateway", gateway))
|
||||
return CardGatewayRoute{}, merrors.InvalidArgument("card routing not configured")
|
||||
}
|
||||
key := strings.ToLower(strings.TrimSpace(gateway))
|
||||
if key == "" {
|
||||
key = defaultCardGateway
|
||||
}
|
||||
route, ok := s.deps.cardRoutes[key]
|
||||
if !ok {
|
||||
s.logger.Warn("card routing missing for gateway", zap.String("gateway", key))
|
||||
return CardGatewayRoute{}, merrors.InvalidArgument("card routing missing for gateway " + key)
|
||||
}
|
||||
if strings.TrimSpace(route.FundingAddress) == "" {
|
||||
s.logger.Warn("card routing missing funding address", zap.String("gateway", key))
|
||||
return CardGatewayRoute{}, merrors.InvalidArgument("card funding address is required for gateway " + key)
|
||||
}
|
||||
return route, nil
|
||||
}
|
||||
|
||||
func (s *Service) submitCardFundingTransfers(ctx context.Context, payment *model.Payment, quote *orchestratorv1.PaymentQuote) error {
|
||||
if payment == nil {
|
||||
return merrors.InvalidArgument("payment is required")
|
||||
}
|
||||
intent := payment.Intent
|
||||
source := intent.Source.ManagedWallet
|
||||
if source == nil || strings.TrimSpace(source.ManagedWalletRef) == "" {
|
||||
return merrors.InvalidArgument("card funding: source managed wallet is required")
|
||||
}
|
||||
if !s.deps.gateway.available() {
|
||||
s.logger.Warn("card funding aborted: chain gateway unavailable")
|
||||
return merrors.InvalidArgument("card funding: chain gateway unavailable")
|
||||
}
|
||||
|
||||
route, err := s.cardRoute(defaultCardGateway)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sourceWalletRef := strings.TrimSpace(source.ManagedWalletRef)
|
||||
fundingAddress := strings.TrimSpace(route.FundingAddress)
|
||||
feeWalletRef := strings.TrimSpace(route.FeeWalletRef)
|
||||
|
||||
amount := cloneMoney(intent.Amount)
|
||||
if amount == nil || strings.TrimSpace(amount.GetAmount()) == "" || strings.TrimSpace(amount.GetCurrency()) == "" {
|
||||
return merrors.InvalidArgument("card funding: amount is required")
|
||||
}
|
||||
|
||||
payoutAmount, err := cardPayoutAmount(payment)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
feeMoney := (*moneyv1.Money)(nil)
|
||||
if quote != nil {
|
||||
feeMoney = quote.GetExpectedFeeTotal()
|
||||
}
|
||||
if feeMoney == nil && payment.LastQuote != nil {
|
||||
feeMoney = payment.LastQuote.ExpectedFeeTotal
|
||||
}
|
||||
feeDecimal := decimal.Zero
|
||||
if feeMoney != nil && strings.TrimSpace(feeMoney.GetAmount()) != "" {
|
||||
if strings.TrimSpace(feeMoney.GetCurrency()) == "" {
|
||||
return merrors.InvalidArgument("card funding: fee currency is required")
|
||||
}
|
||||
feeDecimal, err = decimalFromMoney(feeMoney)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
feeRequired := feeDecimal.IsPositive()
|
||||
|
||||
fundingDest := &chainv1.TransferDestination{
|
||||
Destination: &chainv1.TransferDestination_ExternalAddress{ExternalAddress: fundingAddress},
|
||||
}
|
||||
fundingFee, err := s.estimateTransferNetworkFee(ctx, sourceWalletRef, fundingDest, amount)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var feeTransferFee *moneyv1.Money
|
||||
if feeRequired {
|
||||
if feeWalletRef == "" {
|
||||
return merrors.InvalidArgument("card funding: fee wallet ref is required when fee exists")
|
||||
}
|
||||
feeDest := &chainv1.TransferDestination{
|
||||
Destination: &chainv1.TransferDestination_ManagedWalletRef{ManagedWalletRef: feeWalletRef},
|
||||
}
|
||||
feeTransferFee, err = s.estimateTransferNetworkFee(ctx, sourceWalletRef, feeDest, feeMoney)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
totalFee, gasCurrency, err := sumNetworkFees(fundingFee, feeTransferFee)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var estimatedTotalFee *moneyv1.Money
|
||||
if gasCurrency != "" && !totalFee.IsNegative() {
|
||||
estimatedTotalFee = makeMoney(gasCurrency, totalFee)
|
||||
}
|
||||
|
||||
var topUpMoney *moneyv1.Money
|
||||
var topUpFee *moneyv1.Money
|
||||
topUpPositive := false
|
||||
if estimatedTotalFee != nil {
|
||||
computeResp, err := s.deps.gateway.client.ComputeGasTopUp(ctx, &chainv1.ComputeGasTopUpRequest{
|
||||
WalletRef: sourceWalletRef,
|
||||
EstimatedTotalFee: estimatedTotalFee,
|
||||
})
|
||||
if err != nil {
|
||||
s.logger.Warn("card funding gas top-up compute failed", zap.Error(err), zap.String("payment_ref", payment.PaymentRef))
|
||||
return err
|
||||
}
|
||||
if computeResp != nil {
|
||||
topUpMoney = computeResp.GetTopupAmount()
|
||||
}
|
||||
if topUpMoney != nil && strings.TrimSpace(topUpMoney.GetAmount()) != "" {
|
||||
amountDec, err := decimalFromMoney(topUpMoney)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
topUpPositive = amountDec.IsPositive()
|
||||
}
|
||||
if topUpMoney != nil && topUpPositive {
|
||||
if strings.TrimSpace(topUpMoney.GetCurrency()) == "" {
|
||||
return merrors.InvalidArgument("card funding: gas top-up currency is required")
|
||||
}
|
||||
if feeWalletRef == "" {
|
||||
return merrors.InvalidArgument("card funding: fee wallet ref is required for gas top-up")
|
||||
}
|
||||
topUpDest := &chainv1.TransferDestination{
|
||||
Destination: &chainv1.TransferDestination_ManagedWalletRef{ManagedWalletRef: sourceWalletRef},
|
||||
}
|
||||
topUpFee, err = s.estimateTransferNetworkFee(ctx, feeWalletRef, topUpDest, topUpMoney)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
plan := ensureExecutionPlan(payment)
|
||||
var gasStep *model.ExecutionStep
|
||||
if topUpMoney != nil && topUpPositive {
|
||||
gasStep = ensureExecutionStep(plan, stepCodeGasTopUp)
|
||||
gasStep.Description = "Top up native gas from fee wallet"
|
||||
gasStep.Amount = cloneMoney(topUpMoney)
|
||||
gasStep.NetworkFee = cloneMoney(topUpFee)
|
||||
gasStep.SourceWalletRef = feeWalletRef
|
||||
gasStep.DestinationRef = sourceWalletRef
|
||||
}
|
||||
|
||||
fundStep := ensureExecutionStep(plan, stepCodeFundingTransfer)
|
||||
fundStep.Description = "Transfer payout amount to card funding wallet"
|
||||
fundStep.Amount = cloneMoney(amount)
|
||||
fundStep.NetworkFee = cloneMoney(fundingFee)
|
||||
fundStep.SourceWalletRef = sourceWalletRef
|
||||
fundStep.DestinationRef = fundingAddress
|
||||
|
||||
cardStep := ensureExecutionStep(plan, stepCodeCardPayout)
|
||||
cardStep.Description = "Submit card payout"
|
||||
cardStep.Amount = cloneMoney(payoutAmount)
|
||||
if card := intent.Destination.Card; card != nil {
|
||||
if masked := strings.TrimSpace(card.MaskedPan); masked != "" {
|
||||
cardStep.DestinationRef = masked
|
||||
}
|
||||
}
|
||||
|
||||
if feeRequired {
|
||||
step := ensureExecutionStep(plan, stepCodeFeeTransfer)
|
||||
step.Description = "Transfer fee to fee wallet"
|
||||
step.Amount = cloneMoney(feeMoney)
|
||||
step.NetworkFee = cloneMoney(feeTransferFee)
|
||||
step.SourceWalletRef = sourceWalletRef
|
||||
step.DestinationRef = feeWalletRef
|
||||
}
|
||||
|
||||
updateExecutionPlanTotalNetworkFee(plan)
|
||||
|
||||
exec := payment.Execution
|
||||
if exec == nil {
|
||||
exec = &model.ExecutionRefs{}
|
||||
}
|
||||
|
||||
if topUpMoney != nil && topUpPositive {
|
||||
ensureResp, gasErr := s.deps.gateway.client.EnsureGasTopUp(ctx, &chainv1.EnsureGasTopUpRequest{
|
||||
IdempotencyKey: payment.IdempotencyKey + ":card:gas",
|
||||
OrganizationRef: payment.OrganizationRef.Hex(),
|
||||
SourceWalletRef: feeWalletRef,
|
||||
TargetWalletRef: sourceWalletRef,
|
||||
EstimatedTotalFee: estimatedTotalFee,
|
||||
Metadata: cloneMetadata(payment.Metadata),
|
||||
ClientReference: payment.PaymentRef,
|
||||
})
|
||||
if gasErr != nil {
|
||||
s.logger.Warn("card gas top-up transfer failed", zap.Error(gasErr), zap.String("payment_ref", payment.PaymentRef))
|
||||
return gasErr
|
||||
}
|
||||
if gasStep != nil {
|
||||
actual := (*moneyv1.Money)(nil)
|
||||
if ensureResp != nil {
|
||||
actual = ensureResp.GetTopupAmount()
|
||||
if transfer := ensureResp.GetTransfer(); transfer != nil {
|
||||
gasStep.TransferRef = strings.TrimSpace(transfer.GetTransferRef())
|
||||
}
|
||||
}
|
||||
actualPositive := false
|
||||
if actual != nil && strings.TrimSpace(actual.GetAmount()) != "" {
|
||||
actualDec, err := decimalFromMoney(actual)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
actualPositive = actualDec.IsPositive()
|
||||
}
|
||||
if actual != nil && actualPositive {
|
||||
gasStep.Amount = cloneMoney(actual)
|
||||
if strings.TrimSpace(actual.GetCurrency()) == "" {
|
||||
return merrors.InvalidArgument("card funding: gas top-up currency is required")
|
||||
}
|
||||
topUpDest := &chainv1.TransferDestination{
|
||||
Destination: &chainv1.TransferDestination_ManagedWalletRef{ManagedWalletRef: sourceWalletRef},
|
||||
}
|
||||
topUpFee, err = s.estimateTransferNetworkFee(ctx, feeWalletRef, topUpDest, actual)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
gasStep.NetworkFee = cloneMoney(topUpFee)
|
||||
} else {
|
||||
gasStep.Amount = nil
|
||||
gasStep.NetworkFee = nil
|
||||
}
|
||||
}
|
||||
if gasStep != nil {
|
||||
s.logger.Info("card gas top-up transfer submitted", zap.String("payment_ref", payment.PaymentRef), zap.String("transfer_ref", gasStep.TransferRef))
|
||||
}
|
||||
updateExecutionPlanTotalNetworkFee(plan)
|
||||
}
|
||||
|
||||
// Transfer payout amount to funding wallet.
|
||||
fundReq := &chainv1.SubmitTransferRequest{
|
||||
IdempotencyKey: payment.IdempotencyKey + ":card:fund",
|
||||
OrganizationRef: payment.OrganizationRef.Hex(),
|
||||
SourceWalletRef: sourceWalletRef,
|
||||
Destination: &chainv1.TransferDestination{
|
||||
Destination: &chainv1.TransferDestination_ExternalAddress{ExternalAddress: fundingAddress},
|
||||
},
|
||||
Amount: amount,
|
||||
Metadata: cloneMetadata(payment.Metadata),
|
||||
ClientReference: payment.PaymentRef,
|
||||
}
|
||||
fundResp, err := s.deps.gateway.client.SubmitTransfer(ctx, fundReq)
|
||||
if err != nil {
|
||||
s.logger.Warn("card funding transfer failed", zap.Error(err), zap.String("payment_ref", payment.PaymentRef))
|
||||
return err
|
||||
}
|
||||
if fundResp != nil && fundResp.GetTransfer() != nil {
|
||||
exec.ChainTransferRef = strings.TrimSpace(fundResp.GetTransfer().GetTransferRef())
|
||||
fundStep.TransferRef = exec.ChainTransferRef
|
||||
}
|
||||
s.logger.Info("card funding transfer submitted", zap.String("payment_ref", payment.PaymentRef), zap.String("transfer_ref", exec.ChainTransferRef))
|
||||
|
||||
payment.Execution = exec
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) submitCardPayout(ctx context.Context, payment *model.Payment) error {
|
||||
if payment == nil {
|
||||
return merrors.InvalidArgument("payment is required")
|
||||
}
|
||||
intent := payment.Intent
|
||||
card := intent.Destination.Card
|
||||
if card == nil {
|
||||
return merrors.InvalidArgument("card payout: card endpoint is required")
|
||||
}
|
||||
amount, err := cardPayoutAmount(payment)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
amtDec, err := decimalFromMoney(amount)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
minor := amtDec.Mul(decimal.NewFromInt(100)).IntPart()
|
||||
|
||||
payoutID := payment.PaymentRef
|
||||
currency := strings.TrimSpace(amount.GetCurrency())
|
||||
holder := strings.TrimSpace(card.Cardholder)
|
||||
meta := cloneMetadata(payment.Metadata)
|
||||
customer := intent.Customer
|
||||
customerID := ""
|
||||
customerFirstName := ""
|
||||
customerMiddleName := ""
|
||||
customerLastName := ""
|
||||
customerIP := ""
|
||||
customerZip := ""
|
||||
customerCountry := ""
|
||||
customerState := ""
|
||||
customerCity := ""
|
||||
customerAddress := ""
|
||||
if customer != nil {
|
||||
customerID = strings.TrimSpace(customer.ID)
|
||||
customerFirstName = strings.TrimSpace(customer.FirstName)
|
||||
customerMiddleName = strings.TrimSpace(customer.MiddleName)
|
||||
customerLastName = strings.TrimSpace(customer.LastName)
|
||||
customerIP = strings.TrimSpace(customer.IP)
|
||||
customerZip = strings.TrimSpace(customer.Zip)
|
||||
customerCountry = strings.TrimSpace(customer.Country)
|
||||
customerState = strings.TrimSpace(customer.State)
|
||||
customerCity = strings.TrimSpace(customer.City)
|
||||
customerAddress = strings.TrimSpace(customer.Address)
|
||||
}
|
||||
if customerFirstName == "" {
|
||||
customerFirstName = strings.TrimSpace(card.Cardholder)
|
||||
}
|
||||
if customerLastName == "" {
|
||||
customerLastName = strings.TrimSpace(card.CardholderSurname)
|
||||
}
|
||||
if customerID == "" {
|
||||
return merrors.InvalidArgument("card payout: customer id is required")
|
||||
}
|
||||
if customerFirstName == "" {
|
||||
return merrors.InvalidArgument("card payout: customer first name is required")
|
||||
}
|
||||
if customerLastName == "" {
|
||||
return merrors.InvalidArgument("card payout: customer last name is required")
|
||||
}
|
||||
if customerIP == "" {
|
||||
return merrors.InvalidArgument("card payout: customer ip is required")
|
||||
}
|
||||
|
||||
var (
|
||||
state *mntxv1.CardPayoutState
|
||||
)
|
||||
|
||||
if token := strings.TrimSpace(card.Token); token != "" {
|
||||
req := &mntxv1.CardTokenPayoutRequest{
|
||||
PayoutId: payoutID,
|
||||
CustomerId: customerID,
|
||||
CustomerFirstName: customerFirstName,
|
||||
CustomerMiddleName: customerMiddleName,
|
||||
CustomerLastName: customerLastName,
|
||||
CustomerIp: customerIP,
|
||||
CustomerZip: customerZip,
|
||||
CustomerCountry: customerCountry,
|
||||
CustomerState: customerState,
|
||||
CustomerCity: customerCity,
|
||||
CustomerAddress: customerAddress,
|
||||
AmountMinor: minor,
|
||||
Currency: currency,
|
||||
CardToken: token,
|
||||
CardHolder: holder,
|
||||
MaskedPan: strings.TrimSpace(card.MaskedPan),
|
||||
Metadata: meta,
|
||||
}
|
||||
resp, err := s.deps.mntx.client.CreateCardTokenPayout(ctx, req)
|
||||
if err != nil {
|
||||
s.logger.Warn("card token payout failed", zap.Error(err), zap.String("payment_ref", payment.PaymentRef))
|
||||
return err
|
||||
}
|
||||
state = resp.GetPayout()
|
||||
} else if pan := strings.TrimSpace(card.Pan); pan != "" {
|
||||
req := &mntxv1.CardPayoutRequest{
|
||||
PayoutId: payoutID,
|
||||
CustomerId: customerID,
|
||||
CustomerFirstName: customerFirstName,
|
||||
CustomerMiddleName: customerMiddleName,
|
||||
CustomerLastName: customerLastName,
|
||||
CustomerIp: customerIP,
|
||||
CustomerZip: customerZip,
|
||||
CustomerCountry: customerCountry,
|
||||
CustomerState: customerState,
|
||||
CustomerCity: customerCity,
|
||||
CustomerAddress: customerAddress,
|
||||
AmountMinor: minor,
|
||||
Currency: currency,
|
||||
CardPan: pan,
|
||||
CardExpYear: card.ExpYear,
|
||||
CardExpMonth: card.ExpMonth,
|
||||
CardHolder: holder,
|
||||
Metadata: meta,
|
||||
}
|
||||
resp, err := s.deps.mntx.client.CreateCardPayout(ctx, req)
|
||||
if err != nil {
|
||||
s.logger.Warn("card payout failed", zap.Error(err), zap.String("payment_ref", payment.PaymentRef))
|
||||
return err
|
||||
}
|
||||
state = resp.GetPayout()
|
||||
} else {
|
||||
return merrors.InvalidArgument("card payout: either token or pan must be provided")
|
||||
}
|
||||
|
||||
if state == nil {
|
||||
return merrors.Internal("card payout: missing payout state")
|
||||
}
|
||||
recordCardPayoutState(payment, state)
|
||||
exec := payment.Execution
|
||||
if exec == nil {
|
||||
exec = &model.ExecutionRefs{}
|
||||
}
|
||||
if exec.CardPayoutRef == "" {
|
||||
exec.CardPayoutRef = strings.TrimSpace(state.GetPayoutId())
|
||||
}
|
||||
payment.Execution = exec
|
||||
|
||||
plan := ensureExecutionPlan(payment)
|
||||
if plan != nil {
|
||||
step := ensureExecutionStep(plan, stepCodeCardPayout)
|
||||
step.Description = "Submit card payout"
|
||||
step.Amount = cloneMoney(amount)
|
||||
if masked := strings.TrimSpace(card.MaskedPan); masked != "" {
|
||||
step.DestinationRef = masked
|
||||
}
|
||||
if exec.CardPayoutRef != "" {
|
||||
step.TransferRef = exec.CardPayoutRef
|
||||
}
|
||||
updateExecutionPlanTotalNetworkFee(plan)
|
||||
}
|
||||
|
||||
feeMoney := (*moneyv1.Money)(nil)
|
||||
if payment.LastQuote != nil {
|
||||
feeMoney = payment.LastQuote.ExpectedFeeTotal
|
||||
}
|
||||
if feeMoney != nil && strings.TrimSpace(feeMoney.GetAmount()) != "" {
|
||||
if strings.TrimSpace(feeMoney.GetCurrency()) == "" {
|
||||
return merrors.InvalidArgument("card payout: fee currency is required")
|
||||
}
|
||||
feeDecimal, err := decimalFromMoney(feeMoney)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if feeDecimal.IsPositive() {
|
||||
if !s.deps.gateway.available() {
|
||||
s.logger.Warn("card fee aborted: chain gateway unavailable")
|
||||
return merrors.InvalidArgument("card payout: chain gateway unavailable")
|
||||
}
|
||||
sourceWallet := intent.Source.ManagedWallet
|
||||
if sourceWallet == nil || strings.TrimSpace(sourceWallet.ManagedWalletRef) == "" {
|
||||
return merrors.InvalidArgument("card payout: source managed wallet is required")
|
||||
}
|
||||
route, err := s.cardRoute(defaultCardGateway)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
feeWalletRef := strings.TrimSpace(route.FeeWalletRef)
|
||||
if feeWalletRef == "" {
|
||||
return merrors.InvalidArgument("card payout: fee wallet ref is required when fee exists")
|
||||
}
|
||||
feeReq := &chainv1.SubmitTransferRequest{
|
||||
IdempotencyKey: payment.IdempotencyKey + ":card:fee",
|
||||
OrganizationRef: payment.OrganizationRef.Hex(),
|
||||
SourceWalletRef: strings.TrimSpace(sourceWallet.ManagedWalletRef),
|
||||
Destination: &chainv1.TransferDestination{
|
||||
Destination: &chainv1.TransferDestination_ManagedWalletRef{ManagedWalletRef: feeWalletRef},
|
||||
},
|
||||
Amount: feeMoney,
|
||||
Metadata: cloneMetadata(payment.Metadata),
|
||||
ClientReference: payment.PaymentRef,
|
||||
}
|
||||
feeResp, feeErr := s.deps.gateway.client.SubmitTransfer(ctx, feeReq)
|
||||
if feeErr != nil {
|
||||
s.logger.Warn("card fee transfer failed", zap.Error(feeErr), zap.String("payment_ref", payment.PaymentRef))
|
||||
return feeErr
|
||||
}
|
||||
if feeResp != nil && feeResp.GetTransfer() != nil {
|
||||
exec.FeeTransferRef = strings.TrimSpace(feeResp.GetTransfer().GetTransferRef())
|
||||
}
|
||||
s.logger.Info("card fee transfer submitted", zap.String("payment_ref", payment.PaymentRef), zap.String("transfer_ref", exec.FeeTransferRef))
|
||||
|
||||
if plan != nil {
|
||||
step := ensureExecutionStep(plan, stepCodeFeeTransfer)
|
||||
step.Description = "Transfer fee to fee wallet"
|
||||
step.Amount = cloneMoney(feeMoney)
|
||||
step.SourceWalletRef = strings.TrimSpace(sourceWallet.ManagedWalletRef)
|
||||
step.DestinationRef = feeWalletRef
|
||||
step.TransferRef = exec.FeeTransferRef
|
||||
updateExecutionPlanTotalNetworkFee(plan)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
s.logger.Info("card payout submitted", zap.String("payment_ref", payment.PaymentRef), zap.String("payout_id", exec.CardPayoutRef))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func recordCardPayoutState(payment *model.Payment, state *mntxv1.CardPayoutState) {
|
||||
if payment == nil || state == nil {
|
||||
return
|
||||
}
|
||||
if payment.CardPayout == nil {
|
||||
payment.CardPayout = &model.CardPayout{}
|
||||
}
|
||||
payment.CardPayout.PayoutRef = strings.TrimSpace(state.GetPayoutId())
|
||||
payment.CardPayout.ProviderPaymentID = strings.TrimSpace(state.GetProviderPaymentId())
|
||||
payment.CardPayout.Status = state.GetStatus().String()
|
||||
payment.CardPayout.FailureReason = strings.TrimSpace(state.GetProviderMessage())
|
||||
payment.CardPayout.ProviderCode = strings.TrimSpace(state.GetProviderCode())
|
||||
if payment.CardPayout.CardCountry == "" && payment.Intent.Destination.Card != nil {
|
||||
payment.CardPayout.CardCountry = strings.TrimSpace(payment.Intent.Destination.Card.Country)
|
||||
}
|
||||
if payment.CardPayout.MaskedPan == "" && payment.Intent.Destination.Card != nil {
|
||||
payment.CardPayout.MaskedPan = strings.TrimSpace(payment.Intent.Destination.Card.MaskedPan)
|
||||
}
|
||||
payment.CardPayout.GatewayReference = strings.TrimSpace(state.GetPayoutId())
|
||||
}
|
||||
|
||||
func applyCardPayoutUpdate(payment *model.Payment, payout *mntxv1.CardPayoutState) {
|
||||
if payment == nil || payout == nil {
|
||||
return
|
||||
}
|
||||
recordCardPayoutState(payment, payout)
|
||||
|
||||
if payment.Execution == nil {
|
||||
payment.Execution = &model.ExecutionRefs{}
|
||||
}
|
||||
if payment.Execution.CardPayoutRef == "" {
|
||||
payment.Execution.CardPayoutRef = strings.TrimSpace(payout.GetPayoutId())
|
||||
}
|
||||
|
||||
payment.State = mapMntxStatusToState(payout.GetStatus())
|
||||
switch payout.GetStatus() {
|
||||
case mntxv1.PayoutStatus_PAYOUT_STATUS_PROCESSED:
|
||||
payment.FailureCode = model.PaymentFailureCodeUnspecified
|
||||
payment.FailureReason = ""
|
||||
case mntxv1.PayoutStatus_PAYOUT_STATUS_FAILED:
|
||||
payment.FailureCode = model.PaymentFailureCodePolicy
|
||||
payment.FailureReason = strings.TrimSpace(payout.GetProviderMessage())
|
||||
default:
|
||||
// leave as-is for pending/unspecified
|
||||
}
|
||||
}
|
||||
|
||||
func cardPayoutAmount(payment *model.Payment) (*moneyv1.Money, error) {
|
||||
if payment == nil {
|
||||
return nil, merrors.InvalidArgument("payment is required")
|
||||
}
|
||||
amount := cloneMoney(payment.Intent.Amount)
|
||||
if payment.LastQuote != nil {
|
||||
settlement := payment.LastQuote.ExpectedSettlementAmount
|
||||
if settlement != nil && strings.TrimSpace(settlement.GetAmount()) != "" && strings.TrimSpace(settlement.GetCurrency()) != "" {
|
||||
amount = cloneMoney(settlement)
|
||||
}
|
||||
}
|
||||
if amount == nil || strings.TrimSpace(amount.GetAmount()) == "" || strings.TrimSpace(amount.GetCurrency()) == "" {
|
||||
return nil, merrors.InvalidArgument("card payout: amount is required")
|
||||
}
|
||||
return amount, nil
|
||||
}
|
||||
|
||||
func (s *Service) estimateTransferNetworkFee(ctx context.Context, sourceWalletRef string, destination *chainv1.TransferDestination, amount *moneyv1.Money) (*moneyv1.Money, error) {
|
||||
if !s.deps.gateway.available() {
|
||||
return nil, merrors.InvalidArgument("chain gateway unavailable")
|
||||
}
|
||||
sourceWalletRef = strings.TrimSpace(sourceWalletRef)
|
||||
if sourceWalletRef == "" {
|
||||
return nil, merrors.InvalidArgument("source wallet ref is required")
|
||||
}
|
||||
if amount == nil || strings.TrimSpace(amount.GetAmount()) == "" || strings.TrimSpace(amount.GetCurrency()) == "" {
|
||||
return nil, merrors.InvalidArgument("amount is required")
|
||||
}
|
||||
|
||||
resp, err := s.deps.gateway.client.EstimateTransferFee(ctx, &chainv1.EstimateTransferFeeRequest{
|
||||
SourceWalletRef: sourceWalletRef,
|
||||
Destination: destination,
|
||||
Amount: cloneMoney(amount),
|
||||
})
|
||||
if err != nil {
|
||||
s.logger.Warn("chain gateway fee estimation failed", zap.Error(err), zap.String("source_wallet_ref", sourceWalletRef))
|
||||
return nil, merrors.Internal("chain_gateway_fee_estimation_failed")
|
||||
}
|
||||
if resp == nil {
|
||||
s.logger.Warn("chain gateway fee estimation returned empty response", zap.String("source_wallet_ref", sourceWalletRef))
|
||||
return nil, merrors.Internal("chain_gateway_fee_estimation_failed")
|
||||
}
|
||||
fee := resp.GetNetworkFee()
|
||||
if fee == nil || strings.TrimSpace(fee.GetAmount()) == "" || strings.TrimSpace(fee.GetCurrency()) == "" {
|
||||
s.logger.Warn("chain gateway fee estimation missing network fee", zap.String("source_wallet_ref", sourceWalletRef))
|
||||
return nil, merrors.Internal("chain_gateway_fee_estimation_failed")
|
||||
}
|
||||
return cloneMoney(fee), nil
|
||||
}
|
||||
|
||||
func sumNetworkFees(fees ...*moneyv1.Money) (decimal.Decimal, string, error) {
|
||||
total := decimal.Zero
|
||||
currency := ""
|
||||
for _, fee := range fees {
|
||||
if fee == nil {
|
||||
continue
|
||||
}
|
||||
amount := strings.TrimSpace(fee.GetAmount())
|
||||
feeCurrency := strings.TrimSpace(fee.GetCurrency())
|
||||
if amount == "" || feeCurrency == "" {
|
||||
return decimal.Zero, "", merrors.InvalidArgument("network fee is required")
|
||||
}
|
||||
value, err := decimalFromMoney(fee)
|
||||
if err != nil {
|
||||
return decimal.Zero, "", err
|
||||
}
|
||||
if currency == "" {
|
||||
currency = feeCurrency
|
||||
} else if !strings.EqualFold(currency, feeCurrency) {
|
||||
return decimal.Zero, "", merrors.InvalidArgument("network fee currency mismatch")
|
||||
}
|
||||
total = total.Add(value)
|
||||
}
|
||||
return total, currency, nil
|
||||
}
|
||||
|
||||
func ensureExecutionPlan(payment *model.Payment) *model.ExecutionPlan {
|
||||
if payment == nil {
|
||||
return nil
|
||||
}
|
||||
if payment.ExecutionPlan == nil {
|
||||
payment.ExecutionPlan = &model.ExecutionPlan{}
|
||||
}
|
||||
return payment.ExecutionPlan
|
||||
}
|
||||
|
||||
func ensureExecutionStep(plan *model.ExecutionPlan, code string) *model.ExecutionStep {
|
||||
if plan == nil {
|
||||
return nil
|
||||
}
|
||||
code = strings.TrimSpace(code)
|
||||
if code == "" {
|
||||
return nil
|
||||
}
|
||||
for _, step := range plan.Steps {
|
||||
if step == nil {
|
||||
continue
|
||||
}
|
||||
if strings.EqualFold(step.Code, code) {
|
||||
if step.Code == "" {
|
||||
step.Code = code
|
||||
}
|
||||
return step
|
||||
}
|
||||
}
|
||||
step := &model.ExecutionStep{Code: code}
|
||||
plan.Steps = append(plan.Steps, step)
|
||||
return step
|
||||
}
|
||||
|
||||
func updateExecutionPlanTotalNetworkFee(plan *model.ExecutionPlan) {
|
||||
if plan == nil {
|
||||
return
|
||||
}
|
||||
total := decimal.Zero
|
||||
currency := ""
|
||||
hasFee := false
|
||||
for _, step := range plan.Steps {
|
||||
if step == nil || step.NetworkFee == nil {
|
||||
continue
|
||||
}
|
||||
fee := step.NetworkFee
|
||||
if strings.TrimSpace(fee.GetAmount()) == "" || strings.TrimSpace(fee.GetCurrency()) == "" {
|
||||
continue
|
||||
}
|
||||
if currency == "" {
|
||||
currency = strings.TrimSpace(fee.GetCurrency())
|
||||
} else if !strings.EqualFold(currency, fee.GetCurrency()) {
|
||||
continue
|
||||
}
|
||||
value, err := decimalFromMoney(fee)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
total = total.Add(value)
|
||||
hasFee = true
|
||||
}
|
||||
if !hasFee || currency == "" {
|
||||
plan.TotalNetworkFee = nil
|
||||
return
|
||||
}
|
||||
plan.TotalNetworkFee = makeMoney(currency, total)
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package orchestrator
|
||||
|
||||
const (
|
||||
defaultCardGateway = "monetix"
|
||||
|
||||
stepCodeGasTopUp = "gas_top_up"
|
||||
stepCodeFundingTransfer = "funding_transfer"
|
||||
stepCodeCardPayout = "card_payout"
|
||||
stepCodeFeeTransfer = "fee_transfer"
|
||||
)
|
||||
@@ -0,0 +1,353 @@
|
||||
package orchestrator
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/tech/sendico/payments/orchestrator/storage/model"
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
paymenttypes "github.com/tech/sendico/pkg/payments/types"
|
||||
moneyv1 "github.com/tech/sendico/pkg/proto/common/money/v1"
|
||||
chainv1 "github.com/tech/sendico/pkg/proto/gateway/chain/v1"
|
||||
orchestratorv1 "github.com/tech/sendico/pkg/proto/payments/orchestrator/v1"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func (s *Service) submitCardFundingTransfers(ctx context.Context, payment *model.Payment, quote *orchestratorv1.PaymentQuote) error {
|
||||
if payment == nil {
|
||||
return merrors.InvalidArgument("payment is required")
|
||||
}
|
||||
intent := payment.Intent
|
||||
source := intent.Source.ManagedWallet
|
||||
if source == nil || strings.TrimSpace(source.ManagedWalletRef) == "" {
|
||||
return merrors.InvalidArgument("card funding: source managed wallet is required")
|
||||
}
|
||||
if !s.deps.gateway.available() {
|
||||
s.logger.Warn("card funding aborted: chain gateway unavailable")
|
||||
return merrors.InvalidArgument("card funding: chain gateway unavailable")
|
||||
}
|
||||
|
||||
route, err := s.cardRoute(defaultCardGateway)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sourceWalletRef := strings.TrimSpace(source.ManagedWalletRef)
|
||||
fundingAddress := strings.TrimSpace(route.FundingAddress)
|
||||
feeWalletRef := strings.TrimSpace(route.FeeWalletRef)
|
||||
|
||||
intentAmount := cloneMoney(intent.Amount)
|
||||
if intentAmount == nil || strings.TrimSpace(intentAmount.GetAmount()) == "" || strings.TrimSpace(intentAmount.GetCurrency()) == "" {
|
||||
return merrors.InvalidArgument("card funding: amount is required")
|
||||
}
|
||||
intentAmountProto := protoMoney(intentAmount)
|
||||
|
||||
payoutAmount, err := cardPayoutAmount(payment)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var feeAmount *paymenttypes.Money
|
||||
if quote != nil {
|
||||
feeAmount = moneyFromProto(quote.GetExpectedFeeTotal())
|
||||
}
|
||||
if feeAmount == nil && payment.LastQuote != nil {
|
||||
feeAmount = cloneMoney(payment.LastQuote.ExpectedFeeTotal)
|
||||
}
|
||||
feeDecimal := decimal.Zero
|
||||
if feeAmount != nil && strings.TrimSpace(feeAmount.GetAmount()) != "" {
|
||||
if strings.TrimSpace(feeAmount.GetCurrency()) == "" {
|
||||
return merrors.InvalidArgument("card funding: fee currency is required")
|
||||
}
|
||||
feeDecimal, err = decimalFromMoney(feeAmount)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
feeRequired := feeDecimal.IsPositive()
|
||||
feeAmountProto := protoMoney(feeAmount)
|
||||
|
||||
fundingDest := &chainv1.TransferDestination{
|
||||
Destination: &chainv1.TransferDestination_ExternalAddress{ExternalAddress: fundingAddress},
|
||||
}
|
||||
fundingFee, err := s.estimateTransferNetworkFee(ctx, sourceWalletRef, fundingDest, intentAmountProto)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var feeTransferFee *moneyv1.Money
|
||||
if feeRequired {
|
||||
if feeWalletRef == "" {
|
||||
return merrors.InvalidArgument("card funding: fee wallet ref is required when fee exists")
|
||||
}
|
||||
feeDest := &chainv1.TransferDestination{
|
||||
Destination: &chainv1.TransferDestination_ManagedWalletRef{ManagedWalletRef: feeWalletRef},
|
||||
}
|
||||
feeTransferFee, err = s.estimateTransferNetworkFee(ctx, sourceWalletRef, feeDest, feeAmountProto)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
totalFee, gasCurrency, err := sumNetworkFees(fundingFee, feeTransferFee)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var estimatedTotalFee *moneyv1.Money
|
||||
if gasCurrency != "" && !totalFee.IsNegative() {
|
||||
estimatedTotalFee = makeMoney(gasCurrency, totalFee)
|
||||
}
|
||||
|
||||
var topUpMoney *moneyv1.Money
|
||||
var topUpFee *moneyv1.Money
|
||||
topUpPositive := false
|
||||
if estimatedTotalFee != nil {
|
||||
computeResp, err := s.deps.gateway.client.ComputeGasTopUp(ctx, &chainv1.ComputeGasTopUpRequest{
|
||||
WalletRef: sourceWalletRef,
|
||||
EstimatedTotalFee: estimatedTotalFee,
|
||||
})
|
||||
if err != nil {
|
||||
s.logger.Warn("card funding gas top-up compute failed", zap.Error(err), zap.String("payment_ref", payment.PaymentRef))
|
||||
return err
|
||||
}
|
||||
if computeResp != nil {
|
||||
topUpMoney = computeResp.GetTopupAmount()
|
||||
}
|
||||
if topUpMoney != nil && strings.TrimSpace(topUpMoney.GetAmount()) != "" {
|
||||
amountDec, err := decimalFromMoney(topUpMoney)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
topUpPositive = amountDec.IsPositive()
|
||||
}
|
||||
if topUpMoney != nil && topUpPositive {
|
||||
if strings.TrimSpace(topUpMoney.GetCurrency()) == "" {
|
||||
return merrors.InvalidArgument("card funding: gas top-up currency is required")
|
||||
}
|
||||
if feeWalletRef == "" {
|
||||
return merrors.InvalidArgument("card funding: fee wallet ref is required for gas top-up")
|
||||
}
|
||||
topUpDest := &chainv1.TransferDestination{
|
||||
Destination: &chainv1.TransferDestination_ManagedWalletRef{ManagedWalletRef: sourceWalletRef},
|
||||
}
|
||||
topUpFee, err = s.estimateTransferNetworkFee(ctx, feeWalletRef, topUpDest, topUpMoney)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
plan := ensureExecutionPlan(payment)
|
||||
var gasStep *model.ExecutionStep
|
||||
var feeStep *model.ExecutionStep
|
||||
if topUpMoney != nil && topUpPositive {
|
||||
gasStep = ensureExecutionStep(plan, stepCodeGasTopUp)
|
||||
setExecutionStepRole(gasStep, executionStepRoleSource)
|
||||
setExecutionStepStatus(gasStep, executionStepStatusPlanned)
|
||||
gasStep.Description = "Top up native gas from fee wallet"
|
||||
gasStep.Amount = moneyFromProto(topUpMoney)
|
||||
gasStep.NetworkFee = moneyFromProto(topUpFee)
|
||||
gasStep.SourceWalletRef = feeWalletRef
|
||||
gasStep.DestinationRef = sourceWalletRef
|
||||
}
|
||||
|
||||
fundStep := ensureExecutionStep(plan, stepCodeFundingTransfer)
|
||||
setExecutionStepRole(fundStep, executionStepRoleSource)
|
||||
setExecutionStepStatus(fundStep, executionStepStatusPlanned)
|
||||
fundStep.Description = "Transfer payout amount to card funding wallet"
|
||||
fundStep.Amount = cloneMoney(intentAmount)
|
||||
fundStep.NetworkFee = moneyFromProto(fundingFee)
|
||||
fundStep.SourceWalletRef = sourceWalletRef
|
||||
fundStep.DestinationRef = fundingAddress
|
||||
|
||||
if feeRequired {
|
||||
feeStep = ensureExecutionStep(plan, stepCodeFeeTransfer)
|
||||
setExecutionStepRole(feeStep, executionStepRoleSource)
|
||||
setExecutionStepStatus(feeStep, executionStepStatusPlanned)
|
||||
feeStep.Description = "Transfer fee to fee wallet"
|
||||
feeStep.Amount = cloneMoney(feeAmount)
|
||||
feeStep.NetworkFee = moneyFromProto(feeTransferFee)
|
||||
feeStep.SourceWalletRef = sourceWalletRef
|
||||
feeStep.DestinationRef = feeWalletRef
|
||||
}
|
||||
|
||||
cardStep := ensureExecutionStep(plan, stepCodeCardPayout)
|
||||
setExecutionStepRole(cardStep, executionStepRoleConsumer)
|
||||
setExecutionStepStatus(cardStep, executionStepStatusPlanned)
|
||||
cardStep.Description = "Submit card payout"
|
||||
cardStep.Amount = cloneMoney(payoutAmount)
|
||||
if card := intent.Destination.Card; card != nil {
|
||||
if masked := strings.TrimSpace(card.MaskedPan); masked != "" {
|
||||
cardStep.DestinationRef = masked
|
||||
}
|
||||
}
|
||||
|
||||
updateExecutionPlanTotalNetworkFee(plan)
|
||||
|
||||
exec := payment.Execution
|
||||
if exec == nil {
|
||||
exec = &model.ExecutionRefs{}
|
||||
}
|
||||
|
||||
if topUpMoney != nil && topUpPositive {
|
||||
ensureResp, gasErr := s.deps.gateway.client.EnsureGasTopUp(ctx, &chainv1.EnsureGasTopUpRequest{
|
||||
IdempotencyKey: payment.IdempotencyKey + ":card:gas",
|
||||
OrganizationRef: payment.OrganizationRef.Hex(),
|
||||
SourceWalletRef: feeWalletRef,
|
||||
TargetWalletRef: sourceWalletRef,
|
||||
EstimatedTotalFee: estimatedTotalFee,
|
||||
Metadata: cloneMetadata(payment.Metadata),
|
||||
ClientReference: payment.PaymentRef,
|
||||
})
|
||||
if gasErr != nil {
|
||||
s.logger.Warn("card gas top-up transfer failed", zap.Error(gasErr), zap.String("payment_ref", payment.PaymentRef))
|
||||
return gasErr
|
||||
}
|
||||
if gasStep != nil {
|
||||
actual := (*moneyv1.Money)(nil)
|
||||
if ensureResp != nil {
|
||||
actual = ensureResp.GetTopupAmount()
|
||||
if transfer := ensureResp.GetTransfer(); transfer != nil {
|
||||
gasStep.TransferRef = strings.TrimSpace(transfer.GetTransferRef())
|
||||
}
|
||||
}
|
||||
actualPositive := false
|
||||
if actual != nil && strings.TrimSpace(actual.GetAmount()) != "" {
|
||||
actualDec, err := decimalFromMoney(actual)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
actualPositive = actualDec.IsPositive()
|
||||
}
|
||||
if actual != nil && actualPositive {
|
||||
gasStep.Amount = moneyFromProto(actual)
|
||||
if strings.TrimSpace(actual.GetCurrency()) == "" {
|
||||
return merrors.InvalidArgument("card funding: gas top-up currency is required")
|
||||
}
|
||||
topUpDest := &chainv1.TransferDestination{
|
||||
Destination: &chainv1.TransferDestination_ManagedWalletRef{ManagedWalletRef: sourceWalletRef},
|
||||
}
|
||||
topUpFee, err = s.estimateTransferNetworkFee(ctx, feeWalletRef, topUpDest, actual)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
gasStep.NetworkFee = moneyFromProto(topUpFee)
|
||||
setExecutionStepStatus(gasStep, executionStepStatusSubmitted)
|
||||
} else {
|
||||
gasStep.Amount = nil
|
||||
gasStep.NetworkFee = nil
|
||||
gasStep.TransferRef = ""
|
||||
setExecutionStepStatus(gasStep, executionStepStatusSkipped)
|
||||
}
|
||||
}
|
||||
if gasStep != nil {
|
||||
s.logger.Info("card gas top-up transfer submitted", zap.String("payment_ref", payment.PaymentRef), zap.String("transfer_ref", gasStep.TransferRef))
|
||||
}
|
||||
updateExecutionPlanTotalNetworkFee(plan)
|
||||
}
|
||||
|
||||
fundResp, err := s.deps.gateway.client.SubmitTransfer(ctx, &chainv1.SubmitTransferRequest{
|
||||
IdempotencyKey: payment.IdempotencyKey + ":card:fund",
|
||||
OrganizationRef: payment.OrganizationRef.Hex(),
|
||||
SourceWalletRef: sourceWalletRef,
|
||||
Destination: fundingDest,
|
||||
Amount: cloneProtoMoney(intentAmountProto),
|
||||
Metadata: cloneMetadata(payment.Metadata),
|
||||
ClientReference: payment.PaymentRef,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if fundResp != nil && fundResp.GetTransfer() != nil {
|
||||
exec.ChainTransferRef = strings.TrimSpace(fundResp.GetTransfer().GetTransferRef())
|
||||
fundStep.TransferRef = exec.ChainTransferRef
|
||||
}
|
||||
setExecutionStepStatus(fundStep, executionStepStatusSubmitted)
|
||||
updateExecutionPlanTotalNetworkFee(plan)
|
||||
|
||||
if feeRequired {
|
||||
feeResp, err := s.deps.gateway.client.SubmitTransfer(ctx, &chainv1.SubmitTransferRequest{
|
||||
IdempotencyKey: payment.IdempotencyKey + ":card:fee",
|
||||
OrganizationRef: payment.OrganizationRef.Hex(),
|
||||
SourceWalletRef: sourceWalletRef,
|
||||
Destination: &chainv1.TransferDestination{
|
||||
Destination: &chainv1.TransferDestination_ManagedWalletRef{ManagedWalletRef: feeWalletRef},
|
||||
},
|
||||
Amount: cloneProtoMoney(feeAmountProto),
|
||||
Metadata: cloneMetadata(payment.Metadata),
|
||||
ClientReference: payment.PaymentRef,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if feeResp != nil && feeResp.GetTransfer() != nil {
|
||||
exec.FeeTransferRef = strings.TrimSpace(feeResp.GetTransfer().GetTransferRef())
|
||||
feeStep.TransferRef = exec.FeeTransferRef
|
||||
}
|
||||
setExecutionStepStatus(feeStep, executionStepStatusSubmitted)
|
||||
s.logger.Info("card fee transfer submitted", zap.String("payment_ref", payment.PaymentRef), zap.String("transfer_ref", exec.FeeTransferRef))
|
||||
}
|
||||
|
||||
payment.Execution = exec
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) estimateTransferNetworkFee(ctx context.Context, sourceWalletRef string, destination *chainv1.TransferDestination, amount *moneyv1.Money) (*moneyv1.Money, error) {
|
||||
if !s.deps.gateway.available() {
|
||||
return nil, merrors.InvalidArgument("chain gateway unavailable")
|
||||
}
|
||||
sourceWalletRef = strings.TrimSpace(sourceWalletRef)
|
||||
if sourceWalletRef == "" {
|
||||
return nil, merrors.InvalidArgument("source wallet ref is required")
|
||||
}
|
||||
if amount == nil || strings.TrimSpace(amount.GetAmount()) == "" || strings.TrimSpace(amount.GetCurrency()) == "" {
|
||||
return nil, merrors.InvalidArgument("amount is required")
|
||||
}
|
||||
|
||||
resp, err := s.deps.gateway.client.EstimateTransferFee(ctx, &chainv1.EstimateTransferFeeRequest{
|
||||
SourceWalletRef: sourceWalletRef,
|
||||
Destination: destination,
|
||||
Amount: cloneProtoMoney(amount),
|
||||
})
|
||||
if err != nil {
|
||||
s.logger.Warn("chain gateway fee estimation failed", zap.Error(err), zap.String("source_wallet_ref", sourceWalletRef))
|
||||
return nil, merrors.Internal("chain_gateway_fee_estimation_failed")
|
||||
}
|
||||
if resp == nil {
|
||||
s.logger.Warn("chain gateway fee estimation returned empty response", zap.String("source_wallet_ref", sourceWalletRef))
|
||||
return nil, merrors.Internal("chain_gateway_fee_estimation_failed")
|
||||
}
|
||||
fee := resp.GetNetworkFee()
|
||||
if fee == nil || strings.TrimSpace(fee.GetAmount()) == "" || strings.TrimSpace(fee.GetCurrency()) == "" {
|
||||
s.logger.Warn("chain gateway fee estimation missing network fee", zap.String("source_wallet_ref", sourceWalletRef))
|
||||
return nil, merrors.Internal("chain_gateway_fee_estimation_failed")
|
||||
}
|
||||
return cloneProtoMoney(fee), nil
|
||||
}
|
||||
|
||||
func sumNetworkFees(fees ...*moneyv1.Money) (decimal.Decimal, string, error) {
|
||||
total := decimal.Zero
|
||||
currency := ""
|
||||
for _, fee := range fees {
|
||||
if fee == nil {
|
||||
continue
|
||||
}
|
||||
amount := strings.TrimSpace(fee.GetAmount())
|
||||
feeCurrency := strings.TrimSpace(fee.GetCurrency())
|
||||
if amount == "" || feeCurrency == "" {
|
||||
return decimal.Zero, "", merrors.InvalidArgument("network fee is required")
|
||||
}
|
||||
value, err := decimalFromMoney(fee)
|
||||
if err != nil {
|
||||
return decimal.Zero, "", err
|
||||
}
|
||||
if currency == "" {
|
||||
currency = feeCurrency
|
||||
} else if !strings.EqualFold(currency, feeCurrency) {
|
||||
return decimal.Zero, "", merrors.InvalidArgument("network fee currency mismatch")
|
||||
}
|
||||
total = total.Add(value)
|
||||
}
|
||||
return total, currency, nil
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package orchestrator
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/tech/sendico/payments/orchestrator/storage/model"
|
||||
paymenttypes "github.com/tech/sendico/pkg/payments/types"
|
||||
)
|
||||
|
||||
func ensureExecutionPlan(payment *model.Payment) *model.ExecutionPlan {
|
||||
if payment == nil {
|
||||
return nil
|
||||
}
|
||||
if payment.ExecutionPlan == nil {
|
||||
payment.ExecutionPlan = &model.ExecutionPlan{}
|
||||
}
|
||||
return payment.ExecutionPlan
|
||||
}
|
||||
|
||||
func ensureExecutionStep(plan *model.ExecutionPlan, code string) *model.ExecutionStep {
|
||||
if plan == nil {
|
||||
return nil
|
||||
}
|
||||
code = strings.TrimSpace(code)
|
||||
if code == "" {
|
||||
return nil
|
||||
}
|
||||
for _, step := range plan.Steps {
|
||||
if step == nil {
|
||||
continue
|
||||
}
|
||||
if strings.EqualFold(step.Code, code) {
|
||||
if step.Code == "" {
|
||||
step.Code = code
|
||||
}
|
||||
return step
|
||||
}
|
||||
}
|
||||
step := &model.ExecutionStep{Code: code}
|
||||
plan.Steps = append(plan.Steps, step)
|
||||
return step
|
||||
}
|
||||
|
||||
func updateExecutionPlanTotalNetworkFee(plan *model.ExecutionPlan) {
|
||||
if plan == nil {
|
||||
return
|
||||
}
|
||||
total := decimal.Zero
|
||||
currency := ""
|
||||
hasFee := false
|
||||
for _, step := range plan.Steps {
|
||||
if step == nil || step.NetworkFee == nil {
|
||||
continue
|
||||
}
|
||||
fee := step.NetworkFee
|
||||
if strings.TrimSpace(fee.GetAmount()) == "" || strings.TrimSpace(fee.GetCurrency()) == "" {
|
||||
continue
|
||||
}
|
||||
if currency == "" {
|
||||
currency = strings.TrimSpace(fee.GetCurrency())
|
||||
} else if !strings.EqualFold(currency, fee.GetCurrency()) {
|
||||
continue
|
||||
}
|
||||
value, err := decimalFromMoney(fee)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
total = total.Add(value)
|
||||
hasFee = true
|
||||
}
|
||||
if !hasFee || currency == "" {
|
||||
plan.TotalNetworkFee = nil
|
||||
return
|
||||
}
|
||||
plan.TotalNetworkFee = &paymenttypes.Money{
|
||||
Currency: currency,
|
||||
Amount: total.String(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package orchestrator
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func (s *Service) cardRoute(gateway string) (CardGatewayRoute, error) {
|
||||
if len(s.deps.cardRoutes) == 0 {
|
||||
s.logger.Warn("card routing not configured", zap.String("gateway", gateway))
|
||||
return CardGatewayRoute{}, merrors.InvalidArgument("card routing not configured")
|
||||
}
|
||||
key := strings.ToLower(strings.TrimSpace(gateway))
|
||||
if key == "" {
|
||||
key = defaultCardGateway
|
||||
}
|
||||
route, ok := s.deps.cardRoutes[key]
|
||||
if !ok {
|
||||
s.logger.Warn("card routing missing for gateway", zap.String("gateway", key))
|
||||
return CardGatewayRoute{}, merrors.InvalidArgument("card routing missing for gateway " + key)
|
||||
}
|
||||
if strings.TrimSpace(route.FundingAddress) == "" {
|
||||
s.logger.Warn("card routing missing funding address", zap.String("gateway", key))
|
||||
return CardGatewayRoute{}, merrors.InvalidArgument("card funding address is required for gateway " + key)
|
||||
}
|
||||
return route, nil
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
package orchestrator
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/shopspring/decimal"
|
||||
"github.com/tech/sendico/payments/orchestrator/storage/model"
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
paymenttypes "github.com/tech/sendico/pkg/payments/types"
|
||||
mntxv1 "github.com/tech/sendico/pkg/proto/gateway/mntx/v1"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func (s *Service) submitCardPayout(ctx context.Context, payment *model.Payment) error {
|
||||
if payment == nil {
|
||||
return merrors.InvalidArgument("payment is required")
|
||||
}
|
||||
if payment.Execution != nil && strings.TrimSpace(payment.Execution.CardPayoutRef) != "" {
|
||||
return nil
|
||||
}
|
||||
intent := payment.Intent
|
||||
card := intent.Destination.Card
|
||||
if card == nil {
|
||||
return merrors.InvalidArgument("card payout: card endpoint is required")
|
||||
}
|
||||
amount, err := cardPayoutAmount(payment)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
amtDec, err := decimalFromMoney(amount)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
minor := amtDec.Mul(decimal.NewFromInt(100)).IntPart()
|
||||
|
||||
payoutID := payment.PaymentRef
|
||||
currency := strings.TrimSpace(amount.GetCurrency())
|
||||
holder := strings.TrimSpace(card.Cardholder)
|
||||
meta := cloneMetadata(payment.Metadata)
|
||||
customer := intent.Customer
|
||||
customerID := ""
|
||||
customerFirstName := ""
|
||||
customerMiddleName := ""
|
||||
customerLastName := ""
|
||||
customerIP := ""
|
||||
customerZip := ""
|
||||
customerCountry := ""
|
||||
customerState := ""
|
||||
customerCity := ""
|
||||
customerAddress := ""
|
||||
if customer != nil {
|
||||
customerID = strings.TrimSpace(customer.ID)
|
||||
customerFirstName = strings.TrimSpace(customer.FirstName)
|
||||
customerMiddleName = strings.TrimSpace(customer.MiddleName)
|
||||
customerLastName = strings.TrimSpace(customer.LastName)
|
||||
customerIP = strings.TrimSpace(customer.IP)
|
||||
customerZip = strings.TrimSpace(customer.Zip)
|
||||
customerCountry = strings.TrimSpace(customer.Country)
|
||||
customerState = strings.TrimSpace(customer.State)
|
||||
customerCity = strings.TrimSpace(customer.City)
|
||||
customerAddress = strings.TrimSpace(customer.Address)
|
||||
}
|
||||
if customerFirstName == "" {
|
||||
customerFirstName = strings.TrimSpace(card.Cardholder)
|
||||
}
|
||||
if customerLastName == "" {
|
||||
customerLastName = strings.TrimSpace(card.CardholderSurname)
|
||||
}
|
||||
if customerID == "" {
|
||||
return merrors.InvalidArgument("card payout: customer id is required")
|
||||
}
|
||||
if customerFirstName == "" {
|
||||
return merrors.InvalidArgument("card payout: customer first name is required")
|
||||
}
|
||||
if customerLastName == "" {
|
||||
return merrors.InvalidArgument("card payout: customer last name is required")
|
||||
}
|
||||
if customerIP == "" {
|
||||
return merrors.InvalidArgument("card payout: customer ip is required")
|
||||
}
|
||||
|
||||
var (
|
||||
state *mntxv1.CardPayoutState
|
||||
)
|
||||
|
||||
if token := strings.TrimSpace(card.Token); token != "" {
|
||||
req := &mntxv1.CardTokenPayoutRequest{
|
||||
PayoutId: payoutID,
|
||||
CustomerId: customerID,
|
||||
CustomerFirstName: customerFirstName,
|
||||
CustomerMiddleName: customerMiddleName,
|
||||
CustomerLastName: customerLastName,
|
||||
CustomerIp: customerIP,
|
||||
CustomerZip: customerZip,
|
||||
CustomerCountry: customerCountry,
|
||||
CustomerState: customerState,
|
||||
CustomerCity: customerCity,
|
||||
CustomerAddress: customerAddress,
|
||||
AmountMinor: minor,
|
||||
Currency: currency,
|
||||
CardToken: token,
|
||||
CardHolder: holder,
|
||||
MaskedPan: strings.TrimSpace(card.MaskedPan),
|
||||
Metadata: meta,
|
||||
}
|
||||
resp, err := s.deps.mntx.client.CreateCardTokenPayout(ctx, req)
|
||||
if err != nil {
|
||||
s.logger.Warn("card token payout failed", zap.Error(err), zap.String("payment_ref", payment.PaymentRef))
|
||||
return err
|
||||
}
|
||||
state = resp.GetPayout()
|
||||
} else if pan := strings.TrimSpace(card.Pan); pan != "" {
|
||||
req := &mntxv1.CardPayoutRequest{
|
||||
PayoutId: payoutID,
|
||||
CustomerId: customerID,
|
||||
CustomerFirstName: customerFirstName,
|
||||
CustomerMiddleName: customerMiddleName,
|
||||
CustomerLastName: customerLastName,
|
||||
CustomerIp: customerIP,
|
||||
CustomerZip: customerZip,
|
||||
CustomerCountry: customerCountry,
|
||||
CustomerState: customerState,
|
||||
CustomerCity: customerCity,
|
||||
CustomerAddress: customerAddress,
|
||||
AmountMinor: minor,
|
||||
Currency: currency,
|
||||
CardPan: pan,
|
||||
CardExpYear: card.ExpYear,
|
||||
CardExpMonth: card.ExpMonth,
|
||||
CardHolder: holder,
|
||||
Metadata: meta,
|
||||
}
|
||||
resp, err := s.deps.mntx.client.CreateCardPayout(ctx, req)
|
||||
if err != nil {
|
||||
s.logger.Warn("card payout failed", zap.Error(err), zap.String("payment_ref", payment.PaymentRef))
|
||||
return err
|
||||
}
|
||||
state = resp.GetPayout()
|
||||
} else {
|
||||
return merrors.InvalidArgument("card payout: either token or pan must be provided")
|
||||
}
|
||||
|
||||
if state == nil {
|
||||
return merrors.Internal("card payout: missing payout state")
|
||||
}
|
||||
recordCardPayoutState(payment, state)
|
||||
exec := payment.Execution
|
||||
if exec == nil {
|
||||
exec = &model.ExecutionRefs{}
|
||||
}
|
||||
if exec.CardPayoutRef == "" {
|
||||
exec.CardPayoutRef = strings.TrimSpace(state.GetPayoutId())
|
||||
}
|
||||
payment.Execution = exec
|
||||
|
||||
plan := ensureExecutionPlan(payment)
|
||||
if plan != nil {
|
||||
step := ensureExecutionStep(plan, stepCodeCardPayout)
|
||||
setExecutionStepRole(step, executionStepRoleConsumer)
|
||||
step.Description = "Submit card payout"
|
||||
step.Amount = cloneMoney(amount)
|
||||
if masked := strings.TrimSpace(card.MaskedPan); masked != "" {
|
||||
step.DestinationRef = masked
|
||||
}
|
||||
if exec.CardPayoutRef != "" {
|
||||
step.TransferRef = exec.CardPayoutRef
|
||||
}
|
||||
setExecutionStepStatus(step, executionStepStatusSubmitted)
|
||||
updateExecutionPlanTotalNetworkFee(plan)
|
||||
}
|
||||
|
||||
s.logger.Info("card payout submitted", zap.String("payment_ref", payment.PaymentRef), zap.String("payout_id", exec.CardPayoutRef))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func recordCardPayoutState(payment *model.Payment, state *mntxv1.CardPayoutState) {
|
||||
if payment == nil || state == nil {
|
||||
return
|
||||
}
|
||||
if payment.CardPayout == nil {
|
||||
payment.CardPayout = &model.CardPayout{}
|
||||
}
|
||||
payment.CardPayout.PayoutRef = strings.TrimSpace(state.GetPayoutId())
|
||||
payment.CardPayout.ProviderPaymentID = strings.TrimSpace(state.GetProviderPaymentId())
|
||||
payment.CardPayout.Status = state.GetStatus().String()
|
||||
payment.CardPayout.FailureReason = strings.TrimSpace(state.GetProviderMessage())
|
||||
payment.CardPayout.ProviderCode = strings.TrimSpace(state.GetProviderCode())
|
||||
if payment.CardPayout.CardCountry == "" && payment.Intent.Destination.Card != nil {
|
||||
payment.CardPayout.CardCountry = strings.TrimSpace(payment.Intent.Destination.Card.Country)
|
||||
}
|
||||
if payment.CardPayout.MaskedPan == "" && payment.Intent.Destination.Card != nil {
|
||||
payment.CardPayout.MaskedPan = strings.TrimSpace(payment.Intent.Destination.Card.MaskedPan)
|
||||
}
|
||||
payment.CardPayout.GatewayReference = strings.TrimSpace(state.GetPayoutId())
|
||||
}
|
||||
|
||||
func applyCardPayoutUpdate(payment *model.Payment, payout *mntxv1.CardPayoutState) {
|
||||
if payment == nil || payout == nil {
|
||||
return
|
||||
}
|
||||
recordCardPayoutState(payment, payout)
|
||||
|
||||
if payment.Execution == nil {
|
||||
payment.Execution = &model.ExecutionRefs{}
|
||||
}
|
||||
if payment.Execution.CardPayoutRef == "" {
|
||||
payment.Execution.CardPayoutRef = strings.TrimSpace(payout.GetPayoutId())
|
||||
}
|
||||
|
||||
plan := ensureExecutionPlan(payment)
|
||||
if plan != nil {
|
||||
step := findExecutionStepByTransferRef(plan, strings.TrimSpace(payout.GetPayoutId()))
|
||||
if step == nil {
|
||||
step = ensureExecutionStep(plan, stepCodeCardPayout)
|
||||
setExecutionStepRole(step, executionStepRoleConsumer)
|
||||
if step.TransferRef == "" {
|
||||
step.TransferRef = payment.Execution.CardPayoutRef
|
||||
}
|
||||
}
|
||||
switch payout.GetStatus() {
|
||||
case mntxv1.PayoutStatus_PAYOUT_STATUS_PROCESSED:
|
||||
setExecutionStepStatus(step, executionStepStatusConfirmed)
|
||||
case mntxv1.PayoutStatus_PAYOUT_STATUS_FAILED:
|
||||
setExecutionStepStatus(step, executionStepStatusFailed)
|
||||
case mntxv1.PayoutStatus_PAYOUT_STATUS_PENDING:
|
||||
setExecutionStepStatus(step, executionStepStatusSubmitted)
|
||||
default:
|
||||
setExecutionStepStatus(step, executionStepStatusPlanned)
|
||||
}
|
||||
}
|
||||
|
||||
payment.State = mapMntxStatusToState(payout.GetStatus())
|
||||
switch payout.GetStatus() {
|
||||
case mntxv1.PayoutStatus_PAYOUT_STATUS_PROCESSED:
|
||||
payment.FailureCode = model.PaymentFailureCodeUnspecified
|
||||
payment.FailureReason = ""
|
||||
case mntxv1.PayoutStatus_PAYOUT_STATUS_FAILED:
|
||||
payment.FailureCode = model.PaymentFailureCodePolicy
|
||||
payment.FailureReason = strings.TrimSpace(payout.GetProviderMessage())
|
||||
default:
|
||||
// leave as-is for pending/unspecified
|
||||
}
|
||||
}
|
||||
|
||||
func cardPayoutAmount(payment *model.Payment) (*paymenttypes.Money, error) {
|
||||
if payment == nil {
|
||||
return nil, merrors.InvalidArgument("payment is required")
|
||||
}
|
||||
amount := cloneMoney(payment.Intent.Amount)
|
||||
if payment.LastQuote != nil {
|
||||
settlement := payment.LastQuote.ExpectedSettlementAmount
|
||||
if settlement != nil && strings.TrimSpace(settlement.GetAmount()) != "" && strings.TrimSpace(settlement.GetCurrency()) != "" {
|
||||
amount = cloneMoney(settlement)
|
||||
}
|
||||
}
|
||||
if amount == nil || strings.TrimSpace(amount.GetAmount()) == "" || strings.TrimSpace(amount.GetCurrency()) == "" {
|
||||
return nil, merrors.InvalidArgument("card payout: amount is required")
|
||||
}
|
||||
return amount, nil
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
mntxclient "github.com/tech/sendico/gateway/mntx/client"
|
||||
"github.com/tech/sendico/payments/orchestrator/storage/model"
|
||||
mo "github.com/tech/sendico/pkg/model"
|
||||
paymenttypes "github.com/tech/sendico/pkg/payments/types"
|
||||
moneyv1 "github.com/tech/sendico/pkg/proto/common/money/v1"
|
||||
chainv1 "github.com/tech/sendico/pkg/proto/gateway/chain/v1"
|
||||
mntxv1 "github.com/tech/sendico/pkg/proto/gateway/mntx/v1"
|
||||
@@ -101,7 +102,7 @@ func TestSubmitCardFundingTransfers_PlansTopUpAndFunding(t *testing.T) {
|
||||
MaskedPan: "4111",
|
||||
},
|
||||
},
|
||||
Amount: &moneyv1.Money{Currency: "USDT", Amount: "5"},
|
||||
Amount: &paymenttypes.Money{Currency: "USDT", Amount: "5"},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -122,8 +123,8 @@ func TestSubmitCardFundingTransfers_PlansTopUpAndFunding(t *testing.T) {
|
||||
if len(ensureCalls) != 1 {
|
||||
t.Fatalf("expected 1 gas top-up ensure call, got %d", len(ensureCalls))
|
||||
}
|
||||
if len(submitCalls) != 1 {
|
||||
t.Fatalf("expected 1 transfer submission, got %d", len(submitCalls))
|
||||
if len(submitCalls) != 2 {
|
||||
t.Fatalf("expected 2 transfer submissions, got %d", len(submitCalls))
|
||||
}
|
||||
|
||||
computeCall := computeCalls[0]
|
||||
@@ -153,7 +154,15 @@ func TestSubmitCardFundingTransfers_PlansTopUpAndFunding(t *testing.T) {
|
||||
t.Fatalf("funding amount mismatch: %s %s", fundCall.GetAmount().GetCurrency(), fundCall.GetAmount().GetAmount())
|
||||
}
|
||||
|
||||
if payment.Execution == nil || payment.Execution.ChainTransferRef != "pay-1:card:fund" {
|
||||
feeCall := findSubmitCall(t, submitCalls, "pay-1:card:fee")
|
||||
if feeCall.GetDestination().GetManagedWalletRef() != feeWalletRef {
|
||||
t.Fatalf("fee destination mismatch: %s", feeCall.GetDestination().GetManagedWalletRef())
|
||||
}
|
||||
if feeCall.GetAmount().GetCurrency() != "USDT" || feeCall.GetAmount().GetAmount() != "0.35" {
|
||||
t.Fatalf("fee amount mismatch: %s %s", feeCall.GetAmount().GetCurrency(), feeCall.GetAmount().GetAmount())
|
||||
}
|
||||
|
||||
if payment.Execution == nil || payment.Execution.ChainTransferRef != "pay-1:card:fund" || payment.Execution.FeeTransferRef != "pay-1:card:fee" {
|
||||
t.Fatalf("expected funding transfer ref recorded, got %v", payment.Execution)
|
||||
}
|
||||
|
||||
@@ -192,8 +201,8 @@ func TestSubmitCardFundingTransfers_PlansTopUpAndFunding(t *testing.T) {
|
||||
if feeStep.NetworkFee.GetAmount() != "0.02" || feeStep.NetworkFee.GetCurrency() != "ETH" {
|
||||
t.Fatalf("fee step network fee mismatch: %s %s", feeStep.NetworkFee.GetCurrency(), feeStep.NetworkFee.GetAmount())
|
||||
}
|
||||
if feeStep.TransferRef != "" {
|
||||
t.Fatalf("expected fee step transfer ref to be empty before payout, got %s", feeStep.TransferRef)
|
||||
if feeStep.TransferRef != "pay-1:card:fee" {
|
||||
t.Fatalf("fee step transfer ref mismatch: %s", feeStep.TransferRef)
|
||||
}
|
||||
|
||||
if plan.TotalNetworkFee == nil || plan.TotalNetworkFee.GetAmount() != "0.035" || plan.TotalNetworkFee.GetCurrency() != "ETH" {
|
||||
@@ -201,13 +210,10 @@ func TestSubmitCardFundingTransfers_PlansTopUpAndFunding(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubmitCardPayout_UsesSettlementAmountAndTransfersFee(t *testing.T) {
|
||||
func TestSubmitCardPayout_UsesSettlementAmount(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
const (
|
||||
sourceWalletRef = "wallet-src"
|
||||
feeWalletRef = "wallet-fee"
|
||||
)
|
||||
const sourceWalletRef = "wallet-src"
|
||||
|
||||
var payoutReq *mntxv1.CardPayoutRequest
|
||||
var submitCalls []*chainv1.SubmitTransferRequest
|
||||
@@ -237,12 +243,6 @@ func TestSubmitCardPayout_UsesSettlementAmountAndTransfersFee(t *testing.T) {
|
||||
deps: serviceDependencies{
|
||||
gateway: gatewayDependency{client: gateway},
|
||||
mntx: mntxDependency{client: mntx},
|
||||
cardRoutes: map[string]CardGatewayRoute{
|
||||
defaultCardGateway: {
|
||||
FundingAddress: "0xfunding",
|
||||
FeeWalletRef: feeWalletRef,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -265,7 +265,7 @@ func TestSubmitCardPayout_UsesSettlementAmountAndTransfersFee(t *testing.T) {
|
||||
Cardholder: "Stephan",
|
||||
},
|
||||
},
|
||||
Amount: &moneyv1.Money{Currency: "USDT", Amount: "5"},
|
||||
Amount: &paymenttypes.Money{Currency: "USDT", Amount: "5"},
|
||||
Customer: &model.Customer{
|
||||
ID: "recipient-1",
|
||||
FirstName: "Stephan",
|
||||
@@ -274,8 +274,8 @@ func TestSubmitCardPayout_UsesSettlementAmountAndTransfersFee(t *testing.T) {
|
||||
},
|
||||
},
|
||||
LastQuote: &model.PaymentQuoteSnapshot{
|
||||
ExpectedSettlementAmount: &moneyv1.Money{Currency: "RUB", Amount: "392.30"},
|
||||
ExpectedFeeTotal: &moneyv1.Money{Currency: "USDT", Amount: "0.35"},
|
||||
ExpectedSettlementAmount: &paymenttypes.Money{Currency: "RUB", Amount: "392.30"},
|
||||
ExpectedFeeTotal: &paymenttypes.Money{Currency: "USDT", Amount: "0.35"},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -293,19 +293,9 @@ func TestSubmitCardPayout_UsesSettlementAmountAndTransfersFee(t *testing.T) {
|
||||
if payment.Execution == nil || payment.Execution.CardPayoutRef != "payout-1" {
|
||||
t.Fatalf("expected card payout ref recorded, got %v", payment.Execution)
|
||||
}
|
||||
if payment.Execution.FeeTransferRef != "fee-transfer" {
|
||||
t.Fatalf("expected fee transfer ref recorded, got %v", payment.Execution)
|
||||
}
|
||||
|
||||
if len(submitCalls) != 1 {
|
||||
t.Fatalf("expected 1 fee transfer submission, got %d", len(submitCalls))
|
||||
}
|
||||
feeCall := submitCalls[0]
|
||||
if feeCall.GetSourceWalletRef() != sourceWalletRef {
|
||||
t.Fatalf("fee transfer source mismatch: %s", feeCall.GetSourceWalletRef())
|
||||
}
|
||||
if feeCall.GetDestination().GetManagedWalletRef() != feeWalletRef {
|
||||
t.Fatalf("fee transfer destination mismatch: %s", feeCall.GetDestination().GetManagedWalletRef())
|
||||
if len(submitCalls) != 0 {
|
||||
t.Fatalf("expected 0 fee transfer submissions, got %d", len(submitCalls))
|
||||
}
|
||||
|
||||
plan := payment.ExecutionPlan
|
||||
@@ -320,13 +310,6 @@ func TestSubmitCardPayout_UsesSettlementAmountAndTransfersFee(t *testing.T) {
|
||||
t.Fatalf("card step amount mismatch: %s %s", cardStep.Amount.GetCurrency(), cardStep.Amount.GetAmount())
|
||||
}
|
||||
|
||||
feeStep := findExecutionStep(t, plan, stepCodeFeeTransfer)
|
||||
if feeStep.TransferRef != "fee-transfer" {
|
||||
t.Fatalf("fee step transfer ref mismatch: %s", feeStep.TransferRef)
|
||||
}
|
||||
if feeStep.Amount.GetAmount() != "0.35" || feeStep.Amount.GetCurrency() != "USDT" {
|
||||
t.Fatalf("fee step amount mismatch: %s %s", feeStep.Amount.GetCurrency(), feeStep.Amount.GetAmount())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubmitCardFundingTransfers_RequiresFeeWalletRef(t *testing.T) {
|
||||
@@ -370,7 +353,7 @@ func TestSubmitCardFundingTransfers_RequiresFeeWalletRef(t *testing.T) {
|
||||
MaskedPan: "4111",
|
||||
},
|
||||
},
|
||||
Amount: &moneyv1.Money{Currency: "USDT", Amount: "5"},
|
||||
Amount: &paymenttypes.Money{Currency: "USDT", Amount: "5"},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package orchestrator
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
|
||||
"github.com/tech/sendico/payments/orchestrator/storage/model"
|
||||
"github.com/tech/sendico/pkg/mlogger"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
type compositeGatewayRegistry struct {
|
||||
logger mlogger.Logger
|
||||
registries []GatewayRegistry
|
||||
}
|
||||
|
||||
func NewCompositeGatewayRegistry(logger mlogger.Logger, registries ...GatewayRegistry) GatewayRegistry {
|
||||
items := make([]GatewayRegistry, 0, len(registries))
|
||||
for _, registry := range registries {
|
||||
if registry != nil {
|
||||
items = append(items, registry)
|
||||
}
|
||||
}
|
||||
if len(items) == 0 {
|
||||
return nil
|
||||
}
|
||||
if logger != nil {
|
||||
logger = logger.Named("gateway_registry")
|
||||
}
|
||||
return &compositeGatewayRegistry{
|
||||
logger: logger,
|
||||
registries: items,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *compositeGatewayRegistry) List(ctx context.Context) ([]*model.GatewayInstanceDescriptor, error) {
|
||||
if r == nil || len(r.registries) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
items := map[string]*model.GatewayInstanceDescriptor{}
|
||||
for _, registry := range r.registries {
|
||||
list, err := registry.List(ctx)
|
||||
if err != nil {
|
||||
if r.logger != nil {
|
||||
r.logger.Warn("Failed to list gateway registry", zap.Error(err))
|
||||
}
|
||||
continue
|
||||
}
|
||||
for _, entry := range list {
|
||||
if entry == nil || entry.ID == "" {
|
||||
continue
|
||||
}
|
||||
items[entry.ID] = entry
|
||||
}
|
||||
}
|
||||
result := make([]*model.GatewayInstanceDescriptor, 0, len(items))
|
||||
for _, entry := range items {
|
||||
result = append(result, entry)
|
||||
}
|
||||
sort.Slice(result, func(i, j int) bool {
|
||||
return result[i].ID < result[j].ID
|
||||
})
|
||||
return result, nil
|
||||
}
|
||||
@@ -5,11 +5,15 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/tech/sendico/payments/orchestrator/storage/model"
|
||||
paymenttypes "github.com/tech/sendico/pkg/payments/types"
|
||||
feesv1 "github.com/tech/sendico/pkg/proto/billing/fees/v1"
|
||||
accountingv1 "github.com/tech/sendico/pkg/proto/common/accounting/v1"
|
||||
fxv1 "github.com/tech/sendico/pkg/proto/common/fx/v1"
|
||||
gatewayv1 "github.com/tech/sendico/pkg/proto/common/gateway/v1"
|
||||
moneyv1 "github.com/tech/sendico/pkg/proto/common/money/v1"
|
||||
chainv1 "github.com/tech/sendico/pkg/proto/gateway/chain/v1"
|
||||
oraclev1 "github.com/tech/sendico/pkg/proto/oracle/v1"
|
||||
orchestratorv1 "github.com/tech/sendico/pkg/proto/payments/orchestrator/v1"
|
||||
"google.golang.org/protobuf/proto"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
)
|
||||
|
||||
@@ -18,15 +22,16 @@ func intentFromProto(src *orchestratorv1.PaymentIntent) model.PaymentIntent {
|
||||
return model.PaymentIntent{}
|
||||
}
|
||||
intent := model.PaymentIntent{
|
||||
Kind: modelKindFromProto(src.GetKind()),
|
||||
Source: endpointFromProto(src.GetSource()),
|
||||
Destination: endpointFromProto(src.GetDestination()),
|
||||
Amount: cloneMoney(src.GetAmount()),
|
||||
RequiresFX: src.GetRequiresFx(),
|
||||
FeePolicy: src.GetFeePolicy(),
|
||||
SettlementMode: src.GetSettlementMode(),
|
||||
Attributes: cloneMetadata(src.GetAttributes()),
|
||||
Customer: customerFromProto(src.GetCustomer()),
|
||||
Kind: modelKindFromProto(src.GetKind()),
|
||||
Source: endpointFromProto(src.GetSource()),
|
||||
Destination: endpointFromProto(src.GetDestination()),
|
||||
Amount: moneyFromProto(src.GetAmount()),
|
||||
RequiresFX: src.GetRequiresFx(),
|
||||
FeePolicy: feePolicyFromProto(src.GetFeePolicy()),
|
||||
SettlementMode: settlementModeFromProto(src.GetSettlementMode()),
|
||||
SettlementCurrency: strings.TrimSpace(src.GetSettlementCurrency()),
|
||||
Attributes: cloneMetadata(src.GetAttributes()),
|
||||
Customer: customerFromProto(src.GetCustomer()),
|
||||
}
|
||||
if src.GetFx() != nil {
|
||||
intent.FX = fxIntentFromProto(src.GetFx())
|
||||
@@ -39,8 +44,9 @@ func endpointFromProto(src *orchestratorv1.PaymentEndpoint) model.PaymentEndpoin
|
||||
return model.PaymentEndpoint{Type: model.EndpointTypeUnspecified}
|
||||
}
|
||||
result := model.PaymentEndpoint{
|
||||
Type: model.EndpointTypeUnspecified,
|
||||
Metadata: cloneMetadata(src.GetMetadata()),
|
||||
Type: model.EndpointTypeUnspecified,
|
||||
InstanceID: strings.TrimSpace(src.GetInstanceId()),
|
||||
Metadata: cloneMetadata(src.GetMetadata()),
|
||||
}
|
||||
if ledger := src.GetLedger(); ledger != nil {
|
||||
result.Type = model.EndpointTypeLedger
|
||||
@@ -54,14 +60,14 @@ func endpointFromProto(src *orchestratorv1.PaymentEndpoint) model.PaymentEndpoin
|
||||
result.Type = model.EndpointTypeManagedWallet
|
||||
result.ManagedWallet = &model.ManagedWalletEndpoint{
|
||||
ManagedWalletRef: strings.TrimSpace(managed.GetManagedWalletRef()),
|
||||
Asset: cloneAsset(managed.GetAsset()),
|
||||
Asset: assetFromProto(managed.GetAsset()),
|
||||
}
|
||||
return result
|
||||
}
|
||||
if external := src.GetExternalChain(); external != nil {
|
||||
result.Type = model.EndpointTypeExternalChain
|
||||
result.ExternalChain = &model.ExternalChainEndpoint{
|
||||
Asset: cloneAsset(external.GetAsset()),
|
||||
Asset: assetFromProto(external.GetAsset()),
|
||||
Address: strings.TrimSpace(external.GetAddress()),
|
||||
Memo: strings.TrimSpace(external.GetMemo()),
|
||||
}
|
||||
@@ -89,8 +95,8 @@ func fxIntentFromProto(src *orchestratorv1.FXIntent) *model.FXIntent {
|
||||
return nil
|
||||
}
|
||||
return &model.FXIntent{
|
||||
Pair: clonePair(src.GetPair()),
|
||||
Side: src.GetSide(),
|
||||
Pair: pairFromProto(src.GetPair()),
|
||||
Side: fxSideFromProto(src.GetSide()),
|
||||
Firm: src.GetFirm(),
|
||||
TTLMillis: src.GetTtlMs(),
|
||||
PreferredProvider: strings.TrimSpace(src.GetPreferredProvider()),
|
||||
@@ -103,13 +109,13 @@ func quoteSnapshotToModel(src *orchestratorv1.PaymentQuote) *model.PaymentQuoteS
|
||||
return nil
|
||||
}
|
||||
return &model.PaymentQuoteSnapshot{
|
||||
DebitAmount: cloneMoney(src.GetDebitAmount()),
|
||||
ExpectedSettlementAmount: cloneMoney(src.GetExpectedSettlementAmount()),
|
||||
ExpectedFeeTotal: cloneMoney(src.GetExpectedFeeTotal()),
|
||||
FeeLines: cloneFeeLines(src.GetFeeLines()),
|
||||
FeeRules: cloneFeeRules(src.GetFeeRules()),
|
||||
FXQuote: cloneFXQuote(src.GetFxQuote()),
|
||||
NetworkFee: cloneNetworkEstimate(src.GetNetworkFee()),
|
||||
DebitAmount: moneyFromProto(src.GetDebitAmount()),
|
||||
ExpectedSettlementAmount: moneyFromProto(src.GetExpectedSettlementAmount()),
|
||||
ExpectedFeeTotal: moneyFromProto(src.GetExpectedFeeTotal()),
|
||||
FeeLines: feeLinesFromProto(src.GetFeeLines()),
|
||||
FeeRules: feeRulesFromProto(src.GetFeeRules()),
|
||||
FXQuote: fxQuoteFromProto(src.GetFxQuote()),
|
||||
NetworkFee: networkFeeFromProto(src.GetNetworkFee()),
|
||||
QuoteRef: strings.TrimSpace(src.GetQuoteRef()),
|
||||
}
|
||||
}
|
||||
@@ -128,6 +134,7 @@ func toProtoPayment(src *model.Payment) *orchestratorv1.Payment {
|
||||
LastQuote: modelQuoteToProto(src.LastQuote),
|
||||
Execution: protoExecutionFromModel(src.Execution),
|
||||
ExecutionPlan: protoExecutionPlanFromModel(src.ExecutionPlan),
|
||||
PaymentPlan: protoPaymentPlanFromModel(src.PaymentPlan),
|
||||
Metadata: cloneMetadata(src.Metadata),
|
||||
}
|
||||
if src.CardPayout != nil {
|
||||
@@ -155,15 +162,16 @@ func toProtoPayment(src *model.Payment) *orchestratorv1.Payment {
|
||||
|
||||
func protoIntentFromModel(src model.PaymentIntent) *orchestratorv1.PaymentIntent {
|
||||
intent := &orchestratorv1.PaymentIntent{
|
||||
Kind: protoKindFromModel(src.Kind),
|
||||
Source: protoEndpointFromModel(src.Source),
|
||||
Destination: protoEndpointFromModel(src.Destination),
|
||||
Amount: cloneMoney(src.Amount),
|
||||
RequiresFx: src.RequiresFX,
|
||||
FeePolicy: src.FeePolicy,
|
||||
SettlementMode: src.SettlementMode,
|
||||
Attributes: cloneMetadata(src.Attributes),
|
||||
Customer: protoCustomerFromModel(src.Customer),
|
||||
Kind: protoKindFromModel(src.Kind),
|
||||
Source: protoEndpointFromModel(src.Source),
|
||||
Destination: protoEndpointFromModel(src.Destination),
|
||||
Amount: protoMoney(src.Amount),
|
||||
RequiresFx: src.RequiresFX,
|
||||
FeePolicy: feePolicyToProto(src.FeePolicy),
|
||||
SettlementMode: settlementModeToProto(src.SettlementMode),
|
||||
SettlementCurrency: strings.TrimSpace(src.SettlementCurrency),
|
||||
Attributes: cloneMetadata(src.Attributes),
|
||||
Customer: protoCustomerFromModel(src.Customer),
|
||||
}
|
||||
if src.FX != nil {
|
||||
intent.Fx = protoFXIntentFromModel(src.FX)
|
||||
@@ -209,7 +217,8 @@ func protoCustomerFromModel(src *model.Customer) *orchestratorv1.Customer {
|
||||
|
||||
func protoEndpointFromModel(src model.PaymentEndpoint) *orchestratorv1.PaymentEndpoint {
|
||||
endpoint := &orchestratorv1.PaymentEndpoint{
|
||||
Metadata: cloneMetadata(src.Metadata),
|
||||
Metadata: cloneMetadata(src.Metadata),
|
||||
InstanceId: strings.TrimSpace(src.InstanceID),
|
||||
}
|
||||
switch src.Type {
|
||||
case model.EndpointTypeLedger:
|
||||
@@ -226,7 +235,7 @@ func protoEndpointFromModel(src model.PaymentEndpoint) *orchestratorv1.PaymentEn
|
||||
endpoint.Endpoint = &orchestratorv1.PaymentEndpoint_ManagedWallet{
|
||||
ManagedWallet: &orchestratorv1.ManagedWalletEndpoint{
|
||||
ManagedWalletRef: src.ManagedWallet.ManagedWalletRef,
|
||||
Asset: cloneAsset(src.ManagedWallet.Asset),
|
||||
Asset: assetToProto(src.ManagedWallet.Asset),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -234,7 +243,7 @@ func protoEndpointFromModel(src model.PaymentEndpoint) *orchestratorv1.PaymentEn
|
||||
if src.ExternalChain != nil {
|
||||
endpoint.Endpoint = &orchestratorv1.PaymentEndpoint_ExternalChain{
|
||||
ExternalChain: &orchestratorv1.ExternalChainEndpoint{
|
||||
Asset: cloneAsset(src.ExternalChain.Asset),
|
||||
Asset: assetToProto(src.ExternalChain.Asset),
|
||||
Address: src.ExternalChain.Address,
|
||||
Memo: src.ExternalChain.Memo,
|
||||
},
|
||||
@@ -269,8 +278,8 @@ func protoFXIntentFromModel(src *model.FXIntent) *orchestratorv1.FXIntent {
|
||||
return nil
|
||||
}
|
||||
return &orchestratorv1.FXIntent{
|
||||
Pair: clonePair(src.Pair),
|
||||
Side: src.Side,
|
||||
Pair: pairToProto(src.Pair),
|
||||
Side: fxSideToProto(src.Side),
|
||||
Firm: src.Firm,
|
||||
TtlMs: src.TTLMillis,
|
||||
PreferredProvider: src.PreferredProvider,
|
||||
@@ -299,8 +308,8 @@ func protoExecutionStepFromModel(src *model.ExecutionStep) *orchestratorv1.Execu
|
||||
return &orchestratorv1.ExecutionStep{
|
||||
Code: src.Code,
|
||||
Description: src.Description,
|
||||
Amount: cloneMoney(src.Amount),
|
||||
NetworkFee: cloneMoney(src.NetworkFee),
|
||||
Amount: protoMoney(src.Amount),
|
||||
NetworkFee: protoMoney(src.NetworkFee),
|
||||
SourceWalletRef: src.SourceWalletRef,
|
||||
DestinationRef: src.DestinationRef,
|
||||
TransferRef: src.TransferRef,
|
||||
@@ -323,22 +332,66 @@ func protoExecutionPlanFromModel(src *model.ExecutionPlan) *orchestratorv1.Execu
|
||||
}
|
||||
return &orchestratorv1.ExecutionPlan{
|
||||
Steps: steps,
|
||||
TotalNetworkFee: cloneMoney(src.TotalNetworkFee),
|
||||
TotalNetworkFee: protoMoney(src.TotalNetworkFee),
|
||||
}
|
||||
}
|
||||
|
||||
func protoPaymentStepFromModel(src *model.PaymentStep) *orchestratorv1.PaymentStep {
|
||||
if src == nil {
|
||||
return nil
|
||||
}
|
||||
return &orchestratorv1.PaymentStep{
|
||||
Rail: protoRailFromModel(src.Rail),
|
||||
GatewayId: strings.TrimSpace(src.GatewayID),
|
||||
Action: protoRailOperationFromModel(src.Action),
|
||||
Amount: protoMoney(src.Amount),
|
||||
Ref: strings.TrimSpace(src.Ref),
|
||||
StepId: strings.TrimSpace(src.StepID),
|
||||
InstanceId: strings.TrimSpace(src.InstanceID),
|
||||
DependsOn: cloneStringList(src.DependsOn),
|
||||
CommitPolicy: strings.TrimSpace(string(src.CommitPolicy)),
|
||||
CommitAfter: cloneStringList(src.CommitAfter),
|
||||
}
|
||||
}
|
||||
|
||||
func protoPaymentPlanFromModel(src *model.PaymentPlan) *orchestratorv1.PaymentPlan {
|
||||
if src == nil {
|
||||
return nil
|
||||
}
|
||||
steps := make([]*orchestratorv1.PaymentStep, 0, len(src.Steps))
|
||||
for _, step := range src.Steps {
|
||||
if protoStep := protoPaymentStepFromModel(step); protoStep != nil {
|
||||
steps = append(steps, protoStep)
|
||||
}
|
||||
}
|
||||
if len(steps) == 0 {
|
||||
steps = nil
|
||||
}
|
||||
plan := &orchestratorv1.PaymentPlan{
|
||||
Id: strings.TrimSpace(src.ID),
|
||||
Steps: steps,
|
||||
IdempotencyKey: strings.TrimSpace(src.IdempotencyKey),
|
||||
FxQuote: fxQuoteToProto(src.FXQuote),
|
||||
Fees: feeLinesToProto(src.Fees),
|
||||
}
|
||||
if !src.CreatedAt.IsZero() {
|
||||
plan.CreatedAt = timestamppb.New(src.CreatedAt.UTC())
|
||||
}
|
||||
return plan
|
||||
}
|
||||
|
||||
func modelQuoteToProto(src *model.PaymentQuoteSnapshot) *orchestratorv1.PaymentQuote {
|
||||
if src == nil {
|
||||
return nil
|
||||
}
|
||||
return &orchestratorv1.PaymentQuote{
|
||||
DebitAmount: cloneMoney(src.DebitAmount),
|
||||
ExpectedSettlementAmount: cloneMoney(src.ExpectedSettlementAmount),
|
||||
ExpectedFeeTotal: cloneMoney(src.ExpectedFeeTotal),
|
||||
FeeLines: cloneFeeLines(src.FeeLines),
|
||||
FeeRules: cloneFeeRules(src.FeeRules),
|
||||
FxQuote: cloneFXQuote(src.FXQuote),
|
||||
NetworkFee: cloneNetworkEstimate(src.NetworkFee),
|
||||
DebitAmount: protoMoney(src.DebitAmount),
|
||||
ExpectedSettlementAmount: protoMoney(src.ExpectedSettlementAmount),
|
||||
ExpectedFeeTotal: protoMoney(src.ExpectedFeeTotal),
|
||||
FeeLines: feeLinesToProto(src.FeeLines),
|
||||
FeeRules: feeRulesToProto(src.FeeRules),
|
||||
FxQuote: fxQuoteToProto(src.FXQuote),
|
||||
NetworkFee: networkFeeToProto(src.NetworkFee),
|
||||
QuoteRef: strings.TrimSpace(src.QuoteRef),
|
||||
}
|
||||
}
|
||||
@@ -390,6 +443,42 @@ func modelKindFromProto(kind orchestratorv1.PaymentKind) model.PaymentKind {
|
||||
}
|
||||
}
|
||||
|
||||
func protoRailFromModel(rail model.Rail) gatewayv1.Rail {
|
||||
switch strings.ToUpper(strings.TrimSpace(string(rail))) {
|
||||
case string(model.RailCrypto):
|
||||
return gatewayv1.Rail_RAIL_CRYPTO
|
||||
case string(model.RailProviderSettlement):
|
||||
return gatewayv1.Rail_RAIL_PROVIDER_SETTLEMENT
|
||||
case string(model.RailLedger):
|
||||
return gatewayv1.Rail_RAIL_LEDGER
|
||||
case string(model.RailCardPayout):
|
||||
return gatewayv1.Rail_RAIL_CARD_PAYOUT
|
||||
case string(model.RailFiatOnRamp):
|
||||
return gatewayv1.Rail_RAIL_FIAT_ONRAMP
|
||||
default:
|
||||
return gatewayv1.Rail_RAIL_UNSPECIFIED
|
||||
}
|
||||
}
|
||||
|
||||
func protoRailOperationFromModel(action model.RailOperation) gatewayv1.RailOperation {
|
||||
switch strings.ToUpper(strings.TrimSpace(string(action))) {
|
||||
case string(model.RailOperationDebit):
|
||||
return gatewayv1.RailOperation_RAIL_OPERATION_DEBIT
|
||||
case string(model.RailOperationCredit):
|
||||
return gatewayv1.RailOperation_RAIL_OPERATION_CREDIT
|
||||
case string(model.RailOperationSend):
|
||||
return gatewayv1.RailOperation_RAIL_OPERATION_SEND
|
||||
case string(model.RailOperationFee):
|
||||
return gatewayv1.RailOperation_RAIL_OPERATION_FEE
|
||||
case string(model.RailOperationObserveConfirm):
|
||||
return gatewayv1.RailOperation_RAIL_OPERATION_OBSERVE_CONFIRM
|
||||
case string(model.RailOperationFXConvert):
|
||||
return gatewayv1.RailOperation_RAIL_OPERATION_FX_CONVERT
|
||||
default:
|
||||
return gatewayv1.RailOperation_RAIL_OPERATION_UNSPECIFIED
|
||||
}
|
||||
}
|
||||
|
||||
func protoStateFromModel(state model.PaymentState) orchestratorv1.PaymentState {
|
||||
switch state {
|
||||
case model.PaymentStateAccepted:
|
||||
@@ -431,34 +520,119 @@ func modelStateFromProto(state orchestratorv1.PaymentState) model.PaymentState {
|
||||
func protoFailureFromModel(code model.PaymentFailureCode) orchestratorv1.PaymentFailureCode {
|
||||
switch code {
|
||||
case model.PaymentFailureCodeBalance:
|
||||
return orchestratorv1.PaymentFailureCode_PAYMENT_FAILURE_CODE_BALANCE
|
||||
return orchestratorv1.PaymentFailureCode_FAILURE_BALANCE
|
||||
case model.PaymentFailureCodeLedger:
|
||||
return orchestratorv1.PaymentFailureCode_PAYMENT_FAILURE_CODE_LEDGER
|
||||
return orchestratorv1.PaymentFailureCode_FAILURE_LEDGER
|
||||
case model.PaymentFailureCodeFX:
|
||||
return orchestratorv1.PaymentFailureCode_PAYMENT_FAILURE_CODE_FX
|
||||
return orchestratorv1.PaymentFailureCode_FAILURE_FX
|
||||
case model.PaymentFailureCodeChain:
|
||||
return orchestratorv1.PaymentFailureCode_PAYMENT_FAILURE_CODE_CHAIN
|
||||
return orchestratorv1.PaymentFailureCode_FAILURE_CHAIN
|
||||
case model.PaymentFailureCodeFees:
|
||||
return orchestratorv1.PaymentFailureCode_PAYMENT_FAILURE_CODE_FEES
|
||||
return orchestratorv1.PaymentFailureCode_FAILURE_FEES
|
||||
case model.PaymentFailureCodePolicy:
|
||||
return orchestratorv1.PaymentFailureCode_PAYMENT_FAILURE_CODE_POLICY
|
||||
return orchestratorv1.PaymentFailureCode_FAILURE_POLICY
|
||||
default:
|
||||
return orchestratorv1.PaymentFailureCode_PAYMENT_FAILURE_CODE_UNSPECIFIED
|
||||
return orchestratorv1.PaymentFailureCode_FAILURE_UNSPECIFIED
|
||||
}
|
||||
}
|
||||
|
||||
func cloneAsset(asset *chainv1.Asset) *chainv1.Asset {
|
||||
if asset == nil {
|
||||
func settlementModeFromProto(mode orchestratorv1.SettlementMode) model.SettlementMode {
|
||||
switch mode {
|
||||
case orchestratorv1.SettlementMode_SETTLEMENT_FIX_SOURCE:
|
||||
return model.SettlementModeFixSource
|
||||
case orchestratorv1.SettlementMode_SETTLEMENT_FIX_RECEIVED:
|
||||
return model.SettlementModeFixReceived
|
||||
default:
|
||||
return model.SettlementModeUnspecified
|
||||
}
|
||||
}
|
||||
|
||||
func settlementModeToProto(mode model.SettlementMode) orchestratorv1.SettlementMode {
|
||||
switch mode {
|
||||
case model.SettlementModeFixSource:
|
||||
return orchestratorv1.SettlementMode_SETTLEMENT_FIX_SOURCE
|
||||
case model.SettlementModeFixReceived:
|
||||
return orchestratorv1.SettlementMode_SETTLEMENT_FIX_RECEIVED
|
||||
default:
|
||||
return orchestratorv1.SettlementMode_SETTLEMENT_UNSPECIFIED
|
||||
}
|
||||
}
|
||||
|
||||
func moneyFromProto(m *moneyv1.Money) *paymenttypes.Money {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
return &chainv1.Asset{
|
||||
Chain: asset.GetChain(),
|
||||
TokenSymbol: asset.GetTokenSymbol(),
|
||||
ContractAddress: asset.GetContractAddress(),
|
||||
return &paymenttypes.Money{
|
||||
Currency: m.GetCurrency(),
|
||||
Amount: m.GetAmount(),
|
||||
}
|
||||
}
|
||||
|
||||
func clonePair(pair *fxv1.CurrencyPair) *fxv1.CurrencyPair {
|
||||
func protoMoney(m *paymenttypes.Money) *moneyv1.Money {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
return &moneyv1.Money{
|
||||
Currency: m.GetCurrency(),
|
||||
Amount: m.GetAmount(),
|
||||
}
|
||||
}
|
||||
|
||||
func feePolicyFromProto(src *feesv1.PolicyOverrides) *paymenttypes.FeePolicy {
|
||||
if src == nil {
|
||||
return nil
|
||||
}
|
||||
return &paymenttypes.FeePolicy{
|
||||
InsufficientNet: insufficientPolicyFromProto(src.GetInsufficientNet()),
|
||||
}
|
||||
}
|
||||
|
||||
func feePolicyToProto(src *paymenttypes.FeePolicy) *feesv1.PolicyOverrides {
|
||||
if src == nil {
|
||||
return nil
|
||||
}
|
||||
return &feesv1.PolicyOverrides{
|
||||
InsufficientNet: insufficientPolicyToProto(src.InsufficientNet),
|
||||
}
|
||||
}
|
||||
|
||||
func insufficientPolicyFromProto(policy feesv1.InsufficientNetPolicy) paymenttypes.InsufficientNetPolicy {
|
||||
switch policy {
|
||||
case feesv1.InsufficientNetPolicy_BLOCK_POSTING:
|
||||
return paymenttypes.InsufficientNetBlockPosting
|
||||
case feesv1.InsufficientNetPolicy_SWEEP_ORG_CASH:
|
||||
return paymenttypes.InsufficientNetSweepOrgCash
|
||||
case feesv1.InsufficientNetPolicy_INVOICE_LATER:
|
||||
return paymenttypes.InsufficientNetInvoiceLater
|
||||
default:
|
||||
return paymenttypes.InsufficientNetUnspecified
|
||||
}
|
||||
}
|
||||
|
||||
func insufficientPolicyToProto(policy paymenttypes.InsufficientNetPolicy) feesv1.InsufficientNetPolicy {
|
||||
switch policy {
|
||||
case paymenttypes.InsufficientNetBlockPosting:
|
||||
return feesv1.InsufficientNetPolicy_BLOCK_POSTING
|
||||
case paymenttypes.InsufficientNetSweepOrgCash:
|
||||
return feesv1.InsufficientNetPolicy_SWEEP_ORG_CASH
|
||||
case paymenttypes.InsufficientNetInvoiceLater:
|
||||
return feesv1.InsufficientNetPolicy_INVOICE_LATER
|
||||
default:
|
||||
return feesv1.InsufficientNetPolicy_INSUFFICIENT_NET_UNSPECIFIED
|
||||
}
|
||||
}
|
||||
|
||||
func pairFromProto(pair *fxv1.CurrencyPair) *paymenttypes.CurrencyPair {
|
||||
if pair == nil {
|
||||
return nil
|
||||
}
|
||||
return &paymenttypes.CurrencyPair{
|
||||
Base: pair.GetBase(),
|
||||
Quote: pair.GetQuote(),
|
||||
}
|
||||
}
|
||||
|
||||
func pairToProto(pair *paymenttypes.CurrencyPair) *fxv1.CurrencyPair {
|
||||
if pair == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -468,22 +642,290 @@ func clonePair(pair *fxv1.CurrencyPair) *fxv1.CurrencyPair {
|
||||
}
|
||||
}
|
||||
|
||||
func cloneFXQuote(quote *oraclev1.Quote) *oraclev1.Quote {
|
||||
func fxSideFromProto(side fxv1.Side) paymenttypes.FXSide {
|
||||
switch side {
|
||||
case fxv1.Side_BUY_BASE_SELL_QUOTE:
|
||||
return paymenttypes.FXSideBuyBaseSellQuote
|
||||
case fxv1.Side_SELL_BASE_BUY_QUOTE:
|
||||
return paymenttypes.FXSideSellBaseBuyQuote
|
||||
default:
|
||||
return paymenttypes.FXSideUnspecified
|
||||
}
|
||||
}
|
||||
|
||||
func fxSideToProto(side paymenttypes.FXSide) fxv1.Side {
|
||||
switch side {
|
||||
case paymenttypes.FXSideBuyBaseSellQuote:
|
||||
return fxv1.Side_BUY_BASE_SELL_QUOTE
|
||||
case paymenttypes.FXSideSellBaseBuyQuote:
|
||||
return fxv1.Side_SELL_BASE_BUY_QUOTE
|
||||
default:
|
||||
return fxv1.Side_SIDE_UNSPECIFIED
|
||||
}
|
||||
}
|
||||
|
||||
func fxQuoteFromProto(quote *oraclev1.Quote) *paymenttypes.FXQuote {
|
||||
if quote == nil {
|
||||
return nil
|
||||
}
|
||||
if cloned, ok := proto.Clone(quote).(*oraclev1.Quote); ok {
|
||||
return cloned
|
||||
return &paymenttypes.FXQuote{
|
||||
QuoteRef: strings.TrimSpace(quote.GetQuoteRef()),
|
||||
Pair: pairFromProto(quote.GetPair()),
|
||||
Side: fxSideFromProto(quote.GetSide()),
|
||||
Price: decimalFromProto(quote.GetPrice()),
|
||||
BaseAmount: moneyFromProto(quote.GetBaseAmount()),
|
||||
QuoteAmount: moneyFromProto(quote.GetQuoteAmount()),
|
||||
ExpiresAtUnixMs: quote.GetExpiresAtUnixMs(),
|
||||
Provider: strings.TrimSpace(quote.GetProvider()),
|
||||
RateRef: strings.TrimSpace(quote.GetRateRef()),
|
||||
Firm: quote.GetFirm(),
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func cloneNetworkEstimate(resp *chainv1.EstimateTransferFeeResponse) *chainv1.EstimateTransferFeeResponse {
|
||||
func fxQuoteToProto(quote *paymenttypes.FXQuote) *oraclev1.Quote {
|
||||
if quote == nil {
|
||||
return nil
|
||||
}
|
||||
return &oraclev1.Quote{
|
||||
QuoteRef: strings.TrimSpace(quote.QuoteRef),
|
||||
Pair: pairToProto(quote.Pair),
|
||||
Side: fxSideToProto(quote.Side),
|
||||
Price: decimalToProto(quote.Price),
|
||||
BaseAmount: protoMoney(quote.BaseAmount),
|
||||
QuoteAmount: protoMoney(quote.QuoteAmount),
|
||||
ExpiresAtUnixMs: quote.ExpiresAtUnixMs,
|
||||
Provider: strings.TrimSpace(quote.Provider),
|
||||
RateRef: strings.TrimSpace(quote.RateRef),
|
||||
Firm: quote.Firm,
|
||||
}
|
||||
}
|
||||
|
||||
func decimalFromProto(value *moneyv1.Decimal) *paymenttypes.Decimal {
|
||||
if value == nil {
|
||||
return nil
|
||||
}
|
||||
return &paymenttypes.Decimal{Value: value.GetValue()}
|
||||
}
|
||||
|
||||
func decimalToProto(value *paymenttypes.Decimal) *moneyv1.Decimal {
|
||||
if value == nil {
|
||||
return nil
|
||||
}
|
||||
return &moneyv1.Decimal{Value: value.GetValue()}
|
||||
}
|
||||
|
||||
func assetFromProto(asset *chainv1.Asset) *paymenttypes.Asset {
|
||||
if asset == nil {
|
||||
return nil
|
||||
}
|
||||
return &paymenttypes.Asset{
|
||||
Chain: chainNetworkName(asset.GetChain()),
|
||||
TokenSymbol: asset.GetTokenSymbol(),
|
||||
ContractAddress: asset.GetContractAddress(),
|
||||
}
|
||||
}
|
||||
|
||||
func assetToProto(asset *paymenttypes.Asset) *chainv1.Asset {
|
||||
if asset == nil {
|
||||
return nil
|
||||
}
|
||||
return &chainv1.Asset{
|
||||
Chain: chainNetworkFromName(asset.Chain),
|
||||
TokenSymbol: asset.TokenSymbol,
|
||||
ContractAddress: asset.ContractAddress,
|
||||
}
|
||||
}
|
||||
|
||||
func networkFeeFromProto(resp *chainv1.EstimateTransferFeeResponse) *paymenttypes.NetworkFeeEstimate {
|
||||
if resp == nil {
|
||||
return nil
|
||||
}
|
||||
if cloned, ok := proto.Clone(resp).(*chainv1.EstimateTransferFeeResponse); ok {
|
||||
return cloned
|
||||
return &paymenttypes.NetworkFeeEstimate{
|
||||
NetworkFee: moneyFromProto(resp.GetNetworkFee()),
|
||||
EstimationContext: strings.TrimSpace(resp.GetEstimationContext()),
|
||||
}
|
||||
}
|
||||
|
||||
func networkFeeToProto(resp *paymenttypes.NetworkFeeEstimate) *chainv1.EstimateTransferFeeResponse {
|
||||
if resp == nil {
|
||||
return nil
|
||||
}
|
||||
return &chainv1.EstimateTransferFeeResponse{
|
||||
NetworkFee: protoMoney(resp.NetworkFee),
|
||||
EstimationContext: strings.TrimSpace(resp.EstimationContext),
|
||||
}
|
||||
}
|
||||
|
||||
func feeLinesFromProto(lines []*feesv1.DerivedPostingLine) []*paymenttypes.FeeLine {
|
||||
if len(lines) == 0 {
|
||||
return nil
|
||||
}
|
||||
result := make([]*paymenttypes.FeeLine, 0, len(lines))
|
||||
for _, line := range lines {
|
||||
if line == nil {
|
||||
continue
|
||||
}
|
||||
result = append(result, &paymenttypes.FeeLine{
|
||||
LedgerAccountRef: strings.TrimSpace(line.GetLedgerAccountRef()),
|
||||
Money: moneyFromProto(line.GetMoney()),
|
||||
LineType: postingLineTypeFromProto(line.GetLineType()),
|
||||
Side: entrySideFromProto(line.GetSide()),
|
||||
Meta: cloneMetadata(line.GetMeta()),
|
||||
})
|
||||
}
|
||||
if len(result) == 0 {
|
||||
return nil
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func feeLinesToProto(lines []*paymenttypes.FeeLine) []*feesv1.DerivedPostingLine {
|
||||
if len(lines) == 0 {
|
||||
return nil
|
||||
}
|
||||
result := make([]*feesv1.DerivedPostingLine, 0, len(lines))
|
||||
for _, line := range lines {
|
||||
if line == nil {
|
||||
continue
|
||||
}
|
||||
result = append(result, &feesv1.DerivedPostingLine{
|
||||
LedgerAccountRef: strings.TrimSpace(line.LedgerAccountRef),
|
||||
Money: protoMoney(line.Money),
|
||||
LineType: postingLineTypeToProto(line.LineType),
|
||||
Side: entrySideToProto(line.Side),
|
||||
Meta: cloneMetadata(line.Meta),
|
||||
})
|
||||
}
|
||||
if len(result) == 0 {
|
||||
return nil
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func feeRulesFromProto(rules []*feesv1.AppliedRule) []*paymenttypes.AppliedRule {
|
||||
if len(rules) == 0 {
|
||||
return nil
|
||||
}
|
||||
result := make([]*paymenttypes.AppliedRule, 0, len(rules))
|
||||
for _, rule := range rules {
|
||||
if rule == nil {
|
||||
continue
|
||||
}
|
||||
result = append(result, &paymenttypes.AppliedRule{
|
||||
RuleID: strings.TrimSpace(rule.GetRuleId()),
|
||||
RuleVersion: strings.TrimSpace(rule.GetRuleVersion()),
|
||||
Formula: strings.TrimSpace(rule.GetFormula()),
|
||||
Rounding: roundingModeFromProto(rule.GetRounding()),
|
||||
TaxCode: strings.TrimSpace(rule.GetTaxCode()),
|
||||
TaxRate: strings.TrimSpace(rule.GetTaxRate()),
|
||||
Parameters: cloneMetadata(rule.GetParameters()),
|
||||
})
|
||||
}
|
||||
if len(result) == 0 {
|
||||
return nil
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func feeRulesToProto(rules []*paymenttypes.AppliedRule) []*feesv1.AppliedRule {
|
||||
if len(rules) == 0 {
|
||||
return nil
|
||||
}
|
||||
result := make([]*feesv1.AppliedRule, 0, len(rules))
|
||||
for _, rule := range rules {
|
||||
if rule == nil {
|
||||
continue
|
||||
}
|
||||
result = append(result, &feesv1.AppliedRule{
|
||||
RuleId: strings.TrimSpace(rule.RuleID),
|
||||
RuleVersion: strings.TrimSpace(rule.RuleVersion),
|
||||
Formula: strings.TrimSpace(rule.Formula),
|
||||
Rounding: roundingModeToProto(rule.Rounding),
|
||||
TaxCode: strings.TrimSpace(rule.TaxCode),
|
||||
TaxRate: strings.TrimSpace(rule.TaxRate),
|
||||
Parameters: cloneMetadata(rule.Parameters),
|
||||
})
|
||||
}
|
||||
if len(result) == 0 {
|
||||
return nil
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func entrySideFromProto(side accountingv1.EntrySide) paymenttypes.EntrySide {
|
||||
switch side {
|
||||
case accountingv1.EntrySide_ENTRY_SIDE_DEBIT:
|
||||
return paymenttypes.EntrySideDebit
|
||||
case accountingv1.EntrySide_ENTRY_SIDE_CREDIT:
|
||||
return paymenttypes.EntrySideCredit
|
||||
default:
|
||||
return paymenttypes.EntrySideUnspecified
|
||||
}
|
||||
}
|
||||
|
||||
func entrySideToProto(side paymenttypes.EntrySide) accountingv1.EntrySide {
|
||||
switch side {
|
||||
case paymenttypes.EntrySideDebit:
|
||||
return accountingv1.EntrySide_ENTRY_SIDE_DEBIT
|
||||
case paymenttypes.EntrySideCredit:
|
||||
return accountingv1.EntrySide_ENTRY_SIDE_CREDIT
|
||||
default:
|
||||
return accountingv1.EntrySide_ENTRY_SIDE_UNSPECIFIED
|
||||
}
|
||||
}
|
||||
|
||||
func postingLineTypeFromProto(lineType accountingv1.PostingLineType) paymenttypes.PostingLineType {
|
||||
switch lineType {
|
||||
case accountingv1.PostingLineType_POSTING_LINE_FEE:
|
||||
return paymenttypes.PostingLineTypeFee
|
||||
case accountingv1.PostingLineType_POSTING_LINE_TAX:
|
||||
return paymenttypes.PostingLineTypeTax
|
||||
case accountingv1.PostingLineType_POSTING_LINE_SPREAD:
|
||||
return paymenttypes.PostingLineTypeSpread
|
||||
case accountingv1.PostingLineType_POSTING_LINE_REVERSAL:
|
||||
return paymenttypes.PostingLineTypeReversal
|
||||
default:
|
||||
return paymenttypes.PostingLineTypeUnspecified
|
||||
}
|
||||
}
|
||||
|
||||
func postingLineTypeToProto(lineType paymenttypes.PostingLineType) accountingv1.PostingLineType {
|
||||
switch lineType {
|
||||
case paymenttypes.PostingLineTypeFee:
|
||||
return accountingv1.PostingLineType_POSTING_LINE_FEE
|
||||
case paymenttypes.PostingLineTypeTax:
|
||||
return accountingv1.PostingLineType_POSTING_LINE_TAX
|
||||
case paymenttypes.PostingLineTypeSpread:
|
||||
return accountingv1.PostingLineType_POSTING_LINE_SPREAD
|
||||
case paymenttypes.PostingLineTypeReversal:
|
||||
return accountingv1.PostingLineType_POSTING_LINE_REVERSAL
|
||||
default:
|
||||
return accountingv1.PostingLineType_POSTING_LINE_TYPE_UNSPECIFIED
|
||||
}
|
||||
}
|
||||
|
||||
func roundingModeFromProto(mode moneyv1.RoundingMode) paymenttypes.RoundingMode {
|
||||
switch mode {
|
||||
case moneyv1.RoundingMode_ROUND_HALF_EVEN:
|
||||
return paymenttypes.RoundingModeHalfEven
|
||||
case moneyv1.RoundingMode_ROUND_HALF_UP:
|
||||
return paymenttypes.RoundingModeHalfUp
|
||||
case moneyv1.RoundingMode_ROUND_DOWN:
|
||||
return paymenttypes.RoundingModeDown
|
||||
default:
|
||||
return paymenttypes.RoundingModeUnspecified
|
||||
}
|
||||
}
|
||||
|
||||
func roundingModeToProto(mode paymenttypes.RoundingMode) moneyv1.RoundingMode {
|
||||
switch mode {
|
||||
case paymenttypes.RoundingModeHalfEven:
|
||||
return moneyv1.RoundingMode_ROUND_HALF_EVEN
|
||||
case paymenttypes.RoundingModeHalfUp:
|
||||
return moneyv1.RoundingMode_ROUND_HALF_UP
|
||||
case paymenttypes.RoundingModeDown:
|
||||
return moneyv1.RoundingMode_ROUND_DOWN
|
||||
default:
|
||||
return moneyv1.RoundingMode_ROUNDING_MODE_UNSPECIFIED
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
package orchestrator
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
paymenttypes "github.com/tech/sendico/pkg/payments/types"
|
||||
feesv1 "github.com/tech/sendico/pkg/proto/billing/fees/v1"
|
||||
accountingv1 "github.com/tech/sendico/pkg/proto/common/accounting/v1"
|
||||
fxv1 "github.com/tech/sendico/pkg/proto/common/fx/v1"
|
||||
moneyv1 "github.com/tech/sendico/pkg/proto/common/money/v1"
|
||||
chainv1 "github.com/tech/sendico/pkg/proto/gateway/chain/v1"
|
||||
oraclev1 "github.com/tech/sendico/pkg/proto/oracle/v1"
|
||||
)
|
||||
|
||||
func TestMoneyConversionRoundTrip(t *testing.T) {
|
||||
proto := &moneyv1.Money{Currency: "USD", Amount: "12.34"}
|
||||
model := moneyFromProto(proto)
|
||||
if model == nil || model.Currency != "USD" || model.Amount != "12.34" {
|
||||
t.Fatalf("moneyFromProto mismatch: %#v", model)
|
||||
}
|
||||
back := protoMoney(model)
|
||||
if back == nil || back.GetCurrency() != "USD" || back.GetAmount() != "12.34" {
|
||||
t.Fatalf("protoMoney mismatch: %#v", back)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeePolicyConversionRoundTrip(t *testing.T) {
|
||||
proto := &feesv1.PolicyOverrides{InsufficientNet: feesv1.InsufficientNetPolicy_SWEEP_ORG_CASH}
|
||||
model := feePolicyFromProto(proto)
|
||||
if model == nil || model.InsufficientNet != paymenttypes.InsufficientNetSweepOrgCash {
|
||||
t.Fatalf("feePolicyFromProto mismatch: %#v", model)
|
||||
}
|
||||
back := feePolicyToProto(model)
|
||||
if back == nil || back.GetInsufficientNet() != feesv1.InsufficientNetPolicy_SWEEP_ORG_CASH {
|
||||
t.Fatalf("feePolicyToProto mismatch: %#v", back)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFeeLineConversionRoundTrip(t *testing.T) {
|
||||
protoLine := &feesv1.DerivedPostingLine{
|
||||
LedgerAccountRef: "ledger:fees",
|
||||
Money: &moneyv1.Money{Currency: "EUR", Amount: "1.00"},
|
||||
LineType: accountingv1.PostingLineType_POSTING_LINE_FEE,
|
||||
Side: accountingv1.EntrySide_ENTRY_SIDE_DEBIT,
|
||||
Meta: map[string]string{"k": "v"},
|
||||
}
|
||||
modelLines := feeLinesFromProto([]*feesv1.DerivedPostingLine{protoLine})
|
||||
if len(modelLines) != 1 {
|
||||
t.Fatalf("expected 1 model line, got %d", len(modelLines))
|
||||
}
|
||||
modelLine := modelLines[0]
|
||||
if modelLine.LedgerAccountRef != "ledger:fees" || modelLine.Money.GetCurrency() != "EUR" || modelLine.Money.GetAmount() != "1.00" {
|
||||
t.Fatalf("model line mismatch: %#v", modelLine)
|
||||
}
|
||||
if modelLine.LineType != paymenttypes.PostingLineTypeFee || modelLine.Side != paymenttypes.EntrySideDebit {
|
||||
t.Fatalf("model line enums mismatch: %#v", modelLine)
|
||||
}
|
||||
back := feeLinesToProto(modelLines)
|
||||
if len(back) != 1 {
|
||||
t.Fatalf("expected 1 proto line, got %d", len(back))
|
||||
}
|
||||
protoBack := back[0]
|
||||
if protoBack.GetLedgerAccountRef() != "ledger:fees" || protoBack.GetMoney().GetCurrency() != "EUR" || protoBack.GetMoney().GetAmount() != "1.00" {
|
||||
t.Fatalf("proto line mismatch: %#v", protoBack)
|
||||
}
|
||||
if protoBack.GetLineType() != accountingv1.PostingLineType_POSTING_LINE_FEE || protoBack.GetSide() != accountingv1.EntrySide_ENTRY_SIDE_DEBIT {
|
||||
t.Fatalf("proto line enums mismatch: %#v", protoBack)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFXQuoteConversionRoundTrip(t *testing.T) {
|
||||
proto := &oraclev1.Quote{
|
||||
QuoteRef: "q1",
|
||||
Pair: &fxv1.CurrencyPair{Base: "USD", Quote: "EUR"},
|
||||
Side: fxv1.Side_SELL_BASE_BUY_QUOTE,
|
||||
Price: &moneyv1.Decimal{Value: "0.9"},
|
||||
BaseAmount: &moneyv1.Money{Currency: "USD", Amount: "100"},
|
||||
QuoteAmount: &moneyv1.Money{Currency: "EUR", Amount: "90"},
|
||||
ExpiresAtUnixMs: 1700000000000,
|
||||
Provider: "provider",
|
||||
RateRef: "rate",
|
||||
Firm: true,
|
||||
}
|
||||
model := fxQuoteFromProto(proto)
|
||||
if model == nil || model.QuoteRef != "q1" || model.Pair.GetBase() != "USD" || model.Pair.GetQuote() != "EUR" {
|
||||
t.Fatalf("fxQuoteFromProto mismatch: %#v", model)
|
||||
}
|
||||
if model.Side != paymenttypes.FXSideSellBaseBuyQuote || model.Price.GetValue() != "0.9" {
|
||||
t.Fatalf("fxQuoteFromProto enums mismatch: %#v", model)
|
||||
}
|
||||
back := fxQuoteToProto(model)
|
||||
if back == nil || back.GetQuoteRef() != "q1" || back.GetPair().GetBase() != "USD" || back.GetPair().GetQuote() != "EUR" {
|
||||
t.Fatalf("fxQuoteToProto mismatch: %#v", back)
|
||||
}
|
||||
if back.GetSide() != fxv1.Side_SELL_BASE_BUY_QUOTE || back.GetPrice().GetValue() != "0.9" {
|
||||
t.Fatalf("fxQuoteToProto enums mismatch: %#v", back)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssetConversionRoundTrip(t *testing.T) {
|
||||
proto := &chainv1.Asset{
|
||||
Chain: chainv1.ChainNetwork_CHAIN_NETWORK_TRON_MAINNET,
|
||||
TokenSymbol: "USDT",
|
||||
ContractAddress: "0xabc",
|
||||
}
|
||||
model := assetFromProto(proto)
|
||||
if model == nil || model.Chain != "TRON" || model.TokenSymbol != "USDT" || model.ContractAddress != "0xabc" {
|
||||
t.Fatalf("assetFromProto mismatch: %#v", model)
|
||||
}
|
||||
back := assetToProto(model)
|
||||
if back == nil || back.GetChain() != chainv1.ChainNetwork_CHAIN_NETWORK_TRON_MAINNET || back.GetTokenSymbol() != "USDT" || back.GetContractAddress() != "0xabc" {
|
||||
t.Fatalf("assetToProto mismatch: %#v", back)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package orchestrator
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/tech/sendico/payments/orchestrator/storage/model"
|
||||
"github.com/tech/sendico/pkg/discovery"
|
||||
"github.com/tech/sendico/pkg/mlogger"
|
||||
)
|
||||
|
||||
type discoveryGatewayRegistry struct {
|
||||
logger mlogger.Logger
|
||||
registry *discovery.Registry
|
||||
}
|
||||
|
||||
func NewDiscoveryGatewayRegistry(logger mlogger.Logger, registry *discovery.Registry) GatewayRegistry {
|
||||
if registry == nil {
|
||||
return nil
|
||||
}
|
||||
if logger != nil {
|
||||
logger = logger.Named("discovery_gateway_registry")
|
||||
}
|
||||
return &discoveryGatewayRegistry{
|
||||
logger: logger,
|
||||
registry: registry,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *discoveryGatewayRegistry) List(_ context.Context) ([]*model.GatewayInstanceDescriptor, error) {
|
||||
if r == nil || r.registry == nil {
|
||||
return nil, nil
|
||||
}
|
||||
entries := r.registry.List(time.Now(), true)
|
||||
items := make([]*model.GatewayInstanceDescriptor, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
if entry.Rail == "" {
|
||||
continue
|
||||
}
|
||||
rail := railFromDiscovery(entry.Rail)
|
||||
if rail == model.RailUnspecified {
|
||||
continue
|
||||
}
|
||||
items = append(items, &model.GatewayInstanceDescriptor{
|
||||
ID: entry.ID,
|
||||
InstanceID: entry.InstanceID,
|
||||
Rail: rail,
|
||||
Network: entry.Network,
|
||||
Currencies: normalizeCurrencies(entry.Currencies),
|
||||
Capabilities: capabilitiesFromOps(entry.Operations),
|
||||
Limits: limitsFromDiscovery(entry.Limits),
|
||||
Version: entry.Version,
|
||||
IsEnabled: entry.Healthy,
|
||||
})
|
||||
}
|
||||
sort.Slice(items, func(i, j int) bool {
|
||||
return items[i].ID < items[j].ID
|
||||
})
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func railFromDiscovery(value string) model.Rail {
|
||||
switch strings.ToUpper(strings.TrimSpace(value)) {
|
||||
case string(model.RailCrypto):
|
||||
return model.RailCrypto
|
||||
case string(model.RailProviderSettlement):
|
||||
return model.RailProviderSettlement
|
||||
case string(model.RailLedger):
|
||||
return model.RailLedger
|
||||
case string(model.RailCardPayout):
|
||||
return model.RailCardPayout
|
||||
case string(model.RailFiatOnRamp):
|
||||
return model.RailFiatOnRamp
|
||||
default:
|
||||
return model.RailUnspecified
|
||||
}
|
||||
}
|
||||
|
||||
func capabilitiesFromOps(ops []string) model.RailCapabilities {
|
||||
var cap model.RailCapabilities
|
||||
for _, op := range ops {
|
||||
switch strings.ToLower(strings.TrimSpace(op)) {
|
||||
case "payin.crypto", "payin.card", "payin.fiat":
|
||||
cap.CanPayIn = true
|
||||
case "payout.crypto", "payout.card", "payout.fiat":
|
||||
cap.CanPayOut = true
|
||||
case "balance.read":
|
||||
cap.CanReadBalance = true
|
||||
case "fee.send":
|
||||
cap.CanSendFee = true
|
||||
case "observe.confirm", "observe.confirmation":
|
||||
cap.RequiresObserveConfirm = true
|
||||
}
|
||||
}
|
||||
return cap
|
||||
}
|
||||
|
||||
func limitsFromDiscovery(src *discovery.Limits) model.Limits {
|
||||
if src == nil {
|
||||
return model.Limits{}
|
||||
}
|
||||
limits := model.Limits{
|
||||
MinAmount: strings.TrimSpace(src.MinAmount),
|
||||
MaxAmount: strings.TrimSpace(src.MaxAmount),
|
||||
VolumeLimit: map[string]string{},
|
||||
VelocityLimit: map[string]int{},
|
||||
}
|
||||
for key, value := range src.VolumeLimit {
|
||||
k := strings.TrimSpace(key)
|
||||
v := strings.TrimSpace(value)
|
||||
if k == "" || v == "" {
|
||||
continue
|
||||
}
|
||||
limits.VolumeLimit[k] = v
|
||||
}
|
||||
for key, value := range src.VelocityLimit {
|
||||
k := strings.TrimSpace(key)
|
||||
if k == "" {
|
||||
continue
|
||||
}
|
||||
limits.VelocityLimit[k] = value
|
||||
}
|
||||
if len(limits.VolumeLimit) == 0 {
|
||||
limits.VolumeLimit = nil
|
||||
}
|
||||
if len(limits.VelocityLimit) == 0 {
|
||||
limits.VelocityLimit = nil
|
||||
}
|
||||
return limits
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package orchestrator
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/tech/sendico/payments/orchestrator/storage/model"
|
||||
chainv1 "github.com/tech/sendico/pkg/proto/gateway/chain/v1"
|
||||
)
|
||||
|
||||
const (
|
||||
executionStepMetadataRole = "role"
|
||||
executionStepMetadataStatus = "status"
|
||||
|
||||
executionStepRoleSource = "source"
|
||||
executionStepRoleConsumer = "consumer"
|
||||
|
||||
executionStepStatusPlanned = "planned"
|
||||
executionStepStatusSubmitted = "submitted"
|
||||
executionStepStatusConfirmed = "confirmed"
|
||||
executionStepStatusFailed = "failed"
|
||||
executionStepStatusCancelled = "cancelled"
|
||||
executionStepStatusSkipped = "skipped"
|
||||
)
|
||||
|
||||
func setExecutionStepRole(step *model.ExecutionStep, role string) {
|
||||
role = strings.ToLower(strings.TrimSpace(role))
|
||||
setExecutionStepMetadata(step, executionStepMetadataRole, role)
|
||||
}
|
||||
|
||||
func setExecutionStepStatus(step *model.ExecutionStep, status string) {
|
||||
status = strings.ToLower(strings.TrimSpace(status))
|
||||
setExecutionStepMetadata(step, executionStepMetadataStatus, status)
|
||||
}
|
||||
|
||||
func executionStepRole(step *model.ExecutionStep) string {
|
||||
if step == nil {
|
||||
return ""
|
||||
}
|
||||
if role := strings.TrimSpace(step.Metadata[executionStepMetadataRole]); role != "" {
|
||||
return strings.ToLower(role)
|
||||
}
|
||||
if strings.EqualFold(step.Code, stepCodeCardPayout) {
|
||||
return executionStepRoleConsumer
|
||||
}
|
||||
return executionStepRoleSource
|
||||
}
|
||||
|
||||
func executionStepStatus(step *model.ExecutionStep) string {
|
||||
if step == nil {
|
||||
return ""
|
||||
}
|
||||
status := strings.TrimSpace(step.Metadata[executionStepMetadataStatus])
|
||||
if status == "" {
|
||||
return executionStepStatusPlanned
|
||||
}
|
||||
return strings.ToLower(status)
|
||||
}
|
||||
|
||||
func isSourceExecutionStep(step *model.ExecutionStep) bool {
|
||||
return executionStepRole(step) == executionStepRoleSource
|
||||
}
|
||||
|
||||
func isConsumerExecutionStep(step *model.ExecutionStep) bool {
|
||||
return executionStepRole(step) == executionStepRoleConsumer
|
||||
}
|
||||
|
||||
func sourceStepsConfirmed(plan *model.ExecutionPlan) bool {
|
||||
if plan == nil || len(plan.Steps) == 0 {
|
||||
return false
|
||||
}
|
||||
hasSource := false
|
||||
for _, step := range plan.Steps {
|
||||
if step == nil || !isSourceExecutionStep(step) {
|
||||
continue
|
||||
}
|
||||
status := executionStepStatus(step)
|
||||
if status == executionStepStatusSkipped {
|
||||
continue
|
||||
}
|
||||
hasSource = true
|
||||
if status != executionStepStatusConfirmed {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return hasSource
|
||||
}
|
||||
|
||||
func findExecutionStepByTransferRef(plan *model.ExecutionPlan, transferRef string) *model.ExecutionStep {
|
||||
if plan == nil {
|
||||
return nil
|
||||
}
|
||||
transferRef = strings.TrimSpace(transferRef)
|
||||
if transferRef == "" {
|
||||
return nil
|
||||
}
|
||||
for _, step := range plan.Steps {
|
||||
if step == nil {
|
||||
continue
|
||||
}
|
||||
if strings.EqualFold(strings.TrimSpace(step.TransferRef), transferRef) {
|
||||
return step
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func updateExecutionStepFromTransfer(plan *model.ExecutionPlan, event *chainv1.TransferStatusChangedEvent) *model.ExecutionStep {
|
||||
if plan == nil || event == nil || event.GetTransfer() == nil {
|
||||
return nil
|
||||
}
|
||||
transfer := event.GetTransfer()
|
||||
transferRef := strings.TrimSpace(transfer.GetTransferRef())
|
||||
if transferRef == "" {
|
||||
return nil
|
||||
}
|
||||
step := findExecutionStepByTransferRef(plan, transferRef)
|
||||
if step == nil {
|
||||
return nil
|
||||
}
|
||||
if step.TransferRef == "" {
|
||||
step.TransferRef = transferRef
|
||||
}
|
||||
if status := executionStepStatusFromTransferStatus(transfer.GetStatus()); status != "" {
|
||||
setExecutionStepStatus(step, status)
|
||||
}
|
||||
return step
|
||||
}
|
||||
|
||||
func executionStepStatusFromTransferStatus(status chainv1.TransferStatus) string {
|
||||
switch status {
|
||||
case chainv1.TransferStatus_TRANSFER_CONFIRMED:
|
||||
return executionStepStatusConfirmed
|
||||
case chainv1.TransferStatus_TRANSFER_FAILED:
|
||||
return executionStepStatusFailed
|
||||
case chainv1.TransferStatus_TRANSFER_CANCELLED:
|
||||
return executionStepStatusCancelled
|
||||
case chainv1.TransferStatus_TRANSFER_SIGNING,
|
||||
chainv1.TransferStatus_TRANSFER_PENDING,
|
||||
chainv1.TransferStatus_TRANSFER_SUBMITTED:
|
||||
return executionStepStatusSubmitted
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func setExecutionStepMetadata(step *model.ExecutionStep, key, value string) {
|
||||
if step == nil {
|
||||
return
|
||||
}
|
||||
key = strings.TrimSpace(key)
|
||||
if key == "" {
|
||||
return
|
||||
}
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
if step.Metadata != nil {
|
||||
delete(step.Metadata, key)
|
||||
if len(step.Metadata) == 0 {
|
||||
step.Metadata = nil
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
if step.Metadata == nil {
|
||||
step.Metadata = map[string]string{}
|
||||
}
|
||||
step.Metadata[key] = value
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package orchestrator
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
paymodel "github.com/tech/sendico/payments/orchestrator/storage/model"
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
cons "github.com/tech/sendico/pkg/messaging/consumer"
|
||||
paymentgateway "github.com/tech/sendico/pkg/messaging/notifications/paymentgateway"
|
||||
np "github.com/tech/sendico/pkg/messaging/notifications/processor"
|
||||
"github.com/tech/sendico/pkg/model"
|
||||
"github.com/tech/sendico/pkg/mservice"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func (s *Service) startGatewayConsumers() {
|
||||
if s == nil || s.gatewayBroker == nil {
|
||||
return
|
||||
}
|
||||
processor := paymentgateway.NewPaymentGatewayExecutionProcessor(s.logger, s.onGatewayExecution)
|
||||
s.consumeGatewayProcessor(processor)
|
||||
}
|
||||
|
||||
func (s *Service) consumeGatewayProcessor(processor np.EnvelopeProcessor) {
|
||||
consumer, err := cons.NewConsumer(s.logger, s.gatewayBroker, processor.GetSubject())
|
||||
if err != nil {
|
||||
s.logger.Warn("Failed to create payment gateway consumer", zap.Error(err), zap.String("event", processor.GetSubject().ToString()))
|
||||
return
|
||||
}
|
||||
s.gatewayConsumers = append(s.gatewayConsumers, consumer)
|
||||
go func() {
|
||||
if err := consumer.ConsumeMessages(processor.Process); err != nil {
|
||||
s.logger.Warn("Payment gateway consumer stopped", zap.Error(err), zap.String("event", processor.GetSubject().ToString()))
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (s *Service) onGatewayExecution(ctx context.Context, exec *model.PaymentGatewayExecution) error {
|
||||
if exec == nil {
|
||||
return merrors.InvalidArgument("payment gateway execution is nil", "execution")
|
||||
}
|
||||
paymentRef := strings.TrimSpace(exec.PaymentIntentID)
|
||||
if paymentRef == "" {
|
||||
return merrors.InvalidArgument("payment_intent_id is required", "payment_intent_id")
|
||||
}
|
||||
if s.storage == nil || s.storage.Payments() == nil {
|
||||
return errStorageUnavailable
|
||||
}
|
||||
store := s.storage.Payments()
|
||||
payment, err := store.GetByPaymentRef(ctx, paymentRef)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if payment.Metadata == nil {
|
||||
payment.Metadata = map[string]string{}
|
||||
}
|
||||
if exec.RequestID != "" {
|
||||
payment.Metadata["gateway_request_id"] = exec.RequestID
|
||||
}
|
||||
if exec.QuoteRef != "" {
|
||||
payment.Metadata["gateway_quote_ref"] = exec.QuoteRef
|
||||
}
|
||||
if exec.ExecutedMoney != nil {
|
||||
payment.Metadata["gateway_executed_amount"] = exec.ExecutedMoney.Amount
|
||||
payment.Metadata["gateway_executed_currency"] = exec.ExecutedMoney.Currency
|
||||
}
|
||||
payment.Metadata["gateway_confirmation_status"] = string(exec.Status)
|
||||
|
||||
updatedPlan := updateExecutionStepsFromGatewayExecution(payment, exec)
|
||||
switch exec.Status {
|
||||
case model.ConfirmationStatusConfirmed, model.ConfirmationStatusClarified:
|
||||
if payment.PaymentPlan != nil && updatedPlan && payment.ExecutionPlan != nil && !executionPlanComplete(payment.ExecutionPlan) {
|
||||
return s.resumePaymentPlan(ctx, store, payment)
|
||||
}
|
||||
payment.State = paymodel.PaymentStateSettled
|
||||
payment.FailureCode = paymodel.PaymentFailureCodeUnspecified
|
||||
payment.FailureReason = ""
|
||||
case model.ConfirmationStatusRejected:
|
||||
payment.State = paymodel.PaymentStateFailed
|
||||
payment.FailureCode = paymodel.PaymentFailureCodePolicy
|
||||
payment.FailureReason = "gateway_rejected"
|
||||
case model.ConfirmationStatusTimeout:
|
||||
payment.State = paymodel.PaymentStateFailed
|
||||
payment.FailureCode = paymodel.PaymentFailureCodePolicy
|
||||
payment.FailureReason = "confirmation_timeout"
|
||||
default:
|
||||
s.logger.Warn("Unhandled gateway confirmation status", zap.String("status", string(exec.Status)), zap.String("payment_ref", paymentRef))
|
||||
}
|
||||
if err := store.Update(ctx, payment); err != nil {
|
||||
return err
|
||||
}
|
||||
s.logger.Info("Payment gateway execution applied", zap.String("payment_ref", paymentRef), zap.String("status", string(exec.Status)), zap.String("service", string(mservice.PaymentGateway)))
|
||||
return nil
|
||||
}
|
||||
|
||||
func updateExecutionStepsFromGatewayExecution(payment *paymodel.Payment, exec *model.PaymentGatewayExecution) bool {
|
||||
if payment == nil || exec == nil || payment.PaymentPlan == nil {
|
||||
return false
|
||||
}
|
||||
requestID := strings.TrimSpace(exec.RequestID)
|
||||
if requestID == "" {
|
||||
return false
|
||||
}
|
||||
execPlan := ensureExecutionPlanForPlan(payment, payment.PaymentPlan)
|
||||
if execPlan == nil {
|
||||
return false
|
||||
}
|
||||
status := executionStepStatusFromGatewayStatus(exec.Status)
|
||||
if status == "" {
|
||||
return false
|
||||
}
|
||||
updated := false
|
||||
for idx, planStep := range payment.PaymentPlan.Steps {
|
||||
if planStep == nil {
|
||||
continue
|
||||
}
|
||||
if idx >= len(execPlan.Steps) {
|
||||
continue
|
||||
}
|
||||
execStep := execPlan.Steps[idx]
|
||||
if execStep == nil {
|
||||
execStep = &paymodel.ExecutionStep{Code: planStepID(planStep, idx), Description: describePlanStep(planStep)}
|
||||
execPlan.Steps[idx] = execStep
|
||||
}
|
||||
if strings.EqualFold(strings.TrimSpace(execStep.TransferRef), requestID) {
|
||||
setExecutionStepStatus(execStep, status)
|
||||
updated = true
|
||||
continue
|
||||
}
|
||||
if execStep.TransferRef == "" && planStep.Rail == paymodel.RailProviderSettlement {
|
||||
if planStep.Action == paymodel.RailOperationObserveConfirm || planStep.Action == paymodel.RailOperationSend {
|
||||
execStep.TransferRef = requestID
|
||||
setExecutionStepStatus(execStep, status)
|
||||
updated = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return updated
|
||||
}
|
||||
|
||||
func executionStepStatusFromGatewayStatus(status model.ConfirmationStatus) string {
|
||||
switch status {
|
||||
case model.ConfirmationStatusConfirmed, model.ConfirmationStatusClarified:
|
||||
return executionStepStatusConfirmed
|
||||
case model.ConfirmationStatusRejected, model.ConfirmationStatusTimeout:
|
||||
return executionStepStatusFailed
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) Shutdown() {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
for _, consumer := range s.gatewayConsumers {
|
||||
if consumer != nil {
|
||||
consumer.Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package orchestrator
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
paymodel "github.com/tech/sendico/payments/orchestrator/storage/model"
|
||||
mloggerfactory "github.com/tech/sendico/pkg/mlogger/factory"
|
||||
"github.com/tech/sendico/pkg/model"
|
||||
)
|
||||
|
||||
func TestGatewayExecutionConfirmedUpdatesPayment(t *testing.T) {
|
||||
logger := mloggerfactory.NewLogger(false)
|
||||
store := newHelperPaymentStore()
|
||||
payment := &paymodel.Payment{PaymentRef: "pi-1", State: paymodel.PaymentStateSubmitted}
|
||||
if err := store.Create(context.Background(), payment); err != nil {
|
||||
t.Fatalf("failed to seed payment: %v", err)
|
||||
}
|
||||
svc := &Service{
|
||||
logger: logger,
|
||||
storage: stubRepo{payments: store},
|
||||
}
|
||||
exec := &model.PaymentGatewayExecution{
|
||||
PaymentIntentID: "pi-1",
|
||||
Status: model.ConfirmationStatusConfirmed,
|
||||
RequestID: "req-1",
|
||||
QuoteRef: "quote-1",
|
||||
}
|
||||
if err := svc.onGatewayExecution(context.Background(), exec); err != nil {
|
||||
t.Fatalf("onGatewayExecution error: %v", err)
|
||||
}
|
||||
updated, _ := store.GetByPaymentRef(context.Background(), "pi-1")
|
||||
if updated.State != paymodel.PaymentStateSettled {
|
||||
t.Fatalf("expected payment settled, got %s", updated.State)
|
||||
}
|
||||
if updated.Metadata["gateway_request_id"] != "req-1" {
|
||||
t.Fatalf("expected gateway_request_id metadata")
|
||||
}
|
||||
if updated.Metadata["gateway_confirmation_status"] != string(model.ConfirmationStatusConfirmed) {
|
||||
t.Fatalf("expected gateway_confirmation_status metadata")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayExecutionRejectedFailsPayment(t *testing.T) {
|
||||
logger := mloggerfactory.NewLogger(false)
|
||||
store := newHelperPaymentStore()
|
||||
payment := &paymodel.Payment{PaymentRef: "pi-2", State: paymodel.PaymentStateSubmitted}
|
||||
if err := store.Create(context.Background(), payment); err != nil {
|
||||
t.Fatalf("failed to seed payment: %v", err)
|
||||
}
|
||||
svc := &Service{
|
||||
logger: logger,
|
||||
storage: stubRepo{payments: store},
|
||||
}
|
||||
exec := &model.PaymentGatewayExecution{
|
||||
PaymentIntentID: "pi-2",
|
||||
Status: model.ConfirmationStatusRejected,
|
||||
}
|
||||
if err := svc.onGatewayExecution(context.Background(), exec); err != nil {
|
||||
t.Fatalf("onGatewayExecution error: %v", err)
|
||||
}
|
||||
updated, _ := store.GetByPaymentRef(context.Background(), "pi-2")
|
||||
if updated.State != paymodel.PaymentStateFailed {
|
||||
t.Fatalf("expected payment failed, got %s", updated.State)
|
||||
}
|
||||
if updated.FailureReason != "gateway_rejected" {
|
||||
t.Fatalf("expected failure reason gateway_rejected, got %q", updated.FailureReason)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
package orchestrator
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/tech/sendico/payments/orchestrator/storage/model"
|
||||
"github.com/tech/sendico/pkg/mlogger"
|
||||
gatewayv1 "github.com/tech/sendico/pkg/proto/common/gateway/v1"
|
||||
)
|
||||
|
||||
type gatewayRegistry struct {
|
||||
logger mlogger.Logger
|
||||
static []*model.GatewayInstanceDescriptor
|
||||
}
|
||||
|
||||
// NewGatewayRegistry aggregates static gateway descriptors.
|
||||
func NewGatewayRegistry(logger mlogger.Logger, static []*model.GatewayInstanceDescriptor) GatewayRegistry {
|
||||
if len(static) == 0 {
|
||||
return nil
|
||||
}
|
||||
if logger != nil {
|
||||
logger = logger.Named("gateway_registry")
|
||||
}
|
||||
return &gatewayRegistry{
|
||||
logger: logger,
|
||||
static: cloneGatewayDescriptors(static),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *gatewayRegistry) List(ctx context.Context) ([]*model.GatewayInstanceDescriptor, error) {
|
||||
items := map[string]*model.GatewayInstanceDescriptor{}
|
||||
for _, gw := range r.static {
|
||||
if gw == nil {
|
||||
continue
|
||||
}
|
||||
id := strings.TrimSpace(gw.ID)
|
||||
if id == "" {
|
||||
continue
|
||||
}
|
||||
items[id] = cloneGatewayDescriptor(gw)
|
||||
}
|
||||
|
||||
result := make([]*model.GatewayInstanceDescriptor, 0, len(items))
|
||||
for _, gw := range items {
|
||||
result = append(result, gw)
|
||||
}
|
||||
sort.Slice(result, func(i, j int) bool {
|
||||
return result[i].ID < result[j].ID
|
||||
})
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func modelGatewayFromProto(src *gatewayv1.GatewayInstanceDescriptor) *model.GatewayInstanceDescriptor {
|
||||
if src == nil {
|
||||
return nil
|
||||
}
|
||||
limits := modelLimitsFromProto(src.GetLimits())
|
||||
return &model.GatewayInstanceDescriptor{
|
||||
ID: strings.TrimSpace(src.GetId()),
|
||||
Rail: modelRailFromProto(src.GetRail()),
|
||||
Network: strings.ToUpper(strings.TrimSpace(src.GetNetwork())),
|
||||
Currencies: normalizeCurrencies(src.GetCurrencies()),
|
||||
Capabilities: modelCapabilitiesFromProto(src.GetCapabilities()),
|
||||
Limits: limits,
|
||||
Version: strings.TrimSpace(src.GetVersion()),
|
||||
IsEnabled: src.GetIsEnabled(),
|
||||
}
|
||||
}
|
||||
|
||||
func modelRailFromProto(rail gatewayv1.Rail) model.Rail {
|
||||
switch rail {
|
||||
case gatewayv1.Rail_RAIL_CRYPTO:
|
||||
return model.RailCrypto
|
||||
case gatewayv1.Rail_RAIL_PROVIDER_SETTLEMENT:
|
||||
return model.RailProviderSettlement
|
||||
case gatewayv1.Rail_RAIL_LEDGER:
|
||||
return model.RailLedger
|
||||
case gatewayv1.Rail_RAIL_CARD_PAYOUT:
|
||||
return model.RailCardPayout
|
||||
case gatewayv1.Rail_RAIL_FIAT_ONRAMP:
|
||||
return model.RailFiatOnRamp
|
||||
default:
|
||||
return model.RailUnspecified
|
||||
}
|
||||
}
|
||||
|
||||
func modelCapabilitiesFromProto(src *gatewayv1.RailCapabilities) model.RailCapabilities {
|
||||
if src == nil {
|
||||
return model.RailCapabilities{}
|
||||
}
|
||||
return model.RailCapabilities{
|
||||
CanPayIn: src.GetCanPayIn(),
|
||||
CanPayOut: src.GetCanPayOut(),
|
||||
CanReadBalance: src.GetCanReadBalance(),
|
||||
CanSendFee: src.GetCanSendFee(),
|
||||
RequiresObserveConfirm: src.GetRequiresObserveConfirm(),
|
||||
}
|
||||
}
|
||||
|
||||
func modelLimitsFromProto(src *gatewayv1.Limits) model.Limits {
|
||||
if src == nil {
|
||||
return model.Limits{}
|
||||
}
|
||||
limits := model.Limits{
|
||||
MinAmount: strings.TrimSpace(src.GetMinAmount()),
|
||||
MaxAmount: strings.TrimSpace(src.GetMaxAmount()),
|
||||
PerTxMaxFee: strings.TrimSpace(src.GetPerTxMaxFee()),
|
||||
PerTxMinAmount: strings.TrimSpace(src.GetPerTxMinAmount()),
|
||||
PerTxMaxAmount: strings.TrimSpace(src.GetPerTxMaxAmount()),
|
||||
}
|
||||
|
||||
if len(src.GetVolumeLimit()) > 0 {
|
||||
limits.VolumeLimit = map[string]string{}
|
||||
for key, value := range src.GetVolumeLimit() {
|
||||
bucket := strings.TrimSpace(key)
|
||||
amount := strings.TrimSpace(value)
|
||||
if bucket == "" || amount == "" {
|
||||
continue
|
||||
}
|
||||
limits.VolumeLimit[bucket] = amount
|
||||
}
|
||||
}
|
||||
|
||||
if len(src.GetVelocityLimit()) > 0 {
|
||||
limits.VelocityLimit = map[string]int{}
|
||||
for key, value := range src.GetVelocityLimit() {
|
||||
bucket := strings.TrimSpace(key)
|
||||
if bucket == "" {
|
||||
continue
|
||||
}
|
||||
limits.VelocityLimit[bucket] = int(value)
|
||||
}
|
||||
}
|
||||
|
||||
if len(src.GetCurrencyLimits()) > 0 {
|
||||
limits.CurrencyLimits = map[string]model.LimitsOverride{}
|
||||
for key, override := range src.GetCurrencyLimits() {
|
||||
currency := strings.ToUpper(strings.TrimSpace(key))
|
||||
if currency == "" || override == nil {
|
||||
continue
|
||||
}
|
||||
limits.CurrencyLimits[currency] = model.LimitsOverride{
|
||||
MaxVolume: strings.TrimSpace(override.GetMaxVolume()),
|
||||
MinAmount: strings.TrimSpace(override.GetMinAmount()),
|
||||
MaxAmount: strings.TrimSpace(override.GetMaxAmount()),
|
||||
MaxFee: strings.TrimSpace(override.GetMaxFee()),
|
||||
MaxOps: int(override.GetMaxOps()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return limits
|
||||
}
|
||||
|
||||
func normalizeCurrencies(values []string) []string {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
result := make([]string, 0, len(values))
|
||||
for _, value := range values {
|
||||
clean := strings.ToUpper(strings.TrimSpace(value))
|
||||
if clean == "" || seen[clean] {
|
||||
continue
|
||||
}
|
||||
seen[clean] = true
|
||||
result = append(result, clean)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func cloneGatewayDescriptors(src []*model.GatewayInstanceDescriptor) []*model.GatewayInstanceDescriptor {
|
||||
if len(src) == 0 {
|
||||
return nil
|
||||
}
|
||||
result := make([]*model.GatewayInstanceDescriptor, 0, len(src))
|
||||
for _, item := range src {
|
||||
if item == nil {
|
||||
continue
|
||||
}
|
||||
if cloned := cloneGatewayDescriptor(item); cloned != nil {
|
||||
result = append(result, cloned)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func cloneGatewayDescriptor(src *model.GatewayInstanceDescriptor) *model.GatewayInstanceDescriptor {
|
||||
if src == nil {
|
||||
return nil
|
||||
}
|
||||
dst := *src
|
||||
if src.Currencies != nil {
|
||||
dst.Currencies = append([]string(nil), src.Currencies...)
|
||||
}
|
||||
dst.Limits = cloneLimits(src.Limits)
|
||||
return &dst
|
||||
}
|
||||
|
||||
func cloneLimits(src model.Limits) model.Limits {
|
||||
dst := src
|
||||
if src.VolumeLimit != nil {
|
||||
dst.VolumeLimit = map[string]string{}
|
||||
for key, value := range src.VolumeLimit {
|
||||
dst.VolumeLimit[key] = value
|
||||
}
|
||||
}
|
||||
if src.VelocityLimit != nil {
|
||||
dst.VelocityLimit = map[string]int{}
|
||||
for key, value := range src.VelocityLimit {
|
||||
dst.VelocityLimit[key] = value
|
||||
}
|
||||
}
|
||||
if src.CurrencyLimits != nil {
|
||||
dst.CurrencyLimits = map[string]model.LimitsOverride{}
|
||||
for key, value := range src.CurrencyLimits {
|
||||
dst.CurrencyLimits[key] = value
|
||||
}
|
||||
}
|
||||
return dst
|
||||
}
|
||||
@@ -465,13 +465,14 @@ func (h *initiateConversionCommand) Execute(ctx context.Context, req *orchestrat
|
||||
}
|
||||
|
||||
intentProto := &orchestratorv1.PaymentIntent{
|
||||
Kind: orchestratorv1.PaymentKind_PAYMENT_KIND_FX_CONVERSION,
|
||||
Source: req.GetSource(),
|
||||
Destination: req.GetDestination(),
|
||||
Amount: amount,
|
||||
RequiresFx: true,
|
||||
Fx: fxIntent,
|
||||
FeePolicy: req.GetFeePolicy(),
|
||||
Kind: orchestratorv1.PaymentKind_PAYMENT_KIND_FX_CONVERSION,
|
||||
Source: req.GetSource(),
|
||||
Destination: req.GetDestination(),
|
||||
Amount: amount,
|
||||
RequiresFx: true,
|
||||
Fx: fxIntent,
|
||||
FeePolicy: req.GetFeePolicy(),
|
||||
SettlementCurrency: strings.TrimSpace(amount.GetCurrency()),
|
||||
}
|
||||
|
||||
quote, _, err := h.engine.BuildPaymentQuote(ctx, orgRef, &orchestratorv1.QuotePaymentRequest{
|
||||
|
||||
@@ -10,21 +10,26 @@ import (
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
"github.com/tech/sendico/pkg/mlogger"
|
||||
"github.com/tech/sendico/pkg/mservice"
|
||||
chainv1 "github.com/tech/sendico/pkg/proto/gateway/chain/v1"
|
||||
orchestratorv1 "github.com/tech/sendico/pkg/proto/payments/orchestrator/v1"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
type paymentEventHandler struct {
|
||||
repo storage.Repository
|
||||
ensureRepo func(ctx context.Context) error
|
||||
logger mlogger.Logger
|
||||
repo storage.Repository
|
||||
ensureRepo func(ctx context.Context) error
|
||||
logger mlogger.Logger
|
||||
submitCardPayout func(ctx context.Context, payment *model.Payment) error
|
||||
resumePlan func(ctx context.Context, store storage.PaymentsStore, payment *model.Payment) error
|
||||
}
|
||||
|
||||
func newPaymentEventHandler(repo storage.Repository, ensure func(ctx context.Context) error, logger mlogger.Logger) *paymentEventHandler {
|
||||
func newPaymentEventHandler(repo storage.Repository, ensure func(ctx context.Context) error, logger mlogger.Logger, submitCardPayout func(ctx context.Context, payment *model.Payment) error, resumePlan func(ctx context.Context, store storage.PaymentsStore, payment *model.Payment) error) *paymentEventHandler {
|
||||
return &paymentEventHandler{
|
||||
repo: repo,
|
||||
ensureRepo: ensure,
|
||||
logger: logger,
|
||||
repo: repo,
|
||||
ensureRepo: ensure,
|
||||
logger: logger,
|
||||
submitCardPayout: submitCardPayout,
|
||||
resumePlan: resumePlan,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,6 +53,121 @@ func (h *paymentEventHandler) processTransferUpdate(ctx context.Context, req *or
|
||||
if err != nil {
|
||||
return paymentNotFoundResponder[orchestratorv1.ProcessTransferUpdateResponse](mservice.PaymentOrchestrator, h.logger, err)
|
||||
}
|
||||
if payment.PaymentPlan != nil && len(payment.PaymentPlan.Steps) > 0 {
|
||||
if payment.ExecutionPlan == nil || len(payment.ExecutionPlan.Steps) != len(payment.PaymentPlan.Steps) {
|
||||
ensureExecutionPlanForPlan(payment, payment.PaymentPlan)
|
||||
}
|
||||
updateExecutionStepFromTransfer(payment.ExecutionPlan, req.GetEvent())
|
||||
if payment.Execution == nil {
|
||||
payment.Execution = &model.ExecutionRefs{}
|
||||
}
|
||||
if payment.Execution.ChainTransferRef == "" {
|
||||
payment.Execution.ChainTransferRef = transferRef
|
||||
}
|
||||
reason := transferFailureReason(req.GetEvent())
|
||||
switch transfer.GetStatus() {
|
||||
case chainv1.TransferStatus_TRANSFER_FAILED:
|
||||
payment.State = model.PaymentStateFailed
|
||||
payment.FailureCode = model.PaymentFailureCodeChain
|
||||
payment.FailureReason = reason
|
||||
if err := store.Update(ctx, payment); err != nil {
|
||||
return gsresponse.Auto[orchestratorv1.ProcessTransferUpdateResponse](h.logger, mservice.PaymentOrchestrator, err)
|
||||
}
|
||||
return gsresponse.Success(&orchestratorv1.ProcessTransferUpdateResponse{Payment: toProtoPayment(payment)})
|
||||
case chainv1.TransferStatus_TRANSFER_CANCELLED:
|
||||
payment.State = model.PaymentStateCancelled
|
||||
payment.FailureCode = model.PaymentFailureCodePolicy
|
||||
payment.FailureReason = reason
|
||||
if err := store.Update(ctx, payment); err != nil {
|
||||
return gsresponse.Auto[orchestratorv1.ProcessTransferUpdateResponse](h.logger, mservice.PaymentOrchestrator, err)
|
||||
}
|
||||
return gsresponse.Success(&orchestratorv1.ProcessTransferUpdateResponse{Payment: toProtoPayment(payment)})
|
||||
case chainv1.TransferStatus_TRANSFER_CONFIRMED:
|
||||
if h.resumePlan != nil {
|
||||
if err := h.resumePlan(ctx, store, payment); err != nil {
|
||||
return gsresponse.Auto[orchestratorv1.ProcessTransferUpdateResponse](h.logger, mservice.PaymentOrchestrator, err)
|
||||
}
|
||||
} else {
|
||||
payment.State = model.PaymentStateSubmitted
|
||||
if err := store.Update(ctx, payment); err != nil {
|
||||
return gsresponse.Auto[orchestratorv1.ProcessTransferUpdateResponse](h.logger, mservice.PaymentOrchestrator, err)
|
||||
}
|
||||
}
|
||||
return gsresponse.Success(&orchestratorv1.ProcessTransferUpdateResponse{Payment: toProtoPayment(payment)})
|
||||
case chainv1.TransferStatus_TRANSFER_SIGNING,
|
||||
chainv1.TransferStatus_TRANSFER_PENDING,
|
||||
chainv1.TransferStatus_TRANSFER_SUBMITTED:
|
||||
if payment.State != model.PaymentStateFailed && payment.State != model.PaymentStateCancelled && payment.State != model.PaymentStateSettled {
|
||||
payment.State = model.PaymentStateSubmitted
|
||||
}
|
||||
if err := store.Update(ctx, payment); err != nil {
|
||||
return gsresponse.Auto[orchestratorv1.ProcessTransferUpdateResponse](h.logger, mservice.PaymentOrchestrator, err)
|
||||
}
|
||||
return gsresponse.Success(&orchestratorv1.ProcessTransferUpdateResponse{Payment: toProtoPayment(payment)})
|
||||
default:
|
||||
if err := store.Update(ctx, payment); err != nil {
|
||||
return gsresponse.Auto[orchestratorv1.ProcessTransferUpdateResponse](h.logger, mservice.PaymentOrchestrator, err)
|
||||
}
|
||||
return gsresponse.Success(&orchestratorv1.ProcessTransferUpdateResponse{Payment: toProtoPayment(payment)})
|
||||
}
|
||||
}
|
||||
|
||||
updateExecutionStepFromTransfer(payment.ExecutionPlan, req.GetEvent())
|
||||
if payment.Intent.Destination.Type == model.EndpointTypeCard {
|
||||
if payment.Execution == nil {
|
||||
payment.Execution = &model.ExecutionRefs{}
|
||||
}
|
||||
if payment.Execution.ChainTransferRef == "" {
|
||||
payment.Execution.ChainTransferRef = transferRef
|
||||
}
|
||||
reason := transferFailureReason(req.GetEvent())
|
||||
switch transfer.GetStatus() {
|
||||
case chainv1.TransferStatus_TRANSFER_FAILED:
|
||||
payment.State = model.PaymentStateFailed
|
||||
payment.FailureCode = model.PaymentFailureCodeChain
|
||||
payment.FailureReason = reason
|
||||
case chainv1.TransferStatus_TRANSFER_CANCELLED:
|
||||
payment.State = model.PaymentStateCancelled
|
||||
payment.FailureCode = model.PaymentFailureCodePolicy
|
||||
payment.FailureReason = reason
|
||||
case chainv1.TransferStatus_TRANSFER_CONFIRMED:
|
||||
if payment.State != model.PaymentStateFailed && payment.State != model.PaymentStateCancelled && payment.State != model.PaymentStateSettled {
|
||||
if cardPayoutDependenciesConfirmed(payment.PaymentPlan, payment.ExecutionPlan) {
|
||||
if payment.Execution.CardPayoutRef != "" {
|
||||
payment.State = model.PaymentStateSubmitted
|
||||
} else {
|
||||
payment.State = model.PaymentStateFundsReserved
|
||||
if h.submitCardPayout == nil {
|
||||
h.logger.Warn("card payout execution skipped", zap.String("payment_ref", payment.PaymentRef))
|
||||
} else if err := h.submitCardPayout(ctx, payment); err != nil {
|
||||
payment.State = model.PaymentStateFailed
|
||||
payment.FailureCode = model.PaymentFailureCodePolicy
|
||||
payment.FailureReason = strings.TrimSpace(err.Error())
|
||||
h.logger.Warn("card payout execution failed", zap.Error(err), zap.String("payment_ref", payment.PaymentRef))
|
||||
} else {
|
||||
payment.State = model.PaymentStateSubmitted
|
||||
}
|
||||
}
|
||||
} else {
|
||||
payment.State = model.PaymentStateSubmitted
|
||||
}
|
||||
}
|
||||
case chainv1.TransferStatus_TRANSFER_SIGNING,
|
||||
chainv1.TransferStatus_TRANSFER_PENDING,
|
||||
chainv1.TransferStatus_TRANSFER_SUBMITTED:
|
||||
if payment.State != model.PaymentStateFailed && payment.State != model.PaymentStateCancelled && payment.State != model.PaymentStateSettled {
|
||||
payment.State = model.PaymentStateSubmitted
|
||||
}
|
||||
default:
|
||||
// keep current state
|
||||
}
|
||||
if err := store.Update(ctx, payment); err != nil {
|
||||
return gsresponse.Auto[orchestratorv1.ProcessTransferUpdateResponse](h.logger, mservice.PaymentOrchestrator, err)
|
||||
}
|
||||
h.logger.Info("transfer update applied", zap.String("payment_ref", payment.PaymentRef), zap.String("transfer_ref", transferRef), zap.Any("state", payment.State))
|
||||
return gsresponse.Success(&orchestratorv1.ProcessTransferUpdateResponse{Payment: toProtoPayment(payment)})
|
||||
}
|
||||
|
||||
applyTransferStatus(req.GetEvent(), payment)
|
||||
if err := store.Update(ctx, payment); err != nil {
|
||||
return gsresponse.Auto[orchestratorv1.ProcessTransferUpdateResponse](h.logger, mservice.PaymentOrchestrator, err)
|
||||
@@ -137,3 +257,14 @@ func (h *paymentEventHandler) processCardPayoutUpdate(ctx context.Context, req *
|
||||
Payment: toProtoPayment(payment),
|
||||
})
|
||||
}
|
||||
|
||||
func transferFailureReason(event *chainv1.TransferStatusChangedEvent) string {
|
||||
if event == nil || event.GetTransfer() == nil {
|
||||
return ""
|
||||
}
|
||||
reason := strings.TrimSpace(event.GetReason())
|
||||
if reason != "" {
|
||||
return reason
|
||||
}
|
||||
return strings.TrimSpace(event.GetTransfer().GetFailureReason())
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@ import (
|
||||
"github.com/shopspring/decimal"
|
||||
oracleclient "github.com/tech/sendico/fx/oracle/client"
|
||||
"github.com/tech/sendico/pkg/merrors"
|
||||
"github.com/tech/sendico/pkg/payments/rail"
|
||||
chainv1 "github.com/tech/sendico/pkg/proto/gateway/chain/v1"
|
||||
ledgerv1 "github.com/tech/sendico/pkg/proto/ledger/v1"
|
||||
oraclev1 "github.com/tech/sendico/pkg/proto/oracle/v1"
|
||||
orchestratorv1 "github.com/tech/sendico/pkg/proto/payments/orchestrator/v1"
|
||||
@@ -16,10 +18,14 @@ import (
|
||||
accountingv1 "github.com/tech/sendico/pkg/proto/common/accounting/v1"
|
||||
fxv1 "github.com/tech/sendico/pkg/proto/common/fx/v1"
|
||||
moneyv1 "github.com/tech/sendico/pkg/proto/common/money/v1"
|
||||
chainv1 "github.com/tech/sendico/pkg/proto/gateway/chain/v1"
|
||||
)
|
||||
|
||||
func cloneMoney(input *moneyv1.Money) *moneyv1.Money {
|
||||
type moneyGetter interface {
|
||||
GetAmount() string
|
||||
GetCurrency() string
|
||||
}
|
||||
|
||||
func cloneProtoMoney(input *moneyv1.Money) *moneyv1.Money {
|
||||
if input == nil {
|
||||
return nil
|
||||
}
|
||||
@@ -40,6 +46,24 @@ func cloneMetadata(input map[string]string) map[string]string {
|
||||
return clone
|
||||
}
|
||||
|
||||
func cloneStringList(values []string) []string {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
result := make([]string, 0, len(values))
|
||||
for _, value := range values {
|
||||
clean := strings.TrimSpace(value)
|
||||
if clean == "" {
|
||||
continue
|
||||
}
|
||||
result = append(result, clean)
|
||||
}
|
||||
if len(result) == 0 {
|
||||
return nil
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func cloneFeeLines(lines []*feesv1.DerivedPostingLine) []*feesv1.DerivedPostingLine {
|
||||
if len(lines) == 0 {
|
||||
return nil
|
||||
@@ -112,7 +136,7 @@ func extractFeeTotal(lines []*feesv1.DerivedPostingLine, currency string) *money
|
||||
|
||||
func resolveTradeAmounts(intentAmount *moneyv1.Money, fxQuote *oraclev1.Quote, side fxv1.Side) (*moneyv1.Money, *moneyv1.Money) {
|
||||
if fxQuote == nil {
|
||||
return cloneMoney(intentAmount), cloneMoney(intentAmount)
|
||||
return cloneProtoMoney(intentAmount), cloneProtoMoney(intentAmount)
|
||||
}
|
||||
qSide := fxQuote.GetSide()
|
||||
if qSide == fxv1.Side_SIDE_UNSPECIFIED {
|
||||
@@ -121,27 +145,27 @@ func resolveTradeAmounts(intentAmount *moneyv1.Money, fxQuote *oraclev1.Quote, s
|
||||
|
||||
switch qSide {
|
||||
case fxv1.Side_BUY_BASE_SELL_QUOTE:
|
||||
pay := cloneMoney(fxQuote.GetQuoteAmount())
|
||||
settle := cloneMoney(fxQuote.GetBaseAmount())
|
||||
pay := cloneProtoMoney(fxQuote.GetQuoteAmount())
|
||||
settle := cloneProtoMoney(fxQuote.GetBaseAmount())
|
||||
if pay == nil {
|
||||
pay = cloneMoney(intentAmount)
|
||||
pay = cloneProtoMoney(intentAmount)
|
||||
}
|
||||
if settle == nil {
|
||||
settle = cloneMoney(intentAmount)
|
||||
settle = cloneProtoMoney(intentAmount)
|
||||
}
|
||||
return pay, settle
|
||||
case fxv1.Side_SELL_BASE_BUY_QUOTE:
|
||||
pay := cloneMoney(fxQuote.GetBaseAmount())
|
||||
settle := cloneMoney(fxQuote.GetQuoteAmount())
|
||||
pay := cloneProtoMoney(fxQuote.GetBaseAmount())
|
||||
settle := cloneProtoMoney(fxQuote.GetQuoteAmount())
|
||||
if pay == nil {
|
||||
pay = cloneMoney(intentAmount)
|
||||
pay = cloneProtoMoney(intentAmount)
|
||||
}
|
||||
if settle == nil {
|
||||
settle = cloneMoney(intentAmount)
|
||||
settle = cloneProtoMoney(intentAmount)
|
||||
}
|
||||
return pay, settle
|
||||
default:
|
||||
return cloneMoney(intentAmount), cloneMoney(intentAmount)
|
||||
return cloneProtoMoney(intentAmount), cloneProtoMoney(intentAmount)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -151,7 +175,7 @@ func computeAggregates(pay, settlement, fee *moneyv1.Money, network *chainv1.Est
|
||||
}
|
||||
debitDecimal, err := decimalFromMoney(pay)
|
||||
if err != nil {
|
||||
return cloneMoney(pay), cloneMoney(settlement)
|
||||
return cloneProtoMoney(pay), cloneProtoMoney(settlement)
|
||||
}
|
||||
|
||||
settlementCurrency := pay.GetCurrency()
|
||||
@@ -187,7 +211,7 @@ func computeAggregates(pay, settlement, fee *moneyv1.Money, network *chainv1.Est
|
||||
}
|
||||
|
||||
switch mode {
|
||||
case orchestratorv1.SettlementMode_SETTLEMENT_MODE_FIX_RECEIVED:
|
||||
case orchestratorv1.SettlementMode_SETTLEMENT_FIX_RECEIVED:
|
||||
// Sender pays the fee: keep settlement fixed, increase debit.
|
||||
applyChargeToDebit(fee)
|
||||
default:
|
||||
@@ -197,7 +221,7 @@ func computeAggregates(pay, settlement, fee *moneyv1.Money, network *chainv1.Est
|
||||
|
||||
if network != nil && network.GetNetworkFee() != nil {
|
||||
switch mode {
|
||||
case orchestratorv1.SettlementMode_SETTLEMENT_MODE_FIX_RECEIVED:
|
||||
case orchestratorv1.SettlementMode_SETTLEMENT_FIX_RECEIVED:
|
||||
applyChargeToDebit(network.GetNetworkFee())
|
||||
default:
|
||||
applyChargeToSettlement(network.GetNetworkFee())
|
||||
@@ -207,7 +231,7 @@ func computeAggregates(pay, settlement, fee *moneyv1.Money, network *chainv1.Est
|
||||
return makeMoney(pay.GetCurrency(), debitDecimal), makeMoney(settlementCurrency, settlementDecimal)
|
||||
}
|
||||
|
||||
func decimalFromMoney(m *moneyv1.Money) (decimal.Decimal, error) {
|
||||
func decimalFromMoney(m moneyGetter) (decimal.Decimal, error) {
|
||||
if m == nil {
|
||||
return decimal.Zero, nil
|
||||
}
|
||||
@@ -226,7 +250,7 @@ func ensureCurrency(m *moneyv1.Money, targetCurrency string, quote *oraclev1.Quo
|
||||
return nil, nil
|
||||
}
|
||||
if strings.EqualFold(m.GetCurrency(), targetCurrency) {
|
||||
return cloneMoney(m), nil
|
||||
return cloneProtoMoney(m), nil
|
||||
}
|
||||
return convertWithQuote(m, quote, targetCurrency)
|
||||
}
|
||||
@@ -270,8 +294,8 @@ func quoteToProto(src *oracleclient.Quote) *oraclev1.Quote {
|
||||
Pair: src.Pair,
|
||||
Side: src.Side,
|
||||
Price: &moneyv1.Decimal{Value: src.Price},
|
||||
BaseAmount: cloneMoney(src.BaseAmount),
|
||||
QuoteAmount: cloneMoney(src.QuoteAmount),
|
||||
BaseAmount: cloneProtoMoney(src.BaseAmount),
|
||||
QuoteAmount: cloneProtoMoney(src.QuoteAmount),
|
||||
ExpiresAtUnixMs: src.ExpiresAt.UnixMilli(),
|
||||
Provider: src.Provider,
|
||||
RateRef: src.RateRef,
|
||||
@@ -288,7 +312,7 @@ func ledgerChargesFromFeeLines(lines []*feesv1.DerivedPostingLine) []*ledgerv1.P
|
||||
if line == nil || strings.TrimSpace(line.GetLedgerAccountRef()) == "" {
|
||||
continue
|
||||
}
|
||||
money := cloneMoney(line.GetMoney())
|
||||
money := cloneProtoMoney(line.GetMoney())
|
||||
if money == nil {
|
||||
continue
|
||||
}
|
||||
@@ -335,17 +359,17 @@ func quoteExpiry(now time.Time, feeQuote *feesv1.PrecomputeFeesResponse, fxQuote
|
||||
return expiry
|
||||
}
|
||||
|
||||
func feeBreakdownFromQuote(quote *orchestratorv1.PaymentQuote) []*chainv1.ServiceFeeBreakdown {
|
||||
func feeBreakdownFromQuote(quote *orchestratorv1.PaymentQuote) []rail.FeeBreakdown {
|
||||
if quote == nil {
|
||||
return nil
|
||||
}
|
||||
lines := quote.GetFeeLines()
|
||||
breakdown := make([]*chainv1.ServiceFeeBreakdown, 0, len(lines)+1)
|
||||
breakdown := make([]rail.FeeBreakdown, 0, len(lines)+1)
|
||||
for _, line := range lines {
|
||||
if line == nil {
|
||||
continue
|
||||
}
|
||||
amount := cloneMoney(line.GetMoney())
|
||||
amount := moneyFromProto(line.GetMoney())
|
||||
if amount == nil {
|
||||
continue
|
||||
}
|
||||
@@ -357,16 +381,16 @@ func feeBreakdownFromQuote(quote *orchestratorv1.PaymentQuote) []*chainv1.Servic
|
||||
code = line.GetLineType().String()
|
||||
}
|
||||
desc := strings.TrimSpace(line.GetMeta()["description"])
|
||||
breakdown = append(breakdown, &chainv1.ServiceFeeBreakdown{
|
||||
breakdown = append(breakdown, rail.FeeBreakdown{
|
||||
FeeCode: code,
|
||||
Amount: amount,
|
||||
Description: desc,
|
||||
})
|
||||
}
|
||||
if quote.GetNetworkFee() != nil && quote.GetNetworkFee().GetNetworkFee() != nil {
|
||||
networkAmount := cloneMoney(quote.GetNetworkFee().GetNetworkFee())
|
||||
networkAmount := moneyFromProto(quote.GetNetworkFee().GetNetworkFee())
|
||||
if networkAmount != nil {
|
||||
breakdown = append(breakdown, &chainv1.ServiceFeeBreakdown{
|
||||
breakdown = append(breakdown, rail.FeeBreakdown{
|
||||
FeeCode: "network_fee",
|
||||
Amount: networkAmount,
|
||||
Description: strings.TrimSpace(quote.GetNetworkFee().GetEstimationContext()),
|
||||
@@ -395,7 +419,7 @@ func assignLedgerAccounts(lines []*feesv1.DerivedPostingLine, account string) []
|
||||
return lines
|
||||
}
|
||||
|
||||
func moneyEquals(a, b *moneyv1.Money) bool {
|
||||
func moneyEquals(a, b moneyGetter) bool {
|
||||
if a == nil || b == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ func TestComputeAggregatesConvertsCurrencies(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
debit, settlement := computeAggregates(pay, settle, fee, network, fxQuote, orchestratorv1.SettlementMode_SETTLEMENT_MODE_FIX_RECEIVED)
|
||||
debit, settlement := computeAggregates(pay, settle, fee, network, fxQuote, orchestratorv1.SettlementMode_SETTLEMENT_FIX_RECEIVED)
|
||||
if debit.GetCurrency() != "USD" || debit.GetAmount() != "115" {
|
||||
t.Fatalf("expected debit 115 USD, got %s %s", debit.GetCurrency(), debit.GetAmount())
|
||||
}
|
||||
@@ -69,7 +69,7 @@ func TestComputeAggregatesRecipientPaysFee(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
debit, settlement := computeAggregates(pay, settle, fee, nil, fxQuote, orchestratorv1.SettlementMode_SETTLEMENT_MODE_FIX_SOURCE)
|
||||
debit, settlement := computeAggregates(pay, settle, fee, nil, fxQuote, orchestratorv1.SettlementMode_SETTLEMENT_FIX_SOURCE)
|
||||
if debit.GetCurrency() != "USDT" || debit.GetAmount() != "100" {
|
||||
t.Fatalf("expected debit 100 USDT, got %s %s", debit.GetCurrency(), debit.GetAmount())
|
||||
}
|
||||
|
||||
@@ -2,12 +2,14 @@ package orchestrator
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/tech/sendico/payments/orchestrator/storage/model"
|
||||
"github.com/tech/sendico/pkg/api/routers/gsresponse"
|
||||
"github.com/tech/sendico/pkg/mservice"
|
||||
feesv1 "github.com/tech/sendico/pkg/proto/billing/fees/v1"
|
||||
fxv1 "github.com/tech/sendico/pkg/proto/common/fx/v1"
|
||||
mntxv1 "github.com/tech/sendico/pkg/proto/gateway/mntx/v1"
|
||||
orchestratorv1 "github.com/tech/sendico/pkg/proto/payments/orchestrator/v1"
|
||||
)
|
||||
@@ -73,10 +75,37 @@ func shouldRequestFX(intent *orchestratorv1.PaymentIntent) bool {
|
||||
if intent == nil {
|
||||
return false
|
||||
}
|
||||
if intent.GetRequiresFx() {
|
||||
if fxIntentForQuote(intent) != nil {
|
||||
return true
|
||||
}
|
||||
return intent.GetFx() != nil && intent.GetFx().GetPair() != nil
|
||||
return intent.GetRequiresFx()
|
||||
}
|
||||
|
||||
func fxIntentForQuote(intent *orchestratorv1.PaymentIntent) *orchestratorv1.FXIntent {
|
||||
if intent == nil {
|
||||
return nil
|
||||
}
|
||||
if fx := intent.GetFx(); fx != nil && fx.GetPair() != nil {
|
||||
return fx
|
||||
}
|
||||
amount := intent.GetAmount()
|
||||
if amount == nil {
|
||||
return nil
|
||||
}
|
||||
settlementCurrency := strings.TrimSpace(intent.GetSettlementCurrency())
|
||||
if settlementCurrency == "" {
|
||||
return nil
|
||||
}
|
||||
if strings.EqualFold(amount.GetCurrency(), settlementCurrency) {
|
||||
return nil
|
||||
}
|
||||
return &orchestratorv1.FXIntent{
|
||||
Pair: &fxv1.CurrencyPair{
|
||||
Base: strings.TrimSpace(amount.GetCurrency()),
|
||||
Quote: settlementCurrency,
|
||||
},
|
||||
Side: fxv1.Side_SELL_BASE_BUY_QUOTE,
|
||||
}
|
||||
}
|
||||
|
||||
func mapMntxStatusToState(status mntxv1.PayoutStatus) model.PaymentState {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user