|
| 1 | +// Copyright 2020 Dave Marquard. All rights reserved. |
| 2 | +// Use of this source code is governed by the Apache 2.0 |
| 3 | +// license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +package storage // import "miniflux.app/storage" |
| 6 | + |
| 7 | +import ( |
| 8 | + "context" |
| 9 | + "database/sql" |
| 10 | + |
| 11 | + "golang.org/x/crypto/acme/autocert" |
| 12 | +) |
| 13 | + |
| 14 | +// Making sure that we're adhering to the autocert.Cache interface. |
| 15 | +var _ autocert.Cache = (*Cache)(nil) |
| 16 | + |
| 17 | +// Cache provides a SQL backend to the autocert cache. |
| 18 | +type Cache struct { |
| 19 | + storage *Storage |
| 20 | +} |
| 21 | + |
| 22 | +// NewCache creates an cache instance that can be used with autocert.Cache. |
| 23 | +// It returns any errors that could happen while connecting to SQL. |
| 24 | +func NewCache(storage *Storage) *Cache { |
| 25 | + return &Cache{ |
| 26 | + storage: storage, |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +// Get returns a certificate data for the specified key. |
| 31 | +// If there's no such key, Get returns ErrCacheMiss. |
| 32 | +func (c *Cache) Get(ctx context.Context, key string) ([]byte, error) { |
| 33 | + query := `SELECT data::bytea FROM acme_cache WHERE key = $1` |
| 34 | + var data []byte |
| 35 | + err := c.storage.db.QueryRowContext(ctx, query, key).Scan(&data) |
| 36 | + if err == sql.ErrNoRows { |
| 37 | + return nil, autocert.ErrCacheMiss |
| 38 | + } |
| 39 | + |
| 40 | + return data, err |
| 41 | +} |
| 42 | + |
| 43 | +// Put stores the data in the cache under the specified key. |
| 44 | +func (c *Cache) Put(ctx context.Context, key string, data []byte) error { |
| 45 | + query := `INSERT INTO acme_cache (key, data, updated_at) VALUES($1, $2::bytea, now()) |
| 46 | + ON CONFLICT (key) DO UPDATE SET data = $2::bytea, updated_at = now()` |
| 47 | + _, err := c.storage.db.ExecContext(ctx, query, key, data) |
| 48 | + if err != nil { |
| 49 | + return err |
| 50 | + } |
| 51 | + return nil |
| 52 | +} |
| 53 | + |
| 54 | +// Delete removes a certificate data from the cache under the specified key. |
| 55 | +// If there's no such key in the cache, Delete returns nil. |
| 56 | +func (c *Cache) Delete(ctx context.Context, key string) error { |
| 57 | + query := `DELETE FROM acme_cache WHERE key = $1` |
| 58 | + _, err := c.storage.db.ExecContext(ctx, query, key) |
| 59 | + if err != nil { |
| 60 | + return err |
| 61 | + } |
| 62 | + return nil |
| 63 | +} |
0 commit comments