fork of https://github.com/sourcegraph/zoekt
0

Configure Feed

Select the types of activity you want to include in your feed.

1// Copyright 2016 Google Inc. All rights reserved. 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15package web 16 17import ( 18 "bytes" 19 "context" 20 "encoding/json" 21 "fmt" 22 "html/template" 23 "log" 24 "net" 25 "net/http" 26 "regexp/syntax" 27 "sort" 28 "strconv" 29 "strings" 30 "sync" 31 "time" 32 33 "github.com/grafana/regexp" 34 "github.com/sourcegraph/zoekt" 35 zjson "github.com/sourcegraph/zoekt/json" 36 "github.com/sourcegraph/zoekt/query" 37 "github.com/sourcegraph/zoekt/rpc" 38 "github.com/sourcegraph/zoekt/stream" 39) 40 41var Funcmap = template.FuncMap{ 42 "Inc": func(orig int) int { 43 return orig + 1 44 }, 45 "More": func(orig int) int { 46 return orig * 3 47 }, 48 "HumanUnit": func(orig int64) string { 49 b := orig 50 suffix := "" 51 if orig > 10*(1<<30) { 52 suffix = "G" 53 b = orig / (1 << 30) 54 } else if orig > 10*(1<<20) { 55 suffix = "M" 56 b = orig / (1 << 20) 57 } else if orig > 10*(1<<10) { 58 suffix = "K" 59 b = orig / (1 << 10) 60 } 61 62 return fmt.Sprintf("%d%s", b, suffix) 63 }, 64 "LimitPre": func(limit int, pre string) string { 65 if len(pre) < limit { 66 return pre 67 } 68 return fmt.Sprintf("...(%d bytes skipped)...%s", len(pre)-limit, pre[len(pre)-limit:]) 69 }, 70 "LimitPost": func(limit int, post string) string { 71 if len(post) < limit { 72 return post 73 } 74 return fmt.Sprintf("%s...(%d bytes skipped)...", post[:limit], len(post)-limit) 75 }, 76} 77 78const defaultNumResults = 50 79 80type Server struct { 81 Searcher zoekt.Streamer 82 83 // Serve HTML interface 84 HTML bool 85 86 // Serve RPC 87 RPC bool 88 89 // If set, show files from the index. 90 Print bool 91 92 // Version string for this server. 93 Version string 94 95 // Depending on the Host header, add a query to the entry 96 // page. For example, when serving on "search.myproject.org" 97 // we could add "r:myproject" automatically. This allows a 98 // single instance to serve as search engine for multiple 99 // domains. 100 HostCustomQueries map[string]string 101 102 // This should contain the following templates: "repolist" 103 // (for the repo search result page), "result" for 104 // the search results, "search" (for the opening page), 105 // "box" for the search query input element and 106 // "print" for the show file functionality. 107 Top *template.Template 108 109 repolist *template.Template 110 search *template.Template 111 result *template.Template 112 print *template.Template 113 about *template.Template 114 robots *template.Template 115 116 startTime time.Time 117 118 templateMu sync.Mutex 119 templateCache map[string]*template.Template 120 121 lastStatsMu sync.Mutex 122 lastStats *zoekt.RepoStats 123 lastStatsTS time.Time 124} 125 126func (s *Server) getTemplate(str string) *template.Template { 127 s.templateMu.Lock() 128 defer s.templateMu.Unlock() 129 t := s.templateCache[str] 130 if t != nil { 131 return t 132 } 133 134 t, err := template.New("cache").Parse(str) 135 if err != nil { 136 log.Printf("template parse error: %v", err) 137 t = template.Must(template.New("empty").Parse("")) 138 } 139 s.templateCache[str] = t 140 return t 141} 142 143func NewMux(s *Server) (*http.ServeMux, error) { 144 s.print = s.Top.Lookup("print") 145 if s.print == nil { 146 return nil, fmt.Errorf("missing template 'print'") 147 } 148 149 for k, v := range map[string]**template.Template{ 150 "results": &s.result, 151 "print": &s.print, 152 "search": &s.search, 153 "repolist": &s.repolist, 154 "about": &s.about, 155 "robots": &s.robots, 156 } { 157 *v = s.Top.Lookup(k) 158 if *v == nil { 159 return nil, fmt.Errorf("missing template %q", k) 160 } 161 } 162 163 s.templateCache = map[string]*template.Template{} 164 s.startTime = time.Now() 165 166 mux := http.NewServeMux() 167 168 if s.HTML { 169 mux.HandleFunc("/robots.txt", s.serveRobots) 170 mux.HandleFunc("/search", s.serveSearch) 171 mux.HandleFunc("/", s.serveSearchBox) 172 mux.HandleFunc("/about", s.serveAbout) 173 mux.HandleFunc("/print", s.servePrint) 174 } 175 if s.RPC { 176 mux.Handle(rpc.DefaultRPCPath, rpc.Server(traceAwareSearcher{s.Searcher})) // /rpc 177 mux.Handle("/api/", http.StripPrefix("/api", zjson.JSONServer(traceAwareSearcher{s.Searcher}))) 178 mux.Handle(stream.DefaultSSEPath, stream.Server(traceAwareSearcher{s.Searcher})) // /stream 179 } 180 181 mux.HandleFunc("/healthz", s.serveHealthz) 182 183 return mux, nil 184} 185 186func (s *Server) serveHealthz(w http.ResponseWriter, r *http.Request) { 187 q := &query.Const{Value: true} 188 opts := &zoekt.SearchOptions{ShardMaxMatchCount: 1, TotalMaxMatchCount: 1, MaxDocDisplayCount: 1} 189 190 result, err := s.Searcher.Search(r.Context(), q, opts) 191 if err != nil { 192 http.Error(w, fmt.Sprintf("not ready: %v", err), http.StatusInternalServerError) 193 return 194 } 195 196 w.Header().Set("Content-Type", "application/json") 197 198 _ = json.NewEncoder(w).Encode(result) 199} 200 201func (s *Server) serveSearch(w http.ResponseWriter, r *http.Request) { 202 result, err := s.serveSearchErr(r) 203 if err != nil { 204 http.Error(w, err.Error(), http.StatusTeapot) 205 return 206 } 207 208 qvals := r.URL.Query() 209 if qvals.Get("format") == "json" { 210 w.Header().Add("Content-Type", "application/json") 211 encoder := json.NewEncoder(w) 212 encoder.Encode(result) 213 return 214 } 215 216 var buf bytes.Buffer 217 if result.Repos != nil { 218 err = s.repolist.Execute(&buf, &result.Repos) 219 } else if result.Result != nil { 220 err = s.result.Execute(&buf, &result.Result) 221 } 222 if err != nil { 223 http.Error(w, err.Error(), http.StatusTeapot) 224 return 225 } 226 w.Write(buf.Bytes()) 227} 228 229func (s *Server) serveSearchErr(r *http.Request) (*ApiSearchResult, error) { 230 qvals := r.URL.Query() 231 232 debugScore, _ := strconv.ParseBool(qvals.Get("debug")) 233 234 queryStr := qvals.Get("q") 235 if queryStr == "" { 236 return nil, fmt.Errorf("no query found") 237 } 238 239 q, err := query.Parse(queryStr) 240 if err != nil { 241 return nil, err 242 } 243 244 repoOnly := true 245 query.VisitAtoms(q, func(q query.Q) { 246 _, ok := q.(*query.Repo) 247 repoOnly = repoOnly && ok 248 }) 249 if repoOnly { 250 repos, err := s.serveListReposErr(q, queryStr, r) 251 if err == nil { 252 return &ApiSearchResult{Repos: repos}, nil 253 } 254 return nil, err 255 } 256 257 if qt, ok := q.(*query.Type); ok && qt.Type == query.TypeRepo { 258 repos, err := s.serveListReposErr(q, queryStr, r) 259 if err == nil { 260 return &ApiSearchResult{Repos: repos}, nil 261 } 262 return nil, err 263 } 264 265 numStr := qvals.Get("num") 266 267 num, err := strconv.Atoi(numStr) 268 if err != nil || num <= 0 { 269 num = defaultNumResults 270 } 271 272 sOpts := zoekt.SearchOptions{ 273 MaxWallTime: 10 * time.Second, 274 } 275 276 numCtxLines := 0 277 if qvals.Get("format") == "json" { 278 if ctxLinesStr := qvals.Get("ctx"); ctxLinesStr != "" { 279 numCtxLines, err = strconv.Atoi(ctxLinesStr) 280 if err != nil || numCtxLines < 0 || numCtxLines > 10 { 281 return nil, fmt.Errorf("Number of context lines must be between 0 and 10") 282 } 283 } 284 } 285 sOpts.NumContextLines = numCtxLines 286 287 sOpts.SetDefaults() 288 sOpts.MaxDocDisplayCount = num 289 sOpts.DebugScore = debugScore 290 291 ctx := r.Context() 292 if err := zjson.CalculateDefaultSearchLimits(ctx, q, s.Searcher, &sOpts); err != nil { 293 return nil, err 294 } 295 296 result, err := s.Searcher.Search(ctx, q, &sOpts) 297 if err != nil { 298 return nil, err 299 } 300 301 fileMatches, err := s.formatResults(result, queryStr, s.Print) 302 if err != nil { 303 return nil, err 304 } 305 306 res := ResultInput{ 307 Last: LastInput{ 308 Query: queryStr, 309 Num: num, 310 AutoFocus: true, 311 }, 312 Stats: result.Stats, 313 Query: q.String(), 314 QueryStr: queryStr, 315 FileMatches: fileMatches, 316 } 317 if res.Stats.Wait < res.Stats.Duration/10 { 318 // Suppress queueing stats if they are neglible. 319 res.Stats.Wait = 0 320 } 321 322 res.Last.Debug = debugScore 323 return &ApiSearchResult{Result: &res}, nil 324} 325 326func (s *Server) servePrint(w http.ResponseWriter, r *http.Request) { 327 err := s.servePrintErr(w, r) 328 if err != nil { 329 http.Error(w, err.Error(), http.StatusTeapot) 330 } 331} 332 333const statsStaleNess = 30 * time.Second 334 335func (s *Server) fetchStats(ctx context.Context) (*zoekt.RepoStats, error) { 336 s.lastStatsMu.Lock() 337 stats := s.lastStats 338 if time.Since(s.lastStatsTS) > statsStaleNess { 339 stats = nil 340 } 341 s.lastStatsMu.Unlock() 342 343 if stats != nil { 344 return stats, nil 345 } 346 347 repos, err := s.Searcher.List(ctx, &query.Const{Value: true}, nil) 348 if err != nil { 349 return nil, err 350 } 351 352 stats = &zoekt.RepoStats{} 353 names := map[string]struct{}{} 354 for _, r := range repos.Repos { 355 stats.Add(&r.Stats) 356 names[r.Repository.Name] = struct{}{} 357 } 358 stats.Repos = len(names) 359 360 s.lastStatsMu.Lock() 361 s.lastStatsTS = time.Now() 362 s.lastStats = stats 363 s.lastStatsMu.Unlock() 364 365 return stats, nil 366} 367 368func (s *Server) serveSearchBoxErr(w http.ResponseWriter, r *http.Request) error { 369 stats, err := s.fetchStats(r.Context()) 370 if err != nil { 371 return err 372 } 373 d := SearchBoxInput{ 374 Last: LastInput{ 375 Num: defaultNumResults, 376 AutoFocus: true, 377 }, 378 Stats: stats, 379 Version: s.Version, 380 Uptime: time.Since(s.startTime), 381 } 382 383 d.Last.Query = r.URL.Query().Get("q") 384 if d.Last.Query == "" { 385 custom := s.HostCustomQueries[r.Host] 386 if custom == "" { 387 host, _, _ := net.SplitHostPort(r.Host) 388 custom = s.HostCustomQueries[host] 389 } 390 391 if custom != "" { 392 d.Last.Query = custom + " " 393 } 394 } 395 396 var buf bytes.Buffer 397 if err := s.search.Execute(&buf, &d); err != nil { 398 return err 399 } 400 _, _ = w.Write(buf.Bytes()) 401 return nil 402} 403 404func (s *Server) serveSearchBox(w http.ResponseWriter, r *http.Request) { 405 if err := s.serveSearchBoxErr(w, r); err != nil { 406 http.Error(w, err.Error(), http.StatusTeapot) 407 } 408} 409 410func (s *Server) serveAboutErr(w http.ResponseWriter, r *http.Request) error { 411 stats, err := s.fetchStats(r.Context()) 412 if err != nil { 413 return err 414 } 415 416 d := SearchBoxInput{ 417 Stats: stats, 418 Version: s.Version, 419 Uptime: time.Since(s.startTime), 420 } 421 422 var buf bytes.Buffer 423 if err := s.about.Execute(&buf, &d); err != nil { 424 return err 425 } 426 _, _ = w.Write(buf.Bytes()) 427 return nil 428} 429 430func (s *Server) serveAbout(w http.ResponseWriter, r *http.Request) { 431 if err := s.serveAboutErr(w, r); err != nil { 432 http.Error(w, err.Error(), http.StatusTeapot) 433 } 434} 435 436func (s *Server) serveRobotsErr(w http.ResponseWriter, r *http.Request) error { 437 data := struct{}{} 438 var buf bytes.Buffer 439 if err := s.robots.Execute(&buf, &data); err != nil { 440 return err 441 } 442 _, _ = w.Write(buf.Bytes()) 443 return nil 444} 445 446func (s *Server) serveRobots(w http.ResponseWriter, r *http.Request) { 447 if err := s.serveRobotsErr(w, r); err != nil { 448 http.Error(w, err.Error(), http.StatusTeapot) 449 } 450} 451 452func (s *Server) serveListReposErr(q query.Q, qStr string, r *http.Request) (*RepoListInput, error) { 453 ctx := r.Context() 454 repos, err := s.Searcher.List(ctx, q, nil) 455 if err != nil { 456 return nil, err 457 } 458 459 qvals := r.URL.Query() 460 order := qvals.Get("order") 461 switch order { 462 case "", "name", "revname": 463 sort.Slice(repos.Repos, func(i, j int) bool { 464 return strings.Compare(repos.Repos[i].Repository.Name, repos.Repos[j].Repository.Name) < 0 465 }) 466 case "size", "revsize": 467 sort.Slice(repos.Repos, func(i, j int) bool { 468 return repos.Repos[i].Stats.ContentBytes < repos.Repos[j].Stats.ContentBytes 469 }) 470 case "ram", "revram": 471 sort.Slice(repos.Repos, func(i, j int) bool { 472 return repos.Repos[i].Stats.IndexBytes < repos.Repos[j].Stats.IndexBytes 473 }) 474 case "time", "revtime": 475 sort.Slice(repos.Repos, func(i, j int) bool { 476 return repos.Repos[i].IndexMetadata.IndexTime.Before( 477 repos.Repos[j].IndexMetadata.IndexTime) 478 }) 479 default: 480 return nil, fmt.Errorf("got unknown sort key %q, allowed [rev]name, [rev]time, [rev]size", order) 481 } 482 if strings.HasPrefix(order, "rev") { 483 for i, j := 0, len(repos.Repos)-1; i < j; { 484 repos.Repos[i], repos.Repos[j] = repos.Repos[j], repos.Repos[i] 485 i++ 486 j-- 487 488 } 489 } 490 491 aggregate := zoekt.RepoStats{ 492 Repos: len(repos.Repos), 493 } 494 for _, s := range repos.Repos { 495 aggregate.Add(&s.Stats) 496 } 497 498 numStr := qvals.Get("num") 499 num, err := strconv.Atoi(numStr) 500 if err != nil || num <= 0 { 501 num = 0 502 } 503 if num > 0 { 504 if num > len(repos.Repos) { 505 num = len(repos.Repos) 506 } 507 508 repos.Repos = repos.Repos[:num] 509 } 510 511 res := RepoListInput{ 512 Last: LastInput{ 513 Query: qStr, 514 Num: num, 515 AutoFocus: true, 516 }, 517 Stats: aggregate, 518 } 519 520 for _, r := range repos.Repos { 521 t := s.getTemplate(r.Repository.CommitURLTemplate) 522 523 repo := Repository{ 524 Name: r.Repository.Name, 525 URL: r.Repository.URL, 526 IndexTime: r.IndexMetadata.IndexTime, 527 Size: r.Stats.ContentBytes, 528 MemorySize: r.Stats.IndexBytes, 529 Files: int64(r.Stats.Documents), 530 } 531 for _, b := range r.Repository.Branches { 532 var buf bytes.Buffer 533 if err := t.Execute(&buf, b); err != nil { 534 return nil, err 535 } 536 repo.Branches = append(repo.Branches, 537 Branch{ 538 Name: b.Name, 539 Version: b.Version, 540 URL: buf.String(), 541 }) 542 } 543 res.Repos = append(res.Repos, repo) 544 } 545 return &res, nil 546} 547 548func (s *Server) servePrintErr(w http.ResponseWriter, r *http.Request) error { 549 qvals := r.URL.Query() 550 fileStr := qvals.Get("f") 551 repoStr := qvals.Get("r") 552 queryStr := qvals.Get("q") 553 numStr := qvals.Get("num") 554 num, err := strconv.Atoi(numStr) 555 if err != nil || num <= 0 { 556 num = defaultNumResults 557 } 558 559 re, err := syntax.Parse("^"+regexp.QuoteMeta(fileStr)+"$", 0) 560 if err != nil { 561 return err 562 } 563 564 repoRe, err := regexp.Compile("^" + regexp.QuoteMeta(repoStr) + "$") 565 566 if err != nil { 567 return err 568 } 569 570 qs := []query.Q{ 571 &query.Regexp{Regexp: re, FileName: true, CaseSensitive: true}, 572 &query.Repo{Regexp: repoRe}, 573 } 574 575 if branchStr := qvals.Get("b"); branchStr != "" { 576 qs = append(qs, &query.Branch{Pattern: branchStr}) 577 } 578 579 q := &query.And{Children: qs} 580 581 sOpts := zoekt.SearchOptions{ 582 Whole: true, 583 } 584 585 ctx := r.Context() 586 result, err := s.Searcher.Search(ctx, q, &sOpts) 587 if err != nil { 588 return err 589 } 590 591 if len(result.Files) != 1 { 592 var ss []string 593 for _, n := range result.Files { 594 ss = append(ss, n.FileName) 595 } 596 return fmt.Errorf("ambiguous result: %v", ss) 597 } 598 599 f := result.Files[0] 600 601 byteLines := bytes.Split(f.Content, []byte{'\n'}) 602 strLines := make([]string, 0, len(byteLines)) 603 for _, l := range byteLines { 604 strLines = append(strLines, string(l)) 605 } 606 607 d := PrintInput{ 608 Name: f.FileName, 609 Repo: f.Repository, 610 Lines: strLines, 611 Last: LastInput{ 612 Query: queryStr, 613 Num: num, 614 AutoFocus: false, 615 }, 616 } 617 618 var buf bytes.Buffer 619 if err := s.print.Execute(&buf, &d); err != nil { 620 return err 621 } 622 623 _, _ = w.Write(buf.Bytes()) 624 return nil 625}