gcx/backend/services/chain-indexer/internal/indexer/indexer.go

82 lines
1.6 KiB
Go

package indexer
import (
"fmt"
"sync"
"time"
"go.uber.org/zap"
"github.com/genex/chain-indexer/internal/domain/entity"
)
type Indexer struct {
logger *zap.Logger
lastHeight int64
blocks []entity.Block
transactions []entity.ChainTransaction
mu sync.RWMutex
isRunning bool
}
func NewIndexer(logger *zap.Logger) *Indexer {
return &Indexer{logger: logger}
}
func (idx *Indexer) Start() {
idx.isRunning = true
idx.logger.Info("Chain indexer started (mock mode)")
go func() {
ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
for idx.isRunning {
select {
case <-ticker.C:
idx.mockIndexBlock()
}
}
}()
}
func (idx *Indexer) Stop() {
idx.isRunning = false
idx.logger.Info("Chain indexer stopped")
}
func (idx *Indexer) GetLastHeight() int64 {
idx.mu.RLock()
defer idx.mu.RUnlock()
return idx.lastHeight
}
func (idx *Indexer) GetRecentBlocks(limit int) []entity.Block {
idx.mu.RLock()
defer idx.mu.RUnlock()
start := len(idx.blocks) - limit
if start < 0 {
start = 0
}
result := make([]entity.Block, len(idx.blocks[start:]))
copy(result, idx.blocks[start:])
return result
}
func (idx *Indexer) mockIndexBlock() {
idx.mu.Lock()
defer idx.mu.Unlock()
idx.lastHeight++
block := entity.Block{
Height: idx.lastHeight,
Hash: fmt.Sprintf("0x%064d", idx.lastHeight),
Timestamp: time.Now(),
TxCount: 0,
}
idx.blocks = append(idx.blocks, block)
// Keep only last 1000 blocks in memory
if len(idx.blocks) > 1000 {
idx.blocks = idx.blocks[len(idx.blocks)-1000:]
}
idx.logger.Debug("Indexed mock block", zap.Int64("height", idx.lastHeight))
}