utils

package
v0.0.0-...-21bdbe5 Latest Latest
Warning

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

Go to latest
Published: Jan 14, 2026 License: MPL-2.0 Imports: 42 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AggregateSigningKeysRaw

func AggregateSigningKeysRaw(pdus []federation.PDU) (keysToFetch map[string]map[id.KeyID]time.Time, keyCount int)

AggregateSigningKeysRaw aggregates signing keys to fetch from a list of raw federation PDUs This is more efficient than parsing the PDUs fully as it inspects the JSON bytes directly, avoiding any overhead from unmarshalling into structs.

func BulkIntoFederation

func BulkIntoFederation(evts []*pdu.PDU, roomVersion id.RoomVersion) ([]json.RawMessage, error)

BulkIntoFederation converts a list of PDUs into their JSON representation suitable for federation transmission.

func CheckPassword

func CheckPassword(raw, hashed string) bool

CheckPassword checks if the provided password matches the hashed password The hashed password is expected to be a base64 encoded string raw is the unhashed, user provided password to check.

func ComputeChecksumStream

func ComputeChecksumStream(reader io.ReadSeeker) (string, error)

ComputeChecksumStream computes the SHA-256 checksum of the data read from the provided stream. The stream must implement io.ReadSeeker to allow resetting to the beginning. It returns the checksum as a hexadecimal string.

func CopyAndSumStream

func CopyAndSumStream(src io.Reader, dst io.Writer) (sum string, size int64, err error)

CopyAndSumStream copies data from src to dst while computing the SHA-256 checksum of the data. It returns the computed checksum as a hexadecimal string.

func EventID

func EventID(roomVersion id.RoomVersion, evt *pdu.PDU) id.EventID

EventID gets the event ID from a pdu.PDU, either using its internal cached version, or generating it fresh. Returns an empty string if the ID couldn't be generated if roomVersion is an empty string, only the internal eventCache will be queried.

func FederationToPDU

func FederationToPDU(evt federation.PDU) (*pdu.PDU, error)

FederationToPDU converts a federation PDU into a pdu.PDU. This is a glorified json unmarshal.

func GenerateThumbnail

func GenerateThumbnail(fd io.ReadSeeker, maxWidth, maxHeight int) (*bytes.Buffer, string, error)

GenerateThumbnail generates a thumbnail for the given file descriptor, resizing it as close to {width}x{height} while preserving the aspect ratio. It returns a reader for the thumbnail, the content type of the thumbnail, and an error if any occurred during the process.

func GetDimensions

func GetDimensions(fd io.Reader) (width, height *int64)

GetDimensions fetches the dimensions of the provided fd. It consumes the entire reader. If the dimensions cannot be determined, (nil, nil) is returned.

func GetSalt

func GetSalt() []byte

GetSalt generates a random salt for hashing passwords.

func HashPassword

func HashPassword(raw string) string

HashPassword hashes the raw password using Argon2id, and returns the hashed password The password is returned as a base64 encoded string.

func IntoFederation

func IntoFederation(evt *pdu.PDU, roomVersion id.RoomVersion) (json.RawMessage, error)

IntoFederation converts a PDU into its JSON representation suitable for federation transmission.

func LimitedRead

func LimitedRead(body io.Reader, maxBytes int) ([]byte, error)

LimitedRead limits the number of bytes read from the io.Reader to maxBytes. If there are unconsumed bytes, mautrix.MTooLarge is returned.

func LockContext

func LockContext(lock Lockable, ctx context.Context) bool

LockContext attempts to lock a Lockable (RW/Mutex), but will return false if the provided context is done before the lock is acquired. If the lock is acquired, it returns true. The caller is responsible for unlocking the mutex if true is returned.

func LockWithTimeout

func LockWithTimeout(lock Lockable, ctx context.Context, timeout time.Duration) bool

LockWithTimeout attempts to lock a Lockable (RW/Mutex), but will return false if the timeout is reached before the lock is acquired. If the lock is acquired, it returns true. The caller is responsible for unlocking the mutex if true is returned.

func RLockContext

func RLockContext(lock *sync.RWMutex, ctx context.Context) bool

RLockContext attempts to lock a sync.RWMutex for reading, but will return false if the provided context is done before the lock is acquired. If the lock is acquired, it returns true. The caller is responsible for unlocking the mutex if true is returned.

func RLockWithTimeout

func RLockWithTimeout(lock *sync.RWMutex, ctx context.Context, timeout time.Duration) bool

RLockWithTimeout attempts to lock a sync.RWMutex for reading, but will return false if the timeout is reached before the lock is acquired. If the lock is acquired, it returns true. The caller is responsible for unlocking the mutex if true is returned.

func RealIP

func RealIP(r *http.Request) (net.IP, error)

RealIP gets the trusted remote IP address from the request.

func RoomID

func RoomID(evt *pdu.PDU) id.RoomID

RoomID extracts the canonical room ID for the given event. For normal events, this is just evt.RoomID. For m.room.create events of room versions where the room ID is the event ID of the create event, this function returns the event ID instead.

func ServerAllowedByACL

func ServerAllowedByACL(serverName string, content *event.ServerACLEventContent) bool

ServerAllowedByACL checks if a server is allowed by the given ACL.

func SizeSeek

func SizeSeek(r io.ReadSeeker) (int64, error)

SizeSeek finds the length of an io.ReadSeeker by seeking to the end and back to the original position.

func UnmarshalJSON

func UnmarshalJSON(body io.Reader, v any, maxSize int) error

UnmarshalJSON reads JSON data from the io.Reader and unmarshals it into the provided interface. If the JSON cannot be unmarshalled, mautrix.MNotJSON is returned.

func VerifyStream

func VerifyStream(reader io.ReadSeeker, checksum string) (bool, error)

VerifyStream compares the SHA-256 checksum of the provided stream with the given checksum string.

Types

type HumanDuration

type HumanDuration struct {
	time.Duration
}

HumanDuration is a wrapper around time.Duration that supports marshalling and unmarshalling.

func (*HumanDuration) MarshalJSON

func (d *HumanDuration) MarshalJSON() ([]byte, error)

func (*HumanDuration) MarshalYAML

func (d *HumanDuration) MarshalYAML() (any, error)

func (*HumanDuration) UnmarshalJSON

func (d *HumanDuration) UnmarshalJSON(data []byte) error

func (*HumanDuration) UnmarshalYAML

func (d *HumanDuration) UnmarshalYAML(unmarshal func(any) error) error

type ITask

type ITask interface {
	Start()
	Stop()
	Reset()
}

type KVCache

type KVCache[K comparable, V any] struct {
	Mutex sync.RWMutex
	TTL   time.Duration // TTL is exported because it can safely be changed on the fly
	// contains filtered or unexported fields
}

KVCache is a simple key-value cache with a fixed capacity and optional TTL.

NOTE: You should only ever set pointer types in this cache to avoid excessive copying. While this is not enforced, I will be sad if you don't follow this advice.

NOTE 2: Time-based automatic cache eviction is not handled here. The caller is responsible if they wish to periodically evict expired caches. Otherwise, the usual on-demand eviction based on capacity will occur.

func NewKVCache

func NewKVCache[K comparable, V any](capacity int, ttl time.Duration, label string) *KVCache[K, V]

NewKVCache creates a new KVCache with the specified capacity. Capacity cannot be zero. TTL is the relative time-to-live duration for each entry, set to 0 to disable. Neither capacity nor ttl can be negative, and will panic.

func (*KVCache[K, V]) Add

func (lc *KVCache[K, V]) Add(key K, value V) *KVCache[K, V]

Add is similar to Set, but only adds the key-value pair if the key does not already exist.

func (*KVCache[K, V]) Capacity

func (lc *KVCache[K, V]) Capacity() int

Capacity returns the maximum capacity of the cache.

func (*KVCache[K, V]) Clear

func (lc *KVCache[K, V]) Clear()

Clear removes all entries from the cache.

func (*KVCache[K, V]) EvictExpired

func (lc *KVCache[K, V]) EvictExpired()

EvictExpired removes all entries that have exceeded their TTL. The caller is responsible for acquiring a write lock.

func (*KVCache[K, V]) EvictOldest

func (lc *KVCache[K, V]) EvictOldest()

EvictOldest removes eviction candidates until the cache size is under capacity. The caller is responsible for acquiring a write lock.

func (*KVCache[K, V]) EvictionPriority

func (lc *KVCache[K, V]) EvictionPriority(key K) int

EvictionPriority returns the eviction priority of a key, ranging from 0 (best candidate) to $capacity (least likely). If the key does not exist, it returns -1. This function does not take into account TTL expiration.

func (*KVCache[K, V]) Filter

func (lc *KVCache[K, V]) Filter(predicate func(key K, value V) bool) map[K]V

Filter returns a map of all entries that satisfy the provided predicate function.

func (*KVCache[K, V]) Get

func (lc *KVCache[K, V]) Get(key K) (V, bool)

Get retrieves a value from the cache by key. If the key does not exist or has expired, it returns nil and false.

func (*KVCache[K, V]) Remove

func (lc *KVCache[K, V]) Remove(key K)

Remove manually removes an entry from the cache by key.

func (*KVCache[K, V]) Set

func (lc *KVCache[K, V]) Set(key K, value V) *KVCache[K, V]

Set adds a key-value pair to the cache. If the cache exceeds its capacity, the oldest entry is evicted.

func (*KVCache[K, V]) Size

func (lc *KVCache[K, V]) Size() int

Size returns the current number of entries in the cache.

func (*KVCache[K, V]) UpdateCapacity

func (lc *KVCache[K, V]) UpdateCapacity(newCapacity int)

UpdateCapacity changes the capacity of the cache. This is a very expensive operation if the cache is in use.

type LockMap

type LockMap[K comparable] struct {
	// contains filtered or unexported fields
}

func (*LockMap[K]) Lock

func (lm *LockMap[K]) Lock(key K)

func (*LockMap[K]) TryLock

func (lm *LockMap[K]) TryLock(key K) bool

func (*LockMap[K]) Unlock

func (lm *LockMap[K]) Unlock(key K)

type Lockable

type Lockable interface {
	Lock()
}

type MaybeWriter

type MaybeWriter struct {
	io.Writer
}

MaybeWriter is an io.Writer that discards writes if the underlying writer is nil or there is an error writing.

func (MaybeWriter) Write

func (mw MaybeWriter) Write(p []byte) (int, error)

type Notifier

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

Notifier allows waiting for notifications on specific keys. Like pub/sub but oh my god.

func NewNotifier

func NewNotifier(ctx context.Context, label string) *Notifier

NewNotifier creates a new Notifier instance.

func (*Notifier) Notify

func (n *Notifier) Notify(keys ...string)

Notify sends a notification to all subscribers.

func (*Notifier) WaitAny

func (n *Notifier) WaitAny(ctx context.Context, keys ...string) string

WaitAny waits until any of the specified keys is notified, or the context is done, returning the key that was notified. If the context is done before any key is notified, it returns an empty string.

type RWLockMap

type RWLockMap[K comparable] struct {
	// contains filtered or unexported fields
}

func (*RWLockMap[K]) Lock

func (rlm *RWLockMap[K]) Lock(key K)

func (*RWLockMap[K]) RLock

func (rlm *RWLockMap[K]) RLock(key K)

func (*RWLockMap[K]) RUnlock

func (rlm *RWLockMap[K]) RUnlock(key K)

func (*RWLockMap[K]) TryLock

func (rlm *RWLockMap[K]) TryLock(key K) bool

func (*RWLockMap[K]) TryRLock

func (rlm *RWLockMap[K]) TryRLock(key K) bool

func (*RWLockMap[K]) Unlock

func (rlm *RWLockMap[K]) Unlock(key K)

type Task

type Task struct {
	Name     string
	Callback func(ctx context.Context)
	Interval time.Duration
	Ticker   *time.Ticker
	// contains filtered or unexported fields
}

Task represents a scheduled task with a name, callback function, and interval.

func NewTask

func NewTask(ctx context.Context, name string, interval time.Duration, callback func(ctx context.Context)) *Task

NewTask creates a new generic Task, initialising its fields, and forking the context to allow for cancellation.

func (*Task) Reset

func (t *Task) Reset()

Reset stops the task if it's running and starts it again.

func (*Task) Start

func (t *Task) Start()

Start begins the execution of the task at its specified interval.

func (*Task) Stop

func (t *Task) Stop()

Stop halts the execution of the task and cleans up resources.

Jump to

Keyboard shortcuts

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