utils

package
v0.0.0-...-1203bc7 Latest Latest
Warning

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

Go to latest
Published: May 13, 2026 License: MPL-2.0 Imports: 47 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrHostnameMismatch = errors.New("user ID does not belong to this homeserver")
View Source
var LoopbackIPConst = net.IPv4(127, 0, 0, 1)

Functions

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, error)

CheckPassword checks if the provided password matches the hashed password. The hashed password SHOULD be in PHC format, but if it is not, legacyCheckPassword is invoked instead.

func ChecksumString

func ChecksumString(v string) string

ChecksumString calculates an SHA-256 checksum for the input string.

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 DeferredClose

func DeferredClose(closer io.Closer)

DeferredClose just swallows any error from io.Closer.Close, useful for defers.

func EnvOr

func EnvOr(key, defaultValue string) string

func Eprintlnf

func Eprintlnf(format string, args ...any)

Eprintlnf is the same as Printlnf, but outputs to stderr instead (swallowing any return values).

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 HashPasswordPHC

func HashPasswordPHC(raw string, t, m uint32, p uint8) string

HashPasswordPHC hashes the raw password using Argon2id and the provided parameters, and returns the hashed password in PHC format.

When t is 0, defaultArgonT is used. Likewise, when m is 0, defaultArgonM is used. When p is 0, it defaults to the current value of GOMAXPROCS, typically the number of available CPUs.

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 MarshalCanonical

func MarshalCanonical(v any) ([]byte, error)

MarshalCanonical marshals the given value to canonical JSON.

func MustCheckPassword

func MustCheckPassword(raw, hashed string) bool

func NewNull

func NewNull[T any](v *T) sql.Null[T]

NewNull returns a sql.Null[T] with the given value. If the value is nil, it returns a Null[T] with Valid set to false.

func NewNullString

func NewNullString(v *string) sql.NullString

NewNullString returns a sql.NullString with the given value. If the value is nil, it returns a NullString with Valid set to false.

func NewV1RoomID

func NewV1RoomID(serverName string) id.RoomID

NewV1RoomID creates a new V1 (opaque) room ID with the given server name.

func NilOrString

func NilOrString(v sql.NullString) *string

NilOrString returns a pointer to the string value of a sql.NullString if it is valid, or nil if it is not valid.

func NilOrV

func NilOrV[T any](v sql.Null[T]) *T

NilOrV returns a pointer to the value of a sql.Null[T] if it is valid, or nil if it is not valid.

func PrintDebugInfo

func PrintDebugInfo()

func Printlnf

func Printlnf(format string, args ...any)

Printlnf is a combination of fmt.Println and.

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) (allowed 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 UserIDFromIdentifier

func UserIDFromIdentifier(identifier *mautrix.UserIdentifier, hostname string) (userID id.UserID, err error)

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 time.Duration

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

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 JSONIPNet

type JSONIPNet net.IPNet

func (*JSONIPNet) MarshalJSON

func (n *JSONIPNet) MarshalJSON() ([]byte, error)

func (*JSONIPNet) MarshalYAML

func (n *JSONIPNet) MarshalYAML() (any, error)

func (*JSONIPNet) UnmarshalJSON

func (n *JSONIPNet) UnmarshalJSON(data []byte) error

func (*JSONIPNet) UnmarshalYAML

func (n *JSONIPNet) UnmarshalYAML(unmarshal func(any) error) error

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 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 SyncMap

type SyncMap[K comparable, V any] struct {
	// contains filtered or unexported fields
}

SyncMap is a typed drop in replacement for sync.Map, reducing the number of `any` types the caller has to deal with.

func (*SyncMap[K, V]) Clear

func (m *SyncMap[K, V]) Clear()

Clear deletes all the entries, resulting in an empty Map.

func (*SyncMap[K, V]) CompareAndDelete

func (m *SyncMap[K, V]) CompareAndDelete(key K, old V) (deleted bool)

CompareAndDelete deletes the entry for key if its value is equal to old. The old value must be of a comparable type.

If there is no current value for key in the map, CompareAndDelete returns false (even if the old value is the nil interface value).

func (*SyncMap[K, V]) CompareAndSwap

func (m *SyncMap[K, V]) CompareAndSwap(key K, old, new2 V) (swapped bool)

CompareAndSwap swaps the old and new values for key if the value stored in the map is equal to old. The old value must be of a comparable type.

func (*SyncMap[K, V]) Delete

func (m *SyncMap[K, V]) Delete(key K)

Delete deletes the value for a key. If the key is not in the map, Delete does nothing.

func (*SyncMap[K, V]) Load

func (m *SyncMap[K, V]) Load(key K) (value V, ok bool)

Load returns the value stored in the map for a key, or nil if no value is present. The ok result indicates whether value was found in the map.

func (*SyncMap[K, V]) LoadAndDelete

func (m *SyncMap[K, V]) LoadAndDelete(key K) (value V, loaded bool)

LoadAndDelete deletes the value for a key, returning the previous value if any. The loaded result reports whether the key was present.

func (*SyncMap[K, V]) LoadOrStore

func (m *SyncMap[K, V]) LoadOrStore(key K, value V) (actual V, loaded bool)

LoadOrStore returns the existing value for the key if present. Otherwise, it stores and returns the given value. The loaded result is true if the value was loaded, false if stored.

func (*SyncMap[K, V]) Range

func (m *SyncMap[K, V]) Range(f func(key K, value V) bool)

Range calls f sequentially for each key and value present in the map. If f returns false, range stops the iteration.

Range does not necessarily correspond to any consistent snapshot of the Map's contents: no key will be visited more than once, but if the value for any key is stored or deleted concurrently (including by f), Range may reflect any mapping for that key from any point during the Range call. Range does not block other methods on the receiver; even f itself may call any method on m.

Range may be O(N) with the number of elements in the map even if f returns false after a constant number of calls.

func (*SyncMap[K, V]) Store

func (m *SyncMap[K, V]) Store(key K, value V)

Store sets the value for a key.

func (*SyncMap[K, V]) Swap

func (m *SyncMap[K, V]) Swap(key K, value V) (previous V, loaded bool)

Swap swaps the value for a key and returns the previous value if any. The loaded result reports whether the key was present.

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