-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstreaming_test.go
728 lines (581 loc) · 19.3 KB
/
streaming_test.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
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
package rpc25519
import (
"context"
"fmt"
"io"
"sync"
//"net/http"
"os"
filepath "path/filepath"
"strconv"
//"strings"
//"sync"
"testing"
"time"
//tdigest "github.com/caio/go-tdigest"
"github.com/glycerine/loquet"
myblake3 "github.com/glycerine/rpc25519/hash"
cv "github.com/glycerine/goconvey/convey"
"github.com/glycerine/rpc25519/progress"
)
// 2025 Jan 15 Note: why are there immediate returns after
// these streaming tests start?
//
// Good question! These are highly useful,
// functioning, and complete tests. However
// they can use alot of memory, and blow
// out the memory on small boxes, causing
// OOMs and misleading test failures. Hence I have
// disabled these tests by manually inserting
// a very early return along with a
// reminder. Turn them on if you need them;
// they are great; just very memory hungry
// for building/running on smaller Virtual machines.
// Thanks for reading!
// go test -v -run streaming_test ## to run all 3 tests below.
func Test300_upload_streaming_test_of_large_file(t *testing.T) {
vv("Heya! This test was not run to keep test memory use low.")
return
cv.Convey("before we add compression, we want to test the cli -sendfile (upload) against he srv -readfile, the corresponding server side operation. Test300 is for upload of a file (multiple parts bigger than our max Message size.", t, func() {
// set up server and client.
// start with server
cfg := NewConfig()
cfg.ServerAddr = "127.0.0.1:0"
srv := NewServer("srv_test300", cfg)
serverAddr, err := srv.Start()
panicOn(err)
defer srv.Close()
streamer := NewServerSideUploadState()
// use the example.go example.
fileUploaderServiceName := "__fileUploader"
srv.RegisterUploadReaderFunc(fileUploaderServiceName,
streamer.ReceiveFileInParts)
// client
cfg.ClientDialToHostPort = serverAddr.String()
cli, err := NewClient("cli_test300", cfg)
panicOn(err)
err = cli.Start()
panicOn(err)
defer cli.Close()
// end standard setup of server and client.
// upload a blob from testdata/ directory.
path := "testdata/blob977k"
pathOut := "blob977k.servergot"
os.Remove(pathOut)
if !fileExists(path) {
panic(fmt.Sprintf("drat! cli -sendfile path '%v' not found", path))
}
fi, err := os.Stat(path)
panicOn(err)
pathsize := fi.Size()
meterUp := progress.NewTransferStats(pathsize, "[up]"+filepath.Base(path))
t0 := time.Now()
r, err := os.Open(path)
if err != nil {
panic(fmt.Sprintf("error reading path '%v': '%v'", path, err))
}
ctx, cancelFunc := context.WithCancel(context.Background())
defer cancelFunc()
// wait to initialize the Uploader until we
// actually have data to send.
var strm *Uploader
blake3hash := myblake3.NewBlake3()
// much smoother progress display waiting for 1MB rather than 64MB
//maxMessage := 1024 * 1024
//maxMessage := UserMaxPayload
// chunk smaller than we would for production,
// so our testdata/blob can be small,
// while we still test multiple chunk streaming.
maxMessage := 1024
buf := make([]byte, maxMessage)
var tot int
req := NewMessage()
req.HDR.Created = time.Now()
req.HDR.Args["pathsize"] = fmt.Sprintf("%v", pathsize)
var lastUpdate time.Time
// check for errors
var checkForErrors = func() *Message {
if strm != nil {
//vv("checking strm (sendfile) chan for error: %p; callID='%v'", strm.ErrorCh, strm.CallID())
select {
case errMsg := <-strm.ErrorCh:
vv("error for sendfile: '%v'", err)
return errMsg
default:
}
}
return nil
}
i := 0
upload:
for i = 0; true; i++ {
if err := checkForErrors(); err != nil {
alwaysPrintf("error: '%v'", err.String())
panic(err)
break upload
}
nr, err1 := r.Read(buf)
//vv("on read i=%v, got nr=%v, (maxMessage=%v), err='%v'", i, nr, maxMessage, err1)
send := buf[:nr] // can be empty
tot += nr
sumstring := myblake3.Blake3OfBytesString(send)
//vv("i=%v, len=%v, sumstring = '%v'", i, nr, sumstring)
blake3hash.Write(send)
if i == 0 {
// must copy!
req.JobSerz = append([]byte{}, send...)
filename := filepath.Base(path)
req.HDR.Args = map[string]string{"readFile": filename, "blake3": sumstring}
strm, err = cli.UploadBegin(ctx, fileUploaderServiceName, req, 0)
panicOn(err)
if err1 == io.EOF {
break upload
}
panicOn(err1)
continue
}
streamMsg := NewMessage()
// must copy!
streamMsg.JobSerz = append([]byte{}, send...)
streamMsg.HDR.Args = map[string]string{"blake3": sumstring}
err = strm.UploadMore(ctx, streamMsg, err1 == io.EOF, 0)
// likely just "shutting down", so ask for details.
if err != nil {
err2msg := checkForErrors()
if err2msg != nil {
alwaysPrintf("err: '%v'", err)
alwaysPrintf("err2: '%v'", err2msg.String())
}
panicOn(err)
break upload
}
if time.Since(lastUpdate) > time.Second {
meterUp.DoProgressWithSpeed(int64(tot), false, int64(i))
lastUpdate = time.Now()
}
if err1 == io.EOF {
break upload
}
panicOn(err1)
} // end for i
nparts := i
meterUp.DoProgressWithSpeed(int64(tot), false, int64(i))
clientTotSum := blake3hash.SumString()
fmt.Println()
reportUploadTime := true
if reportUploadTime {
elap := time.Since(t0)
mb := float64(tot) / float64(1<<20)
seconds := (float64(elap) / float64(time.Second))
rate := mb / seconds
alwaysPrintf("upload part of echo done elapsed: %v \n we "+
"uploaded tot = %v bytes (=> %0.6f MB/sec) in %v parts",
elap, tot, rate, nparts)
}
select {
case errMsg := <-strm.ErrorCh:
alwaysPrintf("errMsg: '%v'", errMsg.String())
panic(errMsg)
case reply := <-strm.ReadCh:
if false {
report := string(reply.JobSerz)
vv("reply.HDR: '%v'", reply.HDR.String())
vv("with JobSerz: '%v'", report)
}
fmt.Printf("total time for upload: '%v'\n", time.Since(t0))
fmt.Printf("file size: %v bytes.\n", formatUnder(tot)) // , clientTotSum)
serverTotSum := reply.HDR.Args["serverTotalBlake3sum"]
if clientTotSum == serverTotSum {
vv("GOOD! server and client blake3 checksums are the same!\n serverTotSum='%v'\n clientTotsum='%v'", serverTotSum, clientTotSum)
cv.So(true, cv.ShouldBeTrue)
} else {
vv("PROBLEM! server and client blake3 checksums do not match!\n serverTotSum='%v'\n clientTotsum='%v'", serverTotSum, clientTotSum)
panic("checksum mismatch!")
}
case <-time.After(time.Minute):
panic("should have gotten a reply from the server finishing the stream.")
}
// final result: did we get the file uploaded the same?
diff := compareFilesDiffLen(path, pathOut)
cv.So(diff, cv.ShouldEqual, 0)
if diff == 0 {
// cleanup
os.Remove(pathOut)
}
})
}
func Test301_download_streaming_test(t *testing.T) {
vv("Heya! This test was not run to keep test memory use low.")
return
cv.Convey("before we add compression, test cli -download vs srv -serve are the corresponding server side operations. Test301 is for download of a file (multiple parts)", t, func() {
// set up server and client.
// start with server
cfg := NewConfig()
cfg.ServerAddr = "127.0.0.1:0"
srv := NewServer("srv_test301", cfg)
serverAddr, err := srv.Start()
panicOn(err)
defer srv.Close()
// serve downloads
downloaderName := "__downloaderName" // must match client.go:163
ssss := NewServerSendsDownloadState()
srv.RegisterServerSendsDownloadFunc(downloaderName, ssss.ServerSendsDownload)
// client
cfg.ClientDialToHostPort = serverAddr.String()
cli, err := NewClient("cli_test301", cfg)
panicOn(err)
err = cli.Start()
panicOn(err)
defer cli.Close()
// end standard setup of server and client.
// download a blob from testdata/ directory.
path := "testdata/blob977k"
downloadFile := path + ".downloaded"
observedOutfile := path + ".downloaded.download_client_got"
os.Remove(downloadFile)
os.Remove(observedOutfile)
t0 := time.Now()
var meterDown *progress.TransferStats
ctx := context.Background()
downloader, err := cli.NewDownloader(ctx, downloaderName)
panicOn(err)
defer downloader.Close()
s := NewPerCallID_FileToDiskState(downloader.CallID())
s.OverrideFilename = downloadFile
//vv("downloader.CallID() = '%v'", downloader.CallID())
meterDownQuiet := false
lastUpdate := time.Now()
netread := 0 // net count of bytes read off the network.
err = downloader.BeginDownload(ctx, path)
panicOn(err)
maxPayloadSeen := 0
partsloop:
for part := int64(0); true; part++ {
select {
case <-ctx.Done():
vv("download aborting: context cancelled")
break partsloop
case req := <-downloader.ReadDownloadsCh:
//vv("cli downloader downloadsCh sees %v", req.String())
sz0 := len(req.JobSerz)
netread += sz0
if sz0 > maxPayloadSeen {
maxPayloadSeen = sz0
}
if req.HDR.Typ == CallRPCReply {
vv("cli downloader downloadsCh sees CallRPCReply, exiting")
break partsloop
}
if req.HDR.StreamPart != part {
panic(fmt.Sprintf("%v = req.HDR.StreamPart != part = %v",
req.HDR.StreamPart, part))
}
if part == 0 {
sz, ok := req.HDR.Args["pathsize"]
if !ok {
panic("server did not send of the pathsize in the first part!")
}
szi, err := strconv.Atoi(sz)
pathsize := int64(szi)
panicOn(err)
vv("got 1st download part: %v bytes after %v; can meter total %v bytes:", sz0, time.Since(t0), formatUnder(int(pathsize)))
meterDown = progress.NewTransferStats(
pathsize, "[dn]"+filepath.Base(path))
}
if time.Since(lastUpdate) > time.Second {
meterDown.DoProgressWithSpeed(int64(netread), meterDownQuiet, req.HDR.StreamPart)
lastUpdate = time.Now()
}
last := (req.HDR.Typ == CallDownloadEnd)
// this writes our req.JobSerz to disk.
err = s.WriteOneMsgToFile(req, "download_client_got", last)
if err != nil {
panic(err)
break partsloop
}
if last {
if int(s.BytesWrit) != netread {
panic(fmt.Sprintf("%v = s.BytesWrit != netread = %v", s.BytesWrit, netread))
}
//totSum := "blake3-" + cristalbase64.URLEncoding.EncodeToString(s.Blake3hash.Sum(nil))
////vv("ReceiveFileInParts sees last set!")
//vv("bytesWrit=%v; \nserver totSum='%v'", s.BytesWrit, totSum)
elap := time.Since(s.T0)
mb := float64(s.BytesWrit) / float64(1<<20)
seconds := (float64(elap) / float64(time.Second))
rate := mb / seconds
_ = rate
fmt.Println()
fmt.Printf("total time for download: '%v'\n", time.Since(s.T0))
fmt.Printf("file size: %v bytes.\n", formatUnder(int(s.BytesWrit)))
fmt.Printf("rate: %0.6f MB/sec. Used %v parts of max size %v bytes\n", rate, part+1, maxPayloadSeen)
} // end if last
} //end select
} // end for part loop
diff := compareFilesDiffLen(path, observedOutfile)
cv.So(diff, cv.ShouldEqual, 0)
if diff == 0 {
// cleanup
os.Remove(observedOutfile)
}
})
}
func Test302_bistreaming_test_simultaneous_upload_and_download(t *testing.T) {
vv("Heya! This test was not run to keep test memory use low.")
return
cv.Convey("before we add compression, test bistreaming: cli -echofile vs srv -echo;. Test302 is for bistreaming (simultaneous upload and download of files bigger than max Message size)", t, func() {
// set up server and client.
// start with server
cfg := NewConfig()
cfg.ServerAddr = "127.0.0.1:0"
srv := NewServer("srv_test301", cfg)
serverAddr, err := srv.Start()
panicOn(err)
defer srv.Close()
// serve bistreams
streamerName := "echoBistreamFunc"
// EchoBistreamFunc in example.go has most of the implementation.
srv.RegisterBistreamFunc(streamerName, EchoBistreamFunc)
// client
cfg.ClientDialToHostPort = serverAddr.String()
cli, err := NewClient("cli_test301", cfg)
panicOn(err)
err = cli.Start()
panicOn(err)
defer cli.Close()
// end standard setup of server and client.
// download a blob from testdata/ directory.
//path := "testdata/blob977k"
path := "testdata/blob3m"
observedOutfile := path + ".echoed.echoclientgot"
os.Remove(observedOutfile)
t0 := time.Now()
var bistream *Bistreamer
var wg sync.WaitGroup
bistreamerName := "echoBistreamFunc"
meterDownQuietCh := make(chan bool, 2)
meterDownQuietCh <- true
uploadDone := loquet.NewChan[bool](nil)
var meterDown *progress.TransferStats
// ============================================
//
// begin bistream part: download in parallel,
// on a background goroutine.
//
// ============================================
fi, err := os.Stat(path)
panicOn(err)
meterDown = progress.NewTransferStats(fi.Size(), "[dn]"+filepath.Base(path))
// Approach:
// have the echofile implementation do the upload for us,
// while we do the download in a separate goroutine.
downloadFile := path + ".echoed"
bistream, err = cli.NewBistreamer(bistreamerName)
panicOn(err)
defer bistream.Close()
s := NewPerCallID_FileToDiskState(bistream.CallID())
s.OverrideFilename = downloadFile
//vv("bistream.CallID() = '%v'", bistream.CallID())
wg.Add(1)
go func() {
defer wg.Done()
meterDownQuiet := true
lastUpdate := time.Now()
netread := 0 // net count of bytes read off the network.
whenUploadDone := uploadDone.WhenClosed()
for {
select {
case <-whenUploadDone:
vv("upload done, down has read: %v bytes", netread)
whenUploadDone = nil
case meterDownQuiet = <-meterDownQuietCh:
case req := <-bistream.ReadDownloadsCh:
//vv("cli bistream downloadsCh sees %v", req.String())
sz := len(req.JobSerz)
if netread == 0 {
vv("downloaded %v bytes after %v", sz, time.Since(t0))
}
netread += sz
if req.HDR.Typ == CallRPCReply {
//vv("cli bistream downloadsCh sees CallRPCReply, exiting goro")
return
}
if time.Since(lastUpdate) > time.Second {
meterDown.DoProgressWithSpeed(int64(netread), meterDownQuiet, req.HDR.StreamPart)
lastUpdate = time.Now()
}
last := (req.HDR.Typ == CallDownloadEnd)
// cannot use err here or race detector will fire! use err2.
err2 := s.WriteOneMsgToFile(req, "echoclientgot", last)
if err2 != nil {
panic(err2)
return
}
if last {
//totSum := "blake3-" + cristalbase64.URLEncoding.EncodeToString(s.Blake3hash.Sum(nil))
////vv("ReceiveFileInParts sees last set!")
//vv("bytesWrit=%v; \nserver totSum='%v'", s.BytesWrit, totSum)
elap := time.Since(s.T0)
mb := float64(s.BytesWrit) / float64(1<<20)
seconds := (float64(elap) / float64(time.Second))
rate := mb / seconds
_ = rate
fmt.Println()
fmt.Printf("total time for echo: '%v'\n", time.Since(s.T0))
fmt.Printf("file size: %v bytes.\n", formatUnder(int(s.BytesWrit)))
} // end if last
} //end select
} // end for seenCount
}()
// ===========================
// end bistream download part.
// ===========================
// ==========================================
//
// begin sendfile part: upload in parallel
// with the above download.
//
// ==========================================
if !fileExists(path) {
panic(fmt.Sprintf("drat! cli -sendfile path '%v' not found", path))
}
fi, err = os.Stat(path)
panicOn(err)
pathsize := fi.Size()
meterUp := progress.NewTransferStats(pathsize, "[up]"+filepath.Base(path))
r, err := os.Open(path)
if err != nil {
panic(fmt.Sprintf("error reading path '%v': '%v'", path, err))
}
ctx, cancelFunc := context.WithCancel(context.Background())
defer cancelFunc()
// wait to initialize the Uploader until we
// actually have data to send.
var strm *Uploader
blake3hash := myblake3.NewBlake3()
// much smoother progress display waiting for 1MB rather than 64MB
maxMessage := 1024 * 1024
//maxMessage := UserMaxPayload
//maxMessage := 1024
buf := make([]byte, maxMessage)
var tot int
req := NewMessage()
req.HDR.Created = time.Now()
req.HDR.Args["pathsize"] = fmt.Sprintf("%v", pathsize)
var lastUpdate time.Time
// check for errors
var checkForErrors = func() *Message {
if strm != nil {
//vv("checking strm (sendfile) chan for error: %p; callID='%v'", strm.ErrorCh, strm.CallID())
select {
case errMsg := <-strm.ErrorCh:
vv("error for sendfile: '%v'", err)
return errMsg
default:
}
}
if bistream != nil {
//vv("checking bistream (echofile) chan for error: %p; callID='%v'", bistream.ErrorCh, bistream.CallID())
select {
case errMsg := <-bistream.ErrorCh:
vv("error from echofile: '%v'", err)
return errMsg
default:
}
}
return nil
}
i := 0
upload:
for i = 0; true; i++ {
if err := checkForErrors(); err != nil {
alwaysPrintf("error: '%v'", err.String())
return
}
nr, err1 := r.Read(buf)
//vv("on read i=%v, got nr=%v, (maxMessage=%v), err='%v'", i, nr, maxMessage, err1)
send := buf[:nr] // can be empty
tot += nr
sumstring := myblake3.Blake3OfBytesString(send)
//vv("i=%v, len=%v, sumstring = '%v'", i, nr, sumstring)
blake3hash.Write(send)
if i == 0 {
// must copy!
req.JobSerz = append([]byte{}, send...)
filename := filepath.Base(path)
req.HDR.Args = map[string]string{"readFile": filename, "blake3": sumstring}
//vv("client about to do bistream.Begin(); req = '%v'", req.String())
err = bistream.Begin(ctx, req)
panicOn(err)
if err1 == io.EOF {
uploadDone.Close()
break upload
}
panicOn(err1)
continue
}
streamMsg := NewMessage()
// must copy!
streamMsg.JobSerz = append([]byte{}, send...)
streamMsg.HDR.Args = map[string]string{"blake3": sumstring}
err = bistream.UploadMore(ctx, streamMsg, err1 == io.EOF, 0)
// likely just "shutting down", so ask for details.
if err != nil {
err2msg := checkForErrors()
if err2msg != nil {
alwaysPrintf("err: '%v'", err)
alwaysPrintf("err2: '%v'", err2msg.String())
}
panicOn(err)
return
}
if time.Since(lastUpdate) > time.Second {
meterUp.DoProgressWithSpeed(int64(tot), false, int64(i))
lastUpdate = time.Now()
}
if err1 == io.EOF {
uploadDone.Close()
break upload
}
panicOn(err1)
} // end for i
nparts := i
meterUp.DoProgressWithSpeed(int64(tot), false, int64(i))
//clientTotSum := blake3hash.SumString()
fmt.Println()
reportUploadTime := true
if reportUploadTime {
elap := time.Since(t0)
mb := float64(tot) / float64(1<<20)
seconds := (float64(elap) / float64(time.Second))
rate := mb / seconds
alwaysPrintf("upload part of echo done elapsed: %v \n we "+
"uploaded tot = %v bytes (=> %0.6f MB/sec) in %v parts",
elap, tot, rate, nparts)
}
fmt.Println()
meterDownQuietCh <- false // show the download progress
//vv("bistream about to wait")
wg.Wait()
reportRoundTripTime := true
if reportRoundTripTime {
elap := time.Since(t0)
mb := float64(2*tot) / float64(1<<20)
seconds := (float64(elap) / float64(time.Second))
rate := mb / seconds
alwaysPrintf("round-trip echo done elapsed: %v; we "+
"transferred 2*tot = %v bytes (=> %0.6f MB/sec)", elap, 2*tot, rate)
}
//vv("past Wait, client upload tot-sum='%v'", clientTotSum)
// the goro consumed the CallRPCReply to know when to
// exit, and we get here because when the goro exists, the
// wait is done. so there won't be any more bistream messages coming.
// end sendfile part.
diff := compareFilesDiffLen(path, observedOutfile)
cv.So(diff, cv.ShouldEqual, 0)
if diff == 0 {
// cleanup
os.Remove(observedOutfile)
}
})
}