| 89 | } |
| 90 | |
| 91 | func (s *Server) apiQueryHandler(w http.ResponseWriter, r *http.Request) { |
| 92 | ctx := r.Context() |
| 93 | userId := getRequiredQueryParam(r, "user_id") |
| 94 | deviceId := getRequiredQueryParam(r, "device_id") |
| 95 | queryReason := getOptionalQueryParam(r, "queryReason", s.isTestEnvironment) |
| 96 | isBackgroundQuery := queryReason == "preload" || queryReason == "newclient" |
| 97 | version := getHishtoryVersion(r) |
| 98 | remoteIPAddr := getRemoteAddr(r) |
| 99 | |
| 100 | if !isBackgroundQuery { |
| 101 | s.handleNonCriticalError(s.updateUsageData(r.Context(), version, remoteIPAddr, userId, deviceId, 0, true)) |
| 102 | } |
| 103 | |
| 104 | // Delete any entries that match a pending deletion request |
| 105 | deletionRequests, err := s.db.DeletionRequestsForUserAndDevice(r.Context(), userId, deviceId) |
| 106 | checkGormError(err) |
| 107 | _, err = s.db.ApplyDeletionRequestsToBackend(r.Context(), deletionRequests) |
| 108 | checkGormError(err) |
| 109 | |
| 110 | // Then retrieve |
| 111 | historyEntries, err := s.db.HistoryEntriesForDevice(r.Context(), deviceId, 5) |
| 112 | checkGormError(err) |
| 113 | fmt.Printf("apiQueryHandler: Found %d entries for %s\n", len(historyEntries), r.URL) |
| 114 | if err := json.NewEncoder(w).Encode(historyEntries); err != nil { |
| 115 | panic(err) |
| 116 | } |
| 117 | |
| 118 | // And finally, kick off a background goroutine that will increment the read count. Doing it in the background avoids |
| 119 | // blocking the entire response. This does have a potential race condition, but that is fine. |
| 120 | if s.isProductionEnvironment { |
| 121 | go func() { |
| 122 | span, backgroundCtx := tracer.StartSpanFromContext(context.Background(), "apiQueryHandler.incrementReadCount") |
| 123 | err := s.db.IncrementEntryReadCountsForDevice(backgroundCtx, deviceId) |
| 124 | if err != nil { |
| 125 | fmt.Printf("failed to increment read counts: %v\n", err) |
| 126 | } |
| 127 | span.Finish(tracer.WithError(err)) |
| 128 | }() |
| 129 | } else { |
| 130 | err := s.db.IncrementEntryReadCountsForDevice(ctx, deviceId) |
| 131 | if err != nil { |
| 132 | panic("failed to increment read counts") |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | if s.statsd != nil { |
| 137 | s.statsd.Incr("hishtory.query", []string{"query_reason:" + queryReason}, 1.0) |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | func (s *Server) apiSubmitDumpHandler(w http.ResponseWriter, r *http.Request) { |
| 142 | userId := getRequiredQueryParam(r, "user_id") |