package graph
import (
"context"
"errors"
"fmt"
"log/slog"
"runtime"
"slices"
"sync"
"time"
"gorm.io/gorm"
amtypes "github.com/pancsta/asyncmachine-go/pkg/graph/types"
amhist "github.com/pancsta/asyncmachine-go/pkg/history"
amhistgorm "github.com/pancsta/asyncmachine-go/pkg/history/gorm"
am "github.com/pancsta/asyncmachine-go/pkg/machine"
"github.com/pancsta/asyncmachine-go/pkg/rpc"
)
var (
ErrHistory = errors .New ("history graph error" )
ErrHistoryParams = errors .New ("history params error" )
ErrHistoryAction = errors .New ("history action error" )
ErrMachineNotTracked = errors .New ("machine not tracked" )
)
type HistoryGraph struct {
*Graph
Cfg amhistgorm .Config
Dbs []*gorm .DB
ctx context .Context
onErr func (err error )
parent am .Api
ownPar *am .Machine
mx sync .Mutex
machs map [string ]*historyMach
shardOf map [string ]uint8
shardLen []int
gen map [string ]uint64
genSeq uint64
pending map [string ]string
pendingClocks map [string ]pendingClock
regCh chan trackReq
regWg sync .WaitGroup
stop chan struct {}
stopOnce sync .Once
}
type pendingClock struct {
mTime am .Time
qTick uint64
machTick uint32
}
type trackReq struct {
c *Machine
shard uint8
gen uint64
}
type HistoryGraphOpts struct {
OnErr func (err error )
Parent am .Api
}
type historyMach struct {
mx sync .Mutex
netMach *rpc .NetworkMachine
nmInt *rpc .NetMachInternal
mem amhist .MemoryApi
hash string
states int
shard uint8
}
type HistParams struct {
State string
States am .S
Start time .Time
End time .Time
Limit int
Query amhist .Query
}
type HistoryResp struct {
Action amtypes .HistoryAction `json:"action"`
Machine string `json:"machine"`
Bool bool `json:"bool,omitempty"`
State string `json:"state,omitempty"`
Records []*amhist .MemoryRecord `json:"records,omitempty"`
Record *amhist .MachineRecord `json:"record,omitempty"`
}
func NewHistoryGraph (
g *Graph , dbs []*gorm .DB , cfg amhistgorm .Config , opts ...HistoryGraphOpts ,
) (*HistoryGraph , error ) {
if g == nil {
return nil , fmt .Errorf ("%w: graph is nil" , ErrHistory )
}
if len (dbs ) == 0 {
return nil , fmt .Errorf ("%w: no dbs" , ErrHistory )
}
if len (dbs ) > 255 {
return nil , fmt .Errorf ("%w: too many shards: %d" , ErrHistory , len (dbs ))
}
for i , db := range dbs {
if db == nil {
return nil , fmt .Errorf ("%w: db %d is nil" , ErrHistory , i )
}
if err := amhistgorm .Migrate (db ); err != nil {
return nil , fmt .Errorf ("%w: migrate shard %d: %w" , ErrHistory , i , err )
}
}
hg := &HistoryGraph {
Graph : g ,
Cfg : cfg ,
Dbs : dbs ,
ctx : context .Background (),
machs : make (map [string ]*historyMach ),
shardOf : make (map [string ]uint8 ),
shardLen : make ([]int , len (dbs )),
gen : make (map [string ]uint64 ),
pending : make (map [string ]string ),
pendingClocks : make (map [string ]pendingClock ),
regCh : make (chan trackReq , 4096 ),
stop : make (chan struct {}),
}
hg .Cfg .KeepDb = true
hg .Cfg .SkipMigrate = true
if g .ParentMach != nil {
hg .ctx = g .ParentMach .Context ()
}
hg .onErr = func (err error ) {
if g .ParentMach != nil {
g .ParentMach .AddErr (err , nil )
return
}
slog .Error ("history graph" , "err" , err )
}
hg .parent = g .ParentMach
for _ , opt := range opts {
if opt .OnErr != nil {
hg .onErr = opt .OnErr
}
if opt .Parent != nil {
hg .parent = opt .Parent
}
}
if hg .parent == nil {
hg .ownPar = am .New (hg .ctx , nil , &am .Opts {Id : "history-graph" })
hg .parent = hg .ownPar
}
g .hist = hg
for range dbs {
hg .regWg .Add (1 )
go hg .regLoop ()
}
g .loop .Lock ()
for _ , c := range g .Machines {
hg .Track (c )
}
g .loop .Unlock ()
return hg , nil
}
func (hg *HistoryGraph ) Track (c *Machine ) {
if c == nil || c .Serialized == nil {
return
}
hg .mx .Lock ()
if old := hg .machs [c .ID ]; old != nil && old .hash == c .SchemaHash {
hg .mx .Unlock ()
return
}
if hash , ok := hg .pending [c .ID ]; ok && hash == c .SchemaHash {
hg .mx .Unlock ()
return
}
shard := hg .assignShard (c .ID )
hg .genSeq ++
gen := hg .genSeq
hg .gen [c .ID ] = gen
hg .pending [c .ID ] = c .SchemaHash
hg .mx .Unlock ()
select {
case <- hg .stop :
return
default :
}
req := trackReq {c : c .Clone (), shard : shard , gen : gen }
select {
case hg .regCh <- req :
case <- hg .stop :
}
}
func (hg *HistoryGraph ) assignShard (id string ) uint8 {
if s , ok := hg .shardOf [id ]; ok {
return s
}
s := 0
for i := 1 ; i < len (hg .shardLen ); i ++ {
if hg .shardLen [i ] < hg .shardLen [s ] {
s = i
}
}
hg .shardOf [id ] = uint8 (s )
hg .shardLen [s ]++
return uint8 (s )
}
func (hg *HistoryGraph ) regLoop () {
defer hg .regWg .Done ()
for {
select {
case <- hg .stop :
return
default :
}
select {
case <- hg .stop :
return
case req := <- hg .regCh :
hg .regMachine (req )
}
}
}
func (hg *HistoryGraph ) regMachine (req trackReq ) {
c := req .c
schema := normalizeSchema (c .Schema , c .StateNames )
netMach , nmInt , err := rpc .NewNetworkMachine (hg .ctx , c .ID , nil , schema ,
c .StateNames , hg .parent , nil , false )
if err != nil {
hg .regFailed (req , fmt .Errorf ("%w: %s: %w" , ErrHistory , c .ID , err ))
return
}
mem , err := amhistgorm .NewMemory (hg .ctx , hg .Dbs [req .shard ], netMach ,
hg .Cfg , hg .onErr )
if err != nil {
netMach .Dispose ()
hg .regFailed (req , err )
return
}
hm := &historyMach {
netMach : netMach ,
nmInt : nmInt ,
mem : mem ,
hash : c .SchemaHash ,
states : len (c .StateNames ),
shard : req .shard ,
}
hg .mx .Lock ()
if hg .gen [c .ID ] != req .gen {
hg .mx .Unlock ()
_ = mem .Dispose ()
netMach .Dispose ()
return
}
old := hg .machs [c .ID ]
hg .machs [c .ID ] = hm
delete (hg .pending , c .ID )
pc , hasPC := hg .pendingClocks [c .ID ]
delete (hg .pendingClocks , c .ID )
hg .mx .Unlock ()
if old != nil {
hg .dispose (old )
}
if hasPC {
hm .update (pc .mTime , pc .qTick , pc .machTick )
} else if c .MTimeSum > 0 {
hm .update (c .Time , c .QueueTick , c .MachineTick )
}
}
func (hg *HistoryGraph ) regFailed (req trackReq , err error ) {
hg .mx .Lock ()
if hg .gen [req .c .ID ] == req .gen {
delete (hg .pending , req .c .ID )
delete (hg .pendingClocks , req .c .ID )
}
hg .mx .Unlock ()
hg .onErr (err )
}
func (hg *HistoryGraph ) Update (
id string , mTime am .Time , qTick uint64 , machTick uint32 ,
) {
hg .mx .Lock ()
_ , pending := hg .pending [id ]
if hm := hg .machs [id ]; hm != nil && !pending {
hg .mx .Unlock ()
hm .update (mTime , qTick , machTick )
return
}
if _ , ok := hg .gen [id ]; ok {
hg .pendingClocks [id ] = pendingClock {
mTime : slices .Clone (mTime ),
qTick : qTick ,
machTick : machTick ,
}
}
hg .mx .Unlock ()
}
func (hg *HistoryGraph ) Remove (id string ) {
hg .mx .Lock ()
delete (hg .gen , id )
delete (hg .pending , id )
delete (hg .pendingClocks , id )
hm := hg .machs [id ]
delete (hg .machs , id )
if s , ok := hg .shardOf [id ]; ok {
delete (hg .shardOf , id )
hg .shardLen [s ]--
}
hg .mx .Unlock ()
if hm != nil {
hg .dispose (hm )
}
}
func (hg *HistoryGraph ) ShardCounts () []int {
hg .mx .Lock ()
defer hg .mx .Unlock ()
return slices .Clone (hg .shardLen )
}
func (hg *HistoryGraph ) TrackedCount () int {
hg .mx .Lock ()
defer hg .mx .Unlock ()
return len (hg .machs )
}
func (hg *HistoryGraph ) ShardOf (id string ) (uint8 , bool ) {
hg .mx .Lock ()
defer hg .mx .Unlock ()
if hm := hg .machs [id ]; hm != nil {
return hm .shard , true
}
s , ok := hg .shardOf [id ]
return s , ok
}
func (hg *HistoryGraph ) History (
ctx context .Context , id string , action amtypes .HistoryAction , p HistParams ,
) (*HistoryResp , error ) {
hg .mx .Lock ()
hm := hg .machs [id ]
hg .mx .Unlock ()
if hm == nil {
return nil , fmt .Errorf ("%w: %s" , ErrMachineNotTracked , id )
}
resp := &HistoryResp {Action : action , Machine : id }
mem := hm .mem
switch action {
case amtypes .HistActivatedBetween , amtypes .HistActiveBetween ,
amtypes .HistDeactivatedBetween , amtypes .HistInactiveBetween :
if p .State == "" {
return nil , fmt .Errorf ("%w: state is required" , ErrHistoryParams )
}
switch action {
case amtypes .HistActivatedBetween :
resp .Bool = mem .ActivatedBetween (ctx , p .State , p .Start , p .End )
case amtypes .HistActiveBetween :
resp .Bool = mem .ActiveBetween (ctx , p .State , p .Start , p .End )
case amtypes .HistDeactivatedBetween :
resp .Bool = mem .DeactivatedBetween (ctx , p .State , p .Start , p .End )
case amtypes .HistInactiveBetween :
resp .Bool = mem .InactiveBetween (ctx , p .State , p .Start , p .End )
}
case amtypes .HistLatestActivated , amtypes .HistLatestDeactivated :
if len (p .States ) == 0 {
return nil , fmt .Errorf ("%w: states are required" , ErrHistoryParams )
}
if action == amtypes .HistLatestActivated {
resp .State = mem .LatestActivated (ctx , p .States ...)
} else {
resp .State = mem .LatestDeactivated (ctx , p .States ...)
}
case amtypes .HistFindLatest :
if err := mem .Sync (ctx ); err != nil {
return nil , err
}
limit := p .Limit
if limit <= 0 {
limit = 100
}
records , err := mem .FindLatest (ctx , true , limit , p .Query )
if err != nil {
return nil , err
}
resp .Records = records
resp .Record = mem .MachineRecord ()
default :
return nil , fmt .Errorf ("%w: %s" , ErrHistoryAction , action .Value )
}
return resp , nil
}
func (hg *HistoryGraph ) Close () error {
hg .Graph .loop .Lock ()
if hg .Graph .hist == hg {
hg .Graph .hist = nil
}
hg .Graph .loop .Unlock ()
hg .stopOnce .Do (func () { close (hg .stop ) })
hg .regWg .Wait ()
hg .clearAll ()
if hg .ownPar != nil {
hg .ownPar .Dispose ()
hg .ownPar = nil
}
return nil
}
func (hg *HistoryGraph ) clearAll () {
hg .mx .Lock ()
clear (hg .gen )
clear (hg .pending )
clear (hg .pendingClocks )
clear (hg .shardOf )
for i := range hg .shardLen {
hg .shardLen [i ] = 0
}
list := make ([]*historyMach , 0 , len (hg .machs ))
for id , hm := range hg .machs {
list = append (list , hm )
delete (hg .machs , id )
}
hg .mx .Unlock ()
sem := make (chan struct {}, runtime .NumCPU ())
var wg sync .WaitGroup
for _ , hm := range list {
wg .Add (1 )
sem <- struct {}{}
go func (hm *historyMach ) {
defer wg .Done ()
defer func () { <-sem }()
hg .dispose (hm )
}(hm )
}
wg .Wait ()
}
func (hg *HistoryGraph ) dispose (hm *historyMach ) {
hm .mx .Lock ()
defer hm .mx .Unlock ()
_ = hm .mem .Dispose ()
hm .netMach .Dispose ()
}
func (hm *historyMach ) update (
mTime am .Time , qTick uint64 , machTick uint32 ,
) {
hm .mx .Lock ()
defer hm .mx .Unlock ()
if len (mTime ) != hm .states {
return
}
hm .nmInt .Lock ()
hm .nmInt .UpdateClock (slices .Clone (mTime ), qTick , machTick )
}
func normalizeSchema(schema am .Schema , stateNames am .S ) am .Schema {
ret := make (am .Schema , len (stateNames ))
for _ , name := range stateNames {
ret [name ] = schema [name ]
}
return ret
}
The pages are generated with Golds v0.8.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .