Debian Codegraph @

tq/adapterbase.go

raw symbols SCIP
1 package tq
2
3 import (
4 "net/http"
5 "regexp"
6 "strings"
7 "sync"
8
9 "github.com/git-lfs/git-lfs/v3/errors"
10 "github.com/git-lfs/git-lfs/v3/fs"
11 "github.com/git-lfs/git-lfs/v3/lfsapi"
12 "github.com/git-lfs/git-lfs/v3/tr"
13 "github.com/rubyist/tracerx"
14 )
15
16 // adapterBase implements the common functionality for core adapters which
17 // process transfers with N workers handling an oid each, and which wait for
18 // authentication to succeed on one worker before proceeding
19 type adapterBase struct {
20 fs *fs.Filesystem
21 name string
22 direction Direction
23 transferImpl transferImplementation
24 apiClient *lfsapi.Client
25 remote string
26 jobChan chan *job
27 debugging bool
28 cb ProgressCallback
29 // WaitGroup to sync the completion of all workers
30 workerWait sync.WaitGroup
31 // WaitGroup to sync the completion of all in-flight jobs
32 jobWait *sync.WaitGroup
33 // WaitGroup to serialise the first transfer response to perform login if needed
34 authWait sync.WaitGroup
35 }
36
37 // transferImplementation must be implemented to provide the actual upload/download
38 // implementation for all core transfer approaches that use adapterBase for
39 // convenience. This function will be called on multiple goroutines so it
40 // must be either stateless or thread safe. However it will never be called
41 // for the same oid in parallel.
42 // If authOkFunc is not nil, implementations must call it as early as possible
43 // when authentication succeeded, before the whole file content is transferred
44 type transferImplementation interface {
45 // WorkerStarting is called when a worker goroutine starts to process jobs
46 // Implementations can run some startup logic here & return some context if needed
47 WorkerStarting(workerNum int) (interface{}, error)
48 // WorkerEnding is called when a worker goroutine is shutting down
49 // Implementations can clean up per-worker resources here, context is as returned from WorkerStarting
50 WorkerEnding(workerNum int, ctx interface{})
51 // DoTransfer performs a single transfer within a worker. ctx is any context returned from WorkerStarting
52 DoTransfer(ctx interface{}, t *Transfer, cb ProgressCallback, authOkFunc func()) error
53 }
54
55 const (
56 enableHrefRewriteKey = "lfs.transfer.enablehrefrewrite"
57 defaultEnableHrefRewrite = false
58 )
59
60 func newAdapterBase(f *fs.Filesystem, name string, dir Direction, ti transferImplementation) *adapterBase {
61 return &adapterBase{
62 fs: f,
63 name: name,
64 direction: dir,
65 transferImpl: ti,
66 jobWait: new(sync.WaitGroup),
67 }
68 }
69
70 func (a *adapterBase) Name() string {
71 return a.name
72 }
73
74 func (a *adapterBase) Direction() Direction {
75 return a.direction
76 }
77
78 func (a *adapterBase) Begin(cfg AdapterConfig, cb ProgressCallback) error {
79 a.apiClient = cfg.APIClient()
80 a.remote = cfg.Remote()
81 a.cb = cb
82 a.jobChan = make(chan *job, 100)
83 a.debugging = a.apiClient.OSEnv().Bool("GIT_TRANSFER_TRACE", false) ||
84 a.apiClient.OSEnv().Bool("GIT_CURL_VERBOSE", false)
85 maxConcurrency := cfg.ConcurrentTransfers()
86
87 a.Trace("xfer: adapter %q Begin() with %d workers", a.Name(), maxConcurrency)
88
89 a.workerWait.Add(maxConcurrency)
90 a.authWait.Add(1)
91 for i := 0; i < maxConcurrency; i++ {
92 ctx, err := a.transferImpl.WorkerStarting(i)
93 if err != nil {
94 return err
95 }
96 go a.worker(i, ctx)
97 }
98 a.Trace("xfer: adapter %q started", a.Name())
99 return nil
100 }
101
102 type job struct {
103 T *Transfer
104
105 results chan<- TransferResult
106 wg *sync.WaitGroup
107 }
108
109 func (j *job) Done(err error) {
110 j.results <- TransferResult{j.T, err}
111 j.wg.Done()
112 }
113
114 func (a *adapterBase) Add(transfers ...*Transfer) <-chan TransferResult {
115 results := make(chan TransferResult, len(transfers))
116
117 a.jobWait.Add(len(transfers))
118
119 go func() {
120 for _, t := range transfers {
121 a.jobChan <- &job{t, results, a.jobWait}
122 }
123 a.jobWait.Wait()
124
125 close(results)
126 }()
127
128 return results
129 }
130
131 func (a *adapterBase) End() {
132 a.Trace("xfer: adapter %q End()", a.Name())
133
134 a.jobWait.Wait()
135 close(a.jobChan)
136
137 // wait for all transfers to complete
138 a.workerWait.Wait()
139
140 a.Trace("xfer: adapter %q stopped", a.Name())
141 }
142
143 func (a *adapterBase) Trace(format string, args ...interface{}) {
144 if !a.debugging {
145 return
146 }
147 tracerx.Printf(format, args...)
148 }
149
150 // worker function, many of these run per adapter
151 func (a *adapterBase) worker(workerNum int, ctx interface{}) {
152 a.Trace("xfer: adapter %q worker %d starting", a.Name(), workerNum)
153 waitForAuth := workerNum > 0
154 signalAuthOnResponse := workerNum == 0
155
156 // First worker is the only one allowed to start immediately
157 // The rest wait until successful response from 1st worker to
158 // make sure only 1 login prompt is presented if necessary
159 // Deliberately outside jobChan processing so we know worker 0 will process 1st item
160 if waitForAuth {
161 a.Trace("xfer: adapter %q worker %d waiting for Auth", a.Name(), workerNum)
162 a.authWait.Wait()
163 a.Trace("xfer: adapter %q worker %d auth signal received", a.Name(), workerNum)
164 }
165
166 for job := range a.jobChan {
167 t := job.T
168
169 var authCallback func()
170 if signalAuthOnResponse {
171 authCallback = func() {
172 a.authWait.Done()
173 signalAuthOnResponse = false
174 }
175 }
176 a.Trace("xfer: adapter %q worker %d processing job for %q", a.Name(), workerNum, t.Oid)
177
178 // Actual transfer happens here
179 var err error
180 if t.Size < 0 {
181 err = errors.New(tr.Tr.Get("object %q has invalid size (got: %d)", t.Oid, t.Size))
182 } else {
183 err = a.transferImpl.DoTransfer(ctx, t, a.cb, authCallback)
184 }
185
186 // Mark the job as completed, and alter all listeners
187 job.Done(err)
188
189 a.Trace("xfer: adapter %q worker %d finished job for %q", a.Name(), workerNum, t.Oid)
190 }
191 // This will only happen if no jobs were submitted; just wake up all workers to finish
192 if signalAuthOnResponse {
193 a.authWait.Done()
194 }
195 a.Trace("xfer: adapter %q worker %d stopping", a.Name(), workerNum)
196 a.transferImpl.WorkerEnding(workerNum, ctx)
197 a.workerWait.Done()
198 }
199
200 var httpRE = regexp.MustCompile(`\Ahttps?://`)
201
202 func (a *adapterBase) newHTTPRequest(method string, rel *Action) (*http.Request, error) {
203 enableRewrite := a.apiClient.GitEnv().Bool(enableHrefRewriteKey, defaultEnableHrefRewrite)
204
205 href := rel.Href
206 if enableRewrite {
207 href = a.apiClient.Endpoints.NewEndpoint(a.direction.String(), rel.Href).Url
208 }
209
210 if !httpRE.MatchString(href) {
211 urlfragment := strings.SplitN(href, "?", 2)[0]
212 return nil, errors.New(tr.Tr.Get("missing protocol: %q", urlfragment))
213 }
214
215 req, err := http.NewRequest(method, href, nil)
216 if err != nil {
217 return nil, err
218 }
219
220 for key, value := range rel.Header {
221 req.Header.Set(key, value)
222 }
223
224 return req, nil
225 }
226
227 func (a *adapterBase) doHTTP(t *Transfer, req *http.Request) (*http.Response, error) {
228 if t.Authenticated {
229 return a.apiClient.Do(req)
230 }
231 endpoint := endpointURL(req.URL.String(), t.Oid)
232 return a.apiClient.DoWithAuthNoRetry(a.remote, a.apiClient.Endpoints.AccessFor(endpoint), req)
233 }
234
235 func advanceCallbackProgress(cb ProgressCallback, t *Transfer, numBytes int64) {
236 if cb != nil {
237 // Must split into max int sizes since read count is int
238 const maxInt = int(^uint(0) >> 1)
239 for read := int64(0); read < numBytes; {
240 remainder := numBytes - read
241 if remainder > int64(maxInt) {
242 read += int64(maxInt)
243 cb(t.Name, t.Size, read, maxInt)
244 } else {
245 read += remainder
246 cb(t.Name, t.Size, read, int(remainder))
247 }
248
249 }
250 }
251 }
252
253 func endpointURL(rawurl, oid string) string {
254 return strings.Split(rawurl, oid)[0]
255 }