github.com/voedger/voedger@v0.0.0-20240520144910-273e84102129/pkg/vvm/db_cert_cache/impl.go (about)

     1  /*
     2   * Copyright (c) 2021-present Sigma-Soft, Ltd.
     3   * Aleksei Ponomarev
     4   */
     5  
     6  package dbcertcache
     7  
     8  import (
     9  	"bytes"
    10  	"context"
    11  	"encoding/binary"
    12  	"fmt"
    13  	"reflect"
    14  
    15  	"golang.org/x/crypto/acme/autocert"
    16  )
    17  
    18  // Get return certificate for the specified key(domain).
    19  // If there's no such key, Get returns ErrCacheMiss.
    20  func (ac *autoCertDbCache) Get(ctx context.Context, key string) (data []byte, err error) {
    21  	domainKey, err := createKey(CertPrefixInRouterStorage, key)
    22  	if err != nil {
    23  		return nil, err
    24  	}
    25  	ok, err := (*(ac.appStorage)).Get(domainKey.Bytes(), nil, &data)
    26  	if err != nil {
    27  		return nil, err
    28  	}
    29  	if !ok || len(data) == 0 {
    30  		return nil, autocert.ErrCacheMiss
    31  	}
    32  	return data, err
    33  }
    34  
    35  // Put stores the data in the cache under the specified key.
    36  func (ac *autoCertDbCache) Put(ctx context.Context, key string, data []byte) (err error) {
    37  	domainKey, err := createKey(CertPrefixInRouterStorage, key)
    38  	if err != nil {
    39  		return err
    40  	}
    41  	return (*(ac.appStorage)).Put(domainKey.Bytes(), nil, data)
    42  }
    43  
    44  // Delete IAppStorage does not have Delete method, therefore set value to nil and in Get method check value for length
    45  func (ac *autoCertDbCache) Delete(ctx context.Context, key string) (err error) {
    46  	domainKey, err := createKey(CertPrefixInRouterStorage, key)
    47  	if err != nil {
    48  		return err
    49  	}
    50  	return (*(ac.appStorage)).Put(domainKey.Bytes(), nil, nil)
    51  }
    52  
    53  func createKey(columns ...interface{}) (buf *bytes.Buffer, err error) {
    54  	buf = new(bytes.Buffer)
    55  	for _, col := range columns {
    56  		switch v := col.(type) {
    57  		case uint16:
    58  			if err = binary.Write(buf, binary.BigEndian, v); err != nil {
    59  				// error impossible
    60  				// notest
    61  				return buf, nil
    62  			}
    63  		case string:
    64  			if err = binary.Write(buf, binary.LittleEndian, []byte(v)); err != nil {
    65  				// error impossible
    66  				// notest
    67  				return buf, err
    68  			}
    69  		default:
    70  			return nil, fmt.Errorf("unsupported data type %s: %w", reflect.ValueOf(col).Type(), ErrPKeyCreateError)
    71  		}
    72  	}
    73  	return buf, nil
    74  }