Repository navigation
Expand file tree
/
Copy pathcaller.go
More file actions
93 lines (83 loc) · 2.57 KB
/
Copy pathcaller.go
File metadata and controls
93 lines (83 loc) · 2.57 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
package dbsync
import (
"webtyp.com/changelog"
"webtyp.com/json"
"webtyp.com/model"
"webtyp.com/orm"
"webtyp.com/outbox"
"webtyp.com/router"
)
// Caller is what the views of offline modules call: reads and writes run on the local database
// at once; writes are also queued and pushed to the server.
func (c *Client) Caller() router.Caller { return offlineCaller{c: c} }
type offlineCaller struct{ c *Client }
// Call never blocks its caller: the work runs in its own goroutine and done is called from there.
func (o offlineCaller) Call(op router.Operation, args model.Encodable, into model.Decodable, done func(err error)) {
go func() {
err := o.c.call(op, args, into)
if done != nil {
done(err)
}
}()
}
func (o offlineCaller) Dispatch(op router.Operation, args model.Encodable) { o.Call(op, args, nil, nil) }
func (c *Client) call(op router.Operation, args model.Encodable, into model.Decodable) error {
info, ok := c.op(op)
if !ok {
return errNotOfflineOp(op)
}
if info.action == model.Read {
return c.runLocal(op, args, into)
}
if err := c.write(op, args, into); err != nil {
return err
}
c.wake()
return nil
}
// runLocal runs op on the local modules (loopback answers synchronously).
func (c *Client) runLocal(op router.Operation, args model.Encodable, into model.Decodable) error {
var out error
c.local.Call(op, args, into, func(err error) { out = err })
return out
}
// write runs op locally, queues it, and records which rows it touched (to undo it if the server
// rejects it).
func (c *Client) write(op router.Operation, args model.Encodable, into model.Decodable) error {
c.mu.Lock()
defer c.mu.Unlock()
before := c.localLog.Head()
if err := c.runLocal(op, args, into); err != nil {
return err
}
touched, err := c.localLog.Since(before, maxTouched)
if err != nil {
return err
}
payload := []byte(emptyObject)
if args != nil && !model.IsNil(args) {
payload = nil
if err := json.Encode(args, &payload); err != nil {
return err
}
}
id, err := c.box.Enqueue(outbox.Entry{Op: op.String(), Payload: payload})
if err != nil {
return err
}
now := c.cfg.Now()
for _, t := range touched {
rec := &Touched{Id: c.ids.NewID(), MutationId: id, TableName: t.TableName, RowId: t.RowId, CreatedAt: now}
if err := c.raw.Create(rec); err != nil {
return err
}
}
// Keep the local change log empty at rest: it only exists to tell which rows a write touched.
if len(touched) > 0 {
if err := c.raw.Delete(&changelog.Change{}, orm.Gt(changelog.Change_.Version, before)); err != nil {
return err
}
}
return c.saveState()
}
const emptyObject = "{}"