Open platform to collect and prioritize feedback
refactoring: move autocert to blob storage (#690)
Guilherme Oenning27f031d5e306
diff --git a/Gopkg.lock b/Gopkg.lockindex e7a6a311c..c18a2a8ae 100644--- a/Gopkg.lock+++ b/Gopkg.lock@@ -68,14 +68,6 @@pruneopts = "UT"revision = "553181ed4055278e356ce21812adb34ae487f88e"-[[projects]]- branch = "master"- digest = "1:409b1dfc403db55b7d617924f753e2617101c7d4ccc8f918f84cb7bffa897db3"- name = "github.com/goenning/sqlcertcache"- packages = ["."]- pruneopts = "UT"- revision = "99f858c5bf37a984858e406db3053037d278abdd"-[[projects]]branch = "master"digest = "1:7a6377256f670508711c56c25556d639e673c0fa0f519c5a758fdcbfc8af9ac8"@@ -235,7 +227,6 @@"github.com/aws/aws-sdk-go/service/s3","github.com/dgrijalva/jwt-go","github.com/goenning/letteravatar",- "github.com/goenning/sqlcertcache","github.com/gosimple/slug","github.com/joeshaw/envdecode","github.com/julienschmidt/httprouter",diff --git a/Gopkg.toml b/Gopkg.tomlindex 8af3e0e0d..dc30484a9 100644--- a/Gopkg.toml+++ b/Gopkg.toml@@ -41,10 +41,6 @@ ignored = ["github.com/magefile/mage/mg","github.com/magefile/mage/sh"]version = "v1.16.3"name = "github.com/aws/aws-sdk-go"-[[constraint]]- branch = "master"- name = "github.com/goenning/sqlcertcache"-[[constraint]]branch = "master"name = "github.com/joeshaw/envdecode"diff --git a/app/handlers/images.go b/app/handlers/images.goindex cae68f2c2..f05315935 100644--- a/app/handlers/images.go+++ b/app/handlers/images.go@@ -9,12 +9,10 @@ import ("net/http""strings"- "github.com/getfider/fider/app/pkg/env"-"github.com/getfider/fider/app/pkg/crypto"+ "github.com/getfider/fider/app/pkg/env""github.com/getfider/fider/app/pkg/img""github.com/getfider/fider/app/pkg/log"-"github.com/getfider/fider/app/pkg/web""github.com/goenning/letteravatar")@@ -41,7 +39,7 @@ func Avatar() web.HandlerFunc {if resp.StatusCode == http.StatusOK {bytes, err := ioutil.ReadAll(resp.Body)if err == nil {- return c.Blob(http.StatusOK, http.DetectContentType(bytes), bytes)+ return c.Image(http.DetectContentType(bytes), bytes)}}}@@ -62,7 +60,7 @@ func Avatar() web.HandlerFunc {return c.Failure(err)}- return c.Blob(http.StatusOK, "image/png", buf.Bytes())+ return c.Image("image/png", buf.Bytes())}}@@ -108,7 +106,7 @@ func Favicon() web.HandlerFunc {}}- return c.Blob(http.StatusOK, contentType, bytes)+ return c.Image(contentType, bytes)}}@@ -132,6 +130,6 @@ func ViewUploadedImage() web.HandlerFunc {return c.Failure(err)}- return c.Blob(http.StatusOK, logo.ContentType, bytes)+ return c.Image(logo.ContentType, bytes)}}diff --git a/app/middlewares/setup.go b/app/middlewares/setup.goindex 2afc63af7..ad7beb5b0 100644--- a/app/middlewares/setup.go+++ b/app/middlewares/setup.go@@ -8,7 +8,7 @@ import ("github.com/getfider/fider/app/pkg/di""github.com/getfider/fider/app/pkg/log""github.com/getfider/fider/app/pkg/web"- "github.com/getfider/fider/app/pkg/web/util"+ webutil "github.com/getfider/fider/app/pkg/web/util""github.com/getfider/fider/app/pkg/worker""github.com/getfider/fider/app/storage/postgres")@@ -67,7 +67,7 @@ func WorkerSetup() worker.MiddlewareFunc {Tags: postgres.NewTagStorage(trx),Notifications: postgres.NewNotificationStorage(trx),Emailer: di.NewEmailer(c.Logger()),- Blobs: di.NewBlobStorage(trx),+ Blobs: di.NewBlobStorage(c.Database()),})//Execute the chain@@ -155,7 +155,7 @@ func WebSetup() web.MiddlewareFunc {Tags: postgres.NewTagStorage(trx),Notifications: postgres.NewNotificationStorage(trx),Emailer: di.NewEmailer(c.Logger()),- Blobs: di.NewBlobStorage(trx),+ Blobs: di.NewBlobStorage(c.Engine().Database()),})//Execute the chaindiff --git a/app/pkg/blob/autocert.go b/app/pkg/blob/autocert.gonew file mode 100644index 000000000..fb94b39dd--- /dev/null+++ b/app/pkg/blob/autocert.go@@ -0,0 +1,57 @@+package blob++import (+ "context"+ "strings"++ "golang.org/x/crypto/acme/autocert"+)++// Making sure that we're adhering to the autocert.Cache interface.+var _ autocert.Cache = (*Cache)(nil)++// Cache provides a Blob backend to the autocert cache.+type Cache struct {+ storage Storage+}++// NewAutoCert returns a new AutoCert cache using Blob Storage+func NewAutoCert(storage Storage) *Cache {+ return &Cache{storage}+}++// Get returns a certificate data for the specified key.+// If there's no such key, Get returns ErrCacheMiss.+func (c *Cache) Get(ctx context.Context, key string) ([]byte, error) {+ b, err := c.storage.Get(c.formatKey(key))+ if err == ErrNotFound {+ return nil, autocert.ErrCacheMiss+ }+ if err != nil {+ return nil, err+ }+ return b.Object, nil+}++// Put stores the data in the cache under the specified key.+func (c *Cache) Put(ctx context.Context, key string, data []byte) error {+ err := c.storage.Put(c.formatKey(key), data, "application/x-pem-file")+ if err != nil {+ return err+ }+ return nil+}++// Delete removes a certificate data from the cache under the specified key.+// If there's no such key in the cache, Delete returns nil.+func (c *Cache) Delete(ctx context.Context, key string) error {+ err := c.storage.Delete(c.formatKey(key))+ if err != nil {+ return err+ }+ return nil+}++func (c *Cache) formatKey(key string) string {+ return "autocert/" + strings.ToLower(key)+}diff --git a/app/pkg/blob/blob_test.go b/app/pkg/blob/blob_test.goindex 1342d52a9..7bf77f030 100644--- a/app/pkg/blob/blob_test.go+++ b/app/pkg/blob/blob_test.go@@ -46,9 +46,7 @@ func setupSQL(t *testing.T) *sql.Storage {db := dbx.New()db.Seed()- trx, err := db.Begin()- Expect(err).IsNil()- return sql.NewStorage(trx)+ return sql.NewStorage(db)}func setupFS(t *testing.T) *fs.Storage {diff --git a/app/pkg/blob/s3/s3.go b/app/pkg/blob/s3/s3.goindex f65a6a641..7f41e49aa 100644--- a/app/pkg/blob/s3/s3.go+++ b/app/pkg/blob/s3/s3.go@@ -103,10 +103,7 @@ func (s *Storage) Delete(key string) error {Bucket: s.bucket,Key: aws.String(s.keyFullPathURL(key)),})- if err != nil {- if isNotFound(err) {- return blob.ErrNotFound- }+ if err != nil && !isNotFound(err) {return errors.Wrap(err, "failed to delete blob '%s' from S3", key)}return nildiff --git a/app/pkg/blob/sql/sql.go b/app/pkg/blob/sql/sql.goindex 9842ce728..525e9e987 100644--- a/app/pkg/blob/sql/sql.go+++ b/app/pkg/blob/sql/sql.go@@ -2,7 +2,6 @@ package sqlimport ("database/sql"- "os""time""github.com/getfider/fider/app"@@ -13,8 +12,6 @@ import ("github.com/getfider/fider/app/pkg/errors")-var perm os.FileMode = 0744-var _ blob.Storage = (*Storage)(nil)type dbBlob struct {@@ -25,14 +22,14 @@ type dbBlob struct {// Storage stores blobs on FileSystemtype Storage struct {- trx *dbx.Trx+ db *dbx.Databasetenant *models.Tenant}// NewStorage creates a new SQL Storage-func NewStorage(trx *dbx.Trx) *Storage {+func NewStorage(db *dbx.Database) *Storage {return &Storage{- trx: trx,+ db: db,}}@@ -48,8 +45,14 @@ func (s *Storage) Get(key string) (*blob.Blob, error) {tenantID.Scan(s.tenant.ID)}+ trx, err := s.db.Begin()+ if err != nil {+ return nil, errors.Wrap(err, "failed to open transaction")+ }+ defer trx.Commit()+b := dbBlob{}- err := s.trx.Get(&b, "SELECT file, content_type, size FROM blobs WHERE key = $1 AND (tenant_id = $2 OR ($2 IS NULL AND tenant_id IS NULL))", key, tenantID)+ err = trx.Get(&b, "SELECT file, content_type, size FROM blobs WHERE key = $1 AND (tenant_id = $2 OR ($2 IS NULL AND tenant_id IS NULL))", key, tenantID)if err != nil {if err == app.ErrNotFound {return nil, blob.ErrNotFound@@ -72,7 +75,13 @@ func (s *Storage) Delete(key string) error {tenantID.Scan(s.tenant.ID)}- _, err := s.trx.Execute("DELETE FROM blobs WHERE key = $1 AND (tenant_id = $2 OR ($2 IS NULL AND tenant_id IS NULL))", key, tenantID)+ trx, err := s.db.Begin()+ if err != nil {+ return errors.Wrap(err, "failed to open transaction")+ }+ defer trx.Commit()++ _, err = trx.Execute("DELETE FROM blobs WHERE key = $1 AND (tenant_id = $2 OR ($2 IS NULL AND tenant_id IS NULL))", key, tenantID)if err != nil {return errors.Wrap(err, "failed to delete blob with key '%s'", key)}@@ -95,8 +104,14 @@ func (s *Storage) Put(key string, content []byte, contentType string) error {tenantID.Scan(s.tenant.ID)}+ trx, err := s.db.Begin()+ if err != nil {+ return errors.Wrap(err, "failed to open transaction")+ }+ defer trx.Commit()+now := time.Now()- _, err := s.trx.Execute(`+ _, err = trx.Execute(`INSERT INTO blobs (tenant_id, key, size, content_type, file, created_at, modified_at)VALUES ($1, $2, $3, $4, $5, $6, $7) ON CONFLICT (tenant_id, key)DO UPDATE SET size = $3, content_type = $4, file = $5, modified_at = $7diff --git a/app/pkg/di/blob.go b/app/pkg/di/blob.goindex 3cf572303..68866c8d5 100644--- a/app/pkg/di/blob.go+++ b/app/pkg/di/blob.go@@ -14,7 +14,7 @@ import ("github.com/getfider/fider/app/pkg/email/smtp""github.com/getfider/fider/app/pkg/env""github.com/getfider/fider/app/pkg/log"- "github.com/getfider/fider/app/pkg/web"+ "github.com/getfider/fider/app/pkg/web/http")// NewEmailer creates a new emailer instance based on current configuration@@ -26,7 +26,7 @@ func NewEmailer(logger log.Logger) email.Sender {if env.Config.Email.Mailgun.APIKey != "" {return mailgun.NewSender(logger,- web.NewHTTPClient(),+ http.NewClient(),env.Config.Email.Mailgun.Domain,env.Config.Email.Mailgun.APIKey,)@@ -42,11 +42,11 @@ func NewEmailer(logger log.Logger) email.Sender {}// NewBlobStorage creates a new blob storage instance based on current configuration-func NewBlobStorage(trx *dbx.Trx) blob.Storage {+func NewBlobStorage(db *dbx.Database) blob.Storage {storageType := strings.ToLower(env.Config.BlobStorage.Type)switch storageType {case "sql":- return sql.NewStorage(trx)+ return sql.NewStorage(db)case "s3":return s3.NewStorage(env.Config.BlobStorage.S3.BucketName)case "fs":diff --git a/app/pkg/email/mailgun/mailgun.go b/app/pkg/email/mailgun/mailgun.goindex 5ec171153..f365c7040 100644--- a/app/pkg/email/mailgun/mailgun.go+++ b/app/pkg/email/mailgun/mailgun.go@@ -3,7 +3,6 @@ package mailgunimport ("encoding/json""fmt"- "net/http""net/url""strings"@@ -11,7 +10,7 @@ import ("github.com/getfider/fider/app/pkg/env""github.com/getfider/fider/app/pkg/errors""github.com/getfider/fider/app/pkg/log"- "github.com/getfider/fider/app/pkg/web"+ "github.com/getfider/fider/app/pkg/web/http")var baseURL = "https://api.mailgun.net/v3/%s/messages"@@ -19,13 +18,13 @@ var baseURL = "https://api.mailgun.net/v3/%s/messages"//Sender is used to send emailstype Sender struct {logger log.Logger- client web.Client+ client http.Clientdomain stringapiKey string}//NewSender creates a new mailgun email sender-func NewSender(logger log.Logger, client web.Client, domain, apiKey string) *Sender {+func NewSender(logger log.Logger, client http.Client, domain, apiKey string) *Sender {return &Sender{logger, client, domain, apiKey}}diff --git a/app/pkg/web/client.go b/app/pkg/web/client.godeleted file mode 100644index 1ffccad78..000000000--- a/app/pkg/web/client.go+++ /dev/null@@ -1,35 +0,0 @@-package web--import (- "net/http"- "time"-- "github.com/getfider/fider/app/pkg/env"-)--func init() {- //Increase transport timeouts when running Tests- if env.IsTest() {- transport := http.DefaultTransport.(*http.Transport)- transport.TLSHandshakeTimeout = 30 * time.Second- }-}--// Client is an interface for HTTP Client-type Client interface {- Do(req *http.Request) (*http.Response, error)-}--// HTTPClient is an implementation of HTTP Client-type HTTPClient struct {-}--// NewHTTPClient creates a new HTTPClient-func NewHTTPClient() *HTTPClient {- return &HTTPClient{}-}--// Do sends the request using http.DefaultClient-func (client *HTTPClient) Do(req *http.Request) (*http.Response, error) {- return http.DefaultClient.Do(req)-}diff --git a/app/pkg/web/context.go b/app/pkg/web/context.goindex 4a0e3fb88..19c6ac6e4 100644--- a/app/pkg/web/context.go+++ b/app/pkg/web/context.go@@ -492,6 +492,14 @@ func (ctx *Context) JSON(code int, i interface{}) error {return ctx.Blob(code, UTF8JSONContentType, b)}+// Image sends an image blob response with status code and content type.+func (ctx *Context) Image(contentType string, b []byte) error {+ if !strings.HasPrefix(contentType, "image/") {+ return ctx.Failure(errors.New("'%s' is not an image", ctx.Request.URL.String()))+ }+ return ctx.Blob(http.StatusOK, contentType, b)+}+// Blob sends a blob response with status code and content type.func (ctx *Context) Blob(code int, contentType string, b []byte) error {ctx.Response.Header().Set("Content-Type", contentType)diff --git a/app/pkg/web/engine.go b/app/pkg/web/engine.goindex c3d0b5644..264ce5789 100644--- a/app/pkg/web/engine.go+++ b/app/pkg/web/engine.go@@ -123,7 +123,7 @@ func (e *Engine) Start(address string) {certManager *CertificateManager)if env.Config.AutoSSL {- certManager, err = NewCertificateManager(certFilePath, keyFilePath, e.db.Connection())+ certManager, err = NewCertificateManager(certFilePath, keyFilePath, e.db)if err != nil {panic(errors.Wrap(err, "failed to initialize CertificateManager"))}diff --git a/app/pkg/web/http/client.go b/app/pkg/web/http/client.gonew file mode 100644index 000000000..9f39af0eb--- /dev/null+++ b/app/pkg/web/http/client.go@@ -0,0 +1,42 @@+package http++import (+ "io"+ "net/http"+ gohttp "net/http"+ "time"++ "github.com/getfider/fider/app/pkg/env"+)++func init() {+ //Increase transport timeouts when running Tests+ if env.IsTest() {+ transport := gohttp.DefaultTransport.(*gohttp.Transport)+ transport.TLSHandshakeTimeout = 30 * time.Second+ }+}++// Client is an interface for HTTP Client+type Client interface {+ Do(req *gohttp.Request) (*gohttp.Response, error)+}++// DefaultClient is the default HTTP Client+type DefaultClient struct {+}++// NewClient creates a new defaultClient+func NewClient() *DefaultClient {+ return &DefaultClient{}+}++// NewRequest creates a new HTTP Request+func NewRequest(method, url string, body io.Reader) (*gohttp.Request, error) {+ return gohttp.NewRequest(method, url, body)+}++// Do sends the request using http.DefaultClient+func (client *DefaultClient) Do(req *http.Request) (*http.Response, error) {+ return http.DefaultClient.Do(req)+}diff --git a/app/pkg/web/ssl.go b/app/pkg/web/ssl.goindex cab26971e..2ed8680a3 100644--- a/app/pkg/web/ssl.go+++ b/app/pkg/web/ssl.go@@ -3,13 +3,14 @@ package webimport ("crypto/tls""crypto/x509"- "database/sql""net/http""strings"+ "github.com/getfider/fider/app/pkg/blob"+ "github.com/getfider/fider/app/pkg/dbx"+ "github.com/getfider/fider/app/pkg/di""github.com/getfider/fider/app/pkg/env""github.com/getfider/fider/app/pkg/errors"- "github.com/goenning/sqlcertcache""golang.org/x/crypto/acme/autocert")@@ -45,16 +46,11 @@ type CertificateManager struct {}//NewCertificateManager creates a new CertificateManager-func NewCertificateManager(certFile, keyFile string, conn *sql.DB) (*CertificateManager, error) {- cache, err := sqlcertcache.New(conn, "autocert_cache")- if err != nil {- return nil, errors.Wrap(err, "failed to initialize new sqlcertcache")- }-+func NewCertificateManager(certFile, keyFile string, db *dbx.Database) (*CertificateManager, error) {manager := &CertificateManager{autossl: autocert.Manager{Prompt: autocert.AcceptTOS,- Cache: cache,+ Cache: blob.NewAutoCert(di.NewBlobStorage(db)),},}diff --git a/app/pkg/web/ssl_test.go b/app/pkg/web/ssl_test.goindex 802ea0076..2b64d34b1 100644--- a/app/pkg/web/ssl_test.go+++ b/app/pkg/web/ssl_test.go@@ -37,7 +37,7 @@ func Test_GetCertificate(t *testing.T) {keyFile := env.Path("/app/pkg/web/testdata/" + testCase.cert + ".key")wildcardCert, _ := tls.LoadX509KeyPair(certFile, keyFile)- manager, err := NewCertificateManager(certFile, keyFile, db.Connection())+ manager, err := NewCertificateManager(certFile, keyFile, db)Expect(err).IsNil()cert, err := manager.GetCertificate(&tls.ClientHelloInfo{ServerName: testCase.serverName,@@ -58,7 +58,7 @@ func Test_UseAutoCert(t *testing.T) {db := dbx.New()defer db.Close()- manager, err := NewCertificateManager("", "", db.Connection())+ manager, err := NewCertificateManager("", "", db)Expect(err).IsNil()invalidServerNames := []string{"ideas.app.com", "feedback.mysite.com"}diff --git a/migrations/201812201644_migrate_autocert_to_blobs.sql b/migrations/201812201644_migrate_autocert_to_blobs.sqlnew file mode 100644index 000000000..7756af632--- /dev/null+++ b/migrations/201812201644_migrate_autocert_to_blobs.sql@@ -0,0 +1,2 @@+CREATE UNIQUE INDEX blobs_unique_global_key ON blobs (key, tenant_id) WHERE tenant_id IS NOT NULL;+CREATE UNIQUE INDEX blobs_unique_tenant_key ON blobs (key) WHERE tenant_id IS NULL;\ No newline at end of filediff --git a/vendor/github.com/goenning/sqlcertcache/LICENSE b/vendor/github.com/goenning/sqlcertcache/LICENSEdeleted file mode 100644index 6ab94553f..000000000--- a/vendor/github.com/goenning/sqlcertcache/LICENSE+++ /dev/null@@ -1,21 +0,0 @@-The MIT License (MIT)--Copyright (c) 2018 Guilherme Oenning <[email protected]>--Permission is hereby granted, free of charge, to any person obtaining a copy-of this software and associated documentation files (the "Software"), to deal-in the Software without restriction, including without limitation the rights-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell-copies of the Software, and to permit persons to whom the Software is-furnished to do so, subject to the following conditions:--The above copyright notice and this permission notice shall be included in all-copies or substantial portions of the Software.--THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE-SOFTWARE.\ No newline at end of filediff --git a/vendor/github.com/goenning/sqlcertcache/README.md b/vendor/github.com/goenning/sqlcertcache/README.mddeleted file mode 100644index bd2280f55..000000000--- a/vendor/github.com/goenning/sqlcertcache/README.md+++ /dev/null@@ -1,45 +0,0 @@-[](https://godoc.org/github.com/goenning/sqlcertcache) [](https://goreportcard.com/report/github.com/goenning/sqlcertcache)--# sqlcertcache--SQL cache for [acme/autocert](https://godoc.org/golang.org/x/crypto/acme/autocert) written in Go.--## Example--```go-conn, err := sql.Open("postgres", "postgres://YOUR_CONNECTION_STRING")-if err != nil {- // Handle error-}--cache, err := sqlcertcache.New(conn, "autocert_cache")-if err != nil {- // Handle error-}--m := autocert.Manager{- Prompt: autocert.AcceptTOS,- HostPolicy: autocert.HostWhitelist("example.org"),- Cache: cache,-}--s := &http.Server{- Addr: ":https",- TLSConfig: &tls.Config{GetCertificate: m.GetCertificate},-}--s.ListenAndServeTLS("", "")-```--## Performance--This is just a reminder that autocert has an internal in-memory cache that is used before quering this long-term cache.-So you don't need to worry about your SQL database being hit many times just to get a certificate. It should only do once per process+key.--## Thanks--Inspired by https://github.com/danilobuerger/autocert-s3-cache--## License--MIT\ No newline at end of filediff --git a/vendor/github.com/goenning/sqlcertcache/docker-compose.yml b/vendor/github.com/goenning/sqlcertcache/docker-compose.ymldeleted file mode 100644index 8b3535d05..000000000--- a/vendor/github.com/goenning/sqlcertcache/docker-compose.yml+++ /dev/null@@ -1,10 +0,0 @@-version: '3'-services:- pgcache_test:- restart: always- image: postgres:9.6.8- ports:- - "6543:5432"- environment:- POSTGRES_USER: pgcache_test- POSTGRES_PASSWORD: pgcache_test_pw\ No newline at end of filediff --git a/vendor/github.com/goenning/sqlcertcache/sqlcertcache.go b/vendor/github.com/goenning/sqlcertcache/sqlcertcache.godeleted file mode 100644index f9caa46a9..000000000--- a/vendor/github.com/goenning/sqlcertcache/sqlcertcache.go+++ /dev/null@@ -1,87 +0,0 @@-// Package sqlcertcache implements an autocert.Cache to store certificate data within a SQL Database-//-// See https://godoc.org/golang.org/x/crypto/acme/autocert-package sqlcertcache--import (- "context"- "database/sql"- "errors"- "fmt"- "strings"-- "golang.org/x/crypto/acme/autocert"-)--// ErrEmptyTableName is returned when given table name is empty-var ErrEmptyTableName = errors.New("tableName must not be empty")--// Making sure that we're adhering to the autocert.Cache interface.-var _ autocert.Cache = (*Cache)(nil)--// Cache provides a SQL backend to the autocert cache.-type Cache struct {- conn *sql.DB- getQuery string- putQuery string- deleteQuery string-}--// New creates an cache instance that can be used with autocert.Cache.-// It returns any errors that could happen while connecting to SQL.-func New(conn *sql.DB, tableName string) (*Cache, error) {- if strings.TrimSpace(tableName) == "" {- return nil, ErrEmptyTableName- }-- _, err := conn.Exec(fmt.Sprintf(`create table if not exists %s (- key varchar(400) not null primary key,- data bytea not null,- created_at timestamptz not null,- updated_at timestamptz null- );`, tableName))- if err != nil {- return nil, err- }-- return &Cache{- conn: conn,- getQuery: fmt.Sprintf(`SELECT data::bytea FROM %s WHERE key = $1`, tableName),- putQuery: fmt.Sprintf(`- INSERT INTO %s (key, data, created_at) VALUES($1, $2::bytea, now())- ON CONFLICT (key) DO UPDATE SET data = $2::bytea- `, tableName),- deleteQuery: fmt.Sprintf(`DELETE FROM %s WHERE key = $1`, tableName),- }, nil-}--// Get returns a certificate data for the specified key.-// If there's no such key, Get returns ErrCacheMiss.-func (c *Cache) Get(ctx context.Context, key string) ([]byte, error) {- var data []byte- err := c.conn.QueryRowContext(ctx, c.getQuery, key).Scan(&data)- if err == sql.ErrNoRows {- return nil, autocert.ErrCacheMiss- }-- return data, err-}--// Put stores the data in the cache under the specified key.-func (c *Cache) Put(ctx context.Context, key string, data []byte) error {- _, err := c.conn.ExecContext(ctx, c.putQuery, key, data)- if err != nil {- return err- }- return nil-}--// Delete removes a certificate data from the cache under the specified key.-// If there's no such key in the cache, Delete returns nil.-func (c *Cache) Delete(ctx context.Context, key string) error {- _, err := c.conn.ExecContext(ctx, c.deleteQuery, key)- if err != nil {- return err- }- return nil-}