cache

package
v0.0.122 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: GPL-3.0 Imports: 11 Imported by: 0 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

Index

Constants

View Source
const AudienceGenTTL = 30 * 24 * time.Hour

AudienceGenTTL keeps generation keys from outliving their channel or user forever. An expired key is re-seeded with a fresh random value, which reads as a change — one extra reload, never a stale hit.

Variables

View Source
var ErrCacheMiss = errors.New("cache miss")

ErrCacheMiss is returned when a key is not found in the cache.

Functions

func BumpAudienceGenerations added in v0.0.97

func BumpAudienceGenerations(ctx context.Context, rdb redis.UniversalClient, keys ...string) error

BumpAudienceGenerations moves every key to a new value, by a random step, so a key lost to a Redis restart or eviction (and re-seeded at random) never comes back with a value an old cache entry still carries.

func ChannelAudienceKey added in v0.0.97

func ChannelAudienceKey(channelID string) string

ChannelAudienceKey is the generation key of a channel's audience.

func UserAudienceKey added in v0.0.97

func UserAudienceKey(userID string) string

UserAudienceKey is the generation key of a user's account settings.

Types

type MemberLists added in v0.0.110

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

MemberLists is the shared copy of channels' member rows: one hash per channel holding the audience generation it was read under and a field per member. It is valid only while that generation is the channel's current one (ChannelAudienceKey), which every membership write moves — the services and the history importer alike — so a change is never served stale; the TTL only bounds a generation move that was lost. A hash filled from the whole member list is marked complete and answers "who are the members"; one filled member by member answers only for those members.

func NewMemberLists added in v0.0.110

func NewMemberLists(rdb redis.UniversalClient, ttl time.Duration) *MemberLists

NewMemberLists keeps each channel's copy for at most ttl.

func (*MemberLists) Member added in v0.0.110

func (m *MemberLists) Member(ctx context.Context, channelID, userID string) (*model.ChannelMembership, string, error)

Member returns userID's row in channelID's copy (nil when the copy doesn't hold one at the current generation), and the current generation to store a fill under. One round trip.

func (*MemberLists) Members added in v0.0.110

func (m *MemberLists) Members(ctx context.Context, channelID string) ([]*model.ChannelMembership, string, bool, error)

Members returns channelID's member rows when its copy is complete at the current generation (complete=false otherwise), and the current generation to store a fill under. One round trip.

func (*MemberLists) PutMember added in v0.0.110

func (m *MemberLists) PutMember(ctx context.Context, channelID, gen string, row *model.ChannelMembership) error

PutMember stores one member's row, read under gen.

func (*MemberLists) PutMembers added in v0.0.110

func (m *MemberLists) PutMembers(ctx context.Context, channelID, gen string, rows []*model.ChannelMembership) error

PutMembers stores channelID's complete member list, read under gen.

type RedisCache

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

RedisCache wraps a Redis client to provide typed caching operations.

func NewRedisCache

func NewRedisCache(redisURL string) (*RedisCache, error)

NewRedisCache parses the given Redis URL, creates a client, and verifies connectivity with a PING.

func (*RedisCache) AcquireLock added in v0.0.56

func (c *RedisCache) AcquireLock(ctx context.Context, key, token string, ttl time.Duration) (bool, error)

AcquireLock takes a token-fenced distributed lock via SET key token NX PX ttl. Returns true only if THIS caller now holds it; false if another instance holds it (or a crashed holder's lock hasn't yet aged out). The token must be unique per acquisition so ReleaseLock only ever drops a lock this caller still owns. Backs the single-runner election for cluster-wide maintenance jobs (e.g. the search mapping rebuild) so parallel containers can't double-run one.

func (*RedisCache) AppPausedFor added in v0.0.116

func (c *RedisCache) AppPausedFor(ctx context.Context, webhookID string) (time.Duration, error)

AppPausedFor is how much longer an app stays paused for failing (zero when it isn't).

func (*RedisCache) ArePresenceOnline added in v0.0.59

func (c *RedisCache) ArePresenceOnline(ctx context.Context, userIDs []string) (map[string]bool, error)

ArePresenceOnline reports online status for many users in ONE pipelined round trip — the notification fan-out needs the whole recipient set at once, and a read per recipient made every message cost O(members) Redis calls. A missing set counts zero live members (offline), same as IsPresenceOnline.

func (*RedisCache) ChannelAudiencesChanged added in v0.0.97

func (c *RedisCache) ChannelAudiencesChanged(ctx context.Context, channelIDs ...string) error

ChannelAudiencesChanged moves the audience generations of these channels, for a membership write made outside the services (the history importer).

func (*RedisCache) ClaimIdempotencyKey added in v0.0.116

func (c *RedisCache) ClaimIdempotencyKey(ctx context.Context, scope, key string, ttl time.Duration) (prev []byte, claimed bool, err error)

ClaimIdempotencyKey claims an app's Idempotency-Key for ttl. The first claim gets claimed=true; a later one gets the answer the first stored (empty while the first is still running).

func (*RedisCache) Client

func (c *RedisCache) Client() *redis.Client

Client returns the underlying Redis client for advanced operations.

func (*RedisCache) ConsumePasswordResetTicket added in v0.0.66

func (c *RedisCache) ConsumePasswordResetTicket(ctx context.Context, tokenHash string) (string, error)

ConsumePasswordResetTicket atomically redeems a ticket (GETDEL — a second redemption of the same token finds nothing). Returns ("", nil) for an unknown, expired, or already-used token; the caller answers with a generic "invalid or expired link".

func (*RedisCache) ConsumeWSTicket added in v0.0.64

func (c *RedisCache) ConsumeWSTicket(ctx context.Context, ticket string) (string, time.Time, error)

ConsumeWSTicket atomically redeems a ticket (GETDEL — a second redemption of the same ticket finds nothing). Returns ("", zero, nil) for an unknown, expired, or already-used ticket; the caller answers 401.

func (*RedisCache) DecrementPresence added in v0.0.25

func (c *RedisCache) DecrementPresence(ctx context.Context, userID, connID string) (bool, error)

DecrementPresence removes connID and reports whether the user is now offline (no live connections remain). ZREM of an already-expired/missing member is a harmless no-op — the old counter's negative-value flap (a DECR against a lapsed key knocking a still-connected user offline) is structurally impossible here. Two round trips: the removal+count, then the branch-dependent index update.

func (*RedisCache) Delete

func (c *RedisCache) Delete(ctx context.Context, key string) error

Delete removes a key from Redis.

func (*RedisCache) DeleteUsers added in v0.0.93

func (c *RedisCache) DeleteUsers(ctx context.Context, userIDs []string) error

DeleteUsers drops the cached records of the given users in one round-trip, so the next read reloads them from the store. Used after users are written outside the service layer (e.g. a history import). No-op for an empty list.

func (*RedisCache) DeleteView added in v0.0.116

func (c *RedisCache) DeleteView(ctx context.Context, v *model.StoredView) error

DeleteView forgets a closed form, and its external_id while that still names it.

func (*RedisCache) DropViewExternalID added in v0.0.116

func (c *RedisCache) DropViewExternalID(ctx context.Context, webhookID, externalID, viewID string) error

DropViewExternalID forgets an app's external_id for a form, unless it has moved on to another form meanwhile. No external_id: nothing to do.

func (*RedisCache) FinishIdempotencyKey added in v0.0.116

func (c *RedisCache) FinishIdempotencyKey(ctx context.Context, scope, key string, answer []byte, ttl time.Duration) error

FinishIdempotencyKey stores the answer to a claimed key, so a retry gets it again; answer nil releases the claim (the call failed and may be retried for real).

func (*RedisCache) FrequentEmojis added in v0.0.47

func (c *RedisCache) FrequentEmojis(ctx context.Context, userID string, limit int) ([]string, error)

FrequentEmojis returns up to limit of the user's most-used emoji shortcodes, highest count first. Reading ALSO refreshes the TTL: merely opening the emoji picker (or rendering the quick-reaction bar, which reads this list) keeps a user's favourites alive, so an active user never loses them to the inactivity TTL — only a user who is gone for the whole TTL window ages out.

func (*RedisCache) FrequentPeople added in v0.0.120

func (c *RedisCache) FrequentPeople(ctx context.Context, userID string, limit int) ([]string, error)

FrequentPeople returns up to limit of the people userID mentions or messages most, highest first. Reading refreshes the TTL, as for emoji.

func (*RedisCache) Get

func (c *RedisCache) Get(ctx context.Context, key string, dest interface{}) error

Get retrieves a value from Redis by key and JSON-unmarshals it into dest. Returns ErrCacheMiss if the key does not exist.

func (*RedisCache) GetManyJSON added in v0.0.59

func (c *RedisCache) GetManyJSON(ctx context.Context, keys []string) ([][]byte, error)

GetManyJSON MGETs raw JSON values for the given keys in one round trip. The result is key-aligned; a nil slot is a miss.

func (*RedisCache) GetName added in v0.0.53

func (c *RedisCache) GetName(ctx context.Context, key string) (string, bool)

GetName returns a cached display name for key (e.g. "chan:<id>"/"user:<id>").

func (*RedisCache) GetUser

func (c *RedisCache) GetUser(ctx context.Context, userID string) (*model.User, error)

GetUser attempts to retrieve a cached User by ID. Returns ErrCacheMiss if the user is not in cache; callers are responsible for loading from the store.

func (*RedisCache) GetUsers added in v0.0.59

func (c *RedisCache) GetUsers(ctx context.Context, userIDs []string) (map[string]*model.User, error)

GetUsers retrieves many cached users in ONE MGET round trip instead of a GET per ID (the pattern that made /users/batch cost 2N sequential Redis calls). Misses and undecodable records are simply absent from the result; callers resolve them from the store.

func (*RedisCache) GetView added in v0.0.116

func (c *RedisCache) GetView(ctx context.Context, id string) (*model.StoredView, error)

GetView returns an open form, or nil once it is closed or expired.

func (*RedisCache) IncrementEmojiFrequency added in v0.0.47

func (c *RedisCache) IncrementEmojiFrequency(ctx context.Context, userID, shortcode string) error

IncrementEmojiFrequency records one use of a picked emoji shortcode as a PER-EVENT recency-decayed count: every existing score is multiplied by emojiFreqDecay, then the picked emoji gets +1 (see emojiFreqIncrScript). So the shelf tracks current habits — using OTHER emojis pushes a stale one down right away — while nothing is ever removed (a favourite only sinks, never vanishes). Every pick path records a use (picker, quick-reaction bar, and the composer :shortcode: typeahead — the typeahead not recording was the original "shelf never updates" bug).

func (*RedisCache) IncrementPresence added in v0.0.25

func (c *RedisCache) IncrementPresence(ctx context.Context, userID, connID string) (bool, error)

IncrementPresence records connID as a live connection for the user and reports whether this made the user online (first live connection anywhere in the fleet). Lapsed members are pruned in the same pipeline so a crashed instance's leftovers can't inflate the count past their TTL.

func (*RedisCache) IsPresenceOnline added in v0.0.25

func (c *RedisCache) IsPresenceOnline(ctx context.Context, userID string) (bool, error)

IsPresenceOnline reports whether any process has a LIVE (non-lapsed) websocket connection for a user. Pure read — lapsed members are ignored by score, not pruned here.

func (*RedisCache) ListInteractions added in v0.0.116

func (c *RedisCache) ListInteractions(ctx context.Context, webhookID string) ([]model.InteractionEntry, error)

ListInteractions is an app's history, newest first. A line that can't be read is left out.

func (*RedisCache) LockHeld added in v0.0.56

func (c *RedisCache) LockHeld(ctx context.Context, key string) (bool, error)

LockHeld reports whether the lock key currently exists. Used to reconcile a "running" status whose runner crashed: once the lock's TTL lapses the panel stops showing a phantom in-progress job.

func (*RedisCache) MarkNotificationAcked added in v0.0.51

func (c *RedisCache) MarkNotificationAcked(ctx context.Context, userID, messageID string) error

MarkNotificationAcked records that the user's client confirmed receipt of the desktop notification for messageID. Used by the deferred mobile-push fallback to cancel a push once the desktop has actually delivered the alert.

func (*RedisCache) MintPasswordResetTicket added in v0.0.66

func (c *RedisCache) MintPasswordResetTicket(ctx context.Context, tokenHash, userID string, ttl time.Duration) error

MintPasswordResetTicket stores a reset ticket under the token's hash. The caller owns token generation and hashing so the raw token exists only in the link it emails.

func (*RedisCache) MintResponseURL added in v0.0.116

func (c *RedisCache) MintResponseURL(ctx context.Context, tokenHash string, rec model.ResponseURLRecord, uses int, ttl time.Duration) error

MintResponseURL stores what a response URL stands for, good for `uses` uses within ttl.

func (*RedisCache) MintTrigger added in v0.0.116

func (c *RedisCache) MintTrigger(ctx context.Context, tokenHash string, rec model.TriggerRecord, ttl time.Duration) error

MintTrigger stores what a trigger_id stands for, usable once within ttl.

func (*RedisCache) MintWSTicket added in v0.0.64

func (c *RedisCache) MintWSTicket(ctx context.Context, ticket, userID string, sessionDeadline time.Time) error

MintWSTicket stores a one-time WebSocket upgrade ticket for the user. The session deadline rides along so the socket inherits the access token's remaining lifetime (bounding a deactivated user's exposure even if the ephemeral force-logout event is lost).

func (*RedisCache) NoteAppFailure added in v0.0.116

func (c *RedisCache) NoteAppFailure(ctx context.Context, webhookID string, threshold int, pause time.Duration) (time.Duration, error)

NoteAppFailure counts a failed click in an app's current streak and, at `threshold` in a row, pauses the app for `pause` — the streak goes on, so the first click after the pause that fails pauses it again. Returns how long the app is paused for (zero when it isn't).

func (*RedisCache) NoteAppSuccess added in v0.0.116

func (c *RedisCache) NoteAppSuccess(ctx context.Context, webhookID string) error

NoteAppSuccess ends an app's failure streak.

func (*RedisCache) OnlinePresenceUserIDs added in v0.0.25

func (c *RedisCache) OnlinePresenceUserIDs(ctx context.Context) ([]string, error)

func (*RedisCache) RecordInteraction added in v0.0.116

func (c *RedisCache) RecordInteraction(ctx context.Context, webhookID string, entry model.InteractionEntry) error

RecordInteraction adds one line to an app's history, newest first, keeping the last interactionHistoryLen.

func (*RedisCache) RecordPeopleContact added in v0.0.120

func (c *RedisCache) RecordPeopleContact(ctx context.Context, userID string, weights map[string]float64) error

RecordPeopleContact adds one send's contacts to userID's people ranking: each person's weight (a mention, a DM partner) on top of the decayed history. Nothing to record is a no-op.

func (*RedisCache) RefreshPresence added in v0.0.25

func (c *RedisCache) RefreshPresence(ctx context.Context, userID, connID string) error

RefreshPresence re-scores connID's expiry. This is the single most frequent Redis operation in the backend (every connection, every keep-alive interval). The plain ZADD is the SELF-HEAL path: a member lost to a Redis blip (or a whole set lost to an eviction) is recreated within one keep-alive interval — under the old counter design a lapsed marker stayed gone until the user physically reconnected, showing a live user offline indefinitely. The index re-score keeps the snapshot source fresh the same way.

func (*RedisCache) ReleaseLock added in v0.0.56

func (c *RedisCache) ReleaseLock(ctx context.Context, key, token string) error

ReleaseLock drops the lock only if the caller's token still owns it (see releaseLockScript). A no-op when the token no longer matches — safe to call even after the lock's TTL lapsed and someone else re-acquired it.

func (*RedisCache) SaveView added in v0.0.116

func (c *RedisCache) SaveView(ctx context.Context, v *model.StoredView, ttl time.Duration) error

SaveView stores an open form for ttl, findable by its ID and, when it has one, by its app's external_id.

func (*RedisCache) Set

func (c *RedisCache) Set(ctx context.Context, key string, val interface{}, ttl time.Duration) error

Set JSON-marshals val and stores it in Redis with the given TTL.

func (*RedisCache) SetManyJSON added in v0.0.59

func (c *RedisCache) SetManyJSON(ctx context.Context, keys []string, values []any, ttl time.Duration) error

SetManyJSON writes many JSON values (key-aligned with values, one shared TTL) in one pipelined round trip. Signature stays primitive-typed so service-layer capability assertions don't need a shared struct type.

func (*RedisCache) SetName added in v0.0.53

func (c *RedisCache) SetName(ctx context.Context, key, val string)

SetName caches a display name with a short TTL.

func (*RedisCache) SetUser

func (c *RedisCache) SetUser(ctx context.Context, user *model.User) error

SetUser caches a User with a default TTL.

func (*RedisCache) SetUsers added in v0.0.59

func (c *RedisCache) SetUsers(ctx context.Context, users []*model.User) error

SetUsers caches many users in one pipelined write (misses filled after a batched store read shouldn't cost a round trip each).

func (*RedisCache) TakeView added in v0.0.116

func (c *RedisCache) TakeView(ctx context.Context, v *model.StoredView) (bool, error)

TakeView deletes an open form and reports whether this call deleted it — of several closing it at once, exactly one does.

func (*RedisCache) UseResponseURL added in v0.0.116

func (c *RedisCache) UseResponseURL(ctx context.Context, tokenHash string) (*model.ResponseURLRecord, int, error)

UseResponseURL spends one use of a response URL. It returns the record and the uses left after this one — negative once they are all spent — or a nil record for an expired or unknown URL.

func (*RedisCache) UseTrigger added in v0.0.116

func (c *RedisCache) UseTrigger(ctx context.Context, tokenHash string) (*model.TriggerRecord, error)

UseTrigger spends a trigger_id: the first use gets its record, any later one (or one after it expired) nil.

func (*RedisCache) ViewIDByExternalID added in v0.0.116

func (c *RedisCache) ViewIDByExternalID(ctx context.Context, webhookID, externalID string) (string, error)

ViewIDByExternalID finds an app's open form by the external_id it gave; "" when there is none.

func (*RedisCache) WasNotificationAcked added in v0.0.51

func (c *RedisCache) WasNotificationAcked(ctx context.Context, userID, messageID string) bool

WasNotificationAcked reports whether the user's client has acknowledged the desktop notification for messageID. A Redis error or a missing key both resolve to false — "not acked" — so an ack lookup failure makes the fallback FedEx the push rather than silently swallow it (fail toward delivery).

type UserGroupCopies added in v0.0.121

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

UserGroupCopies is the shared copy of user groups (their row and members) that a group mention reads instead of DynamoDB. It is a copy, never the source: a reader that misses reads the store and stores what it read, and every committed change deletes the copy. A reader that read the store just before a change can store the previous members after the delete; the short TTL bounds how long that copy lives.

func NewUserGroupCopies added in v0.0.121

func NewUserGroupCopies(rdb redis.UniversalClient, ttl time.Duration) *UserGroupCopies

NewUserGroupCopies keeps each group's copy for at most ttl.

func (*UserGroupCopies) Forget added in v0.0.121

func (c *UserGroupCopies) Forget(ctx context.Context, id string) error

Forget deletes a group's copy after a committed change, so the next reader reads the store.

func (*UserGroupCopies) Get added in v0.0.121

Get returns the copies of the groups with these IDs; groups without one are absent. One round trip.

func (*UserGroupCopies) Put added in v0.0.121

Put stores g, as read from the store.

Jump to

Keyboard shortcuts

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