all repos — searchix @ d804ce1e5023d7c0ed5505736a3b553f6c81d7da

Search engine for NixOS, nix-darwin, home-manager and NUR users

internal/importer/main.go (view raw)

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
package importer

import (
	"context"
	"errors"
	"maps"
	"os/exec"
	"slices"
	"strings"
	"time"

	"alin.ovh/x/log"

	"alin.ovh/searchix/internal/config"
	"alin.ovh/searchix/internal/fetcher"
	"alin.ovh/searchix/internal/file"
	"alin.ovh/searchix/internal/index"
	"alin.ovh/searchix/internal/manpages"
	"alin.ovh/searchix/internal/programs"
	"alin.ovh/searchix/internal/storage"

	"github.com/Southclaws/fault"
	"github.com/Southclaws/fault/fmsg"
)

type Options struct {
	LowMemory  bool
	Offline    bool
	Logger     *log.Logger
	WriteIndex *index.WriteIndex
	Manpages   *manpages.URLMap
	Root       *file.Root
	Storage    *storage.Store
}

type Importer struct {
	config  *config.Config
	options *Options
}

func New(
	cfg *config.Config,
	options *Options,
) (*Importer, error) {
	Job.LastRun = options.WriteIndex.Meta.LastImport

	return &Importer{
		config:  cfg,
		options: options,
	}, nil
}

func (imp *Importer) Fetch(
	ctx context.Context,
	forceUpdate bool,
	fetchOnly bool,
	onlyUpdateSources *[]string,
) error {
	if len(imp.config.Importer.Sources) == 0 {
		imp.options.Logger.Info("No sources enabled")

		return nil
	}

	imp.options.Logger.Debug("starting importer", "timeout", imp.config.Importer.Timeout.Duration)
	importCtx, cancelImport := context.WithTimeout(
		ctx,
		imp.config.Importer.Timeout.Duration,
	)
	defer cancelImport()

	forceUpdate = forceUpdate || (onlyUpdateSources != nil && len(*onlyUpdateSources) > 0)

	meta := imp.options.WriteIndex.Meta

	importSource := imp.createSourceImporter(importCtx, meta, forceUpdate, fetchOnly)
	for name, source := range imp.config.Importer.Sources {
		if onlyUpdateSources != nil && len(*onlyUpdateSources) > 0 {
			if !slices.Contains(*onlyUpdateSources, name) {
				continue
			}
		}
		err := importSource(source)
		if err != nil {
			imp.options.Logger.Error("import failed", "source", name, "error", err)
		}
	}

	MarkLastFetch(meta)
	err := imp.options.WriteIndex.SaveMeta()
	if err != nil {
		return fault.Wrap(err, fmsg.With("failed to save metadata"))
	}

	return nil
}

func (imp *Importer) Index(ctx context.Context) error {
	for name, source := range imp.config.Importer.Sources {
		hadErrors, err := imp.indexSource(ctx, source)
		if err != nil {
			return fault.Wrap(err, fmsg.Withf("Failed to import source %s", name))
		}

		if hadErrors {
			imp.options.Logger.Warn("Imported source encountered errors", "source", source.Name)
		}
	}

	return nil
}

func (imp *Importer) EnsureSourcesIndexed(
	ctx context.Context,
	read *index.ReadIndex,
) error {
	cfgEnabledSources := slices.Collect(maps.Keys(imp.config.Importer.Sources))
	slices.Sort(cfgEnabledSources)

	indexedSources, err := read.GetEnabledSources()
	if err != nil {
		return fault.Wrap(err, fmsg.With("Failed to get enabled sources from index"))
	}
	slices.Sort(indexedSources)
	if !slices.Equal(cfgEnabledSources, indexedSources) {
		newSources := slices.DeleteFunc(slices.Clone(cfgEnabledSources), func(s string) bool {
			return slices.Contains(indexedSources, s)
		})
		retiredSources := slices.DeleteFunc(slices.Clone(indexedSources), func(s string) bool {
			return slices.Contains(cfgEnabledSources, s)
		})
		if len(newSources) > 0 {
			imp.options.Logger.Info("adding new sources", "sources", newSources)
			err := imp.Fetch(
				ctx,
				false,
				false,
				&newSources,
			)
			if err != nil {
				return fault.Wrap(err, fmsg.With("Failed to update index with new sources"))
			}
		}
		if len(retiredSources) > 0 {
			imp.options.Logger.Info("removing retired sources", "sources", retiredSources)
			for _, s := range retiredSources {
				err := imp.options.WriteIndex.DeleteBySource(s)
				if err != nil {
					return fault.Wrap(err, fmsg.Withf("Failed to remove retired source %s", s))
				}
			}
		}
	}

	return nil
}

func (imp *Importer) createSourceImporter(
	parent context.Context,
	meta *index.Meta,
	forceUpdate bool,
	fetchOnly bool,
) func(*config.Source) error {
	return func(source *config.Source) error {
		var files *fetcher.FetchedFiles

		logger := imp.options.Logger.With("name", source.Key)
		pdb, err := programs.New(source, &programs.Options{
			Logger: logger,
			Root:   imp.options.Root,
		})
		if err != nil {
			return fault.Wrap(err, fmsg.With("error creating program database"))
		}

		sourceMeta := meta.GetSourceMeta(source.Key)
		previousUpdate := sourceMeta.UpdatedAt

		fopts := &fetcher.Options{
			Logger: logger,
			Root:   imp.options.Root,
		}

		ctx, cancel := context.WithTimeout(parent, source.Timeout.Duration)
		defer cancel()

		if imp.options.Offline {
			logger.Debug("skipping fetch; in offline mode")

			files, err = fetcher.Open(source, fopts)
			if err != nil {
				return fault.Wrap(err, fmsg.With("error opening fetched files"))
			}
		} else {
			logger.Debug("starting fetcher")

			fetcher, err := fetcher.New(source, fopts)
			if err != nil {
				return fault.Wrap(err, fmsg.With("error creating fetcher"))
			}

			files, err = fetcher.FetchIfNeeded(ctx, sourceMeta)
			if err != nil {
				var exerr *exec.ExitError
				if errors.As(err, &exerr) {
					lines := strings.SplitSeq(strings.TrimSpace(string(exerr.Stderr)), "\n")
					for line := range lines {
						logger.Error(
							"importer fetch failed",
							"fetcher",
							source.Fetcher.String(),
							"stderr",
							line,
							"status",
							exerr.ExitCode(),
						)
					}
				}

				return fault.Wrap(err, fmsg.With("importer fetch failed"))
			}
			logger.Info(
				"importer fetch succeeded",
				"previous",
				previousUpdate.Format(time.DateTime),
				"current",
				sourceMeta.UpdatedAt.Format(time.DateTime),
				"is_updated",
				sourceMeta.UpdatedAt.After(previousUpdate),
				"update_force",
				forceUpdate,
				"fetch_only",
				fetchOnly,
			)

			if source.Programs.Enable {
				err = pdb.Instantiate(ctx)
				if err != nil {
					logger.Warn("programs database instantiation failed", "error", err)
				}
			}

			if source.Manpages.Enable {
				err = imp.options.Manpages.Update(ctx, source)
				if err != nil {
					logger.Warn("manpages database update failed", "error", err)
				}
			}
		}

		if !fetchOnly &&
			(!sourceMeta.UpdatedAt.After(sourceMeta.StoredAt) || sourceMeta.StoredAt.IsZero() || forceUpdate) {

			if files.Revision != nil {
				err = setRepoRevision(files.Revision, source)
				if err != nil {
					logger.Warn("could not set source repo revision", "error", err)
				}
			}

			var processor Processor
			logger.Debug(
				"creating processor",
				"importer_type",
				source.Importer,
				"revision",
				source.Repo.Revision,
			)
			switch source.Importer {
			case config.Options:
				processor, err = NewOptionProcessor(
					files.Options,
					source,
					logger.Named("processor"),
				)
			case config.Packages:
				processor, err = NewPackageProcessor(
					files.Packages,
					source,
					logger.Named("processor"),
					pdb,
				)
			}
			if err != nil {
				return fault.Wrap(err, fmsg.Withf("failed to create processor"))
			}

			hadWarnings, err := pipe(
				ctx,
				logger.Named("importer"),
				processor.Process,
				imp.options.Storage.MakeSourceImporter(source),
			)
			if err != nil {
				return fault.Wrap(err, fmsg.Withf("failed to process source"))
			}

			sourceMeta.StoredAt = time.Now()

			if hadWarnings {
				logger.Warn("importer succeeded, but with warnings/errors")
			} else {
				logger.Info("importer succeeded")
			}
		}

		sourceMeta.Rev = source.Repo.Revision
		meta.SetSourceMeta(source.Key, sourceMeta)

		return nil
	}
}