all repos — searchix @ link-other-instance

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

internal/server/mux.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
package server

import (
	"cmp"
	"maps"
	"net/http"
	"path"
	"slices"
	"strings"
	"time"

	"alin.ovh/searchix/frontend"
	"alin.ovh/searchix/internal/config"
	"alin.ovh/searchix/internal/sentryhttp"

	"alin.ovh/x/log"
	"github.com/Southclaws/fault"
	"github.com/Southclaws/fault/fmsg"
	"github.com/osdevisnot/sorvor/pkg/livereload"
)

type HTTPError struct {
	Error   error
	Message string
	Code    int
}

var sources []config.Source

func applyDevModeOverrides(cfg *config.Config) {
	if len(cfg.Web.ContentSecurityPolicy.ScriptSrc) == 0 {
		cfg.Web.ContentSecurityPolicy.ScriptSrc = cfg.Web.ContentSecurityPolicy.DefaultSrc
	}
	cfg.Web.ContentSecurityPolicy.ScriptSrc = append(
		cfg.Web.ContentSecurityPolicy.ScriptSrc,
		"'unsafe-inline'",
	)
	cfg.Web.GracefulShutdownTimeout.Duration = 200 * time.Millisecond
}

func sortSources(ss map[string]config.Source) {
	sources = slices.SortedFunc(maps.Values(ss), func(a, b config.Source) int {
		return cmp.Or(
			cmp.Compare(a.Order, b.Order),
			strings.Compare(a.Key, b.Key),
			strings.Compare(a.Name, b.Name),
		)
	})
}

func NewMux(
	cfg *config.Config,
	options *Options,
	log *log.Logger,
	liveReload bool,
) (*http.ServeMux, error) {
	if cfg == nil {
		return nil, fault.New("cfg is nil")
	}
	if options.ReadIndex == nil {
		return nil, fault.New("read index is nil")
	}
	sortSources(cfg.Importer.Sources)
	assets, err := frontend.New()
	if err != nil {
		return nil, fault.Wrap(err, fmsg.With("could not create frontend asset collection"))
	}

	handler := &GlobalHandler{
		assets:       assets,
		cfg:          cfg,
		log:          log,
		index:        options.ReadIndex,
		mdb:          options.ManpagesURLMap,
		errorHandler: createErrorHandler(cfg, assets, log),
	}

	mux := sentryhttp.NewServeMux()

	// Register global routes
	mux.HandleFunc("/{$}", handler.CombinedSearch)
	mux.HandleFunc("/opensearch.xml", handler.RootOpenSearch)

	mux.HandleFunc("/", handler.StaticFile)
	mux.HandleFunc("/assets/", handler.Asset)
	mux.HandleFunc("/man/{section}/{page}", handler.ManualPage)

	mux.Handle("/all/search", http.RedirectHandler("/", http.StatusFound))
	mux.Handle("/all/opensearch.xml", http.RedirectHandler("/opensearch.xml", http.StatusFound))

	for _, it := range []config.ImporterType{config.Options, config.Packages} {
		singularPath := path.Join("/", it.Singular())
		mux.HandleFunc(singularPath+"/", func(w http.ResponseWriter, r *http.Request) {
			newPath := path.Join("/", it.String(), strings.TrimPrefix(r.URL.Path, singularPath))
			http.Redirect(w, r, newPath, http.StatusFound)
		})
	}

	for _, source := range cfg.Importer.Sources {
		mux.Handle(source.LocalURL().String(), handler.NewSourceHandler(source))
	}

	top := http.NewServeMux()
	if liveReload {
		applyDevModeOverrides(cfg)
		cfg.Web.ExtraHeadHTML = livereload.JsSnippet
		liveReload := livereload.New()
		liveReload.Start()
		top.Handle("/livereload", liveReload)
		fw, err := NewFileWatcher(log.Named("watcher"), "frontend")
		if err != nil {
			return nil, fault.Wrap(err, fmsg.With("could not create file watcher"))
		}
		err = fw.AddRecursive(".")
		if err != nil {
			return nil, fault.Wrap(err, fmsg.With("could not add directory to file watcher"))
		}
		go fw.Start(func(filename string) {
			if match, _ := path.Match("frontend/static/*", filename); match {
				err := assets.Rehash()
				if err != nil {
					log.Error("failed to re-hash frontend assets", "error", err)
				}
			}
			liveReload.Reload()
		})
	}

	top.Handle("/",
		AddHeadersMiddleware(
			wrapHandlerWithLogging(mux, wrappedHandlerOptions{
				defaultHostname: cfg.Web.BaseURL.Hostname(),
				logger:          log,
				enabled:         cfg.Web.LogRequests,
			}),
			cfg,
		),
	)
	// no logging, no sentry
	top.HandleFunc("/health", func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusOK)
	})

	return top, nil
}