indexer

package module
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: Apache-2.0, MIT Imports: 9 Imported by: 4 modules, 8 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.

README

go-indexer-core

Go Reference Coverage Status

Storage specialized for indexing provider content

The indexer-core is a key-value store that is optimized for storing large numbers of multihashes mapping to relatively few provider data objects. A multihash (CID without codec) uniquely identifies a piece of content, and the provider data describes where and how to retrieve the content.

Content is indexed by giving a provider data object (the value) and a set of multihashes (keys) that map to that value. Typically, the provider value represents a storage deal and the multihash keys identify content stored within that deal. To subsequently retrieve a provider value, the indexer-core is given a multihash key to lookup.

Data Storage provides more detail on how data is stored by the indexer-core.

This indexer-core is the component of an indexer that provides data storage and retrieval for content index data. An indexer must also supply all the service functionality necessary to create an indexing service, which is not included in the indexer-core component.

Configurable Cache

An integrated cache is included to aid in fast index lookups. By default the cache is configured as a retrieval cache, meaning that items are only stored in the cache when index data is looked up, and will speed up repeated lookups of the same data. The cache can be optionally disabled, and its size is configurable. The cache interface allows alternative cache implementations to be used if desired.

See Usage Example for details.

Choice of Persistent Storage

The persistent storage is provided by a choice of storage systems that include pebble, and an in-memory implementation. The storage interface allows any other storage system solution to be adapted.

See Usage Example for details.

Install

 go get github.com/ipni/go-indexer-core

Usage

import "github.com/ipni/go-indexer-core"

See pkg.go.dev documentation

Example
package main

import (
	"log"
	"os"

	"github.com/ipni/go-indexer-core"
	"github.com/ipni/go-indexer-core/cache"
	"github.com/ipni/go-indexer-core/cache/radixcache"
	"github.com/ipni/go-indexer-core/engine"
	"github.com/ipni/go-indexer-core/store/pebble"
	"github.com/ipfs/go-cid"
	"github.com/libp2p/go-libp2p-core/peer"
)

func main() {
	// Configuration values.
	const valueStoreDir = "/tmp/indexvaluestore"
	const cacheSize = 65536

	// Create value store of configured type.
	os.Mkdir(valueStoreDir, 0770)
    valueStore, err := pebble.New(valueStoreDir, nil)
	if err != nil {
		log.Fatal(err)
	}

	// Create result cache, or disabled it.
	var resultCache cache.Interface
	if cacheSize > 0 {
		resultCache = radixcache.New(cacheSize)
	} else {
		log.Print("Result cache disabled")
	}

	// Create indexer core.
	indexerCore := engine.New(resultCache, valueStore)

	// Put some index data into indexer core.
	cid1, _ := cid.Decode("QmPNHBy5h7f19yJDt7ip9TvmMRbqmYsa6aetkrsc1ghjLB")
	cid2, _ := cid.Decode("QmUaPc2U1nUJeVj6HxBxS5fGxTWAmpvzwnhB8kavMVAotE")
	peerID, _ := peer.Decode("12D3KooWKRyzVWW6ChFjQjK4miCty85Niy48tpPV95XdKu1BcvMA")
	ctxID := []byte("someCtxID")
	value := indexer.Value{
		ProviderID:    peerID,
		ContextID:     ctxID,
		MetadataBytes: []byte("someMetadata"),
	}
	err = indexerCore.Put(value, cid1.Hash(), cid2.Hash())
	if err != nil {
		log.Fatal(err)
	}

	// Lookup provider data by multihash.
	values, found, err := indexerCore.Get(cid1.Hash())
	if err != nil {
		log.Fatal(err)
	}
	if found {
		log.Printf("Found %d values for cid1", len(values))
	}
	
	// Remove provider values by contextID, and multihashes that map to them.
	err = indexerCore.RemoveProviderContext(peerID, ctxID)
	if err != nil {
		log.Fatal(err)                                                                                                                   
	}
}

License

This project is dual-licensed under Apache 2.0 and MIT terms:

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrMeteringNotSupported signals that an indexer.Interface does not support
	// storage metering.
	ErrMeteringNotSupported = errors.New("metering is not supported by store")
	// ErrScanInProgress is returned by MeteringTriggerScan when a scan is already running.
	ErrScanInProgress = errors.New("metering scan already in progress")
	// ErrScanNotInProgress is returned by MeteringCancelScan when no scan is running.
	ErrScanNotInProgress = errors.New("metering scan is not in progress")
	// ErrScanCancelled is recorded on scan status when MeteringCancelScan stops a scan.
	// A non-empty reason is appended after this text.
	ErrScanCancelled = errors.New("user cancelled")
)
View Source
var (

	// ErrCodecOverflow signals that unexpected size was encountered while
	// unmarshalling bytes to Value.
	ErrCodecOverflow = errors.New("overflow")
)
View Source
var ErrStatsNotSupported = errors.New("stats is not supported by store")

ErrStatsNotSupported signals that an indexer.Interface does not support Stats calculation.

Functions

func ScanCancelledError added in v0.10.0

func ScanCancelledError(reason string) error

ScanCancelledError is ErrScanCancelled, optionally annotated with reason. The result is always errors.Is(..., ErrScanCancelled).

Types

type AllStatsReport added in v0.10.0

type AllStatsReport struct {
	CompletedScanStats
	Providers []ProviderStats
}

AllStatsReport is a finished scan as returned by MeteringAllStats. The embedded CompletedScanStats is the whole store. Providers is the subset selected by the caller: nil means every provider that has a peer ID, an empty slice means none, and a non-empty slice means only those IDs. Providers with an empty ProviderID are omitted.

type BinaryValueCodec

type BinaryValueCodec struct {
	// ZeroCopy controls whether decoded values of []byte type point into
	// the input []byte parameter passed to UnmarshalValue or
	// UnmarshalValueKeys.
	//
	// This optimization prevents unnecessary copying. It is optional as
	// the caller MUST ensure that the input parameter []byte is not
	// modified after the Unmarshal happens, as any changes are mirrored in
	// the decoded result.
	ZeroCopy bool
}

BinaryValueCodec serializes and deserializes Value as binary sections prepended with byte length as varint.

func (BinaryValueCodec) MarshalValue

func (BinaryValueCodec) MarshalValue(v Value) ([]byte, error)

func (BinaryValueCodec) MarshalValueKeys

func (BinaryValueCodec) MarshalValueKeys(vk [][]byte) ([]byte, error)

func (BinaryValueCodec) UnmarshalValue

func (c BinaryValueCodec) UnmarshalValue(b []byte) (Value, error)

UnmarshalValue deserializes a single value.

If a failure occurs during serialization an error is returned along with the partially deserialized value keys. Only nil error means complete and successful deserialization.

func (BinaryValueCodec) UnmarshalValueKeys

func (c BinaryValueCodec) UnmarshalValueKeys(b []byte) ([][]byte, error)

UnmarshalValueKeys deserializes value keys.

If a failure occurs during serialization an error is returned along with the partially deserialized value keys. Only nil error means complete and successful deserialization.

type BinaryWithJsonFallbackCodec deprecated

type BinaryWithJsonFallbackCodec struct {
	BinaryValueCodec
	JsonValueCodec
}

BinaryWithJsonFallbackCodec always serialises values as binary but deserializes both from binary and JSON, which gracefully and opportunistically migrates codec from JSON to the more efficient binary format.

Deprecated: no store reads or writes values with this codec. It will be removed.

func (BinaryWithJsonFallbackCodec) MarshalValue

func (bjc BinaryWithJsonFallbackCodec) MarshalValue(v Value) ([]byte, error)

func (BinaryWithJsonFallbackCodec) MarshalValueKeys

func (bjc BinaryWithJsonFallbackCodec) MarshalValueKeys(vk [][]byte) ([]byte, error)

func (BinaryWithJsonFallbackCodec) UnmarshalValue

func (bjc BinaryWithJsonFallbackCodec) UnmarshalValue(b []byte) (Value, error)

func (BinaryWithJsonFallbackCodec) UnmarshalValueKeys

func (bjc BinaryWithJsonFallbackCodec) UnmarshalValueKeys(b []byte) ([][]byte, error)

type CompletedScanStats added in v0.10.0

type CompletedScanStats struct {
	// MeasuredAt is when the scan finished counting.
	MeasuredAt time.Time
	// Totals is the whole-store counters. It does not change with the caller's
	// provider selection. The same struct is ScanStatus.Current.Totals while
	// the scan is still running.
	Totals StoreTotals
}

CompletedScanStats is the header of a finished scan: when measuring stopped and the whole-store counters. It does not include per-provider rows or the walk cursor. MeteringAllStats returns it embedded in AllStatsReport. The Pebble store writes it as the current-scan record when the walk finishes.

type EntryMeters added in v0.10.0

type EntryMeters struct {
	// Entries is the number of multihash keys in this class.
	Entries uint64
	// KeyBytes is the total size of those keys.
	KeyBytes uint64
	// ValueBytes is the total size of those values.
	ValueBytes uint64
	// Slots is the number of value-key entries packed inside those records.
	// One multihash mapped to two contexts counts as two slots. A slot whose
	// value record was later deleted is still counted.
	Slots uint64
}

EntryMeters counts one class of multihash records: how many there are, how many bytes their keys and values occupy, and how many value-key slots they pack. StoreTotals uses one value for records that decoded and another for records that did not. The in-progress snapshot and the finished report both store StoreTotals, so the two views stay the same shape. Invalid records leave Slots at zero because their value list did not decode.

type Interface

type Interface interface {
	// Get retrieves a slice of Value for a multihash.
	Get(multihash.Multihash) ([]Value, bool, error)

	// Put stores a Value and adds a mapping from each of the given multihashes
	// to that Value. If the Value has the same ProviderID and ContextID as a
	// previously stored Value, then update the metadata in the stored Value
	// with the metadata from the provided Value. Call Put without any
	// multihashes to only update existing values.
	Put(Value, ...multihash.Multihash) error

	// Remove removes the mapping of each multihash to the specified value.
	Remove(Value, ...multihash.Multihash) error

	// RemoveProvider removes all values for specified provider. This is used
	// when a provider is no longer indexed by the indexer.
	RemoveProvider(context.Context, peer.ID) error

	// RemoveProviderContext removes all values for specified provider that
	// have the specified contextID. This is used when a provider no longer
	// provides values for a particular context.
	RemoveProviderContext(providerID peer.ID, contextID []byte) error

	// Size returns the total bytes of storage used to store the indexed
	// content in persistent storage. This does not include memory used by any
	// in-memory cache that the indexer implementation may have, as that would
	// only contain a limited quantity of data and not represent the total
	// amount of data stored by the indexer.
	Size() (int64, error)

	// Flush commits any changes to the value storage,
	Flush() error

	// Close gracefully closes the store flushing all pending data from memory,
	Close() error

	// Stats returns statistical information about the indexed values.
	// If unsupported by the backing store, ErrStatsNotSupported is returned.
	Stats() (*Stats, error)

	// StatsMeter reports storage statistics from a background scan.
	// Implementations that cannot scan return ErrMeteringNotSupported.
	StatsMeter
}

type JsonValueCodec deprecated

type JsonValueCodec struct{}

JsonValueCodec serializes and deserializes Value as JSON. See: json.Marshal, json.Unmarshal

Deprecated: no store reads or writes values with this codec. It will be removed.

func (JsonValueCodec) MarshalValue

func (JsonValueCodec) MarshalValue(v Value) ([]byte, error)

func (JsonValueCodec) MarshalValueKeys

func (JsonValueCodec) MarshalValueKeys(vk [][]byte) ([]byte, error)

func (JsonValueCodec) UnmarshalValue

func (JsonValueCodec) UnmarshalValue(b []byte) (v Value, err error)

func (JsonValueCodec) UnmarshalValueKeys

func (JsonValueCodec) UnmarshalValueKeys(b []byte) (vk [][]byte, err error)

type ProviderStats added in v0.10.0

type ProviderStats struct {
	// ProviderID is the provider these counters belong to. Empty when no
	// value record for this provider could be read.
	ProviderID peer.ID
	// Multihashes is the number of distinct multihash keys that have at least
	// one remaining value record for this provider.
	Multihashes uint64
	// Slots is the number of value-key entries for this provider whose value
	// record is still present. One multihash advertised under two contexts
	// counts as two slots and one multihash.
	Slots uint64
	// DeletedContexts is the number of slots whose context value record is
	// gone while this provider still has some other value record. Each slot
	// is counted once. A provider with no value records left is counted in
	// StoreTotals.Deleted instead.
	DeletedContexts uint64
}

ProviderStats counts one provider inside one scan. The scan addresses the row by the provider hash taken from multihash slots, then fills ProviderID from that provider's value record the first time the hash is seen.

Multihashes here is not a share of StoreTotals.Active. A multihash that names two providers increments each provider once and the store total once. Multihashes counts only slots whose value record is still present. An empty ProviderID means every value record for that provider was already gone; the row is still stored so a resumed scan does not count the provider again, and both APIs omit it.

type ScanState added in v0.10.0

type ScanState string

ScanState is the lifecycle of the latest metering scan. It is the process view returned by MeteringScanStatus. The counters themselves are Current.Totals, the same StoreTotals the finished report stores.

const (
	// ScanStateNone means no scan has been recorded.
	ScanStateNone ScanState = "none"
	// ScanStateInProgress means a scan is running, or an interrupted scan is
	// waiting to resume.
	ScanStateInProgress ScanState = "in_progress"
	// ScanStateDone means the latest scan finished and its counters are kept.
	ScanStateDone ScanState = "done"
	// ScanStateError means the latest scan stopped with a failure. Error
	// carries the reason. The counters committed before the failure are kept.
	ScanStateError ScanState = "error"
)

type ScanStatus added in v0.10.0

type ScanStatus struct {
	// State is none, in_progress, done, or error.
	State ScanState
	// ScanID identifies this walk. It is the start time in microseconds.
	// Empty when State is none.
	ScanID uint64
	// StartedAt is when this walk started.
	StartedAt time.Time
	// EstimatedPercentDone is a rough estimate of how much of the scan is
	// done, from 0 to 100. It can stay flat or jump while the scan runs.
	// Computed when status is read, not stored. A done scan reports 100.
	EstimatedPercentDone float64
	// EstimatedFinish is when the scan is expected to complete if the rate so
	// far continues. Nil when the fraction done is still zero or StartedAt is
	// unset. A done scan reports the time it finished. Filled when status is
	// read, not stored on this struct.
	EstimatedFinish *time.Time
	// Current is the counters committed by finished batches, and by a scan
	// that has since finished or failed. Totals is a StoreTotals, the same
	// struct as the finished report. Providers follows the caller's selection.
	Current StatsSnapshot
	// Error is why the scan stopped when State is error. Empty otherwise.
	Error string `json:",omitempty"`
}

ScanStatus is the walk, returned by MeteringScanStatus. State, the start time, and the estimate describe the walk. Current.Totals is a StoreTotals, the same struct the finished report stores, including after the scan is done or has failed.

EstimatedPercentDone and EstimatedFinish are not stored on this struct. While the scan is running the store computes them when status is read. They are rough estimates: percent done can stay flat or jump, and the finish time can move. A done scan reports 100 and the time the scan finished.

type Stats

type Stats struct {
	// MultihashCount is the number of unique multihashes indexed.
	MultihashCount uint64
}

Stats provides statistics about the indexed values.

type StatsMeter added in v0.10.0

type StatsMeter interface {
	// MeteringAllStats returns the latest completed scan, or nil if no scan has
	// completed yet. Totals are always for the whole store. Providers follows
	// the providerIDs selection.
	MeteringAllStats(ctx context.Context, providerIDs []peer.ID) (*AllStatsReport, error)
	// MeteringScanStatus returns the latest scan. State is none when no scan
	// has been recorded, in_progress while one is running, done after it
	// finishes, and error when it stopped with a failure. A finished or failed
	// scan keeps its counters until the next scan replaces them. Current
	// provider rows follow the providerIDs selection. Totals stay whole-store.
	MeteringScanStatus(ctx context.Context, providerIDs []peer.ID) (*ScanStatus, error)
	// MeteringTriggerScan signals that a scan should start now. ErrScanInProgress means
	// a scan is already running. Progress is available from MeteringScanStatus while
	// the scan runs, and from MeteringAllStats after it completes.
	MeteringTriggerScan(ctx context.Context) error
	// MeteringCancelScan asks the in-progress scan to stop. reason is recorded
	// after ErrScanCancelled on MeteringScanStatus. An empty reason records
	// ErrScanCancelled alone. The caller formats reason.
	// ErrScanNotInProgress means no scan is running. A second cancel while the
	// same scan is still stopping is a no-op.
	MeteringCancelScan(ctx context.Context, reason string) error
}

StatsMeter is embedded in Interface. Implementations that cannot scan return ErrMeteringNotSupported from each method.

providerIDs selects which providers are included in a result. nil includes every provider. An empty slice includes none. A non-empty slice includes only those providers, omitting any with no recorded stats.

type StatsSnapshot added in v0.10.0

type StatsSnapshot struct {
	Totals    StoreTotals
	Providers []ProviderStats
}

StatsSnapshot is StoreTotals plus provider rows at one moment during a scan. ScanStatus.Current uses it for batches committed so far. The provider selection rules are the same as AllStatsReport.Providers. Totals stay whole-store and use the same StoreTotals as the finished report.

type StoreTotals added in v0.10.0

type StoreTotals struct {
	// Active counts multihash keys that decoded and still have at least one
	// value record. A key another provider still serves is active, including
	// slots whose own context record was removed.
	Active EntryMeters
	// Deleted counts multihash keys that decoded and whose value records are
	// all gone.
	Deleted EntryMeters
	// Invalid counts multihash keys whose value could not be decoded.
	// Slots stays zero for these records.
	Invalid EntryMeters
}

StoreTotals is the whole-store counters for one scan. It is written at the end of each batch, returned in ScanStatus.Current while the walk is running, and copied into the finished scan header when the walk completes.

Active, Deleted, and Invalid are separate: each multihash key is counted in one of them.

type Value

type Value struct {
	// ProviderID is the peer ID of the provider of the multihash.
	ProviderID peer.ID `json:"p"`
	// ContextID identifies the metadata that is part of this value.
	ContextID []byte `json:"c"`
	// MetadataBytes is serialized metadata. The is kept serialized, because
	// the indexer only uses the serialized form of this data.
	MetadataBytes []byte `json:"m,omitempty"`
}

Value is the value of an index entry that is stored for each multihash in the indexer.

func (Value) Equal

func (v Value) Equal(other Value) bool

Equal returns true if two Value instances are identical.

func (Value) Match

func (v Value) Match(other Value) bool

Match return true if both values have the same ProviderID and ContextID.

func (Value) MatchEqual

func (v Value) MatchEqual(other Value) (isMatch bool, isEqual bool)

MatchEqual returns true for the first bool if both values have the same ProviderID and ContextID, and returns true for the second value if the metadata is also equal.

type ValueCodec

type ValueCodec interface {
	// MarshalValue serializes a single value.
	MarshalValue(Value) ([]byte, error)
	// UnmarshalValue deserializes a single value.
	UnmarshalValue(b []byte) (Value, error)
	// MarshalValueKeys serializes a Value list for storage.
	MarshalValueKeys([][]byte) ([]byte, error)
	// UnmarshalValueKeys deserializes value keys list.
	UnmarshalValueKeys([]byte) ([][]byte, error)
}

ValueCodec represents Value serializer and deserializer to/from bytes.

Directories

Path Synopsis
store
dhstore
Package dhstore defines an dhstore client.
Package dhstore defines an dhstore client.
dhstore/client
Package client forks the HTTP request models of dhtsotre in order to avoid forcing upstream projects into C-bindings required by Foundation DB.
Package client forks the HTTP request models of dhtsotre in order to avoid forcing upstream projects into C-bindings required by Foundation DB.
memory
Package memory defines an in-memory value store
Package memory defines an in-memory value store
test
Package test provides tests that are usable by any store that implements store.Interface.
Package test provides tests that are usable by any store that implements store.Interface.

Jump to

Keyboard shortcuts

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