-
Notifications
You must be signed in to change notification settings - Fork 97
/
dataservice.go
454 lines (374 loc) · 14.2 KB
/
dataservice.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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"encoding/json"
duktape "gopkg.in/olebedev/go-duktape.v3"
"github.com/hyperledger/fabric/core/chaincode/shim"
)
import "time"
// This is the object type used to form composite keys for the collection of collections.
const collectionObjectType = "$syscollections"
// DataService is a Go wrapper around an instance of the DataService JavaScript class.
type DataService struct {
VM *duktape.Context
Stub shim.ChaincodeStubInterface
}
// NewDataService creates a Go wrapper around a new instance of the DataService JavaScript class.
func NewDataService(vm *duktape.Context, context *Context, stub shim.ChaincodeStubInterface) (result *DataService) {
logger.Debug("Entering NewDataService", vm, context, &stub)
defer func() { logger.Debug("Exiting NewDataService", result) }()
// Ensure the JavaScript stack is reset.
defer vm.SetTop(vm.GetTop())
// Create the new data service.
result = &DataService{VM: vm, Stub: stub}
// Create a new instance of the JavaScript DataService class.
vm.PushGlobalObject() // [ global ]
vm.GetPropString(-1, "composer") // [ global composer ]
vm.GetPropString(-1, "DataService") // [ global composer DataService ]
err := vm.Pnew(0) // [ global composer theDataService ]
if err != nil {
panic(err)
}
// Store the data service into the global stash.
vm.PushGlobalStash() // [ global composer theDataService stash ]
vm.Dup(-2) // [ global composer theDataService stash theDataService ]
vm.PutPropString(-2, "dataService") // [ global composer theDataService stash ]
vm.Pop() // [ global composer theDataService ]
// Bind the methods into the JavaScript object.
vm.PushGoFunction(result.createCollection) // [ global composer theDataService createCollection ]
vm.PutPropString(-2, "_createCollection") // [ global composer theDataService ]
vm.PushGoFunction(result.deleteCollection) // [ global composer theDataService deleteCollection ]
vm.PutPropString(-2, "_deleteCollection") // [ global composer theDataService ]
vm.PushGoFunction(result.getCollection) // [ global composer theDataService getCollection ]
vm.PutPropString(-2, "_getCollection") // [ global composer theDataService ]
vm.PushGoFunction(result.existsCollection) // [ global composer theDataService existsCollection ]
vm.PutPropString(-2, "_existsCollection") // [ global composer theDataService ]
vm.PushGoFunction(result.executeQuery) // [ global composer theDataService executeQuery ]
vm.PutPropString(-2, "_executeQuery") // [ global composer theDataService ]
// Return the new data service.
return result
}
// createCollection creates a collection of objects in the world state.
func (dataService *DataService) createCollection(vm *duktape.Context) (result int) {
logger.Debug("Entering DataService.createCollection", vm)
start := time.Now()
defer func() { logger.Debug("@perf DataService.createCollection total duration for txnId [", dataService.Stub.GetTxID(), "] : ", time.Now().Sub(start)) }()
defer func() { logger.Debug("Exiting DataService.createCollection", result) }()
// Validate the arguments from JavaScript.
id := vm.RequireString(0)
force := vm.RequireBoolean(1)
vm.RequireFunction(2)
// Create the composite key.
// The collection is stored with a composite key of collection ID.
key, err := dataService.Stub.CreateCompositeKey(collectionObjectType, []string{id})
if err != nil {
vm.Dup(2)
vm.PushErrorObjectVa(duktape.ErrError, "%s", err.Error())
if vm.Pcall(1) == duktape.ExecError {
panic(err)
}
return 0
}
if !force {
// Check to see if the collection already exists.
existingValue, err := dataService.Stub.GetState(key)
if err != nil {
vm.Dup(2)
vm.PushErrorObjectVa(duktape.ErrError, "%s", err.Error())
if vm.Pcall(1) == duktape.ExecError {
panic(err)
}
return 0
} else if existingValue != nil {
vm.Dup(2)
vm.PushErrorObjectVa(duktape.ErrError, "Failed to add collection with ID '%s' as the collection already exists", id)
if vm.Pcall(1) == duktape.ExecError {
panic(err)
}
return 0
}
}
// Store the collection.
collection := map[string]interface{}{"id": id}
value, err := json.Marshal(collection)
if err != nil {
vm.Dup(2)
vm.PushErrorObjectVa(duktape.ErrError, "%s", err.Error())
if vm.Pcall(1) == duktape.ExecError {
panic(err)
}
return 0
}
err = dataService.Stub.PutState(key, value)
if err != nil {
vm.Dup(2)
vm.PushErrorObjectVa(duktape.ErrError, "%s", err.Error())
if vm.Pcall(1) == duktape.ExecError {
panic(err)
}
return 0
}
// Create a new data collection.
NewDataCollection(vm, dataService, dataService.Stub, id)
// Call the callback.
vm.PushGlobalStash()
vm.GetPropString(-1, "dataCollection")
vm.Dup(2)
vm.PushNull()
vm.Dup(-3)
if vm.Pcall(2) == duktape.ExecError {
panic(vm.ToString(-1))
}
return 0
}
// deleteCollection deletes a collection of objects in the world state.
func (dataService *DataService) deleteCollection(vm *duktape.Context) (result int) {
logger.Debug("Entering DataService.deleteCollection", vm)
start := time.Now()
defer func() { logger.Debug("@perf DataService.deleteCollection total duration for txnId [", dataService.Stub.GetTxID(), "] : ", time.Now().Sub(start)) }()
defer func() { logger.Debug("Exiting DataService.deleteCollection", result) }()
// Validate the arguments from JavaScript.
id := vm.RequireString(0)
vm.RequireFunction(1)
// Create the composite key.
// The collection is stored with a composite key of collection ID.
key, err := dataService.Stub.CreateCompositeKey(collectionObjectType, []string{id})
if err != nil {
vm.Dup(1)
vm.PushErrorObjectVa(duktape.ErrError, "%s", err.Error())
if vm.Pcall(1) == duktape.ExecError {
panic(err)
}
return 0
}
// Remove all of the objects from the collection.
err = dataService.clearCollection(id)
if err != nil {
vm.Dup(1)
vm.PushErrorObjectVa(duktape.ErrError, "%s", err.Error())
if vm.Pcall(1) == duktape.ExecError {
panic(err)
}
return 0
}
// Delete the collection.
err = dataService.Stub.DelState(key)
if err != nil {
vm.Dup(1)
vm.PushErrorObjectVa(duktape.ErrError, "%s", err.Error())
if vm.Pcall(1) == duktape.ExecError {
panic(err)
}
return 0
}
// Call the callback.
vm.Dup(1)
vm.PushNull()
if vm.Pcall(1) == duktape.ExecError {
panic(vm.ToString(-1))
}
return 0
}
// getCollection retrieves an existing collection from the world state.
func (dataService *DataService) getCollection(vm *duktape.Context) (result int) {
logger.Debug("Entering DataService.getCollection", vm)
start := time.Now()
defer func() { logger.Debug("@perf DataService.getCollection total duration for txnId [", dataService.Stub.GetTxID(), "] : ", time.Now().Sub(start)) }()
defer func() { logger.Debug("Exiting DataService.getCollection", result) }()
// Validate the arguments from JavaScript.
id := vm.RequireString(0)
vm.RequireFunction(1)
// Create the composite key.
// The collection is stored with a composite key of collection ID.
key, err := dataService.Stub.CreateCompositeKey(collectionObjectType, []string{id})
if err != nil {
vm.Dup(1)
vm.PushErrorObjectVa(duktape.ErrError, "%s", err.Error())
if vm.Pcall(1) == duktape.ExecError {
panic(err)
}
return 0
}
increment := time.Now();
// Get the collection.
value, err := dataService.Stub.GetState(key)
if err != nil {
vm.Dup(1)
vm.PushErrorObjectVa(duktape.ErrError, "%s", err.Error())
if vm.Pcall(1) == duktape.ExecError {
panic(err)
}
return 0
} else if value == nil {
vm.Dup(1)
vm.PushErrorObjectVa(duktape.ErrError, "Collection with ID '%s' does not exist", id)
if vm.Pcall(1) == duktape.ExecError {
panic(err)
}
return 0
}
logger.Debug("@perf DataService.getCollection getState duration for txnId [", dataService.Stub.GetTxID(), "] : ", time.Now().Sub(increment))
increment = time.Now();
// Create the new data collection.
NewDataCollection(vm, dataService, dataService.Stub, id)
logger.Debug("@perf DataService.getCollection NewDataCollection duration for txnId [", dataService.Stub.GetTxID(), "] : ", time.Now().Sub(increment))
increment = time.Now();
// Call the callback.
vm.PushGlobalStash()
vm.GetPropString(-1, "dataCollection")
vm.Dup(1)
vm.PushNull()
vm.Dup(-3)
if vm.Pcall(2) == duktape.ExecError {
panic(vm.ToString(-1))
}
logger.Debug("@perf DataService.getCollection callback duration for txnId [", dataService.Stub.GetTxID(), "] : ", time.Now().Sub(increment))
return 0
}
// existsCollection checks to see if a collection exists in the world state.
func (dataService *DataService) existsCollection(vm *duktape.Context) (result int) {
logger.Debug("Entering DataService.existsCollection", vm)
start := time.Now()
defer func() { logger.Debug("@perf DataService.existsCollection total duration for txnId [", dataService.Stub.GetTxID(), "] : ", time.Now().Sub(start)) }()
defer func() { logger.Debug("Exiting DataService.existsCollection", result) }()
// Validate the arguments from JavaScript.
id := vm.RequireString(0)
vm.RequireFunction(1)
// Create the composite key.
// The collection is stored with a composite key of collection ID.
key, err := dataService.Stub.CreateCompositeKey(collectionObjectType, []string{id})
if err != nil {
vm.Dup(1)
vm.PushErrorObjectVa(duktape.ErrError, "%s", err.Error())
if vm.Pcall(1) == duktape.ExecError {
panic(err)
}
return 0
}
increment := time.Now();
// Get the collection.
value, err := dataService.Stub.GetState(key)
if err != nil {
vm.Dup(1)
vm.PushErrorObjectVa(duktape.ErrError, "%s", err.Error())
if vm.Pcall(1) == duktape.ExecError {
panic(err)
}
return 0
}
logger.Debug("@perf DataService.existsCollection GetState duration for txnId [", dataService.Stub.GetTxID(), "] : ", time.Now().Sub(increment))
increment = time.Now();
// Call the callback.
vm.PushGlobalStash()
vm.GetPropString(-1, "dataCollection")
vm.Dup(1)
vm.PushNull()
vm.PushBoolean(value != nil)
if vm.Pcall(2) == duktape.ExecError {
panic(vm.ToString(-1))
}
logger.Debug("@perf DataService.existsCollection callback duration for txnId [", dataService.Stub.GetTxID(), "] : ", time.Now().Sub(increment))
return 0
}
// executeQuery executes a query against the data in the world state.
func (dataService *DataService) executeQuery(vm *duktape.Context) (result int) {
logger.Debug("Entering DataService.executeQuery", vm)
start := time.Now()
defer func() { logger.Debug("@perf DataService.executeQuery total duration for txnId [", dataService.Stub.GetTxID(), "] : ", time.Now().Sub(start)) }()
defer func() { logger.Debug("Exiting DataService.executeQuery", result) }()
// argument 0 is the CouchDB queryString
queryString := vm.RequireString(0)
logger.Debug("CouchDB query string", queryString)
// argument 1 is the callback function (err,response)
vm.RequireFunction(1)
increment := time.Now()
resultsIterator, err := dataService.Stub.GetQueryResult(queryString)
if err != nil {
vm.Dup(1)
vm.PushErrorObjectVa(duktape.ErrError, "%s", err.Error())
if vm.Pcall(1) == duktape.ExecError {
panic(err)
}
return 0
}
defer resultsIterator.Close()
logger.Debug("Got an iterator", resultsIterator)
logger.Debug("@perf DataService.executeQuery GetQueryResult duration for txnId [", dataService.Stub.GetTxID(), "] : ", time.Now().Sub(increment))
increment = time.Now();
arrIdx := vm.PushArray()
arrNum := uint(0)
for resultsIterator.HasNext() {
current, err := resultsIterator.Next()
if err != nil {
vm.Dup(1)
vm.PushErrorObjectVa(duktape.ErrError, "%s", err.Error())
if vm.Pcall(1) == duktape.ExecError {
panic(err)
}
return 0
}
logger.Debug("Element index", arrNum)
logger.Debug("-- key.Key", current.Key)
logger.Debug("-- key.Value", string(current.Value))
// we have to remove nulls from the key (which delimit a compound key)
vm.PushString(string(current.Value))
vm.JsonDecode(-1)
vm.PutPropIndex(arrIdx, arrNum)
arrNum++
}
logger.Debug("@perf DataService.executeQuery resultsIterator.HasNext() duration for txnId [", dataService.Stub.GetTxID(), "] : ", time.Now().Sub(increment))
increment = time.Now();
// Call the callback.
vm.Dup(1)
vm.PushNull() // no error
vm.Dup(arrIdx)
if vm.Pcall(2) == duktape.ExecError {
panic(vm.ToString(-1))
}
logger.Debug("@perf DataService.executeQuery callback execution duration for txnId [", dataService.Stub.GetTxID(), "] : ", time.Now().Sub(increment))
return 0
}
// clearCollection is called to clear all objects from a collection.
func (dataService *DataService) clearCollection(collectionID string) (err error) {
logger.Debug("Entering DataService.clearCollection", collectionID)
start := time.Now()
defer func() { logger.Debug("@perf DataService.clearCollection total duration for txnId [", dataService.Stub.GetTxID(), "] : ", time.Now().Sub(start)) }()
defer func() { logger.Debug("Exiting DataService.clearCollection", err) }()
increment := time.Now();
// We look for all objects in this collection by performing a partial query.
// The objects are stored with composite keys of collectionID + objectID.
iterator, err := dataService.Stub.GetStateByPartialCompositeKey(collectionID, []string{})
if err != nil {
return err
}
logger.Debug("@perf DataService.getCollection GetStateByPartialCompositeKey duration for txnId [", dataService.Stub.GetTxID(), "] : ", time.Now().Sub(increment))
increment = time.Now();
// Must close iterator to free resources.
defer iterator.Close()
// Iterate over all the keys returned by the partial query above.
for iterator.HasNext() {
// Read the current key.
kv, err := iterator.Next()
if err != nil {
return err
}
// Delete the current key.
err = dataService.Stub.DelState(kv.Key)
if err != nil {
return err
}
}
return nil
}