golang.org/x/build@v0.0.0-20240506185731-218518f32b70/autocertcache/autocertcache.go (about)

     1  // Copyright 2017 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package autocertcache contains autocert.Cache implementations
     6  // for golang.org/x/crypto/autocert.
     7  package autocertcache
     8  
     9  import (
    10  	"context"
    11  	"io"
    12  
    13  	"cloud.google.com/go/storage"
    14  	"golang.org/x/crypto/acme/autocert"
    15  )
    16  
    17  // NewGoogleCloudStorageCache returns an autocert.Cache storing its cache entries
    18  // in the named Google Cloud Storage bucket. The implementation assumes that it
    19  // owns the entire bucket namespace.
    20  func NewGoogleCloudStorageCache(sc *storage.Client, bucket string) autocert.Cache {
    21  	return &gcsAutocertCache{sc, bucket}
    22  }
    23  
    24  // gcsAutocertCache implements the
    25  // golang.org/x/crypto/acme/autocert.Cache interface using a Google
    26  // Cloud Storage bucket. It assumes that autocert gets to use the
    27  // whole keyspace of the bucket. That is, don't reuse this bucket for
    28  // other purposes.
    29  type gcsAutocertCache struct {
    30  	gcs    *storage.Client
    31  	bucket string
    32  }
    33  
    34  func (c *gcsAutocertCache) Get(ctx context.Context, key string) ([]byte, error) {
    35  	rd, err := c.gcs.Bucket(c.bucket).Object(key).NewReader(ctx)
    36  	if err == storage.ErrObjectNotExist {
    37  		return nil, autocert.ErrCacheMiss
    38  	}
    39  	if err != nil {
    40  		return nil, err
    41  	}
    42  	defer rd.Close()
    43  	return io.ReadAll(rd)
    44  }
    45  
    46  func (c *gcsAutocertCache) Put(ctx context.Context, key string, data []byte) error {
    47  	wr := c.gcs.Bucket(c.bucket).Object(key).NewWriter(ctx)
    48  	if _, err := wr.Write(data); err != nil {
    49  		return err
    50  	}
    51  	return wr.Close()
    52  }
    53  
    54  func (c *gcsAutocertCache) Delete(ctx context.Context, key string) error {
    55  	err := c.gcs.Bucket(c.bucket).Object(key).Delete(ctx)
    56  	if err == storage.ErrObjectNotExist {
    57  		return nil
    58  	}
    59  	return err
    60  }