Files
notarius/internal/framework/pipeline/producer_cache.go

68 lines
2.4 KiB
Go

package pipeline
import (
"context"
"fmt"
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
)
func observeProducerCache[T any](ctx context.Context, cache *contracts.ProducerCache[T], observation contracts.CacheObservation) error {
if err := ctx.Err(); err != nil {
return err
}
if cache != nil && cache.Observe != nil {
if err := cache.Observe(ctx, observation); err != nil {
return err
}
}
return ctx.Err()
}
func lookupProducerCache[T any](ctx context.Context, cache *contracts.ProducerCache[T], mode contracts.CacheMode, hash string) (*T, error) {
if mode == contracts.CacheRefresh {
return nil, observeProducerCache(ctx, cache, contracts.CacheObservation{Decision: "refresh", MessageContentHash: hash})
}
content, err := cache.Store.Lookup(ctx, mode, hash)
if canceled := ctx.Err(); canceled != nil {
return nil, canceled
}
if err != nil {
return nil, observeProducerCache(ctx, cache, contracts.CacheObservation{Decision: "lookup_failed", MessageContentHash: hash, Err: err})
}
if content == nil {
return nil, observeProducerCache(ctx, cache, contracts.CacheObservation{Decision: "miss", MessageContentHash: hash})
}
value, err := cache.Decode(content)
if canceled := ctx.Err(); canceled != nil {
return nil, canceled
}
if err != nil {
return nil, observeProducerCache(ctx, cache, contracts.CacheObservation{Decision: "unusable", MessageContentHash: hash, Err: err, Artifact: content})
}
if err := observeProducerCache(ctx, cache, contracts.CacheObservation{Decision: "hit", MessageContentHash: hash, Artifact: content}); err != nil {
return nil, err
}
return &value, nil
}
func storeProducerCache[T any](ctx context.Context, cache *contracts.ProducerCache[T], mode contracts.CacheMode, hash string, value T) error {
if err := ctx.Err(); err != nil {
return err
}
content, err := cache.Encode(value)
if err != nil {
// Artifact encoding is an ordinary application boundary, not a cache I/O
// failure. Do not hide an unusable producer value as a cache warning.
return fmt.Errorf("encode accepted artifact: %w", err)
}
if err := ctx.Err(); err != nil {
return err
}
observation := contracts.CacheObservation{Decision: "stored", MessageContentHash: hash, Artifact: content}
if err := cache.Store.Store(ctx, mode, hash, content); err != nil {
observation.Decision, observation.Err = "store_failed", err
}
return observeProducerCache(ctx, cache, observation)
}