github.com/grafana/synthetic-monitoring-agent@v0.64.2/internal/cache/noop.go (about)

     1  package cache
     2  
     3  import (
     4  	"context"
     5  	"time"
     6  
     7  	"github.com/rs/zerolog"
     8  )
     9  
    10  // Noop is a cache implementation that does nothing.
    11  // It always returns ErrCacheMiss for Get operations and silently
    12  // discards all Set/Delete/Flush operations.
    13  //
    14  // This allows client code to use the cache without nil checks,
    15  // simplifying the codebase and making it easier to test.
    16  type Noop struct {
    17  	logger zerolog.Logger
    18  }
    19  
    20  const KindNoop = Kind("noop")
    21  
    22  // Ensure noopCache implements Cache interface at compile time
    23  var _ Cache = (*Noop)(nil)
    24  
    25  // NewNoop creates a new no-op cache that implements the Cache interface
    26  // but performs no actual caching.
    27  //
    28  // This is useful when:
    29  //   - No memcached servers are configured
    30  //   - Cache initialization fails but the agent should continue
    31  //   - Testing code that uses cache without running memcached
    32  //
    33  // The noop cache always returns ErrCacheMiss for Get operations and
    34  // succeeds (but does nothing) for Set, Delete, and Flush operations.
    35  func NewNoop(logger zerolog.Logger) *Noop {
    36  	return &Noop{
    37  		logger: logger.With().Str("component", "cache").Str("type", "noop").Logger(),
    38  	}
    39  }
    40  
    41  // Set discards the value and returns nil (successful no-op).
    42  func (n *Noop) Set(ctx context.Context, key string, value any, expiration time.Duration) error {
    43  	n.logger.Debug().Str("key", key).Msg("noop cache set (discarded)")
    44  	return nil
    45  }
    46  
    47  // Get always returns ErrCacheMiss since nothing is cached.
    48  func (n *Noop) Get(ctx context.Context, key string, dest any) error {
    49  	n.logger.Debug().Str("key", key).Msg("noop cache get (always miss)")
    50  	return ErrCacheMiss
    51  }
    52  
    53  // Delete does nothing and returns nil (successful no-op).
    54  func (n *Noop) Delete(ctx context.Context, key string) error {
    55  	n.logger.Debug().Str("key", key).Msg("noop cache delete (discarded)")
    56  	return nil
    57  }
    58  
    59  // Flush does nothing and returns nil (successful no-op).
    60  func (n *Noop) Flush(ctx context.Context) error {
    61  	n.logger.Debug().Msg("noop cache flush (discarded)")
    62  	return nil
    63  }