-
Notifications
You must be signed in to change notification settings - Fork 138
/
replication.go
300 lines (241 loc) · 7.2 KB
/
replication.go
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
package data
import (
"log"
"net/http"
"strconv"
"github.com/cozy/cozy-stack/model/permission"
"github.com/cozy/cozy-stack/model/vfs"
"github.com/cozy/cozy-stack/pkg/config/config"
"github.com/cozy/cozy-stack/pkg/consts"
"github.com/cozy/cozy-stack/pkg/couchdb"
"github.com/cozy/cozy-stack/pkg/jsonapi"
"github.com/cozy/cozy-stack/web/middlewares"
"github.com/labstack/echo/v4"
)
func proxy(c echo.Context, path string) error {
doctype := c.Param("doctype")
instance := middlewares.GetInstance(c)
p := couchdb.Proxy(instance, doctype, path)
logger := instance.Logger().WithNamespace("data-proxy").Writer()
defer logger.Close()
p.ErrorLog = log.New(logger, "", 0)
p.ServeHTTP(c.Response(), c.Request())
return nil
}
func getLocalDoc(c echo.Context) error {
doctype := c.Param("doctype")
docid := c.Get("docid").(string)
if err := middlewares.AllowWholeType(c, permission.GET, doctype); err != nil {
return err
}
if err := permission.CheckReadable(doctype); err != nil {
return err
}
return proxy(c, "_local/"+docid)
}
func setLocalDoc(c echo.Context) error {
doctype := c.Param("doctype")
docid := c.Get("docid").(string)
if err := middlewares.AllowWholeType(c, permission.GET, doctype); err != nil {
return err
}
if err := permission.CheckReadable(doctype); err != nil {
return err
}
return proxy(c, "_local/"+docid)
}
func bulkGet(c echo.Context) error {
doctype := c.Param("doctype")
if err := middlewares.AllowWholeType(c, permission.GET, doctype); err != nil {
return err
}
if err := permission.CheckReadable(doctype); err != nil {
return err
}
return proxy(c, "_bulk_get")
}
func bulkDocs(c echo.Context) error {
doctype := c.Param("doctype")
if err := middlewares.AllowWholeType(c, permission.POST, doctype); err != nil {
return err
}
if err := permission.CheckWritable(doctype); err != nil {
return err
}
instance := middlewares.GetInstance(c)
if err := couchdb.EnsureDBExist(instance, doctype); err != nil {
return err
}
p, req, err := couchdb.ProxyBulkDocs(instance, doctype, c.Request())
if err != nil {
var code int
if errHTTP, ok := err.(*echo.HTTPError); ok {
code = errHTTP.Code
} else {
code = http.StatusInternalServerError
}
return c.JSON(code, echo.Map{
"error": err.Error(),
})
}
p.ServeHTTP(c.Response(), req)
return nil
}
func createDB(c echo.Context) error {
doctype := c.Param("doctype")
if err := middlewares.AllowWholeType(c, permission.POST, doctype); err != nil {
return err
}
if err := permission.CheckWritable(doctype); err != nil {
return err
}
return proxy(c, "/")
}
func fullCommit(c echo.Context) error {
doctype := c.Param("doctype")
if err := middlewares.AllowWholeType(c, permission.GET, doctype); err != nil {
return err
}
if err := permission.CheckWritable(doctype); err != nil {
return err
}
return proxy(c, "_ensure_full_commit")
}
func revsDiff(c echo.Context) error {
doctype := c.Param("doctype")
if err := middlewares.AllowWholeType(c, permission.GET, doctype); err != nil {
return err
}
if err := permission.CheckReadable(doctype); err != nil {
return err
}
return proxy(c, "_revs_diff")
}
var allowedChangesParams = map[string]bool{
"feed": true,
"style": true,
"since": true,
"limit": true,
"timeout": true,
"include_docs": true,
"heartbeat": true, // Pouchdb sends heartbeet even for non-continuous
"_nonce": true, // Pouchdb sends a request hash to avoid aggressive caching by some browsers
"seq_interval": true,
"descending": true,
}
func changesFeed(c echo.Context) error {
instance := middlewares.GetInstance(c)
doctype := c.Param("doctype")
// Drop a clear error for parameters not supported by stack
for key := range c.QueryParams() {
if key == "filter" && c.Request().Method == http.MethodPost {
continue
}
if !allowedChangesParams[key] {
return jsonapi.Errorf(http.StatusBadRequest, "Unsupported query parameter '%s'", key)
}
}
feed, err := couchdb.ValidChangesMode(c.QueryParam("feed"))
if err != nil {
return jsonapi.Errorf(http.StatusBadRequest, "%s", err)
}
feedStyle, err := couchdb.ValidChangesStyle(c.QueryParam("style"))
if err != nil {
return jsonapi.Errorf(http.StatusBadRequest, "%s", err)
}
filter, err := couchdb.StaticChangesFilter(c.QueryParam("filter"))
if err != nil {
return jsonapi.Errorf(http.StatusBadRequest, "%s", err)
}
limitString := c.QueryParam("limit")
limit := 0
if limitString != "" {
if limit, err = strconv.Atoi(limitString); err != nil {
return jsonapi.Errorf(http.StatusBadRequest, "Invalid limit value '%s': %s", limitString, err.Error())
}
}
seqIntervalString := c.QueryParam("seq_interval")
seqInterval := 0
if seqIntervalString != "" {
if seqInterval, err = strconv.Atoi(seqIntervalString); err != nil {
return jsonapi.Errorf(http.StatusBadRequest, "Invalid seq_interval value '%s': %s", seqIntervalString, err.Error())
}
}
includeDocs := paramIsTrue(c, "include_docs")
descending := paramIsTrue(c, "descending")
if err = permission.CheckReadable(doctype); err != nil {
return err
}
if err = middlewares.AllowWholeType(c, permission.GET, doctype); err != nil {
return err
}
// Use the VFS lock for the files to avoid sending the changed feed while
// the VFS is moving a directory.
if doctype == consts.Files {
mu := config.Lock().ReadWrite(instance, "vfs")
if err := mu.Lock(); err != nil {
return err
}
defer mu.Unlock()
}
couchReq := &couchdb.ChangesRequest{
DocType: doctype,
Feed: feed,
Style: feedStyle,
Filter: filter,
Since: c.QueryParam("since"),
Limit: limit,
IncludeDocs: includeDocs,
SeqInterval: seqInterval,
Descending: descending,
}
var results *couchdb.ChangesResponse
if filter == "" {
results, err = couchdb.GetChanges(instance, couchReq)
} else {
results, err = couchdb.PostChanges(instance, couchReq, c.Request().Body)
}
if err != nil {
return err
}
if doctype == consts.Files {
if client, ok := middlewares.GetOAuthClient(c); ok {
err = vfs.FilterNotSynchronizedDocs(instance.VFS(), client.ID(), results)
if err != nil {
return err
}
}
}
return c.JSON(http.StatusOK, results)
}
func dbStatus(c echo.Context) error {
instance := middlewares.GetInstance(c)
doctype := c.Param("doctype")
if err := middlewares.AllowWholeType(c, permission.GET, doctype); err != nil {
return err
}
if err := permission.CheckReadable(doctype); err != nil {
return err
}
status, err := couchdb.DBStatus(instance, doctype)
if err != nil {
return err
}
return c.JSON(http.StatusOK, status)
}
func replicationRoutes(group *echo.Group) {
group.PUT("/", createDB)
// Routes used only for replication
group.GET("/", dbStatus)
group.GET("/_changes", changesFeed)
// POST=GET+filter see http://docs.couchdb.org/en/stable/api/database/changes.html#post--db-_changes)
group.POST("/_changes", changesFeed)
group.POST("/_ensure_full_commit", fullCommit)
// useful for Pouchdb replication
group.POST("/_bulk_get", bulkGet) // https://github.com/couchbase/sync_gateway/wiki/Bulk-GET
group.POST("/_bulk_docs", bulkDocs)
group.POST("/_revs_diff", revsDiff)
// for storing checkpoints
group.GET("/_local/:docid", getLocalDoc)
group.PUT("/_local/:docid", setLocalDoc)
}