From 8a1393fe985305aeccabce38aed8ded66c15aef6 Mon Sep 17 00:00:00 2001 From: Nayor <11463011+Nayor@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:37:24 +0100 Subject: [PATCH 01/10] feat(itinevert): time on site, classes of days and transport hubs The core of the search of the routes reachable by public transport from a transport hub of a town, without database nor Navitia calls: - reachability: the answers of Navitia journeys without destination / origin reduced to the stop times, joined with the stop areas of the access waypoints, give the time on site of each waypoint and route (traverses included); - day_classes: the class of days of a date (kind of day x school holiday period of the zone of the origin, or season), cut at the yearly timetable change; the school holidays come from the open data of the ministry of education (scripts/itinevert/update_school_holidays.py); - hubs: the stop areas of a town where the most lines stop, grouped within 200 m, more than 10 lines, at most 6, at least the best one. --- MANIFEST.in | 1 + c2corg_api/itinevert/__init__.py | 16 ++ c2corg_api/itinevert/day_classes.py | 175 ++++++++++++ c2corg_api/itinevert/hubs.py | 144 ++++++++++ c2corg_api/itinevert/reachability.py | 258 ++++++++++++++++++ c2corg_api/itinevert/school_holidays.json | 61 +++++ c2corg_api/tests/itinevert/__init__.py | 0 .../tests/itinevert/test_day_classes.py | 106 +++++++ c2corg_api/tests/itinevert/test_hubs.py | 81 ++++++ .../tests/itinevert/test_reachability.py | 148 ++++++++++ scripts/itinevert/update_school_holidays.py | 87 ++++++ 11 files changed, 1077 insertions(+) create mode 100644 c2corg_api/itinevert/__init__.py create mode 100644 c2corg_api/itinevert/day_classes.py create mode 100644 c2corg_api/itinevert/hubs.py create mode 100644 c2corg_api/itinevert/reachability.py create mode 100644 c2corg_api/itinevert/school_holidays.json create mode 100644 c2corg_api/tests/itinevert/__init__.py create mode 100644 c2corg_api/tests/itinevert/test_day_classes.py create mode 100644 c2corg_api/tests/itinevert/test_hubs.py create mode 100644 c2corg_api/tests/itinevert/test_reachability.py create mode 100644 scripts/itinevert/update_school_holidays.py diff --git a/MANIFEST.in b/MANIFEST.in index 88a8f3add..18064b62a 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -3,3 +3,4 @@ recursive-include c2corg_api *.ico *.png *.css *.gif *.jpg *.pt *.txt *.mak *.ma graft c2corg_api/emails/ recursive-include c2corg_api/search/es_mappings *.json recursive-include c2corg_api/partners/regions *.json +include c2corg_api/itinevert/school_holidays.json diff --git a/c2corg_api/itinevert/__init__.py b/c2corg_api/itinevert/__init__.py new file mode 100644 index 000000000..74ac07d09 --- /dev/null +++ b/c2corg_api/itinevert/__init__.py @@ -0,0 +1,16 @@ +"""The search of the routes reachable by public transport (Itinevert). + +A search starts from a transport hub of a town (a Navitia stop area), on a +class of days (the timetables repeat: kind of day x period). Two Navitia +`journeys` requests without destination / without origin give, for the whole +day, the earliest arrival at and the latest departure from every stop point +reachable; joined with the stop areas linked to the access waypoints, they +give the time on site of each waypoint and route. + +The modules are plain functions, without database or Navitia calls, except +the ones of `search` which bind them together: +- `reachability`: the answers of Navitia reduced to the stop times, and the + time on site of the waypoints and routes; +- `day_classes`: the class of days of a date; +- `hubs`: the transport hubs of a town. +""" diff --git a/c2corg_api/itinevert/day_classes.py b/c2corg_api/itinevert/day_classes.py new file mode 100644 index 000000000..ba97ee1b2 --- /dev/null +++ b/c2corg_api/itinevert/day_classes.py @@ -0,0 +1,175 @@ +"""The class of days of a date: the dates of a class share their timetables. + +A class is a kind of day (weekday, Saturday, Sunday or bank holiday) in a +period: a school holiday period of the zone of the origin, or a season out of +the holidays. The classes are also cut at the yearly change of the timetables +(the second Sunday of December), so that a search computed before the change +is not used after it. + +The school holidays are in school_holidays.json (see +scripts/itinevert/update_school_holidays.py). +""" + +import json +import pathlib +from dataclasses import dataclass +from datetime import date, timedelta +from functools import cache + +WEEKDAY = 'weekday' +SATURDAY = 'saturday' +SUNDAY = 'sunday' # and bank holidays + +SEASONS = { + 12: 'winter', + 1: 'winter', + 2: 'winter', + 3: 'spring', + 4: 'spring', + 5: 'spring', + 6: 'summer', + 7: 'summer', + 8: 'summer', + 9: 'autumn', + 10: 'autumn', + 11: 'autumn', +} + +# the school holiday zone of each department (the academies of 2026) +_ZONE_DEPARTMENTS = { + # Besançon, Bordeaux, Clermont-Ferrand, Dijon, Grenoble, Limoges, Lyon, + # Poitiers + 'A': '25 39 70 90 24 33 40 47 64 03 15 43 63 21 58 71 89 07 26 38 73 74 ' + '19 23 87 01 42 69 16 17 79 86', + # Aix-Marseille, Amiens, Lille, Nancy-Metz, Nantes, Nice, Normandie, + # Orléans-Tours, Reims, Rennes, Strasbourg + 'B': '04 05 13 84 02 60 80 59 62 54 55 57 88 44 49 53 72 85 06 83 14 27 ' + '50 61 76 18 28 36 37 41 45 08 10 51 52 22 29 35 56 67 68', + # Créteil, Montpellier, Paris, Toulouse, Versailles + 'C': '77 93 94 11 30 34 48 66 75 09 12 31 32 46 65 81 82 78 91 92 95', + 'corsica': '2A 2B', +} +ZONES = { + department: zone + for zone, departments in _ZONE_DEPARTMENTS.items() + for department in departments.split() +} +# Alsace-Moselle has two more bank holidays +_ALSACE_MOSELLE = {'57', '67', '68'} + + +def department(insee: str | None) -> str | None: + """Return the department of the INSEE code of a town.""" + if not insee or len(insee) != 5: + return None + return insee[:3] if insee.startswith('97') else insee[:2] + + +def zone(insee: str | None) -> str | None: + """Return the school holiday zone of a town, None out of France.""" + return ZONES.get(department(insee)) + + +def easter(year: int) -> date: + """Return the Easter Sunday of a year (anonymous Gregorian algorithm).""" + a, b, c = year % 19, year // 100, year % 100 + d, e = b // 4, b % 4 + f = (b + 8) // 25 + g = (b - f + 1) // 3 + h = (19 * a + b - d - g + 15) % 30 + i, k = c // 4, c % 4 + m = (32 + 2 * e + 2 * i - h - k) % 7 + n = (a + 11 * h + 22 * m) // 451 + month, day = divmod(h + m - 7 * n + 114, 31) + return date(year, month, day + 1) + + +@cache +def bank_holidays(year: int, alsace_moselle: bool = False) -> frozenset[date]: + sunday = easter(year) + days = { + date(year, 1, 1), + sunday + timedelta(days=1), + date(year, 5, 1), + date(year, 5, 8), + sunday + timedelta(days=39), + sunday + timedelta(days=50), + date(year, 7, 14), + date(year, 8, 15), + date(year, 11, 1), + date(year, 11, 11), + date(year, 12, 25), + } + if alsace_moselle: + days |= {sunday - timedelta(days=2), date(year, 12, 26)} + return frozenset(days) + + +def timetable_change(year: int) -> date: + """Return the yearly change of the timetables: the 2nd Sunday of December.""" + first = date(year, 12, 1) + return first + timedelta(days=(6 - first.weekday()) % 7 + 7) + + +def timetable_year(day: date) -> int: + """Return the year of the timetables of a day. + + The timetables starting in December of a year are the ones of the next + year. + """ + return day.year + 1 if day >= timetable_change(day.year) else day.year + + +@cache +def _school_holidays() -> dict[str, list[tuple[str, date, date]]]: + path = pathlib.Path(__file__).with_name('school_holidays.json') + raw = json.loads(path.read_text(encoding='utf-8')) + return { + z: [ + (name, date.fromisoformat(s), date.fromisoformat(e)) + for name, s, e in periods + ] + for z, periods in raw.items() + } + + +def holiday_period(day: date, holiday_zone: str | None): + """Return the school holiday period of a day: (name, first day), or None.""" + for name, start, end in _school_holidays().get(holiday_zone, ()): + if start <= day < end: + return name, start + return None + + +def kind_of_day(day: date, insee: str | None = None) -> str: + alsace_moselle = department(insee) in _ALSACE_MOSELLE + if day.weekday() == 6 or day in bank_holidays(day.year, alsace_moselle): + return SUNDAY + return SATURDAY if day.weekday() == 5 else WEEKDAY + + +@dataclass(frozen=True) +class DayClass: + """The class of days of a date: its key names the cache of a search.""" + + timetable_year: int + period: str + kind: str + + @property + def key(self) -> str: + return f'{self.timetable_year}:{self.period}:{self.kind}' + + +def day_class(day: date, insee: str | None = None) -> DayClass: + """Return the class of days of a date, for an origin in the town `insee`. + + A holiday period is named by its first day: the same period of another + year is another class. Out of the holidays, the season. + """ + holidays = holiday_period(day, zone(insee)) + if holidays: + period = f'{holidays[0]}-{holidays[1].isoformat()}' + else: + period = SEASONS[day.month] + return DayClass(timetable_year(day), period, kind_of_day(day, insee)) diff --git a/c2corg_api/itinevert/hubs.py b/c2corg_api/itinevert/hubs.py new file mode 100644 index 000000000..e9c40737c --- /dev/null +++ b/c2corg_api/itinevert/hubs.py @@ -0,0 +1,144 @@ +"""The transport hubs of a town: where a search starts from. + +A town does not start from its centre on foot (what Navitia does for an +administrative region without main stop areas), but from the stop areas where +the most lines stop, of all modes. They are found in the answer of Navitia's +`coords/{lon;lat}/stop_areas?depth=3` (the stop areas around the centre of +the town with their lines), first with the stop areas served by more than +buses (HUB_MODES), then, for a small town without any, with all of them. + +The stop areas of a hub (the train station, the bus station beside it...) are +grouped when closer than GROUP_RADIUS. The hubs of at least MIN_LINES lines +are proposed, at most MAX_HUBS, always at least the best one. +""" + +from dataclasses import dataclass, field + +from c2corg_api.itinevert.reachability import distance + +# more than 10 lines +MIN_LINES = 11 +MAX_HUBS = 6 +GROUP_RADIUS = 200 # meters +# the radius around the centre of the town +SEARCH_RADIUS = 4000 # meters +# the physical modes of the hubs: the stop areas served by buses only are +# fetched for a town without any of these +HUB_MODES = ( + 'Train', + 'LocalTrain', + 'LongDistanceTrain', + 'RapidTransit', + 'Metro', + 'Tramway', + 'Coach', + 'Funicular', +) + + +def hub_modes_filter() -> str: + """Return the Navitia filter of the stop areas served by a HUB_MODES mode.""" + return ' or '.join(f'physical_mode.id=physical_mode:{mode}' for mode in HUB_MODES) + + +@dataclass +class Hub: + # the stop area of the hub with the most lines: the origin of a search + stop_area_id: str + name: str + lon: float + lat: float + lines: int + # the number of lines per physical mode + modes: dict[str, int] = field(default_factory=dict) + stop_area_ids: list[str] = field(default_factory=list) + # from the centre of the town + distance: float = 0 + + def to_dict(self): + return { + 'id': self.stop_area_id, + 'name': self.name, + 'lon': self.lon, + 'lat': self.lat, + 'lines': self.lines, + 'modes': self.modes, + } + + +def _in_town(stop_area, insee): + return any( + admin.get('insee') == insee + for admin in stop_area.get('administrative_regions', []) + ) + + +def _coord(stop_area): + return float(stop_area['coord']['lon']), float(stop_area['coord']['lat']) + + +def rank_hubs( + stop_areas: list[dict], insee: str, centre: tuple[float, float] +) -> list[Hub]: + """Return the hubs of a town from the stop areas of a Navitia answer. + + The most lines first, the closest to the centre first on a tie. + """ + in_town = [s for s in stop_areas if _in_town(s, insee) and 'coord' in s] + + # the groups of stop areas closer than GROUP_RADIUS to one another + parent = list(range(len(in_town))) + + def root(i): + while parent[i] != i: + parent[i] = parent[parent[i]] + i = parent[i] + return i + + coords = [_coord(s) for s in in_town] + for i in range(len(in_town)): + for j in range(i): + if distance(*coords[i], *coords[j]) < GROUP_RADIUS: + parent[root(i)] = root(j) + groups: dict[int, list[int]] = {} + for i in range(len(in_town)): + groups.setdefault(root(i), []).append(i) + + hubs = [] + for members in groups.values(): + lines = {} + for i in members: + for line in in_town[i].get('lines', []): + lines[line['id']] = line + modes: dict[str, int] = {} + for line in lines.values(): + for mode in line.get('physical_modes', []): + modes[mode['name']] = modes.get(mode['name'], 0) + 1 + best = max(members, key=lambda i: len(in_town[i].get('lines', []))) + lon, lat = coords[best] + hubs.append( + Hub( + stop_area_id=in_town[best]['id'], + name=in_town[best]['name'], + lon=lon, + lat=lat, + lines=len(lines), + modes=modes, + stop_area_ids=[in_town[i]['id'] for i in members], + distance=distance(lon, lat, *centre), + ) + ) + hubs.sort(key=lambda h: (-h.lines, h.distance)) + return hubs + + +def select_hubs( + hubs: list[Hub], min_lines: int = MIN_LINES, max_hubs: int = MAX_HUBS +) -> list[Hub]: + """Return the hubs proposed. + + At least min_lines lines, at most max_hubs, at least the best one when + there is one. + """ + selected = [h for h in hubs if h.lines >= min_lines][:max_hubs] + return selected or hubs[:1] diff --git a/c2corg_api/itinevert/reachability.py b/c2corg_api/itinevert/reachability.py new file mode 100644 index 000000000..237c6ebf5 --- /dev/null +++ b/c2corg_api/itinevert/reachability.py @@ -0,0 +1,258 @@ +"""The time on site of the waypoints and routes, from the stop times. + +The answers of Navitia `journeys` without destination (outbound: the earliest +arrival at each stop point) or without origin (return, with +`datetime_represents=arrival`: the latest departure from each stop point) +weigh tens of MB. They are reduced to what the search needs: per stop point +its position and a time, in minutes from the midnight of the day of the search +(over 1440 after midnight). + +The stop areas linked to the access waypoints (`waypoints_stopareas`) are +Navitia stop areas, while the answers give stop points: a stop area is joined +to the stop points around its position (`STOP_POINT_RADIUS`). +""" + +import math +from dataclasses import dataclass +from datetime import date, datetime + +# the stop points of a stop area are around its position +STOP_POINT_RADIUS = 200 # meters +# the walking speed of the distances of waypoints_stopareas (Navitia's +# default, the one of scripts/public_transport) +WALKING_SPEED = 1.12 # m/s +OUTBOUND = 'outbound' +RETURN = 'return' + +# the size of the cells of the spatial index of the stop points: about 1 km +_CELL = 0.01 # degrees + + +@dataclass(frozen=True) +class StopTime: + """A stop point reached and its time, in minutes from midnight.""" + + stop_point_id: str + lon: float + lat: float + minutes: int + + +def minutes_from(day: date, navitia_datetime: str) -> int: + """Return the minutes from the midnight of `day` of a Navitia datetime.""" + # a local time of the coverage, as the day + moment = datetime.strptime(navitia_datetime, '%Y%m%dT%H%M%S') # noqa: DTZ007 + return (moment.date() - day).days * 1440 + moment.hour * 60 + moment.minute + + +def stop_times(answer: dict, direction: str, day: date) -> list[StopTime]: + """Return the stop times of a Navitia `journeys` answer. + + Without destination (outbound) or without origin (return). + + A stop point appears once: the earliest arrival, the latest departure. + """ + outbound = direction == OUTBOUND + best: dict[str, StopTime] = {} + for journey in answer.get('journeys', []): + place = journey['to'] if outbound else journey['from'] + stop_point = place.get('stop_point') + if not stop_point or 'coord' not in stop_point: + continue + moment = journey['arrival_date_time' if outbound else 'departure_date_time'] + stop_time = StopTime( + stop_point['id'], + float(stop_point['coord']['lon']), + float(stop_point['coord']['lat']), + minutes_from(day, moment), + ) + known = best.get(stop_time.stop_point_id) + if ( + known is None + or (outbound and stop_time.minutes < known.minutes) + or (not outbound and stop_time.minutes > known.minutes) + ): + best[stop_time.stop_point_id] = stop_time + return list(best.values()) + + +def compact(times: list[StopTime]) -> list[list]: + """Return the stop times as a list of lists, to be stored (about 1 MB).""" + return [ + [t.stop_point_id, round(t.lon, 6), round(t.lat, 6), t.minutes] for t in times + ] + + +def uncompact(rows: list[list]) -> list[StopTime]: + return [StopTime(row[0], row[1], row[2], row[3]) for row in rows] + + +def distance(lon1: float, lat1: float, lon2: float, lat2: float) -> float: + """Return the distance in meters between two points (equirectangular).""" + x = math.radians(lon2 - lon1) * math.cos(math.radians((lat1 + lat2) / 2)) + y = math.radians(lat2 - lat1) + return 6371000 * math.hypot(x, y) + + +class StopTimeIndex: + """The stop times of a direction, found by position.""" + + def __init__(self, times: list[StopTime], direction: str): + self.outbound = direction == OUTBOUND + self._cells: dict[tuple[int, int], list[StopTime]] = {} + for t in times: + self._cells.setdefault(self._cell(t.lon, t.lat), []).append(t) + + @staticmethod + def _cell(lon, lat): + return int(math.floor(lon / _CELL)), int(math.floor(lat / _CELL)) + + def best_around(self, lon: float, lat: float, radius: float = STOP_POINT_RADIUS): + """Return the best time at the stop points around a position. + + The earliest arrival (outbound) or latest departure (return), None + when none is reached. + """ + x, y = self._cell(lon, lat) + best = None + for dx in (-1, 0, 1): + for dy in (-1, 0, 1): + for t in self._cells.get((x + dx, y + dy), ()): + if distance(lon, lat, t.lon, t.lat) > radius: + continue + if ( + best is None + or (self.outbound and t.minutes < best) + or (not self.outbound and t.minutes > best) + ): + best = t.minutes + return best + + +@dataclass(frozen=True) +class StopAreaLink: + """A stop area linked to an access waypoint (waypoints_stopareas).""" + + waypoint_id: int + lon: float + lat: float + # the walking distance between the stop area and the waypoint + distance_km: float + + +@dataclass(frozen=True) +class Access: + """When a waypoint can be reached and left, in minutes from midnight.""" + + arrival: int | None + departure: int | None + + @property + def time_on_site(self) -> int | None: + if self.arrival is None or self.departure is None: + return None + return max(self.departure - self.arrival, 0) + + +def walking_minutes(distance_km: float, walking_speed: float = WALKING_SPEED) -> int: + return math.ceil(distance_km * 1000 / walking_speed / 60) + + +def waypoint_access( + links: list[StopAreaLink], + outbound: StopTimeIndex, + back: StopTimeIndex, + walking_speed: float = WALKING_SPEED, +) -> dict[int, Access]: + """Return when each waypoint can be reached and left. + + The earliest arrival at and the latest departure from each waypoint, by + its stop areas, the walk between the stop and the waypoint included. + + The arrival and the departure may be at different stop areas of the + waypoint. + """ + arrivals: dict[int, int] = {} + departures: dict[int, int] = {} + for link in links: + walk = walking_minutes(link.distance_km, walking_speed) + arrival = outbound.best_around(link.lon, link.lat) + if arrival is not None: + arrival += walk + if link.waypoint_id not in arrivals or arrival < arrivals[link.waypoint_id]: + arrivals[link.waypoint_id] = arrival + departure = back.best_around(link.lon, link.lat) + if departure is not None: + departure -= walk + if ( + link.waypoint_id not in departures + or departure > departures[link.waypoint_id] + ): + departures[link.waypoint_id] = departure + return { + waypoint_id: Access(arrivals.get(waypoint_id), departures.get(waypoint_id)) + for waypoint_id in {link.waypoint_id for link in links} + } + + +@dataclass(frozen=True) +class RouteAccess: + """The access of a route: by which waypoints, and the time on site.""" + + arrival: int | None + departure: int | None + arrival_waypoint_id: int | None + departure_waypoint_id: int | None + + @property + def time_on_site(self) -> int | None: + if self.arrival is None or self.departure is None: + return None + return self.departure - self.arrival + + +def route_access( + access_waypoint_ids: list[int], waypoints: dict[int, Access], traverse: bool +) -> RouteAccess: + """Return the best access of a route by its access waypoints. + + A traverse arrives by one access waypoint and leaves from another one; + the other routes leave from the waypoint they arrived at (their access + waypoints are alternatives: going back to another one is not given). + """ + known = [(w, waypoints[w]) for w in access_waypoint_ids if w in waypoints] + if traverse: + arrivals = [(a.arrival, w) for w, a in known if a.arrival is not None] + departures = [(a.departure, w) for w, a in known if a.departure is not None] + arrival = min(arrivals) if arrivals else (None, None) + departure = max(departures) if departures else (None, None) + if ( + arrival[0] is not None + and departure[0] is not None + and departure[0] < arrival[0] + ): + return RouteAccess(None, None, None, None) + return RouteAccess(arrival[0], departure[0], arrival[1], departure[1]) + + best = None + for w, a in known: + on_site = a.time_on_site + if on_site is None or a.departure < a.arrival: + continue + if best is None or on_site > best.time_on_site: + best = RouteAccess(a.arrival, a.departure, w, w) + return best or RouteAccess(None, None, None, None) + + +def fits(access: RouteAccess, duration_minutes: int | None) -> bool | None: + """Return whether the time on site is long enough for the route. + + None when the duration of the route is unknown (the time on site is shown + instead). + """ + on_site = access.time_on_site + if on_site is None: + return False + if duration_minutes is None: + return None + return on_site >= duration_minutes diff --git a/c2corg_api/itinevert/school_holidays.json b/c2corg_api/itinevert/school_holidays.json new file mode 100644 index 000000000..7ecbddd08 --- /dev/null +++ b/c2corg_api/itinevert/school_holidays.json @@ -0,0 +1,61 @@ +{ + "A": [ + ["autumn_holidays", "2025-10-18", "2025-11-03"], + ["christmas_holidays", "2025-12-20", "2026-01-05"], + ["winter_holidays", "2026-02-07", "2026-02-23"], + ["spring_holidays", "2026-04-04", "2026-04-20"], + ["summer_holidays", "2026-07-04", "2026-09-01"], + ["autumn_holidays", "2026-10-17", "2026-11-02"], + ["christmas_holidays", "2026-12-19", "2027-01-04"], + ["winter_holidays", "2027-02-13", "2027-03-01"], + ["spring_holidays", "2027-04-10", "2027-04-26"], + ["summer_holidays", "2027-07-03", "2027-09-02"], + ["autumn_holidays", "2027-10-23", "2027-11-08"], + ["christmas_holidays", "2027-12-18", "2028-01-03"], + ["winter_holidays", "2028-02-19", "2028-03-06"], + ["spring_holidays", "2028-04-22", "2028-05-09"] + ], + "B": [ + ["autumn_holidays", "2025-10-18", "2025-11-03"], + ["christmas_holidays", "2025-12-20", "2026-01-05"], + ["winter_holidays", "2026-02-14", "2026-03-02"], + ["spring_holidays", "2026-04-11", "2026-04-27"], + ["summer_holidays", "2026-07-04", "2026-09-01"], + ["autumn_holidays", "2026-10-17", "2026-11-02"], + ["christmas_holidays", "2026-12-19", "2027-01-04"], + ["winter_holidays", "2027-02-20", "2027-03-08"], + ["spring_holidays", "2027-04-17", "2027-05-03"], + ["summer_holidays", "2027-07-03", "2027-09-02"], + ["autumn_holidays", "2027-10-23", "2027-11-08"], + ["christmas_holidays", "2027-12-18", "2028-01-03"], + ["winter_holidays", "2028-02-05", "2028-02-21"], + ["spring_holidays", "2028-04-08", "2028-04-24"] + ], + "C": [ + ["autumn_holidays", "2025-10-18", "2025-11-03"], + ["christmas_holidays", "2025-12-20", "2026-01-05"], + ["winter_holidays", "2026-02-21", "2026-03-09"], + ["spring_holidays", "2026-04-18", "2026-05-04"], + ["summer_holidays", "2026-07-04", "2026-09-01"], + ["autumn_holidays", "2026-10-17", "2026-11-02"], + ["christmas_holidays", "2026-12-19", "2027-01-04"], + ["winter_holidays", "2027-02-06", "2027-02-22"], + ["spring_holidays", "2027-04-03", "2027-04-19"], + ["summer_holidays", "2027-07-03", "2027-09-02"], + ["autumn_holidays", "2027-10-23", "2027-11-08"], + ["christmas_holidays", "2027-12-18", "2028-01-03"], + ["winter_holidays", "2028-02-12", "2028-02-28"], + ["spring_holidays", "2028-04-15", "2028-05-02"] + ], + "corsica": [ + ["autumn_holidays", "2025-10-18", "2025-11-03"], + ["christmas_holidays", "2025-12-20", "2026-01-05"], + ["winter_holidays", "2026-02-14", "2026-03-02"], + ["spring_holidays", "2026-04-11", "2026-04-27"], + ["summer_holidays", "2026-07-04", "2026-09-03"], + ["autumn_holidays", "2026-10-17", "2026-11-02"], + ["christmas_holidays", "2026-12-19", "2027-01-04"], + ["winter_holidays", "2027-02-13", "2027-03-01"], + ["spring_holidays", "2027-04-10", "2027-04-26"] + ] +} diff --git a/c2corg_api/tests/itinevert/__init__.py b/c2corg_api/tests/itinevert/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/c2corg_api/tests/itinevert/test_day_classes.py b/c2corg_api/tests/itinevert/test_day_classes.py new file mode 100644 index 000000000..bd1702f6d --- /dev/null +++ b/c2corg_api/tests/itinevert/test_day_classes.py @@ -0,0 +1,106 @@ +from datetime import date + +from c2corg_api.itinevert.day_classes import ( + SATURDAY, + SUNDAY, + WEEKDAY, + bank_holidays, + day_class, + department, + easter, + holiday_period, + kind_of_day, + timetable_change, + timetable_year, + zone, +) + +GRENOBLE = '38185' +PARIS = '75056' +STRASBOURG = '67482' + + +def test_zone(): + assert department(GRENOBLE) == '38' + assert zone(GRENOBLE) == 'A' + assert zone(PARIS) == 'C' + assert zone(STRASBOURG) == 'B' + assert zone('2A004') == 'corsica' + assert department('97411') == '974' + assert zone('97411') is None + assert zone(None) is None + + +def test_easter(): + assert easter(2026) == date(2026, 4, 5) + assert easter(2027) == date(2027, 3, 28) + + +def test_bank_holidays(): + days = bank_holidays(2027) + # Easter Monday, Ascension, Whit Monday + assert {date(2027, 3, 29), date(2027, 5, 6), date(2027, 5, 17)} <= days + assert date(2027, 3, 26) not in days + # Good Friday in Alsace-Moselle + assert date(2027, 3, 26) in bank_holidays(2027, alsace_moselle=True) + + +def test_kind_of_day(): + assert kind_of_day(date(2026, 12, 4)) == WEEKDAY + assert kind_of_day(date(2026, 12, 5)) == SATURDAY + assert kind_of_day(date(2026, 12, 6)) == SUNDAY + # Christmas, a Friday + assert kind_of_day(date(2026, 12, 25)) == SUNDAY + assert kind_of_day(date(2026, 12, 26)) == SATURDAY + assert kind_of_day(date(2026, 12, 26), STRASBOURG) == SUNDAY + + +def test_timetable_change(): + assert timetable_change(2026) == date(2026, 12, 13) + assert timetable_change(2027) == date(2027, 12, 12) + assert timetable_year(date(2026, 12, 12)) == 2026 + assert timetable_year(date(2026, 12, 13)) == 2027 + assert timetable_year(date(2027, 1, 9)) == 2027 + + +def test_holiday_period(): + # the Christmas holidays of the zone A: from Saturday 19 to Sunday 3 + assert holiday_period(date(2026, 12, 18), 'A') is None + assert holiday_period(date(2026, 12, 19), 'A') == ( + 'christmas_holidays', + date(2026, 12, 19), + ) + assert holiday_period(date(2027, 1, 3), 'A') == ( + 'christmas_holidays', + date(2026, 12, 19), + ) + assert holiday_period(date(2027, 1, 4), 'A') is None + assert holiday_period(date(2027, 2, 6), 'C')[0] == 'winter_holidays' + assert holiday_period(date(2027, 2, 6), 'A') is None + assert holiday_period(date(2027, 2, 6), None) is None + + +def test_day_class_shared_by_the_saturdays_of_a_period(): + first = day_class(date(2027, 1, 9), GRENOBLE) + assert first == day_class(date(2027, 1, 30), GRENOBLE) + assert first.key == '2027:winter:saturday' + # not the Sunday, not the holidays + assert day_class(date(2027, 1, 10), GRENOBLE) != first + assert day_class(date(2027, 2, 13), GRENOBLE).key == ( + '2027:winter_holidays-2027-02-13:saturday' + ) + # the same Saturday out of holidays in Paris, during them in Grenoble + assert day_class(date(2027, 2, 6), GRENOBLE).key == '2027:winter:saturday' + assert day_class(date(2027, 2, 6), PARIS).key.startswith('2027:winter_holidays') + + +def test_day_class_cut_at_the_timetable_change(): + before = day_class(date(2026, 12, 5), GRENOBLE) + after = day_class(date(2027, 1, 9), GRENOBLE) + assert before.key == '2026:winter:saturday' + assert before != after + + +def test_day_class_out_of_france(): + # no school holidays known: the seasons only + assert day_class(date(2027, 2, 13), None).key == '2027:winter:saturday' diff --git a/c2corg_api/tests/itinevert/test_hubs.py b/c2corg_api/tests/itinevert/test_hubs.py new file mode 100644 index 000000000..5546a8f53 --- /dev/null +++ b/c2corg_api/tests/itinevert/test_hubs.py @@ -0,0 +1,81 @@ +from c2corg_api.itinevert.hubs import ( + Hub, + hub_modes_filter, + rank_hubs, + select_hubs, +) + +GRENOBLE = '38185' +CENTRE = (5.7245, 45.1885) + + +def _stop_area(id, lon, lat, lines, insee=GRENOBLE): + return { + 'id': id, + 'name': id, + 'coord': {'lon': str(lon), 'lat': str(lat)}, + 'administrative_regions': [{'insee': insee}, {'insee': ''}], + 'lines': [ + {'id': f'line:{line}', 'physical_modes': [{'name': mode}]} + for line, mode in lines + ], + } + + +def _lines(prefix, count, mode='Bus'): + return [(f'{prefix}{i}', mode) for i in range(count)] + + +def test_hub_modes_filter(): + assert hub_modes_filter().startswith( + 'physical_mode.id=physical_mode:Train or physical_mode.id=' + ) + + +def test_rank_hubs_groups_the_stop_areas_of_a_hub(): + stop_areas = [ + # the station and its bus station, 100 m apart, sharing a line + _stop_area( + 'station', 5.7146, 45.1914, _lines('t', 8, 'Train') + [('c0', 'Coach')] + ), + _stop_area('bus-station', 5.7158, 45.1910, _lines('c', 5, 'Coach')), + _stop_area('tram', 5.7300, 45.1850, _lines('tram', 3, 'Tramway')), + # another town + _stop_area('elsewhere', 5.7200, 45.1900, _lines('x', 30), insee='38179'), + ] + hubs = rank_hubs(stop_areas, GRENOBLE, CENTRE) + assert [h.stop_area_id for h in hubs] == ['station', 'tram'] + station = hubs[0] + assert station.lines == 13 + assert station.modes == {'Train': 8, 'Coach': 5} + assert sorted(station.stop_area_ids) == ['bus-station', 'station'] + + +def test_rank_hubs_tie_closest_to_the_centre(): + stop_areas = [ + _stop_area('far', 5.70, 45.17, _lines('a', 2, 'Coach')), + _stop_area('close', 5.7246, 45.1886, _lines('b', 2, 'Coach')), + ] + assert [h.stop_area_id for h in rank_hubs(stop_areas, GRENOBLE, CENTRE)] == [ + 'close', + 'far', + ] + + +def _hub(id, lines): + return Hub(id, id, 0, 0, lines) + + +def test_select_hubs_more_than_10_lines(): + hubs = [_hub('a', 52), _hub('b', 13), _hub('c', 11), _hub('d', 10)] + assert [h.stop_area_id for h in select_hubs(hubs)] == ['a', 'b', 'c'] + + +def test_select_hubs_at_most(): + hubs = [_hub(str(i), 50 - i) for i in range(10)] + assert len(select_hubs(hubs)) == 6 + + +def test_select_hubs_small_town_keeps_the_best(): + assert [h.stop_area_id for h in select_hubs([_hub('a', 2), _hub('b', 1)])] == ['a'] + assert select_hubs([]) == [] diff --git a/c2corg_api/tests/itinevert/test_reachability.py b/c2corg_api/tests/itinevert/test_reachability.py new file mode 100644 index 000000000..295409939 --- /dev/null +++ b/c2corg_api/tests/itinevert/test_reachability.py @@ -0,0 +1,148 @@ +from datetime import date + +from c2corg_api.itinevert.reachability import ( + OUTBOUND, + RETURN, + Access, + StopAreaLink, + StopTime, + StopTimeIndex, + compact, + fits, + minutes_from, + route_access, + stop_times, + uncompact, + walking_minutes, + waypoint_access, +) + +DAY = date(2026, 12, 5) + +# two stops of the Vercors, 1 km apart +VILLARD = (5.5530, 45.0717) +LANS = (5.5895, 45.1280) + + +def _journey(place_key, stop_id, lon, lat, moment): + key = 'arrival_date_time' if place_key == 'to' else 'departure_date_time' + return { + place_key: { + 'id': stop_id, + 'stop_point': {'id': stop_id, 'coord': {'lon': str(lon), 'lat': str(lat)}}, + }, + key: moment, + } + + +def test_minutes_from(): + assert minutes_from(DAY, '20261205T082700') == 8 * 60 + 27 + # after midnight + assert minutes_from(DAY, '20261206T001000') == 1440 + 10 + + +def test_stop_times_outbound_keeps_the_earliest_arrival(): + answer = { + 'journeys': [ + _journey('to', 'sp:1', *VILLARD, '20261205T090000'), + _journey('to', 'sp:1', *VILLARD, '20261205T082700'), + _journey('to', 'sp:2', *LANS, '20261205T081700'), + # an address, not a stop point + { + 'to': {'id': 'addr', 'address': {}}, + 'arrival_date_time': '20261205T070000', + }, + ] + } + times = {t.stop_point_id: t.minutes for t in stop_times(answer, OUTBOUND, DAY)} + assert times == {'sp:1': 507, 'sp:2': 497} + + +def test_stop_times_return_keeps_the_latest_departure(): + answer = { + 'journeys': [ + _journey('from', 'sp:1', *VILLARD, '20261205T175500'), + _journey('from', 'sp:1', *VILLARD, '20261205T163000'), + ] + } + (t,) = stop_times(answer, RETURN, DAY) + assert t.minutes == 17 * 60 + 55 + + +def test_compact_round_trip(): + times = [StopTime('sp:1', 5.553, 45.0717, 507)] + assert uncompact(compact(times)) == times + + +def test_index_finds_the_stop_points_around(): + index = StopTimeIndex( + [StopTime('sp:1', *VILLARD, 507), StopTime('sp:2', 5.5531, 45.0718, 520)], + OUTBOUND, + ) + assert index.best_around(*VILLARD) == 507 + # 1 km away: none + assert index.best_around(5.5530, 45.0807) is None + + +def test_index_return_takes_the_latest(): + index = StopTimeIndex( + [StopTime('sp:1', *VILLARD, 1000), StopTime('sp:2', 5.5531, 45.0718, 1075)], + RETURN, + ) + assert index.best_around(*VILLARD) == 1075 + + +def test_walking_minutes(): + # 1.12 m/s: 1 km in 15 minutes + assert walking_minutes(1.0) == 15 + assert walking_minutes(0) == 0 + + +def test_waypoint_access_adds_the_walk(): + outbound = StopTimeIndex([StopTime('sp:1', *VILLARD, 507)], OUTBOUND) + back = StopTimeIndex([StopTime('sp:1', *VILLARD, 1075)], RETURN) + links = [StopAreaLink(10, *VILLARD, 1.0), StopAreaLink(11, *LANS, 0.1)] + access = waypoint_access(links, outbound, back) + assert access[10] == Access(507 + 15, 1075 - 15) + assert access[10].time_on_site == 1075 - 507 - 30 + # its stop is not served + assert access[11] == Access(None, None) + assert access[11].time_on_site is None + + +def test_waypoint_access_best_stop_each_way(): + # arrival by one stop area, departure from another one + outbound = StopTimeIndex([StopTime('sp:1', *VILLARD, 500)], OUTBOUND) + back = StopTimeIndex([StopTime('sp:2', *LANS, 1100)], RETURN) + links = [StopAreaLink(10, *VILLARD, 0), StopAreaLink(10, *LANS, 0)] + assert waypoint_access(links, outbound, back)[10] == Access(500, 1100) + + +def test_route_access_not_traverse_stays_at_one_waypoint(): + waypoints = {1: Access(500, 600), 2: Access(700, 1100), 3: Access(450, None)} + access = route_access([1, 2, 3], waypoints, traverse=False) + assert (access.arrival, access.departure) == (700, 1100) + assert access.arrival_waypoint_id == access.departure_waypoint_id == 2 + assert access.time_on_site == 400 + + +def test_route_access_traverse_changes_waypoint(): + waypoints = {1: Access(450, None), 2: Access(700, 1100)} + access = route_access([1, 2], waypoints, traverse=True) + assert (access.arrival_waypoint_id, access.departure_waypoint_id) == (1, 2) + assert access.time_on_site == 650 + + +def test_route_access_unreached(): + access = route_access([1, 4], {1: Access(None, 900)}, traverse=False) + assert access.time_on_site is None + assert route_access([1], {1: Access(900, 800)}, traverse=True).time_on_site is None + + +def test_fits(): + access = route_access([1], {1: Access(500, 1000)}, traverse=False) + assert fits(access, 400) is True + assert fits(access, 600) is False + # duration unknown: the time on site is shown + assert fits(access, None) is None + assert fits(route_access([9], {}, traverse=False), 60) is False diff --git a/scripts/itinevert/update_school_holidays.py b/scripts/itinevert/update_school_holidays.py new file mode 100644 index 000000000..d9966051c --- /dev/null +++ b/scripts/itinevert/update_school_holidays.py @@ -0,0 +1,87 @@ +"""Update the school holidays of c2corg_api/itinevert/school_holidays.json. + +The French school holidays per zone, from the open data of the ministry of +education (data.education.gouv.fr, dataset fr-en-calendrier-scolaire, Licence +Ouverte). To run when a new school year is published (about a year ahead): + + python scripts/itinevert/update_school_holidays.py + +The days of holidays of a period are [start, end): the end is the first day of +school again. The one-day bridges (Ascension) are left out. +""" + +import json +import pathlib +import urllib.parse +import urllib.request +from datetime import datetime +from zoneinfo import ZoneInfo + +URL = ( + 'https://data.education.gouv.fr/api/explore/v2.1/catalog/datasets/' + 'fr-en-calendrier-scolaire/records' +) +TARGET = ( + pathlib.Path(__file__).resolve().parents[2] + / 'c2corg_api' + / 'itinevert' + / 'school_holidays.json' +) +PARIS = ZoneInfo('Europe/Paris') +ZONES = {'Zone A': 'A', 'Zone B': 'B', 'Zone C': 'C', 'Corse': 'corsica'} +PERIODS = { + 'Vacances de la Toussaint': 'autumn_holidays', + 'Vacances de Noël': 'christmas_holidays', + "Vacances d'Hiver": 'winter_holidays', + 'Vacances de Printemps': 'spring_holidays', + "Vacances d'Été": 'summer_holidays', +} + + +def _day(value): + return datetime.fromisoformat(value).astimezone(PARIS).date().isoformat() + + +def fetch(year): + where = f'annee_scolaire="{year}" and population in ("-", "Élèves")' + query = urllib.parse.urlencode( + { + 'select': 'description,start_date,end_date,zones', + 'where': where, + 'group_by': 'description,start_date,end_date,zones', + 'limit': 100, + } + ) + request = urllib.request.Request( + f'{URL}?{query}', headers={'User-Agent': 'c2corg-api'} + ) + with urllib.request.urlopen(request, timeout=30) as response: + return json.load(response)['results'] + + +def main(): + first = datetime.now(PARIS).year - 1 + holidays = {zone: [] for zone in ZONES.values()} + for year in range(first, first + 3): + for row in fetch(f'{year}-{year + 1}'): + zone = ZONES.get(row['zones']) + period = PERIODS.get(row['description'].strip()) + if zone and period: + holidays[zone].append( + [period, _day(row['start_date']), _day(row['end_date'])] + ) + for periods in holidays.values(): + periods.sort(key=lambda p: p[1]) + # a period per line + zones = ',\n'.join( + f' "{zone}": [\n' + + ',\n'.join(f' {json.dumps(period)}' for period in periods) + + '\n ]' + for zone, periods in holidays.items() + ) + TARGET.write_text('{\n' + zones + '\n}\n', encoding='utf-8') + print(TARGET, {zone: len(periods) for zone, periods in holidays.items()}) + + +if __name__ == '__main__': + main() From 8ad7643d59b8d79880388b41b4dc97531c73a249 Mon Sep 17 00:00:00 2001 From: Nayor <11463011+Nayor@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:42:17 +0100 Subject: [PATCH 02/10] feat(itinevert): search API from the transport hubs, by class of days Two routes for the new search of the routes reachable by public transport: - GET /itinevert/hubs: the transport hubs of the town at a position (one or two light Navitia calls, cached ITINEVERT_HUBS_CACHE_DAYS, 365 by default); with a date, whether each hub has its search in cache; - GET /itinevert/reachable: from a hub on a date, the earliest arrival at and latest departure from each access waypoint, and per route its best access and time on site. Two heavy Navitia calls on the first search of a class of days, cached ITINEVERT_SEARCH_CACHE_DAYS (90 by default); a concurrent search of the same class waits for it. The dates are limited to the timetables known by Navitia. Both go through the daily Navitia budget and the limits per client. --- c2corg_api/app.py | 2 + c2corg_api/itinevert/search.py | 384 ++++++++++++++++++ c2corg_api/tests/contract/routes.txt | 2 + .../contract/snapshots/itinevert_hubs.json | 25 ++ .../contract/snapshots/itinevert_invalid.json | 18 + .../snapshots/itinevert_reachable.json | 32 ++ c2corg_api/tests/contract/test_itinevert.py | 95 +++++ c2corg_api/tests/itinevert/test_search.py | 248 +++++++++++ c2corg_api/views/itinevert.py | 80 ++++ c2corg_api/web/itinevert.py | 91 +++++ 10 files changed, 977 insertions(+) create mode 100644 c2corg_api/itinevert/search.py create mode 100644 c2corg_api/tests/contract/snapshots/itinevert_hubs.json create mode 100644 c2corg_api/tests/contract/snapshots/itinevert_invalid.json create mode 100644 c2corg_api/tests/contract/snapshots/itinevert_reachable.json create mode 100644 c2corg_api/tests/contract/test_itinevert.py create mode 100644 c2corg_api/tests/itinevert/test_search.py create mode 100644 c2corg_api/views/itinevert.py create mode 100644 c2corg_api/web/itinevert.py diff --git a/c2corg_api/app.py b/c2corg_api/app.py index fa98110d1..945d760cf 100644 --- a/c2corg_api/app.py +++ b/c2corg_api/app.py @@ -22,6 +22,7 @@ feeds, health, history, + itinevert, misc, navitia, openapi, @@ -129,6 +130,7 @@ def create_fastapi_app(settings, registry=None): misc.include(app) users.include(app) navitia.include(app) + itinevert.include(app) avalanche_bulletins.include(app) partner_outings.include(app) user_actions.include(app) diff --git a/c2corg_api/itinevert/search.py b/c2corg_api/itinevert/search.py new file mode 100644 index 000000000..a46d00c20 --- /dev/null +++ b/c2corg_api/itinevert/search.py @@ -0,0 +1,384 @@ +"""The search of the routes reachable by public transport, with Navitia. + +Binds the plain modules (reachability, day_classes, hubs) to Navitia, Redis +and the database. Every Navitia call goes through `navitia_get`, counted in +the daily budget, and the answers are cached in Redis: +- the hubs of a town: ITINEVERT_HUBS_CACHE_DAYS (the hubs rarely change); +- the stop times of a search, by origin and class of days: + ITINEVERT_SEARCH_CACHE_DAYS (the data of Navitia is reloaded every day, but + the timetables of a class of days rarely change; the check of a chosen + route with a `journeys` request uses the current data); +- the validity period of the data of a coverage: a day. +""" + +import json +import logging +import os +import time +import zlib +from datetime import date, datetime +from zoneinfo import ZoneInfo + +from sqlalchemy import and_, case, func, or_ + +from c2corg_api.httpexceptions import ( + HTTPBadRequest, + HTTPInternalServerError, + HTTPNotFound, + HTTPServiceUnavailable, +) +from c2corg_api.itinevert import hubs as hubs_module +from c2corg_api.itinevert.day_classes import DayClass, day_class +from c2corg_api.itinevert.reachability import ( + OUTBOUND, + RETURN, + StopAreaLink, + StopTimeIndex, + compact, + distance, + route_access, + stop_times, + uncompact, + waypoint_access, +) +from c2corg_api.models import DBSession +from c2corg_api.models.association import Association +from c2corg_api.models.route import Route +from c2corg_api.models.stoparea import Stoparea +from c2corg_api.models.waypoint import Waypoint +from c2corg_api.models.waypoint_stoparea import WaypointStoparea +from c2corg_api.views.coverage import get_coverage +from c2corg_api.views.navitia import BASE_URL, navitia_get, redis_client + +log = logging.getLogger(__name__) + +# the whole day explored: the departures from the origin after +# EARLIEST_DEPARTURE, the arrivals back before LATEST_ARRIVAL, journeys of at +# most MAX_DURATION +EARLIEST_DEPARTURE = '060000' +LATEST_ARRIVAL = '220000' +MAX_DURATION = 4 * 3600 # seconds + +SEARCH_CACHE_DAYS_DEFAULT = 90 +HUBS_CACHE_DAYS_DEFAULT = 365 +COVERAGE_CACHE = 86400 # seconds +# a search being computed by another request: wait for it +LOCK_TTL = 120 # seconds +LOCK_WAIT = 60 # seconds + +_PREFIX = 'itinevert' +PARIS = ZoneInfo('Europe/Paris') + + +def _days_setting(name, default): + try: + return max(int(os.getenv(name, default)), 1) + except ValueError: + return default + + +def _api_key(): + api_key = os.getenv('NAVITIA_API_KEY') + if not api_key: + raise HTTPInternalServerError('Navitia API config is missing') + return api_key + + +def _navitia(path, params): + return navitia_get( + f'{BASE_URL}/{path}', params=params, headers={'Authorization': _api_key()} + ) + + +def _navitia_or_nothing(path, params): + """Call Navitia, an empty answer when nothing is found (no_solution...).""" + try: + return _navitia(path, params) or {} + except HTTPNotFound: + return {} + + +def _get_json(r, key): + raw = r.get(key) + return None if raw is None else json.loads(zlib.decompress(raw)) + + +def _set_json(r, key, value, seconds): + r.set(key, zlib.compress(json.dumps(value).encode()), ex=seconds) + + +def coverage_of(lon: float, lat: float) -> str: + coverage = get_coverage(lon, lat) + if not coverage: + raise HTTPBadRequest('no_coverage') + return coverage + + +def coverage_end(coverage: str) -> date: + """Return the last day of the timetables of a coverage (a light call).""" + r = redis_client() + key = f'{_PREFIX}:coverage_end:{coverage}' + cached = r.get(key) + if cached is None: + region = _navitia(f'coverage/{coverage}', None)['regions'][0] + cached = region['end_production_date'].encode() + r.set(key, cached, ex=COVERAGE_CACHE) + return datetime.strptime(cached.decode(), '%Y%m%d').date() # noqa: DTZ007 + + +def check_date(day: date, coverage: str, today: date): + """Refuse a date out of the timetables known by Navitia.""" + if day < today or day > coverage_end(coverage): + raise HTTPBadRequest('date_out_of_range') + + +def _stop_areas_around(lon, lat, with_filter): + params = { + 'distance': hubs_module.SEARCH_RADIUS, + 'depth': 3, + 'count': 300, + } + if with_filter: + params['filter'] = hubs_module.hub_modes_filter() + answer = _navitia_or_nothing( + f'coverage/{coverage_of(lon, lat)}/coords/{lon};{lat}/stop_areas', params + ) + return answer.get('stop_areas', []) + + +def _town_of(stop_areas, lon, lat): + """Return the INSEE code of the town of the stop area closest to a point.""" + closest = min( + (s for s in stop_areas if 'coord' in s), + key=lambda s: distance( + lon, lat, float(s['coord']['lon']), float(s['coord']['lat']) + ), + default=None, + ) + if closest is None: + return None + return next( + ( + a['insee'] + for a in closest.get('administrative_regions', []) + if a.get('insee') + ), + None, + ) + + +def town_hubs(lon: float, lat: float, insee: str | None = None): + """Return the hubs of the town at a point: (insee, hubs). + + One light Navitia call, two for a small town served by buses only. + """ + r = redis_client() + key = f'{_PREFIX}:hubs:{insee}' if insee else None + if key: + cached = _get_json(r, key) + if cached is not None: + return insee, [hubs_module.Hub(**h) for h in cached] + + centre = (lon, lat) + stop_areas = _stop_areas_around(lon, lat, with_filter=True) + insee = insee or _town_of(stop_areas, lon, lat) + ranked = hubs_module.rank_hubs(stop_areas, insee, centre) if insee else [] + if not ranked: + # a small town without train, tramway or coach: its bus stops + stop_areas = _stop_areas_around(lon, lat, with_filter=False) + insee = insee or _town_of(stop_areas, lon, lat) + ranked = hubs_module.rank_hubs(stop_areas, insee, centre) if insee else [] + selected = hubs_module.select_hubs(ranked) + if insee: + days = _days_setting('ITINEVERT_HUBS_CACHE_DAYS', HUBS_CACHE_DAYS_DEFAULT) + _set_json( + r, f'{_PREFIX}:hubs:{insee}', [vars(h) for h in selected], days * 86400 + ) + return insee, selected + + +def _search_key(coverage, origin, klass: DayClass): + return f'{_PREFIX}:search:{coverage}:{origin}:{klass.key}' + + +def cached_search(coverage, origin, klass) -> bool: + return bool(redis_client().exists(_search_key(coverage, origin, klass))) + + +def _fetch_stop_times(coverage, origin, day: date): + """Return the stop times of a day from an origin: two heavy calls.""" + stamp = day.strftime('%Y%m%d') + outbound = _navitia_or_nothing( + f'coverage/{coverage}/journeys', + { + 'from': origin, + 'datetime': f'{stamp}T{EARLIEST_DEPARTURE}', + 'datetime_represents': 'departure', + 'max_duration': MAX_DURATION, + }, + ) + back = _navitia_or_nothing( + f'coverage/{coverage}/journeys', + { + 'to': origin, + 'datetime': f'{stamp}T{LATEST_ARRIVAL}', + 'datetime_represents': 'arrival', + 'max_duration': MAX_DURATION, + }, + ) + return { + 'date': day.isoformat(), + OUTBOUND: compact(stop_times(outbound, OUTBOUND, day)), + RETURN: compact(stop_times(back, RETURN, day)), + } + + +def search_stop_times(coverage: str, origin: str, day: date, insee: str | None): + """Return the stop times of the class of days of a date, from the cache. + + The first search of a class computes it on its date; the requests asking + for it meanwhile wait for it rather than calling Navitia again. + """ + klass = day_class(day, insee) + r = redis_client() + key = _search_key(coverage, origin, klass) + lock = f'{key}:lock' + deadline = time.monotonic() + LOCK_WAIT + while True: + cached = _get_json(r, key) + if cached is not None: + return klass, cached + if r.set(lock, 1, nx=True, ex=LOCK_TTL): + break + if time.monotonic() > deadline: + raise HTTPServiceUnavailable('itinevert_search_busy') + time.sleep(1) + try: + value = _fetch_stop_times(coverage, origin, day) + days = _days_setting('ITINEVERT_SEARCH_CACHE_DAYS', SEARCH_CACHE_DAYS_DEFAULT) + _set_json(r, key, value, days * 86400) + log.info( + 'itinevert search computed: %s %s, %d / %d stop points', + origin, + klass.key, + len(value[OUTBOUND]), + len(value[RETURN]), + ) + return klass, value + finally: + r.delete(lock) + + +def stop_area_links(): + """Return the stop areas linked to the access waypoints.""" + geom = func.ST_Transform(Stoparea.geom, 4326) + rows = ( + DBSession.query( + WaypointStoparea.waypoint_id, + func.ST_X(geom), + func.ST_Y(geom), + WaypointStoparea.distance, + ) + .join(Stoparea, Stoparea.stoparea_id == WaypointStoparea.stoparea_id) + .join(Waypoint, Waypoint.document_id == WaypointStoparea.waypoint_id) + .filter(Waypoint.waypoint_type == 'access', Stoparea.geom.isnot(None)) + .distinct() + .all() + ) + return [StopAreaLink(w, lon, lat, d) for w, lon, lat, d in rows] + + +def routes_of_waypoints(waypoint_ids): + """Return the routes of access waypoints. + + {route_id: (waypoint ids, traverse, duration in minutes)} + """ + # the associations in both directions: the waypoint is the parent, or + # the route is + waypoint_id = case( + ( + Association.parent_document_id == Route.document_id, + Association.child_document_id, + ), + else_=Association.parent_document_id, + ) + rows = ( + DBSession.query( + Route.document_id, + waypoint_id, + Route.route_types, + Route.calculated_duration, + ) + .join( + Association, + or_( + and_( + Association.child_document_id == Route.document_id, + Association.parent_document_id.in_(waypoint_ids), + ), + and_( + Association.parent_document_id == Route.document_id, + Association.child_document_id.in_(waypoint_ids), + ), + ), + ) + .filter(Route.redirects_to.is_(None)) + .all() + ) + routes = {} + for route_id, waypoint_id, route_types, duration in rows: + waypoints, _, _ = routes.setdefault( + route_id, + ( + [], + 'traverse' in (route_types or []), + round(duration * 24 * 60) if duration else None, + ), + ) + waypoints.append(waypoint_id) + return routes + + +def reachable(stop_times_value): + """Return the time on site of the waypoints and routes reachable.""" + outbound = StopTimeIndex(uncompact(stop_times_value[OUTBOUND]), OUTBOUND) + back = StopTimeIndex(uncompact(stop_times_value[RETURN]), RETURN) + access = waypoint_access(stop_area_links(), outbound, back) + waypoints = { + w: a + for w, a in access.items() + if a.arrival is not None or a.departure is not None + } + routes = [] + for route_id, (waypoint_ids, traverse, duration) in routes_of_waypoints( + list(waypoints) + ).items(): + best = route_access(waypoint_ids, waypoints, traverse) + if best.time_on_site is None: + continue + routes.append( + { + 'id': route_id, + 'arrival': best.arrival, + 'departure': best.departure, + 'arrival_waypoint_id': best.arrival_waypoint_id, + 'departure_waypoint_id': best.departure_waypoint_id, + 'time_on_site': best.time_on_site, + # in minutes, None when unknown + 'duration': duration, + } + ) + # the longest time on site first + routes.sort(key=lambda r: (-r['time_on_site'], r['id'])) + return { + 'waypoints': [ + {'id': w, 'arrival': a.arrival, 'departure': a.departure} + for w, a in sorted(waypoints.items()) + ], + 'routes': routes, + } + + +def today_in_france(): + """Return the current day in France, the day of the timetables.""" + return datetime.now(PARIS).date() diff --git a/c2corg_api/tests/contract/routes.txt b/c2corg_api/tests/contract/routes.txt index 003c2b93e..c88b58fb4 100644 --- a/c2corg_api/tests/contract/routes.txt +++ b/c2corg_api/tests/contract/routes.txt @@ -70,6 +70,8 @@ GET /images/{id} [public] PUT /images/{id} [authenticated] GET /images/{id}/{lang}/info [public] GET /images/{id}/{lang}/{version_id} [public] +GET /itinevert/hubs [public] +GET /itinevert/reachable [public] GET /maps [public] POST /maps [moderator] GET /maps/{id} [public] diff --git a/c2corg_api/tests/contract/snapshots/itinevert_hubs.json b/c2corg_api/tests/contract/snapshots/itinevert_hubs.json new file mode 100644 index 000000000..eaf62666f --- /dev/null +++ b/c2corg_api/tests/contract/snapshots/itinevert_hubs.json @@ -0,0 +1,25 @@ +{ + "body": { + "day_class": "str", + "hubs": [ + { + "cached": "bool", + "id": "str", + "lat": "float", + "lines": "int", + "lon": "float", + "modes": { + "Train": "int" + }, + "name": "str" + } + ], + "insee": "str" + }, + "headers": { + "Access-Control-Allow-Origin": "http://localhost:6553", + "Access-Control-Expose-Headers": "Content-Type", + "Content-Type": "application/json" + }, + "status": 200 +} diff --git a/c2corg_api/tests/contract/snapshots/itinevert_invalid.json b/c2corg_api/tests/contract/snapshots/itinevert_invalid.json new file mode 100644 index 000000000..c043f1f2a --- /dev/null +++ b/c2corg_api/tests/contract/snapshots/itinevert_invalid.json @@ -0,0 +1,18 @@ +{ + "body": { + "errors": [ + { + "description": "str", + "location": "str", + "name": "str" + } + ], + "status": "str" + }, + "headers": { + "Access-Control-Allow-Origin": "http://localhost:6553", + "Access-Control-Expose-Headers": "Content-Type", + "Content-Type": "application/json" + }, + "status": 400 +} diff --git a/c2corg_api/tests/contract/snapshots/itinevert_reachable.json b/c2corg_api/tests/contract/snapshots/itinevert_reachable.json new file mode 100644 index 000000000..a572c89eb --- /dev/null +++ b/c2corg_api/tests/contract/snapshots/itinevert_reachable.json @@ -0,0 +1,32 @@ +{ + "body": { + "computed_on": "str", + "date": "str", + "day_class": "str", + "origin": "str", + "routes": [ + { + "arrival": "int", + "arrival_waypoint_id": "int", + "departure": "int", + "departure_waypoint_id": "int", + "duration": "null", + "id": "int", + "time_on_site": "int" + } + ], + "waypoints": [ + { + "arrival": "int", + "departure": "int", + "id": "int" + } + ] + }, + "headers": { + "Access-Control-Allow-Origin": "http://localhost:6553", + "Access-Control-Expose-Headers": "Content-Type", + "Content-Type": "application/json" + }, + "status": 200 +} diff --git a/c2corg_api/tests/contract/test_itinevert.py b/c2corg_api/tests/contract/test_itinevert.py new file mode 100644 index 000000000..626f5c9bc --- /dev/null +++ b/c2corg_api/tests/contract/test_itinevert.py @@ -0,0 +1,95 @@ +from datetime import date +from unittest import mock + +import pytest + +from c2corg_api.itinevert import search +from c2corg_api.models.area import Area +from c2corg_api.models.document import DocumentLocale +from c2corg_api.models.stoparea import Stoparea +from c2corg_api.models.waypoint_stoparea import WaypointStoparea +from c2corg_api.tests.contract import check_snapshot, contract +from c2corg_api.tests.contract.test_misc import navitia_coverage # noqa: F401 +from c2corg_api.tests.itinevert.test_search import ORIGIN, FakeRedis, _navitia +from c2corg_api.tests.views.test_reachable import POINT, add_route, add_waypoint + +HUBS = ('GET', '/itinevert/hubs') +REACHABLE = ('GET', '/itinevert/reachable') +# in the coverage of the navitia_coverage fixture +POSITION = {'lon': 5.71, 'lat': 45.655} + + +@pytest.fixture +def fakes(): + with ( + mock.patch.object(search, 'redis_client', return_value=FakeRedis()), + mock.patch.object(search, 'navitia_get', side_effect=_navitia) as navitia, + mock.patch.object(search, 'today_in_france', return_value=date(2026, 12, 2)), + mock.patch('c2corg_api.web.itinevert.navitia_rate_limited', return_value=False), + mock.patch.dict('os.environ', {'NAVITIA_API_KEY': 'contract-test-key'}), + ): + yield navitia + + +@pytest.fixture +def reachable_route(session): + area = Area(area_type='range', locales=[DocumentLocale(lang='fr', title='A')]) + session.add(area) + session.flush() + waypoint = add_waypoint(session, area, 'access', 'Arret') + stoparea = Stoparea( + navitia_id='stop_area:1', + stoparea_name='Arret', + line='1', + operator='Bus', + geom=POINT, + ) + session.add(stoparea) + session.flush() + session.add( + WaypointStoparea( + waypoint_id=waypoint.document_id, + stoparea_id=stoparea.stoparea_id, + distance=0.5, + ) + ) + add_route(session, area, 'hiking', 'Boucle', waypoint) + session.flush() + + +@pytest.mark.usefixtures('navitia_coverage', 'fakes') +class TestItinevert: + @contract(HUBS) + def test_hubs(self, browser): + response = browser.get( + '/itinevert/hubs', params={**POSITION, 'date': '2026-12-05'} + ) + check_snapshot('itinevert_hubs', response) + assert response.json['hubs'][0]['id'] == ORIGIN + + @contract(HUBS) + def test_hubs_invalid(self, browser): + response = browser.get( + '/itinevert/hubs', params={**POSITION, 'insee': 'x'}, status=400 + ) + check_snapshot('itinevert_invalid', response) + + @pytest.mark.usefixtures('reachable_route') + @contract(REACHABLE) + def test_reachable(self, browser): + response = browser.get( + '/itinevert/reachable', + params={**POSITION, 'origin': ORIGIN, 'date': '2026-12-05'}, + ) + check_snapshot('itinevert_reachable', response) + assert len(response.json['routes']) == 1 + + @contract(REACHABLE) + def test_reachable_out_of_range(self, browser): + response = browser.get( + '/itinevert/reachable', + params={**POSITION, 'origin': ORIGIN, 'date': '2027-06-01'}, + status=400, + ) + check_snapshot('itinevert_invalid', response) + assert response.json['errors'][0]['description'] == 'date_out_of_range' diff --git a/c2corg_api/tests/itinevert/test_search.py b/c2corg_api/tests/itinevert/test_search.py new file mode 100644 index 000000000..65d87c4df --- /dev/null +++ b/c2corg_api/tests/itinevert/test_search.py @@ -0,0 +1,248 @@ +"""The search with the database, Navitia and Redis replaced by fakes.""" + +from datetime import date +from unittest import mock + +import pytest + +from c2corg_api.httpexceptions import HTTPNotFound +from c2corg_api.itinevert import search +from c2corg_api.models.area import Area +from c2corg_api.models.document import DocumentLocale +from c2corg_api.models.stoparea import Stoparea +from c2corg_api.models.waypoint_stoparea import WaypointStoparea +from c2corg_api.tests.views.test_reachable import ( + POINT, + add_route, + add_waypoint, +) + +DAY = date(2026, 12, 5) +ORIGIN = 'stop_area:SNC:StopArea:OCE87747006' +GRENOBLE = (5.7146, 45.1914) +# POINT, the stop area of the tests, in WGS84 +STOP = (5.71293, 45.64489) + + +class FakeRedis: + """In-memory replacement of the Redis client of the search.""" + + def __init__(self): + self.data = {} + + def get(self, key): + return self.data.get(key) + + def set(self, key, value, ex=None, nx=False): + if nx and key in self.data: + return False + self.data[key] = value if isinstance(value, bytes) else str(value).encode() + return True + + def exists(self, key): + return int(key in self.data) + + def delete(self, key): + self.data.pop(key, None) + + +def _journey(place_key, moment): + key = 'arrival_date_time' if place_key == 'to' else 'departure_date_time' + return { + place_key: { + 'id': 'stop_point:1', + 'stop_point': { + 'id': 'stop_point:1', + 'coord': {'lon': str(STOP[0]), 'lat': str(STOP[1])}, + }, + }, + key: moment, + } + + +def _navitia(url, params=None, headers=None): + """Answer as Navitia, from the path of the url.""" + if url.endswith('/coverage/fr-se'): + return {'regions': [{'end_production_date': '20270302'}]} + if url.endswith('/journeys'): + if 'from' in params: + return {'journeys': [_journey('to', '20261205T082700')]} + return {'journeys': [_journey('from', '20261205T175500')]} + if url.endswith('/stop_areas'): + return { + 'stop_areas': [ + { + 'id': ORIGIN, + 'name': 'Grenoble', + 'coord': {'lon': str(GRENOBLE[0]), 'lat': str(GRENOBLE[1])}, + 'administrative_regions': [{'insee': '38185'}], + 'lines': [ + {'id': f'line:{i}', 'physical_modes': [{'name': 'Train'}]} + for i in range(12) + ], + } + ] + } + raise AssertionError(url) + + +@pytest.fixture +def fakes(): + redis = FakeRedis() + with ( + mock.patch.object(search, 'redis_client', return_value=redis), + mock.patch.object(search, 'navitia_get', side_effect=_navitia) as navitia, + mock.patch.object(search, 'get_coverage', return_value='fr-se'), + mock.patch.object(search, 'today_in_france', return_value=date(2026, 12, 2)), + mock.patch('c2corg_api.web.itinevert.navitia_rate_limited', return_value=False), + mock.patch.dict('os.environ', {'NAVITIA_API_KEY': 'key'}), + ): + yield navitia + + +@pytest.fixture +def access(session): + area = Area(area_type='range', locales=[DocumentLocale(lang='fr', title='A')]) + session.add(area) + session.flush() + waypoint = add_waypoint(session, area, 'access', 'Arret') + stoparea = Stoparea( + navitia_id='stop_area:1', + stoparea_name='Arret', + line='1', + operator='Bus', + geom=POINT, + ) + session.add(stoparea) + session.flush() + # 0.5 km: 8 minutes of walk + session.add( + WaypointStoparea( + waypoint_id=waypoint.document_id, + stoparea_id=stoparea.stoparea_id, + distance=0.5, + ) + ) + route = add_route(session, area, 'hiking', 'Boucle', waypoint) + reverse = add_route(session, area, 'hiking', 'Inverse', waypoint, reverse=True) + session.flush() + return waypoint, route, reverse + + +def test_stop_area_links(access): + waypoint, _, _ = access + links = search.stop_area_links() + (link,) = [found for found in links if found.waypoint_id == waypoint.document_id] + assert link.lon == pytest.approx(STOP[0], abs=1e-4) + assert link.lat == pytest.approx(STOP[1], abs=1e-4) + assert link.distance_km == 0.5 + + +def test_routes_of_waypoints_both_directions(access): + waypoint, route, reverse = access + routes = search.routes_of_waypoints([waypoint.document_id]) + assert routes[route.document_id][0] == [waypoint.document_id] + assert routes[reverse.document_id][0] == [waypoint.document_id] + + +def test_reachable(client, access, fakes): + waypoint, route, _ = access + params = { + 'origin': ORIGIN, + 'lon': GRENOBLE[0], + 'lat': GRENOBLE[1], + 'date': '2026-12-05', + } + body = client.get('/itinevert/reachable', params=params, status=200).json + assert body['day_class'] == '2026:winter:saturday' + assert body['computed_on'] == '2026-12-05' + # 08:27 + 8 minutes of walk, 17:55 - 8 minutes + assert { + 'id': waypoint.document_id, + 'arrival': 8 * 60 + 35, + 'departure': 17 * 60 + 47, + } in body['waypoints'] + (found,) = [r for r in body['routes'] if r['id'] == route.document_id] + assert found['time_on_site'] == 17 * 60 + 47 - (8 * 60 + 35) + assert found['arrival_waypoint_id'] == waypoint.document_id + # the coverage, the outbound and the return + assert fakes.call_count == 3 + + # another Saturday of the class: from the cache + params['date'] = '2026-12-12' + body = client.get('/itinevert/reachable', params=params, status=200).json + assert body['computed_on'] == '2026-12-05' + assert fakes.call_count == 3 + + +def test_reachable_invalid(client, fakes): + params = {'origin': ORIGIN, 'lon': GRENOBLE[0], 'lat': GRENOBLE[1]} + for invalid in ( + {'date': '2026-12-05', 'origin': 'admin:fr:38185'}, + {'date': '2026-13-05'}, + # past, after the end of the timetables + {'date': '2026-12-01'}, + {'date': '2027-03-03'}, + {'date': '2026-12-05', 'lon': 200}, + ): + client.get('/itinevert/reachable', params={**params, **invalid}, status=400) + # a required parameter missing + client.get('/itinevert/reachable', params=params, status=422) + # no search computed + assert not [c for c in fakes.call_args_list if c.args[0].endswith('/journeys')] + + +def test_reachable_nothing_found(client, fakes): + def nothing(url, params=None, headers=None): + if url.endswith('/journeys'): + raise HTTPNotFound('no_solution') + return _navitia(url, params, headers) + + fakes.side_effect = nothing + params = { + 'origin': ORIGIN, + 'lon': GRENOBLE[0], + 'lat': GRENOBLE[1], + 'date': '2026-12-05', + } + body = client.get('/itinevert/reachable', params=params, status=200).json + assert body['routes'] == [] + + +def test_hubs(client, fakes): + params = {'lon': GRENOBLE[0], 'lat': GRENOBLE[1], 'date': '2026-12-05'} + body = client.get('/itinevert/hubs', params=params, status=200).json + assert body['insee'] == '38185' + assert [(h['id'], h['lines'], h['cached']) for h in body['hubs']] == [ + (ORIGIN, 12, False) + ] + calls = fakes.call_count + # from the cache of the town + client.get('/itinevert/hubs', params={**params, 'insee': '38185'}, status=200) + assert fakes.call_count == calls + + +def test_hubs_cached_search(client, access, fakes): + search_params = { + 'origin': ORIGIN, + 'lon': GRENOBLE[0], + 'lat': GRENOBLE[1], + 'date': '2026-12-05', + 'insee': '38185', + } + client.get('/itinevert/reachable', params=search_params, status=200) + params = {'lon': GRENOBLE[0], 'lat': GRENOBLE[1], 'date': '2026-12-12'} + body = client.get('/itinevert/hubs', params=params, status=200).json + assert body['hubs'][0]['cached'] is True + + +def test_search_waits_for_the_one_computing(fakes, monkeypatch): + redis = search.redis_client() + klass = search.day_class(DAY, '38185') + key = search._search_key('fr-se', ORIGIN, klass) + redis.set(f'{key}:lock', 1) + monkeypatch.setattr(search, 'LOCK_WAIT', 0) + monkeypatch.setattr(search.time, 'sleep', lambda s: None) + with pytest.raises(search.HTTPServiceUnavailable): + search.search_stop_times('fr-se', ORIGIN, DAY, '38185') + assert fakes.call_count == 0 diff --git a/c2corg_api/views/itinevert.py b/c2corg_api/views/itinevert.py new file mode 100644 index 000000000..30a0cb4c8 --- /dev/null +++ b/c2corg_api/views/itinevert.py @@ -0,0 +1,80 @@ +"""The views of the search of the routes reachable by public transport.""" + +import re +from datetime import date + +from c2corg_api.httpexceptions import HTTPBadRequest +from c2corg_api.itinevert import search +from c2corg_api.itinevert.day_classes import day_class + +# a Navitia stop area: the origin of a search +STOP_AREA = re.compile(r'^stop_area:[\w:.\-]{1,120}$') +INSEE = re.compile(r'^(\d{5}|2[AB]\d{3})$') + + +def _position(request): + lon, lat = request.validated['lon'], request.validated['lat'] + if not (-180 <= lon <= 180 and -90 <= lat <= 90): + raise HTTPBadRequest('invalid_position') + return lon, lat + + +def _insee(request): + insee = request.validated.get('insee') + if insee is not None and not INSEE.match(insee): + raise HTTPBadRequest('invalid_insee') + return insee + + +def _date(request): + try: + return date.fromisoformat(request.validated['date']) + except ValueError as e: + raise HTTPBadRequest('invalid_date') from e + + +def read_hubs(request): + """Return the transport hubs of the town at a position. + + With a date, each hub says whether its search of the class of days of the + date is already computed (an immediate answer, no Navitia call). + """ + lon, lat = _position(request) + insee, hubs = search.town_hubs(lon, lat, _insee(request)) + answer = {'insee': insee, 'hubs': [h.to_dict() for h in hubs]} + if request.validated.get('date') and hubs: + day = _date(request) + klass = day_class(day, insee) + coverage = search.coverage_of(lon, lat) + for hub in answer['hubs']: + hub['cached'] = search.cached_search(coverage, hub['id'], klass) + answer['day_class'] = klass.key + return answer + + +def read_reachable(request): + """Return the waypoints and routes reachable from a hub on a date. + + The times are in minutes from the midnight of the date: the earliest + arrival at and the latest departure from each access waypoint (the walk + from the stop included), and per route the best access and its time on + site. Computed with two Navitia calls on the first search of a class of + days, from the cache afterwards. + """ + origin = request.validated['origin'] + if not STOP_AREA.match(origin): + raise HTTPBadRequest('invalid_origin') + lon, lat = _position(request) + insee = _insee(request) + day = _date(request) + coverage = search.coverage_of(lon, lat) + search.check_date(day, coverage, search.today_in_france()) + klass, stop_times = search.search_stop_times(coverage, origin, day, insee) + return { + 'origin': origin, + 'date': day.isoformat(), + 'day_class': klass.key, + # the date the class was computed on + 'computed_on': stop_times['date'], + **search.reachable(stop_times), + } diff --git a/c2corg_api/web/itinevert.py b/c2corg_api/web/itinevert.py new file mode 100644 index 000000000..bd2e428d5 --- /dev/null +++ b/c2corg_api/web/itinevert.py @@ -0,0 +1,91 @@ +"""The search of the routes reachable by public transport (Itinevert).""" +# The routes call the functions of views/ through web.handlers, as the +# document routes do (#2365). Their parameters are typed (#2512). + +from typing import Annotated + +from fastapi import Depends, Query, Request + +from c2corg_api.httpexceptions import HTTPTooManyRequests +from c2corg_api.security.rate_limiting import navitia_rate_limited +from c2corg_api.views.itinevert import read_hubs, read_reachable +from c2corg_api.web.auth import CurrentUser, current_user +from c2corg_api.web.handlers import serve_read, typed_values + +User = Annotated[CurrentUser | None, Depends(current_user)] +Lon = Annotated[float, Query(description='The longitude (WGS84).')] +Lat = Annotated[float, Query(description='The latitude (WGS84).')] +Insee = Annotated[ + str | None, + Query(description='The INSEE code of the town, found from the position else.'), +] +Day = Annotated[str, Query(description='The date, YYYY-MM-DD.')] + + +def include(app): + """Add the routes of this module to the FastAPI application.""" + for path, endpoint in ( + ('/itinevert/hubs', hubs), + ('/itinevert/reachable', reachable), + ): + # typed parameters: described in the OpenAPI document (web.openapi) + endpoint.described = True + app.add_api_route( + path, + endpoint, + methods=['GET', 'HEAD'], + operation_id=endpoint.__name__, + tags=['itinevert'], + ) + + +def _limited(view, bucket): + """Return the view, refusing the requests of a client over its limit.""" + + def limited(request): + if navitia_rate_limited(request, request.registry.settings, bucket): + raise HTTPTooManyRequests('Too many public transport searches: retry later') + return view(request) + + return limited + + +# the hubs: one or two light Navitia calls; a search: two heavy ones +_read_hubs = _limited(read_hubs, 'navitia') +_read_reachable = _limited(read_reachable, 'navitia_job') + + +def hubs( + request: Request, + user: User, + lon: Lon, + lat: Lat, + insee: Insee = None, + date: Annotated[ + str | None, + Query(description='A date: whether each hub has its search in cache.'), + ] = None, +): + """Return the transport hubs of the town at a position.""" + validated = {'lon': lon, 'lat': lat, 'insee': insee, 'date': date} + return serve_read(request, user, [typed_values(validated)], _read_hubs) + + +def reachable( + request: Request, + user: User, + origin: Annotated[str, Query(description='The stop area of the hub.')], + lon: Lon, + lat: Lat, + date: Day, + insee: Insee = None, +): + """Return the waypoints and routes reachable from a hub on a date.""" + validated = { + 'origin': origin, + 'lon': lon, + 'lat': lat, + 'date': date, + 'insee': insee, + } + return serve_read(request, user, [typed_values(validated)], _read_reachable) From 17d9845eadb996bbce85268ebebf7a160f8e537b Mon Sep 17 00:00:00 2001 From: Nayor <11463011+Nayor@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:44:05 +0100 Subject: [PATCH 03/10] feat(itinevert): the route listings filtered by a search in cache The parameter itv=origin,date[,insee] of the route listings keeps the routes reachable of a search of /itinevert/reachable in cache, with the other filters and the sort of the topoguide: the routes whose time on site covers their duration first, then the routes of an unknown duration. A listing never calls Navitia: without the search in cache, it answers 400. The cache of a search no longer depends on the coverage: a Navitia stop area is in one coverage. --- c2corg_api/itinevert/search.py | 30 ++++++++++-- c2corg_api/tests/itinevert/test_search.py | 29 ++++++++++- c2corg_api/views/document.py | 60 ++++++++++++++++++++++- c2corg_api/views/itinevert.py | 3 +- 4 files changed, 113 insertions(+), 9 deletions(-) diff --git a/c2corg_api/itinevert/search.py b/c2corg_api/itinevert/search.py index a46d00c20..7397a430d 100644 --- a/c2corg_api/itinevert/search.py +++ b/c2corg_api/itinevert/search.py @@ -197,12 +197,13 @@ def town_hubs(lon: float, lat: float, insee: str | None = None): return insee, selected -def _search_key(coverage, origin, klass: DayClass): - return f'{_PREFIX}:search:{coverage}:{origin}:{klass.key}' +def _search_key(origin, klass: DayClass): + # a Navitia stop area is in one coverage + return f'{_PREFIX}:search:{origin}:{klass.key}' -def cached_search(coverage, origin, klass) -> bool: - return bool(redis_client().exists(_search_key(coverage, origin, klass))) +def cached_search(origin, klass) -> bool: + return bool(redis_client().exists(_search_key(origin, klass))) def _fetch_stop_times(coverage, origin, day: date): @@ -241,7 +242,7 @@ def search_stop_times(coverage: str, origin: str, day: date, insee: str | None): """ klass = day_class(day, insee) r = redis_client() - key = _search_key(coverage, origin, klass) + key = _search_key(origin, klass) lock = f'{key}:lock' deadline = time.monotonic() + LOCK_WAIT while True: @@ -379,6 +380,25 @@ def reachable(stop_times_value): } +def cached_route_ids(origin: str, day: date, insee: str | None): + """Return the ids of the routes reachable, from a search in cache. + + (the ids of the routes whose time on site covers their duration, the ids + of the routes of an unknown duration). The listings of the topoguide + never call Navitia: the search is computed by /itinevert/reachable first. + """ + cached = _get_json(redis_client(), _search_key(origin, day_class(day, insee))) + if cached is None: + raise HTTPBadRequest('itinevert_search_not_computed') + fitting, unknown = [], [] + for route in reachable(cached)['routes']: + if route['duration'] is None: + unknown.append(route['id']) + elif route['time_on_site'] >= route['duration']: + fitting.append(route['id']) + return fitting, unknown + + def today_in_france(): """Return the current day in France, the day of the timetables.""" return datetime.now(PARIS).date() diff --git a/c2corg_api/tests/itinevert/test_search.py b/c2corg_api/tests/itinevert/test_search.py index 65d87c4df..df91a694a 100644 --- a/c2corg_api/tests/itinevert/test_search.py +++ b/c2corg_api/tests/itinevert/test_search.py @@ -11,6 +11,7 @@ from c2corg_api.models.document import DocumentLocale from c2corg_api.models.stoparea import Stoparea from c2corg_api.models.waypoint_stoparea import WaypointStoparea +from c2corg_api.tests.search import reset_search_index from c2corg_api.tests.views.test_reachable import ( POINT, add_route, @@ -239,10 +240,36 @@ def test_hubs_cached_search(client, access, fakes): def test_search_waits_for_the_one_computing(fakes, monkeypatch): redis = search.redis_client() klass = search.day_class(DAY, '38185') - key = search._search_key('fr-se', ORIGIN, klass) + key = search._search_key(ORIGIN, klass) redis.set(f'{key}:lock', 1) monkeypatch.setattr(search, 'LOCK_WAIT', 0) monkeypatch.setattr(search.time, 'sleep', lambda s: None) with pytest.raises(search.HTTPServiceUnavailable): search.search_stop_times('fr-se', ORIGIN, DAY, '38185') assert fakes.call_count == 0 + + +def test_route_listing_of_a_search(client, session, access, fakes): + _, route, reverse = access + reset_search_index(session) + itv = f'{ORIGIN},2026-12-05' + # the search not computed yet: the listing does not call Navitia + client.get('/routes', params={'itv': itv}, status=400) + assert fakes.call_count == 0 + + params = { + 'origin': ORIGIN, + 'lon': GRENOBLE[0], + 'lat': GRENOBLE[1], + 'date': '2026-12-05', + } + client.get('/itinevert/reachable', params=params, status=200) + body = client.get('/routes', params={'itv': itv}, status=200).json + assert sorted(d['document_id'] for d in body['documents']) == sorted( + [route.document_id, reverse.document_id] + ) + assert body['total'] == 2 + # with the filters of the topoguide + body = client.get('/routes', params={'itv': itv, 'act': 'skitouring'}).json + assert body['total'] == 0 + client.get('/routes', params={'itv': 'stop_area:1'}, status=400) diff --git a/c2corg_api/views/document.py b/c2corg_api/views/document.py index d3c01603e..8e4a3686d 100644 --- a/c2corg_api/views/document.py +++ b/c2corg_api/views/document.py @@ -44,6 +44,7 @@ update_feed_document_update, ) from c2corg_api.models.outing import OUTING_TYPE +from c2corg_api.models.route import ROUTE_TYPE from c2corg_api.models.topo_map import MAP_TYPE from c2corg_api.models.topo_map_association import get_maps, update_maps_for_document from c2corg_api.schemas.area import area_listing_schema @@ -68,6 +69,9 @@ log = logging.getLogger(__name__) +# the routes reachable by public transport (see itinevert_search_documents) +ITINEVERT_PARAM = 'itv' + # the maximum number of documents that can be returned in a request (the map # of the waypoints asks for that many in its view) LIMIT_MAX = 500 @@ -644,7 +648,10 @@ def collection_get(request, doc_type, documents_config): # https://www.elastic.co/guide/en/elasticsearch/reference/master/search-request-from-size.html raise HTTPBadRequest('offset + limit greater than 10000') - if advanced_search.contains_search_params(request.GET): + if ITINEVERT_PARAM in request.GET and doc_type == ROUTE_TYPE: + # the routes reachable by public transport, of a search in cache + search_documents = itinevert_search_documents(request, meta_params) + elif advanced_search.contains_search_params(request.GET): # search with ElasticSearch search_documents = advanced_search.get_search_documents( request.GET, meta_params, doc_type @@ -656,6 +663,57 @@ def collection_get(request, doc_type, documents_config): return get_documents(documents_config, meta_params, search_documents) +def itinevert_search_documents(request, meta_params): + """Return a function searching the routes reachable by public transport. + + The routes of a search of /itinevert/reachable in cache (`itv`: + `origin,date[,insee]`), filtered and sorted with the other parameters: + the routes whose time on site covers their duration, then the routes of + an unknown duration (which cannot be checked). + """ + # imported here: the itinevert search imports the navitia views, which + # import the route views, which import this module + from datetime import date + + from c2corg_api.itinevert.search import cached_route_ids + + parts = request.GET[ITINEVERT_PARAM].split(',') + try: + origin, day = parts[0], date.fromisoformat(parts[1]) + insee = parts[2] if len(parts) > 2 else None + except IndexError, ValueError: + raise HTTPBadRequest('invalid itv: origin,date[,insee]') from None + params = {k: v for k, v in request.GET.items() if k != ITINEVERT_PARAM} + + def search_documents(_, __): + fitting, unknown = cached_route_ids(origin, day, insee) + return _two_groups_page(params, meta_params, fitting, unknown) + + return search_documents + + +def _two_groups_page(params, meta_params, first_ids, then_ids): + """Return a page of two groups of documents, filtered and sorted in ES. + + The documents of the second group come after all the ones of the first. + """ + offset, limit = meta_params['offset'], meta_params['limit'] + + def page(ids, page_offset, page_limit): + if not ids: + return [], 0 + return advanced_search.get_filtered_docs_page( + params, + {**meta_params, 'offset': page_offset, 'limit': page_limit}, + ids, + ROUTE_TYPE, + ) + + first, first_total = page(first_ids, offset, limit) + then, then_total = page(then_ids, max(0, offset - first_total), limit - len(first)) + return [*first, *then], first_total + then_total + + def search_documents_paginated(meta_params, doc_type, base_query, base_total_query): """Return a batch of document ids with the given `offset` and `limit`.""" # The total of a listing without search parameters only depends on the diff --git a/c2corg_api/views/itinevert.py b/c2corg_api/views/itinevert.py index 30a0cb4c8..440a36d0e 100644 --- a/c2corg_api/views/itinevert.py +++ b/c2corg_api/views/itinevert.py @@ -45,9 +45,8 @@ def read_hubs(request): if request.validated.get('date') and hubs: day = _date(request) klass = day_class(day, insee) - coverage = search.coverage_of(lon, lat) for hub in answer['hubs']: - hub['cached'] = search.cached_search(coverage, hub['id'], klass) + hub['cached'] = search.cached_search(hub['id'], klass) answer['day_class'] = klass.key return answer From 2b2ecfd69b6d39765710f5adcb25992af12da0fe Mon Sep 17 00:00:00 2001 From: Nayor <11463011+Nayor@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:39:26 +0100 Subject: [PATCH 04/10] fix(itinevert): explore the day in windows, from the hubs proposed only Checked on Navitia: its max_duration is a window from the time asked, the wait included (from 06:00 in 4 hours, no stop reached after 10:00; a return by 22:00 in 4 hours keeps the departures after 18:00 only). The day is explored in two windows of 5 hours, settings ITINEVERT_OUTBOUND_WINDOW (06:00-11:00) and ITINEVERT_RETURN_WINDOW (16:00-21:00): from Grenoble station, 21,000 stop points reached outbound and 30,000 for the return, in 7 and 12 s (a return window of 10 hours timed out at Navitia). The journeys start from the position of the hub rather than its stop area: Navitia repeats the stop area of the origin with all its lines in each journey (266 MB instead of 37 MB). A search starts from a hub proposed by /itinevert/hubs only, whose position and town are kept: /itinevert/reachable takes the hub and the date, and the listing parameter itv the hub and the date. --- c2corg_api/itinevert/search.py | 100 +++++++++++++---- c2corg_api/tests/contract/test_itinevert.py | 13 +-- c2corg_api/tests/itinevert/test_search.py | 112 ++++++++++++-------- c2corg_api/views/document.py | 7 +- c2corg_api/views/itinevert.py | 10 +- c2corg_api/web/itinevert.py | 15 +-- 6 files changed, 166 insertions(+), 91 deletions(-) diff --git a/c2corg_api/itinevert/search.py b/c2corg_api/itinevert/search.py index 7397a430d..61ecadc04 100644 --- a/c2corg_api/itinevert/search.py +++ b/c2corg_api/itinevert/search.py @@ -52,12 +52,13 @@ log = logging.getLogger(__name__) -# the whole day explored: the departures from the origin after -# EARLIEST_DEPARTURE, the arrivals back before LATEST_ARRIVAL, journeys of at -# most MAX_DURATION -EARLIEST_DEPARTURE = '060000' -LATEST_ARRIVAL = '220000' -MAX_DURATION = 4 * 3600 # seconds +# The day explored: the outbound leaves the hub in OUTBOUND_WINDOW, the +# return leaves the stops in RETURN_WINDOW (settings ITINEVERT_OUTBOUND_WINDOW +# and ITINEVERT_RETURN_WINDOW, `HH:MM-HH:MM`). Navitia's max_duration is a +# window from the time asked, the wait included: a wider window reaches more +# stops but weighs more (a return window of 10 hours timed out at Navitia). +OUTBOUND_WINDOW_DEFAULT = '06:00-11:00' +RETURN_WINDOW_DEFAULT = '16:00-21:00' SEARCH_CACHE_DAYS_DEFAULT = 90 HUBS_CACHE_DAYS_DEFAULT = 365 @@ -77,6 +78,30 @@ def _days_setting(name, default): return default +def _window(name, default): + """Return a window of a setting: (start HHMMSS, end HHMMSS, seconds).""" + for value in (os.getenv(name, default), default): + try: + start, end = ( + datetime.strptime(t.strip(), '%H:%M') # noqa: DTZ007 + for t in value.split('-') + ) + except ValueError: + continue + seconds = int((end - start).total_seconds()) + if seconds > 0: + return start.strftime('%H%M%S'), end.strftime('%H%M%S'), seconds + raise ValueError(default) + + +def windows(): + """Return the outbound and return windows.""" + return ( + _window('ITINEVERT_OUTBOUND_WINDOW', OUTBOUND_WINDOW_DEFAULT), + _window('ITINEVERT_RETURN_WINDOW', RETURN_WINDOW_DEFAULT), + ) + + def _api_key(): api_key = os.getenv('NAVITIA_API_KEY') if not api_key: @@ -194,37 +219,68 @@ def town_hubs(lon: float, lat: float, insee: str | None = None): _set_json( r, f'{_PREFIX}:hubs:{insee}', [vars(h) for h in selected], days * 86400 ) + # the hubs a search can start from: the ones proposed + for hub in selected: + _set_json( + r, + f'{_PREFIX}:hub:{hub.stop_area_id}', + {'lon': hub.lon, 'lat': hub.lat, 'insee': insee}, + days * 86400, + ) return insee, selected +def known_hub(origin: str) -> dict: + """Return a hub proposed by town_hubs: {lon, lat, insee}. + + A search starts from a hub proposed only: no search from anywhere, and + the cache of a hub is computed from its own position. + """ + hub = _get_json(redis_client(), f'{_PREFIX}:hub:{origin}') + if hub is None: + raise HTTPBadRequest('unknown_hub') + return hub + + def _search_key(origin, klass: DayClass): - # a Navitia stop area is in one coverage - return f'{_PREFIX}:search:{origin}:{klass.key}' + # a Navitia stop area is in one coverage; the windows explored are part of + # the search + (out_start, out_end, _), (back_start, back_end, _) = windows() + explored = f'{out_start[:4]}-{out_end[:4]}.{back_start[:4]}-{back_end[:4]}' + return f'{_PREFIX}:search:{origin}:{explored}:{klass.key}' def cached_search(origin, klass) -> bool: return bool(redis_client().exists(_search_key(origin, klass))) -def _fetch_stop_times(coverage, origin, day: date): - """Return the stop times of a day from an origin: two heavy calls.""" +def _fetch_stop_times(hub, day: date): + """Return the stop times of a day from a hub: two heavy calls. + + From the position of the hub rather than its stop area: Navitia repeats the + stop area of the origin, with all its lines, in each of the thousands of + journeys (ten times the weight). + """ + coverage = coverage_of(hub['lon'], hub['lat']) + position = f'{hub["lon"]};{hub["lat"]}' stamp = day.strftime('%Y%m%d') + (out_start, _, out_seconds), (_, back_end, back_seconds) = windows() outbound = _navitia_or_nothing( f'coverage/{coverage}/journeys', { - 'from': origin, - 'datetime': f'{stamp}T{EARLIEST_DEPARTURE}', + 'from': position, + 'datetime': f'{stamp}T{out_start}', 'datetime_represents': 'departure', - 'max_duration': MAX_DURATION, + 'max_duration': out_seconds, }, ) back = _navitia_or_nothing( f'coverage/{coverage}/journeys', { - 'to': origin, - 'datetime': f'{stamp}T{LATEST_ARRIVAL}', + 'to': position, + 'datetime': f'{stamp}T{back_end}', 'datetime_represents': 'arrival', - 'max_duration': MAX_DURATION, + 'max_duration': back_seconds, }, ) return { @@ -234,13 +290,14 @@ def _fetch_stop_times(coverage, origin, day: date): } -def search_stop_times(coverage: str, origin: str, day: date, insee: str | None): +def search_stop_times(origin: str, day: date): """Return the stop times of the class of days of a date, from the cache. The first search of a class computes it on its date; the requests asking for it meanwhile wait for it rather than calling Navitia again. """ - klass = day_class(day, insee) + hub = known_hub(origin) + klass = day_class(day, hub['insee']) r = redis_client() key = _search_key(origin, klass) lock = f'{key}:lock' @@ -255,7 +312,7 @@ def search_stop_times(coverage: str, origin: str, day: date, insee: str | None): raise HTTPServiceUnavailable('itinevert_search_busy') time.sleep(1) try: - value = _fetch_stop_times(coverage, origin, day) + value = _fetch_stop_times(hub, day) days = _days_setting('ITINEVERT_SEARCH_CACHE_DAYS', SEARCH_CACHE_DAYS_DEFAULT) _set_json(r, key, value, days * 86400) log.info( @@ -380,14 +437,15 @@ def reachable(stop_times_value): } -def cached_route_ids(origin: str, day: date, insee: str | None): +def cached_route_ids(origin: str, day: date): """Return the ids of the routes reachable, from a search in cache. (the ids of the routes whose time on site covers their duration, the ids of the routes of an unknown duration). The listings of the topoguide never call Navitia: the search is computed by /itinevert/reachable first. """ - cached = _get_json(redis_client(), _search_key(origin, day_class(day, insee))) + klass = day_class(day, known_hub(origin)['insee']) + cached = _get_json(redis_client(), _search_key(origin, klass)) if cached is None: raise HTTPBadRequest('itinevert_search_not_computed') fitting, unknown = [], [] diff --git a/c2corg_api/tests/contract/test_itinevert.py b/c2corg_api/tests/contract/test_itinevert.py index 626f5c9bc..7fd82a943 100644 --- a/c2corg_api/tests/contract/test_itinevert.py +++ b/c2corg_api/tests/contract/test_itinevert.py @@ -9,14 +9,12 @@ from c2corg_api.models.stoparea import Stoparea from c2corg_api.models.waypoint_stoparea import WaypointStoparea from c2corg_api.tests.contract import check_snapshot, contract -from c2corg_api.tests.contract.test_misc import navitia_coverage # noqa: F401 from c2corg_api.tests.itinevert.test_search import ORIGIN, FakeRedis, _navitia from c2corg_api.tests.views.test_reachable import POINT, add_route, add_waypoint HUBS = ('GET', '/itinevert/hubs') REACHABLE = ('GET', '/itinevert/reachable') -# in the coverage of the navitia_coverage fixture -POSITION = {'lon': 5.71, 'lat': 45.655} +POSITION = {'lon': 5.7146, 'lat': 45.1914} @pytest.fixture @@ -24,6 +22,7 @@ def fakes(): with ( mock.patch.object(search, 'redis_client', return_value=FakeRedis()), mock.patch.object(search, 'navitia_get', side_effect=_navitia) as navitia, + mock.patch.object(search, 'get_coverage', return_value='fr-se'), mock.patch.object(search, 'today_in_france', return_value=date(2026, 12, 2)), mock.patch('c2corg_api.web.itinevert.navitia_rate_limited', return_value=False), mock.patch.dict('os.environ', {'NAVITIA_API_KEY': 'contract-test-key'}), @@ -57,7 +56,7 @@ def reachable_route(session): session.flush() -@pytest.mark.usefixtures('navitia_coverage', 'fakes') +@pytest.mark.usefixtures('fakes') class TestItinevert: @contract(HUBS) def test_hubs(self, browser): @@ -77,18 +76,20 @@ def test_hubs_invalid(self, browser): @pytest.mark.usefixtures('reachable_route') @contract(REACHABLE) def test_reachable(self, browser): + browser.get('/itinevert/hubs', params=POSITION) response = browser.get( '/itinevert/reachable', - params={**POSITION, 'origin': ORIGIN, 'date': '2026-12-05'}, + params={'origin': ORIGIN, 'date': '2026-12-05'}, ) check_snapshot('itinevert_reachable', response) assert len(response.json['routes']) == 1 @contract(REACHABLE) def test_reachable_out_of_range(self, browser): + browser.get('/itinevert/hubs', params=POSITION) response = browser.get( '/itinevert/reachable', - params={**POSITION, 'origin': ORIGIN, 'date': '2027-06-01'}, + params={'origin': ORIGIN, 'date': '2027-06-01'}, status=400, ) check_snapshot('itinevert_invalid', response) diff --git a/c2corg_api/tests/itinevert/test_search.py b/c2corg_api/tests/itinevert/test_search.py index df91a694a..643f7e98f 100644 --- a/c2corg_api/tests/itinevert/test_search.py +++ b/c2corg_api/tests/itinevert/test_search.py @@ -146,15 +146,20 @@ def test_routes_of_waypoints_both_directions(access): assert routes[reverse.document_id][0] == [waypoint.document_id] +HUB_PARAMS = {'lon': GRENOBLE[0], 'lat': GRENOBLE[1]} +SEARCH = {'origin': ORIGIN, 'date': '2026-12-05'} + + +def _propose_hub(client): + # a search starts from a hub proposed by /itinevert/hubs + client.get('/itinevert/hubs', params=HUB_PARAMS, status=200) + + def test_reachable(client, access, fakes): waypoint, route, _ = access - params = { - 'origin': ORIGIN, - 'lon': GRENOBLE[0], - 'lat': GRENOBLE[1], - 'date': '2026-12-05', - } - body = client.get('/itinevert/reachable', params=params, status=200).json + _propose_hub(client) + calls = fakes.call_count + body = client.get('/itinevert/reachable', params=SEARCH, status=200).json assert body['day_class'] == '2026:winter:saturday' assert body['computed_on'] == '2026-12-05' # 08:27 + 8 minutes of walk, 17:55 - 8 minutes @@ -167,28 +172,45 @@ def test_reachable(client, access, fakes): assert found['time_on_site'] == 17 * 60 + 47 - (8 * 60 + 35) assert found['arrival_waypoint_id'] == waypoint.document_id # the coverage, the outbound and the return - assert fakes.call_count == 3 + assert fakes.call_count == calls + 3 + journeys = [c for c in fakes.call_args_list if c.args[0].endswith('/journeys')] + # from the position of the hub, in the windows of the day + position = f'{GRENOBLE[0]};{GRENOBLE[1]}' + assert journeys[0].kwargs['params'] == { + 'from': position, + 'datetime': '20261205T060000', + 'datetime_represents': 'departure', + 'max_duration': 5 * 3600, + } + assert journeys[1].kwargs['params'] == { + 'to': position, + 'datetime': '20261205T210000', + 'datetime_represents': 'arrival', + 'max_duration': 5 * 3600, + } # another Saturday of the class: from the cache - params['date'] = '2026-12-12' + params = {**SEARCH, 'date': '2026-12-12'} body = client.get('/itinevert/reachable', params=params, status=200).json assert body['computed_on'] == '2026-12-05' - assert fakes.call_count == 3 + assert fakes.call_count == calls + 3 def test_reachable_invalid(client, fakes): - params = {'origin': ORIGIN, 'lon': GRENOBLE[0], 'lat': GRENOBLE[1]} + # not a hub proposed + client.get('/itinevert/reachable', params=SEARCH, status=400) + _propose_hub(client) for invalid in ( - {'date': '2026-12-05', 'origin': 'admin:fr:38185'}, + {'origin': 'admin:fr:38185'}, + {'origin': 'stop_area:elsewhere'}, {'date': '2026-13-05'}, # past, after the end of the timetables {'date': '2026-12-01'}, {'date': '2027-03-03'}, - {'date': '2026-12-05', 'lon': 200}, ): - client.get('/itinevert/reachable', params={**params, **invalid}, status=400) + client.get('/itinevert/reachable', params={**SEARCH, **invalid}, status=400) # a required parameter missing - client.get('/itinevert/reachable', params=params, status=422) + client.get('/itinevert/reachable', params={'origin': ORIGIN}, status=422) # no search computed assert not [c for c in fakes.call_args_list if c.args[0].endswith('/journeys')] @@ -200,18 +222,13 @@ def nothing(url, params=None, headers=None): return _navitia(url, params, headers) fakes.side_effect = nothing - params = { - 'origin': ORIGIN, - 'lon': GRENOBLE[0], - 'lat': GRENOBLE[1], - 'date': '2026-12-05', - } - body = client.get('/itinevert/reachable', params=params, status=200).json + _propose_hub(client) + body = client.get('/itinevert/reachable', params=SEARCH, status=200).json assert body['routes'] == [] def test_hubs(client, fakes): - params = {'lon': GRENOBLE[0], 'lat': GRENOBLE[1], 'date': '2026-12-05'} + params = {**HUB_PARAMS, 'date': '2026-12-05'} body = client.get('/itinevert/hubs', params=params, status=200).json assert body['insee'] == '38185' assert [(h['id'], h['lines'], h['cached']) for h in body['hubs']] == [ @@ -224,46 +241,51 @@ def test_hubs(client, fakes): def test_hubs_cached_search(client, access, fakes): - search_params = { - 'origin': ORIGIN, - 'lon': GRENOBLE[0], - 'lat': GRENOBLE[1], - 'date': '2026-12-05', - 'insee': '38185', - } - client.get('/itinevert/reachable', params=search_params, status=200) - params = {'lon': GRENOBLE[0], 'lat': GRENOBLE[1], 'date': '2026-12-12'} + _propose_hub(client) + client.get('/itinevert/reachable', params=SEARCH, status=200) + params = {**HUB_PARAMS, 'date': '2026-12-12'} body = client.get('/itinevert/hubs', params=params, status=200).json assert body['hubs'][0]['cached'] is True -def test_search_waits_for_the_one_computing(fakes, monkeypatch): +def test_search_waits_for_the_one_computing(client, fakes, monkeypatch): + _propose_hub(client) + calls = fakes.call_count redis = search.redis_client() - klass = search.day_class(DAY, '38185') - key = search._search_key(ORIGIN, klass) + key = search._search_key(ORIGIN, search.day_class(DAY, '38185')) redis.set(f'{key}:lock', 1) monkeypatch.setattr(search, 'LOCK_WAIT', 0) monkeypatch.setattr(search.time, 'sleep', lambda s: None) with pytest.raises(search.HTTPServiceUnavailable): - search.search_stop_times('fr-se', ORIGIN, DAY, '38185') - assert fakes.call_count == 0 + search.search_stop_times(ORIGIN, DAY) + assert fakes.call_count == calls + + +def test_windows(monkeypatch): + assert search.windows() == ( + ('060000', '110000', 5 * 3600), + ('160000', '210000', 5 * 3600), + ) + monkeypatch.setenv('ITINEVERT_OUTBOUND_WINDOW', '05:30-12:00') + # an invalid setting: the default + monkeypatch.setenv('ITINEVERT_RETURN_WINDOW', '21:00-16:00') + assert search.windows() == ( + ('053000', '120000', 6 * 3600 + 1800), + ('160000', '210000', 5 * 3600), + ) def test_route_listing_of_a_search(client, session, access, fakes): _, route, reverse = access reset_search_index(session) itv = f'{ORIGIN},2026-12-05' + _propose_hub(client) + calls = fakes.call_count # the search not computed yet: the listing does not call Navitia client.get('/routes', params={'itv': itv}, status=400) - assert fakes.call_count == 0 + assert fakes.call_count == calls - params = { - 'origin': ORIGIN, - 'lon': GRENOBLE[0], - 'lat': GRENOBLE[1], - 'date': '2026-12-05', - } - client.get('/itinevert/reachable', params=params, status=200) + client.get('/itinevert/reachable', params=SEARCH, status=200) body = client.get('/routes', params={'itv': itv}, status=200).json assert sorted(d['document_id'] for d in body['documents']) == sorted( [route.document_id, reverse.document_id] diff --git a/c2corg_api/views/document.py b/c2corg_api/views/document.py index 8e4a3686d..c84ff2f97 100644 --- a/c2corg_api/views/document.py +++ b/c2corg_api/views/document.py @@ -667,7 +667,7 @@ def itinevert_search_documents(request, meta_params): """Return a function searching the routes reachable by public transport. The routes of a search of /itinevert/reachable in cache (`itv`: - `origin,date[,insee]`), filtered and sorted with the other parameters: + `origin,date`), filtered and sorted with the other parameters: the routes whose time on site covers their duration, then the routes of an unknown duration (which cannot be checked). """ @@ -680,13 +680,12 @@ def itinevert_search_documents(request, meta_params): parts = request.GET[ITINEVERT_PARAM].split(',') try: origin, day = parts[0], date.fromisoformat(parts[1]) - insee = parts[2] if len(parts) > 2 else None except IndexError, ValueError: - raise HTTPBadRequest('invalid itv: origin,date[,insee]') from None + raise HTTPBadRequest('invalid itv: origin,date') from None params = {k: v for k, v in request.GET.items() if k != ITINEVERT_PARAM} def search_documents(_, __): - fitting, unknown = cached_route_ids(origin, day, insee) + fitting, unknown = cached_route_ids(origin, day) return _two_groups_page(params, meta_params, fitting, unknown) return search_documents diff --git a/c2corg_api/views/itinevert.py b/c2corg_api/views/itinevert.py index 440a36d0e..36a2bc769 100644 --- a/c2corg_api/views/itinevert.py +++ b/c2corg_api/views/itinevert.py @@ -54,6 +54,8 @@ def read_hubs(request): def read_reachable(request): """Return the waypoints and routes reachable from a hub on a date. + The hub is one proposed by /itinevert/hubs. + The times are in minutes from the midnight of the date: the earliest arrival at and the latest departure from each access waypoint (the walk from the stop included), and per route the best access and its time on @@ -63,12 +65,12 @@ def read_reachable(request): origin = request.validated['origin'] if not STOP_AREA.match(origin): raise HTTPBadRequest('invalid_origin') - lon, lat = _position(request) - insee = _insee(request) day = _date(request) - coverage = search.coverage_of(lon, lat) + # a hub proposed by /itinevert/hubs only + hub = search.known_hub(origin) + coverage = search.coverage_of(hub['lon'], hub['lat']) search.check_date(day, coverage, search.today_in_france()) - klass, stop_times = search.search_stop_times(coverage, origin, day, insee) + klass, stop_times = search.search_stop_times(origin, day) return { 'origin': origin, 'date': day.isoformat(), diff --git a/c2corg_api/web/itinevert.py b/c2corg_api/web/itinevert.py index bd2e428d5..665f8d0d3 100644 --- a/c2corg_api/web/itinevert.py +++ b/c2corg_api/web/itinevert.py @@ -74,18 +74,11 @@ def hubs( def reachable( request: Request, user: User, - origin: Annotated[str, Query(description='The stop area of the hub.')], - lon: Lon, - lat: Lat, + origin: Annotated[ + str, Query(description='The stop area of a hub of /itinevert/hubs.') + ], date: Day, - insee: Insee = None, ): """Return the waypoints and routes reachable from a hub on a date.""" - validated = { - 'origin': origin, - 'lon': lon, - 'lat': lat, - 'date': date, - 'insee': insee, - } + validated = {'origin': origin, 'date': date} return serve_read(request, user, [typed_values(validated)], _read_reachable) From 7f7b5aca189b95fc7e46e818e9ebea5f2a9703c5 Mon Sep 17 00:00:00 2001 From: Nayor <11463011+Nayor@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:59:17 +0100 Subject: [PATCH 05/10] feat(itinevert): parse the Navitia journeys while reading them, bound the transfers The journeys requests without destination answer tens of megabytes: they are parsed journey by journey with ijson instead of being decoded at once. The journeys are limited to 3 transfers (ITINEVERT_MAX_TRANSFERS) and the default windows are narrower (06:00-10:00 outbound, 16:00-20:30 return), to bound the computation of Navitia and the weight of its answers. --- c2corg_api/itinevert/reachability.py | 10 ++-- c2corg_api/itinevert/search.py | 60 +++++++++++++++---- c2corg_api/tests/contract/test_itinevert.py | 8 ++- .../tests/itinevert/test_reachability.py | 5 +- c2corg_api/tests/itinevert/test_search.py | 55 +++++++++++++++-- c2corg_api/views/navitia.py | 29 +++++++++ pyproject.toml | 2 + uv.lock | 34 +++++++++++ 8 files changed, 180 insertions(+), 23 deletions(-) diff --git a/c2corg_api/itinevert/reachability.py b/c2corg_api/itinevert/reachability.py index 237c6ebf5..0838ef48d 100644 --- a/c2corg_api/itinevert/reachability.py +++ b/c2corg_api/itinevert/reachability.py @@ -13,6 +13,7 @@ """ import math +from collections.abc import Iterable from dataclasses import dataclass from datetime import date, datetime @@ -45,16 +46,17 @@ def minutes_from(day: date, navitia_datetime: str) -> int: return (moment.date() - day).days * 1440 + moment.hour * 60 + moment.minute -def stop_times(answer: dict, direction: str, day: date) -> list[StopTime]: - """Return the stop times of a Navitia `journeys` answer. +def stop_times(journeys: Iterable[dict], direction: str, day: date) -> list[StopTime]: + """Return the stop times of the journeys of a Navitia `journeys` answer. - Without destination (outbound) or without origin (return). + Without destination (outbound) or without origin (return); the journeys + may be read one by one, as the answer is parsed. A stop point appears once: the earliest arrival, the latest departure. """ outbound = direction == OUTBOUND best: dict[str, StopTime] = {} - for journey in answer.get('journeys', []): + for journey in journeys: place = journey['to'] if outbound else journey['from'] stop_point = place.get('stop_point') if not stop_point or 'coord' not in stop_point: diff --git a/c2corg_api/itinevert/search.py b/c2corg_api/itinevert/search.py index 61ecadc04..bc6569def 100644 --- a/c2corg_api/itinevert/search.py +++ b/c2corg_api/itinevert/search.py @@ -48,7 +48,12 @@ from c2corg_api.models.waypoint import Waypoint from c2corg_api.models.waypoint_stoparea import WaypointStoparea from c2corg_api.views.coverage import get_coverage -from c2corg_api.views.navitia import BASE_URL, navitia_get, redis_client +from c2corg_api.views.navitia import ( + BASE_URL, + navitia_get, + navitia_get_items, + redis_client, +) log = logging.getLogger(__name__) @@ -56,9 +61,13 @@ # return leaves the stops in RETURN_WINDOW (settings ITINEVERT_OUTBOUND_WINDOW # and ITINEVERT_RETURN_WINDOW, `HH:MM-HH:MM`). Navitia's max_duration is a # window from the time asked, the wait included: a wider window reaches more -# stops but weighs more (a return window of 10 hours timed out at Navitia). -OUTBOUND_WINDOW_DEFAULT = '06:00-11:00' -RETURN_WINDOW_DEFAULT = '16:00-21:00' +# stops but weighs more (a return window of 10 hours timed out at Navitia, 5 +# hours answered 48 and 68 MB from Grenoble). +OUTBOUND_WINDOW_DEFAULT = '06:00-10:00' +RETURN_WINDOW_DEFAULT = '16:00-20:30' +# The transfers of a journey (setting ITINEVERT_MAX_TRANSFERS): fewer bound +# the computation of Navitia and the stops reached. Navitia's default is 10. +MAX_TRANSFERS_DEFAULT = 3 SEARCH_CACHE_DAYS_DEFAULT = 90 HUBS_CACHE_DAYS_DEFAULT = 365 @@ -94,6 +103,13 @@ def _window(name, default): raise ValueError(default) +def max_transfers(): + try: + return max(int(os.getenv('ITINEVERT_MAX_TRANSFERS', MAX_TRANSFERS_DEFAULT)), 0) + except ValueError: + return MAX_TRANSFERS_DEFAULT + + def windows(): """Return the outbound and return windows.""" return ( @@ -115,6 +131,23 @@ def _navitia(path, params): ) +def _journeys(path, params): + """Yield the journeys of a Navitia answer, none when nothing is found. + + Parsed while read: the answer of a journeys request without destination + weighs tens of megabytes. + """ + try: + yield from navitia_get_items( + f'{BASE_URL}/{path}', + 'journeys.item', + params=params, + headers={'Authorization': _api_key()}, + ) + except HTTPNotFound: + return + + def _navitia_or_nothing(path, params): """Call Navitia, an empty answer when nothing is found (no_solution...).""" try: @@ -243,10 +276,13 @@ def known_hub(origin: str) -> dict: def _search_key(origin, klass: DayClass): - # a Navitia stop area is in one coverage; the windows explored are part of - # the search + # a Navitia stop area is in one coverage; the windows and the transfers + # explored are part of the search (out_start, out_end, _), (back_start, back_end, _) = windows() - explored = f'{out_start[:4]}-{out_end[:4]}.{back_start[:4]}-{back_end[:4]}' + explored = ( + f'{out_start[:4]}-{out_end[:4]}.{back_start[:4]}-{back_end[:4]}' + f'.t{max_transfers()}' + ) return f'{_PREFIX}:search:{origin}:{explored}:{klass.key}' @@ -265,27 +301,31 @@ def _fetch_stop_times(hub, day: date): position = f'{hub["lon"]};{hub["lat"]}' stamp = day.strftime('%Y%m%d') (out_start, _, out_seconds), (_, back_end, back_seconds) = windows() - outbound = _navitia_or_nothing( + transfers = max_transfers() + outbound = _journeys( f'coverage/{coverage}/journeys', { 'from': position, 'datetime': f'{stamp}T{out_start}', 'datetime_represents': 'departure', 'max_duration': out_seconds, + 'max_nb_transfers': transfers, }, ) - back = _navitia_or_nothing( + outbound_times = compact(stop_times(outbound, OUTBOUND, day)) + back = _journeys( f'coverage/{coverage}/journeys', { 'to': position, 'datetime': f'{stamp}T{back_end}', 'datetime_represents': 'arrival', 'max_duration': back_seconds, + 'max_nb_transfers': transfers, }, ) return { 'date': day.isoformat(), - OUTBOUND: compact(stop_times(outbound, OUTBOUND, day)), + OUTBOUND: outbound_times, RETURN: compact(stop_times(back, RETURN, day)), } diff --git a/c2corg_api/tests/contract/test_itinevert.py b/c2corg_api/tests/contract/test_itinevert.py index 7fd82a943..5a7645c21 100644 --- a/c2corg_api/tests/contract/test_itinevert.py +++ b/c2corg_api/tests/contract/test_itinevert.py @@ -9,7 +9,12 @@ from c2corg_api.models.stoparea import Stoparea from c2corg_api.models.waypoint_stoparea import WaypointStoparea from c2corg_api.tests.contract import check_snapshot, contract -from c2corg_api.tests.itinevert.test_search import ORIGIN, FakeRedis, _navitia +from c2corg_api.tests.itinevert.test_search import ( + ORIGIN, + FakeRedis, + _navitia, + streamed, +) from c2corg_api.tests.views.test_reachable import POINT, add_route, add_waypoint HUBS = ('GET', '/itinevert/hubs') @@ -22,6 +27,7 @@ def fakes(): with ( mock.patch.object(search, 'redis_client', return_value=FakeRedis()), mock.patch.object(search, 'navitia_get', side_effect=_navitia) as navitia, + mock.patch.object(search, 'navitia_get_items', side_effect=streamed(navitia)), mock.patch.object(search, 'get_coverage', return_value='fr-se'), mock.patch.object(search, 'today_in_france', return_value=date(2026, 12, 2)), mock.patch('c2corg_api.web.itinevert.navitia_rate_limited', return_value=False), diff --git a/c2corg_api/tests/itinevert/test_reachability.py b/c2corg_api/tests/itinevert/test_reachability.py index 295409939..e1f0d2ed2 100644 --- a/c2corg_api/tests/itinevert/test_reachability.py +++ b/c2corg_api/tests/itinevert/test_reachability.py @@ -54,7 +54,8 @@ def test_stop_times_outbound_keeps_the_earliest_arrival(): }, ] } - times = {t.stop_point_id: t.minutes for t in stop_times(answer, OUTBOUND, DAY)} + journeys = iter(answer['journeys']) + times = {t.stop_point_id: t.minutes for t in stop_times(journeys, OUTBOUND, DAY)} assert times == {'sp:1': 507, 'sp:2': 497} @@ -65,7 +66,7 @@ def test_stop_times_return_keeps_the_latest_departure(): _journey('from', 'sp:1', *VILLARD, '20261205T163000'), ] } - (t,) = stop_times(answer, RETURN, DAY) + (t,) = stop_times(iter(answer['journeys']), RETURN, DAY) assert t.minutes == 17 * 60 + 55 diff --git a/c2corg_api/tests/itinevert/test_search.py b/c2corg_api/tests/itinevert/test_search.py index 643f7e98f..0ef877e6e 100644 --- a/c2corg_api/tests/itinevert/test_search.py +++ b/c2corg_api/tests/itinevert/test_search.py @@ -1,5 +1,7 @@ """The search with the database, Navitia and Redis replaced by fakes.""" +import io +import json from datetime import date from unittest import mock @@ -17,6 +19,7 @@ add_route, add_waypoint, ) +from c2corg_api.views import navitia as navitia_views DAY = date(2026, 12, 5) ORIGIN = 'stop_area:SNC:StopArea:OCE87747006' @@ -87,12 +90,23 @@ def _navitia(url, params=None, headers=None): raise AssertionError(url) +def streamed(navitia): + """Fake `navitia_get_items` from a fake of `navitia_get`, counting its calls.""" + + def items(url, prefix, params=None, headers=None): + assert prefix == 'journeys.item' + yield from navitia(url, params=params, headers=headers)['journeys'] + + return items + + @pytest.fixture def fakes(): redis = FakeRedis() with ( mock.patch.object(search, 'redis_client', return_value=redis), mock.patch.object(search, 'navitia_get', side_effect=_navitia) as navitia, + mock.patch.object(search, 'navitia_get_items', side_effect=streamed(navitia)), mock.patch.object(search, 'get_coverage', return_value='fr-se'), mock.patch.object(search, 'today_in_france', return_value=date(2026, 12, 2)), mock.patch('c2corg_api.web.itinevert.navitia_rate_limited', return_value=False), @@ -180,13 +194,15 @@ def test_reachable(client, access, fakes): 'from': position, 'datetime': '20261205T060000', 'datetime_represents': 'departure', - 'max_duration': 5 * 3600, + 'max_duration': 4 * 3600, + 'max_nb_transfers': 3, } assert journeys[1].kwargs['params'] == { 'to': position, - 'datetime': '20261205T210000', + 'datetime': '20261205T203000', 'datetime_represents': 'arrival', - 'max_duration': 5 * 3600, + 'max_duration': 4 * 3600 + 1800, + 'max_nb_transfers': 3, } # another Saturday of the class: from the cache @@ -263,18 +279,45 @@ def test_search_waits_for_the_one_computing(client, fakes, monkeypatch): def test_windows(monkeypatch): assert search.windows() == ( - ('060000', '110000', 5 * 3600), - ('160000', '210000', 5 * 3600), + ('060000', '100000', 4 * 3600), + ('160000', '203000', 4 * 3600 + 1800), ) monkeypatch.setenv('ITINEVERT_OUTBOUND_WINDOW', '05:30-12:00') # an invalid setting: the default monkeypatch.setenv('ITINEVERT_RETURN_WINDOW', '21:00-16:00') assert search.windows() == ( ('053000', '120000', 6 * 3600 + 1800), - ('160000', '210000', 5 * 3600), + ('160000', '203000', 4 * 3600 + 1800), ) +def test_max_transfers(monkeypatch): + assert search.max_transfers() == 3 + monkeypatch.setenv('ITINEVERT_MAX_TRANSFERS', '2') + assert search.max_transfers() == 2 + monkeypatch.setenv('ITINEVERT_MAX_TRANSFERS', 'many') + assert search.max_transfers() == 3 + + +def test_navitia_answer_parsed_while_read(monkeypatch): + body = json.dumps({'journeys': [{'id': 1}, {'id': 2}], 'links': []}).encode() + + class Response: + ok = True + raw = io.BytesIO(body) + + def __enter__(self): + return self + + def __exit__(self, *args): + return False + + monkeypatch.setattr(navitia_views.requests, 'get', lambda *a, **k: Response()) + monkeypatch.setattr(navitia_views, 'consume_navitia_budget', lambda: None) + items = navitia_views.navitia_get_items('url', 'journeys.item') + assert [item['id'] for item in items] == [1, 2] + + def test_route_listing_of_a_search(client, session, access, fakes): _, route, reverse = access reset_search_index(session) diff --git a/c2corg_api/views/navitia.py b/c2corg_api/views/navitia.py index f2c384021..cd9054ab4 100644 --- a/c2corg_api/views/navitia.py +++ b/c2corg_api/views/navitia.py @@ -8,6 +8,7 @@ from datetime import UTC, datetime, timedelta import anyio +import ijson import redis import requests from anyio import to_thread @@ -837,6 +838,34 @@ def navitia_get(url, *, params=None, headers=None, timeout=30): raise HTTPInternalServerError(str(e)) from e +def navitia_get_items(url, prefix, *, params=None, headers=None, timeout=30): + """Yield the items of an array of a Navitia answer, counted in the budget. + + The answer is parsed while it is read (`prefix` as ijson's, e.g. + 'journeys.item'): a journeys request without destination answers tens of + megabytes, which would take hundreds once decoded at once. + """ + consume_navitia_budget() + try: + with requests.get( + url, params=params, headers=headers, timeout=timeout, stream=True + ) as response: + if not response.ok: + handle_navitia_response(response) + # gzip, as requests asks for it + response.raw.decode_content = True + yield from ijson.items(response.raw, prefix, use_float=True) + + except HTTPException: + raise + + except requests.exceptions.Timeout as e: + raise HTTPInternalServerError('Timeout when calling the Navitia API') from e + + except (requests.exceptions.RequestException, ijson.JSONError) as e: + raise HTTPInternalServerError(str(e)) from e + + def configure_jobs_redis(settings): """Connect the jobs to the Redis of the settings (redis.url, redis.db_jobs).""" global _jobs_redis_pool, _budget_redis_pool diff --git a/pyproject.toml b/pyproject.toml index 7587328a2..2f6655e0c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -38,6 +38,8 @@ dependencies = [ "Shapely==2.2.0", "SQLAlchemy==2.1.4", "gunicorn==27.0.1", + # parses the big Navitia answers while reading them (Itinevert) + "ijson==3.6.0", # the ASGI server, run by gunicorn: -k uvicorn_worker.UvicornWorker "uvicorn==0.54.0", "uvicorn-worker==0.4.0", diff --git a/uv.lock b/uv.lock index 1eb793fb0..ee3397eef 100644 --- a/uv.lock +++ b/uv.lock @@ -151,6 +151,7 @@ dependencies = [ { name = "geojson" }, { name = "geomet" }, { name = "gunicorn" }, + { name = "ijson" }, { name = "kombu" }, { name = "markdown" }, { name = "nh3" }, @@ -199,6 +200,7 @@ requires-dist = [ { name = "geojson", specifier = "==3.3.0" }, { name = "geomet", specifier = "==1.1.0" }, { name = "gunicorn", specifier = "==27.0.1" }, + { name = "ijson", specifier = "==3.6.0" }, { name = "kombu", specifier = "==5.7.0" }, { name = "markdown", specifier = "==3.11.3" }, { name = "nh3", specifier = "==0.3.8" }, @@ -614,6 +616,38 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c", size = 69583, upload-time = "2026-09-17T14:11:03.168Z" }, ] +[[package]] +name = "ijson" +version = "3.6.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/75/61/4066af787ed25bfca02c3edd2d7fd489b1b5ca27b54b400b187e5f2865e7/ijson-3.6.0.tar.gz", hash = "sha256:ec8f9265524e724905ecf00bdd061c374baaa8d5045ef50425695fb06efb45f5", size = 70134, upload-time = "2026-10-12T20:40:00.165Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f2/64/96853dd6376e0def284a774de1dbd05dd1455fee3a3d648ea0dbb8086670/ijson-3.6.0-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:e58bc4b0470497e5d00f0faa055d0b8aef275ed210266d5f86ed17a23d064408", size = 89323, upload-time = "2026-10-12T20:39:27.618Z" }, + { url = "https://files.pythonhosted.org/packages/d9/f4/0fd4129c76d1493cd9ce6ba95c2bb697f4416164de25bdad2fe0ee2a3951/ijson-3.6.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:2e6b9c56a8a727153935c83d91450d1eae8f2a9ad4091360eb6ec03d47aa08e6", size = 60888, upload-time = "2026-10-12T20:39:28.536Z" }, + { url = "https://files.pythonhosted.org/packages/00/a8/a4db191ab78cacb6da8c66d9183e023b10a33ccc5bbb2a78f7508b9a23a7/ijson-3.6.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:d847615380321e4dfb3d269deb562876f170ab9f46c80cbf880a2496fb09a0e3", size = 60861, upload-time = "2026-10-12T20:39:29.476Z" }, + { url = "https://files.pythonhosted.org/packages/66/78/015f30c10f73064efa4cbbacaa2e581d7d3c161e2de7bcea5aaeab570261/ijson-3.6.0-cp315-cp315-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:e60c40f78fa00325df96d57f68786f1fed3e6091b9d41cf9811d22914dff8f94", size = 143887, upload-time = "2026-10-12T20:39:30.414Z" }, + { url = "https://files.pythonhosted.org/packages/11/a4/865672b6bff38a6b1b3f50ce4c5244ce84a5a3457652f33154a36d361540/ijson-3.6.0-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7b48f4ce1fbb89045e7b92defe75c848275f84734cef8ab01cfa3ee443d8a4bc", size = 152135, upload-time = "2026-10-12T20:39:31.476Z" }, + { url = "https://files.pythonhosted.org/packages/6c/20/fac4d452eef9a4400f4561e37fb84d3c3d757d11bb63e3be4595697b49c5/ijson-3.6.0-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5454696282add7cde430fc6dc90d0d65db2f1585303b8ec701e1c36aee14fc4c", size = 150585, upload-time = "2026-10-12T20:39:32.707Z" }, + { url = "https://files.pythonhosted.org/packages/e0/f2/29e356b9f034127f09e01c4d460677f8e1837ae37a24fdb734f52136fa68/ijson-3.6.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:4b5addfd509ca4192ec7107a3f07d0295221e62b974d8abfa8cc9b67c10dc9e2", size = 152496, upload-time = "2026-10-12T20:39:33.739Z" }, + { url = "https://files.pythonhosted.org/packages/39/7d/4115b88dc29922f8e41f51eb112a116298ba39c6b2bc9b5c7e8798ba724e/ijson-3.6.0-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:160c94c9cac5837f49e5b9cbb725604e75694083260c7180ef381f705850992a", size = 146659, upload-time = "2026-10-12T20:39:35.194Z" }, + { url = "https://files.pythonhosted.org/packages/6f/30/ccd58a0c5d56d602ec59a2701939a3416edc2c837c5866adbb45bd7e3a1d/ijson-3.6.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:7c1deb116218a900fe6f231544c31e8e2dd625819ff7ce5ce908aa19622fa1c9", size = 152532, upload-time = "2026-10-12T20:39:36.236Z" }, + { url = "https://files.pythonhosted.org/packages/f0/f6/adb1149fc1c2a834dae3612abe9d1c3250597ef7525eca6cc0d9669093fb/ijson-3.6.0-cp315-cp315-win32.whl", hash = "sha256:20d227e46ff03ad2f40cb5bfa56adcc47b6713f7b81c67b9767f761ceded90bb", size = 53270, upload-time = "2026-10-12T20:39:37.225Z" }, + { url = "https://files.pythonhosted.org/packages/0b/c0/abf3695b0e300a4d9b45aafa352a5ffbd2b776ad754530dcb99faf0c5662/ijson-3.6.0-cp315-cp315-win_amd64.whl", hash = "sha256:e18f1486106c072c037a8699c9ff1450574c395f45687cdf5b4142d9c2d2df61", size = 55578, upload-time = "2026-10-12T20:39:38.945Z" }, + { url = "https://files.pythonhosted.org/packages/e6/c4/c2bb635321379aaa6d9b9f56d226e633c0dec70c2b24bb411648e7c59dd8/ijson-3.6.0-cp315-cp315-win_arm64.whl", hash = "sha256:4bc6c5351352760fd0c29cc437e48598b92f66133f2be5ef712f75180e1759a7", size = 54745, upload-time = "2026-10-12T20:39:39.892Z" }, + { url = "https://files.pythonhosted.org/packages/1c/d4/414294b4c3acbbd182737c78a053df6702f9fdbc7ee45dc4125e0f07896f/ijson-3.6.0-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:96863aca6697edc2c5465e1dd2d7ea7b67b7743b9657adb1e65c04aab9c6c2ab", size = 93316, upload-time = "2026-10-12T20:39:41.405Z" }, + { url = "https://files.pythonhosted.org/packages/dc/f0/829812e27f46a357c4894b9a1d3adf53c18d186d344d32a5a11a2749fd5b/ijson-3.6.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:5a7e4220d788bfa155fc2885edf04d8beada42eeaa260a02fe749d056dc6ffb9", size = 62932, upload-time = "2026-10-12T20:39:42.52Z" }, + { url = "https://files.pythonhosted.org/packages/61/98/6f4b83aacd1037a0d95dea7511cdb40260ea8c45a06c13a62470f5981931/ijson-3.6.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:ee99f497c4fd997bc6be85dfc72635ad69f08e8a727937193dd449c6b7f9348c", size = 62724, upload-time = "2026-10-12T20:39:43.648Z" }, + { url = "https://files.pythonhosted.org/packages/d6/b2/56de3c977f476d57b58373c08dea5361ba4e959bc18092d68bb1edce784a/ijson-3.6.0-cp315-cp315t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:21a7cd561d97f20a7011760d7b0687cafbd86b1f67738badb7809ce7e2385261", size = 200710, upload-time = "2026-10-12T20:39:44.598Z" }, + { url = "https://files.pythonhosted.org/packages/12/2d/4a00b8475c2f41e1172b3939adb8d6cc0eecffdf63a810987230fadcc8c5/ijson-3.6.0-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7dfd28144223c9ee6e0544b903efd334214cb2048c6e22f9cb9c11fdf1ae86d9", size = 218004, upload-time = "2026-10-12T20:39:45.624Z" }, + { url = "https://files.pythonhosted.org/packages/51/7f/403edf91b6d5e4bba077243cb0290e1b751e1104fd8c9d79e59b21dfa251/ijson-3.6.0-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:539b2d8b9427b322ccc15db0e7bda8cd7597be62bd07b969df3e482e67c11fb7", size = 208754, upload-time = "2026-10-12T20:39:46.75Z" }, + { url = "https://files.pythonhosted.org/packages/73/a4/f56e9d5e4d6b4b7eaa4723f852900a865019a2155d65e432298487a2657e/ijson-3.6.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:503c938e6ae6686e0c702b3ae33e37433450ca41c0d022746e7bef3173ea9778", size = 213535, upload-time = "2026-10-12T20:39:47.787Z" }, + { url = "https://files.pythonhosted.org/packages/9f/e3/dd6858b224b041a1e5164aee70c515c793fcec4c0b6316a5356d83d9a3af/ijson-3.6.0-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:2b0f27fc60291fb1aa73de1a4588476efb49f8a4977c20c679aa15480e3f63a8", size = 201185, upload-time = "2026-10-12T20:39:49.232Z" }, + { url = "https://files.pythonhosted.org/packages/d0/c1/891e782e3b72a9a54150da7c40d71a3fe69a3c38e7506fa0f7e179780f82/ijson-3.6.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:130bbccf2569ca8fc69dd1496dc8f55231408cad56ccfdd9d4ab17593a65cc95", size = 206095, upload-time = "2026-10-12T20:39:50.284Z" }, + { url = "https://files.pythonhosted.org/packages/48/3e/3bebd41958495d2365cef21f0f7727b82647d736dea05e01fe87bf0b3a0b/ijson-3.6.0-cp315-cp315t-win32.whl", hash = "sha256:600912be7871678688c7890c254d44421079781991badf84792073b43d05890b", size = 54474, upload-time = "2026-10-12T20:39:51.358Z" }, + { url = "https://files.pythonhosted.org/packages/f6/4b/29f22cbe8e9cdeaf632ec2cb551237f432f0df8689c6ae3d282f4c3a1065/ijson-3.6.0-cp315-cp315t-win_amd64.whl", hash = "sha256:9846fd8da153a478f797ac417b07ce47c0f73acd7798038ba16a45d417cb50c9", size = 56585, upload-time = "2026-10-12T20:39:52.247Z" }, + { url = "https://files.pythonhosted.org/packages/3f/aa/dc4c4d1b7ec85a2a5c1e97f73aa23742b68345a7fed4a423b7ef4bffcaeb/ijson-3.6.0-cp315-cp315t-win_arm64.whl", hash = "sha256:f994df777d7e9c4ac72a54ed382c9abef4804d705d8904acc19ed141a3604b3c", size = 56128, upload-time = "2026-10-12T20:39:53.186Z" }, +] + [[package]] name = "iniconfig" version = "2.1.0" From 147dbb3127e1acc2f55272d180943b26dad0eaa8 Mon Sep 17 00:00:00 2001 From: Nayor <11463011+Nayor@users.noreply.github.com> Date: Wed, 2 Dec 2026 23:06:53 +0100 Subject: [PATCH 06/10] feat(itinevert): give the name of the hub of a search The interface shows it from a link or after a reload, without the hubs of the town. --- c2corg_api/itinevert/search.py | 4 ++-- c2corg_api/tests/contract/snapshots/itinevert_reachable.json | 1 + c2corg_api/tests/itinevert/test_search.py | 1 + c2corg_api/views/itinevert.py | 2 ++ 4 files changed, 6 insertions(+), 2 deletions(-) diff --git a/c2corg_api/itinevert/search.py b/c2corg_api/itinevert/search.py index bc6569def..b003e051b 100644 --- a/c2corg_api/itinevert/search.py +++ b/c2corg_api/itinevert/search.py @@ -257,14 +257,14 @@ def town_hubs(lon: float, lat: float, insee: str | None = None): _set_json( r, f'{_PREFIX}:hub:{hub.stop_area_id}', - {'lon': hub.lon, 'lat': hub.lat, 'insee': insee}, + {'lon': hub.lon, 'lat': hub.lat, 'insee': insee, 'name': hub.name}, days * 86400, ) return insee, selected def known_hub(origin: str) -> dict: - """Return a hub proposed by town_hubs: {lon, lat, insee}. + """Return a hub proposed by town_hubs: {lon, lat, insee, name}. A search starts from a hub proposed only: no search from anywhere, and the cache of a hub is computed from its own position. diff --git a/c2corg_api/tests/contract/snapshots/itinevert_reachable.json b/c2corg_api/tests/contract/snapshots/itinevert_reachable.json index a572c89eb..4cedab43e 100644 --- a/c2corg_api/tests/contract/snapshots/itinevert_reachable.json +++ b/c2corg_api/tests/contract/snapshots/itinevert_reachable.json @@ -4,6 +4,7 @@ "date": "str", "day_class": "str", "origin": "str", + "origin_name": "str", "routes": [ { "arrival": "int", diff --git a/c2corg_api/tests/itinevert/test_search.py b/c2corg_api/tests/itinevert/test_search.py index 0ef877e6e..5adc8bbb1 100644 --- a/c2corg_api/tests/itinevert/test_search.py +++ b/c2corg_api/tests/itinevert/test_search.py @@ -174,6 +174,7 @@ def test_reachable(client, access, fakes): _propose_hub(client) calls = fakes.call_count body = client.get('/itinevert/reachable', params=SEARCH, status=200).json + assert body['origin_name'] == 'Grenoble' assert body['day_class'] == '2026:winter:saturday' assert body['computed_on'] == '2026-12-05' # 08:27 + 8 minutes of walk, 17:55 - 8 minutes diff --git a/c2corg_api/views/itinevert.py b/c2corg_api/views/itinevert.py index 36a2bc769..340e90daa 100644 --- a/c2corg_api/views/itinevert.py +++ b/c2corg_api/views/itinevert.py @@ -73,6 +73,8 @@ def read_reachable(request): klass, stop_times = search.search_stop_times(origin, day) return { 'origin': origin, + # registered before the name was: none until proposed again + 'origin_name': hub.get('name'), 'date': day.isoformat(), 'day_class': klass.key, # the date the class was computed on From 873a893f95d2706ae2721a4115d4bf713d9651bf Mon Sep 17 00:00:00 2001 From: Nayor <11463011+Nayor@users.noreply.github.com> Date: Thu, 3 Dec 2026 08:08:44 +0100 Subject: [PATCH 07/10] feat(itinevert): keep the return window of 5 hours Navitia gives every journey of the return the requested time as arrival, so the stops a narrower return window would lose cannot be measured. --- c2corg_api/itinevert/search.py | 6 ++++-- c2corg_api/tests/itinevert/test_search.py | 8 ++++---- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/c2corg_api/itinevert/search.py b/c2corg_api/itinevert/search.py index b003e051b..277c40319 100644 --- a/c2corg_api/itinevert/search.py +++ b/c2corg_api/itinevert/search.py @@ -62,9 +62,11 @@ # and ITINEVERT_RETURN_WINDOW, `HH:MM-HH:MM`). Navitia's max_duration is a # window from the time asked, the wait included: a wider window reaches more # stops but weighs more (a return window of 10 hours timed out at Navitia, 5 -# hours answered 48 and 68 MB from Grenoble). +# hours answered 48 and 68 MB from Grenoble). Navitia gives every journey of +# the return the time asked as arrival: the stops a narrower return loses +# cannot be measured, the return keeps 5 hours. OUTBOUND_WINDOW_DEFAULT = '06:00-10:00' -RETURN_WINDOW_DEFAULT = '16:00-20:30' +RETURN_WINDOW_DEFAULT = '16:00-21:00' # The transfers of a journey (setting ITINEVERT_MAX_TRANSFERS): fewer bound # the computation of Navitia and the stops reached. Navitia's default is 10. MAX_TRANSFERS_DEFAULT = 3 diff --git a/c2corg_api/tests/itinevert/test_search.py b/c2corg_api/tests/itinevert/test_search.py index 5adc8bbb1..9daf36287 100644 --- a/c2corg_api/tests/itinevert/test_search.py +++ b/c2corg_api/tests/itinevert/test_search.py @@ -200,9 +200,9 @@ def test_reachable(client, access, fakes): } assert journeys[1].kwargs['params'] == { 'to': position, - 'datetime': '20261205T203000', + 'datetime': '20261205T210000', 'datetime_represents': 'arrival', - 'max_duration': 4 * 3600 + 1800, + 'max_duration': 5 * 3600, 'max_nb_transfers': 3, } @@ -281,14 +281,14 @@ def test_search_waits_for_the_one_computing(client, fakes, monkeypatch): def test_windows(monkeypatch): assert search.windows() == ( ('060000', '100000', 4 * 3600), - ('160000', '203000', 4 * 3600 + 1800), + ('160000', '210000', 5 * 3600), ) monkeypatch.setenv('ITINEVERT_OUTBOUND_WINDOW', '05:30-12:00') # an invalid setting: the default monkeypatch.setenv('ITINEVERT_RETURN_WINDOW', '21:00-16:00') assert search.windows() == ( ('053000', '120000', 6 * 3600 + 1800), - ('160000', '203000', 4 * 3600 + 1800), + ('160000', '210000', 5 * 3600), ) From 592919831ef01790720b0b70ece7206e98e6a445 Mon Sep 17 00:00:00 2001 From: Nayor <11463011+Nayor@users.noreply.github.com> Date: Thu, 3 Dec 2026 08:17:13 +0100 Subject: [PATCH 08/10] feat(itinevert): keep the outbound window until 11:00 Until 10:00 only, the search would lose the valleys whose morning coach arrives after 10:00. --- c2corg_api/itinevert/search.py | 8 +++++--- c2corg_api/tests/itinevert/test_search.py | 4 ++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/c2corg_api/itinevert/search.py b/c2corg_api/itinevert/search.py index 277c40319..b2eda71d1 100644 --- a/c2corg_api/itinevert/search.py +++ b/c2corg_api/itinevert/search.py @@ -64,11 +64,13 @@ # stops but weighs more (a return window of 10 hours timed out at Navitia, 5 # hours answered 48 and 68 MB from Grenoble). Navitia gives every journey of # the return the time asked as arrival: the stops a narrower return loses -# cannot be measured, the return keeps 5 hours. -OUTBOUND_WINDOW_DEFAULT = '06:00-10:00' +# cannot be measured, the return keeps 5 hours. An outbound until 10:00 only +# would lose the valleys whose morning coach arrives after 10:00. +OUTBOUND_WINDOW_DEFAULT = '06:00-11:00' RETURN_WINDOW_DEFAULT = '16:00-21:00' # The transfers of a journey (setting ITINEVERT_MAX_TRANSFERS): fewer bound -# the computation of Navitia and the stops reached. Navitia's default is 10. +# the computation of Navitia and the stops reached (3 kept the 40 routes of a +# sample around Grenoble). Navitia's default is 10. MAX_TRANSFERS_DEFAULT = 3 SEARCH_CACHE_DAYS_DEFAULT = 90 diff --git a/c2corg_api/tests/itinevert/test_search.py b/c2corg_api/tests/itinevert/test_search.py index 9daf36287..218aa0fa1 100644 --- a/c2corg_api/tests/itinevert/test_search.py +++ b/c2corg_api/tests/itinevert/test_search.py @@ -195,7 +195,7 @@ def test_reachable(client, access, fakes): 'from': position, 'datetime': '20261205T060000', 'datetime_represents': 'departure', - 'max_duration': 4 * 3600, + 'max_duration': 5 * 3600, 'max_nb_transfers': 3, } assert journeys[1].kwargs['params'] == { @@ -280,7 +280,7 @@ def test_search_waits_for_the_one_computing(client, fakes, monkeypatch): def test_windows(monkeypatch): assert search.windows() == ( - ('060000', '100000', 4 * 3600), + ('060000', '110000', 5 * 3600), ('160000', '210000', 5 * 3600), ) monkeypatch.setenv('ITINEVERT_OUTBOUND_WINDOW', '05:30-12:00') From 883440e7995b24ae5b83c869ac4e7b48c497e120 Mon Sep 17 00:00:00 2001 From: Nayor <11463011+Nayor@users.noreply.github.com> Date: Thu, 3 Dec 2026 13:09:52 +0100 Subject: [PATCH 09/10] feat(itinevert): give the position and town of the hub of a search The interface proposes the search again (hubs of the town, from the cache) from a link or a reload. --- c2corg_api/tests/contract/snapshots/itinevert_reachable.json | 3 +++ c2corg_api/tests/itinevert/test_search.py | 2 ++ c2corg_api/views/itinevert.py | 5 +++++ 3 files changed, 10 insertions(+) diff --git a/c2corg_api/tests/contract/snapshots/itinevert_reachable.json b/c2corg_api/tests/contract/snapshots/itinevert_reachable.json index 4cedab43e..ba287091b 100644 --- a/c2corg_api/tests/contract/snapshots/itinevert_reachable.json +++ b/c2corg_api/tests/contract/snapshots/itinevert_reachable.json @@ -4,6 +4,9 @@ "date": "str", "day_class": "str", "origin": "str", + "origin_insee": "str", + "origin_lat": "float", + "origin_lon": "float", "origin_name": "str", "routes": [ { diff --git a/c2corg_api/tests/itinevert/test_search.py b/c2corg_api/tests/itinevert/test_search.py index 218aa0fa1..5854d91c0 100644 --- a/c2corg_api/tests/itinevert/test_search.py +++ b/c2corg_api/tests/itinevert/test_search.py @@ -175,6 +175,8 @@ def test_reachable(client, access, fakes): calls = fakes.call_count body = client.get('/itinevert/reachable', params=SEARCH, status=200).json assert body['origin_name'] == 'Grenoble' + assert (body['origin_lon'], body['origin_lat']) == GRENOBLE + assert body['origin_insee'] == '38185' assert body['day_class'] == '2026:winter:saturday' assert body['computed_on'] == '2026-12-05' # 08:27 + 8 minutes of walk, 17:55 - 8 minutes diff --git a/c2corg_api/views/itinevert.py b/c2corg_api/views/itinevert.py index 340e90daa..135eaa0b8 100644 --- a/c2corg_api/views/itinevert.py +++ b/c2corg_api/views/itinevert.py @@ -75,6 +75,11 @@ def read_reachable(request): 'origin': origin, # registered before the name was: none until proposed again 'origin_name': hub.get('name'), + # where the hub is and its town, to propose its search again from the + # cache of the hubs of the town + 'origin_lon': hub['lon'], + 'origin_lat': hub['lat'], + 'origin_insee': hub['insee'], 'date': day.isoformat(), 'day_class': klass.key, # the date the class was computed on From c0d9a7e99e25c96e9184e0c4611db492fd8eb576 Mon Sep 17 00:00:00 2001 From: Nayor <11463011+Nayor@users.noreply.github.com> Date: Thu, 3 Dec 2026 13:16:51 +0100 Subject: [PATCH 10/10] feat(itinevert): check the access of a route with the real timetables of the date Two light journeys requests (outbound and return) between the hub and the stop areas of the access waypoints, cached an hour. --- c2corg_api/itinevert/search.py | 114 ++++++++++++++ c2corg_api/tests/contract/routes.txt | 1 + .../contract/snapshots/itinevert_check.json | 27 ++++ c2corg_api/tests/contract/test_itinevert.py | 16 ++ c2corg_api/tests/itinevert/test_search.py | 145 ++++++++++++++++++ c2corg_api/views/itinevert.py | 17 ++ c2corg_api/web/itinevert.py | 30 +++- 7 files changed, 349 insertions(+), 1 deletion(-) create mode 100644 c2corg_api/tests/contract/snapshots/itinevert_check.json diff --git a/c2corg_api/itinevert/search.py b/c2corg_api/itinevert/search.py index b2eda71d1..aa4f19379 100644 --- a/c2corg_api/itinevert/search.py +++ b/c2corg_api/itinevert/search.py @@ -8,6 +8,9 @@ ITINEVERT_SEARCH_CACHE_DAYS (the data of Navitia is reloaded every day, but the timetables of a class of days rarely change; the check of a chosen route with a `journeys` request uses the current data); +- the check of the access of a route, with the real timetables of the date + (two light `journeys` requests between the hub and the stop areas of the + access waypoints): CHECK_CACHE seconds; - the validity period of the data of a coverage: a day. """ @@ -36,9 +39,11 @@ StopTimeIndex, compact, distance, + minutes_from, route_access, stop_times, uncompact, + walking_minutes, waypoint_access, ) from c2corg_api.models import DBSession @@ -76,6 +81,7 @@ SEARCH_CACHE_DAYS_DEFAULT = 90 HUBS_CACHE_DAYS_DEFAULT = 365 COVERAGE_CACHE = 86400 # seconds +CHECK_CACHE = 3600 # seconds # a search being computed by another request: wait for it LOCK_TTL = 120 # seconds LOCK_WAIT = 60 # seconds @@ -390,6 +396,114 @@ def stop_area_links(): return [StopAreaLink(w, lon, lat, d) for w, lon, lat, d in rows] +def _closest_stop_area(waypoint_id: int): + """Return the Navitia id and the distance (km) of the closest stop area.""" + row = ( + DBSession.query(Stoparea.navitia_id, WaypointStoparea.distance) + .join(Stoparea, Stoparea.stoparea_id == WaypointStoparea.stoparea_id) + .join(Waypoint, Waypoint.document_id == WaypointStoparea.waypoint_id) + .filter( + WaypointStoparea.waypoint_id == waypoint_id, + Waypoint.waypoint_type == 'access', + Stoparea.navitia_id.isnot(None), + ) + .order_by(WaypointStoparea.distance, Stoparea.stoparea_id) + .first() + ) + if row is None: + raise HTTPBadRequest('no_stop_area') + return row[0], row[1] or 0 + + +def _journey_times(day: date, journey: dict): + return { + 'departure': minutes_from(day, journey['departure_date_time']), + 'arrival': minutes_from(day, journey['arrival_date_time']), + 'transfers': journey.get('nb_transfers', 0), + } + + +def check_access(origin, day: date, waypoint_id: int, return_waypoint_id: int): + """Return the real arrival and departure at the access of a route. + + Two light `journeys` requests with the timetables of the date, between + the hub and the closest stop area of the waypoints: the earliest arrival + of the outbound, the latest departure of the return (None when Navitia + finds nothing). The times are in minutes from the midnight of the date, + the walk from the stop included. Cached an hour. + """ + hub = known_hub(origin) + coverage = coverage_of(hub['lon'], hub['lat']) + check_date(day, coverage, today_in_france()) + out_area, out_km = _closest_stop_area(waypoint_id) + back_area, back_km = _closest_stop_area(return_waypoint_id) + + (out_start, out_end, out_seconds), (back_start, back_end, back_seconds) = windows() + transfers = max_transfers() + r = redis_client() + key = ( + f'{_PREFIX}:check:{origin}:{day.isoformat()}:{waypoint_id}:' + f'{return_waypoint_id}:{out_start[:4]}-{out_end[:4]}.' + f'{back_start[:4]}-{back_end[:4]}.t{transfers}' + ) + cached = _get_json(r, key) + if cached is not None: + return cached + + position = f'{hub["lon"]};{hub["lat"]}' + stamp = day.strftime('%Y%m%d') + path = f'coverage/{coverage}/journeys' + outbound = _navitia_or_nothing( + path, + { + 'from': position, + 'to': out_area, + 'datetime': f'{stamp}T{out_start}', + 'datetime_represents': 'departure', + 'max_duration': out_seconds, + 'max_nb_transfers': transfers, + }, + ).get('journeys', []) + back = _navitia_or_nothing( + path, + { + 'from': back_area, + 'to': position, + 'datetime': f'{stamp}T{back_end}', + 'datetime_represents': 'arrival', + 'max_duration': back_seconds, + 'max_nb_transfers': transfers, + }, + ).get('journeys', []) + + out_journey = min(outbound, key=lambda j: j['arrival_date_time'], default=None) + back_journey = max(back, key=lambda j: j['departure_date_time'], default=None) + out_times = _journey_times(day, out_journey) if out_journey else None + back_times = _journey_times(day, back_journey) if back_journey else None + arrival = out_times['arrival'] + walking_minutes(out_km) if out_times else None + departure = ( + back_times['departure'] - walking_minutes(back_km) if back_times else None + ) + time_on_site = ( + departure - arrival + if arrival is not None and departure is not None and departure > arrival + else None + ) + value = { + 'origin': origin, + 'date': day.isoformat(), + 'waypoint': waypoint_id, + 'return_waypoint': return_waypoint_id, + 'arrival': arrival, + 'departure': departure, + 'time_on_site': time_on_site, + 'outbound': out_times, + 'return': back_times, + } + _set_json(r, key, value, CHECK_CACHE) + return value + + def routes_of_waypoints(waypoint_ids): """Return the routes of access waypoints. diff --git a/c2corg_api/tests/contract/routes.txt b/c2corg_api/tests/contract/routes.txt index c88b58fb4..ab86272eb 100644 --- a/c2corg_api/tests/contract/routes.txt +++ b/c2corg_api/tests/contract/routes.txt @@ -70,6 +70,7 @@ GET /images/{id} [public] PUT /images/{id} [authenticated] GET /images/{id}/{lang}/info [public] GET /images/{id}/{lang}/{version_id} [public] +GET /itinevert/check [public] GET /itinevert/hubs [public] GET /itinevert/reachable [public] GET /maps [public] diff --git a/c2corg_api/tests/contract/snapshots/itinevert_check.json b/c2corg_api/tests/contract/snapshots/itinevert_check.json new file mode 100644 index 000000000..79818f53c --- /dev/null +++ b/c2corg_api/tests/contract/snapshots/itinevert_check.json @@ -0,0 +1,27 @@ +{ + "body": { + "arrival": "int", + "date": "str", + "departure": "int", + "origin": "str", + "outbound": { + "arrival": "int", + "departure": "int", + "transfers": "int" + }, + "return": { + "arrival": "int", + "departure": "int", + "transfers": "int" + }, + "return_waypoint": "int", + "time_on_site": "int", + "waypoint": "int" + }, + "headers": { + "Access-Control-Allow-Origin": "http://localhost:6553", + "Access-Control-Expose-Headers": "Content-Type", + "Content-Type": "application/json" + }, + "status": 200 +} diff --git a/c2corg_api/tests/contract/test_itinevert.py b/c2corg_api/tests/contract/test_itinevert.py index 5a7645c21..2b4566da1 100644 --- a/c2corg_api/tests/contract/test_itinevert.py +++ b/c2corg_api/tests/contract/test_itinevert.py @@ -17,6 +17,7 @@ ) from c2corg_api.tests.views.test_reachable import POINT, add_route, add_waypoint +CHECK = ('GET', '/itinevert/check') HUBS = ('GET', '/itinevert/hubs') REACHABLE = ('GET', '/itinevert/reachable') POSITION = {'lon': 5.7146, 'lat': 45.1914} @@ -60,6 +61,7 @@ def reachable_route(session): ) add_route(session, area, 'hiking', 'Boucle', waypoint) session.flush() + return waypoint @pytest.mark.usefixtures('fakes') @@ -100,3 +102,17 @@ def test_reachable_out_of_range(self, browser): ) check_snapshot('itinevert_invalid', response) assert response.json['errors'][0]['description'] == 'date_out_of_range' + + @contract(CHECK) + def test_check(self, browser, reachable_route): + browser.get('/itinevert/hubs', params=POSITION) + response = browser.get( + '/itinevert/check', + params={ + 'origin': ORIGIN, + 'date': '2026-12-05', + 'waypoint': reachable_route.document_id, + }, + ) + check_snapshot('itinevert_check', response) + assert response.json['time_on_site'] > 0 diff --git a/c2corg_api/tests/itinevert/test_search.py b/c2corg_api/tests/itinevert/test_search.py index 5854d91c0..502af9904 100644 --- a/c2corg_api/tests/itinevert/test_search.py +++ b/c2corg_api/tests/itinevert/test_search.py @@ -64,11 +64,24 @@ def _journey(place_key, moment): } +def _check_journey(arrival, departure, transfers=1): + return { + 'departure_date_time': departure, + 'arrival_date_time': arrival, + 'nb_transfers': transfers, + } + + def _navitia(url, params=None, headers=None): """Answer as Navitia, from the path of the url.""" if url.endswith('/coverage/fr-se'): return {'regions': [{'end_production_date': '20270302'}]} if url.endswith('/journeys'): + if str(params.get('to', '')).startswith('stop_area:'): + # the check of an access: the outbound + return {'journeys': [_check_journey('20261205T082700', '20261205T073000')]} + if str(params.get('from', '')).startswith('stop_area:'): + return {'journeys': [_check_journey('20261205T190000', '20261205T175500')]} if 'from' in params: return {'journeys': [_journey('to', '20261205T082700')]} return {'journeys': [_journey('from', '20261205T175500')]} @@ -341,3 +354,135 @@ def test_route_listing_of_a_search(client, session, access, fakes): body = client.get('/routes', params={'itv': itv, 'act': 'skitouring'}).json assert body['total'] == 0 client.get('/routes', params={'itv': 'stop_area:1'}, status=400) + + +def _check_params(waypoint, **more): + return {**SEARCH, 'waypoint': waypoint.document_id, **more} + + +def _check_calls(fakes): + return [ + c + for c in fakes.call_args_list + if c.args[0].endswith('/journeys') + and 'to' in c.kwargs['params'] + and 'from' in c.kwargs['params'] + ] + + +def test_check(client, access, fakes): + waypoint, _, _ = access + _propose_hub(client) + calls = fakes.call_count + body = client.get('/itinevert/check', params=_check_params(waypoint)).json + # 08:27 + 8 minutes of walk, 17:55 - 8 minutes + assert body == { + 'origin': ORIGIN, + 'date': '2026-12-05', + 'waypoint': waypoint.document_id, + 'return_waypoint': waypoint.document_id, + 'arrival': 8 * 60 + 35, + 'departure': 17 * 60 + 47, + 'time_on_site': 17 * 60 + 47 - (8 * 60 + 35), + 'outbound': {'departure': 7 * 60 + 30, 'arrival': 8 * 60 + 27, 'transfers': 1}, + 'return': {'departure': 17 * 60 + 55, 'arrival': 19 * 60, 'transfers': 1}, + } + # the coverage (end of the timetables) and the two journeys + assert fakes.call_count == calls + 3 + position = f'{GRENOBLE[0]};{GRENOBLE[1]}' + out, back = [c.kwargs['params'] for c in _check_calls(fakes)] + assert out == { + 'from': position, + 'to': 'stop_area:1', + 'datetime': '20261205T060000', + 'datetime_represents': 'departure', + 'max_duration': 5 * 3600, + 'max_nb_transfers': 3, + } + assert back == { + 'from': 'stop_area:1', + 'to': position, + 'datetime': '20261205T210000', + 'datetime_represents': 'arrival', + 'max_duration': 5 * 3600, + 'max_nb_transfers': 3, + } + # cached: no new call + client.get('/itinevert/check', params=_check_params(waypoint), status=200) + assert fakes.call_count == calls + 3 + + +def test_check_best_journeys(client, access, fakes): + waypoint, _, _ = access + _propose_hub(client) + + def two(url, params=None, headers=None): + if url.endswith('/journeys'): + if params['datetime_represents'] == 'departure': + return { + 'journeys': [ + _check_journey('20261205T093000', '20261205T080000', 0), + _check_journey('20261205T090000', '20261205T074500', 2), + ] + } + return { + 'journeys': [ + _check_journey('20261205T190000', '20261205T170000', 0), + _check_journey('20261205T200000', '20261205T180000', 3), + ] + } + return _navitia(url, params, headers) + + fakes.side_effect = two + body = client.get('/itinevert/check', params=_check_params(waypoint)).json + assert body['outbound'] == { + 'departure': 7 * 60 + 45, + 'arrival': 9 * 60, + 'transfers': 2, + } + assert body['return'] == { + 'departure': 18 * 60, + 'arrival': 20 * 60, + 'transfers': 3, + } + assert body['arrival'] == 9 * 60 + 8 + assert body['departure'] == 18 * 60 - 8 + + +def test_check_one_side_without_solution(client, access, fakes): + waypoint, _, _ = access + _propose_hub(client) + + def no_return(url, params=None, headers=None): + if url.endswith('/journeys') and params['datetime_represents'] == 'arrival': + raise HTTPNotFound('no_solution') + return _navitia(url, params, headers) + + fakes.side_effect = no_return + body = client.get('/itinevert/check', params=_check_params(waypoint)).json + assert body['arrival'] == 8 * 60 + 35 + assert body['departure'] is None + assert body['time_on_site'] is None + assert body['return'] is None + assert body['outbound'] is not None + + +def test_check_invalid(client, access, fakes): + waypoint, _, _ = access + params = _check_params(waypoint) + # not a hub proposed + client.get('/itinevert/check', params=params, status=400) + _propose_hub(client) + for invalid in ( + {'origin': 'admin:fr:38185'}, + {'origin': 'stop_area:elsewhere'}, + {'date': '2026-13-05'}, + {'date': '2026-12-01'}, + {'date': '2027-03-03'}, + # a waypoint without stop area + {'waypoint': 999999999}, + {'return_waypoint': 999999999}, + ): + client.get('/itinevert/check', params={**params, **invalid}, status=400) + client.get('/itinevert/check', params=SEARCH, status=422) + assert not _check_calls(fakes) diff --git a/c2corg_api/views/itinevert.py b/c2corg_api/views/itinevert.py index 135eaa0b8..711c54aa8 100644 --- a/c2corg_api/views/itinevert.py +++ b/c2corg_api/views/itinevert.py @@ -86,3 +86,20 @@ def read_reachable(request): 'computed_on': stop_times['date'], **search.reachable(stop_times), } + + +def read_check(request): + """Return the real arrival and departure at the access of a route. + + Checked with the timetables of the date (two light Navitia calls, cached + an hour), not with the class of days of /itinevert/reachable. The times + are in minutes from the midnight of the date, the walk included. + """ + origin = request.validated['origin'] + if not STOP_AREA.match(origin): + raise HTTPBadRequest('invalid_origin') + day = _date(request) + waypoint = request.validated['waypoint'] + return search.check_access( + origin, day, waypoint, request.validated.get('return_waypoint') or waypoint + ) diff --git a/c2corg_api/web/itinevert.py b/c2corg_api/web/itinevert.py index 665f8d0d3..8c8b29d60 100644 --- a/c2corg_api/web/itinevert.py +++ b/c2corg_api/web/itinevert.py @@ -8,7 +8,7 @@ from c2corg_api.httpexceptions import HTTPTooManyRequests from c2corg_api.security.rate_limiting import navitia_rate_limited -from c2corg_api.views.itinevert import read_hubs, read_reachable +from c2corg_api.views.itinevert import read_check, read_hubs, read_reachable from c2corg_api.web.auth import CurrentUser, current_user from c2corg_api.web.handlers import serve_read, typed_values @@ -25,6 +25,7 @@ def include(app): """Add the routes of this module to the FastAPI application.""" for path, endpoint in ( + ('/itinevert/check', check), ('/itinevert/hubs', hubs), ('/itinevert/reachable', reachable), ): @@ -53,6 +54,8 @@ def limited(request): # the hubs: one or two light Navitia calls; a search: two heavy ones _read_hubs = _limited(read_hubs, 'navitia') _read_reachable = _limited(read_reachable, 'navitia_job') +# the check: two light calls +_read_check = _limited(read_check, 'navitia') def hubs( @@ -82,3 +85,28 @@ def reachable( """Return the waypoints and routes reachable from a hub on a date.""" validated = {'origin': origin, 'date': date} return serve_read(request, user, [typed_values(validated)], _read_reachable) + + +def check( + request: Request, + user: User, + origin: Annotated[ + str, Query(description='The stop area of a hub of /itinevert/hubs.') + ], + date: Day, + waypoint: Annotated[ + int, Query(description='The access waypoint the route is reached from.') + ], + return_waypoint: Annotated[ + int | None, + Query(description='The access waypoint the return leaves from.'), + ] = None, +): + """Return the real arrival and departure at the access of a route.""" + validated = { + 'origin': origin, + 'date': date, + 'waypoint': waypoint, + 'return_waypoint': return_waypoint, + } + return serve_read(request, user, [typed_values(validated)], _read_check)