velocity.go48 lines, 1.5 KB
| 1 | package risk |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | _ "embed" |
| 6 | "fmt" |
| 7 | "time" |
| 8 | |
| 9 | "github.com/google/uuid" |
| 10 | "github.com/redis/go-redis/v9" |
| 11 | ) |
| 12 | |
| 13 | //go:embed velocity.lua |
| 14 | var velocityLua string |
| 15 | |
| 16 | var velocityScript = redis.NewScript(velocityLua) |
| 17 | |
| 18 | // Recent is a user's recent transfers. |
| 19 | type Recent struct { |
| 20 | Count int // in the count window |
| 21 | Amount int64 // in the amount window, in US cents |
| 22 | } |
| 23 | |
| 24 | // Velocity keeps each user's recent transfers in Redis, so every instance of |
| 25 | // the transfer service sees the same numbers. |
| 26 | type Velocity struct { |
| 27 | rdb *redis.Client |
| 28 | countWindow, amountWindow time.Duration |
| 29 | } |
| 30 | |
| 31 | // NewVelocity returns a Velocity that counts transfers in countWindow, and |
| 32 | // adds up their amounts in amountWindow, the longer one. |
| 33 | func NewVelocity(rdb *redis.Client, countWindow, amountWindow time.Duration) *Velocity { |
| 34 | return &Velocity{rdb: rdb, countWindow: countWindow, amountWindow: amountWindow} |
| 35 | } |
| 36 | |
| 37 | // Record adds transfer id, of amount, to user's recent transfers, once, and |
| 38 | // returns them, this one included. |
| 39 | func (v *Velocity) Record(ctx context.Context, user, id uuid.UUID, amount int64) (Recent, error) { |
| 40 | key := "risk:velocity:" + user.String() |
| 41 | member := fmt.Sprintf("%s:%d", id, amount) |
| 42 | res, err := velocityScript.Run(ctx, v.rdb, []string{key}, member, |
| 43 | v.countWindow.Milliseconds(), v.amountWindow.Milliseconds()).Int64Slice() |
| 44 | if err != nil { |
| 45 | return Recent{}, fmt.Errorf("velocity of %s: %w", user, err) |
| 46 | } |
| 47 | return Recent{Count: int(res[0]), Amount: res[1]}, nil |
| 48 | } |