Debian Codegraph @

pkg/http-client/client.go

raw
1 // Copyright 2024 The Archivista Contributors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package httpclient
16
17 import (
18 "bytes"
19 "context"
20 "encoding/json"
21 "errors"
22 "fmt"
23 "io"
24 "net/http"
25 "net/url"
26
27 "github.com/in-toto/archivista/pkg/api"
28 "github.com/in-toto/go-witness/dsse"
29 )
30
31 type ArchivistaClient struct {
32 BaseURL string
33 GraphQLURL string
34 requestHeaders http.Header
35 *http.Client
36 }
37
38 type Option func(*ArchivistaClient)
39
40 func WithHeaders(h http.Header) Option {
41 return func(ac *ArchivistaClient) {
42 if h != nil {
43 ac.requestHeaders = h.Clone()
44 }
45 }
46 }
47
48 func (ac *ArchivistaClient) requestOptions() []api.RequestOption {
49 opts := []api.RequestOption{}
50 if ac.requestHeaders != nil {
51 opts = append(opts, api.WithHeaders(ac.requestHeaders))
52 }
53
54 return opts
55 }
56
57 type HttpClienter interface {
58 DownloadDSSE(ctx context.Context, gitoid string) (dsse.Envelope, error)
59 DownloadReadCloser(ctx context.Context, gitoid string) (io.ReadCloser, error)
60 DownloadWithWriter(ctx context.Context, gitoid string, dst io.Writer) error
61 Store(ctx context.Context, envelope dsse.Envelope) (api.UploadResponse, error)
62 StoreWithReader(ctx context.Context, r io.Reader) (api.UploadResponse, error)
63 GraphQLRetrieveSubjectResults(ctx context.Context, gitoid string) (api.RetrieveSubjectResults, error)
64 GraphQLRetrieveSearchResults(ctx context.Context, algo string, digest string) (api.SearchResults, error)
65 GraphQLQueryIface(ctx context.Context, query string, variables interface{}) (*GraphQLResponseInterface, error)
66 GraphQLQueryToDst(ctx context.Context, query string, variables interface{}, dst interface{}) error
67 GraphQLQueryReadCloser(ctx context.Context, query string, variables interface{}) (io.ReadCloser, error)
68 }
69
70 func CreateArchivistaClient(httpClient *http.Client, baseURL string, opts ...Option) (*ArchivistaClient, error) {
71 client := &ArchivistaClient{
72 BaseURL: baseURL,
73 Client: http.DefaultClient,
74 }
75
76 if httpClient != nil {
77 client.Client = httpClient
78 }
79
80 for _, opt := range opts {
81 opt(client)
82 }
83
84 var err error
85 client.GraphQLURL, err = url.JoinPath(client.BaseURL, "query")
86 if err != nil {
87 return nil, err
88 }
89
90 return client, nil
91 }
92
93 func (ac *ArchivistaClient) DownloadDSSE(ctx context.Context, gitoid string) (dsse.Envelope, error) {
94 reader, err := api.DownloadReadCloserWithHTTPClient(ctx, ac.Client, ac.BaseURL, gitoid, ac.requestOptions()...)
95 if err != nil {
96 return dsse.Envelope{}, err
97 }
98 env := dsse.Envelope{}
99 if err := json.NewDecoder(reader).Decode(&env); err != nil {
100 return dsse.Envelope{}, err
101 }
102 return env, nil
103 }
104
105 func (ac *ArchivistaClient) DownloadReadCloser(ctx context.Context, gitoid string) (io.ReadCloser, error) {
106 return api.DownloadReadCloserWithHTTPClient(ctx, ac.Client, ac.BaseURL, gitoid, ac.requestOptions()...)
107 }
108
109 func (ac *ArchivistaClient) DownloadWithWriter(ctx context.Context, gitoid string, dst io.Writer) error {
110 return api.DownloadWithWriterWithHTTPClient(ctx, ac.Client, ac.BaseURL, gitoid, dst, ac.requestOptions()...)
111 }
112
113 func (ac *ArchivistaClient) Store(ctx context.Context, envelope dsse.Envelope) (api.UploadResponse, error) {
114 return api.Store(ctx, ac.BaseURL, envelope, ac.requestOptions()...)
115 }
116
117 func (ac *ArchivistaClient) StoreWithReader(ctx context.Context, r io.Reader) (api.UploadResponse, error) {
118 return api.StoreWithReader(ctx, ac.BaseURL, r, ac.requestOptions()...)
119 }
120
121 type GraphQLRequestBodyInterface struct {
122 Query string `json:"query"`
123 Variables interface{} `json:"variables,omitempty"`
124 }
125
126 type GraphQLResponseInterface struct {
127 Data interface{}
128 Errors []api.GraphQLError `json:"errors,omitempty"`
129 }
130
131 // GraphQLRetrieveSubjectResults retrieves the subjects for a given gitoid.
132 func (ac *ArchivistaClient) GraphQLRetrieveSubjectResults(
133 ctx context.Context,
134 gitoid string,
135 ) (api.RetrieveSubjectResults, error) {
136 return api.GraphQlQuery[api.RetrieveSubjectResults](
137 ctx,
138 ac.BaseURL,
139 api.RetrieveSubjectsQuery,
140 api.RetrieveSubjectVars{Gitoid: gitoid},
141 ac.requestOptions()...,
142 )
143 }
144
145 // GraphQLRetrieveSearchResults retrieves the search results for a given algorithm and digest.
146 func (ac *ArchivistaClient) GraphQLRetrieveSearchResults(
147 ctx context.Context,
148 algo string,
149 digest string,
150 ) (api.SearchResults, error) {
151 return api.GraphQlQuery[api.SearchResults](
152 ctx,
153 ac.BaseURL,
154 api.SearchQuery,
155 api.SearchVars{Algorithm: algo, Digest: digest},
156 ac.requestOptions()...,
157 )
158 }
159
160 // GraphQLQueryIface executes a GraphQL query against the Archivista API and returns the response as an interface.
161 //
162 // Parameters:
163 // - ctx: The context to control the query's lifecycle, such as cancellations or deadlines.
164 // - query: A string representing the GraphQL query to be executed.
165 // - variables: A map or struct containing variables to parameterize the query.
166 //
167 // Returns:
168 // - A pointer to a GraphQLResponseInterface containing the query's result or errors.
169 // - An error if the query execution or response parsing fails.
170 //
171 // Example:
172 //
173 // response, err := client.GraphQLQueryIface(ctx, query, variables)
174 // if err != nil {
175 // log.Fatalf("GraphQL query failed: %v", err)
176 // }
177 // fmt.Printf("Response data: %+v\n", response.Data)
178 func (ac *ArchivistaClient) GraphQLQueryIface(
179 ctx context.Context,
180 query string,
181 variables interface{},
182 ) (*GraphQLResponseInterface, error) {
183 reader, err := ac.GraphQLQueryReadCloser(ctx, query, variables)
184 if err != nil {
185 return nil, err
186 }
187 defer reader.Close()
188 gqlRes := GraphQLResponseInterface{}
189 dec := json.NewDecoder(reader)
190 if err := dec.Decode(&gqlRes); err != nil {
191 return nil, err
192 }
193 if len(gqlRes.Errors) > 0 {
194 return nil, fmt.Errorf("graph ql query failed: %v", gqlRes.Errors)
195 }
196 return &gqlRes, nil
197 }
198
199 // GraphQLQueryToDst executes a GraphQL query against the Archivista API and unmarshals the response into a destination object.
200 func (ac *ArchivistaClient) GraphQLQueryToDst(ctx context.Context, query string, variables interface{}, dst interface{}) error {
201 reader, err := ac.GraphQLQueryReadCloser(ctx, query, variables)
202 if err != nil {
203 return err
204 }
205 defer reader.Close()
206 dec := json.NewDecoder(reader)
207 if err := dec.Decode(&dst); err != nil {
208 return err
209 }
210 return nil
211 }
212
213 // GraphQLQueryReadCloser executes a GraphQL query against the Archivista API and returns the response as an io.ReadCloser.
214 func (ac *ArchivistaClient) GraphQLQueryReadCloser(
215 ctx context.Context,
216 query string,
217 variables interface{},
218 ) (io.ReadCloser, error) {
219 requestBodyMap := GraphQLRequestBodyInterface{
220 Query: query,
221 Variables: variables,
222 }
223
224 requestBodyJSON, err := json.Marshal(requestBodyMap)
225 if err != nil {
226 return nil, err
227 }
228
229 req, err := http.NewRequestWithContext(ctx, http.MethodPost, ac.GraphQLURL, bytes.NewReader(requestBodyJSON))
230 if err != nil {
231 return nil, err
232 }
233
234 if ac.requestHeaders != nil {
235 req.Header = ac.requestHeaders
236 }
237
238 req.Header.Set("Content-Type", "application/json")
239 res, err := ac.Do(req)
240 if err != nil {
241 return nil, err
242 }
243
244 if res.StatusCode != http.StatusOK {
245 defer res.Body.Close()
246 errMsg, err := io.ReadAll(res.Body)
247 if err != nil {
248 return nil, err
249 }
250 return nil, errors.New(string(errMsg))
251 }
252
253 return res.Body, nil
254 }