swr

package module
v1.21.108 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2026 License: Apache-2.0 Imports: 15 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.

README

Clicky SWR cache

Use github.com/flanksource/clicky/cache/swr to share typed read snapshots across commands and servers. swr.New[T] holds decoded snapshots in Otter v2 and uses a cache.ConditionalStore for the shared tier. Clicky's valkey.NewStore implements that interface for Redis and Valkey. cache.NewMemory implements it for unit tests.

Bind every swr.Scope to an authenticated tenant and an authority-specific group such as a source connection or credential fingerprint. Lookup reads at most swr.BatchSize requested IDs and returns their freshness and validation times. Callers use current source authorization to choose which results to serve. Heads and control keys share a Redis Cluster hash tag within a scope so their updates can be atomic. Heads contain publication IDs, source revisions, and deadlines. Payload keys contain a hashed identity, a hashed revision, and a random publication ID. Values are versioned JSON frames with optional Zstandard compression for sufficiently large and compressible records.

Use Revalidate on a bounded set of IDs and return the source revision with every loader result. Unchanged revisions widen the refresh and stale intervals under the configured Policy. A changed revision resets those intervals. Use Invalidate to mark known changes stale or publish a tombstone after deletion, and pass guards with Revalidate when a background scheduler owns a distributed lease. A concurrent change supersedes an older publication. The caller owns worker lifetime, upstream queries, event handling, and the decision to serve stale data.

The runnable package example loads a scoped snapshot and reads it back. Run it from this module with gavel test . --framework go.

Documentation

Overview

Package swr caches typed, revisioned observations in a local Otter cache and a shared Clicky store. Callers authorize reads and supply authoritative loaders.

Index

Examples

Constants

View Source
const BatchSize = 100

Variables

View Source
var ErrSuperseded = errors.New("cache publication superseded")

Functions

This section is empty.

Types

type Band

type Band struct {
	QuietFor   time.Duration
	Multiplier int
	StaleFor   time.Duration
}

type Cache

type Cache[T any] struct {
	// contains filtered or unexported fields
}
Example
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/flanksource/clicky/cache"
	"github.com/flanksource/clicky/cache/swr"
)

func main() {
	ctx := context.Background()
	store := cache.NewMemory().(cache.ConditionalStore)
	snapshots, err := swr.New[string](swr.Config{Shared: store, Policy: swr.Policy{
		FreshFor: time.Minute, MaxFreshFor: time.Hour, StaleFor: 72 * time.Hour,
		MaxLocalAge: 2 * time.Hour, MaxSharedAge: 7 * 24 * time.Hour,
	}})
	if err != nil {
		panic(err)
	}
	scope := swr.Scope{Prefix: "example:state:v1:tenant-a:issue", Group: "connection-a"}
	ids := []string{"TASK-21"}
	err = snapshots.Revalidate(ctx, scope, swr.Refresh[string]{IDs: ids,
		Load: func(context.Context, map[string]string) (map[string]swr.Loaded[string], error) {
			return map[string]swr.Loaded[string]{"TASK-21": {Data: "Review roadmap", Revision: "3"}}, nil
		}})
	if err != nil {
		panic(err)
	}
	rows, err := snapshots.Lookup(ctx, scope, ids)
	if err != nil {
		panic(err)
	}
	fmt.Println(rows["TASK-21"].Data)
}
Output:
Review roadmap

func New

func New[T any](cfg Config) (*Cache[T], error)

func (*Cache[T]) Invalidate

func (c *Cache[T]) Invalidate(ctx context.Context, scope Scope, request Invalidation) error

func (*Cache[T]) Lookup

func (c *Cache[T]) Lookup(ctx context.Context, scope Scope, ids []string) (map[string]Value[T], error)

Lookup returns only the eligible records. An omitted identity is a miss.

func (*Cache[T]) Revalidate

func (c *Cache[T]) Revalidate(ctx context.Context, scope Scope, request Refresh[T]) error

type CodecConfig

type CodecConfig struct {
	CompressAt int
	MaxStored  int
	MaxDecoded int
}

type Config

type Config struct {
	Shared      cache.ConditionalStore
	Policy      Policy
	Codec       CodecConfig
	LocalWeight uint64
	Now         func() time.Time
	ReadTimeout time.Duration
}

type Invalidation

type Invalidation struct {
	IDs    []string
	Delete bool
}

type Loaded

type Loaded[T any] struct {
	Data     T
	Revision string
	Deleted  bool
}

type Policy

type Policy struct {
	FreshFor     time.Duration
	MaxFreshFor  time.Duration
	StaleFor     time.Duration
	MaxLocalAge  time.Duration
	MaxSharedAge time.Duration
	Bands        []Band
}

type Refresh

type Refresh[T any] struct {
	IDs    []string
	Guards []cache.Guard
	// Load returns observations for the requested IDs. An omitted ID is unchanged
	// in the cache. An unchanged source revision still needs a successful observation.
	Load func(context.Context, map[string]string) (map[string]Loaded[T], error)
}

type Scope

type Scope struct {
	Prefix string
	Group  string
}

func (Scope) ControlKey

func (s Scope) ControlKey(name string) string

type State

type State string
const (
	Fresh State = "fresh"
	Stale State = "stale"
)

type Value

type Value[T any] struct {
	Data        T
	Revision    string
	State       State
	Tier        string
	ValidatedAt time.Time
	FreshUntil  time.Time
	ServeUntil  time.Time
}

Jump to

Keyboard shortcuts

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