all repos — homestead @ 82424b77fba708e4450c1a0cec5b0c7967b13d7b

Code for my website

shared/storage/sqlite/writer.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
package sqlite

import (
	"context"
	"database/sql"
	"encoding/json"
	"fmt"
	"hash/fnv"
	"io"
	"mime"
	"net/http"
	"os"
	"path/filepath"
	"time"

	"alin.ovh/homestead/domain/content"
	"alin.ovh/homestead/shared/buffer"
	"alin.ovh/homestead/shared/storage"
	"alin.ovh/homestead/shared/storage/sqlite/db"
	"alin.ovh/x/log"
	"github.com/andybalholm/brotli"
	"github.com/klauspost/compress/gzip"
	"github.com/klauspost/compress/zstd"

	"github.com/Southclaws/fault"
	"github.com/Southclaws/fault/fmsg"
	_ "modernc.org/sqlite" // import registers db/SQL driver
)

var encodings = []string{"gzip", "br", "zstd"}

type Writer struct {
	options *Options
	log     *log.Logger
	queries *db.Queries
}

type Options struct {
	Compress bool
}

func OpenDB(dbPath string) (*sql.DB, error) {
	db, err := sql.Open(
		"sqlite",
		fmt.Sprintf(
			"file:%s?mode=%s&_pragma=foreign_keys(1)&_pragma=mmap_size(%d)",
			dbPath,
			"rwc",
			16*1024*1024,
		),
	)
	if err != nil {
		return nil, fault.Wrap(err)
	}

	return db, nil
}

func NewWriter(conn *sql.DB, logger *log.Logger, opts *Options) (*Writer, error) {
	q, err := os.ReadFile("schema.sql")
	if err != nil {
		return nil, fault.Wrap(err)
	}

	_, err = conn.Exec(string(q))
	if err != nil {
		return nil, fault.Wrap(err, fmsg.With("creating tables"))
	}

	w := &Writer{
		queries: db.New(conn),
		log:     logger,
		options: opts,
	}

	return w, nil
}

func (s *Writer) Mkdirp(string) error {
	return nil
}

func (s *Writer) storeURL(path string) (int64, error) {
	id, err := s.queries.InsertURL(context.TODO(), path)
	if err != nil {
		return 0, fault.Wrap(err, fmsg.With(fmt.Sprintf("inserting URL %s into database", path)))
	}

	return id, nil
}

func (s *Writer) storeFile(urlID int64, file *storage.File) (int64, error) {
	if file.ContentType == "" {
		file.ContentType = http.DetectContentType(file.Encodings["identity"].Bytes())
		s.log.Warn(
			"file has no content type, sniffing",
			"path",
			file.Path,
			"sniffed",
			file.ContentType,
		)
	}
	params := db.InsertFileParams{
		UrlID:        urlID,
		ContentType:  file.ContentType,
		LastModified: file.LastModified.Unix(),
		Etag:         file.Etag,
		StyleHash:    file.StyleHash,
		Title:        file.Title,
		Headers:      []byte{},
	}
	if file.Headers != nil {
		var err error
		params.Headers, err = json.Marshal(file.Headers)
		if err != nil {
			return 0, fault.Wrap(err, fmsg.With("marshalling headers to JSON"))
		}
	}
	id, err := s.queries.InsertFile(context.TODO(), params)
	if err != nil {
		return 0, fault.Wrap(err, fmsg.With("inserting file into database"))
	}

	return id, nil
}

func (s *Writer) storeEncoding(fileID int64, encoding string, data []byte) error {
	err := s.queries.InsertContent(context.TODO(), db.InsertContentParams{
		Fileid:   fileID,
		Encoding: encoding,
		Body:     data,
	})
	if err != nil {
		return fault.Wrap(
			err,
			fmsg.With(fmt.Sprintf("inserting encoding into database file_id: %d encoding: %s",
				fileID,
				encoding)),
		)
	}

	return nil
}

func etag(content []byte) (string, error) {
	hash := fnv.New64a()
	_, err := hash.Write(content)
	if err != nil {
		return "", fault.Wrap(err)
	}

	return fmt.Sprintf(`W/"%x"`, hash.Sum(nil)), nil
}

func contentType(pathname string) string {
	return mime.TypeByExtension(filepath.Ext(pathNameToFileName(pathname)))
}

func (s *Writer) NewFileFromPost(post *content.Post) *storage.File {
	file := &storage.File{
		Title:        post.Title,
		Path:         post.URL,
		FSPath:       pathNameToFileName(post.URL),
		LastModified: post.Date,
		Encodings:    map[string]*buffer.Buffer{},
	}

	return file
}

func (s *Writer) WritePost(post *content.Post, content *buffer.Buffer) error {
	s.log.Debug("storing post", "title", post.Title)

	return s.WriteFile(s.NewFileFromPost(post), content)
}

func (s *Writer) Write(pathname string, title string, content *buffer.Buffer) error {
	file := &storage.File{
		Title:        title,
		Path:         cleanPathName(pathname),
		FSPath:       pathname,
		LastModified: time.Now(),
		Encodings:    map[string]*buffer.Buffer{},
	}

	return s.WriteFile(file, content)
}

func (s *Writer) WriteFile(file *storage.File, content *buffer.Buffer) error {
	s.log.Debug("storing content", "pathname", file.Path)

	urlID, err := s.storeURL(file.Path)
	if err != nil {
		return fault.Wrap(err, fmsg.With("storing URL"))
	}

	if file.Encodings == nil {
		file.Encodings = map[string]*buffer.Buffer{}
	}
	file.Encodings["identity"] = content

	if file.ContentType == "" {
		file.ContentType = contentType(file.FSPath)
	}

	if file.Etag == "" {
		file.Etag, err = etag(content.Bytes())
		if err != nil {
			return fault.Wrap(err, fmsg.With("could not calculate file etag"))
		}
	}

	if err := content.SeekStart(); err != nil {
		return fault.Wrap(err, fmsg.With("seeking content start"))
	}

	err = file.CalculateStyleHash()
	if err != nil {
		return fault.Wrap(err, fmsg.With("calculating file hash"))
	}

	fileID, err := s.storeFile(urlID, file)
	if err != nil {
		return fault.Wrap(err, fmsg.With("storing file"))
	}

	err = s.storeEncoding(fileID, "identity", content.Bytes())
	if err != nil {
		return err
	}

	if s.options.Compress {
		for _, enc := range encodings {
			compressed, err := compress(enc, content)
			if err != nil {
				return fault.Wrap(err, fmsg.With("compressing file"))
			}

			err = s.storeEncoding(fileID, enc, compressed.Bytes())
			if err != nil {
				return err
			}

		}
	}

	return nil
}

func compress(encoding string, content *buffer.Buffer) (*buffer.Buffer, error) {
	var w io.WriteCloser
	compressed := new(buffer.Buffer)
	switch encoding {
	case "gzip":
		w = gzip.NewWriter(compressed)
	case "br":
		w = brotli.NewWriter(compressed)
	case "zstd":
		var err error
		w, err = zstd.NewWriter(compressed)
		if err != nil {
			return nil, fault.Wrap(err, fmsg.With("could not create zstd writer"))
		}
	}
	defer w.Close()

	if err := content.SeekStart(); err != nil {
		return nil, fault.Wrap(err, fmsg.With("seeking to start of content buffer"))
	}
	if _, err := io.Copy(w, content); err != nil {
		return nil, fault.Wrap(err, fmsg.With("compressing file"))
	}

	return compressed, nil
}