2023-03-06 09:18:41 +01:00
|
|
|
package pub
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/nats-io/nats.go"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2023-03-08 15:19:33 +01:00
|
|
|
streamName string = "CUSTODIAL"
|
|
|
|
streamSubjects string = "CUSTODIAL.*"
|
2023-03-06 09:18:41 +01:00
|
|
|
AccountNewNonce string = "CUSTODIAL.accountNewNonce"
|
|
|
|
AccountRegister string = "CUSTODIAL.accountRegister"
|
|
|
|
AccountGiftGas string = "CUSTODIAL.systemNewAccountGas"
|
|
|
|
AccountGiftVoucher string = "CUSTODIAL.systemNewAccountVoucher"
|
|
|
|
AccountRefillGas string = "CUSTODIAL.systemRefillAccountGas"
|
|
|
|
DispatchFail string = "CUSTODIAL.dispatchFail"
|
|
|
|
DispatchSuccess string = "CUSTODIAL.dispatchSuccess"
|
|
|
|
SignTransfer string = "CUSTODIAL.signTransfer"
|
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
|
|
|
PubOpts struct {
|
|
|
|
DedupDuration time.Duration
|
|
|
|
JsCtx nats.JetStreamContext
|
|
|
|
PersistDuration time.Duration
|
|
|
|
}
|
|
|
|
|
|
|
|
Pub struct {
|
|
|
|
jsCtx nats.JetStreamContext
|
|
|
|
}
|
|
|
|
|
|
|
|
EventPayload struct {
|
|
|
|
OtxId uint `json:"otxId"`
|
|
|
|
TrackingId string `json:"trackingId"`
|
|
|
|
TxHash string `json:"txHash"`
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
func NewPub(o PubOpts) (*Pub, error) {
|
2023-03-08 15:19:33 +01:00
|
|
|
stream, _ := o.JsCtx.StreamInfo(streamName)
|
2023-03-06 09:18:41 +01:00
|
|
|
if stream == nil {
|
|
|
|
_, err := o.JsCtx.AddStream(&nats.StreamConfig{
|
2023-03-08 15:19:33 +01:00
|
|
|
Name: streamName,
|
2023-03-06 09:18:41 +01:00
|
|
|
MaxAge: o.PersistDuration,
|
|
|
|
Storage: nats.FileStorage,
|
2023-03-08 15:19:33 +01:00
|
|
|
Subjects: []string{streamSubjects},
|
2023-03-06 09:18:41 +01:00
|
|
|
Duplicates: o.DedupDuration,
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return &Pub{
|
|
|
|
jsCtx: o.JsCtx,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *Pub) Publish(subject string, dedupId string, eventPayload interface{}) error {
|
|
|
|
jsonData, err := json.Marshal(eventPayload)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
_, err = p.jsCtx.Publish(subject, jsonData, nats.MsgId(dedupId))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|