state

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2026 License: MIT Imports: 16 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 state keeps the guilds, channels, roles, members, messages and voice states a bot sees, built from gateway events.

Feed a Cache from the session handler before the router, so handlers read the state after the event:

cache := state.New(state.WithMemberPolicy(state.MembersInVoice()))
session.Handler = func(event string, data json.RawMessage) {
	cache.Handle(event, data)
	router.Handle(event, data)
}

Flags and policies decide what is kept. OnChange passes the value from before an update or delete. A Chunker loads guild members, a Resolver falls back to REST for anything missing, and a Store decides where the data lives. The default store is in memory; the state/redis module shares one cache between processes.

Index

Constants

View Source
const DefaultMessagesPerChannel = 100

DefaultMessagesPerChannel is the number of messages kept per channel when WithMessages is not used.

Variables

View Source
var ErrChunkTimeout = errors.New("state: member chunks did not arrive in time")

ErrChunkTimeout is returned by Chunker.Request when not all chunks arrived within Chunker.Timeout.

Functions

func ChunkAll

func ChunkAll(string) bool

ChunkAll is a Chunker.Filter that matches every guild.

func ChunkGuilds

func ChunkGuilds(ids ...string) func(string) bool

ChunkGuilds returns a Chunker.Filter that matches the listed guilds.

func OnChange

func OnChange[E any, P interface {
	*E
	fluxer.Event
}, O any](c *Cache, fn func(old O, e P)) func()

OnChange registers fn for events of type P. old is Change.Old converted to O, or the zero value of O if the types do not match. With a pointer type such as *fluxer.Channel for O, fn receives nil when nothing was cached.

Types

type Cache

type Cache struct {
	// SkipMembers stops the cache from storing members other than the bot's own member.
	SkipMembers bool
	// OnError receives events that Handle could not decode.
	OnError func(event string, err error)
	// contains filtered or unexported fields
}

Cache keeps gateway state in a Store. Pass every dispatch to Handle or Apply; the read methods are safe to call from any goroutine.

func New

func New(opts ...Option) *Cache

New returns a cache that stores everything in FlagsAll, with opts applied in order.

func (*Cache) Apply

func (c *Cache) Apply(e fluxer.Event)

Apply updates the cache from a decoded event and then runs the OnChange handlers. Events for the same guild are applied one at a time.

func (*Cache) CanManageMember

func (c *Cache) CanManageMember(guildID, actorID, targetID string) bool

CanManageMember reports whether actorID outranks targetID in the role hierarchy. Nobody can manage the owner or themselves, the owner can manage everyone else, and a target without cached roles can be managed by any actor that has one. Permissions are not checked.

func (*Cache) CanManageRole

func (c *Cache) CanManageRole(guildID, actorID, roleID string) bool

CanManageRole reports whether actorID ranks above roleID in the role hierarchy. The guild owner can manage every role. Permissions are not checked.

func (*Cache) Channel

func (c *Cache) Channel(id string) (fluxer.Channel, bool)

Channel returns a cached guild channel, thread or DM channel by ID.

func (*Cache) ChannelByName

func (c *Cache) ChannelByName(guildID, name string) (fluxer.Channel, bool)

ChannelByName returns the first non-thread channel by position whose name matches, ignoring case and a leading #.

func (*Cache) EachGuild

func (c *Cache) EachGuild() iter.Seq[fluxer.Guild]

EachGuild yields the available guilds in no particular order, assembled like Guild, without building a slice first.

func (*Cache) EachMember

func (c *Cache) EachMember(guildID string) iter.Seq[fluxer.Member]

EachMember yields the guild's cached members in no particular order.

func (*Cache) EachMessage

func (c *Cache) EachMessage(channelID string) iter.Seq[fluxer.Message]

EachMessage yields a channel's cached messages in no particular order.

func (*Cache) Emoji

func (c *Cache) Emoji(guildID, emojiID string) (fluxer.Emoji, bool)

Emoji returns a cached guild emoji.

func (*Cache) EmojiByName

func (c *Cache) EmojiByName(guildID, name string) (fluxer.Emoji, bool)

EmojiByName returns a guild emoji with exactly that name. If several share the name, any one of them is returned.

func (*Cache) FindMember

func (c *Cache) FindMember(guildID, name string) (fluxer.Member, bool)

FindMember looks up a member by username, tag or display name, ignoring case, surrounding spaces and a leading @. An exact match wins; otherwise it returns the member with the lowest user ID whose name starts with name.

func (*Cache) Flags

func (c *Cache) Flags() Flags

Flags returns the flags the cache was configured with.

func (*Cache) Guild

func (c *Cache) Guild(id string) (fluxer.Guild, bool)

Guild returns a cached guild with its roles, emojis, stickers and non-thread channels filled in. Unavailable guilds are reported as missing.

func (*Cache) GuildChannels

func (c *Cache) GuildChannels(guildID string) []fluxer.Channel

GuildChannels returns the guild's channels without threads, sorted by position and then ID.

func (*Cache) Guilds

func (c *Cache) Guilds() []fluxer.Guild

Guilds returns all available guilds sorted by ID, assembled like Guild.

func (*Cache) Handle

func (c *Cache) Handle(event string, data json.RawMessage)

Handle decodes a raw gateway dispatch and applies it. Decode errors go to OnError and event names the library does not know are ignored.

func (*Cache) HighestRole

func (c *Cache) HighestRole(guildID, userID string) (fluxer.Role, bool)

HighestRole returns the member's highest cached role by position, preferring the lower ID on a tie. It returns false when none of the member's roles is cached.

func (*Cache) Member

func (c *Cache) Member(guildID, userID string) (fluxer.Member, bool)

Member returns a cached member. When the stored member carries only a user ID, the user is filled in from the user table.

func (*Cache) MemberPartial

func (c *Cache) MemberPartial(guildID, userID string) bool

MemberPartial reports whether a member is cached without user details such as the username.

func (*Cache) Members

func (c *Cache) Members(guildID string) []fluxer.Member

Members returns the guild's cached members sorted by user ID.

func (*Cache) Message

func (c *Cache) Message(channelID, messageID string) (fluxer.Message, bool)

Message returns a cached message.

func (*Cache) MessageByID

func (c *Cache) MessageByID(messageID string) (fluxer.Message, bool)

MessageByID returns a cached message without knowing its channel. It needs a store whose message table supports Locate.

func (*Cache) Messages

func (c *Cache) Messages(channelID string, q fluxer.MessageQuery) []fluxer.Message

Messages returns cached messages of a channel between q.After and q.Before, newest first. When only q.After is set, it returns the messages right after it, oldest first. q.Limit caps the number of results.

func (*Cache) OnChange

func (c *Cache) OnChange(fn func(Change)) func()

OnChange registers fn to run after each event, once the cache has applied it and released its lock. Handlers run on the goroutine that called Apply. The returned function removes the handler.

func (*Cache) PendingGuilds

func (c *Cache) PendingGuilds() int

PendingGuilds returns how many guilds from the last READY have not arrived yet.

func (*Cache) Permissions

func (c *Cache) Permissions(guildID, channelID, userID string) (fluxer.Permissions, bool)

Permissions computes a member's permissions from cached data. An empty channelID gives guild-level permissions, and a thread uses its parent's overwrites. It returns false when the guild, member or channel is not cached.

func (*Cache) Presence

func (c *Cache) Presence(guildID, userID string) (fluxer.Presence, bool)

Presence returns a user's presence in a guild. Offline users have no cached presence.

func (*Cache) Presences

func (c *Cache) Presences(guildID string) []fluxer.Presence

Presences returns the guild's cached presences sorted by user ID.

func (*Cache) Role

func (c *Cache) Role(guildID, roleID string) (fluxer.Role, bool)

Role returns a cached role.

func (*Cache) RoleByName

func (c *Cache) RoleByName(guildID, name string) (fluxer.Role, bool)

RoleByName returns the lowest role by position whose name matches, ignoring case.

func (*Cache) Self

func (c *Cache) Self() fluxer.User

Self returns the bot user from the last READY, kept current by USER_UPDATE.

func (*Cache) SelfMember

func (c *Cache) SelfMember(guildID string) (fluxer.Member, bool)

SelfMember returns the bot's own member in a guild.

func (*Cache) Stats

func (c *Cache) Stats() Stats

Stats counts the entries in every table of the store. It walks all groups, which can be slow with a remote store.

func (*Cache) Store

func (c *Cache) Store() Store

Store returns the backing store.

func (*Cache) SweepMembers

func (c *Cache) SweepMembers() int

SweepMembers checks every cached member against the flags, SkipMembers and the member policy again and removes the ones that no longer pass. It returns the number of members removed.

func (*Cache) SweepMessages

func (c *Cache) SweepMessages() int

SweepMessages removes expired messages and messages that fail the message policy, calling the evict function for each one. It returns the number removed.

func (*Cache) Threads

func (c *Cache) Threads(parentID string) []fluxer.Channel

Threads returns the cached threads of parentID sorted by ID. It returns nil when the parent channel is not cached.

func (*Cache) Unavailable

func (c *Cache) Unavailable(id string) bool

Unavailable reports whether the guild is known but currently unavailable.

func (*Cache) User

func (c *Cache) User(id string) (fluxer.User, bool)

User returns a cached user. Users are collected from READY, members, presences and messages while FlagUsers is set.

func (*Cache) VoiceChannel

func (c *Cache) VoiceChannel(guildID, userID string) string

VoiceChannel returns the voice channel a user is in, or an empty string. For a user with several connections in the guild it returns any one of them.

func (*Cache) VoiceMembers

func (c *Cache) VoiceMembers(guildID, channelID string) []fluxer.Member

VoiceMembers returns the cached members in a voice channel, sorted by user ID. Users in the channel without a cached member are left out.

func (*Cache) VoiceStates

func (c *Cache) VoiceStates(guildID string) []fluxer.VoiceState

VoiceStates returns the guild's voice states sorted by user ID. A user connected from several sessions appears once per connection.

func (*Cache) WaitGuilds

func (c *Cache) WaitGuilds(ctx context.Context) error

WaitGuilds blocks until every guild listed in the last READY has arrived through GUILD_CREATE or GUILD_DELETE, or until ctx is done.

type Change

type Change struct {
	// Event is the applied event.
	Event fluxer.Event
	// Old is the cached value from before the event. It is a pointer such as
	// *fluxer.Channel or *fluxer.Message for update, delete and reaction events, and
	// that pointer is nil when nothing was cached. MessageDeleteBulk gives the cached
	// []fluxer.Message, and emoji and sticker updates give the previous slice. Old is
	// nil for events that have no previous value.
	Old any
}

Change describes an event that a cache has applied.

type Chunker

type Chunker struct {
	// Requester sends the member requests.
	Requester MemberRequester
	// Filter, when set, makes Handle request all members of each guild in a
	// GUILD_CREATE for which it returns true. ChunkAll and ChunkGuilds are ready-made
	// filters.
	Filter func(guildID string) bool
	// Timeout is how long Request waits for all chunks after sending the request. The
	// default is 30 seconds.
	Timeout time.Duration
	// OnError receives errors from the requests started by Filter.
	OnError func(guildID string, err error)
	// contains filtered or unexported fields
}

Chunker requests guild members over the gateway and collects the matching GUILD_MEMBERS_CHUNK events. Pass raw dispatches to Handle.

func NewChunker

func NewChunker(r MemberRequester) *Chunker

NewChunker returns a chunker that sends requests through r.

func (*Chunker) Handle

func (k *Chunker) Handle(event string, data json.RawMessage)

Handle processes a raw gateway dispatch. It reads GUILD_MEMBERS_CHUNK, RATE_LIMITED and GUILD_CREATE and ignores other events. Chunks without a nonce or with a nonce the chunker did not send are ignored.

func (*Chunker) Request

func (k *Chunker) Request(ctx context.Context, r fluxer.RequestMembers) ([]fluxer.Member, error)

Request sends r with a new nonce, waits until every chunk for that nonce has arrived and returns the collected members. Presences in the chunks are not returned. It fails with a *RateLimitedError if the gateway rate limits the request, with ErrChunkTimeout after Timeout, or with the context's error.

func (*Chunker) RequestAll

func (k *Chunker) RequestAll(ctx context.Context, guildID string) ([]fluxer.Member, error)

RequestAll requests every member of a guild.

type Flags

type Flags uint32

Flags selects which kinds of data a Cache stores.

const (
	FlagGuilds Flags = 1 << iota
	FlagChannels
	FlagThreads
	FlagRoles
	FlagMembers
	FlagVoiceStates
	FlagEmojis
	FlagStickers
	FlagUsers
	FlagPresences
	FlagMessages

	FlagsAll = FlagGuilds | FlagChannels | FlagThreads | FlagRoles | FlagMembers | FlagVoiceStates | FlagEmojis | FlagStickers |
		FlagUsers | FlagPresences | FlagMessages
)

Flags for the individual tables. FlagThreads covers thread channels and FlagChannels all other channels. FlagsAll is the default for New.

func (Flags) Has

func (f Flags) Has(flag Flags) bool

Has reports whether every bit of flag is set in f.

type GuildRecord

type GuildRecord struct {
	Guild fluxer.Guild `json:"guild"`
	// Unavailable is set while the gateway reports the guild as unavailable.
	Unavailable bool `json:"unavailable,omitempty"`
	// JoinedAt is when the bot joined the guild, if the gateway sent it.
	JoinedAt *time.Time `json:"joined_at,omitempty"`
}

GuildRecord is the stored form of a guild. Guild has no roles, channels, emojis or stickers; the cache keeps those in their own tables and adds them back on read.

type Instances

type Instances struct {
	// SkipMembers is copied to each cache when it is created. Changing it later does not
	// affect existing caches.
	SkipMembers bool
	// OnError receives decode errors from all caches together with the origin that
	// produced them. It is read when a cache is created.
	OnError func(origin, event string, err error)
	// Options returns extra options for one origin. They are applied after the options
	// passed to NewInstances.
	Options func(origin string) []Option
	// contains filtered or unexported fields
}

Instances keeps one Cache per origin, for bots connected to several Fluxer instances. A cache is created the first time its origin is used.

func NewInstances

func NewInstances(opts ...Option) *Instances

NewInstances returns an empty set of caches. opts apply to every cache it creates.

func (*Instances) Drop

func (m *Instances) Drop(origin string)

Drop forgets the cache for origin. The next call to For creates a new, empty one.

func (*Instances) For

func (m *Instances) For(origin string) *Cache

For returns the cache for origin, creating it on the first call.

func (*Instances) Handler

func (m *Instances) Handler(origin string) func(event string, data json.RawMessage)

Handler returns the Handle method of the cache for origin, for use as a raw gateway event handler.

func (*Instances) Origins

func (m *Instances) Origins() []string

Origins returns the origins that have a cache, sorted.

type MemberRequester

type MemberRequester interface {
	RequestGuildMembers(ctx context.Context, r fluxer.RequestMembers) error
}

MemberRequester sends a request guild members command. *fluxer.Session implements it.

type MemoryStore

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

MemoryStore is the default in-memory Store. Its channel and message tables are indexed.

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore returns an empty store.

func (*MemoryStore) Channels

func (s *MemoryStore) Channels() Table[fluxer.Channel]

Channels returns the channel table.

func (*MemoryStore) Emojis

func (s *MemoryStore) Emojis() Table[fluxer.Emoji]

Emojis returns the emoji table.

func (*MemoryStore) Guilds

func (s *MemoryStore) Guilds() Table[GuildRecord]

Guilds returns the guild table.

func (*MemoryStore) Members

func (s *MemoryStore) Members() Table[fluxer.Member]

Members returns the member table.

func (*MemoryStore) Messages

func (s *MemoryStore) Messages() Table[fluxer.Message]

Messages returns the message table.

func (*MemoryStore) Presences

func (s *MemoryStore) Presences() Table[fluxer.Presence]

Presences returns the presence table.

func (*MemoryStore) Roles

func (s *MemoryStore) Roles() Table[fluxer.Role]

Roles returns the role table.

func (*MemoryStore) Stickers

func (s *MemoryStore) Stickers() Table[fluxer.Sticker]

Stickers returns the sticker table.

func (*MemoryStore) Users

func (s *MemoryStore) Users() Table[fluxer.User]

Users returns the user table.

func (*MemoryStore) VoiceStates

func (s *MemoryStore) VoiceStates() Table[fluxer.VoiceState]

VoiceStates returns the voice state table.

type MemoryTable

type MemoryTable[V any] struct {
	// contains filtered or unexported fields
}

MemoryTable is an in-memory Table, sharded by group. An indexed table also records which group holds each key, for Locate.

func NewMemoryTable

func NewMemoryTable[V any](indexed bool) *MemoryTable[V]

NewMemoryTable returns an empty table. With indexed set, Locate works, which assumes that each key is used in only one group.

func (*MemoryTable[V]) Delete

func (t *MemoryTable[V]) Delete(group, key string)

Delete removes one value and drops the group once it is empty.

func (*MemoryTable[V]) DeleteGroup

func (t *MemoryTable[V]) DeleteGroup(group string)

DeleteGroup removes every value in group.

func (*MemoryTable[V]) Get

func (t *MemoryTable[V]) Get(group, key string) (V, bool)

Get returns the value stored under group and key.

func (*MemoryTable[V]) Group

func (t *MemoryTable[V]) Group(group string) iter.Seq2[string, V]

Group returns a snapshot of group taken when Group is called.

func (*MemoryTable[V]) Groups

func (t *MemoryTable[V]) Groups() iter.Seq[string]

Groups returns a snapshot of the names of all non-empty groups.

func (*MemoryTable[V]) Len

func (t *MemoryTable[V]) Len(group string) int

Len returns the number of values in group.

func (*MemoryTable[V]) Locate

func (t *MemoryTable[V]) Locate(key string) (string, bool)

Locate returns the group that holds key. It always returns false for a table created without an index.

func (*MemoryTable[V]) Put

func (t *MemoryTable[V]) Put(group, key string, v V)

Put stores v under group and key.

type Option

type Option func(*Cache)

Option configures a Cache created by New.

func WithChannelPolicy

func WithChannelPolicy(p Policy[fluxer.Channel]) Option

WithChannelPolicy limits which channels and threads are cached. A cached channel that stops matching on a later update is removed.

func WithFlags

func WithFlags(f Flags) Option

WithFlags replaces the cache flags, which default to FlagsAll.

func WithMemberPolicy

func WithMemberPolicy(p Policy[fluxer.Member]) Option

WithMemberPolicy limits which members are cached. The bot's own member is always kept, regardless of the policy, FlagMembers and SkipMembers. A cached member that stops matching on a later update is removed.

func WithMessageEvict

func WithMessageEvict(fn func(fluxer.Message)) Option

WithMessageEvict sets a function that is called for every message removed by the limit, the TTL or SweepMessages. Messages deleted by events are not reported.

func WithMessagePolicy

func WithMessagePolicy(p Policy[fluxer.Message]) Option

WithMessagePolicy limits which messages are cached. SweepMessages removes cached messages that no longer match.

func WithMessages

func WithMessages(perChannel int, ttl time.Duration) Option

WithMessages sets how many messages are kept per channel and for how long. When a channel goes over perChannel, its oldest messages are evicted. A ttl of zero keeps messages until the limit evicts them; otherwise expired messages are removed when the channel gets a new message or by SweepMessages. A perChannel of zero or less disables the message cache.

func WithStore

func WithStore(s Store) Option

WithStore sets the backing store. The default is a new MemoryStore.

func WithoutFlags

func WithoutFlags(f Flags) Option

WithoutFlags clears f from the flags set so far.

type Policy

type Policy[T any] func(c *Cache, v T) bool

Policy decides whether a value is kept in the cache. It runs on every write of that kind of value, so it should be cheap, and it must not apply events to the same cache.

func All

func All[T any]() Policy[T]

All returns a policy that keeps every value.

func ChannelTypes

func ChannelTypes(types ...int) Policy[fluxer.Channel]

ChannelTypes keeps channels whose type is one of types.

func MemberOwner

func MemberOwner() Policy[fluxer.Member]

MemberOwner keeps the owner of each cached guild.

func MembersInGuilds

func MembersInGuilds(guildIDs ...string) Policy[fluxer.Member]

MembersInGuilds keeps members of the listed guilds.

func MembersInVoice

func MembersInVoice() Policy[fluxer.Member]

MembersInVoice keeps members that are in a voice channel according to the cached voice states, so it needs FlagVoiceStates. A member is dropped when its voice state shows that it left.

func MembersOnline

func MembersOnline() Policy[fluxer.Member]

MembersOnline keeps members with a cached presence that is not offline. Members who go offline stay cached until their next member update or SweepMembers.

func MembersTimedOut

func MembersTimedOut() Policy[fluxer.Member]

MembersTimedOut keeps members whose timeout has not ended yet. Members whose timeout runs out stay cached until their next member update or SweepMembers.

func MembersWithRole

func MembersWithRole(roleIDs ...string) Policy[fluxer.Member]

MembersWithRole keeps members that have at least one of the listed roles.

func MessagesFromHumans

func MessagesFromHumans() Policy[fluxer.Message]

MessagesFromHumans keeps messages that were not sent by a bot or a webhook.

func MessagesInGuilds

func MessagesInGuilds(guildIDs ...string) Policy[fluxer.Message]

MessagesInGuilds keeps messages sent in the listed guilds.

func None

func None[T any]() Policy[T]

None returns a policy that keeps no value.

func (Policy[T]) And

func (p Policy[T]) And(other Policy[T]) Policy[T]

And returns a policy that keeps a value only if both p and other keep it.

func (Policy[T]) Not

func (p Policy[T]) Not() Policy[T]

Not returns a policy that keeps exactly the values p rejects.

func (Policy[T]) Or

func (p Policy[T]) Or(other Policy[T]) Policy[T]

Or returns a policy that keeps a value if p or other keeps it.

type RateLimitedError

type RateLimitedError struct {
	GuildID string
	// RetryAfter is how long to wait before requesting members of the guild again.
	RetryAfter time.Duration
}

RateLimitedError is returned by Chunker.Request when the gateway answers the request with RATE_LIMITED.

func (*RateLimitedError) Error

func (e *RateLimitedError) Error() string

Error implements the error interface.

type Resolver

type Resolver struct {
	Cache  *Cache
	Client *fluxer.Client
	// contains filtered or unexported fields
}

Resolver reads from a Cache and falls back to the REST API on a miss. Fetched values are written back to the cache, subject to its flags and policies, and concurrent fetches of the same value share one request.

func NewResolver

func NewResolver(c *Cache, client *fluxer.Client) *Resolver

NewResolver returns a resolver for c that fetches missing data with client.

func (*Resolver) Channel

func (r *Resolver) Channel(ctx context.Context, id string) (fluxer.Channel, error)

Channel returns a channel from the cache or fetches it.

func (*Resolver) Guild

func (r *Resolver) Guild(ctx context.Context, id string) (fluxer.Guild, error)

Guild returns a guild from the cache or fetches it.

func (*Resolver) Member

func (r *Resolver) Member(ctx context.Context, guildID, userID string) (fluxer.Member, error)

Member returns a member from the cache, or fetches it when it is missing or partial.

func (*Resolver) Message

func (r *Resolver) Message(ctx context.Context, channelID, messageID string) (fluxer.Message, error)

Message returns a message from the cache or fetches it.

func (*Resolver) Permissions

func (r *Resolver) Permissions(ctx context.Context, guildID, channelID, userID string) (fluxer.Permissions, error)

Permissions fetches whatever is missing of the guild, its roles, the member, the channel and a thread's parent, and then computes the permissions like Cache.Permissions. An empty channelID gives guild-level permissions.

func (*Resolver) Roles

func (r *Resolver) Roles(ctx context.Context, guildID string) ([]fluxer.Role, error)

Roles returns the guild's roles. Any cached role for the guild counts as a hit, and only a guild without cached roles is fetched.

func (*Resolver) User

func (r *Resolver) User(ctx context.Context, id string) (fluxer.User, error)

User returns a user from the cache or fetches it.

type Stats

type Stats struct {
	Guilds      int
	Channels    int
	Roles       int
	Members     int
	Users       int
	Presences   int
	VoiceStates int
	Messages    int
	Emojis      int
	Stickers    int
	// Hits counts Resolver lookups that were answered from the cache.
	Hits uint64
	// Misses counts Resolver lookups that went to the API.
	Misses uint64
}

Stats is a snapshot of how many entries each table of a cache holds.

type Store

type Store interface {
	// Guilds holds guild records under the empty group, keyed by guild ID.
	Guilds() Table[GuildRecord]
	// Channels holds channels grouped by guild ID, with DM channels under the empty
	// group. The cache uses Locate to find a channel by ID alone.
	Channels() Table[fluxer.Channel]
	// Roles holds roles grouped by guild ID.
	Roles() Table[fluxer.Role]
	// Members holds members grouped by guild ID and keyed by user ID.
	Members() Table[fluxer.Member]
	// VoiceStates holds voice states grouped by guild ID and keyed by connection ID, or
	// by user ID when a state has no connection ID.
	VoiceStates() Table[fluxer.VoiceState]
	// Emojis holds custom emojis grouped by guild ID.
	Emojis() Table[fluxer.Emoji]
	// Stickers holds stickers grouped by guild ID.
	Stickers() Table[fluxer.Sticker]
	// Users holds users under the empty group, keyed by user ID.
	Users() Table[fluxer.User]
	// Presences holds presences grouped by guild ID and keyed by user ID.
	Presences() Table[fluxer.Presence]
	// Messages holds messages grouped by channel ID. Cache.MessageByID needs Locate to
	// work on this table.
	Messages() Table[fluxer.Message]
}

Store holds the tables a Cache reads and writes. NewMemoryStore is the default; the state/redis module provides a Store that several processes can share.

type Table

type Table[V any] interface {
	// Get returns the value stored under group and key.
	Get(group, key string) (V, bool)
	// Put stores v under group and key, replacing any previous value.
	Put(group, key string, v V)
	// Delete removes one value.
	Delete(group, key string)
	// DeleteGroup removes every value in group.
	DeleteGroup(group string)
	// Group returns the entries of group. The entries are read when Group is called, so
	// the table can be changed while iterating.
	Group(group string) iter.Seq2[string, V]
	// Len returns the number of values in group.
	Len(group string) int
	// Groups returns the names of all groups that hold at least one value.
	Groups() iter.Seq[string]
	// Locate returns the group that holds key. Tables that keep no key index always
	// return false.
	Locate(key string) (string, bool)
}

Table is a two-level key-value table used by a Store. Values live under a group, usually a guild or channel ID, and a key inside that group.

Directories

Path Synopsis
redis module

Jump to

Keyboard shortcuts

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