/
simple.go
252 lines (219 loc) · 5.84 KB
/
simple.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
package deje
import (
"errors"
"log"
"sort"
"github.com/DJDNS/go-deje/document"
"github.com/DJDNS/go-deje/state"
"github.com/DJDNS/go-deje/timestamps"
"github.com/DJDNS/go-deje/util"
)
// Wraps the low-level capabilities of the basic Client to provide
// an easier, more useful API to downstream code.
type SimpleClient struct {
Tip *document.Event
client *Client
tt timestamps.TimestampTracker
logger *log.Logger
onReTipCallback OnReTipCallback
}
// Unless you want to manually specify router URL and topic separately,
// you should probably use Open() instead of NewSimpleClient().
func NewSimpleClient(topic string, logger *log.Logger) *SimpleClient {
raw_client := NewClient(topic)
doc := raw_client.Doc
simple_client := &SimpleClient{
nil,
&raw_client,
timestamps.NewTimestampTracker(doc, timestamps.NewPeerTimestampService(doc)),
logger,
nil,
}
raw_client.SetEventCallback(func(event interface{}) {
err := simple_client.onRcv(event)
if err != nil {
simple_client.Log(err)
}
})
return simple_client
}
// The preferred way to create SimpleClients. Handles the Connect() call, and
// uses GetRouterAndTopic() to turn a single deje://... URL into a router URL
// and topic.
func Open(deje_url string, logger *log.Logger, cb state.OnPrimitiveCallback) (*SimpleClient, error) {
router, topic, err := GetRouterAndTopic(deje_url)
if err != nil {
return nil, err
}
sc := NewSimpleClient(topic, logger)
sc.SetPrimitiveCallback(cb)
if err = sc.Connect(router); err != nil {
return nil, err
}
return sc, nil
}
func (sc *SimpleClient) rcvEventList(parent map[string]interface{}, key string) error {
doc := sc.GetDoc()
events, ok := parent[key].([]interface{})
if !ok {
return errors.New("Message with bad '" + key + "' param")
}
for _, serial_event := range events {
doc_ev := doc.NewEvent("")
err := util.CloneMarshal(serial_event, &doc_ev)
if err != nil {
return err
}
doc_ev.Register()
}
sc.ReTip()
return nil
}
func (sc *SimpleClient) onRcv(event interface{}) error {
map_ev, ok := event.(map[string]interface{})
if !ok {
return errors.New("Non-{} message")
}
evtype, ok := map_ev["type"].(string)
if !ok {
return errors.New("Message with no 'type' param")
}
doc := sc.GetDoc()
switch evtype {
case "02-request-events":
sc.PublishEvents()
case "02-publish-events":
return sc.rcvEventList(map_ev, "events")
case "02-request-timestamps":
sc.PublishTimestamps()
case "02-publish-timestamps":
ts, ok := map_ev["timestamps"].([]interface{})
if !ok {
return errors.New("Message with bad 'timestamps' param")
}
ts_strings := make([]string, len(ts))
for i, timestamp := range ts {
ts_string, ok := timestamp.(string)
if !ok {
return errors.New("Message with bad 'timestamps' param")
}
ts_strings[i] = ts_string
}
doc.Timestamps = ts_strings
var unfamiliar bool
for _, ts_string := range doc.Timestamps {
if _, ok := doc.Events[ts_string]; !ok {
unfamiliar = true
}
}
if unfamiliar {
sc.RequestEvents()
} else {
sc.ReTip()
}
case "log":
// Do nothing
default:
return errors.New("Unfamiliar message type: '" + evtype + "'")
}
return nil
}
// Connect and immediately request timestamps.
func (sc *SimpleClient) Connect(url string) error {
err := sc.client.Connect(url)
if err != nil {
return err
}
return sc.RequestTimestamps()
}
func (sc *SimpleClient) Log(args ...interface{}) {
if sc.logger != nil {
sc.logger.Println(args...)
}
}
func (sc *SimpleClient) ReTip() {
var err error
sc.Tip, err = sc.tt.FindLatest()
if err != nil {
sc.Log(err)
}
if sc.Tip != nil {
sc.Tip.Goto()
} else {
sc.GetDoc().State.Reset()
}
if sc.onReTipCallback != nil {
sc.onReTipCallback(sc.Tip)
}
}
func (sc *SimpleClient) RequestEvents() error {
return sc.Publish(map[string]interface{}{
"type": "02-request-events",
})
}
func (sc *SimpleClient) PublishEvents() error {
doc := sc.GetDoc()
hashes := make([]string, len(doc.Events))
events := make([]*document.Event, len(doc.Events))
// Provide events in hash-sorted order
var i int
for hash := range doc.Events {
hashes[i] = hash
i++
}
sort.Strings(hashes)
for i, hash := range hashes {
events[i] = doc.Events[hash]
}
return sc.Publish(map[string]interface{}{
"type": "02-publish-events",
"events": events,
})
}
func (sc *SimpleClient) RequestTimestamps() error {
return sc.Publish(map[string]interface{}{
"type": "02-request-timestamps",
})
}
func (sc *SimpleClient) PublishTimestamps() error {
return sc.Publish(map[string]interface{}{
"type": "02-publish-timestamps",
"timestamps": sc.GetDoc().Timestamps,
})
}
func (sc *SimpleClient) Publish(data interface{}) error {
return sc.client.Publish(data)
}
// Navigate the Document to an Event, and promote it as the tip.
func (sc *SimpleClient) Promote(ev document.Event) error {
doc := sc.GetDoc()
if err := ev.Goto(); err != nil {
return err
}
doc.Timestamps = append(doc.Timestamps, ev.Hash())
sc.ReTip()
return sc.PublishTimestamps()
}
// Set a callback for when primitives are applied to the document state.
func (sc *SimpleClient) SetPrimitiveCallback(c state.OnPrimitiveCallback) {
sc.GetDoc().State.SetPrimitiveCallback(c)
}
// An optional callback to be called whenever we reanalyze which event is tip.
type OnReTipCallback func(*document.Event)
// Set a callback for when we reanalyze which event is tip. This may be called
// multiple times with the same result tip.
func (sc *SimpleClient) SetRetipCallback(c OnReTipCallback) {
sc.onReTipCallback = c
}
// Get the Document object owned by this Client.
func (sc *SimpleClient) GetDoc() *document.Document {
return sc.client.Doc
}
// Get the Topic of the underlying Client.
func (sc *SimpleClient) GetTopic() string {
return sc.client.Topic
}
// Return the current contents of the document.
func (sc *SimpleClient) Export() interface{} {
return sc.client.Doc.State.Export()
}