-
-
Notifications
You must be signed in to change notification settings - Fork 46
/
rolodex_remote_loader.go
436 lines (367 loc) · 11.7 KB
/
rolodex_remote_loader.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
// Copyright 2023 Princess B33f Heavy Industries / Dave Shanley
// SPDX-License-Identifier: MIT
package index
import (
"context"
"errors"
"fmt"
"github.com/pb33f/libopenapi/datamodel"
"github.com/pb33f/libopenapi/utils"
"golang.org/x/sync/syncmap"
"gopkg.in/yaml.v3"
"io"
"io/fs"
"log/slog"
"net/http"
"net/url"
"os"
"path/filepath"
"time"
)
const (
YAML FileExtension = iota
JSON
UNSUPPORTED
)
// FileExtension is the type of file extension.
type FileExtension int
// RemoteFS is a file system that indexes remote files. It implements the fs.FS interface. Files are located remotely
// and served via HTTP.
type RemoteFS struct {
indexConfig *SpecIndexConfig
rootURL string
rootURLParsed *url.URL
RemoteHandlerFunc utils.RemoteURLHandler
Files syncmap.Map
ProcessingFiles syncmap.Map
FetchTime int64
FetchChannel chan *RemoteFile
remoteErrors []error
logger *slog.Logger
extractedFiles map[string]RolodexFile
}
// RemoteFile is a file that has been indexed by the RemoteFS. It implements the RolodexFile interface.
type RemoteFile struct {
filename string
name string
extension FileExtension
data []byte
fullPath string
URL *url.URL
lastModified time.Time
seekingErrors []error
index *SpecIndex
parsed *yaml.Node
offset int64
}
// GetFileName returns the name of the file.
func (f *RemoteFile) GetFileName() string {
return f.filename
}
// GetContent returns the content of the file as a string.
func (f *RemoteFile) GetContent() string {
return string(f.data)
}
// GetContentAsYAMLNode returns the content of the file as a yaml.Node.
func (f *RemoteFile) GetContentAsYAMLNode() (*yaml.Node, error) {
if f.parsed != nil {
return f.parsed, nil
}
if f.index != nil && f.index.root != nil {
return f.index.root, nil
}
if f.data == nil {
return nil, fmt.Errorf("no data to parse for file: %s", f.fullPath)
}
var root yaml.Node
err := yaml.Unmarshal(f.data, &root)
if err != nil {
return nil, err
}
if f.index != nil && f.index.root == nil {
f.index.root = &root
}
f.parsed = &root
return &root, nil
}
// GetFileExtension returns the file extension of the file.
func (f *RemoteFile) GetFileExtension() FileExtension {
return f.extension
}
// GetLastModified returns the last modified time of the file.
func (f *RemoteFile) GetLastModified() time.Time {
return f.lastModified
}
// GetErrors returns any errors that occurred while reading the file.
func (f *RemoteFile) GetErrors() []error {
return f.seekingErrors
}
// GetFullPath returns the full path of the file.
func (f *RemoteFile) GetFullPath() string {
return f.fullPath
}
// fs.FileInfo interfaces
// Name returns the name of the file.
func (f *RemoteFile) Name() string {
return f.name
}
// Size returns the size of the file.
func (f *RemoteFile) Size() int64 {
return int64(len(f.data))
}
// Mode returns the file mode bits for the file.
func (f *RemoteFile) Mode() fs.FileMode {
return fs.FileMode(0)
}
// ModTime returns the modification time of the file.
func (f *RemoteFile) ModTime() time.Time {
return f.lastModified
}
// IsDir returns true if the file is a directory.
func (f *RemoteFile) IsDir() bool {
return false
}
// fs.File interfaces
// Sys returns the underlying data source (always returns nil)
func (f *RemoteFile) Sys() interface{} {
return nil
}
// Close closes the file (doesn't do anything, returns no error)
func (f *RemoteFile) Close() error {
return nil
}
// Stat returns the FileInfo for the file.
func (f *RemoteFile) Stat() (fs.FileInfo, error) {
return f, nil
}
// Read reads the file. Makes it compatible with io.Reader.
func (f *RemoteFile) Read(b []byte) (int, error) {
if f.offset >= int64(len(f.data)) {
return 0, io.EOF
}
if f.offset < 0 {
return 0, &fs.PathError{Op: "read", Path: f.name, Err: fs.ErrInvalid}
}
n := copy(b, f.data[f.offset:])
f.offset += int64(n)
return n, nil
}
// Index indexes the file and returns a *SpecIndex, any errors are returned as well.
func (f *RemoteFile) Index(config *SpecIndexConfig) (*SpecIndex, error) {
if f.index != nil {
return f.index, nil
}
content := f.data
// first, we must parse the content of the file
info, err := datamodel.ExtractSpecInfoWithDocumentCheck(content, true)
if err != nil {
return nil, err
}
index := NewSpecIndexWithConfig(info.RootNode, config)
index.specAbsolutePath = config.SpecAbsolutePath
f.index = index
return index, nil
}
// GetIndex returns the index for the file.
func (f *RemoteFile) GetIndex() *SpecIndex {
return f.index
}
// NewRemoteFSWithConfig creates a new RemoteFS using the supplied SpecIndexConfig.
func NewRemoteFSWithConfig(specIndexConfig *SpecIndexConfig) (*RemoteFS, error) {
if specIndexConfig == nil {
return nil, errors.New("no spec index config provided")
}
remoteRootURL := specIndexConfig.BaseURL
log := specIndexConfig.Logger
if log == nil {
log = slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelError,
}))
}
rfs := &RemoteFS{
indexConfig: specIndexConfig,
logger: log,
rootURLParsed: remoteRootURL,
FetchChannel: make(chan *RemoteFile),
}
if remoteRootURL != nil {
rfs.rootURL = remoteRootURL.String()
}
if specIndexConfig.RemoteURLHandler != nil {
rfs.RemoteHandlerFunc = specIndexConfig.RemoteURLHandler
} else {
// default http client
client := &http.Client{
Timeout: time.Second * 120,
}
rfs.RemoteHandlerFunc = func(url string) (*http.Response, error) {
return client.Get(url)
}
}
return rfs, nil
}
// NewRemoteFSWithRootURL creates a new RemoteFS using the supplied root URL.
func NewRemoteFSWithRootURL(rootURL string) (*RemoteFS, error) {
remoteRootURL, err := url.Parse(rootURL)
if err != nil {
return nil, err
}
config := CreateOpenAPIIndexConfig()
config.BaseURL = remoteRootURL
return NewRemoteFSWithConfig(config)
}
// SetRemoteHandlerFunc sets the remote handler function.
func (i *RemoteFS) SetRemoteHandlerFunc(handlerFunc utils.RemoteURLHandler) {
i.RemoteHandlerFunc = handlerFunc
}
// SetIndexConfig sets the index configuration.
func (i *RemoteFS) SetIndexConfig(config *SpecIndexConfig) {
i.indexConfig = config
}
// GetFiles returns the files that have been indexed.
func (i *RemoteFS) GetFiles() map[string]RolodexFile {
files := make(map[string]RolodexFile)
i.Files.Range(func(key, value interface{}) bool {
files[key.(string)] = value.(*RemoteFile)
return true
})
i.extractedFiles = files
return files
}
// GetErrors returns any errors that occurred during the indexing process.
func (i *RemoteFS) GetErrors() []error {
return i.remoteErrors
}
// Open opens a file, returning it or an error. If the file is not found, the error is of type *PathError.
func (i *RemoteFS) Open(remoteURL string) (fs.File, error) {
if i.indexConfig != nil && !i.indexConfig.AllowRemoteLookup {
return nil, fmt.Errorf("remote lookup for '%s' is not allowed, please set "+
"AllowRemoteLookup to true as part of the index configuration", remoteURL)
}
remoteParsedURL, err := url.Parse(remoteURL)
if err != nil {
return nil, err
}
remoteParsedURLOriginal, _ := url.Parse(remoteURL)
// try path first
if r, ok := i.Files.Load(remoteParsedURL.Path); ok {
return r.(*RemoteFile), nil
}
// if we're processing, we need to block and wait for the file to be processed
// try path first
if _, ok := i.ProcessingFiles.Load(remoteParsedURL.Path); ok {
i.logger.Debug("waiting for existing fetch to complete", "file", remoteURL,
"remoteURL", remoteParsedURL.String())
// Create a context with a timeout of 50ms
ctxTimeout, cancel := context.WithTimeout(context.Background(), time.Millisecond*50)
defer cancel()
f := make(chan *RemoteFile)
fwait := func(path string, c chan *RemoteFile) {
for {
if wf, ko := i.Files.Load(remoteParsedURL.Path); ko {
c <- wf.(*RemoteFile)
}
}
}
go fwait(remoteParsedURL.Path, f)
select {
case <-ctxTimeout.Done():
i.logger.Info("waiting for remote file timed out, trying again", "file", remoteURL,
"remoteURL", remoteParsedURL.String())
case v := <-f:
return v, nil
}
}
// add to processing
i.ProcessingFiles.Store(remoteParsedURL.Path, true)
fileExt := ExtractFileType(remoteParsedURL.Path)
if fileExt == UNSUPPORTED {
return nil, &fs.PathError{Op: "open", Path: remoteURL, Err: fs.ErrInvalid}
}
// if the remote URL is absolute (http:// or https://), and we have a rootURL defined, we need to override
// the host being defined by this URL, and use the rootURL instead, but keep the path.
if i.rootURLParsed != nil {
remoteParsedURL.Host = i.rootURLParsed.Host
remoteParsedURL.Scheme = i.rootURLParsed.Scheme
if !filepath.IsAbs(remoteParsedURL.Path) {
remoteParsedURL.Path = filepath.Join(i.rootURLParsed.Path, remoteParsedURL.Path)
}
}
if remoteParsedURL.Scheme == "" {
i.ProcessingFiles.Delete(remoteParsedURL.Path)
return nil, nil // not a remote file, nothing wrong with that - just we can't keep looking here partner.
}
i.logger.Debug("loading remote file", "file", remoteURL, "remoteURL", remoteParsedURL.String())
response, clientErr := i.RemoteHandlerFunc(remoteParsedURL.String())
if clientErr != nil {
i.remoteErrors = append(i.remoteErrors, clientErr)
// remove from processing
i.ProcessingFiles.Delete(remoteParsedURL.Path)
if response != nil {
i.logger.Error("client error", "error", clientErr, "status", response.StatusCode)
} else {
i.logger.Error("client error", "error", clientErr.Error())
}
return nil, clientErr
}
if response == nil {
return nil, fmt.Errorf("empty response from remote URL: %s", remoteParsedURL.String())
}
responseBytes, readError := io.ReadAll(response.Body)
if readError != nil {
// remove from processing
i.ProcessingFiles.Delete(remoteParsedURL.Path)
return nil, fmt.Errorf("error reading bytes from remote file '%s': [%s]",
remoteParsedURL.String(), readError.Error())
}
if response.StatusCode >= 400 {
// remove from processing
i.ProcessingFiles.Delete(remoteParsedURL.Path)
i.logger.Error("unable to fetch remote document",
"file", remoteParsedURL.Path, "status", response.StatusCode, "resp", string(responseBytes))
return nil, fmt.Errorf("unable to fetch remote document: %s", string(responseBytes))
}
absolutePath, _ := filepath.Abs(remoteParsedURL.Path)
// extract last modified from response
lastModified := response.Header.Get("Last-Modified")
// parse the last modified date into a time object
lastModifiedTime, parseErr := time.Parse(time.RFC1123, lastModified)
if parseErr != nil {
// can't extract last modified, so use now
lastModifiedTime = time.Now()
}
filename := filepath.Base(remoteParsedURL.Path)
remoteFile := &RemoteFile{
filename: filename,
name: remoteParsedURL.Path,
extension: fileExt,
data: responseBytes,
fullPath: absolutePath,
URL: remoteParsedURL,
lastModified: lastModifiedTime,
}
copiedCfg := *i.indexConfig
newBase := fmt.Sprintf("%s://%s%s", remoteParsedURLOriginal.Scheme, remoteParsedURLOriginal.Host,
filepath.Dir(remoteParsedURL.Path))
newBaseURL, _ := url.Parse(newBase)
if newBaseURL != nil {
copiedCfg.BaseURL = newBaseURL
}
copiedCfg.SpecAbsolutePath = remoteParsedURL.String()
if len(remoteFile.data) > 0 {
i.logger.Debug("successfully loaded file", "file", absolutePath)
}
// remove from processing
i.ProcessingFiles.Delete(remoteParsedURL.Path)
i.Files.Store(absolutePath, remoteFile)
idx, idxError := remoteFile.Index(&copiedCfg)
if idxError != nil && idx == nil {
i.remoteErrors = append(i.remoteErrors, idxError)
} else {
// for each index, we need a resolver
resolver := NewResolver(idx)
idx.resolver = resolver
idx.BuildIndex()
}
return remoteFile, errors.Join(i.remoteErrors...)
}