redisstore

package
v2.1.6 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Overview

Package redisstore stores audit records in Redis for audit-kit.

It lives in its own package so that importing the root package does not drag go-redis -- and with it cespare/xxhash and go.uber.org/atomic -- into binaries that never talk to Redis. A service that writes its audit log to a file or to Postgres pays nothing for Redis support existing; only importing this package links it in.

The store is a translation layer and nothing more: what a record contains, how a query filter is interpreted and when a record is masked all live in the root package.

store := redisstore.New(redisClient)
logger := audit.NewLoggerWithWriter(store, audit.DefaultConfig())

Records are short-lived by design. Each one is a key with a TTL, indexed in a sorted set by timestamp, so Redis is the right backend for "what happened in the last few days" and the wrong one for retention that has to outlive a DefaultTTL window. Pair it with a file or database store through github.com/soulteary/audit-kit/v2.NewMultiStorage when both are needed.

Example

A Redis-backed audit log, kept for a week by default.

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/alicebob/miniredis/v2"
	"github.com/redis/go-redis/v9"

	audit "github.com/soulteary/audit-kit/v2"
	"github.com/soulteary/audit-kit/v2/redisstore"
)

func main() {
	// A real program dials its own Redis; miniredis keeps the example runnable.
	server, err := miniredis.Run()
	if err != nil {
		panic(err)
	}
	defer server.Close()

	client := redis.NewClient(&redis.Options{Addr: server.Addr()})
	defer func() { _ = client.Close() }()

	store := redisstore.NewWithConfig(client, &redisstore.Config{
		KeyPrefix: "myservice:audit:",
		TTL:       48 * time.Hour,
	})

	logger := audit.NewLogger(store, audit.DefaultConfig())
	logger.LogAuth(context.Background(), audit.EventLoginFailed, "user-42", audit.ResultFailure,
		audit.WithRecordReason("bad password"),
		audit.WithRecordIP("203.0.113.9"),
	)

	records, err := store.Query(context.Background(), audit.DefaultQueryFilter().WithUserID("user-42"))
	if err != nil {
		panic(err)
	}
	fmt.Println(records[0].EventType, records[0].Reason)

	// Closing the store leaves the client open: the rest of the program is
	// still using it. Config.CloseClient reverses that.
	_ = store.Close()
	fmt.Println(client.Ping(context.Background()).Err() == nil)

}
Output:
login_failed bad password
true

Index

Examples

Constants

View Source
const (
	// DefaultKeyPrefix is the prefix every key and the index share when
	// [Config.KeyPrefix] is not set.
	DefaultKeyPrefix = "audit:"

	// DefaultTTL is how long a record survives when [Config.TTL] is not set.
	DefaultTTL = 7 * 24 * time.Hour
)

Variables

View Source
var ErrNilClient = errors.New("redisstore: redis client is nil")

ErrNilClient is returned by every operation when the store was built with no client. It is an error rather than a panic because an audit backend that takes the process down is worse than the lost record it was meant to report.

Functions

This section is empty.

Types

type Client

type Client interface {
	Get(ctx context.Context, key string) *redis.StringCmd
	Set(ctx context.Context, key string, value interface{}, expiration time.Duration) *redis.StatusCmd
	Exists(ctx context.Context, keys ...string) *redis.IntCmd
	ZAdd(ctx context.Context, key string, members ...redis.Z) *redis.IntCmd
	ZRange(ctx context.Context, key string, start, stop int64) *redis.StringSliceCmd
	ZRangeArgs(ctx context.Context, z redis.ZRangeArgs) *redis.StringSliceCmd
	ZRem(ctx context.Context, key string, members ...interface{}) *redis.IntCmd
}

Client is the part of a go-redis client this store uses. *redis.Client, *redis.ClusterClient, *redis.Ring and redis.UniversalClient all satisfy it, so a store written against it works the same on a standalone server, a cluster and a Sentinel failover setup.

Every method here is part of redis.Cmdable, which means an instrumented or wrapped client satisfies it too.

type Config

type Config struct {
	KeyPrefix string        // Key prefix (default: DefaultKeyPrefix)
	TTL       time.Duration // Time-to-live for records (default: DefaultTTL)

	// CloseClient makes [Storage.Close] close the underlying client.
	//
	// It is off by default: a Redis client is normally shared with the rest of
	// the program, and closing it from an audit store -- which
	// audit.MultiStorage and audit.Logger.Stop both do on shutdown -- takes
	// the rest of the program's Redis with it. Set it when the store owns the
	// client. This reverses v1's behaviour, where RedisStorage.Close() always
	// closed the client.
	CloseClient bool
}

Config holds configuration for Redis storage.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns default Redis configuration.

type Storage

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

Storage implements audit.Storage on top of Redis. It is suitable for short-term storage and quick access.

func New

func New(client Client) *Storage

New creates a new Redis storage instance with the default configuration.

Example (Cluster)

The store takes any go-redis client shape, so a cluster needs no special case.

package main

import (
	"fmt"

	"github.com/redis/go-redis/v9"

	"github.com/soulteary/audit-kit/v2/redisstore"
)

func main() {
	// NewUniversalClient returns a redis.UniversalClient, which satisfies
	// redisstore.Client just as *redis.Client does.
	client := redis.NewUniversalClient(&redis.UniversalOptions{
		Addrs: []string{"10.0.0.1:6379", "10.0.0.2:6379", "10.0.0.3:6379"},
	})
	defer func() { _ = client.Close() }()

	store := redisstore.New(client)
	fmt.Println(store.KeyPrefix(), store.TTL())
}
Output:
audit: 168h0m0s

func NewWithConfig

func NewWithConfig(client Client, config *Config) *Storage

NewWithConfig creates a new Redis storage instance with config. A nil config means DefaultConfig; a zero KeyPrefix or a non-positive TTL falls back to the default for that field alone.

func (*Storage) Cleanup

func (s *Storage) Cleanup(ctx context.Context) (int64, error)

Cleanup removes from the index the entries whose record has already expired, and reports how many it removed. Queries skip such entries and drop them one by one, so this is an optimisation for an index that has grown large, not a correctness requirement.

func (*Storage) Client

func (s *Storage) Client() Client

Client returns the underlying Redis client.

func (*Storage) Close

func (s *Storage) Close() error

Close releases the store. It closes the underlying client only when the store was built with Config.CloseClient; see that field for why a shared client is left alone by default.

func (*Storage) KeyPrefix

func (s *Storage) KeyPrefix() string

KeyPrefix returns the key prefix.

func (*Storage) Query

func (s *Storage) Query(ctx context.Context, filter *audit.QueryFilter) ([]*audit.Record, error)

Query queries audit records from Redis.

func (*Storage) TTL

func (s *Storage) TTL() time.Duration

TTL returns the TTL.

func (*Storage) Write

func (s *Storage) Write(ctx context.Context, record *audit.Record) error

Write writes an audit record to Redis.

Jump to

Keyboard shortcuts

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