-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexamples_test.go
More file actions
569 lines (473 loc) · 14.9 KB
/
Copy pathexamples_test.go
File metadata and controls
569 lines (473 loc) · 14.9 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
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
package tcs_test
import (
"context"
"errors"
"fmt"
"log"
"time"
"github.com/tarantool/go-tarantool/v2"
"github.com/tarantool/go-storage/driver/tcs"
gsTesting "github.com/tarantool/go-storage/internal/testing"
"github.com/tarantool/go-storage/locker"
"github.com/tarantool/go-storage/operation"
"github.com/tarantool/go-storage/predicate"
)
func newResponse(success bool, data [][]any) *gsTesting.MockResponse {
return gsTesting.NewMockResponse(gsTesting.NewT(), []any{
map[string]any{
"data": map[string]any{
"responses": data,
"is_success": success,
},
"revision": 1000,
},
})
}
func createTCSDriverExecuteSimple() *tcs.Driver {
mock := gsTesting.NewMockDoer(gsTesting.NewT(),
newResponse(true, [][]any{{}}),
newResponse(true, [][]any{
{
map[string]any{
"path": []byte("/config/app/version"),
"value": []byte("1.0.0"),
"mod_revision": 1000,
},
},
}),
newResponse(true, [][]any{{}}),
newResponse(true, [][]any{{}, {}}),
)
// createDriver is a function to create dummy driver.
return tcs.New(gsTesting.NewMockDoerWithWatcher(mock, nil))
}
// ExampleExecuteBasicOperations demonstrates basic Execute operations with the TCS driver.
// This example shows Put, Get, and Delete operations without predicates.
func ExampleDriver_Execute_simple() {
ctx := context.Background()
driver := createTCSDriverExecuteSimple()
// Example 1: Simple Put operation.
{
key := []byte("/config/app/version")
value := []byte("1.0.0")
_, err := driver.Execute(ctx, nil, []operation.Operation{
operation.Put(key, value),
}, nil)
if err != nil {
log.Printf("Put operation failed: %v", err)
return
}
fmt.Println("Key", string(key), "stored with value:", string(value))
}
// Example 2: Simple Get operation.
{
key := []byte("/config/app/version")
response, err := driver.Execute(ctx, nil, []operation.Operation{
operation.Get(key),
}, nil)
if err != nil {
log.Printf("Get operation failed: %v", err)
return
}
if response.Succeeded && len(response.Results) > 0 {
if len(response.Results[0].Values) > 0 {
kv := response.Results[0].Values[0]
fmt.Printf("Retrieved key: %s, value: %s, version: %d\n",
string(kv.Key), string(kv.Value), kv.ModRevision)
}
}
}
// Example 3: Simple Delete operation.
{
key := []byte("/config/app/version")
_, err := driver.Execute(ctx, nil, []operation.Operation{
operation.Delete(key),
}, nil)
if err != nil {
log.Printf("Delete operation failed: %v", err)
return
}
fmt.Println("Successfully deleted key:", string(key))
}
// Example 4: Multiple operations in single transaction.
{
response, err := driver.Execute(ctx, nil, []operation.Operation{
operation.Put([]byte("/config/app/name"), []byte("MyApp")),
operation.Put([]byte("/config/app/environment"), []byte("production")),
}, nil)
if err != nil {
log.Printf("Multi-put operation failed: %v", err)
return
}
fmt.Println("Successfully stored", len(response.Results), "configuration items")
}
// Output:
// Key /config/app/version stored with value: 1.0.0
// Retrieved key: /config/app/version, value: 1.0.0, version: 1000
// Successfully deleted key: /config/app/version
// Successfully stored 2 configuration items
}
func createTCSDriverExecuteWithPredicates() *tcs.Driver {
mock := gsTesting.NewMockDoer(gsTesting.NewT(),
newResponse(true, [][]any{{}}),
newResponse(true, [][]any{{}}),
newResponse(true, [][]any{
{
map[string]any{
"path": []byte("/config/app/feature"),
"value": []byte("enabled"),
"mod_revision": 1000,
},
},
}),
newResponse(true, [][]any{{}}),
newResponse(true, [][]any{{}, {}}),
newResponse(true, [][]any{{}, {}}),
newResponse(false, [][]any{{}, {}}),
)
// createDriver is a function to create dummy driver.
return tcs.New(gsTesting.NewMockDoerWithWatcher(mock, nil))
}
// ExampleDriver_Execute_WithPredicates demonstrates conditional Execute operations using predicates.
// This example shows how to use value and version predicates for conditional execution.
func ExampleDriver_Execute_with_predicates() {
ctx := context.Background()
driver := createTCSDriverExecuteWithPredicates()
// Example 1: Value-based conditional update.
{
key := []byte("/config/app/settings")
currentValue := []byte("old-settings")
newValue := []byte("new-settings")
_, _ = driver.Execute(ctx, nil, []operation.Operation{
operation.Put(key, currentValue),
}, nil)
response, err := driver.Execute(ctx, []predicate.Predicate{
predicate.ValueEqual(key, "old-settings"),
}, []operation.Operation{
operation.Put(key, newValue),
}, nil)
if err != nil {
log.Printf("Conditional update failed: %v", err)
return
}
if response.Succeeded {
fmt.Println("Conditional update succeeded - value was updated")
} else {
fmt.Println("Conditional update failed - value did not match")
}
}
// Example 2: Version-based conditional update.
{
key := []byte("/config/app/feature")
value := []byte("enabled")
_, err := driver.Execute(ctx, nil, []operation.Operation{
operation.Put(key, value),
}, nil)
if err != nil {
log.Printf("Initial update failed: %v", err)
return
}
getResponse, err := driver.Execute(ctx, nil, []operation.Operation{
operation.Get(key),
}, nil)
if err != nil {
log.Printf("Get operation failed: %v", err)
return
}
var currentVersion int64
if len(getResponse.Results) > 0 && len(getResponse.Results[0].Values) > 0 {
currentVersion = getResponse.Results[0].Values[0].ModRevision
}
response, err := driver.Execute(ctx, []predicate.Predicate{
predicate.VersionEqual(key, currentVersion),
}, []operation.Operation{
operation.Put(key, []byte("disabled")),
}, nil)
if err != nil {
log.Printf("Version-based update failed: %v", err)
return
}
if response.Succeeded {
fmt.Println("Version-based update succeeded - no concurrent modification")
} else {
fmt.Println("Version-based update failed - version conflict detected")
}
}
// Example 3: Multiple predicates with Else operations.
{
key1 := []byte("/config/database/host")
key2 := []byte("/config/database/port")
_, _ = driver.Execute(ctx, nil, []operation.Operation{
operation.Put(key1, []byte("localhost")),
operation.Put(key2, []byte("5432")),
}, nil)
response, err := driver.Execute(ctx, []predicate.Predicate{
predicate.ValueEqual(key1, "localhost"),
predicate.ValueEqual(key2, "5432"),
}, []operation.Operation{
operation.Put(key1, []byte("new-host")),
operation.Put(key2, []byte("6432")),
}, []operation.Operation{
operation.Delete(key1),
operation.Delete(key2),
})
if err != nil {
log.Printf("Multi-predicate transaction failed: %v", err)
return
}
if response.Succeeded {
fmt.Println("Multi-predicate transaction succeeded - values were updated")
} else {
fmt.Println("Multi-predicate transaction failed - cleanup operations executed")
}
}
// Output:
// Conditional update succeeded - value was updated
// Version-based update succeeded - no concurrent modification
// Multi-predicate transaction failed - cleanup operations executed
}
func createTCSDriverWatch() *tcs.Driver {
return tcs.New(
gsTesting.NewMockDoerWithWatcher(
gsTesting.NewMockDoer(gsTesting.NewT(),
newResponse(true, [][]any{{}}),
newResponse(true, [][]any{{}}),
newResponse(true, [][]any{{}}),
newResponse(true, [][]any{{}}),
),
map[string][]tarantool.WatchEvent{
"config.storage:/config/app/status": {
tarantool.WatchEvent{
Conn: nil,
Key: "/config/app/status",
Value: nil,
},
},
"config.storage:/config/database/": {
tarantool.WatchEvent{
Conn: nil,
Key: "/config/database/host",
Value: nil,
},
tarantool.WatchEvent{
Conn: nil,
Key: "/config/database/port",
Value: nil,
},
tarantool.WatchEvent{
Conn: nil,
Key: "/config/database/host",
Value: nil,
},
},
"config.storage:/config/monitoring/metrics": {},
},
),
)
}
// ExampleWatchOperations demonstrates how to use Watch for real-time change notifications.
// This example shows watching individual keys and handling watch events.
func ExampleDriver_Watch() {
ctx := context.Background()
driver := createTCSDriverWatch()
// Example 1: Basic watch on a single key.
{
key := []byte("/config/app/status")
watchCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
eventCh, stopWatch, err := driver.Watch(watchCtx, key)
if err != nil {
log.Printf("Failed to start watch: %v", err)
return
}
defer stopWatch()
fmt.Println("Watching for changes on:", string(key))
go func() {
time.Sleep(100 * time.Millisecond)
_, _ = driver.Execute(ctx, nil, []operation.Operation{
operation.Put(key, []byte("running")),
}, nil)
}()
select {
case event := <-eventCh:
fmt.Printf("Received watch event for key: %s\n", string(event.Prefix))
case <-watchCtx.Done():
fmt.Println("Watch context expired")
}
}
// Example 2: Watch with multiple operations.
{
key := []byte("/config/database/")
watchCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
eventCh, stopWatch, err := driver.Watch(watchCtx, key)
if err != nil {
log.Printf("Failed to start watch: %v", err)
return
}
defer stopWatch()
fmt.Println("Watching for changes on prefix:", string(key))
go func() {
time.Sleep(100 * time.Millisecond)
_, _ = driver.Execute(ctx, nil, []operation.Operation{
operation.Put([]byte("/config/database/host"), []byte("db1")),
}, nil)
time.Sleep(200 * time.Millisecond)
_, _ = driver.Execute(ctx, nil, []operation.Operation{
operation.Put([]byte("/config/database/port"), []byte("5432")),
}, nil)
time.Sleep(300 * time.Millisecond)
_, _ = driver.Execute(ctx, nil, []operation.Operation{
operation.Delete([]byte("/config/database/host")),
}, nil)
}()
eventCount := 0
for eventCount < 3 {
select {
case event := <-eventCh:
fmt.Printf("Event %d: change detected on %s\n", eventCount+1, string(event.Prefix))
eventCount++
case <-watchCtx.Done():
fmt.Println("Watch context expired")
return
}
}
}
// Example 3: Graceful watch termination.
{
key := []byte("/config/monitoring/metrics")
watchCtx, cancel := context.WithCancel(ctx)
eventCh, stopWatch, err := driver.Watch(watchCtx, key)
if err != nil {
log.Printf("Failed to start watch: %v", err)
cancel()
return
}
fmt.Println("Started watch with manual control")
go func() {
time.Sleep(100 * time.Millisecond)
fmt.Println("Stopping watch gracefully...")
stopWatch()
cancel()
}()
for {
select {
case event, ok := <-eventCh:
if !ok {
return
}
fmt.Printf("Received event: %s\n", string(event.Prefix))
case <-watchCtx.Done():
return
}
}
}
// Output:
// Watching for changes on: /config/app/status
// Received watch event for key: /config/app/status
// Watching for changes on prefix: /config/database/
// Event 1: change detected on /config/database
// Event 2: change detected on /config/database
// Event 3: change detected on /config/database
// Started watch with manual control
// Stopping watch gracefully...
}
// lockerMockResponse builds a raw config.storage.* response (an outer
// single-element list wrapping body) as the typed locker decoders expect.
func lockerMockResponse(body any) *gsTesting.MockResponse {
return gsTesting.NewMockResponse(gsTesting.NewT(), []any{body})
}
// createTCSDriverNewLocker scripts a MockDoer that mimics a TCS server
// advertising features.ttl + features.keepalive, then walks two Lockers
// through one round of contention plus a clean handover.
func createTCSDriverNewLocker() *tcs.Driver {
infoFeatures := map[string]any{
"features": map[string]any{"ttl": true, "keepalive": true},
}
getEntry := func(path string, modRev int64) any {
return map[string]any{"path": path, "value": "", "mod_revision": modRev}
}
getResponse := func(entries ...any) any {
return map[string]any{"data": entries, "revision": int64(1000)}
}
mock := gsTesting.NewMockDoer(gsTesting.NewT(),
// Holder NewLocker probes features.
lockerMockResponse(infoFeatures),
// Holder TryLock: put → get(only-self) → smallest, held.
lockerMockResponse(map[string]any{"revision": int64(10)}),
lockerMockResponse(getResponse(getEntry("/locks/leader/h", 10))),
// Contender NewLocker probes features.
lockerMockResponse(infoFeatures),
// Contender TryLock: put → get(holder+self) → not smallest → ErrLocked
// → cleanup delete of contender's failed key.
lockerMockResponse(map[string]any{"revision": int64(20)}),
lockerMockResponse(getResponse(
getEntry("/locks/leader/h", 10),
getEntry("/locks/leader/c", 20),
)),
lockerMockResponse(map[string]any{}),
// Holder Unlock deletes its key.
lockerMockResponse(map[string]any{}),
// Contender TryLock again: put → get(only-self) → smallest, held.
lockerMockResponse(map[string]any{"revision": int64(30)}),
lockerMockResponse(getResponse(getEntry("/locks/leader/c2", 30))),
// Contender Unlock deletes its key.
lockerMockResponse(map[string]any{}),
)
return tcs.New(gsTesting.NewMockDoerWithWatcher(mock, nil))
}
// ExampleDriver_NewLocker demonstrates acquiring a TCS-backed distributed
// lock, observing contention from a second Locker on the same name, and
// releasing the lock so the contender can proceed.
//
// The TCS server must advertise features.ttl and features.keepalive — on
// older schemas NewLocker returns tcs.ErrUnsupportedFeatures.
func ExampleDriver_NewLocker() {
ctx := context.Background()
driver := createTCSDriverNewLocker()
// A long TTL keeps the keepalive ticker (ttl/3) from firing during the
// example, so the scripted MockDoer only sees the calls illustrated below.
const ttl = 120 * time.Second
holder, err := driver.NewLocker(ctx, "/locks/leader", locker.WithTTL(ttl))
if err != nil {
log.Printf("NewLocker (holder) failed: %v", err)
return
}
err = holder.TryLock(ctx)
if err != nil {
log.Printf("holder TryLock failed: %v", err)
return
}
fmt.Println("holder acquired:", holder.Key() != "")
contender, err := driver.NewLocker(ctx, "/locks/leader", locker.WithTTL(ttl))
if err != nil {
log.Printf("NewLocker (contender) failed: %v", err)
return
}
err = contender.TryLock(ctx)
if errors.Is(err, locker.ErrLocked) {
fmt.Println("contender saw the lock as held")
}
err = holder.Unlock(ctx)
if err != nil {
log.Printf("Unlock failed: %v", err)
return
}
fmt.Println("holder released")
err = contender.TryLock(ctx)
if err != nil {
log.Printf("contender TryLock after release failed: %v", err)
return
}
fmt.Println("contender acquired:", contender.Key() != "")
err = contender.Unlock(ctx)
if err != nil {
log.Printf("Unlock failed: %v", err)
return
}
// Output:
// holder acquired: true
// contender saw the lock as held
// holder released
// contender acquired: true
}