File: progress_roundtripper.go

package info (click to toggle)
singularity-container 4.0.3%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 21,672 kB
  • sloc: asm: 3,857; sh: 2,125; ansic: 1,677; awk: 414; makefile: 110; python: 99
file content (70 lines) | stat: -rw-r--r-- 1,482 bytes parent folder | download
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
// Copyright (c) 2023, Sylabs Inc. All rights reserved.
// This software is licensed under a 3-clause BSD license. Please consult the
// LICENSE.md file distributed with the sources of this project regarding your
// rights to use or distribute this software.

package progress

import (
	"io"
	"net/http"
)

const contentSizeThreshold = 1024

type RoundTripper struct {
	inner http.RoundTripper
	pb    *DownloadBar
}

func NewRoundTripper(inner http.RoundTripper, pb *DownloadBar) *RoundTripper {
	if inner == nil {
		inner = http.DefaultTransport
	}

	rt := RoundTripper{
		inner: inner,
		pb:    pb,
	}

	return &rt
}

type rtReadCloser struct {
	inner io.ReadCloser
	pb    *DownloadBar
}

func (r *rtReadCloser) Read(p []byte) (int, error) {
	return r.inner.Read(p)
}

func (r *rtReadCloser) Close() error {
	err := r.inner.Close()
	if err == nil {
		r.pb.Wait()
	} else {
		r.pb.Abort(false)
	}

	return err
}

func (t *RoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
	if t.pb != nil && req.Body != nil && req.ContentLength >= contentSizeThreshold {
		t.pb.Init(req.ContentLength)
		req.Body = &rtReadCloser{
			inner: t.pb.bar.ProxyReader(req.Body),
			pb:    t.pb,
		}
	}
	resp, err := t.inner.RoundTrip(req)
	if t.pb != nil && resp != nil && resp.Body != nil && resp.ContentLength >= contentSizeThreshold {
		t.pb.Init(resp.ContentLength)
		resp.Body = &rtReadCloser{
			inner: t.pb.bar.ProxyReader(resp.Body),
			pb:    t.pb,
		}
	}
	return resp, err
}