client

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 9 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 client is the Go client for cache-boy (and any RESP server).

c, err := client.Dial("127.0.0.1:6380", client.Password("secret"))
defer c.Close()
c.Set(ctx, "greeting", "hello", client.SetOptions{TTL: time.Minute})
v, err := c.Get(ctx, "greeting")

A Client is safe for concurrent use; it keeps a pool of connections. Do runs any command; typed helpers cover common and cache-boy commands.

Index

Constants

View Source
const (
	CacheHit     = "hit"
	CacheCompute = "compute"
	CacheTimeout = "timeout"
)

CacheGet statuses.

View Source
const NoExpiry time.Duration = -1

NoExpiry is returned by TTL for a key without a TTL.

Variables

View Source
var ErrClosed = errors.New("cache-boy: client closed")

ErrClosed is returned after Close.

View Source
var ErrNil = errors.New("cache-boy: nil")

ErrNil is returned by typed helpers when the server replies null (missing key...).

View Source
var ErrNotAcquired = errors.New("cache-boy: lock not acquired")

ErrNotAcquired is returned by Lock when the lock is held by someone else.

Functions

func Args

func Args(args ...any) ([]string, error)

Args converts arguments to strings: string, []byte, integers, floats, bool (1/0), time.Duration (milliseconds) and fmt.Stringer are supported.

Types

type CacheGetOptions

type CacheGetOptions struct {
	Lock time.Duration // compute lock duration (server default 10s)
	Wait time.Duration // how long to wait for another computer (server default 5s)
}

CacheGetOptions are the options of CacheGet.

type CacheResult

type CacheResult struct {
	Status string // CacheHit, CacheCompute or CacheTimeout
	Value  string // set when Status is CacheHit
}

CacheResult is the reply of CACHE.GET.

type Client

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

Client is a pool of connections to one server.

func Dial

func Dial(addr string, opts ...Option) (*Client, error)

Dial connects to addr ("host:port") and checks the connection (and credentials) by opening the first pooled connection.

func (*Client) CacheGet

func (c *Client) CacheGet(ctx context.Context, key string, opts ...CacheGetOptions) (CacheResult, error)

CacheGet runs CACHE.GET. Prefer Wrap, which implements the whole protocol.

func (*Client) CacheRelease

func (c *Client) CacheRelease(ctx context.Context, key string) (bool, error)

CacheRelease gives up the compute lock taken by CACHE.GET.

func (*Client) Close

func (c *Client) Close() error

Close closes all idle connections; connections in use close when returned.

func (*Client) Del

func (c *Client) Del(ctx context.Context, keys ...string) (int64, error)

Del deletes keys and returns how many existed.

func (*Client) Do

func (c *Client) Do(ctx context.Context, args ...any) (Value, error)

Do runs one command and returns its reply. An error reply is returned as both the Value and an Error. A null reply is returned as a null Value with a nil error (typed helpers turn it into ErrNil).

func (*Client) Eval

func (c *Client) Eval(ctx context.Context, script string, keys []string, args ...any) (Value, error)

Eval runs a server-side JavaScript script (see docs/features.md).

func (*Client) Exists

func (c *Client) Exists(ctx context.Context, keys ...string) (int64, error)

Exists counts how many of keys exist.

func (*Client) Expire

func (c *Client) Expire(ctx context.Context, key string, ttl time.Duration) (bool, error)

Expire sets a TTL (millisecond precision); false if the key doesn't exist.

func (*Client) Get

func (c *Client) Get(ctx context.Context, key string) (string, error)

Get returns the value of key, or ErrNil.

func (*Client) HGetAll

func (c *Client) HGetAll(ctx context.Context, key string) (map[string]string, error)

HGetAll returns every field of a hash (empty map if missing).

func (*Client) HSet

func (c *Client) HSet(ctx context.Context, key string, fields map[string]any) (int64, error)

HSet sets hash fields and returns how many were new.

func (*Client) Incr

func (c *Client) Incr(ctx context.Context, key string) (int64, error)

Incr increments an integer value and returns the new value.

func (*Client) KeyWatch

func (c *Client) KeyWatch(ctx context.Context, patterns ...string) (*Subscription, error)

KeyWatch streams changes of keys matching the patterns: each Message has Channel = key and Payload = operation ("set", "del", "expired"...).

func (*Client) LPush

func (c *Client) LPush(ctx context.Context, key string, values ...any) (int64, error)

LPush prepends values and returns the new length.

func (*Client) Lock

func (c *Client) Lock(ctx context.Context, name string, ttl time.Duration, opts ...LockOptions) (*Lock, error)

Lock acquires name for ttl, or returns ErrNotAcquired.

func (*Client) PSubscribe

func (c *Client) PSubscribe(ctx context.Context, patterns ...string) (*Subscription, error)

PSubscribe listens to channels matching glob patterns.

func (*Client) Pipeline

func (c *Client) Pipeline() *Pipeline

func (*Client) Publish

func (c *Client) Publish(ctx context.Context, channel string, message any) (int64, error)

Publish sends a message and returns how many subscribers received it.

func (*Client) QAck

func (c *Client) QAck(ctx context.Context, queue, id string) (bool, error)

QAck marks a job as done.

func (*Client) QNack

func (c *Client) QNack(ctx context.Context, queue, id string, delay time.Duration) (bool, error)

QNack fails a job: it is retried after delay, or dead-lettered.

func (*Client) QPop

func (c *Client) QPop(ctx context.Context, queue string, opts ...QPopOptions) (*Job, error)

QPop takes the next job, or returns ErrNil when none is ready (after blocking, if asked). Blocking honours ctx cancellation.

func (*Client) QPush

func (c *Client) QPush(ctx context.Context, queue string, payload any, opts ...QPushOptions) (string, error)

QPush enqueues a job and returns its id.

func (*Client) RPop

func (c *Client) RPop(ctx context.Context, key string) (string, error)

RPop removes and returns the last element, or ErrNil.

func (*Client) RateLimit

func (c *Client) RateLimit(ctx context.Context, key string, limit int64, period time.Duration, cost ...int64) (RateLimitResult, error)

RateLimit consumes cost (default 1) from a GCRA limit of `limit` per `period` for key.

func (*Client) SAdd

func (c *Client) SAdd(ctx context.Context, key string, members ...any) (int64, error)

SAdd adds members and returns how many were new.

func (*Client) SMembers

func (c *Client) SMembers(ctx context.Context, key string) ([]string, error)

SMembers returns all members of a set.

func (*Client) Set

func (c *Client) Set(ctx context.Context, key string, value any, opts ...SetOptions) (bool, error)

Set stores value at key. It returns false (and no error) when NX/XX prevented the write.

func (*Client) Subscribe

func (c *Client) Subscribe(ctx context.Context, channels ...string) (*Subscription, error)

Subscribe listens to channels on a dedicated connection.

func (*Client) TTL

func (c *Client) TTL(ctx context.Context, key string) (time.Duration, error)

TTL returns the remaining time to live, NoExpiry, or ErrNil if the key doesn't exist.

func (*Client) TagAdd

func (c *Client) TagAdd(ctx context.Context, key string, tags ...string) (int64, error)

TagAdd attaches tags to a key; returns how many were newly attached.

func (*Client) TagInvalidate

func (c *Client) TagInvalidate(ctx context.Context, tags ...string) (int64, error)

TagInvalidate deletes every key carrying any of the tags; returns the count.

func (*Client) Wrap

func (c *Client) Wrap(ctx context.Context, key string, ttl time.Duration, fn func(ctx context.Context) (string, error)) (string, error)

Wrap returns the cached value of key, or computes it with fn exactly once across all clients (others wait for the result):

  • hit: the cached value is returned.
  • compute: fn runs; its result is stored with SET key value PX ttl. If fn fails, the compute lock is released (CACHE.RELEASE) and the error returned.
  • timeout (another client took too long): fn runs and its result is returned without being stored.

func (*Client) ZAdd

func (c *Client) ZAdd(ctx context.Context, key string, members ...Z) (int64, error)

ZAdd adds members and returns how many were new.

func (*Client) ZRange

func (c *Client) ZRange(ctx context.Context, key string, start, stop int64) ([]string, error)

ZRange returns members by rank (inclusive, negative = from the end).

func (*Client) ZRangeWithScores

func (c *Client) ZRangeWithScores(ctx context.Context, key string, start, stop int64) ([]Z, error)

ZRangeWithScores returns members and scores by rank.

type Error

type Error string

Error is an error reply from the server, such as "WRONGTYPE ...".

func (Error) Code

func (e Error) Code() string

Code returns the error code: "ERR", "WRONGTYPE", "NOPERM"...

func (Error) Error

func (e Error) Error() string

type Job

type Job struct {
	Queue   string
	ID      string
	Payload string
	Attempt int64
	// contains filtered or unexported fields
}

Job is a job taken with QPop. Ack or Nack it when done.

func (*Job) Ack

func (j *Job) Ack(ctx context.Context) (bool, error)

Ack is QAck for this job.

func (*Job) Nack

func (j *Job) Nack(ctx context.Context, delay time.Duration) (bool, error)

Nack is QNack for this job.

type Lock

type Lock struct {
	Name  string
	Token int64
	// contains filtered or unexported fields
}

Lock is a held distributed lock. Token is the fencing token: pass it along with writes so stale holders can be rejected.

func (*Lock) Extend

func (l *Lock) Extend(ctx context.Context, ttl time.Duration) (bool, error)

Extend sets a new TTL; false if the lock is no longer held.

func (*Lock) Unlock

func (l *Lock) Unlock(ctx context.Context) (bool, error)

Unlock releases the lock; false if it had expired or was taken over.

type LockOptions

type LockOptions struct {
	Wait  time.Duration // how long to wait for the lock (0 = don't wait)
	Owner string        // shown in LOCK.INFO
}

LockOptions are the options of Lock.

type Message

type Message struct {
	Kind    string // "message", "pmessage", "keyevent", or another push kind
	Pattern string // for pmessage
	Channel string // channel, or the key for keyevent
	Payload string // message, or the operation (set, del, expired...) for keyevent
	Raw     Value
}

Message is one push received by a Subscription.

type Option

type Option func(*options)

Option configures Dial.

func DialTimeout

func DialTimeout(d time.Duration) Option

DialTimeout bounds connecting and the handshake (default 5s).

func Namespace

func Namespace(ns string) Option

Namespace isolates every key used by this client (NAMESPACE USE on connect).

func Password

func Password(p string) Option

Password authenticates as the default user, or as Username if set.

func PoolSize

func PoolSize(n int) Option

PoolSize is the maximum number of pooled connections (default 10).

func Protocol

func Protocol(v int) Option

Protocol selects RESP2 (default) or RESP3 (maps, doubles, booleans).

func Username

func Username(u string) Option

Username sets the ACL user (used with Password).

type Pipeline

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

Pipeline queues commands and sends them in one round-trip.

p := c.Pipeline()
p.Do("SET", "a", 1)
p.Do("INCR", "a")
replies, err := p.Exec(ctx)

func (*Pipeline) Do

func (p *Pipeline) Do(args ...any) *Pipeline

Do queues a command.

func (*Pipeline) Exec

func (p *Pipeline) Exec(ctx context.Context) ([]Value, error)

Exec sends all queued commands and returns one reply per command, in order. Error replies are returned as error Values; err is only set for network or argument errors. The pipeline is empty afterwards.

func (*Pipeline) Len

func (p *Pipeline) Len() int

Len is the number of queued commands.

type QPopOptions

type QPopOptions struct {
	Visibility time.Duration // re-deliver if not acked within this time (server default 30s)
	Block      time.Duration // wait up to this long for a job
	Forever    bool          // wait until a job arrives or ctx ends (BLOCK 0)
}

QPopOptions are the options of QPop.

type QPushOptions

type QPushOptions struct {
	Delay   time.Duration // deliver later
	Retries int           // max retries before the dead-letter list (0 = server default, 3)
	ID      string        // idempotency id; a duplicate is ignored
}

QPushOptions are the options of QPush.

type RateLimitResult

type RateLimitResult struct {
	Allowed    bool
	Remaining  int64
	RetryAfter time.Duration // 0 when allowed
	ResetAfter time.Duration
}

RateLimitResult is the reply of RATELIMIT.

type SetOptions

type SetOptions struct {
	TTL  time.Duration // EX/PX; 0 = no expiry
	NX   bool          // only set if the key doesn't exist
	XX   bool          // only set if the key exists
	Tags []string      // cache-boy tags (see TagInvalidate)
}

SetOptions are the options of Set.

type Subscription

type Subscription struct {
	C <-chan Message
	// contains filtered or unexported fields
}

Subscription receives pushes on its own connection. Read C until it is closed (after Close, ctx cancellation, or a connection error; see Err).

func (*Subscription) Close

func (s *Subscription) Close() error

Close ends the subscription and closes its connection.

func (*Subscription) Err

func (s *Subscription) Err() error

Err returns the connection error that ended the subscription, if any.

type Value

type Value = resp.Value

Value is a RESP reply. Use v.Type, v.Str, v.Int, v.Float, v.Bool, v.Elems, or v.String() for scalars. RESP3 maps keep key, value, key, value... in Elems.

type Z

type Z struct {
	Member string
	Score  float64
}

Z is a sorted-set member with its score.

Jump to

Keyboard shortcuts

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