about summary refs log tree commit diff stats
path: root/searchix.go
blob: 534624ede3ebddcc3e3ae8c2db2d359141eea5e1 (plain)
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
package searchix

import (
	"context"
	"slices"
	"sync"
	"time"

	"go.alanpearce.eu/searchix/internal/config"
	"go.alanpearce.eu/searchix/internal/importer"
	"go.alanpearce.eu/searchix/internal/index"
	"go.alanpearce.eu/searchix/internal/server"
	"go.alanpearce.eu/x/log"

	"github.com/getsentry/sentry-go"
	"github.com/pkg/errors"
)

func nextUTCOccurrenceOfTime(t config.LocalTime) time.Time {
	now := time.Now()
	dayTime := t
	nextRun := time.Date(
		now.Year(),
		now.Month(),
		now.Day(),
		dayTime.Hour,
		dayTime.Minute,
		dayTime.Second,
		0,
		time.UTC,
	)
	if nextRun.Before(now) {
		return nextRun.AddDate(0, 0, 1)
	}

	return nextRun
}

type IndexOptions struct {
	Update    bool
	Replace   bool
	LowMemory bool
	Logger    *log.Logger
}

func (s *Server) SetupIndex(options *IndexOptions) error {
	var i uint
	cfgEnabledSources := make([]string, len(s.cfg.Importer.Sources))
	for key := range s.cfg.Importer.Sources {
		cfgEnabledSources[i] = key
		i++
	}
	slices.Sort(cfgEnabledSources)

	read, write, exists, err := index.OpenOrCreate(
		s.cfg.DataPath,
		options.Replace,
		&index.Options{
			LowMemory: options.LowMemory,
			Logger:    options.Logger.Named("index"),
		},
	)
	if err != nil {
		return errors.Wrap(err, "Failed to open or create index")
	}
	s.readIndex = read
	s.writeIndex = write

	if !exists || options.Replace || options.Update {
		s.log.Info(
			"Starting build job",
			"new",
			!exists,
			"replace",
			options.Replace,
			"update",
			options.Update,
		)
		err = importer.Start(
			s.cfg,
			s.log.Named("importer"),
			write,
			options.Replace || options.Update,
			nil,
		)
		if err != nil {
			return errors.Wrap(err, "Failed to build index")
		}
		if options.Replace || options.Update {
			return nil
		}
	} else {
		indexedSources, err := read.GetEnabledSources()
		if err != nil {
			return errors.Wrap(err, "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 {
				s.log.Info("adding new sources", "sources", newSources)
				err := importer.Start(s.cfg, options.Logger.Named("importer"), write, false, &newSources)
				if err != nil {
					return errors.Wrap(err, "Failed to update index with new sources")
				}
			}
			if len(retiredSources) > 0 {
				s.log.Info("removing retired sources", "sources", retiredSources)
				for _, s := range retiredSources {
					err := write.DeleteBySource(s)
					if err != nil {
						return errors.Wrapf(err, "Failed to remove retired source %s", s)
					}
				}
			}
		}
	}

	return nil
}

type Server struct {
	sv         *server.Server
	wg         *sync.WaitGroup
	cfg        *config.Config
	log        *log.Logger
	sentryHub  *sentry.Hub
	readIndex  *index.ReadIndex
	writeIndex *index.WriteIndex
}

func New(cfg *config.Config, log *log.Logger) (*Server, error) {
	err := sentry.Init(sentry.ClientOptions{
		EnableTracing:    true,
		TracesSampleRate: 0.01,
		Dsn:              cfg.Web.SentryDSN,
		Environment:      cfg.Web.Environment,
	})
	if err != nil {
		log.Warn("could not initialise sentry", "error", err)
	}

	return &Server{
		cfg:       cfg,
		log:       log,
		sentryHub: sentry.CurrentHub(),
	}, nil
}

func (s *Server) startUpdateTimer(
	ctx context.Context,
	localHub *sentry.Hub,
) {
	const monitorSlug = "import"
	localHub.WithScope(func(scope *sentry.Scope) {
		var err error
		scope.SetContext("monitor", sentry.Context{"slug": monitorSlug})
		monitorConfig := &sentry.MonitorConfig{
			Schedule: sentry.IntervalSchedule(1, sentry.MonitorScheduleUnitDay),
			// minutes
			MaxRuntime:    10,
			CheckInMargin: 5,
			Timezone:      time.Local.String(),
		}

		s.wg.Add(1)
		nextRun := nextUTCOccurrenceOfTime(s.cfg.Importer.UpdateAt)
		for {
			s.log.Debug("scheduling next run", "next-run", nextRun)
			select {
			case <-ctx.Done():
				s.log.Debug("stopping scheduler")
				s.wg.Done()

				return
			case <-time.After(time.Until(nextRun)):
			}
			s.wg.Add(1)
			s.log.Info("updating index")

			eventID := localHub.CaptureCheckIn(&sentry.CheckIn{
				MonitorSlug: monitorSlug,
				Status:      sentry.CheckInStatusInProgress,
			}, monitorConfig)

			err = importer.Start(s.cfg, s.log.Named("importer"), s.writeIndex, false, nil)
			s.wg.Done()
			if err != nil {
				s.log.Warn("error updating index", "error", err)

				localHub.CaptureException(err)
				localHub.CaptureCheckIn(&sentry.CheckIn{
					ID:          *eventID,
					MonitorSlug: monitorSlug,
					Status:      sentry.CheckInStatusError,
				}, monitorConfig)
			} else {
				s.log.Info("update complete")

				localHub.CaptureCheckIn(&sentry.CheckIn{
					ID:          *eventID,
					MonitorSlug: monitorSlug,
					Status:      sentry.CheckInStatusOK,
				}, monitorConfig)
			}
			nextRun = nextRun.AddDate(0, 0, 1)
		}
	})
}

func (s *Server) Start(ctx context.Context, liveReload bool) error {
	var err error
	s.sv, err = server.New(s.cfg, s.readIndex, s.log.Named("server"), liveReload)
	if err != nil {
		return errors.Wrap(err, "error setting up server")
	}

	s.wg = &sync.WaitGroup{}
	go s.startUpdateTimer(ctx, sentry.CurrentHub().Clone())

	s.wg.Add(1)
	err = s.sv.Start()
	if err != nil {
		s.wg.Done()

		return errors.Wrap(err, "error starting server")
	}

	return nil
}

func (s *Server) Stop() {
	<-s.sv.Stop()
	defer s.wg.Done()
	s.sentryHub.Flush(2 * time.Second)
}