Repository navigation
Expand file tree
/
Copy pathtranscode.go
More file actions
600 lines (509 loc) · 20.9 KB
/
Copy pathtranscode.go
File metadata and controls
600 lines (509 loc) · 20.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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
package main
import (
"context"
"fmt"
"math/rand"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/tigrisdata/deployment-test/workload"
)
// TranscodeMetrics holds metrics for transcode operations
type TranscodeMetrics struct {
TotalOps int64
SuccessOps int64
ErrorOps int64
AvgLatency time.Duration
P50Latency time.Duration
P95Latency time.Duration
P99Latency time.Duration
AvgTTFB time.Duration
P50TTFB time.Duration
P95TTFB time.Duration
P99TTFB time.Duration
ThroughputMBs float64
OpsPerSecond float64
Latencies []time.Duration
TTFBs []time.Duration
}
// ConsistencyMetrics holds metrics for read-after-write consistency
type ConsistencyMetrics struct {
TotalChecks int64
ImmediateReads int64
EventualReads int64
FailedReads int64
AvgLatency time.Duration
P50Latency time.Duration
P95Latency time.Duration
P99Latency time.Duration
TargetMetPercentage float64 // Percentage meeting <200ms target
Latencies []time.Duration
}
// workerTranscodeMetrics holds per-worker metrics to avoid lock contention
type workerTranscodeMetrics struct {
readLatencies []time.Duration
readTTFBs []time.Duration
writeLatencies []time.Duration
consLatencies []time.Duration
readSuccess int64
readErrors int64
writeSuccess int64
writeErrors int64
consImmediate int64
consEventual int64
consFailed int64
}
// TranscodeTest implements the Test interface for transcoding workload testing
type TranscodeTest struct {
validator *TigrisValidator
}
// NewTranscodeTest creates a new transcoding test
func NewTranscodeTest(validator *TigrisValidator) *TranscodeTest {
return &TranscodeTest{
validator: validator,
}
}
// Name returns the display name of the test
func (t *TranscodeTest) Name() string {
return "Transcoding Workload Tests"
}
// Type returns the type of test
func (t *TranscodeTest) Type() TestType {
return TestTypeTranscode
}
// Setup performs preload of source files using per-worker S3 clients
func (t *TranscodeTest) Setup(ctx context.Context) error {
cfg := t.validator.config.TranscodeConfig
baseClient := t.validator.clients["global"]
fmt.Printf("\n%sSetup Phase: Uploading %d source files (%s each)...%s\n",
ColorBrightWhite, cfg.SourceFileCount, formatBytes(cfg.SourceFileSize), ColorReset)
start := time.Now()
var completed int32
// Upload source files in parallel
var wg sync.WaitGroup
errChan := make(chan error, cfg.SourceFileCount)
for i := 0; i < cfg.SourceFileCount; i++ {
wg.Add(1)
go func(idx int) {
defer wg.Done()
// Create per-worker S3 client for isolated connection pool
// This prevents connection pool contention between parallel uploads
workerClient := workload.CreateWorkerS3Client(baseClient)
ops := workload.NewS3Operations(workerClient, t.validator.config.BucketName, true, 10*1024*1024)
key := fmt.Sprintf("%s/transcode/sources/video-%03d.bin", t.validator.config.Prefix, idx)
// Use streaming upload with chunked data generation
uploadStart := time.Now()
result := ops.PutObjectAuto(ctx, key, cfg.SourceFileSize)
uploadDuration := time.Since(uploadStart)
if !result.Success {
errChan <- fmt.Errorf("failed to upload source file %d: %w", idx, result.Error)
return
}
current := atomic.AddInt32(&completed, 1)
fmt.Printf(" Progress: %d/%d files uploaded (%s)\n",
current, cfg.SourceFileCount, formatDuration(uploadDuration))
}(i)
}
wg.Wait()
close(errChan)
// Check for errors
if len(errChan) > 0 {
return <-errChan
}
duration := time.Since(start)
totalSize := int64(cfg.SourceFileCount) * cfg.SourceFileSize
bandwidth := float64(totalSize) / duration.Seconds() // bytes per second
bandwidthGbps := (bandwidth * 8) / 1_000_000_000 // Convert to Gbps
fmt.Printf(" %sCompleted: %d files (%s total) in %s - %.2f Gbps%s\n\n",
ColorBrightGreen, cfg.SourceFileCount, formatBytes(totalSize),
formatDuration(duration), bandwidthGbps, ColorReset)
return nil
}
// Run executes the transcoding workload test
func (t *TranscodeTest) Run(ctx context.Context) TestStatus {
startTime := time.Now()
fmt.Printf("\n%s%s%s\n", ColorYellow, strings.Repeat("=", 80), ColorReset)
fmt.Println(" TRANSCODING WORKLOAD TESTS")
fmt.Printf("%s%s%s\n", ColorYellow, strings.Repeat("=", 80), ColorReset)
cfg := t.validator.config.TranscodeConfig
fmt.Printf("\nConfiguration:\n")
fmt.Printf(" Source Files: %d files, %s each\n", cfg.SourceFileCount, formatBytes(cfg.SourceFileSize))
fmt.Printf(" Chunk Size: %s per read\n", formatBytes(cfg.ChunkSize))
fmt.Printf(" Segment Size: %s - %s per write\n", formatBytes(cfg.SegmentSizeMin), formatBytes(cfg.SegmentSizeMax))
fmt.Printf(" Parallel Jobs: %d parallel jobs\n", cfg.JobCount)
fmt.Printf(" Test Duration: %s\n", cfg.TestDuration)
// Setup phase - only run if not already done
// Check if source files exist
baseClient := t.validator.clients["global"]
testKey := fmt.Sprintf("%s/transcode/sources/video-%03d.bin", t.validator.config.Prefix, 0)
checkCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
_, err := baseClient.HeadObject(checkCtx, &s3.HeadObjectInput{
Bucket: aws.String(t.validator.config.BucketName),
Key: aws.String(testKey),
})
if err != nil {
// Source files don't exist, run setup
fmt.Printf("\n%s", strings.Repeat("-", 60))
if err := t.Setup(ctx); err != nil {
return TestStatus{
Passed: false,
Duration: time.Since(startTime),
Message: fmt.Sprintf("Setup failed: %v", err),
Details: nil,
}
}
}
// Run transcode simulation
fmt.Printf("%s\n%sTranscoding Simulation (%d parallel jobs, %s duration):%s\n",
strings.Repeat("-", 60), ColorBrightWhite, cfg.JobCount, cfg.TestDuration, ColorReset)
readMetrics, writeMetrics, consistencyMetrics := t.runTranscodeSimulation(ctx)
// Display results
t.displayResults(readMetrics, writeMetrics, consistencyMetrics)
// Cleanup
fmt.Printf("\n%sCleanup Phase: Removing test objects...%s ", ColorBrightWhite, ColorReset)
if err := t.Cleanup(ctx); err != nil {
fmt.Printf("%sFAILED%s\n", ColorBrightRed, ColorReset)
} else {
fmt.Printf("%sDONE%s\n", ColorBrightGreen, ColorReset)
}
totalDuration := time.Since(startTime)
fmt.Printf("\nTotal Duration: %s\n", formatDuration(totalDuration))
// Determine pass/fail based on consistency metrics
passed := consistencyMetrics.TargetMetPercentage >= 95.0 // 95% should meet <200ms target
message := "Transcoding workload test completed"
if !passed {
message = "Transcoding workload test failed consistency requirements"
}
return TestStatus{
Passed: passed,
Duration: totalDuration,
Message: message,
Details: map[string]interface{}{
"reads": readMetrics,
"writes": writeMetrics,
"consistency": consistencyMetrics,
},
}
}
// Cleanup performs cleanup after test
func (t *TranscodeTest) Cleanup(ctx context.Context) error {
client := t.validator.clients["global"]
prefix := fmt.Sprintf("%s/transcode/", t.validator.config.Prefix)
// List all objects with the transcode prefix
paginator := s3.NewListObjectsV2Paginator(client, &s3.ListObjectsV2Input{
Bucket: aws.String(t.validator.config.BucketName),
Prefix: aws.String(prefix),
})
var objectsToDelete []string
for paginator.HasMorePages() {
page, err := paginator.NextPage(ctx)
if err != nil {
return fmt.Errorf("failed to list objects: %w", err)
}
for _, obj := range page.Contents {
objectsToDelete = append(objectsToDelete, *obj.Key)
}
}
// Delete objects in batches
for i := 0; i < len(objectsToDelete); i += 100 {
end := i + 100
if end > len(objectsToDelete) {
end = len(objectsToDelete)
}
batch := objectsToDelete[i:end]
for _, key := range batch {
_, err := client.DeleteObject(ctx, &s3.DeleteObjectInput{
Bucket: aws.String(t.validator.config.BucketName),
Key: aws.String(key),
})
if err != nil {
return fmt.Errorf("failed to delete object %s: %w", key, err)
}
}
}
return nil
}
// runTranscodeSimulation simulates the transcoding workload
func (t *TranscodeTest) runTranscodeSimulation(ctx context.Context) (*TranscodeMetrics, *TranscodeMetrics, *ConsistencyMetrics) {
cfg := t.validator.config.TranscodeConfig
baseClient := t.validator.clients["global"]
// Create context with timeout
simCtx, cancel := context.WithTimeout(ctx, cfg.TestDuration)
defer cancel()
// Estimate operations per worker for pre-allocation
// Assume ~1 op/second per worker for duration = ~300 ops for 5 minutes
estimatedOpsPerWorker := int(cfg.TestDuration.Seconds())
var wg sync.WaitGroup
workerMetricsChan := make(chan *workerTranscodeMetrics, cfg.JobCount)
// Start worker jobs
for i := 0; i < cfg.JobCount; i++ {
wg.Add(1)
go func(jobID int) {
defer wg.Done()
// Create per-worker S3 client for isolated connection pool
workerClient := workload.CreateWorkerS3Client(baseClient)
ops := workload.NewS3Operations(workerClient, t.validator.config.BucketName, false, 0)
// Create per-worker RNG to avoid global lock contention
workerRng := rand.New(rand.NewSource(time.Now().UnixNano() + int64(jobID)))
// Per-worker metrics (no locks needed!)
localMetrics := &workerTranscodeMetrics{
readLatencies: make([]time.Duration, 0, estimatedOpsPerWorker),
readTTFBs: make([]time.Duration, 0, estimatedOpsPerWorker),
writeLatencies: make([]time.Duration, 0, estimatedOpsPerWorker),
consLatencies: make([]time.Duration, 0, estimatedOpsPerWorker),
}
for {
select {
case <-simCtx.Done():
// Send worker metrics to aggregation channel
workerMetricsChan <- localMetrics
return
default:
// Simulate encoder reading a chunk and writing output
// 1. Read a chunk from random source file (range GET)
sourceIdx := workerRng.Intn(cfg.SourceFileCount)
sourceKey := fmt.Sprintf("%s/transcode/sources/video-%03d.bin", t.validator.config.Prefix, sourceIdx)
// Calculate random offset within source file
maxOffset := cfg.SourceFileSize - cfg.ChunkSize
if maxOffset < 0 {
maxOffset = 0
}
startByte := workerRng.Int63n(maxOffset + 1)
endByte := startByte + cfg.ChunkSize - 1
// Create per-operation context with fixed timeout
// This ensures operations have sufficient time even near test end
readCtx, readCancel := context.WithTimeout(context.Background(), 2*time.Minute)
readResult := ops.GetObjectRange(readCtx, sourceKey, startByte, endByte)
readCancel()
// Collect metrics without locks
if readResult.Success {
localMetrics.readSuccess++
localMetrics.readLatencies = append(localMetrics.readLatencies, readResult.Duration)
localMetrics.readTTFBs = append(localMetrics.readTTFBs, readResult.TTFB)
} else {
localMetrics.readErrors++
if t.validator.config.Verbose {
fmt.Printf("[Job %d] Read failed: key=%s, range=%d-%d, error=%v\n",
jobID, sourceKey, startByte, endByte, readResult.Error)
}
}
// 2. Write output segment (small file)
segmentSize := cfg.SegmentSizeMin + workerRng.Int63n(cfg.SegmentSizeMax-cfg.SegmentSizeMin+1)
segmentData := make([]byte, segmentSize)
workerRng.Read(segmentData) // Use worker RNG, not global
outputKey := fmt.Sprintf("%s/transcode/outputs/video-%03d/segment-%d-%d.bin",
t.validator.config.Prefix, sourceIdx, jobID, time.Now().UnixNano())
// Create per-operation context with fixed timeout
writeCtx, writeCancel := context.WithTimeout(context.Background(), 2*time.Minute)
writeResult := ops.PutObject(writeCtx, outputKey, segmentData)
writeCancel()
// Collect metrics without locks
if writeResult.Success {
localMetrics.writeSuccess++
localMetrics.writeLatencies = append(localMetrics.writeLatencies, writeResult.Duration)
} else {
localMetrics.writeErrors++
if t.validator.config.Verbose {
fmt.Printf("[Job %d] Write failed: key=%s, size=%d, error=%v\n",
jobID, outputKey, segmentSize, writeResult.Error)
}
}
// 3. Read-after-write consistency check
if writeResult.Success {
// Create per-operation context with fixed timeout
consCtx, consCancel := context.WithTimeout(context.Background(), 2*time.Minute)
immediate, eventual, failed, convergenceTime := checkReadAfterWriteConsistency(consCtx, ops, outputKey)
consCancel()
if immediate {
localMetrics.consImmediate++
localMetrics.consLatencies = append(localMetrics.consLatencies, convergenceTime)
} else if eventual {
localMetrics.consEventual++
localMetrics.consLatencies = append(localMetrics.consLatencies, convergenceTime)
if t.validator.config.Verbose {
fmt.Printf("[Job %d] Eventual consistency: key=%s, convergence=%v\n",
jobID, outputKey, convergenceTime)
}
} else if failed {
localMetrics.consFailed++
if t.validator.config.Verbose {
fmt.Printf("[Job %d] Consistency check failed: key=%s (timeout)\n",
jobID, outputKey)
}
}
}
}
}
}(i)
}
wg.Wait()
close(workerMetricsChan)
// Aggregate metrics from all workers
readMetrics := &TranscodeMetrics{}
writeMetrics := &TranscodeMetrics{}
consistencyMetrics := &ConsistencyMetrics{}
// Estimate total capacity for pre-allocation
totalOps := estimatedOpsPerWorker * cfg.JobCount
readMetrics.Latencies = make([]time.Duration, 0, totalOps)
readMetrics.TTFBs = make([]time.Duration, 0, totalOps)
writeMetrics.Latencies = make([]time.Duration, 0, totalOps)
consistencyMetrics.Latencies = make([]time.Duration, 0, totalOps)
// Combine all worker metrics
for workerMetrics := range workerMetricsChan {
// Aggregate read metrics
readMetrics.SuccessOps += workerMetrics.readSuccess
readMetrics.ErrorOps += workerMetrics.readErrors
readMetrics.Latencies = append(readMetrics.Latencies, workerMetrics.readLatencies...)
readMetrics.TTFBs = append(readMetrics.TTFBs, workerMetrics.readTTFBs...)
// Aggregate write metrics
writeMetrics.SuccessOps += workerMetrics.writeSuccess
writeMetrics.ErrorOps += workerMetrics.writeErrors
writeMetrics.Latencies = append(writeMetrics.Latencies, workerMetrics.writeLatencies...)
// Aggregate consistency metrics
consistencyMetrics.ImmediateReads += workerMetrics.consImmediate
consistencyMetrics.EventualReads += workerMetrics.consEventual
consistencyMetrics.FailedReads += workerMetrics.consFailed
consistencyMetrics.TotalChecks += workerMetrics.consImmediate + workerMetrics.consEventual + workerMetrics.consFailed
consistencyMetrics.Latencies = append(consistencyMetrics.Latencies, workerMetrics.consLatencies...)
}
// Calculate statistics
t.calculateMetrics(readMetrics, cfg.TestDuration)
t.calculateMetrics(writeMetrics, cfg.TestDuration)
t.calculateConsistencyMetrics(consistencyMetrics)
return readMetrics, writeMetrics, consistencyMetrics
}
// calculateMetrics calculates statistics for transcode metrics
func (t *TranscodeTest) calculateMetrics(m *TranscodeMetrics, duration time.Duration) {
if len(m.Latencies) > 0 {
m.AvgLatency = average(m.Latencies)
m.P50Latency = percentile(m.Latencies, 0.50)
m.P95Latency = percentile(m.Latencies, 0.95)
m.P99Latency = percentile(m.Latencies, 0.99)
}
if len(m.TTFBs) > 0 {
m.AvgTTFB = average(m.TTFBs)
m.P50TTFB = percentile(m.TTFBs, 0.50)
m.P95TTFB = percentile(m.TTFBs, 0.95)
m.P99TTFB = percentile(m.TTFBs, 0.99)
}
if duration > 0 {
m.OpsPerSecond = float64(m.SuccessOps) / duration.Seconds()
}
}
// calculateConsistencyMetrics calculates consistency statistics
func (t *TranscodeTest) calculateConsistencyMetrics(m *ConsistencyMetrics) {
if len(m.Latencies) > 0 {
m.AvgLatency = average(m.Latencies)
m.P50Latency = percentile(m.Latencies, 0.50)
m.P95Latency = percentile(m.Latencies, 0.95)
m.P99Latency = percentile(m.Latencies, 0.99)
}
if m.TotalChecks > 0 {
m.TargetMetPercentage = float64(m.ImmediateReads) * 100.0 / float64(m.TotalChecks)
}
}
// displayResults displays the test results
func (t *TranscodeTest) displayResults(read, write *TranscodeMetrics, cons *ConsistencyMetrics) {
fmt.Printf("\n%sRead Operations (Range Requests, %s chunks):%s\n",
ColorBrightWhite, formatBytes(t.validator.config.TranscodeConfig.ChunkSize), ColorReset)
fmt.Printf(" Latency - %sAvg:%s %s, %sP50:%s %s, %sP95:%s %s, %sP99:%s %s\n",
ColorBrightWhite, ColorReset, formatDurationAligned(read.AvgLatency),
ColorBrightWhite, ColorReset, formatDurationAligned(read.P50Latency),
ColorBrightWhite, ColorReset, formatDurationAligned(read.P95Latency),
ColorBrightWhite, ColorReset, formatDurationAligned(read.P99Latency))
fmt.Printf(" TTFB - %sAvg:%s %s, %sP50:%s %s, %sP95:%s %s, %sP99:%s %s\n",
ColorBrightWhite, ColorReset, formatDurationAligned(read.AvgTTFB),
ColorBrightWhite, ColorReset, formatDurationAligned(read.P50TTFB),
ColorBrightWhite, ColorReset, formatDurationAligned(read.P95TTFB),
ColorBrightWhite, ColorReset, formatDurationAligned(read.P99TTFB))
// Calculate bandwidth for read operations in Gbps
readBandwidthBytes := read.OpsPerSecond * float64(t.validator.config.TranscodeConfig.ChunkSize)
readBandwidthGbps := (readBandwidthBytes * 8) / 1_000_000_000
fmt.Printf(" Throughput - %s%.2f ops/s (%.2f Gbps)%s | %s%d success%s",
ColorBrightWhite, read.OpsPerSecond, readBandwidthGbps, ColorReset,
ColorBrightGreen, read.SuccessOps, ColorReset)
if read.ErrorOps > 0 {
fmt.Printf(", %s%d failed%s", ColorBrightRed, read.ErrorOps, ColorReset)
}
fmt.Printf("\n")
fmt.Printf("\n%sWrite Operations (Output Segments, %s - %s):%s\n",
ColorBrightWhite,
formatBytes(t.validator.config.TranscodeConfig.SegmentSizeMin),
formatBytes(t.validator.config.TranscodeConfig.SegmentSizeMax),
ColorReset)
fmt.Printf(" Latency - %sAvg:%s %s, %sP50:%s %s, %sP95:%s %s, %sP99:%s %s\n",
ColorBrightWhite, ColorReset, formatDurationAligned(write.AvgLatency),
ColorBrightWhite, ColorReset, formatDurationAligned(write.P50Latency),
ColorBrightWhite, ColorReset, formatDurationAligned(write.P95Latency),
ColorBrightWhite, ColorReset, formatDurationAligned(write.P99Latency))
// Calculate average write size and bandwidth in Gbps
avgWriteSize := (t.validator.config.TranscodeConfig.SegmentSizeMin + t.validator.config.TranscodeConfig.SegmentSizeMax) / 2
writeBandwidthBytes := write.OpsPerSecond * float64(avgWriteSize)
writeBandwidthGbps := (writeBandwidthBytes * 8) / 1_000_000_000
fmt.Printf(" Throughput - %s%.2f ops/s (%.2f Gbps)%s | %s%d success%s",
ColorBrightWhite, write.OpsPerSecond, writeBandwidthGbps, ColorReset,
ColorBrightGreen, write.SuccessOps, ColorReset)
if write.ErrorOps > 0 {
fmt.Printf(", %s%d failed%s", ColorBrightRed, write.ErrorOps, ColorReset)
}
fmt.Printf("\n")
fmt.Printf("\n%sRead-After-Write Consistency:%s\n", ColorBrightWhite, ColorReset)
fmt.Printf(" Convergence - %sAvg:%s %s, %sP50:%s %s, %sP95:%s %s, %sP99:%s %s\n",
ColorBrightWhite, ColorReset, formatDurationAligned(cons.AvgLatency),
ColorBrightWhite, ColorReset, formatDurationAligned(cons.P50Latency),
ColorBrightWhite, ColorReset, formatDurationAligned(cons.P95Latency),
ColorBrightWhite, ColorReset, formatDurationAligned(cons.P99Latency))
immediatePercent := 0.0
eventualPercent := 0.0
failedPercent := 0.0
if cons.TotalChecks > 0 {
immediatePercent = float64(cons.ImmediateReads) * 100.0 / float64(cons.TotalChecks)
eventualPercent = float64(cons.EventualReads) * 100.0 / float64(cons.TotalChecks)
failedPercent = float64(cons.FailedReads) * 100.0 / float64(cons.TotalChecks)
}
fmt.Printf(" Distribution - Immediate (<200ms): %5.1f%%, Eventual (>200ms): %5.1f%%, Failed: %5.1f%%\n",
immediatePercent, eventualPercent, failedPercent)
targetColor := ColorBrightGreen
if cons.TargetMetPercentage < 95.0 {
targetColor = ColorBrightRed
}
fmt.Printf(" Target (<200ms): %s%.1f%% within target%s\n",
targetColor, cons.TargetMetPercentage, ColorReset)
}
// checkReadAfterWriteConsistency performs a read-after-write consistency check
// Returns: (immediate bool, eventual bool, failed bool, convergenceTime time.Duration)
func checkReadAfterWriteConsistency(ctx context.Context, ops *workload.S3Operations, key string) (bool, bool, bool, time.Duration) {
const (
maxRetries = 600
retryInterval = 100 * time.Millisecond
maxWaitDuration = 1 * time.Minute
)
startTime := time.Now()
attempts := 0
// Retry until object is readable or timeout
for attempts < maxRetries {
readBackResult := ops.GetObject(ctx, key)
if readBackResult.Success {
// Object read successfully
convergenceTime := time.Duration(attempts) * retryInterval
if attempts == 0 {
// Immediate consistency - success on first try
return true, false, false, convergenceTime
}
// Eventual consistency - success after retries
return false, true, false, convergenceTime
}
// Check if we've exceeded max wait time
if time.Since(startTime) > maxWaitDuration {
break
}
attempts++
time.Sleep(retryInterval)
}
// Timeout or max retries exceeded
return false, false, true, 0
}