MCPcopy
hub / github.com/ddworken/hishtory / apiQueryHandler

Method apiQueryHandler

backend/server/internal/server/api_handlers.go:91–139  ·  view source on GitHub ↗
(w http.ResponseWriter, r *http.Request)

Source from the content-addressed store, hash-verified

89}
90
91func (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
141func (s *Server) apiSubmitDumpHandler(w http.ResponseWriter, r *http.Request) {
142 userId := getRequiredQueryParam(r, "user_id")

Callers 3

TestESubmitThenQueryFunction · 0.95
TestDeletionRequestsFunction · 0.95

Calls 11

updateUsageDataMethod · 0.95
getRequiredQueryParamFunction · 0.85
getOptionalQueryParamFunction · 0.85
getHishtoryVersionFunction · 0.85
getRemoteAddrFunction · 0.85
checkGormErrorFunction · 0.85

Tested by 3

TestESubmitThenQueryFunction · 0.76
TestDeletionRequestsFunction · 0.76