-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
response_writer.go
292 lines (263 loc) · 6.74 KB
/
response_writer.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
package query
//lint:file-ignore SA1019 Ignore for now
import (
"context"
"encoding/csv"
"encoding/json"
"io"
"strconv"
"time"
"github.com/influxdata/influxdb/v2/influxql"
"github.com/influxdata/influxdb/v2/kit/tracing"
"github.com/influxdata/influxdb/v2/models"
"github.com/tinylib/msgp/msgp"
)
// ResponseWriter is an interface for writing a response.
type ResponseWriter interface {
// WriteResponse writes a response.
WriteResponse(ctx context.Context, w io.Writer, resp Response) error
}
// NewResponseWriter creates a new ResponseWriter based on the Accept header
// in the request that wraps the ResponseWriter.
func NewResponseWriter(encoding influxql.EncodingFormat) ResponseWriter {
switch encoding {
case influxql.EncodingFormatAppCSV, influxql.EncodingFormatTextCSV:
return &csvFormatter{statementID: -1}
case influxql.EncodingFormatMessagePack:
return &msgpFormatter{}
case influxql.EncodingFormatJSON:
fallthrough
default:
// TODO(sgc): Add EncodingFormatJSONPretty
return &jsonFormatter{Pretty: false}
}
}
type jsonFormatter struct {
Pretty bool
}
func (f *jsonFormatter) WriteResponse(ctx context.Context, w io.Writer, resp Response) (err error) {
span, _ := tracing.StartSpanFromContext(ctx)
defer span.Finish()
var b []byte
if f.Pretty {
b, err = json.MarshalIndent(resp, "", " ")
} else {
b, err = json.Marshal(resp)
}
if err != nil {
_, err = io.WriteString(w, err.Error())
} else {
_, err = w.Write(b)
}
w.Write([]byte("\n"))
return err
}
type csvFormatter struct {
statementID int
columns []string
}
func (f *csvFormatter) WriteResponse(ctx context.Context, w io.Writer, resp Response) (err error) {
span, _ := tracing.StartSpanFromContext(ctx)
defer span.Finish()
wr := csv.NewWriter(w)
if resp.Err != nil {
wr.Write([]string{"error"})
wr.Write([]string{resp.Err.Error()})
wr.Flush()
return wr.Error()
}
for _, result := range resp.Results {
if result.StatementID != f.statementID {
// If there are no series in the result, skip past this result.
if len(result.Series) == 0 {
continue
}
// Set the statement id and print out a newline if this is not the first statement.
if f.statementID >= 0 {
// Flush the csv writer and write a newline.
wr.Flush()
if err := wr.Error(); err != nil {
return err
}
if _, err := io.WriteString(w, "\n"); err != nil {
return err
}
}
f.statementID = result.StatementID
// Print out the column headers from the first series.
f.columns = make([]string, 2+len(result.Series[0].Columns))
f.columns[0] = "name"
f.columns[1] = "tags"
copy(f.columns[2:], result.Series[0].Columns)
if err := wr.Write(f.columns); err != nil {
return err
}
}
for i, row := range result.Series {
if i > 0 && !stringsEqual(result.Series[i-1].Columns, row.Columns) {
// The columns have changed. Print a newline and reprint the header.
wr.Flush()
if err := wr.Error(); err != nil {
return err
}
if _, err := io.WriteString(w, "\n"); err != nil {
return err
}
f.columns = make([]string, 2+len(row.Columns))
f.columns[0] = "name"
f.columns[1] = "tags"
copy(f.columns[2:], row.Columns)
if err := wr.Write(f.columns); err != nil {
return err
}
}
f.columns[0] = row.Name
f.columns[1] = ""
if len(row.Tags) > 0 {
hashKey := models.NewTags(row.Tags).HashKey()
if len(hashKey) > 0 {
f.columns[1] = string(hashKey[1:])
}
}
for _, values := range row.Values {
for i, value := range values {
if value == nil {
f.columns[i+2] = ""
continue
}
switch v := value.(type) {
case float64:
f.columns[i+2] = strconv.FormatFloat(v, 'f', -1, 64)
case int64:
f.columns[i+2] = strconv.FormatInt(v, 10)
case uint64:
f.columns[i+2] = strconv.FormatUint(v, 10)
case string:
f.columns[i+2] = v
case bool:
if v {
f.columns[i+2] = "true"
} else {
f.columns[i+2] = "false"
}
case time.Time:
f.columns[i+2] = strconv.FormatInt(v.UnixNano(), 10)
case *float64, *int64, *string, *bool:
f.columns[i+2] = ""
}
}
wr.Write(f.columns)
}
}
}
wr.Flush()
return wr.Error()
}
type msgpFormatter struct{}
func (f *msgpFormatter) ContentType() string {
return "application/x-msgpack"
}
func (f *msgpFormatter) WriteResponse(ctx context.Context, w io.Writer, resp Response) (err error) {
span, _ := tracing.StartSpanFromContext(ctx)
defer span.Finish()
enc := msgp.NewWriter(w)
defer enc.Flush()
enc.WriteMapHeader(1)
if resp.Err != nil {
enc.WriteString("error")
enc.WriteString(resp.Err.Error())
return nil
} else {
enc.WriteString("results")
enc.WriteArrayHeader(uint32(len(resp.Results)))
for _, result := range resp.Results {
if result.Err != nil {
enc.WriteMapHeader(1)
enc.WriteString("error")
enc.WriteString(result.Err.Error())
continue
}
sz := 2
if len(result.Messages) > 0 {
sz++
}
if result.Partial {
sz++
}
enc.WriteMapHeader(uint32(sz))
enc.WriteString("statement_id")
enc.WriteInt(result.StatementID)
if len(result.Messages) > 0 {
enc.WriteString("messages")
enc.WriteArrayHeader(uint32(len(result.Messages)))
for _, msg := range result.Messages {
enc.WriteMapHeader(2)
enc.WriteString("level")
enc.WriteString(msg.Level)
enc.WriteString("text")
enc.WriteString(msg.Text)
}
}
enc.WriteString("series")
enc.WriteArrayHeader(uint32(len(result.Series)))
for _, series := range result.Series {
sz := 2
if series.Name != "" {
sz++
}
if len(series.Tags) > 0 {
sz++
}
if series.Partial {
sz++
}
enc.WriteMapHeader(uint32(sz))
if series.Name != "" {
enc.WriteString("name")
enc.WriteString(series.Name)
}
if len(series.Tags) > 0 {
enc.WriteString("tags")
enc.WriteMapHeader(uint32(len(series.Tags)))
for k, v := range series.Tags {
enc.WriteString(k)
enc.WriteString(v)
}
}
enc.WriteString("columns")
enc.WriteArrayHeader(uint32(len(series.Columns)))
for _, col := range series.Columns {
enc.WriteString(col)
}
enc.WriteString("values")
enc.WriteArrayHeader(uint32(len(series.Values)))
for _, values := range series.Values {
enc.WriteArrayHeader(uint32(len(values)))
for _, v := range values {
enc.WriteIntf(v)
}
}
if series.Partial {
enc.WriteString("partial")
enc.WriteBool(series.Partial)
}
}
if result.Partial {
enc.WriteString("partial")
enc.WriteBool(true)
}
}
}
return nil
}
func stringsEqual(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}