firestore_counter_cache

package module
v0.0.0-...-39c100f Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2025 License: MIT Imports: 5 Imported by: 0

README

Firestore Counter Cache

Firestore has limitations on how often one document can be updated + frequent updates add up to costs. So if there is no need in realtime updates, we can cache counter delta in memory and then commit to Firestore.

It is basically a simpler implementation of sync.Map.

Example usage:

// Init cache using one of the methods from caches.go
cache := NewUInt32Cache[string](db, func (k string) string {
    return fmt.Sprintf("collection/%s", k)
}, "Counter field name")
// Atomically add delta. If entry does not exist, it is automatically created
cache.Update("yourawesomeid", 1)
// Commit changes to database (increments fields). May be scheduled to run periodically or invoked when needed
// During commit operation dirty map is locked. This will slow down some operations
cache.Commit(context)

Benchmark:

goos: windows
goarch: amd64
pkg: go-counter-map
cpu: Intel(R) Core(TM) i5-9500F CPU @ 3.00GHz
BenchmarkMultiThread
BenchmarkMultiThread-6          51986534                23.65 ns/op            4 B/op          1 allocs/op
PASS

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CounterCache

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

func NewInt32Cache

func NewInt32Cache[K comparable](client *firestore.Client, docIdFunc func(key K) string, fieldName string) *CounterCache[K, int32]

func NewInt64Cache

func NewInt64Cache[K comparable](client *firestore.Client, docIdFunc func(key K) string, fieldName string) *CounterCache[K, int64]

func NewUInt32Cache

func NewUInt32Cache[K comparable](client *firestore.Client, docIdFunc func(key K) string, fieldName string) *CounterCache[K, uint32]

func NewUInt64Cache

func NewUInt64Cache[K comparable](client *firestore.Client, docIdFunc func(key K) string, fieldName string) *CounterCache[K, uint64]

func (*CounterCache[K, V]) Commit

func (c *CounterCache[K, V]) Commit(ctx context.Context)

Commit changes to database Entries with zero delta will be moved to dirty map and deleted during next commit operation if they will stay zero

func (*CounterCache[K, V]) Update

func (c *CounterCache[K, V]) Update(key K, delta V) (old V)

Update Updates value in cache or creates entry if not already created /**

Jump to

Keyboard shortcuts

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