github.com/ethersphere/bee/v2@v2.2.0/pkg/feeds/epochs/updater.go (about)

     1  // Copyright 2021 The Swarm Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package epochs
     6  
     7  import (
     8  	"context"
     9  
    10  	"github.com/ethersphere/bee/v2/pkg/crypto"
    11  	"github.com/ethersphere/bee/v2/pkg/feeds"
    12  	storage "github.com/ethersphere/bee/v2/pkg/storage"
    13  )
    14  
    15  var _ feeds.Updater = (*updater)(nil)
    16  
    17  // Updater encapsulates a feeds putter to generate successive updates for epoch based feeds
    18  // it persists the last update
    19  type updater struct {
    20  	*feeds.Putter
    21  	last  int64
    22  	epoch feeds.Index
    23  }
    24  
    25  // NewUpdater constructs a feed updater
    26  func NewUpdater(putter storage.Putter, signer crypto.Signer, topic []byte) (feeds.Updater, error) {
    27  	p, err := feeds.NewPutter(putter, signer, topic)
    28  	if err != nil {
    29  		return nil, err
    30  	}
    31  	return &updater{Putter: p}, nil
    32  }
    33  
    34  // Update pushes an update to the feed through the chunk stores
    35  func (u *updater) Update(ctx context.Context, at int64, payload []byte) error {
    36  	e := next(u.epoch, u.last, uint64(at))
    37  	err := u.Put(ctx, e, at, payload)
    38  	if err != nil {
    39  		return err
    40  	}
    41  	u.last = at
    42  	u.epoch = e
    43  	return nil
    44  }
    45  
    46  func (u *updater) Feed() *feeds.Feed {
    47  	return u.Putter.Feed
    48  }