kvdb

package
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 1, 2026 License: BSD-3-Clause Imports: 30 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package crdt provides a replicated go-datastore (key-value store) implementation using Merkle-CRDTs built with IPLD nodes.

This Datastore is agnostic to how new MerkleDAG roots are broadcasted to the rest of replicas (`Broadcaster` component) and to how the IPLD nodes are made discoverable and retrievable to by other replicas (`DAGSyncer` component).

The implementation is based on the "Merkle-CRDTs: Merkle-DAGs meet CRDTs" paper by Héctor Sanjuán, Samuli Pöyhtäri and Pedro Teixeira.

Note that, in the absence of compaction, a crdt.Datastore will only grow in size even when keys are deleted: deleting a key adds a tombstone without removing the history that preceded it. Compact (or, for outright deletion of a whole named DAG's history, PurgeDAG) can be called manually to fold a named DAG's live state into a small "snapshot" generation and discard the DAG history it replaces. Compact is coordination-free, like every other operation this package exposes: it needs no quiescence or single-writer guarantee from the caller. See the Compact doc comment for the full algorithm and the (non-mandatory) notes on replica upgrade ordering.

The time to be fully synced for new Datastore replicas will depend on how fast they can retrieve the DAGs announced by the other replicas, but newer values will be available before older ones.

Index

Constants

This section is empty.

Variables

View Source
var (
	QueryBufferSize        = 1024
	ReadQueryResultTimeout = 50 * time.Millisecond
)
View Source
var (
	ErrNoMoreBroadcast = errors.New("receiving blocks aborted since no new blocks will be broadcasted")
)

Common errors.

View Source
var MaxTimeBetweenGroupedWrites = 5 * time.Millisecond

Functions

func New

func New(node peer.Node) kvdb.Factory

func NewStats

func NewStats() kvdb.Stats

Types

type BasicPubSubBroadcaster added in v1.2.0

type BasicPubSubBroadcaster struct {
	// contains filtered or unexported fields
}

BasicPubSubBroadcaster implements a Broadcaster using libp2p PubSub.

func NewBasicPubSubBroadcaster added in v1.2.0

func NewBasicPubSubBroadcaster(ctx context.Context, psub *pubsub.PubSub, topic string) (*BasicPubSubBroadcaster, error)

NewBasicPubSubBroadcaster returns a new broadcaster using the given PubSub and a topic to subscribe/broadcast to. The given context can be used to cancel the broadcaster. Please register any topic validators before creating the Broadcaster.

The broadcaster can be shut down by cancelling the given context. This must be done before Closing the crdt.Datastore, otherwise things may hang.

func (*BasicPubSubBroadcaster) Broadcast added in v1.2.0

func (pbc *BasicPubSubBroadcaster) Broadcast(ctx context.Context, data []byte) error

Broadcast publishes some data.

func (*BasicPubSubBroadcaster) Next added in v1.2.0

func (pbc *BasicPubSubBroadcaster) Next(ctx context.Context) ([]byte, error)

Next returns published data.

type Broadcaster added in v1.2.0

type Broadcaster interface {
	// Send payload to other replicas.
	Broadcast(context.Context, []byte) error
	// Obtain the next payload received from the network.
	Next(context.Context) ([]byte, error)
}

A Broadcaster provides a way to send (notify) an opaque payload to all replicas and to retrieve payloads broadcasted.

type Datastore added in v1.2.0

type Datastore struct {
	// contains filtered or unexported fields
}

Datastore makes a go-datastore a distributed Key-Value store using Merkle-CRDTs and IPLD.

func NewDatastore added in v1.2.0

func NewDatastore(
	store ds.Datastore,
	namespace ds.Key,
	dagSyncer ipld.DAGService,
	bcast Broadcaster,
	opts *Options,
) (*Datastore, error)

New returns a Merkle-CRDT-based Datastore using the given one to persist all the necessary data under the given namespace. It needs a DAG-Service component for IPLD nodes and a Broadcaster component to distribute and receive information to and from the rest of replicas. Actual implementation of these must be provided by the user, but it normally means using ipfs-lite (https://github.com/hsanjuan/ipfs-lite) as a DAG Service and the included libp2p PubSubBroadcaster as a Broadcaster.

The given Datastore is used to back all CRDT-datastore contents and accounting information. When using an asynchronous datastore, the user is in charge of calling Sync() regularly. Sync() will persist paths related to the given prefix, but note that if other replicas are modifying the datastore, the prefixes that will need syncing are not only those modified by the local replica. Therefore the user should consider calling Sync("/"), with an empty prefix, in that case, or use a synchronous underlying datastore that persists things directly on write.

The CRDT-Datastore should call Close() before the given store is closed.

func (*Datastore) Batch added in v1.2.0

func (store *Datastore) Batch(ctx context.Context) (ds.Batch, error)

Batch implements batching for writes by accumulating Put and Delete in the same CRDT-delta and only applying it and broadcasting it on Commit().

func (*Datastore) Close added in v1.2.0

func (store *Datastore) Close() error

Close shuts down the CRDT datastore. It should not be used afterwards.

func (*Datastore) Compact added in v1.2.0

func (store *Datastore) Compact(ctx context.Context, dagName string) (int, error)

Compact rewrites a named DAG's live state as one or more small "snapshot" generation blocks and purges the DAG history that is now redundant with them, returning the number of DAG blocks purged. Compacting the default (unnamed) DAG is Compact(ctx, "").

What it does

Compact walks the named DAG's history locally (never touching the network) starting from its current heads, exactly like PurgeDAG. For every key touched by that history it computes the same "best value" that findBestValue would (highest priority, ties broken by the greatest value) and, separately, which of the key's tombstones must be carried forward (see below). It then builds one or more new DAG blocks -- "snapshot" nodes, marked as such via Delta.IsSnapshot -- containing exactly that live state, linked to all the heads it covers, and merges them locally (replacing the covered heads with the new snapshot head(s)). Finally it purges the old DAG blocks and their set entries, and broadcasts the new snapshot head(s).

A fresh replica that later fetches this DAG only ever needs the snapshot block(s): it never descends into a snapshot node's links (see processNode/repairDAG), which is what makes the old history safe to purge. Per-element priorities are preserved exactly (see Item G3), so a snapshot changes nothing about which value wins a concurrent write for a still-being-replicated key.

Two-generation tombstone rule

A tombstone cannot simply be dropped once its target's block is purged: a lagging replica that has not yet processed the original history may still be holding the (soon to be dead) element and needs the tombstone to eventually reach it. So a tombstone is carried into a snapshot generation if either (a) the block of the element it targets is being purged in this very Compact call (the lagging replica may hold that element and needs the kill now), or (b) that element's marker is still present locally at all (it is alive -- possibly reintroduced by a different dagName sharing the key -- and the kill must not be lost). A tombstone matching neither condition already did its job in a previous generation and is dropped.

A carried tombstone's marker is written with an alias pointing at the snapshot block that carries it (see putTombs), mirroring a re-homed element's marker (S2): in the common carry case (a), the tombstone's target id is the very id being purged by THIS SAME Compact call, so without an alias the purge below would immediately delete the marker it just (re)wrote, and a later-arriving element for that id -- exactly the kind of divergent write Compact must now tolerate -- would wrongly resurrect the key. A plain (non-carried) tombstone is unaffected: it keeps the alias-less, nil-valued marker it has always had.

Coordination-free

Compact needs no coordination with anything else writing to this dagName, same as every other operation this package exposes: concurrent Puts, Deletes, and Compacts -- whether they observe the same view or have diverged (different, unsynced sets of prior operations), and regardless of the order replicas eventually exchange them in -- converge to exactly the state the uncompacted history would have produced. This holds because every element keeps its ORIGINAL id for its entire life, including across compaction: a snapshot changes which block hosts an element's storage (recorded as an alias on its marker, see putElems) but never changes the element's identity, so a tombstone that targets an id it observed before compaction ran keeps covering that exact element afterwards, in every generation, on every replica -- compaction is pure representation GC, invisible to the CRDT semantics. Local Put/Delete/Batch.Commit calls on this same Datastore serialize against Compact via compactMux (see addDAGNode) as an implementation detail, not because concurrent remote writes would be unsafe.

A few things remain worth noting, though none of them are correctness requirements:

  • Upgrade ordering. All replicas that may ever see this dagName's history should run a version of this package that understands snapshot deltas (this one) before Compact is called anywhere. This is the same rollout rule as any wire-format addition: an old-code replica does not know to avoid descending into a snapshot node's links, and would try to fetch purged blocks (failing) while also mis-attributing every element's priority to the snapshot's own height.
  • Compact when reasonably synced. Compaction works correctly regardless of how far behind other replicas are: a replica that is very far behind still converges correctly on reconnect (the snapshot resupplies live values and carries the tombstones it needs). Running it while replicas are reasonably caught up is purely an efficiency consideration -- it maximizes how much history gets folded away in one pass, rather than repeating the exercise generation after generation.

Purged-block bookkeeping trade-off

Unlike PurgeDAG, Compact deliberately *keeps* the processed-block markers for the CIDs it purges (instead of deleting them). They are tiny, and their presence means that a stale rebroadcast of now-purged history (from a lagging replica that has not yet reconnected) is recognized as already processed and skipped, rather than triggering a doomed attempt to fetch a block that no longer exists.

Receiver-side reclamation

Compact itself only reclaims space on the replica that runs it, and a fresh replica never downloads the purged history at all. A long-lived replica that had already merged the covered history before the snapshot arrived, however, starts out keeping its local copy of that history (set markers and blocks): merging a snapshot does not, by itself, purge anything on the receiving side.

That residue is what Options.ReclaimOnSnapshot (default: on) reclaims automatically. Every snapshot delta Compact produces carries generation metadata -- snapshotTotal (the number of sibling snapshot nodes Compact split this generation into) and snapshotId (an id shared by all of them, deterministically derived from their covered heads). When a replica merges one of these siblings (processNode, triggered from the normal DAG walk -- never from a local publish, and never from Compact's own processing of the nodes it just wrote, which would be a redundant double-reclaim), it increments a per-generation counter. Once that counter reaches snapshotTotal -- every sibling has now been merged, so every live key's snapshot marker is in place -- it purges its own copy of the covered history exactly as Compact would (reclaimCovered), and records a done marker so the generation is never reclaimed twice. This counter-driven wait is what avoids a visibility gap: reclaiming before every sibling has merged could transiently drop a key whose surviving value lives in a not-yet-merged sibling.

This is a best-effort, soft-failure feature: any error along that path (bumping the counter, walking, purging, writing the done marker) is logged and otherwise swallowed -- it never fails the merge that triggered it and never marks the datastore dirty. The main gap this leaves is a crash between the merge being recorded and the counter increment, which permanently loses one count for that generation (accepted as a consequence of not making local Compact/merge state part of the same transaction). Legacy snapshots produced by a pre-metadata version of this package (empty snapshotId/snapshotTotal) are never auto-reclaimed either.

Datastore.ReclaimCompacted is the manual/recovery path for all of the above: crash-missed generations, ReclaimOnSnapshot=false deployments, and legacy snapshots (for which it derives the same id Compact would have, from the snapshot node's covered-heads links). It is safe to call at any time and is idempotent (already-reclaimed generations are skipped via the same done marker).

func (*Datastore) Delete added in v1.2.0

func (store *Datastore) Delete(ctx context.Context, key ds.Key) error

Delete removes the value for given `key`.

func (*Datastore) DotDAG added in v1.2.0

func (store *Datastore) DotDAG(ctx context.Context, w io.Writer) error

DotDAG writes a dot-format representation of the CRDT DAG to the given writer. It can be converted to image format and visualized with graphviz tooling.

func (*Datastore) Get added in v1.2.0

func (store *Datastore) Get(ctx context.Context, key ds.Key) (value []byte, err error)

Get retrieves the object `value` named by `key`. Get will return ErrNotFound if the key is not mapped to a value.

func (*Datastore) GetSize added in v1.2.0

func (store *Datastore) GetSize(ctx context.Context, key ds.Key) (size int, err error)

GetSize returns the size of the `value` named by `key`. In some contexts, it may be much cheaper to only get the size of the value rather than retrieving the value itself.

func (*Datastore) Has added in v1.2.0

func (store *Datastore) Has(ctx context.Context, key ds.Key) (exists bool, err error)

Has returns whether the `key` is mapped to a `value`. In some contexts, it may be much cheaper only to check for existence of a value, rather than retrieving the value itself. (e.g. HTTP HEAD). The default implementation is found in `GetBackedHas`.

func (*Datastore) InternalStats added in v1.2.0

func (store *Datastore) InternalStats(ctx context.Context) Stats

InternalStats returns internal datastore information like the current heads and max height.

func (*Datastore) IsDirty added in v1.2.0

func (store *Datastore) IsDirty(ctx context.Context) bool

IsDirty returns whether the datastore is marked dirty.

func (*Datastore) MarkClean added in v1.2.0

func (store *Datastore) MarkClean(ctx context.Context)

MarkClean removes the dirty mark from the datastore.

func (*Datastore) MarkDirty added in v1.2.0

func (store *Datastore) MarkDirty(ctx context.Context)

MarkDirty marks the Datastore as dirty.

func (*Datastore) PrintDAG added in v1.2.0

func (store *Datastore) PrintDAG(ctx context.Context) error

PrintDAG pretty prints the current Merkle-DAG to stdout in a pretty fashion. Only use for small DAGs. DotDAG is an alternative for larger DAGs.

func (*Datastore) Put added in v1.2.0

func (store *Datastore) Put(ctx context.Context, key ds.Key, value []byte) error

Put stores the object `value` named by `key`.

func (*Datastore) Query added in v1.2.0

func (store *Datastore) Query(ctx context.Context, q query.Query) (query.Results, error)

Query searches the datastore and returns a query result. This function may return before the query actually runs. To wait for the query:

result, _ := ds.Query(q)

// use the channel interface; result may come in at different times
for entry := range result.Next() { ... }

// or wait for the query to be completely done
entries, _ := result.Rest()
for entry := range entries { ... }

func (*Datastore) ReclaimCompacted added in v1.2.0

func (store *Datastore) ReclaimCompacted(ctx context.Context, dagName string) (int, error)

ReclaimCompacted is the explicit, manual reclamation entry point: the recovery path for compaction generations that the automatic per-merge trigger (Options.ReclaimOnSnapshot) missed -- the documented crash window, deployments running with ReclaimOnSnapshot set to false, and snapshots produced by an older version of this package that never stamped generation metadata (legacy snapshots, whose generation id is derived here the same way Compact would have: the hash over their covered-heads links).

It walks dagName's current heads locally (like PurgeDAG/Compact) and, for every compaction generation found that has not already been reclaimed, reclaims that generation's covered history and records it as reclaimed. Returns the total number of DAG blocks reclaimed across every generation processed. It is safe to call at any time and is idempotent: an already-reclaimed generation is skipped.

Like the automatic path, it reclaims a generation only once every one of its sibling snapshot nodes is present locally (a generation Compact split into N sibling blocks is reclaimed only when all N have been merged here). Reclaiming a partially-merged generation would purge covered history whose surviving value lives in a not-yet-merged sibling, transiently dropping that key. An incomplete generation is left untouched and picked up by a later call once its remaining siblings arrive. Legacy snapshots carry no sibling count and are reclaimed as found.

It serializes against Compact (holds compactMux): both walk and mutate the same local DAG/set state for a dagName, and Compact's own snapshot nodes must not be observed half-written.

func (*Datastore) Repair added in v1.2.0

func (store *Datastore) Repair(ctx context.Context) error

Repair triggers a DAG-repair, which tries to re-walk the CRDT-DAG from the current heads until the roots, processing currently unprocessed branches.

Calling Repair will walk the full DAG even if the dirty bit is unset, but will mark the store as clean unpon successful completion.

func (*Datastore) Sync added in v1.2.0

func (store *Datastore) Sync(ctx context.Context, prefix ds.Key) error

Sync ensures that all the data under the given prefix is flushed to disk in the underlying datastore.

type Delta added in v1.2.0

type Delta interface {
	GetElements() ([]*pb.Element, error)
	GetTombstones() ([]*pb.Element, error)
	GetPriority() uint64
	SetElements(elems []*pb.Element)
	SetTombstones(tombs []*pb.Element)
	SetPriority(p uint64)
	Size() int
	GetDagName() string
	SetDagName(string)
	// IsSnapshot reports whether this delta is a compaction snapshot (see
	// Datastore.Compact): its Elements/Tombstones represent the full live
	// state (and carried tombstones) of a named DAG's history up to this
	// point, rather than an incremental change. Snapshot deltas' links are
	// "covered heads" bookkeeping only -- they must never be walked/fetched,
	// since the history they point to may have been purged.
	IsSnapshot() bool
	SetSnapshot(bool)
	// SnapshotMeta returns the compaction-generation metadata carried by a
	// snapshot delta: total is the number of sibling snapshot nodes created
	// by the same Compact() run, and id identifies that generation (see
	// SetSnapshotMeta). Both are zero-valued on non-snapshot deltas and on
	// snapshot deltas produced before this metadata existed (legacy
	// snapshots).
	SnapshotMeta() (total uint32, id []byte)
	// SetSnapshotMeta sets the compaction-generation metadata (see
	// SnapshotMeta).
	SetSnapshotMeta(total uint32, id []byte)
	IsEmpty() bool
	Unmarshal([]byte) error
	Marshal() ([]byte, error)
}

Delta represent a CRDT changeset, it carries new or updated elements and new or updated tombstones. The priority value allows comparing this update with others, to determine which elements take precedence.

type FilterKeyRegEx

type FilterKeyRegEx struct {
	// contains filtered or unexported fields
}

func NewFilterKeyRegEx

func NewFilterKeyRegEx(regexs ...string) (*FilterKeyRegEx, error)

func (*FilterKeyRegEx) Filter

func (f *FilterKeyRegEx) Filter(e query.Entry) bool
type Head struct {
	HeadValue
	Cid cid.Cid
}

func (Head) String added in v1.2.0

func (h Head) String() string

type HeadValue added in v1.2.0

type HeadValue struct {
	Height  uint64
	DAGName string
}

type Heads added in v1.2.0

type Heads interface {
	Get(ctx context.Context, c cid.Cid) (Head, bool)
	Len(ctx context.Context) (int, error)
	LenDAG(ctx context.Context, dagName string) (int, error)
	Replace(ctx context.Context, old Head, new Head) error
	Add(ctx context.Context, head Head) error
	List(ctx context.Context) ([]Head, uint64, error)
	ListDAG(ctx context.Context, dagName string) ([]Head, uint64, error)
}

Heads represents a set of the current root CIDs of the Merkle-CRDT DAG.

type InternalNamespaces added in v1.2.0

type InternalNamespaces struct {
	Heads           string
	DAGHeads        string
	Set             string
	ProcessedBlocks string
	DirtyBitKey     string
	BadShutdownKey  string
	VersionKey      string
	// Reclaim namespaces the bookkeeping used by receiver-side reclamation
	// of compacted history (see Options.ReclaimOnSnapshot and
	// Datastore.ReclaimCompacted).
	Reclaim string
}

DatatstoreNamespaces carries configuration for how internal namespaces are named.

type MerkleCRDT added in v1.2.0

type MerkleCRDT struct {
	*Datastore
}

A MerkleCRDT is an advanced type to manually customize the merkle-CRDT. It allows submission of custom deltas and other advanced methods. If you just need a key-value store that conforms to the Datastore interface, use NewDatastore() instead.

func NewMerkleCRDT added in v1.2.0

func NewMerkleCRDT(
	store ds.Datastore,
	namespace ds.Key,
	dagSyncer ipld.DAGService,
	bcast Broadcaster,
	opts *Options,
	internalOptions *MerkleCRDTOptions,
) (*MerkleCRDT, error)

NewMerkleCRDT returns a Merkle-CRDT Datastore wrapped with advanced methods. It allows setting internal options.

func (*MerkleCRDT) Heads added in v1.2.0

func (mcrdt *MerkleCRDT) Heads() Heads

func (*MerkleCRDT) IsProcessed added in v1.2.0

func (mcrdt *MerkleCRDT) IsProcessed(ctx context.Context, c cid.Cid) (bool, error)

IsProcessed returns whether the given CID has been processed. Nodes are marked as processed as they are traversed during the DAG walk, so a CID being processed means it has been visited and merged into the set.

func (*MerkleCRDT) Publish added in v1.2.0

func (mcrdt *MerkleCRDT) Publish(ctx context.Context, delta Delta) (Head, error)

Publish allows to manually publish a Delta. The Priority is set automatically, upon which the delta is merged, serialized and broadcasted. Returns the CID of the new root node resulting from applying the delta.

func (*MerkleCRDT) PurgeDAG added in v1.2.0

func (mcrdt *MerkleCRDT) PurgeDAG(ctx context.Context, dagName string) (int, error)

PurgeDAG removes all state associated with a named DAG: its heads, all DAG blocks reachable from those heads, the set entries created by those blocks, and processed block markers. Returns the number of DAG nodes removed.

Heads are deleted last so that a partial failure leaves them intact and a subsequent call can resume the cleanup.

The caller must ensure no concurrent writes to this dagName during purge. The Datastore's background workers (rebroadcast, repair, DAG walking) also access heads and set state — callers should either Close() the Datastore first or ensure the dagName is not being actively synced.

func (*MerkleCRDT) Set added in v1.2.0

func (mcrdt *MerkleCRDT) Set() Set

Set returns the internal set.

func (*MerkleCRDT) Traverse added in v1.2.0

func (mcrdt *MerkleCRDT) Traverse(ctx context.Context,
	from []cid.Cid,
	visit func(ipld.Node) error,
) error

Traverse visits nodes in the Merkle-CRDT tree. It skips duplicates and calls the visit function with the Deltas extracted from every node. An error results in the traversal operations being aborted.

type MerkleCRDTOptions added in v1.2.0

type MerkleCRDTOptions struct {
	DeltaFactory func() Delta
	Namespaces   InternalNamespaces
}

type Options added in v1.2.0

type Options struct {
	Logger logging.StandardLogger
	// RebroadcastInterval specifies how often the system
	// re-publishes its latest heads so that new replicas can
	// learn about them. It only broadcasts heads that have not
	// been already broadcasted by other replicas in the
	// interval. Default: 1m.
	RebroadcastInterval time.Duration
	// The PutHook function is triggered whenever an element
	// is successfully added to the datastore (either by a local
	// or remote update), and only when that addition is considered the
	// prevalent value. Default: nil.
	PutHook func(k ds.Key, v []byte)
	// The DeleteHook function is triggered whenever a version of an
	// element is successfully removed from the datastore (either by a
	// local or remote update). Unordered and concurrent updates may
	// result in the DeleteHook being triggered even though the element is
	// still present in the datastore because it was re-added or not fully
	// tombstoned. If that is relevant, use Has() to check if the removed
	// element is still part of the datastore. Default: nil.
	DeleteHook func(k ds.Key)
	// NumWorkers specifies the number of workers ready to
	// retrieve and merge deltas while walking the DAGs. Default:
	// 5.
	NumWorkers int
	// DAGSyncerTimeout specifies how long to wait for a DAGSyncer
	// to, for example, receive a delta from a different replica.
	// Set to 0 to disable. Default: 5m.
	DAGSyncerTimeout time.Duration
	// MaxBatchDeltaSize will automatically commit any batches whose
	// delta size gets too big. This helps keep DAG nodes small
	// enough that they will be transferred by the network. Default: 1MiB.
	MaxBatchDeltaSize int
	// RepairInterval specifies how often to walk the full DAG until
	// the root(s) if it has been marked dirty. 0 to disable. Default: 1h.
	RepairInterval time.Duration
	// MultiHeadProcessing lets several new heads to be processed
	// in parallel. This results in more branching in
	// general. More branching is not necessarily a bad thing and
	// may improve throughput, but everything depends on
	// usage. Default: false.
	MultiHeadProcessing bool
	// BroadcastBatchDelay batches the new Head broadcasts when
	// publishing new deltas into a single message. As a result,
	// broadcast traffic is reduced on systems with high
	// utilization. On the other side, the delay introduces
	// latency as a change will not be published until it is
	// included in the crdtBatch when the delay expires. 0 to
	// disable. Default: 0.
	BroadcastBatchDelay time.Duration
	// ReclaimOnSnapshot enables receiver-side reclamation of compacted
	// history: when a replica merges a snapshot delta produced by another
	// replica's Compact() call and has now merged every sibling of that
	// compaction generation, it purges its own local copy of the DAG
	// history that snapshot generation covers (blocks and set entries),
	// exactly as Compact does on the compacting replica. This is a
	// best-effort, soft-failure feature: a failed or missed reclaim never
	// fails the triggering merge and never corrupts state, it just leaves
	// local history unreclaimed until the next opportunity. Use
	// Datastore.ReclaimCompacted for manual/recovery reclamation (crash
	// windows, legacy pre-metadata snapshots, or when this option is
	// disabled). Default: true.
	ReclaimOnSnapshot bool
	// contains filtered or unexported fields
}

Options holds configurable values for Datastore.

func DefaultOptions added in v1.2.0

func DefaultOptions() *Options

DefaultOptions initializes an Options object with sensible defaults.

type PubSubBroadcaster

type PubSubBroadcaster struct {
	// contains filtered or unexported fields
}

PubSubBroadcaster implements a Broadcaster using libp2p PubSub.

func NewPubSubBroadcaster

func NewPubSubBroadcaster(ctx context.Context, psub *pubsub.PubSub, topic string) (b *PubSubBroadcaster, err error)

NewPubSubBroadcaster returns a new broadcaster using the given PubSub and a topic to subscribe/broadcast to. The given context can be used to cancel the broadcaster. Please register any topic validators before creating the Broadcaster.

The broadcaster can be shut down by cancelling the given context. This must be done before Closing the Datastore, otherwise things may hang.

func (*PubSubBroadcaster) Broadcast

func (pbc *PubSubBroadcaster) Broadcast(ctx context.Context, data []byte) error

Broadcast publishes some data.

libp2p Topic.Publish can wedge in the pubsub validation pipeline when the router is tearing down (e.g. a killed node) — it stops observing ctx once past its initial check. Publish detached and return as soon as the broadcaster is shutting down, so a CRDT rebroadcast can never block Datastore.Close()'s wg.Wait (and thus service/universe teardown). The abandoned Publish unwinds on its own when the pubsub finishes closing.

func (*PubSubBroadcaster) Next

func (pbc *PubSubBroadcaster) Next(ctx context.Context) ([]byte, error)

Next returns published data.

type SessionDAGService added in v1.2.0

type SessionDAGService interface {
	ipld.DAGService
	Session(context.Context) ipld.NodeGetter
}

A SessionDAGService is a Sessions-enabled DAGService. This type of DAG-Service provides an optimized NodeGetter to make multiple related requests. The same session-enabled NodeGetter is used to download DAG branches when the DAGSyncer supports it.

type Set added in v1.2.0

type Set interface {
	Add(ctx context.Context, key string, value []byte) (Delta, error)
	Rmv(ctx context.Context, key string) (Delta, error)
	Merge(ctx context.Context, d Delta, id string) error
	Element(ctx context.Context, key string) ([]byte, error)
	Elements(ctx context.Context, q query.Query) (query.Results, error)
	InSet(ctx context.Context, key string) (bool, error)
}

Set specifies operations that the add-wins observed-removed set must fulfil.

type Stats added in v1.2.0

type Stats struct {
	Heads      []Head
	MaxHeight  uint64
	QueuedJobs int
}

Stats wraps internal information about the datastore. Might be expanded in the future.

Directories

Path Synopsis
Package pb contains generated protobuf types
Package pb contains generated protobuf types

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL