2019-10-15 12:35:45 +01:00
|
|
|
// Package cloudflare is a store implementation backed by cloudflare workers kv
|
|
|
|
// Note that the cloudflare workers KV API is eventually consistent.
|
|
|
|
package cloudflare
|
|
|
|
|
|
|
|
import (
|
2019-10-23 17:26:34 +01:00
|
|
|
"bytes"
|
2019-10-15 12:35:45 +01:00
|
|
|
"context"
|
2019-10-23 17:26:34 +01:00
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
2019-10-15 12:35:45 +01:00
|
|
|
"log"
|
2019-10-23 17:26:34 +01:00
|
|
|
"math"
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
2019-10-23 23:10:44 +01:00
|
|
|
"os"
|
2019-10-23 17:26:34 +01:00
|
|
|
"strconv"
|
2019-10-15 12:35:45 +01:00
|
|
|
"time"
|
|
|
|
|
2020-01-30 14:39:00 +03:00
|
|
|
"github.com/micro/go-micro/v2/store"
|
2019-10-23 17:26:34 +01:00
|
|
|
"github.com/pkg/errors"
|
2020-03-02 18:14:25 +00:00
|
|
|
|
2020-03-03 13:35:49 +00:00
|
|
|
"github.com/patrickmn/go-cache"
|
2019-10-15 12:35:45 +01:00
|
|
|
)
|
|
|
|
|
2019-10-23 22:54:55 +01:00
|
|
|
const (
|
|
|
|
apiBaseURL = "https://api.cloudflare.com/client/v4/"
|
|
|
|
)
|
2019-10-15 12:35:45 +01:00
|
|
|
|
|
|
|
type workersKV struct {
|
2019-12-16 14:38:51 +00:00
|
|
|
options store.Options
|
2019-10-23 22:51:08 +01:00
|
|
|
// cf account id
|
|
|
|
account string
|
|
|
|
// cf api token
|
|
|
|
token string
|
|
|
|
// cf kv namespace
|
|
|
|
namespace string
|
|
|
|
// http client to use
|
2019-10-23 17:26:34 +01:00
|
|
|
httpClient *http.Client
|
2020-03-02 18:14:25 +00:00
|
|
|
// cache
|
2020-03-03 13:35:49 +00:00
|
|
|
cache *cache.Cache
|
2019-10-15 12:35:45 +01:00
|
|
|
}
|
|
|
|
|
2019-10-23 22:57:11 +01:00
|
|
|
// apiResponse is a cloudflare v4 api response
|
|
|
|
type apiResponse struct {
|
|
|
|
Result []struct {
|
|
|
|
ID string `json:"id"`
|
|
|
|
Type string `json:"type"`
|
|
|
|
Name string `json:"name"`
|
2020-03-03 18:15:50 +00:00
|
|
|
Expiration int64 `json:"expiration"`
|
2019-10-23 22:57:11 +01:00
|
|
|
Content string `json:"content"`
|
|
|
|
Proxiable bool `json:"proxiable"`
|
|
|
|
Proxied bool `json:"proxied"`
|
2020-03-03 18:15:50 +00:00
|
|
|
TTL int64 `json:"ttl"`
|
|
|
|
Priority int64 `json:"priority"`
|
2019-10-23 22:57:11 +01:00
|
|
|
Locked bool `json:"locked"`
|
|
|
|
ZoneID string `json:"zone_id"`
|
|
|
|
ZoneName string `json:"zone_name"`
|
|
|
|
ModifiedOn time.Time `json:"modified_on"`
|
|
|
|
CreatedOn time.Time `json:"created_on"`
|
|
|
|
} `json:"result"`
|
|
|
|
Success bool `json:"success"`
|
|
|
|
Errors []apiMessage `json:"errors"`
|
|
|
|
// not sure Messages is ever populated?
|
|
|
|
Messages []apiMessage `json:"messages"`
|
|
|
|
ResultInfo struct {
|
|
|
|
Page int `json:"page"`
|
|
|
|
PerPage int `json:"per_page"`
|
|
|
|
Count int `json:"count"`
|
|
|
|
TotalCount int `json:"total_count"`
|
|
|
|
} `json:"result_info"`
|
|
|
|
}
|
|
|
|
|
|
|
|
// apiMessage is a Cloudflare v4 API Error
|
|
|
|
type apiMessage struct {
|
|
|
|
Code int `json:"code"`
|
|
|
|
Message string `json:"message"`
|
|
|
|
}
|
|
|
|
|
2019-10-23 23:10:44 +01:00
|
|
|
// getOptions returns account id, token and namespace
|
|
|
|
func getOptions() (string, string, string) {
|
|
|
|
accountID := os.Getenv("CF_ACCOUNT_ID")
|
|
|
|
apiToken := os.Getenv("CF_API_TOKEN")
|
|
|
|
namespace := os.Getenv("KV_NAMESPACE_ID")
|
|
|
|
|
|
|
|
return accountID, apiToken, namespace
|
|
|
|
}
|
|
|
|
|
|
|
|
func validateOptions(account, token, namespace string) {
|
|
|
|
if len(account) == 0 {
|
|
|
|
log.Fatal("Store: CF_ACCOUNT_ID is blank")
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(token) == 0 {
|
|
|
|
log.Fatal("Store: CF_API_TOKEN is blank")
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(namespace) == 0 {
|
|
|
|
log.Fatal("Store: KV_NAMESPACE_ID is blank")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-08 12:11:31 +00:00
|
|
|
func (w *workersKV) Init(opts ...store.Option) error {
|
|
|
|
for _, o := range opts {
|
|
|
|
o(&w.options)
|
|
|
|
}
|
|
|
|
if len(w.options.Namespace) > 0 {
|
|
|
|
w.namespace = w.options.Namespace
|
|
|
|
}
|
2020-03-02 18:14:25 +00:00
|
|
|
ttl := w.options.Context.Value("STORE_CACHE_TTL")
|
|
|
|
if ttl != nil {
|
2020-03-03 13:15:26 +00:00
|
|
|
ttlduration, ok := ttl.(time.Duration)
|
2020-03-02 18:14:25 +00:00
|
|
|
if !ok {
|
|
|
|
log.Fatal("STORE_CACHE_TTL from context must be type int64")
|
|
|
|
}
|
2020-03-03 13:35:49 +00:00
|
|
|
w.cache = cache.New(ttlduration, 3*ttlduration)
|
2020-03-02 18:14:25 +00:00
|
|
|
}
|
2020-01-08 12:11:31 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-01-08 22:23:14 +00:00
|
|
|
func (w *workersKV) list(prefix string) ([]string, error) {
|
2019-10-23 17:26:34 +01:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
|
2019-10-23 22:51:08 +01:00
|
|
|
path := fmt.Sprintf("accounts/%s/storage/kv/namespaces/%s/keys", w.account, w.namespace)
|
2019-10-23 17:26:34 +01:00
|
|
|
|
2020-01-08 22:23:14 +00:00
|
|
|
body := make(map[string]string)
|
|
|
|
|
|
|
|
if len(prefix) > 0 {
|
|
|
|
body["prefix"] = prefix
|
|
|
|
}
|
|
|
|
|
|
|
|
response, _, _, err := w.request(ctx, http.MethodGet, path, body, make(http.Header))
|
2019-10-15 12:35:45 +01:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2019-10-23 22:51:08 +01:00
|
|
|
|
2019-10-23 21:54:37 +01:00
|
|
|
a := &apiResponse{}
|
2019-10-23 17:26:34 +01:00
|
|
|
if err := json.Unmarshal(response, a); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2019-10-23 22:51:08 +01:00
|
|
|
|
2019-10-23 17:26:34 +01:00
|
|
|
if !a.Success {
|
|
|
|
messages := ""
|
|
|
|
for _, m := range a.Errors {
|
|
|
|
messages += strconv.Itoa(m.Code) + " " + m.Message + "\n"
|
|
|
|
}
|
|
|
|
return nil, errors.New(messages)
|
|
|
|
}
|
|
|
|
|
2019-11-04 10:33:53 +00:00
|
|
|
keys := make([]string, 0, len(a.Result))
|
2019-10-23 22:51:08 +01:00
|
|
|
|
2019-10-23 17:26:34 +01:00
|
|
|
for _, r := range a.Result {
|
2019-10-15 12:35:45 +01:00
|
|
|
keys = append(keys, r.Name)
|
|
|
|
}
|
2019-10-23 22:51:08 +01:00
|
|
|
|
2020-01-08 22:23:14 +00:00
|
|
|
return keys, nil
|
2019-10-15 12:35:45 +01:00
|
|
|
}
|
|
|
|
|
2020-01-08 22:23:14 +00:00
|
|
|
// In the cloudflare workers KV implemention, List() doesn't guarantee
|
|
|
|
// anything as the workers API is eventually consistent.
|
|
|
|
func (w *workersKV) List() ([]*store.Record, error) {
|
|
|
|
keys, err := w.list("")
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
var gerr error
|
|
|
|
var records []*store.Record
|
|
|
|
|
|
|
|
for _, key := range keys {
|
|
|
|
r, err := w.Read(key)
|
|
|
|
if err != nil {
|
|
|
|
gerr = err
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
records = append(records, r...)
|
|
|
|
}
|
|
|
|
|
|
|
|
return records, gerr
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w *workersKV) Read(key string, opts ...store.ReadOption) ([]*store.Record, error) {
|
2019-10-15 12:35:45 +01:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
|
2020-01-08 22:23:14 +00:00
|
|
|
var options store.ReadOptions
|
|
|
|
for _, o := range opts {
|
|
|
|
o(&options)
|
|
|
|
}
|
|
|
|
|
|
|
|
keys := []string{key}
|
|
|
|
|
|
|
|
if options.Prefix {
|
|
|
|
k, err := w.list(key)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
keys = k
|
|
|
|
}
|
|
|
|
|
2019-12-03 22:59:44 +03:00
|
|
|
//nolint:prealloc
|
2019-10-15 12:35:45 +01:00
|
|
|
var records []*store.Record
|
2019-10-23 22:51:08 +01:00
|
|
|
|
2019-10-15 12:35:45 +01:00
|
|
|
for _, k := range keys {
|
2020-03-02 18:14:25 +00:00
|
|
|
if w.cache != nil {
|
|
|
|
if resp, hit := w.cache.Get(k); hit {
|
|
|
|
if record, ok := resp.(*store.Record); ok {
|
|
|
|
records = append(records, record)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-10-23 22:51:08 +01:00
|
|
|
path := fmt.Sprintf("accounts/%s/storage/kv/namespaces/%s/values/%s", w.account, w.namespace, url.PathEscape(k))
|
2019-10-23 17:26:34 +01:00
|
|
|
response, headers, status, err := w.request(ctx, http.MethodGet, path, nil, make(http.Header))
|
2019-10-15 12:35:45 +01:00
|
|
|
if err != nil {
|
|
|
|
return records, err
|
|
|
|
}
|
2019-10-23 17:26:34 +01:00
|
|
|
if status < 200 || status >= 300 {
|
|
|
|
return records, errors.New("Received unexpected Status " + strconv.Itoa(status) + string(response))
|
|
|
|
}
|
|
|
|
record := &store.Record{
|
2019-10-15 12:35:45 +01:00
|
|
|
Key: k,
|
2019-10-23 17:26:34 +01:00
|
|
|
Value: response,
|
|
|
|
}
|
|
|
|
if expiry := headers.Get("Expiration"); len(expiry) != 0 {
|
|
|
|
expiryUnix, err := strconv.ParseInt(expiry, 10, 64)
|
|
|
|
if err != nil {
|
|
|
|
return records, err
|
|
|
|
}
|
|
|
|
record.Expiry = time.Until(time.Unix(expiryUnix, 0))
|
|
|
|
}
|
2020-03-03 13:54:56 +00:00
|
|
|
if w.cache != nil {
|
|
|
|
w.cache.Set(record.Key, record, cache.DefaultExpiration)
|
|
|
|
}
|
2019-10-23 17:26:34 +01:00
|
|
|
records = append(records, record)
|
2019-10-15 12:35:45 +01:00
|
|
|
}
|
2019-10-23 22:51:08 +01:00
|
|
|
|
2019-10-15 12:35:45 +01:00
|
|
|
return records, nil
|
|
|
|
}
|
|
|
|
|
2020-01-08 22:23:14 +00:00
|
|
|
func (w *workersKV) Write(r *store.Record) error {
|
2020-03-02 18:14:25 +00:00
|
|
|
// Set it in local cache, with the global TTL from options
|
|
|
|
if w.cache != nil {
|
2020-03-03 13:35:49 +00:00
|
|
|
w.cache.Set(r.Key, r, cache.DefaultExpiration)
|
2020-03-02 18:14:25 +00:00
|
|
|
}
|
2019-10-15 12:35:45 +01:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
|
2020-01-08 22:23:14 +00:00
|
|
|
path := fmt.Sprintf("accounts/%s/storage/kv/namespaces/%s/values/%s", w.account, w.namespace, url.PathEscape(r.Key))
|
|
|
|
if r.Expiry != 0 {
|
|
|
|
// Minimum cloudflare TTL is 60 Seconds
|
|
|
|
exp := int(math.Max(60, math.Round(r.Expiry.Seconds())))
|
|
|
|
path = path + "?expiration_ttl=" + strconv.Itoa(exp)
|
|
|
|
}
|
2019-10-23 22:51:08 +01:00
|
|
|
|
2020-01-08 22:23:14 +00:00
|
|
|
headers := make(http.Header)
|
2019-10-23 22:51:08 +01:00
|
|
|
|
2020-01-08 22:23:14 +00:00
|
|
|
resp, _, _, err := w.request(ctx, http.MethodPut, path, r.Value, headers)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-10-23 22:51:08 +01:00
|
|
|
|
2020-01-08 22:23:14 +00:00
|
|
|
a := &apiResponse{}
|
|
|
|
if err := json.Unmarshal(resp, a); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-10-23 22:51:08 +01:00
|
|
|
|
2020-01-08 22:23:14 +00:00
|
|
|
if !a.Success {
|
|
|
|
messages := ""
|
|
|
|
for _, m := range a.Errors {
|
|
|
|
messages += strconv.Itoa(m.Code) + " " + m.Message + "\n"
|
2019-10-23 17:26:34 +01:00
|
|
|
}
|
2020-01-08 22:23:14 +00:00
|
|
|
return errors.New(messages)
|
2019-10-15 12:35:45 +01:00
|
|
|
}
|
2019-10-23 22:51:08 +01:00
|
|
|
|
2019-10-15 12:35:45 +01:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-01-08 22:23:14 +00:00
|
|
|
func (w *workersKV) Delete(key string) error {
|
2020-03-03 13:15:26 +00:00
|
|
|
if w.cache != nil {
|
2020-03-03 13:35:49 +00:00
|
|
|
w.cache.Delete(key)
|
2020-03-03 13:15:26 +00:00
|
|
|
}
|
2019-10-15 12:35:45 +01:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
|
2020-01-08 22:23:14 +00:00
|
|
|
path := fmt.Sprintf("accounts/%s/storage/kv/namespaces/%s/values/%s", w.account, w.namespace, url.PathEscape(key))
|
|
|
|
resp, _, _, err := w.request(ctx, http.MethodDelete, path, nil, make(http.Header))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-10-23 17:26:34 +01:00
|
|
|
|
2020-01-08 22:23:14 +00:00
|
|
|
a := &apiResponse{}
|
|
|
|
if err := json.Unmarshal(resp, a); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-10-23 22:51:08 +01:00
|
|
|
|
2020-01-08 22:23:14 +00:00
|
|
|
if !a.Success {
|
|
|
|
messages := ""
|
|
|
|
for _, m := range a.Errors {
|
|
|
|
messages += strconv.Itoa(m.Code) + " " + m.Message + "\n"
|
2019-10-23 17:26:34 +01:00
|
|
|
}
|
2020-01-08 22:23:14 +00:00
|
|
|
return errors.New(messages)
|
2019-10-15 12:35:45 +01:00
|
|
|
}
|
2019-10-23 22:51:08 +01:00
|
|
|
|
2019-10-15 12:35:45 +01:00
|
|
|
return nil
|
|
|
|
}
|
2019-10-23 17:26:34 +01:00
|
|
|
|
|
|
|
func (w *workersKV) request(ctx context.Context, method, path string, body interface{}, headers http.Header) ([]byte, http.Header, int, error) {
|
|
|
|
var jsonBody []byte
|
|
|
|
var err error
|
|
|
|
|
|
|
|
if body != nil {
|
|
|
|
if paramBytes, ok := body.([]byte); ok {
|
|
|
|
jsonBody = paramBytes
|
|
|
|
} else {
|
|
|
|
jsonBody, err = json.Marshal(body)
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, 0, errors.Wrap(err, "error marshalling params to JSON")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
jsonBody = nil
|
|
|
|
}
|
2019-10-23 22:51:08 +01:00
|
|
|
|
2019-10-23 17:26:34 +01:00
|
|
|
var reqBody io.Reader
|
2019-10-23 22:51:08 +01:00
|
|
|
|
2019-10-23 17:26:34 +01:00
|
|
|
if jsonBody != nil {
|
|
|
|
reqBody = bytes.NewReader(jsonBody)
|
|
|
|
}
|
2019-10-23 22:51:08 +01:00
|
|
|
|
2019-10-23 17:26:34 +01:00
|
|
|
req, err := http.NewRequestWithContext(ctx, method, apiBaseURL+path, reqBody)
|
2019-11-09 07:18:51 -08:00
|
|
|
if err != nil {
|
|
|
|
return nil, nil, 0, errors.Wrap(err, "error creating new request")
|
|
|
|
}
|
|
|
|
|
2019-10-23 17:26:34 +01:00
|
|
|
for key, value := range headers {
|
|
|
|
req.Header[key] = value
|
|
|
|
}
|
2019-10-23 22:51:08 +01:00
|
|
|
|
|
|
|
// set token if it exists
|
|
|
|
if len(w.token) > 0 {
|
|
|
|
req.Header.Set("Authorization", "Bearer "+w.token)
|
2019-10-23 17:26:34 +01:00
|
|
|
}
|
2019-10-23 22:51:08 +01:00
|
|
|
|
|
|
|
// set the user agent to micro
|
2019-10-23 17:26:34 +01:00
|
|
|
req.Header.Set("User-Agent", "micro/1.0 (https://micro.mu)")
|
|
|
|
|
|
|
|
// Official cloudflare client does exponential backoff here
|
2019-10-23 22:51:08 +01:00
|
|
|
// TODO: retry and use util/backoff
|
2019-10-23 17:26:34 +01:00
|
|
|
resp, err := w.httpClient.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
return nil, nil, 0, err
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
2019-10-23 22:51:08 +01:00
|
|
|
|
2019-10-23 17:26:34 +01:00
|
|
|
respBody, err := ioutil.ReadAll(resp.Body)
|
|
|
|
if err != nil {
|
|
|
|
return respBody, resp.Header, resp.StatusCode, err
|
|
|
|
}
|
2019-10-23 22:51:08 +01:00
|
|
|
|
2019-10-23 17:26:34 +01:00
|
|
|
return respBody, resp.Header, resp.StatusCode, nil
|
|
|
|
}
|
|
|
|
|
2020-01-10 19:13:55 +00:00
|
|
|
func (w *workersKV) String() string {
|
|
|
|
return "cloudflare"
|
|
|
|
}
|
|
|
|
|
2020-03-02 18:14:25 +00:00
|
|
|
// NewStore returns a cloudflare Store implementation.
|
2019-10-23 23:10:44 +01:00
|
|
|
// Account ID, Token and Namespace must either be passed as options or
|
|
|
|
// environment variables. If set as env vars we expect the following;
|
|
|
|
// CF_API_TOKEN to a cloudflare API token scoped to Workers KV.
|
|
|
|
// CF_ACCOUNT_ID to contain a string with your cloudflare account ID.
|
2019-10-23 22:54:55 +01:00
|
|
|
// KV_NAMESPACE_ID to contain the namespace UUID for your KV storage.
|
2019-12-16 14:38:51 +00:00
|
|
|
func NewStore(opts ...store.Option) store.Store {
|
|
|
|
var options store.Options
|
|
|
|
for _, o := range opts {
|
|
|
|
o(&options)
|
|
|
|
}
|
2019-10-23 22:54:55 +01:00
|
|
|
|
2019-12-16 14:38:51 +00:00
|
|
|
// get options from environment
|
2019-10-23 23:10:44 +01:00
|
|
|
account, token, namespace := getOptions()
|
2019-10-23 22:54:55 +01:00
|
|
|
|
2019-12-16 14:38:51 +00:00
|
|
|
if len(account) == 0 {
|
|
|
|
account = getAccount(options.Context)
|
2019-10-23 22:54:55 +01:00
|
|
|
}
|
|
|
|
|
2019-12-16 14:38:51 +00:00
|
|
|
if len(token) == 0 {
|
|
|
|
token = getToken(options.Context)
|
2019-10-23 22:54:55 +01:00
|
|
|
}
|
|
|
|
|
2019-12-16 14:38:51 +00:00
|
|
|
if len(namespace) == 0 {
|
2020-01-08 12:11:31 +00:00
|
|
|
namespace = options.Namespace
|
2019-10-23 22:54:55 +01:00
|
|
|
}
|
|
|
|
|
2019-10-23 23:10:44 +01:00
|
|
|
// validate options are not blank or log.Fatal
|
|
|
|
validateOptions(account, token, namespace)
|
|
|
|
|
2019-10-23 22:54:55 +01:00
|
|
|
return &workersKV{
|
|
|
|
account: account,
|
|
|
|
namespace: namespace,
|
|
|
|
token: token,
|
2019-12-16 14:38:51 +00:00
|
|
|
options: options,
|
2019-10-23 22:54:55 +01:00
|
|
|
httpClient: &http.Client{},
|
|
|
|
}
|
|
|
|
}
|