-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
411 lines (351 loc) · 8.67 KB
/
main.go
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
package main
import (
"bufio"
"compress/bzip2"
"encoding/xml"
"flag"
"fmt"
"html/template"
"io"
"log"
"net/http"
_ "net/http/pprof"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"sync"
"github.com/blevesearch/bleve"
"github.com/creachadair/cityhash"
pbzip2 "github.com/d4l3k/go-pbzip2"
"github.com/d4l3k/wikigopher/wikitext"
"github.com/pkg/errors"
)
var (
indexFile = flag.String("index", "enwiki-latest-pages-articles-multistream-index.txt.bz2", "the index file to load")
articlesFile = flag.String("articles", "enwiki-latest-pages-articles-multistream.xml.bz2", "the article dump file to load")
search = flag.Bool("search", false, "whether or not to build a search index")
searchIndexFile = flag.String("searchIndex", "index.bleve", "the search index file")
httpAddr = flag.String("http", ":8080", "the address to bind HTTP to")
)
var tmpls = map[string]*template.Template{}
func loadTemplates() error {
files, err := filepath.Glob("templates/*")
if err != nil {
return err
}
for _, file := range files {
name := filepath.Base(file)
tmpls[name], err = template.ParseFiles("templates/base.html", file)
if err != nil {
return err
}
}
return nil
}
func executeTemplate(wr io.Writer, name string, data interface{}) error {
return tmpls[name].ExecuteTemplate(wr, "base", data)
}
type indexEntry struct {
id, seek int
}
var mu = struct {
sync.Mutex
offsets map[uint64]indexEntry
offsetSize map[int]int
}{
offsets: map[uint64]indexEntry{},
offsetSize: map[int]int{},
}
var index bleve.Index
func loadIndex() error {
mapping := bleve.NewIndexMapping()
os.RemoveAll(*searchIndexFile)
var err error
index, err = bleve.New(*searchIndexFile, mapping)
if err != nil {
return err
}
f, err := os.Open(*indexFile)
if err != nil {
return err
}
defer f.Close()
r, err := pbzip2.NewReader(f)
if err != nil {
return err
}
defer r.Close()
scanner := bufio.NewScanner(r)
log.Printf("Reading index file...")
i := 0
for scanner.Scan() {
parts := strings.Split(scanner.Text(), ":")
if len(parts) < 3 {
return errors.Errorf("expected at least 3 parts, got: %#v", parts)
}
seek, err := strconv.Atoi(parts[0])
if err != nil {
return err
}
id, err := strconv.Atoi(parts[1])
if err != nil {
return err
}
title := strings.Join(parts[2:], ":")
entry := indexEntry{
id: id,
seek: seek,
}
titleHash := cityhash.Hash64([]byte(title))
mu.Lock()
mu.offsets[titleHash] = entry
mu.offsetSize[entry.seek]++
mu.Unlock()
i++
if i%100000 == 0 {
log.Printf("read %d entries", i)
}
}
if err := scanner.Err(); err != nil {
return err
}
log.Printf("Done reading!")
if !*search {
return nil
}
/*
log.Printf("Indexing titles...")
i = 0
batch := index.NewBatch()
mu.Lock()
defer mu.Unlock()
for key, entry := range mu.offsets {
mu.Unlock()
if err := batch.Index(key, entry); err != nil {
mu.Lock()
return err
}
i++
if i%100000 == 0 {
if err := index.Batch(batch); err != nil {
mu.Lock()
return err
}
batch.Reset()
log.Printf("indexed %d entries", i)
}
mu.Lock()
}
log.Printf("Done indexing!")
*/
return nil
}
/*
Example:
<page>
<title>AccessibleComputing</title>
<ns>0</ns>
<id>10</id>
<redirect title="Computer accessibility" />
<revision>
<id>834079434</id>
<parentid>767284433</parentid>
<timestamp>2018-04-03T20:38:02Z</timestamp>
<contributor>
<username>امیر اعوانی</username>
<id>8214454</id>
</contributor>
<minor />
<model>wikitext</model>
<format>text/x-wiki</format>
<text xml:space="preserve">#REDIRECT [[Computer accessibility]]
{{Redirect category shell}}
{{R from move}}
{{R from CamelCase}}
{{R unprintworthy}}</text>
<sha1>qdiw0cwardl0qpkyeutu3pd77fwym8y</sha1>
</revision>
</page>
*/
type redirect struct {
Title string `xml:"title,attr"`
}
type page struct {
XMLName xml.Name `xml:"page"`
Title string `xml:"title"`
NS int `xml:"ns"`
ID int `xml:"id"`
Redirect []redirect `xml:"redirect"`
RevisionID string `xml:"revision>id"`
Timestamp string `xml:"revision>timestamp"`
Username string `xml:"revision>contributor>username"`
UserID string `xml:"revision>contributor>id"`
Model string `xml:"revision>model"`
Format string `xml:"revision>format"`
Text string `xml:"revision>text"`
}
func readArticle(meta indexEntry) (page, error) {
f, err := os.Open(*articlesFile)
if err != nil {
return page{}, err
}
defer f.Close()
mu.Lock()
maxTries := mu.offsetSize[meta.seek]
mu.Unlock()
r := bzip2.NewReader(f)
if _, err := f.Seek(int64(meta.seek), 0); err != nil {
return page{}, err
}
d := xml.NewDecoder(r)
var p page
for i := 0; i < maxTries; i++ {
if err := d.Decode(&p); err != nil {
return page{}, err
}
if p.ID == meta.id {
return p, nil
}
}
return page{}, errors.Errorf("failed to find page after %d tries", maxTries)
}
func fetchArticle(name string) (indexEntry, error) {
mu.Lock()
defer mu.Unlock()
articleMeta, ok := mu.offsets[cityhash.Hash64([]byte(name))]
if ok {
return articleMeta, nil
}
articleMeta, ok = mu.offsets[cityhash.Hash64([]byte(strings.Title(strings.ToLower(name))))]
if ok {
return articleMeta, nil
}
return indexEntry{}, statusErrorf(http.StatusNotFound, "article not found: %q", name)
}
func randomArticleHash() (uint64, error) {
mu.Lock()
defer mu.Unlock()
for hash := range mu.offsets {
return hash, nil
}
return 0, errors.Errorf("no articles")
}
func randomArticle() (page, error) {
hash, err := randomArticleHash()
if err != nil {
return page{}, err
}
mu.Lock()
meta := mu.offsets[hash]
mu.Unlock()
return readArticle(meta)
}
type statusError int
func (s statusError) Error() string {
return fmt.Sprintf("%d - %s", int(s), http.StatusText(int(s)))
}
func statusErrorf(code int, str string, args ...interface{}) error {
return errors.Wrapf(statusError(code), str, args...)
}
func errorHandler(f func(w http.ResponseWriter, r *http.Request) error) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := f(w, r); err != nil {
cause := errors.Cause(err)
status := http.StatusInternalServerError
if cause, ok := cause.(statusError); ok {
status = int(cause)
}
if err := executeTemplate(w, "error.html", struct {
Title, Error string
}{
Title: err.Error(),
Error: fmt.Sprintf("%+v", err),
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(status)
}
}
}
func handleArticle(w http.ResponseWriter, r *http.Request) error {
articleName := wikitext.URLToTitle(path.Base(r.URL.Path))
if articleName == "Special:Random" {
article, err := randomArticle()
if err != nil {
return err
}
http.Redirect(w, r, path.Join("/wiki/", wikitext.TitleToURL(article.Title)), http.StatusTemporaryRedirect)
return nil
}
articleMeta, err := fetchArticle(articleName)
if err != nil {
return err
}
p, err := readArticle(articleMeta)
if err != nil {
return err
}
if p.Title != articleName {
http.Redirect(w, r, path.Join("/wiki/", wikitext.TitleToURL(p.Title)), http.StatusTemporaryRedirect)
return nil
}
body, err := wikitext.Convert(
[]byte(p.Text),
wikitext.TemplateHandler(p.templateHandler),
)
if err != nil {
return err
}
if err := executeTemplate(w, "article.html", struct {
Title string
Body template.HTML
}{
Title: articleName,
Body: template.HTML(body),
}); err != nil {
return err
}
return nil
}
func handleSource(w http.ResponseWriter, r *http.Request) error {
articleName := wikitext.URLToTitle(path.Base(r.URL.Path))
articleMeta, err := fetchArticle(articleName)
if err != nil {
return err
}
p, err := readArticle(articleMeta)
if err != nil {
return err
}
return executeTemplate(w, "source.html", p)
}
func handleIndex(w http.ResponseWriter, r *http.Request) error {
http.Redirect(w, r, "/wiki/Main_Page", http.StatusTemporaryRedirect)
return nil
}
func main() {
if err := run(); err != nil {
log.Fatalf("%+v", err)
}
}
func run() error {
flag.Parse()
log.SetFlags(log.Flags() | log.Lshortfile)
go func() {
if err := loadIndex(); err != nil {
log.Fatalf("%+v", err)
}
}()
if err := loadTemplates(); err != nil {
return err
}
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
http.HandleFunc("/source/", errorHandler(handleSource))
http.HandleFunc("/wiki/", errorHandler(handleArticle))
http.HandleFunc("/", errorHandler(handleIndex))
log.Printf("Listening on %s...", *httpAddr)
return http.ListenAndServe(*httpAddr, nil)
}