github.com/Jeffail/benthos/v3@v3.65.0/public/service/example_cache_plugin_test.go (about)

     1  package service_test
     2  
     3  import (
     4  	"context"
     5  	"time"
     6  
     7  	"github.com/Jeffail/benthos/v3/public/service"
     8  
     9  	// Import all standard Benthos components
    10  	_ "github.com/Jeffail/benthos/v3/public/components/all"
    11  )
    12  
    13  // LossyCache is a terrible cache example and silently drops items when the
    14  // capacity is reached. It also doesn't respect TTLs.
    15  type LossyCache struct {
    16  	capacity int
    17  	mDropped *service.MetricCounter
    18  	items    map[string][]byte
    19  }
    20  
    21  func (l *LossyCache) Get(ctx context.Context, key string) ([]byte, error) {
    22  	if b, ok := l.items[key]; ok {
    23  		return b, nil
    24  	}
    25  	return nil, service.ErrKeyNotFound
    26  }
    27  
    28  func (l *LossyCache) Set(ctx context.Context, key string, value []byte, ttl *time.Duration) error {
    29  	if len(l.items) >= l.capacity {
    30  		// Dropped, whoopsie!
    31  		l.mDropped.Incr(1)
    32  		return nil
    33  	}
    34  	l.items[key] = value
    35  	return nil
    36  }
    37  
    38  func (l *LossyCache) Add(ctx context.Context, key string, value []byte, ttl *time.Duration) error {
    39  	if _, exists := l.items[key]; exists {
    40  		return service.ErrKeyAlreadyExists
    41  	}
    42  	if len(l.items) >= l.capacity {
    43  		// Dropped, whoopsie!
    44  		l.mDropped.Incr(1)
    45  		return nil
    46  	}
    47  	l.items[key] = value
    48  	return nil
    49  }
    50  
    51  func (l *LossyCache) Delete(ctx context.Context, key string) error {
    52  	delete(l.items, key)
    53  	return nil
    54  }
    55  
    56  func (l *LossyCache) Close(ctx context.Context) error {
    57  	return nil
    58  }
    59  
    60  // This example demonstrates how to create a cache plugin, where the
    61  // implementation of the cache (type `LossyCache`) also contains fields that
    62  // should be parsed within the Benthos config.
    63  func Example_cachePlugin() {
    64  	configSpec := service.NewConfigSpec().
    65  		Summary("Creates a terrible cache with a fixed capacity.").
    66  		Field(service.NewIntField("capacity").Default(100))
    67  
    68  	err := service.RegisterCache("lossy", configSpec,
    69  		func(conf *service.ParsedConfig, mgr *service.Resources) (service.Cache, error) {
    70  			capacity, err := conf.FieldInt("capacity")
    71  			if err != nil {
    72  				return nil, err
    73  			}
    74  			return &LossyCache{
    75  				capacity: capacity,
    76  				mDropped: mgr.Metrics().NewCounter("dropped_just_cus"),
    77  				items:    make(map[string][]byte, capacity),
    78  			}, nil
    79  		})
    80  	if err != nil {
    81  		panic(err)
    82  	}
    83  
    84  	// And then execute Benthos with:
    85  	// service.RunCLI(context.Background())
    86  }