github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/modules/operator/pool/pool.go (about)

     1  package pool
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"sync"
     7  
     8  	"github.com/machinefi/w3bstream/pkg/depends/kit/sqlx"
     9  	"github.com/machinefi/w3bstream/pkg/modules/operator"
    10  	optypes "github.com/machinefi/w3bstream/pkg/modules/operator/pool/types"
    11  	"github.com/machinefi/w3bstream/pkg/types"
    12  )
    13  
    14  type Pool struct {
    15  	db        sqlx.DBExecutor
    16  	mux       sync.RWMutex
    17  	operators map[string]*optypes.SyncOperator
    18  }
    19  
    20  func (p *Pool) getKey(accountID types.SFID, opName string) string {
    21  	return fmt.Sprintf("%d-%s", accountID, opName)
    22  }
    23  
    24  func (p *Pool) Get(accountID types.SFID, opName string) (*optypes.SyncOperator, error) {
    25  	key := p.getKey(accountID, opName)
    26  
    27  	p.mux.RLock()
    28  	op, ok := p.operators[key]
    29  	p.mux.RUnlock()
    30  
    31  	if ok {
    32  		return op, nil
    33  	}
    34  
    35  	return p.setOperator(accountID, opName)
    36  }
    37  
    38  func (p *Pool) setOperator(accountID types.SFID, opName string) (*optypes.SyncOperator, error) {
    39  	p.mux.Lock()
    40  	defer p.mux.Unlock()
    41  
    42  	key := p.getKey(accountID, opName)
    43  	sop, ok := p.operators[key]
    44  	if ok {
    45  		return sop, nil
    46  	}
    47  
    48  	op, err := operator.GetByAccountAndName(types.WithMgrDBExecutor(context.Background(), p.db), accountID, opName)
    49  	if err != nil {
    50  		return nil, err
    51  	}
    52  	nsop := &optypes.SyncOperator{
    53  		Op: op,
    54  	}
    55  	p.operators[key] = nsop
    56  	return nsop, nil
    57  }
    58  
    59  func (p *Pool) Delete(id types.SFID) error {
    60  	ctx := types.WithMgrDBExecutor(context.Background(), p.db)
    61  	op, err := operator.GetBySFID(ctx, id)
    62  	if err != nil {
    63  		return err
    64  	}
    65  	if err := operator.RemoveBySFID(ctx, id); err != nil {
    66  		return err
    67  	}
    68  
    69  	key := p.getKey(op.AccountID, op.Name)
    70  
    71  	p.mux.Lock()
    72  	defer p.mux.Unlock()
    73  	delete(p.operators, key)
    74  
    75  	return nil
    76  }
    77  
    78  // operator memory pool
    79  func NewPool(mgrDB sqlx.DBExecutor) optypes.Pool {
    80  	return &Pool{
    81  		db:        mgrDB,
    82  		operators: make(map[string]*optypes.SyncOperator),
    83  	}
    84  }