maps: stop reading 24/7 as closed and caching failed enrichments
- Commit
f1756c8f52ec89dbba83d91576aa8c5eb6f6e655- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-23 21:55 UTC (3 months ago)
- Parents
f84f465
Diff
maps/src/main/java/com/vayunmathur/maps/data/OpeningHours.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/OpeningHours.kt b/maps/src/main/java/com/vayunmathur/maps/data/OpeningHours.ktindex 7d1746f99b..217317bdbe 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/OpeningHours.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/OpeningHours.kt@@ -19,32 +19,73 @@ class OpeningHours(val rawString: String) { private val rules: List<OpeningRule> = parse(rawString) + /**+ * Whether anything at all was understood.+ *+ * Worth asking before showing a schedule: with no rules every day reads+ * "Closed", which for an unparseable string is a confident lie. Callers should+ * fall back to whatever else they have instead.+ */+ val hasRules: Boolean get() = rules.isNotEmpty()+ companion object { fun from(input: String): OpeningHours = OpeningHours(input) + /** OSM spells an all-day interval `00:00-24:00`, which normalises to this. */+ private val ALL_DAY = TimeInterval(LocalTime(0, 0), LocalTime(0, 0))+ private fun parse(input: String): List<OpeningRule> { // Wrap each rule parse in runCatching so a single malformed segment // doesn't crash the bottom sheet. Real OSM `opening_hours` strings- // include things like "24/7", "Mo-Fr sunrise-sunset", "PH", or+ // include things like "Mo-Fr sunrise-sunset", "Jan-Mar 09:00-17:00" or // localised abbreviations we don't handle yet — silently drop those // rather than throwing NumberFormatException up the UI stack. return input.split(";").mapNotNull { part ->- runCatching {- val trimmed = part.trim()- if (trimmed.isEmpty()) return@runCatching null-- val lastSpace = trimmed.lastIndexOf(' ')- val dayPart = if (lastSpace != -1) trimmed.substring(0, lastSpace) else "Mo-Su"- val timePart = trimmed.substring(lastSpace + 1)-- OpeningRule(- days = parseDays(dayPart),- intervals = parseIntervals(timePart)- )- }.getOrNull()+ runCatching { parseRule(part) }.getOrNull() } } + private fun parseRule(part: String): OpeningRule? {+ // A trailing comment (`Mo-Fr 08:00-18:00 "by appointment"`) documents the+ // schedule rather than being part of it.+ val spec = part.substringBefore('"').trim()+ if (spec.isEmpty()) return null++ val tokens = spec.split(' ').filter { it.isNotEmpty() }+ // Split day selector from time selector at the first time-looking token.+ // Anchoring on the LAST space instead mis-sliced every rule whose time+ // list contains one — `Mo-Fr 08:00-12:00, 13:00-18:00` handed the day+ // parser `Mo-Fr 08:00-12:00,` and lost the rule entirely.+ val firstTime = tokens.indexOfFirst { isTimeToken(it) }+ val dayTokens = if (firstTime == -1) tokens else tokens.subList(0, firstTime)+ val timeTokens = if (firstTime == -1) emptyList() else tokens.subList(firstTime, tokens.size)++ // No day selector at all ("24/7", a bare "off") applies to every day.+ val days =+ if (dayTokens.isEmpty()) DayOfWeek.entries.toSet()+ else parseDays(dayTokens.joinToString(" "))+ // A selector we cannot represent — `PH`, `Jan-Mar`, `week 1-53` — has to+ // drop its rule. Public holidays in particular would otherwise need a+ // holiday calendar we do not have, and guessing is worse than omitting.+ if (days.isEmpty()) return null++ // Joined without a separator so `08:00-12:00, 13:00-18:00` rejoins into+ // the comma-separated list `parseIntervals` expects.+ // A null means the time selector was there but said nothing we could use+ // (`Mo-Fr 08:00`, a bare `Mo-Fr`). Keeping such a rule would read as+ // "closed those days", inventing a fact from a typo.+ val intervals = parseIntervals(timeTokens.joinToString("")) ?: return null+ return OpeningRule(days, intervals)+ }++ /** A time selector rather than a day one: a clock time, `24/7`, or a closure. */+ private fun isTimeToken(token: String): Boolean {+ val t = token.trimEnd(',')+ return t.firstOrNull()?.isDigit() == true ||+ t.equals("off", ignoreCase = true) ||+ t.equals("closed", ignoreCase = true)+ }+ private fun parseDays(dayStr: String): Set<DayOfWeek> { val days = mutableSetOf<DayOfWeek>() val map = mapOf(@@ -76,15 +117,28 @@ class OpeningHours(val rawString: String) { return days } - private fun parseIntervals(timeStr: String): List<TimeInterval> {- if (timeStr == "off") return emptyList()- return timeStr.split(",").mapNotNull {+ /**+ * The intervals a time selector names: empty for an explicit closure, and+ * null when nothing could be read at all — a distinction the caller needs,+ * since "closed" and "unintelligible" must not render the same way.+ */+ private fun parseIntervals(timeStr: String): List<TimeInterval>? {+ val spec = timeStr.trim().trimEnd(',')+ if (spec.isEmpty()) return null+ if (spec.equals("off", ignoreCase = true) || spec.equals("closed", ignoreCase = true)) {+ return emptyList()+ }+ // `24/7` is its own token in the grammar, not a day/time pair. Falling+ // through would leave it with no intervals, which renders as permanently+ // shut — a 24-hour pharmacy shipped as closed.+ if (spec == "24/7") return listOf(ALL_DAY)+ return spec.split(",").mapNotNull { val range = it.split("-") if (range.size != 2) return@mapNotNull null val start = parseCustomTime(range[0]) ?: return@mapNotNull null val end = parseCustomTime(range[1]) ?: return@mapNotNull null TimeInterval(start, end)- }+ }.ifEmpty { null } } // Returns null for unparseable strings instead of throwing — OSM has@@ -143,8 +197,17 @@ class OpeningHours(val rawString: String) { fun openingHours(): Map<DayOfWeek, String> { return DayOfWeek.entries.associateWith { day -> val rule = rules.findLast { it.days.contains(day) }- if (rule == null || rule.intervals.isEmpty()) "Closed"- else rule.intervals.joinToString(", ") { "${it.start.format(timeFormat)}-${it.end.format(timeFormat)}" }+ val intervals = rule?.intervals+ when {+ intervals.isNullOrEmpty() -> "Closed"+ // Only when the whole day is one open interval. Testing `any` instead+ // would relabel a multi-interval rule and throw its other intervals+ // away.+ intervals.size == 1 && intervals[0].isAllDay -> "Open 24 hours"+ else -> intervals.joinToString(", ") {+ "${it.start.format(timeFormat)}-${it.end.format(timeFormat)}"+ }+ } } } }@@ -162,11 +225,18 @@ private data class OpeningRule(val days: Set<DayOfWeek>, val intervals: List<Tim @Serializable private data class TimeInterval(val start: LocalTime, val end: LocalTime) {+ /**+ * OSM writes an all-day interval as `00:00-24:00`, and 24:00 normalises to 00:00+ * — so the range comes out zero-width. Reading that literally is what made an+ * all-day interval render as permanently Closed.+ */+ val isAllDay: Boolean get() = start == end+ fun contains(time: LocalTime): Boolean {- return if (end < start) {- time !in end..<start- } else {- time in start..<end+ return when {+ isAllDay -> true+ end < start -> time !in end..<start+ else -> time in start..<end } } }\ No newline at end of file
maps/src/main/java/com/vayunmathur/maps/data/google/GooglePoiDataSource.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/data/google/GooglePoiDataSource.kt b/maps/src/main/java/com/vayunmathur/maps/data/google/GooglePoiDataSource.ktindex 6c7b573736..639c687948 100644--- a/maps/src/main/java/com/vayunmathur/maps/data/google/GooglePoiDataSource.kt+++ b/maps/src/main/java/com/vayunmathur/maps/data/google/GooglePoiDataSource.kt@@ -66,11 +66,28 @@ object GooglePoiDataSource { // Bounded LRU cache (access-ordered). Stores the resolved info OR null (a // negative cache entry) so a place with no Google match isn't retried on // every reselect. Guarded by `synchronized(cache)`.+ //+ // Only a request that COMPLETED is ever written here — see [Outcome]. private data class Key(val name: String, val lat: Double, val lon: Double) private val cache = object : LinkedHashMap<Key, GooglePoiInfo?>(16, 0.75f, true) { override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Key, GooglePoiInfo?>) = size > 64 } + /**+ * Why a fetch came back empty.+ *+ * The two reasons must not be remembered alike. "Google has nothing for this+ * place" is a stable fact and worth caching; "the request did not complete" is a+ * property of the moment, and caching it strands the place for the rest of the+ * process — a POI tapped offline would stay bare even after connectivity+ * returned, with no way for the user to ask again.+ */+ private sealed interface Outcome {+ data class Found(val info: GooglePoiInfo) : Outcome+ data object NoMatch : Outcome+ data object Failed : Outcome+ }+ /** * Fetch enrichment for an OSM place identified by [name] at [lat],[lon]. * Returns null when there's no confident Google match or the scrape fails —@@ -80,24 +97,32 @@ object GooglePoiDataSource { if (name.isBlank()) return null val key = Key(name, lat, lon) synchronized(cache) { if (cache.containsKey(key)) return cache[key] }- val info = runCatching { fetchUncached(name, lat, lon) }.getOrNull()- synchronized(cache) { cache[key] = info }- return info+ val outcome = runCatching { fetchUncached(name, lat, lon) }.getOrElse { Outcome.Failed }+ return when (outcome) {+ is Outcome.Found -> outcome.info.also { synchronized(cache) { cache[key] = it } }+ Outcome.NoMatch -> null.also { synchronized(cache) { cache[key] = null } }+ // Deliberately not cached, so the next tap retries.+ Outcome.Failed -> null+ } } - private suspend fun fetchUncached(name: String, lat: Double, lon: Double): GooglePoiInfo? =+ private suspend fun fetchUncached(name: String, lat: Double, lon: Double): Outcome = withContext(Dispatchers.IO) { warmSession() val pb = buildSearchPb(name, lat, lon) val url = "$SEARCH_ENDPOINT&q=${name.enc()}&pb=${pb.enc()}"- val body = get(url) ?: return@withContext null- val root = GoogleResponse.parseOrNull(body) ?: return@withContext null- val entry = pickEntry(root, lat, lon) ?: return@withContext null+ // A transport error or a non-2xx never became an answer.+ val body = get(url) ?: return@withContext Outcome.Failed+ // Nor did a body we cannot parse: a 200 that does not decode is far more+ // likely an interstitial (consent, captcha, rate limit) than a genuine+ // "no such place".+ val root = GoogleResponse.parseOrNull(body) ?: return@withContext Outcome.Failed+ val entry = pickEntry(root, lat, lon) ?: return@withContext Outcome.NoMatch // Reviews are no longer fetched here: the dead `listentitiesreviews` RPC 404s, and the // WebView scrape ([WebReviewsFetcher]) is async/slow, so it must NOT block base // enrichment. The base info carries reviews = emptyList(); the caller fills them in // progressively once it has [GooglePoiInfo.featureId].- parsePlace(entry)+ parsePlace(entry)?.let { Outcome.Found(it) } ?: Outcome.NoMatch } // --- HTTP plumbing ------------------------------------------------------
maps/src/test/java/com/vayunmathur/maps/data/OpeningHoursTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/data/OpeningHoursTest.kt b/maps/src/test/java/com/vayunmathur/maps/data/OpeningHoursTest.ktnew file mode 100644index 0000000000..66199d9539--- /dev/null+++ b/maps/src/test/java/com/vayunmathur/maps/data/OpeningHoursTest.kt@@ -0,0 +1,158 @@+package com.vayunmathur.maps.data++import kotlinx.datetime.DayOfWeek+import kotlinx.datetime.LocalDateTime+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * The OSM `opening_hours` parser.+ *+ * Every failure mode here reads as a confident lie rather than as an error: an+ * unparsed rule leaves no rules, and no rules renders as "Closed" on every day of+ * the week. So the cases that matter are the ones where the string is perfectly+ * valid OSM and we used to drop it — `24/7` above all.+ *+ * Assertions go through [OpeningHours.isOpen] rather than the formatted week from+ * [OpeningHours.openingHours], because formatting a clock time reaches into+ * `android.icu`, which is not available to a JVM unit test. Only the two literal+ * strings ("Closed", "Open 24 hours") are safe to assert on.+ */+class OpeningHoursTest {++ /** A Wednesday, so `Mo-Fr` matches and `Sa`/`Su` do not. */+ private fun wed(hour: Int, minute: Int = 0) =+ LocalDateTime(2026, 8, 19, hour, minute)++ private fun sat(hour: Int, minute: Int = 0) =+ LocalDateTime(2026, 8, 22, hour, minute)++ private fun sun(hour: Int, minute: Int = 0) =+ LocalDateTime(2026, 8, 23, hour, minute)++ @Test+ fun `24-7 is open at every hour, not permanently closed`() {+ val hours = OpeningHours.from("24/7")+ assertTrue(hours.hasRules)+ for (h in listOf(0, 3, 12, 23)) {+ assertTrue(hours.isOpen(wed(h)), "open at $h:00")+ assertTrue(hours.isOpen(sat(h)), "open on Saturday at $h:00")+ }+ assertEquals(+ DayOfWeek.entries.associateWith { "Open 24 hours" },+ hours.openingHours(),+ )+ }++ /** The same schedule written the long way round, which normalises identically. */+ @Test+ fun `an explicit all-day interval is open all day`() {+ val hours = OpeningHours.from("Mo-Su 00:00-24:00")+ assertTrue(hours.isOpen(wed(0)))+ assertTrue(hours.isOpen(wed(23, 59)))+ }++ @Test+ fun `a weekday and weekend rule each apply to their own days`() {+ val hours = OpeningHours.from("Mo-Fr 08:00-18:00; Sa 09:00-13:00")++ assertTrue(hours.isOpen(wed(8)))+ assertTrue(hours.isOpen(wed(17, 59)))+ assertFalse(hours.isOpen(wed(7, 59)))+ assertFalse(hours.isOpen(wed(18)))++ assertTrue(hours.isOpen(sat(9)))+ assertFalse(hours.isOpen(sat(13)))++ // Sunday is named by neither rule.+ assertFalse(hours.isOpen(sun(12)))+ }++ /** An interval that wraps midnight has to stay open on both sides of it. */+ @Test+ fun `an overnight interval spans midnight`() {+ val hours = OpeningHours.from("Mo-Su 22:00-02:00")+ assertTrue(hours.isOpen(wed(23)))+ assertTrue(hours.isOpen(wed(1)))+ assertFalse(hours.isOpen(wed(12)))+ }++ /**+ * Public holidays need a calendar we do not have, so the rule must be dropped+ * rather than applied to all seven days — which is what a missing day selector+ * means everywhere else in the grammar.+ */+ @Test+ fun `a public-holiday rule is dropped rather than applied to every day`() {+ val hours = OpeningHours.from("Mo-Fr 08:00-18:00; PH off")+ assertTrue(hours.isOpen(wed(9)), "the weekday rule survives")++ assertFalse(OpeningHours.from("PH off").hasRules, "nothing understood")+ }++ /**+ * The time list contains a space, which the old last-space split fed to the day+ * parser — losing the whole rule and rendering the place as always closed.+ */+ @Test+ fun `a spaced time list keeps both of its intervals`() {+ val hours = OpeningHours.from("Mo-Fr 08:00-12:00, 13:00-18:00")+ assertTrue(hours.isOpen(wed(9)))+ assertFalse(hours.isOpen(wed(12, 30)), "closed over lunch")+ assertTrue(hours.isOpen(wed(14)))+ }++ @Test+ fun `a trailing comment is ignored rather than eaten as a time`() {+ val hours = OpeningHours.from("""Mo-Fr 08:00-18:00 "by appointment"""")+ assertTrue(hours.isOpen(wed(9)))+ assertFalse(hours.isOpen(wed(19)))+ }++ @Test+ fun `off closes the day it names without touching the others`() {+ val hours = OpeningHours.from("Mo-Su 09:00-17:00; Su off")+ assertTrue(hours.isOpen(wed(10)))+ assertFalse(hours.isOpen(sun(10)), "Sunday is off")+ }++ /** Unrepresentable rules must be dropped quietly, never thrown out of the sheet. */+ @Test+ fun `malformed and unsupported rules are dropped without throwing`() {+ for (raw in listOf(+ "Mo-Fr sunrise-sunset",+ "Jan-Mar 09:00-17:00",+ "garbage",+ "Mo-Fr 08:00",+ ";;;",+ "",+ )) {+ val hours = OpeningHours.from(raw)+ assertFalse(hours.isOpen(wed(12)), "'$raw' must not claim to be open")+ assertFalse(hours.hasRules, "'$raw' understood nothing, and says so")+ }+ }++ /** A dropped rule must not take a valid neighbour down with it. */+ @Test+ fun `a valid rule survives a malformed one beside it`() {+ val hours = OpeningHours.from("Mo-Fr sunrise-sunset; Sa 09:00-13:00")+ assertTrue(hours.hasRules)+ assertTrue(hours.isOpen(sat(10)))+ }++ @Test+ fun `the next status change is the end of the current interval`() {+ val hours = OpeningHours.from("Mo-Fr 08:00-18:00")+ assertEquals(wed(18), hours.nextStatusChangeTime(wed(9)))+ }++ /** Nothing ever changes under 24/7, and the sentinel for that is `current`. */+ @Test+ fun `a 24-7 schedule reports no next status change`() {+ val hours = OpeningHours.from("24/7")+ assertEquals(wed(9), hours.nextStatusChangeTime(wed(9)))+ }+}