-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstorage.go
More file actions
177 lines (159 loc) · 4.88 KB
/
Copy pathstorage.go
File metadata and controls
177 lines (159 loc) · 4.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
package main
import (
"database/sql"
"encoding/json"
"fmt"
_ "github.com/lib/pq"
_ "github.com/mattn/go-sqlite3"
"net/http"
"regexp"
"strings"
"time"
)
// regexp POSTGRES_PLACEHOLDERS matches strings '$1', '$2', '$3', ...
var POSTGRES_PLACEHOLDERS *regexp.Regexp = regexp.MustCompile("\\$\\d+")
// Storage is the interface to the SQL database.
type Storage struct {
driver string
dataSource string
db *sql.DB
}
// TODO: move call to CREATE_SCHEMA_IF_NOT_EXISTS_SQL to NewServer
func NewStorage(driver string, dataSource string) (*Storage, error) {
db, err := sql.Open(driver, dataSource)
if err != nil {
return nil, err
}
storage := &Storage{driver: driver, dataSource: dataSource, db: db}
_, err = storage.db.Exec(storage.dialectifySchema(CREATE_SCHEMA_IF_NOT_EXISTS_SQL))
return storage, err
}
// Storage.FindEndpoint returns an endpoint matching the given site and HTTP request.
func (storage *Storage) FindEndpoint(site string, req *http.Request) (endpoint *Endpoint, found bool, err error) {
endpoints, err := storage.getEndpoints(site)
if err != nil {
return nil, false, err
}
for _, endpoint := range endpoints {
if endpoint.Matches(req) {
return endpoint, true, nil
}
}
return nil, false, nil
}
func (storage *Storage) getEndpoints(site string) ([]*Endpoint, error) {
endpoints := make([]*Endpoint, 0)
rows, err := storage.db.Query(storage.dialectifyQuery(GET_SITE_ENDPOINTS_SQL), site)
if err != nil {
return endpoints, err
}
defer rows.Close()
for rows.Next() {
endpoint, err := makeEndpoint(rows)
if err != nil {
return endpoints, err
}
endpoints = append(endpoints, endpoint)
}
return endpoints, rows.Err()
}
func (storage *Storage) dialectifyQuery(sql string) string {
if storage.isPostgres() {
return sql
}
return POSTGRES_PLACEHOLDERS.ReplaceAllString(sql, "?")
}
func (storage *Storage) isPostgres() bool {
return storage.driver == "postgres"
}
func (storage *Storage) dialectifySchema(sql string) string {
if storage.isPostgres() {
return sql
}
// it's not pretty, but it's covered by tests
REPLACE_ALL := -1
return strings.Replace(sql, " BYTEA,", " BLOB,", REPLACE_ALL)
}
func makeEndpoint(rows *sql.Rows) (*Endpoint, error) {
endpoint := &Endpoint{}
var headersJson string
var delay int64
err := rows.Scan(&endpoint.Site, &endpoint.Path, &endpoint.Method, &headersJson, &delay,
&endpoint.StatusCode, &endpoint.Response)
if err != nil {
return endpoint, err
}
endpoint.Delay = time.Duration(delay)
endpoint.Headers, err = jsonToStringMap(headersJson)
return endpoint, err
}
func jsonToStringMap(js string) (map[string]string, error) {
object := make(map[string]interface{})
err := json.Unmarshal([]byte(js), &object)
if err != nil {
return nil, err
}
return objectToStringMap(object)
}
func objectToStringMap(object map[string]interface{}) (map[string]string, error) {
m := make(map[string]string)
for key, value := range object {
switch value.(type) {
case string:
m[key] = value.(string)
default:
return nil, fmt.Errorf("Expecting string, got %+v", value)
}
}
return m, nil
}
// Storage.SaveEndpoint upserts the given endpoint into a database.
func (storage *Storage) SaveEndpoint(endpoint *Endpoint) error {
tx, err := storage.db.Begin()
if err != nil {
return err
}
// If tx is commited, then tx.Rollback() basically has no effect.
// If there's some error and tx isn't commited, then we want to rollback.
defer tx.Rollback()
// upsert as delete-and-insert isn't correct in all cases
// (e.g concurrent upserts of the same endpoint will lead to "duplicate key value violates unique constraint")
// but is practical enough, because concurrent upserts of the same endpoint are going to be extremely rare
_, err = tx.Exec(storage.dialectifyQuery(DELETE_ENDPOINT_SQL),
endpoint.Site, endpoint.Path, endpoint.Method)
if err != nil {
return err
}
headersJson, err := stringMapToJson(endpoint.Headers)
if err != nil {
return err
}
_, err = tx.Exec(storage.dialectifyQuery(INSERT_ENDPOINT_SQL),
endpoint.Site, endpoint.Path, endpoint.Method,
headersJson, int64(endpoint.Delay), endpoint.StatusCode, endpoint.Response)
if err != nil {
return err
}
return tx.Commit()
}
func stringMapToJson(m map[string]string) (string, error) {
jsonBytes, err := json.Marshal(m)
return string(jsonBytes), err
}
// Storage.CreateSite returns an error if the given site already exists in a database.
func (storage *Storage) CreateSite(site string) error {
_, err := storage.db.Exec(storage.dialectifyQuery(INSERT_SITE_SQL), site)
return err
}
func (storage *Storage) SiteExists(site string) (bool, error) {
return storage.HasResults(GET_SITE_SQL, site)
}
func (storage *Storage) HasResults(sql string, args ...interface{}) (bool, error) {
rows, err := storage.db.Query(storage.dialectifyQuery(sql), args...)
if err != nil {
return false, err
}
defer rows.Close()
hasResults := rows.Next()
return hasResults, rows.Err()
}