aboutsummaryrefslogtreecommitdiffstats
path: root/pkg/server/server.go
blob: c08d5a41d005778495b15d935fda1f1c0721cc01 (plain) (blame)
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
package server

import (
	"bytes"
	"io"
	"log/slog"
	"net/http"
	"strings"
	"sync"
	"time"

	"github.com/jpappel/atlas/pkg/data"
	"github.com/jpappel/atlas/pkg/index"
	"github.com/jpappel/atlas/pkg/query"
)

func info(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte(`
	<h1>Atlas Server</h1>
	<p>This is the experimental atlas server!
	Try POSTing a query to <pre>/search</pre></p>
	`))
}

func New(db *data.Query) *http.ServeMux {
	mux := http.NewServeMux()

	outputBufPool := &sync.Pool{}
	outputBufPool.New = func() any {
		return &bytes.Buffer{}
	}

	mux.HandleFunc("/", info)
	mux.HandleFunc("/search", func(w http.ResponseWriter, r *http.Request) {
		b := &strings.Builder{}
		if _, err := io.Copy(b, r.Body); err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte("Error processing request"))
			slog.Error("Error reading request body", slog.String("err", err.Error()))
			return
		}
		artifact, err := query.Compile(b.String(), 0, 1)
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			w.Write([]byte(err.Error()))
			slog.Error("Error compiling query", slog.String("err", err.Error()))
			return
		}

		pathDocs, err := db.Execute(artifact)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte("Error executing query"))
			slog.Error("Error executing query", slog.String("err", err.Error()))
			return
		}

		docs := make([]*index.Document, 0, len(pathDocs))
		var maxFileTime time.Time
		for _, doc := range pathDocs {
			docs = append(docs, doc)
			if doc.FileTime.After(maxFileTime) {
				maxFileTime = doc.FileTime
			}
		}

		if !maxFileTime.IsZero() {
			w.Header().Add("Last-Modified", maxFileTime.UTC().Format(http.TimeFormat))
		}

		buf, ok := outputBufPool.Get().(*bytes.Buffer)
		if !ok {
			panic("Expected *bytes.Buffer in pool")
		}
		_, err = query.JsonOutput{}.OutputTo(buf, docs)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			w.Write([]byte("Error while writing output"))
			slog.Error("Error writing json output", slog.String("err", err.Error()))
		}

		http.ServeContent(w, r, "result.json", maxFileTime, bytes.NewReader(buf.Bytes()))
	})

	return mux
}