|
| 1 | +package streaming |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "bytes" |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "io" |
| 9 | + "net/http" |
| 10 | + "net/url" |
| 11 | +) |
| 12 | + |
| 13 | +// NewRequest returns an http.Request against the streaming API for query. |
| 14 | +func NewRequest(baseURL string, query string) (*http.Request, error) { |
| 15 | + u := baseURL + "/search/stream?q=" + url.QueryEscape(query) |
| 16 | + req, err := http.NewRequest("GET", u, nil) |
| 17 | + if err != nil { |
| 18 | + return nil, err |
| 19 | + } |
| 20 | + req.Header.Set("Accept", "text/event-stream") |
| 21 | + return req, nil |
| 22 | +} |
| 23 | + |
| 24 | +// Decoder decodes streaming events from a Server Sent Event stream. We only |
| 25 | +// support streams which are generated by Sourcegraph. IE this is not a fully |
| 26 | +// compliant Server Sent Events decoder. |
| 27 | +type Decoder struct { |
| 28 | + OnProgress func(*Progress) |
| 29 | + OnMatches func([]EventMatch) |
| 30 | + OnFilters func([]*EventFilter) |
| 31 | + OnAlert func(*EventAlert) |
| 32 | + OnError func(*EventError) |
| 33 | + OnUnknown func(event, data []byte) |
| 34 | +} |
| 35 | + |
| 36 | +func (rr Decoder) ReadAll(r io.Reader) error { |
| 37 | + const maxPayloadSize = 10 * 1024 * 1024 // 10mb |
| 38 | + scanner := bufio.NewScanner(r) |
| 39 | + scanner.Buffer(make([]byte, 0, 4096), maxPayloadSize) |
| 40 | + // bufio.ScanLines, except we look for two \n\n which separate events. |
| 41 | + split := func(data []byte, atEOF bool) (int, []byte, error) { |
| 42 | + if atEOF && len(data) == 0 { |
| 43 | + return 0, nil, nil |
| 44 | + } |
| 45 | + if i := bytes.Index(data, []byte("\n\n")); i >= 0 { |
| 46 | + return i + 2, data[:i], nil |
| 47 | + } |
| 48 | + // If we're at EOF, we have a final, non-terminated event. This should |
| 49 | + // be empty. |
| 50 | + if atEOF { |
| 51 | + return len(data), data, nil |
| 52 | + } |
| 53 | + // Request more data. |
| 54 | + return 0, nil, nil |
| 55 | + } |
| 56 | + scanner.Split(split) |
| 57 | + |
| 58 | + for scanner.Scan() { |
| 59 | + // event: $event\n |
| 60 | + // data: json($data)\n\n |
| 61 | + data := scanner.Bytes() |
| 62 | + nl := bytes.Index(data, []byte("\n")) |
| 63 | + if nl < 0 { |
| 64 | + return fmt.Errorf("malformed event, no newline: %s", data) |
| 65 | + } |
| 66 | + |
| 67 | + eventK, event := splitColon(data[:nl]) |
| 68 | + dataK, data := splitColon(data[nl+1:]) |
| 69 | + |
| 70 | + if !bytes.Equal(eventK, []byte("event")) { |
| 71 | + return fmt.Errorf("malformed event, expected event: %s", eventK) |
| 72 | + } |
| 73 | + if !bytes.Equal(dataK, []byte("data")) { |
| 74 | + return fmt.Errorf("malformed event %s, expected data: %s", eventK, dataK) |
| 75 | + } |
| 76 | + |
| 77 | + if bytes.Equal(event, []byte("progress")) { |
| 78 | + if rr.OnProgress == nil { |
| 79 | + continue |
| 80 | + } |
| 81 | + var d Progress |
| 82 | + if err := json.Unmarshal(data, &d); err != nil { |
| 83 | + return fmt.Errorf("failed to decode progress payload: %w", err) |
| 84 | + } |
| 85 | + rr.OnProgress(&d) |
| 86 | + } else if bytes.Equal(event, []byte("matches")) { |
| 87 | + if rr.OnMatches == nil { |
| 88 | + continue |
| 89 | + } |
| 90 | + var d []eventMatchUnmarshaller |
| 91 | + if err := json.Unmarshal(data, &d); err != nil { |
| 92 | + return fmt.Errorf("failed to decode matches payload: %w", err) |
| 93 | + } |
| 94 | + m := make([]EventMatch, 0, len(d)) |
| 95 | + for _, e := range d { |
| 96 | + m = append(m, e.EventMatch) |
| 97 | + } |
| 98 | + rr.OnMatches(m) |
| 99 | + } else if bytes.Equal(event, []byte("filters")) { |
| 100 | + if rr.OnFilters == nil { |
| 101 | + continue |
| 102 | + } |
| 103 | + var d []*EventFilter |
| 104 | + if err := json.Unmarshal(data, &d); err != nil { |
| 105 | + return fmt.Errorf("failed to decode filters payload: %w", err) |
| 106 | + } |
| 107 | + rr.OnFilters(d) |
| 108 | + } else if bytes.Equal(event, []byte("alert")) { |
| 109 | + if rr.OnAlert == nil { |
| 110 | + continue |
| 111 | + } |
| 112 | + var d EventAlert |
| 113 | + if err := json.Unmarshal(data, &d); err != nil { |
| 114 | + return fmt.Errorf("failed to decode alert payload: %w", err) |
| 115 | + } |
| 116 | + rr.OnAlert(&d) |
| 117 | + } else if bytes.Equal(event, []byte("error")) { |
| 118 | + if rr.OnError == nil { |
| 119 | + continue |
| 120 | + } |
| 121 | + var d EventError |
| 122 | + if err := json.Unmarshal(data, &d); err != nil { |
| 123 | + return fmt.Errorf("failed to decode error payload: %w", err) |
| 124 | + } |
| 125 | + rr.OnError(&d) |
| 126 | + } else if bytes.Equal(event, []byte("done")) { |
| 127 | + // Always the last event |
| 128 | + break |
| 129 | + } else { |
| 130 | + if rr.OnUnknown == nil { |
| 131 | + continue |
| 132 | + } |
| 133 | + rr.OnUnknown(event, data) |
| 134 | + } |
| 135 | + } |
| 136 | + return scanner.Err() |
| 137 | +} |
| 138 | + |
| 139 | +func splitColon(data []byte) ([]byte, []byte) { |
| 140 | + i := bytes.Index(data, []byte(":")) |
| 141 | + if i < 0 { |
| 142 | + return bytes.TrimSpace(data), nil |
| 143 | + } |
| 144 | + return bytes.TrimSpace(data[:i]), bytes.TrimSpace(data[i+1:]) |
| 145 | +} |
| 146 | + |
| 147 | +type eventMatchUnmarshaller struct { |
| 148 | + EventMatch |
| 149 | +} |
| 150 | + |
| 151 | +func (r *eventMatchUnmarshaller) UnmarshalJSON(b []byte) error { |
| 152 | + var typeU struct { |
| 153 | + Type MatchType `json:"type"` |
| 154 | + } |
| 155 | + |
| 156 | + if err := json.Unmarshal(b, &typeU); err != nil { |
| 157 | + return err |
| 158 | + } |
| 159 | + |
| 160 | + switch typeU.Type { |
| 161 | + case FileMatchType: |
| 162 | + r.EventMatch = &EventFileMatch{} |
| 163 | + case RepoMatchType: |
| 164 | + r.EventMatch = &EventRepoMatch{} |
| 165 | + case SymbolMatchType: |
| 166 | + r.EventMatch = &EventSymbolMatch{} |
| 167 | + case CommitMatchType: |
| 168 | + r.EventMatch = &EventCommitMatch{} |
| 169 | + default: |
| 170 | + return fmt.Errorf("unknown MatchType %v", typeU.Type) |
| 171 | + } |
| 172 | + return json.Unmarshal(b, r.EventMatch) |
| 173 | +} |
0 commit comments