github.com/onflow/flow-go@v0.35.7-crescendo-preview.23-atree-inlining/module/jobqueue/finalized_block_reader.go (about)

     1  package jobqueue
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/onflow/flow-go/model/flow"
     7  	"github.com/onflow/flow-go/module"
     8  	"github.com/onflow/flow-go/state/protocol"
     9  	"github.com/onflow/flow-go/storage"
    10  )
    11  
    12  // FinalizedBlockReader provides an abstraction for consumers to read blocks as job.
    13  type FinalizedBlockReader struct {
    14  	state  protocol.State
    15  	blocks storage.Blocks
    16  }
    17  
    18  var _ module.Jobs = (*FinalizedBlockReader)(nil)
    19  
    20  // NewFinalizedBlockReader creates and returns a FinalizedBlockReader.
    21  func NewFinalizedBlockReader(state protocol.State, blocks storage.Blocks) *FinalizedBlockReader {
    22  	return &FinalizedBlockReader{
    23  		state:  state,
    24  		blocks: blocks,
    25  	}
    26  }
    27  
    28  // AtIndex returns the block job at the given index.
    29  // The block job at an index is just the finalized block at that index (i.e., height).
    30  func (r FinalizedBlockReader) AtIndex(index uint64) (module.Job, error) {
    31  	block, err := r.blockByHeight(index)
    32  	if err != nil {
    33  		return nil, fmt.Errorf("could not get block by index %v: %w", index, err)
    34  	}
    35  	return BlockToJob(block), nil
    36  }
    37  
    38  // blockByHeight returns the block at the given height.
    39  func (r FinalizedBlockReader) blockByHeight(height uint64) (*flow.Block, error) {
    40  	block, err := r.blocks.ByHeight(height)
    41  	if err != nil {
    42  		return nil, fmt.Errorf("could not get block by height %d: %w", height, err)
    43  	}
    44  
    45  	return block, nil
    46  }
    47  
    48  // Head returns the last finalized height as job index.
    49  func (r FinalizedBlockReader) Head() (uint64, error) {
    50  	header, err := r.state.Final().Head()
    51  	if err != nil {
    52  		return 0, fmt.Errorf("could not get header of last finalized block: %w", err)
    53  	}
    54  
    55  	return header.Height, nil
    56  }