|
| 1 | +package api |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "io" |
| 9 | + "mime" |
| 10 | + "net/http" |
| 11 | + |
| 12 | + "github.com/sted/heligo" |
| 13 | + "github.com/sted/smoothdb/database" |
| 14 | + "github.com/sted/smoothdb/jqeval" |
| 15 | +) |
| 16 | + |
| 17 | +// maxJQBatchEvals caps the number of evaluations in a single POST /jq call |
| 18 | +const maxJQBatchEvals = 200 |
| 19 | + |
| 20 | +type jqEvalItem struct { |
| 21 | + Program string `json:"program"` |
| 22 | + Input json.RawMessage `json:"input"` |
| 23 | + Args map[string]any `json:"args"` |
| 24 | +} |
| 25 | + |
| 26 | +type jqBatchRequest struct { |
| 27 | + ParseOnly bool `json:"parse_only"` |
| 28 | + Evals []jqEvalItem `json:"evals"` |
| 29 | +} |
| 30 | + |
| 31 | +type jqOutputItem struct { |
| 32 | + Output json.RawMessage `json:"output"` |
| 33 | +} |
| 34 | + |
| 35 | +type jqErrorItem struct { |
| 36 | + Error string `json:"error"` |
| 37 | +} |
| 38 | + |
| 39 | +// InitJQRoute registers the standalone jq evaluation endpoint. |
| 40 | +// It is called only when jq evaluation is enabled, so the route 404s otherwise. |
| 41 | +func InitJQRoute(apiHelper Helper) { |
| 42 | + router := apiHelper.GetRouter() |
| 43 | + jq := router.Group("/jq", apiHelper.MiddlewareDBE()) |
| 44 | + |
| 45 | + // POST /jq: batch evaluation of jq programs, or compile-only validation |
| 46 | + // with parse_only. Errors are reported per item; 400 is reserved for a |
| 47 | + // malformed envelope. |
| 48 | + jq.Handle("POST", "", func(c context.Context, w http.ResponseWriter, r heligo.Request) (int, error) { |
| 49 | + var req jqBatchRequest |
| 50 | + err := r.ReadJSON(&req) |
| 51 | + if err != nil { |
| 52 | + return WriteBadRequest(w, err) |
| 53 | + } |
| 54 | + if len(req.Evals) > maxJQBatchEvals { |
| 55 | + return WriteBadRequest(w, fmt.Errorf("too many evals in a single call (max %d)", maxJQBatchEvals)) |
| 56 | + } |
| 57 | + results := make([]any, 0, len(req.Evals)) |
| 58 | + for _, item := range req.Evals { |
| 59 | + results = append(results, jqEvalOne(c, &item, req.ParseOnly)) |
| 60 | + } |
| 61 | + return heligo.WriteJSON(w, http.StatusOK, results) |
| 62 | + }) |
| 63 | +} |
| 64 | + |
| 65 | +// jqContentType is the media type for a raw jq program in a request body. |
| 66 | +// There is no registered media type for jq, so we use the vendor tree, |
| 67 | +// following the application/vnd.pgrst.* precedent. |
| 68 | +const jqContentType = "application/vnd.smoothdb.jq" |
| 69 | + |
| 70 | +// hasJQBody reports whether the request carries a raw jq program in its body |
| 71 | +func hasJQBody(r heligo.Request) bool { |
| 72 | + ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) |
| 73 | + return err == nil && ct == jqContentType |
| 74 | +} |
| 75 | + |
| 76 | +// jqUpdateHandler handles a jq-update PATCH /{table}?{filters}: an atomic |
| 77 | +// read-modify-write of the matched rows, driven by a jq program given either |
| 78 | +// in the jq= query parameter (with an empty body) or as the raw request body |
| 79 | +// with Content-Type: application/jq. |
| 80 | +func jqUpdateHandler(c context.Context, w http.ResponseWriter, r heligo.Request, sourcename string) (int, error) { |
| 81 | + body, err := io.ReadAll(r.Body) |
| 82 | + if err != nil { |
| 83 | + return WriteBadRequest(w, err) |
| 84 | + } |
| 85 | + options := database.GetQueryOptions(c) |
| 86 | + if hasJQBody(r) { |
| 87 | + if options.JQ != "" { |
| 88 | + return WriteBadRequest(w, fmt.Errorf("the jq program must be given either in the jq= parameter or in the request body, not both")) |
| 89 | + } |
| 90 | + options.JQ = string(body) |
| 91 | + } else if len(bytes.TrimSpace(body)) != 0 { |
| 92 | + return WriteBadRequest(w, fmt.Errorf("a request body and the jq= parameter cannot be used together")) |
| 93 | + } |
| 94 | + data, count, err := database.UpdateRecordsWithJQ(c, sourcename, r.URL.Query()) |
| 95 | + if err == nil { |
| 96 | + SetResponseHeaders(c, w, r, count) |
| 97 | + if data == nil { |
| 98 | + return heligo.WriteHeader(w, http.StatusNoContent) |
| 99 | + } else { |
| 100 | + return WriteContent(c, w, http.StatusOK, data) |
| 101 | + } |
| 102 | + } else { |
| 103 | + return WriteError(w, err) |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +func jqEvalOne(ctx context.Context, item *jqEvalItem, parseOnly bool) any { |
| 108 | + if parseOnly { |
| 109 | + if err := jqeval.Parse(item.Program, item.Args); err != nil { |
| 110 | + return jqErrorItem{err.Error()} |
| 111 | + } |
| 112 | + return struct{}{} |
| 113 | + } |
| 114 | + var input any |
| 115 | + if len(item.Input) != 0 { |
| 116 | + var err error |
| 117 | + input, err = jqeval.Unmarshal(item.Input) |
| 118 | + if err != nil { |
| 119 | + return jqErrorItem{err.Error()} |
| 120 | + } |
| 121 | + } |
| 122 | + output, err := jqeval.Eval(ctx, item.Program, input, item.Args) |
| 123 | + if err != nil { |
| 124 | + return jqErrorItem{err.Error()} |
| 125 | + } |
| 126 | + encoded, err := jqeval.Marshal(output) |
| 127 | + if err != nil { |
| 128 | + return jqErrorItem{err.Error()} |
| 129 | + } |
| 130 | + return jqOutputItem{encoded} |
| 131 | +} |
0 commit comments