mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-29 16:10:07 +00:00
feat(maps): bill a place search as one session instead of per keystroke
Google charges autocomplete per request unless the requests carry a session token. With one, the keystrokes of a single search and the details lookup that ends it are charged together, which is also how a user experiences it: they looked up one place. TREK sent no token at all, so every debounced keystroke was its own billable request. On a busy trip that is the largest line on the Places bill, and it is paid by whoever owns the key, which for a self-hosted instance is the person running it. A session opens with the first suggestion request and closes when the user picks a result. It has to close on the abandoned paths too: a token carried into the next search would merge two searches into one billed session and scope the suggestions wrongly. So the search box clearing it, the text-search fallback and the error paths all end it. The token is validated on the way in. The autocomplete body goes through the Zod pipe, the details query does not, so the controller shape-checks it there. Anything that does not match Google's URL-safe 36-character form is dropped rather than forwarded, which falls back to per-request billing instead of breaking a lookup. A cached details hit never reaches Google and so never closes its session. That is billing-neutral: an unclosed session is charged as a plain autocomplete session, which is still cheaper than the per-request behaviour it replaces.
This commit is contained in:
@@ -930,9 +930,9 @@ export const journeyApi = {
|
||||
|
||||
export const mapsApi = {
|
||||
search: (query: string, lang?: string) => apiClient.post(`/maps/search?lang=${lang || 'en'}`, { query }).then(r => checkInDev(mapsSearchResultSchema, r.data, 'maps.search')),
|
||||
autocomplete: (input: string, lang?: string, locationBias?: { low: { lat: number; lng: number }; high: { lat: number; lng: number } }, signal?: AbortSignal) =>
|
||||
apiClient.post('/maps/autocomplete', { input, lang, locationBias }, { signal }).then(r => checkInDev(mapsAutocompleteResultSchema, r.data, 'maps.autocomplete')),
|
||||
details: (placeId: string, lang?: string) => apiClient.get(`/maps/details/${encodeURIComponent(placeId)}`, { params: { lang } }).then(r => checkInDev(mapsPlaceDetailsResultSchema, r.data, 'maps.details')),
|
||||
autocomplete: (input: string, lang?: string, locationBias?: { low: { lat: number; lng: number }; high: { lat: number; lng: number } }, signal?: AbortSignal, sessionToken?: string) =>
|
||||
apiClient.post('/maps/autocomplete', { input, lang, locationBias, sessionToken }, { signal }).then(r => checkInDev(mapsAutocompleteResultSchema, r.data, 'maps.autocomplete')),
|
||||
details: (placeId: string, lang?: string, sessionToken?: string) => apiClient.get(`/maps/details/${encodeURIComponent(placeId)}`, { params: { lang, sessionToken } }).then(r => checkInDev(mapsPlaceDetailsResultSchema, r.data, 'maps.details')),
|
||||
// Pictures and a description for a place that is being looked at but not yet
|
||||
// saved. Fans out to several providers server-side, so it takes a signal and
|
||||
// the caller is expected to abort it when the selection changes, and a longer
|
||||
|
||||
@@ -20,6 +20,7 @@ import { BookingCostsSection } from './BookingCostsSection'
|
||||
import type { BookingExpenseRequest } from './BookingCostsSection.types'
|
||||
import type { Place, Category, Assignment, BudgetItem } from '../../types'
|
||||
import { NumericInput } from '../shared/NumericInput'
|
||||
import { PlacesSession } from '../../utils/placesSession'
|
||||
|
||||
// The submit payload mirrors the form, but lat/lng are parsed to numbers and
|
||||
// category_id is normalised, plus any files chosen before the place existed.
|
||||
@@ -106,6 +107,9 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
|
||||
const [acHighlight, setAcHighlight] = useState(-1)
|
||||
const acDebounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const acAbortRef = useRef<AbortController | null>(null)
|
||||
// Ties one search's keystrokes and its details lookup into a single Google
|
||||
// billing session (see utils/placesSession).
|
||||
const placesSessionRef = useRef(new PlacesSession())
|
||||
const toast = useToast()
|
||||
const { t, language, locale } = useTranslation()
|
||||
const { hasMapsKey, placesEnrichEnabled } = useAuthStore()
|
||||
@@ -244,7 +248,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
|
||||
const controller = new AbortController()
|
||||
acAbortRef.current = controller
|
||||
try {
|
||||
const result = await mapsApi.autocomplete(query, language, locationBias, controller.signal)
|
||||
const result = await mapsApi.autocomplete(query, language, locationBias, controller.signal, placesSessionRef.current.current())
|
||||
setAcSuggestions(result.suggestions || [])
|
||||
setAcHighlight(-1)
|
||||
} catch (err: unknown) {
|
||||
@@ -263,6 +267,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
|
||||
if (trimmed.length < 2 || isGoogleMapsUrl(trimmed)) {
|
||||
setAcSuggestions([])
|
||||
setAcHighlight(-1)
|
||||
placesSessionRef.current.end()
|
||||
return
|
||||
}
|
||||
|
||||
@@ -349,7 +354,9 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
|
||||
// clickable instead of dead-ending on "Place search failed". (#1192)
|
||||
let place: Record<string, unknown> | null = null
|
||||
try {
|
||||
const result = await mapsApi.details(suggestion.placeId, language)
|
||||
// Spends the session the suggestions opened, so Google bills the search
|
||||
// once rather than per keystroke.
|
||||
const result = await mapsApi.details(suggestion.placeId, language, placesSessionRef.current.peek())
|
||||
if (result.place && result.place.lat != null && result.place.lng != null) {
|
||||
place = result.place
|
||||
}
|
||||
@@ -373,6 +380,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
|
||||
toast.error(getApiErrorMessage(err, t('places.mapsSearchError')))
|
||||
} finally {
|
||||
setIsSearchingMaps(false)
|
||||
placesSessionRef.current.end()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { Loader2, Search } from 'lucide-react'
|
||||
import { mapsApi } from '../../../../api/client'
|
||||
import { PlacesSession } from '../../../../utils/placesSession'
|
||||
import { isGoogleMapsUrl } from '../../../../components/Planner/PlaceFormModal.helpers'
|
||||
import { getApiErrorMessage } from '../../../../utils/apiError'
|
||||
import { FIELD_CLS } from './PlSheetChrome'
|
||||
@@ -67,6 +68,8 @@ export default function PlPlaceSearch({ planner, locationBias, onPick, onResolvi
|
||||
const [searching, setSearching] = useState(false)
|
||||
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const abortRef = useRef<AbortController | null>(null)
|
||||
// One Google billing session per search (see utils/placesSession).
|
||||
const placesSessionRef = useRef(new PlacesSession())
|
||||
|
||||
const setResolving = useCallback(
|
||||
(v: boolean) => {
|
||||
@@ -82,7 +85,7 @@ export default function PlPlaceSearch({ planner, locationBias, onPick, onResolvi
|
||||
const controller = new AbortController()
|
||||
abortRef.current = controller
|
||||
try {
|
||||
const result = await mapsApi.autocomplete(input, language, locationBias, controller.signal)
|
||||
const result = await mapsApi.autocomplete(input, language, locationBias, controller.signal, placesSessionRef.current.current())
|
||||
setSuggestions(result.suggestions || [])
|
||||
} catch (err: unknown) {
|
||||
// Superseded request — axios rejects an aborted call with CanceledError.
|
||||
@@ -150,6 +153,7 @@ export default function PlPlaceSearch({ planner, locationBias, onPick, onResolvi
|
||||
toast.error(getApiErrorMessage(err, t('places.mapsSearchError')))
|
||||
} finally {
|
||||
setResolving(false)
|
||||
placesSessionRef.current.end()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,7 +168,8 @@ export default function PlPlaceSearch({ planner, locationBias, onPick, onResolvi
|
||||
// back to the text-search path so suggestions never dead-end. (#1192)
|
||||
let place: MapsPlace | null = null
|
||||
try {
|
||||
const result = await mapsApi.details(suggestion.placeId, language)
|
||||
// Spends the session the suggestions opened.
|
||||
const result = await mapsApi.details(suggestion.placeId, language, placesSessionRef.current.peek())
|
||||
if (result.place && result.place.lat != null && result.place.lng != null) place = result.place
|
||||
} catch {
|
||||
// fall through to text search
|
||||
@@ -185,6 +190,7 @@ export default function PlPlaceSearch({ planner, locationBias, onPick, onResolvi
|
||||
toast.error(getApiErrorMessage(err, t('places.mapsSearchError')))
|
||||
} finally {
|
||||
setResolving(false)
|
||||
placesSessionRef.current.end()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Google bills place autocomplete per keystroke unless the requests carry a
|
||||
* session token. With one, the keystrokes and the details lookup that ends the
|
||||
* search are charged as a single session, which is what a user experiences as
|
||||
* "I looked up one place".
|
||||
*
|
||||
* A session starts with the first suggestion request and ends when the user
|
||||
* picks a result (or gives up). Reusing a token across two searches would merge
|
||||
* them into one billed session and return stale-scoped suggestions, so `end()`
|
||||
* has to run on both paths.
|
||||
*
|
||||
* The token has to be URL-safe ASCII and at most 36 characters; a UUID is
|
||||
* exactly 36 and is what Google's own clients use. `crypto.randomUUID` is
|
||||
* missing on http:// origins in some browsers, hence the fallback.
|
||||
*/
|
||||
export function newSessionToken(): string {
|
||||
const c = globalThis.crypto;
|
||||
if (c && typeof c.randomUUID === 'function') return c.randomUUID();
|
||||
if (c && typeof c.getRandomValues === 'function') {
|
||||
const bytes = new Uint8Array(16);
|
||||
c.getRandomValues(bytes);
|
||||
return Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
return `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 12)}`;
|
||||
}
|
||||
|
||||
/** One search's worth of token, created lazily and cleared when it is spent. */
|
||||
export class PlacesSession {
|
||||
private token: string | null = null;
|
||||
|
||||
/** The token for the running search, starting one if none is open. */
|
||||
current(): string {
|
||||
if (!this.token) this.token = newSessionToken();
|
||||
return this.token;
|
||||
}
|
||||
|
||||
/** The token without starting a session: a details lookup that no search led
|
||||
* to must not open one, or it would be billed as an empty session. */
|
||||
peek(): string | undefined {
|
||||
return this.token ?? undefined;
|
||||
}
|
||||
|
||||
/** Call when the search is over, whether it ended in a pick or not. */
|
||||
end(): void {
|
||||
this.token = null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user