Add documentation, remove unused files

This commit is contained in:
lash 2024-11-03 19:04:44 +00:00
parent 4491f0155f
commit e420231f10
Signed by: lash
GPG Key ID: 21D2E7BB88C2A746
11 changed files with 89 additions and 83 deletions

View File

@ -9,10 +9,15 @@ import (
"git.defalsify.org/vise.git/db/mem" "git.defalsify.org/vise.git/db/mem"
"git.grassecon.net/urdt/ussd/initializers"
"git.grassecon.net/term/config" "git.grassecon.net/term/config"
"git.grassecon.net/term/event/nats" "git.grassecon.net/term/event/nats"
) )
func init() {
initializers.LoadEnvVariables()
}
func main() { func main() {
ctx := context.Background() ctx := context.Background()
db := mem.NewMemDb() db := mem.NewMemDb()

View File

@ -1,18 +0,0 @@
package common
import (
"encoding/hex"
)
func NormalizeHex(s string) (string, error) {
if len(s) >= 2 {
if s[:2] == "0x" {
s = s[2:]
}
}
r, err := hex.DecodeString(s)
if err != nil {
return "", err
}
return hex.EncodeToString(r), nil
}

View File

@ -10,9 +10,6 @@ var (
JetstreamClientName string JetstreamClientName string
) )
func init() {
initializers.LoadEnvVariables()
}
func LoadConfig() { func LoadConfig() {
urdtconfig.LoadConfig() urdtconfig.LoadConfig()

View File

@ -13,10 +13,12 @@ const (
evReg = "CUSTODIAL_REGISTRATION" evReg = "CUSTODIAL_REGISTRATION"
) )
// fields used for handling custodial registration event.
type eventCustodialRegistration struct { type eventCustodialRegistration struct {
Account string Account string
} }
// attempt to coerce event as custodial registration.
func asCustodialRegistrationEvent(gev *geEvent.Event) (*eventCustodialRegistration, bool) { func asCustodialRegistrationEvent(gev *geEvent.Event) (*eventCustodialRegistration, bool) {
var ok bool var ok bool
var ev eventCustodialRegistration var ev eventCustodialRegistration
@ -32,6 +34,7 @@ func asCustodialRegistrationEvent(gev *geEvent.Event) (*eventCustodialRegistrati
return &ev, true return &ev, true
} }
// handle custodial registration.
func handleCustodialRegistration(ctx context.Context, store *common.UserDataStore, ev *eventCustodialRegistration) error { func handleCustodialRegistration(ctx context.Context, store *common.UserDataStore, ev *eventCustodialRegistration) error {
identity, err := lookup.IdentityFromAddress(ctx, store, ev.Account) identity, err := lookup.IdentityFromAddress(ctx, store, ev.Account)
if err != nil { if err != nil {

View File

@ -19,6 +19,9 @@ var (
logg = logging.NewVanilla().WithDomain("term-nats") logg = logging.NewVanilla().WithDomain("term-nats")
) )
// NatsSubscription encapsulates the jetstream session providing events.
//
// Extends Router.
type NatsSubscription struct { type NatsSubscription struct {
event.Router event.Router
ctx context.Context ctx context.Context
@ -28,6 +31,7 @@ type NatsSubscription struct {
cctx jetstream.ConsumeContext cctx jetstream.ConsumeContext
} }
// NewNatsSubscription creates a new NatsSubscription with the given user store.
func NewNatsSubscription(store db.Db) *NatsSubscription { func NewNatsSubscription(store db.Db) *NatsSubscription {
return &NatsSubscription{ return &NatsSubscription{
Router: event.Router{ Router: event.Router{
@ -38,19 +42,12 @@ func NewNatsSubscription(store db.Db) *NatsSubscription {
} }
} }
func toServerInfo(conn *nats.Conn) string { // Connect sets up the connection to the nats server and a consumer for the
return fmt.Sprintf("%s@%s (v%s)", conn.ConnectedServerName(), conn.ConnectedUrlRedacted(), conn.ConnectedServerVersion()) // "Jetstream".
} //
// Fails if connection fails or the "Jetstream" consumer cannot be set up.
func disconnectHandler(conn *nats.Conn, err error) { //
logg.Errorf("nats disconnected", "status", conn.Status(), "reconnects", conn.Stats().Reconnects, "err", err) // Once connected, it will attempt to reconnect if disconnected.
}
func reconnectHandler(conn *nats.Conn) {
serverInfo := toServerInfo(conn)
logg.Errorf("nats reconnected", "status", conn.Status(), "reconnects", conn.Stats().Reconnects, "server", serverInfo)
}
func(n *NatsSubscription) Connect(ctx context.Context, connStr string) error { func(n *NatsSubscription) Connect(ctx context.Context, connStr string) error {
var err error var err error
@ -84,6 +81,7 @@ func(n *NatsSubscription) Connect(ctx context.Context, connStr string) error {
return nil return nil
} }
// Close cleanly brings down the nats and jetstream connection.
func(n *NatsSubscription) Close() error { func(n *NatsSubscription) Close() error {
n.cctx.Stop() n.cctx.Stop()
select { select {
@ -93,13 +91,7 @@ func(n *NatsSubscription) Close() error {
return nil return nil
} }
func fail(m jetstream.Msg) { // jetstream message handler and acknowledger.
err := m.Nak()
if err != nil {
logg.Errorf("nats nak fail", "err", err)
}
}
func(n *NatsSubscription) handleEvent(m jetstream.Msg) { func(n *NatsSubscription) handleEvent(m jetstream.Msg) {
var ev geEvent.Event var ev geEvent.Event
@ -123,3 +115,27 @@ func(n *NatsSubscription) handleEvent(m jetstream.Msg) {
} }
logg.DebugCtxf(n.ctx, "handle msg complete") logg.DebugCtxf(n.ctx, "handle msg complete")
} }
// used if message should be retried.
func fail(m jetstream.Msg) {
err := m.Nak()
if err != nil {
logg.Errorf("nats nak fail", "err", err)
}
}
// server info string for debug.
func toServerInfo(conn *nats.Conn) string {
return fmt.Sprintf("%s@%s (v%s)", conn.ConnectedServerName(), conn.ConnectedUrlRedacted(), conn.ConnectedServerVersion())
}
// on nats disconnection.
func disconnectHandler(conn *nats.Conn, err error) {
logg.Errorf("nats disconnected", "status", conn.Status(), "reconnects", conn.Stats().Reconnects, "err", err)
}
// on nats reconnection.
func reconnectHandler(conn *nats.Conn) {
serverInfo := toServerInfo(conn)
logg.Errorf("nats reconnected", "status", conn.Status(), "reconnects", conn.Stats().Reconnects, "server", serverInfo)
}

View File

@ -10,19 +10,21 @@ import (
"git.grassecon.net/urdt/ussd/common" "git.grassecon.net/urdt/ussd/common"
) )
// TODO: this vocabulary should be public in and provided by the eth-tracker repo
const (
evGive = "FAUCET_GIVE"
)
var ( var (
logg = logging.NewVanilla().WithDomain("term-event") logg = logging.NewVanilla().WithDomain("term-event")
) )
// Router is responsible for invoking handlers corresponding to events.
type Router struct { type Router struct {
// User data store abstraction over application data.
Store *common.UserDataStore Store *common.UserDataStore
} }
// Route parses an event from the event stream, and resolves the handler
// corresponding to the event.
//
// An error will be returned if no handler can be found, or if the resolved
// handler fails to successfully execute.
func(r *Router) Route(ctx context.Context, gev *geEvent.Event) error { func(r *Router) Route(ctx context.Context, gev *geEvent.Event) error {
logg.DebugCtxf(ctx, "have event", "ev", gev) logg.DebugCtxf(ctx, "have event", "ev", gev)
evCC, ok := asCustodialRegistrationEvent(gev) evCC, ok := asCustodialRegistrationEvent(gev)

View File

@ -1,12 +0,0 @@
package event
import (
"context"
"io"
)
type Subscription interface {
io.Closer
Connect(ctx context.Context, connStr string) error
Next() error
}

View File

@ -16,14 +16,11 @@ import (
const ( const (
evTokenTransfer = "TOKEN_TRANSFER" evTokenTransfer = "TOKEN_TRANSFER"
// TODO: use export from urdt storage // TODO: export from urdt storage package
DATATYPE_USERSUB = 64 DATATYPE_USERSUB = 64
) )
func renderTx() { // fields used for handling token transfer event.
}
type eventTokenTransfer struct { type eventTokenTransfer struct {
From string From string
To string To string
@ -32,10 +29,14 @@ type eventTokenTransfer struct {
VoucherAddress string VoucherAddress string
} }
// formatter for transaction data
//
// TODO: current formatting is a placeholder.
func formatTransaction(idx int, tx dataserviceapi.Last10TxResponse) string { func formatTransaction(idx int, tx dataserviceapi.Last10TxResponse) string {
return fmt.Sprintf("%d %s %s", idx, tx.DateBlock, tx.TxHash[:10]) return fmt.Sprintf("%d %s %s", idx, tx.DateBlock, tx.TxHash[:10])
} }
// refresh and store transaction history.
func updateTokenTransferList(ctx context.Context, store *common.UserDataStore, identity lookup.Identity) error { func updateTokenTransferList(ctx context.Context, store *common.UserDataStore, identity lookup.Identity) error {
var r []string var r []string
@ -53,6 +54,9 @@ func updateTokenTransferList(ctx context.Context, store *common.UserDataStore, i
return store.WriteEntry(ctx, identity.SessionId, common.DATA_TRANSACTIONS, []byte(s)) return store.WriteEntry(ctx, identity.SessionId, common.DATA_TRANSACTIONS, []byte(s))
} }
// refresh and store token list.
//
// TODO: when subprefixdb has been exported, can use function in ...urdt/ussd/common/ instead
func updateTokenList(ctx context.Context, store *common.UserDataStore, identity lookup.Identity) error { func updateTokenList(ctx context.Context, store *common.UserDataStore, identity lookup.Identity) error {
holdings, err := lookup.Api.FetchVouchers(ctx, identity.ChecksumAddress) holdings, err := lookup.Api.FetchVouchers(ctx, identity.ChecksumAddress)
if err != nil { if err != nil {
@ -61,7 +65,6 @@ func updateTokenList(ctx context.Context, store *common.UserDataStore, identity
metadata := common.ProcessVouchers(holdings) metadata := common.ProcessVouchers(holdings)
_ = metadata _ = metadata
// TODO: export subprefixdb and use that instead
// TODO: make sure subprefixdb is thread safe when using gdbm // TODO: make sure subprefixdb is thread safe when using gdbm
// TODO: why is address session here unless explicitly set // TODO: why is address session here unless explicitly set
store.Db.SetSession(identity.SessionId) store.Db.SetSession(identity.SessionId)
@ -94,6 +97,7 @@ func updateTokenList(ctx context.Context, store *common.UserDataStore, identity
return nil return nil
} }
// set default token to given symbol.
func updateDefaultToken(ctx context.Context, store *common.UserDataStore, identity lookup.Identity, activeSym string) error { func updateDefaultToken(ctx context.Context, store *common.UserDataStore, identity lookup.Identity, activeSym string) error {
pfxDb := common.StoreToPrefixDb(store, []byte("vouchers")) pfxDb := common.StoreToPrefixDb(store, []byte("vouchers"))
// TODO: the activeSym input should instead be newline separated list? // TODO: the activeSym input should instead be newline separated list?
@ -101,14 +105,15 @@ func updateDefaultToken(ctx context.Context, store *common.UserDataStore, identi
if err != nil { if err != nil {
return err return err
} }
logg.TraceCtxf(ctx, "tokendaa", "d", tokenData)
return common.UpdateVoucherData(ctx, store, identity.SessionId, tokenData) return common.UpdateVoucherData(ctx, store, identity.SessionId, tokenData)
} }
// waiter to check whether object is available on dependency endpoints.
func updateWait(ctx context.Context) error { func updateWait(ctx context.Context) error {
return nil return nil
} }
// use api to resolve address to token symbol.
func toSym(ctx context.Context, address string) ([]byte, error) { func toSym(ctx context.Context, address string) ([]byte, error) {
voucherData, err := lookup.Api.VoucherData(ctx, address) voucherData, err := lookup.Api.VoucherData(ctx, address)
if err != nil { if err != nil {
@ -117,6 +122,7 @@ func toSym(ctx context.Context, address string) ([]byte, error) {
return []byte(voucherData.TokenSymbol), nil return []byte(voucherData.TokenSymbol), nil
} }
// execute all
func updateToken(ctx context.Context, store *common.UserDataStore, identity lookup.Identity, tokenAddress string) error { func updateToken(ctx context.Context, store *common.UserDataStore, identity lookup.Identity, tokenAddress string) error {
err := updateTokenList(ctx, store, identity) err := updateTokenList(ctx, store, identity)
if err != nil { if err != nil {
@ -152,6 +158,7 @@ func updateToken(ctx context.Context, store *common.UserDataStore, identity look
return nil return nil
} }
// attempt to coerce event as token transfer event.
func asTokenTransferEvent(gev *geEvent.Event) (*eventTokenTransfer, bool) { func asTokenTransferEvent(gev *geEvent.Event) (*eventTokenTransfer, bool) {
var err error var err error
var ok bool var ok bool
@ -162,7 +169,7 @@ func asTokenTransferEvent(gev *geEvent.Event) (*eventTokenTransfer, bool) {
} }
pl := gev.Payload pl := gev.Payload
// assuming from and to are checksum addresses // we are assuming from and to are checksum addresses
ev.From, ok = pl["from"].(string) ev.From, ok = pl["from"].(string)
if !ok { if !ok {
return nil, false return nil, false
@ -192,6 +199,9 @@ func asTokenTransferEvent(gev *geEvent.Event) (*eventTokenTransfer, bool) {
return &ev, true return &ev, true
} }
// handle token transfer.
//
// if from and to are NOT the same, handle code will be executed once for each side of the transfer.
func handleTokenTransfer(ctx context.Context, store *common.UserDataStore, ev *eventTokenTransfer) error { func handleTokenTransfer(ctx context.Context, store *common.UserDataStore, ev *eventTokenTransfer) error {
identity, err := lookup.IdentityFromAddress(ctx, store, ev.From) identity, err := lookup.IdentityFromAddress(ctx, store, ev.From)
if err != nil { if err != nil {
@ -204,6 +214,8 @@ func handleTokenTransfer(ctx context.Context, store *common.UserDataStore, ev *e
return err return err
} }
} }
if strings.Compare(ev.To, ev.From) {
identity, err = lookup.IdentityFromAddress(ctx, store, ev.To) identity, err = lookup.IdentityFromAddress(ctx, store, ev.To)
if err != nil { if err != nil {
if !db.IsNotFound(err) { if !db.IsNotFound(err) {
@ -215,6 +227,7 @@ func handleTokenTransfer(ctx context.Context, store *common.UserDataStore, ev *e
return err return err
} }
} }
}
return nil return nil
} }

View File

@ -1,9 +0,0 @@
package handler
import (
"fmt"
)
var (
ErrInvalidPayload = fmt.Errorf("Invalid event payload")
)

View File

@ -12,12 +12,19 @@ var (
logg = logging.NewVanilla().WithDomain("term-lookup") logg = logging.NewVanilla().WithDomain("term-lookup")
) )
// Identity contains all flavors of identifiers used across stream, api and
// client for a single agent.
type Identity struct { type Identity struct {
NormalAddress string NormalAddress string
ChecksumAddress string ChecksumAddress string
SessionId string SessionId string
} }
// IdentityFromAddress fully populates and Identity object from a given
// checksum address.
//
// It is the caller's responsibility to ensure that a valid checksum address
// is passed.
func IdentityFromAddress(ctx context.Context, store *common.UserDataStore, address string) (Identity, error) { func IdentityFromAddress(ctx context.Context, store *common.UserDataStore, address string) (Identity, error) {
var err error var err error
var ident Identity var ident Identity
@ -34,6 +41,7 @@ func IdentityFromAddress(ctx context.Context, store *common.UserDataStore, addre
return ident, nil return ident, nil
} }
// load matching session from address from db store.
func getSessionIdByAddress(ctx context.Context, store *common.UserDataStore, address string) (string, error) { func getSessionIdByAddress(ctx context.Context, store *common.UserDataStore, address string) (string, error) {
// TODO: replace with userdatastore when double sessionid issue fixed // TODO: replace with userdatastore when double sessionid issue fixed
//r, err := store.ReadEntry(ctx, address, common.DATA_PUBLIC_KEY_REVERSE) //r, err := store.ReadEntry(ctx, address, common.DATA_PUBLIC_KEY_REVERSE)

View File

@ -5,5 +5,6 @@ import (
) )
var ( var (
// Api provides the api implementation for all external lookups.
Api remote.AccountServiceInterface = &remote.AccountService{} Api remote.AccountServiceInterface = &remote.AccountService{}
) )