gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package lfs
  4. import (
  5. "bytes"
  6. "context"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "net/http"
  11. "net/url"
  12. "strings"
  13. "code.gitea.io/gitea/modules/json"
  14. "code.gitea.io/gitea/modules/log"
  15. "code.gitea.io/gitea/modules/proxy"
  16. "code.gitea.io/gitea/modules/setting"
  17. "golang.org/x/sync/errgroup"
  18. )
  19. // HTTPClient is used to communicate with the LFS server
  20. // https://github.com/git-lfs/git-lfs/blob/main/docs/api/batch.md
  21. type HTTPClient struct {
  22. client *http.Client
  23. endpoint string
  24. transfers map[string]TransferAdapter
  25. }
  26. // BatchSize returns the preferred size of batchs to process
  27. func (c *HTTPClient) BatchSize() int {
  28. return setting.LFSClient.BatchSize
  29. }
  30. func newHTTPClient(endpoint *url.URL, httpTransport *http.Transport) *HTTPClient {
  31. if httpTransport == nil {
  32. httpTransport = &http.Transport{
  33. Proxy: proxy.Proxy(),
  34. }
  35. }
  36. hc := &http.Client{
  37. Transport: httpTransport,
  38. }
  39. basic := &BasicTransferAdapter{hc}
  40. client := &HTTPClient{
  41. client: hc,
  42. endpoint: strings.TrimSuffix(endpoint.String(), "/"),
  43. transfers: map[string]TransferAdapter{
  44. basic.Name(): basic,
  45. },
  46. }
  47. return client
  48. }
  49. func (c *HTTPClient) transferNames() []string {
  50. keys := make([]string, len(c.transfers))
  51. i := 0
  52. for k := range c.transfers {
  53. keys[i] = k
  54. i++
  55. }
  56. return keys
  57. }
  58. func (c *HTTPClient) batch(ctx context.Context, operation string, objects []Pointer) (*BatchResponse, error) {
  59. log.Trace("BATCH operation with objects: %v", objects)
  60. url := c.endpoint + "/objects/batch"
  61. // Original: In some lfs server implementations, they require the ref attribute. #32838
  62. // `ref` is an "optional object describing the server ref that the objects belong to"
  63. // but some (incorrect) lfs servers like aliyun require it, so maybe adding an empty ref here doesn't break the correct ones.
  64. // https://github.com/git-lfs/git-lfs/blob/a32a02b44bf8a511aa14f047627c49e1a7fd5021/docs/api/batch.md?plain=1#L37
  65. //
  66. // UPDATE: it can't use "empty ref" here because it breaks others like https://github.com/go-gitea/gitea/issues/33453
  67. request := &BatchRequest{operation, c.transferNames(), nil, objects}
  68. payload := new(bytes.Buffer)
  69. err := json.NewEncoder(payload).Encode(request)
  70. if err != nil {
  71. log.Error("Error encoding json: %v", err)
  72. return nil, err
  73. }
  74. req, err := createRequest(ctx, http.MethodPost, url, map[string]string{"Content-Type": MediaType}, payload)
  75. if err != nil {
  76. return nil, err
  77. }
  78. res, err := performRequest(ctx, c.client, req)
  79. if err != nil {
  80. return nil, err
  81. }
  82. defer res.Body.Close()
  83. var response BatchResponse
  84. err = json.NewDecoder(res.Body).Decode(&response)
  85. if err != nil {
  86. log.Error("Error decoding json: %v", err)
  87. return nil, err
  88. }
  89. if len(response.Transfer) == 0 {
  90. response.Transfer = "basic"
  91. }
  92. return &response, nil
  93. }
  94. // Download reads the specific LFS object from the LFS server
  95. func (c *HTTPClient) Download(ctx context.Context, objects []Pointer, callback DownloadCallback) error {
  96. return c.performOperation(ctx, objects, callback, nil)
  97. }
  98. // Upload sends the specific LFS object to the LFS server
  99. func (c *HTTPClient) Upload(ctx context.Context, objects []Pointer, callback UploadCallback) error {
  100. return c.performOperation(ctx, objects, nil, callback)
  101. }
  102. // performOperation takes a slice of LFS object pointers, batches them, and performs the upload/download operations concurrently in each batch
  103. func (c *HTTPClient) performOperation(ctx context.Context, objects []Pointer, dc DownloadCallback, uc UploadCallback) error {
  104. if len(objects) == 0 {
  105. return nil
  106. }
  107. operation := "download"
  108. if uc != nil {
  109. operation = "upload"
  110. }
  111. result, err := c.batch(ctx, operation, objects)
  112. if err != nil {
  113. return err
  114. }
  115. transferAdapter, ok := c.transfers[result.Transfer]
  116. if !ok {
  117. return fmt.Errorf("TransferAdapter not found: %s", result.Transfer)
  118. }
  119. if setting.LFSClient.BatchOperationConcurrency <= 0 {
  120. panic("BatchOperationConcurrency must be greater than 0, forgot to init?")
  121. }
  122. errGroup, groupCtx := errgroup.WithContext(ctx)
  123. errGroup.SetLimit(setting.LFSClient.BatchOperationConcurrency)
  124. for _, object := range result.Objects {
  125. errGroup.Go(func() error {
  126. return performSingleOperation(groupCtx, object, dc, uc, transferAdapter)
  127. })
  128. }
  129. // only the first error is returned, preserving legacy behavior before concurrency
  130. return errGroup.Wait()
  131. }
  132. // performSingleOperation performs an LFS upload or download operation on a single object
  133. func performSingleOperation(ctx context.Context, object *ObjectResponse, dc DownloadCallback, uc UploadCallback, transferAdapter TransferAdapter) error {
  134. // the response from a lfs batch api request for this specific object id contained an error
  135. if object.Error != nil {
  136. log.Trace("Error on object %v: %v", object.Pointer, object.Error)
  137. // this was an 'upload' request inside the batch request
  138. if uc != nil {
  139. if _, err := uc(object.Pointer, object.Error); err != nil {
  140. return err
  141. }
  142. } else {
  143. // this was NOT an 'upload' request inside the batch request, meaning it must be a 'download' request
  144. if err := dc(object.Pointer, nil, object.Error); err != nil {
  145. return err
  146. }
  147. }
  148. // if the callback returns no err, then the error could be ignored, and the operations should continue
  149. return nil
  150. }
  151. // the response from an lfs batch api request contained necessary upload/download fields to act upon
  152. if uc != nil {
  153. if len(object.Actions) == 0 {
  154. log.Trace("%v already present on server", object.Pointer)
  155. return nil
  156. }
  157. link, ok := object.Actions["upload"]
  158. if !ok {
  159. return errors.New("missing action 'upload'")
  160. }
  161. content, err := uc(object.Pointer, nil)
  162. if err != nil {
  163. return err
  164. }
  165. err = transferAdapter.Upload(ctx, link, object.Pointer, content)
  166. if err != nil {
  167. return err
  168. }
  169. link, ok = object.Actions["verify"]
  170. if ok {
  171. if err := transferAdapter.Verify(ctx, link, object.Pointer); err != nil {
  172. return err
  173. }
  174. }
  175. } else {
  176. link, ok := object.Actions["download"]
  177. if !ok {
  178. // no actions block in response, try legacy response schema
  179. link, ok = object.Links["download"]
  180. }
  181. if !ok {
  182. log.Debug("%+v", object)
  183. return errors.New("missing action 'download'")
  184. }
  185. content, err := transferAdapter.Download(ctx, link)
  186. if err != nil {
  187. return err
  188. }
  189. if err := dc(object.Pointer, content, nil); err != nil {
  190. return err
  191. }
  192. }
  193. return nil
  194. }
  195. // createRequest creates a new request, and sets the headers.
  196. func createRequest(ctx context.Context, method, url string, headers map[string]string, body io.Reader) (*http.Request, error) {
  197. log.Trace("createRequest: %s", url)
  198. req, err := http.NewRequestWithContext(ctx, method, url, body)
  199. if err != nil {
  200. log.Error("Error creating request: %v", err)
  201. return nil, err
  202. }
  203. for key, value := range headers {
  204. req.Header.Set(key, value)
  205. }
  206. req.Header.Set("Accept", AcceptHeader)
  207. req.Header.Set("User-Agent", UserAgentHeader)
  208. return req, nil
  209. }
  210. // performRequest sends a request, optionally performs a callback on the request and returns the response.
  211. // If the status code is 200, the response is returned, and it will contain a non-nil Body.
  212. // Otherwise, it will return an error, and the Body will be nil or closed.
  213. func performRequest(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) {
  214. log.Trace("performRequest: %s", req.URL)
  215. res, err := client.Do(req)
  216. if err != nil {
  217. select {
  218. case <-ctx.Done():
  219. return res, ctx.Err()
  220. default:
  221. }
  222. log.Error("Error while processing request: %v", err)
  223. return res, err
  224. }
  225. if res.StatusCode != http.StatusOK {
  226. defer res.Body.Close()
  227. return res, handleErrorResponse(res)
  228. }
  229. return res, nil
  230. }
  231. func handleErrorResponse(resp *http.Response) error {
  232. var er ErrorResponse
  233. err := json.NewDecoder(resp.Body).Decode(&er)
  234. if err != nil {
  235. if err == io.EOF {
  236. return io.ErrUnexpectedEOF
  237. }
  238. log.Error("Error decoding json: %v", err)
  239. return err
  240. }
  241. log.Trace("ErrorResponse(%v): %v", resp.Status, er)
  242. return errors.New(er.Message)
  243. }