Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

front: undefined fetchedSections when opening a scenario #10950

Open
emersion opened this issue Feb 25, 2025 · 1 comment
Open

front: undefined fetchedSections when opening a scenario #10950

emersion opened this issue Feb 25, 2025 · 1 comment
Labels
area:front Work on Standard OSRD Interface modules kind:bug Something isn't working module:operational-studies Multi-train simulation with structured studies management severity:minor Minor severity bug

Comments

@emersion
Copy link
Member

emersion commented Feb 25, 2025

What happened?

Failed to fetch track sections: TypeError: fetchedSections is undefined
    getTrackSectionsByIds useCachedTrackSections.ts:26
    getPathItemsCoordinates SimulationResultsMap.tsx:75
    SimulationResultMap SimulationResultsMap.tsx:100

What did you expect to happen?

No response

How can we reproduce it (as minimally and precisely as possible)?

Open/close a scenario until the error pops up.

On which environments the bug occurs?

Local

On which browser the bug occurs?

Firefox

OSRD version (top right corner Account button > Informations)

3ebcea2

@emersion emersion added kind:bug Something isn't working area:front Work on Standard OSRD Interface modules module:operational-studies Multi-train simulation with structured studies management labels Feb 25, 2025
@emersion
Copy link
Member Author

cc @Synar

There is a weird rtk-query interaction going on: loadInfraObject() returns undefined. It seems to happen when fetching a large number of track sections.

  • Multiple requests are running in parallel, and the first sent request may complete last if it queried many track sections.
  • useLazyQuery() shouldn't be used there, initiate() should be used instead. But fixing that doesn't fix the issue.
  • Turning the request into a mutation makes the error go away. This leads me to believe rtk-query's caching mechanism is involved somehow.
  • Disabling the cache (by setting serializeQueryArgs, merge and forceRefetch) also fixes the issue, but results in tracks[id] being undefined down the line…
Turn the query into a mutation
diff --git a/front/src/common/api/generatedEditoastApi.ts b/front/src/common/api/generatedEditoastApi.ts
index 54a71ad94117..c11ca2f3e95d 100644
--- a/front/src/common/api/generatedEditoastApi.ts
+++ b/front/src/common/api/generatedEditoastApi.ts
@@ -293,7 +293,7 @@ const injectedRtkApi = api
         query: (queryArg) => ({ url: `/infra/${queryArg.infraId}/lock`, method: 'POST' }),
         invalidatesTags: ['infra'],
       }),
-      postInfraByInfraIdObjectsAndObjectType: build.query<
+      postInfraByInfraIdObjectsAndObjectType: build.mutation<
         PostInfraByInfraIdObjectsAndObjectTypeApiResponse,
         PostInfraByInfraIdObjectsAndObjectTypeApiArg
       >({
@@ -302,7 +302,7 @@ const injectedRtkApi = api
           method: 'POST',
           body: queryArg.body,
         }),
-        providesTags: ['infra'],
+        invalidatesTags: ['infra'],
       }),
       postInfraByInfraIdPathProperties: build.query<
         PostInfraByInfraIdPathPropertiesApiResponse,
diff --git a/front/src/config/openapi-editoast-config.cts b/front/src/config/openapi-editoast-config.cts
index dd5f3cd7b714..9da0396a938a 100644
--- a/front/src/config/openapi-editoast-config.cts
+++ b/front/src/config/openapi-editoast-config.cts
@@ -11,7 +11,7 @@ const config: ConfigFile = {
   endpointOverrides: [
     {
       pattern: [
-        'postInfraByInfraIdObjectsAndObjectType',
+        //'postInfraByInfraIdObjectsAndObjectType',
         'postInfraByInfraIdPathfinding',
         'postInfraByInfraIdPathfindingBlocks',
         'postInfraByInfraIdPathProperties',
Disable the cache
diff --git a/front/src/applications/operationalStudies/hooks/useCachedTrackSections.ts b/front/src/applications/operationalStudies/hooks/useCachedTrackSections.ts
index d22001606e10..ab8ae11697e2 100644
--- a/front/src/applications/operationalStudies/hooks/useCachedTrackSections.ts
+++ b/front/src/applications/operationalStudies/hooks/useCachedTrackSections.ts
@@ -1,26 +1,31 @@
-import { useRef, useCallback } from 'react';
+import { useRef, useCallback, useState } from 'react';
 
 import { uniq } from 'lodash';
 
 import { osrdEditoastApi } from 'common/api/osrdEditoastApi';
 import type { TrackSection } from 'common/api/osrdEditoastApi';
+import { useAppDispatch } from 'store';
 
 export default function useCachedTrackSections(infraId: number) {
   const trackIdsRef = useRef<Set<string>>(new Set());
   const trackSectionsRef = useRef<Record<string, TrackSection>>({});
-  const [loadInfraObject, { isLoading }] =
-    osrdEditoastApi.endpoints.postInfraByInfraIdObjectsAndObjectType.useLazyQuery();
+  const [isLoading, setIsLoading] = useState(false);
+  const dispatch = useAppDispatch();
 
   const getTrackSectionsByIds = useCallback(
     async (requestedTrackIds: string[]) => {
       const uniqueNewIds = uniq(requestedTrackIds.filter((id) => !trackIdsRef.current.has(id)));
       if (uniqueNewIds.length !== 0) {
+        setIsLoading(true);
         try {
-          const fetchedSections = await loadInfraObject({
+          console.log('start', uniqueNewIds);
+          const promise = dispatch(osrdEditoastApi.endpoints.postInfraByInfraIdObjectsAndObjectType.initiate({
             infraId,
             objectType: 'TrackSection',
             body: uniqueNewIds,
-          }).unwrap();
+          }, { subscribe: false }));
+          const fetchedSections = await promise.unwrap();
+          console.log('done', fetchedSections, uniqueNewIds);
 
           uniqueNewIds.forEach((id) => trackIdsRef.current.add(id));
           fetchedSections.forEach((rawSection) => {
@@ -29,6 +34,8 @@ export default function useCachedTrackSections(infraId: number) {
           });
         } catch (error) {
           console.error('Failed to fetch track sections:', error);
+        } finally {
+          setIsLoading(false);
         }
       }
 
diff --git a/front/src/applications/operationalStudies/hooks/useScenarioData.ts b/front/src/applications/operationalStudies/hooks/useScenarioData.ts
index e2a0b6009dbd..0187a34d2ca3 100644
--- a/front/src/applications/operationalStudies/hooks/useScenarioData.ts
+++ b/front/src/applications/operationalStudies/hooks/useScenarioData.ts
@@ -45,13 +45,17 @@ const useScenarioData = (scenario: ScenarioResponse, infra: InfraWithState) => {
 
   const projectionPath = usePathProjection(infra);
 
-  const { data: trainSchedulesResults = [] } =
+  const { data: fetchTrainSchedulesResults } =
     osrdEditoastApi.endpoints.getAllTimetableByIdTrainSchedules.useQuery(
       { timetableId: scenario?.timetable_id },
       {
         skip: !scenario,
       }
     );
+  const trainSchedulesResults = useMemo(
+    () => fetchTrainSchedulesResults || [],
+    [fetchTrainSchedulesResults]
+  );
 
   const { trainScheduleSummariesById, setTrainScheduleSummariesById, allTrainsLoaded } =
     useLazyLoadTrains({
diff --git a/front/src/common/api/osrdEditoastApi.ts b/front/src/common/api/osrdEditoastApi.ts
index d6354e319b13..5b11d488eb8e 100644
--- a/front/src/common/api/osrdEditoastApi.ts
+++ b/front/src/common/api/osrdEditoastApi.ts
@@ -165,6 +165,12 @@ const osrdEditoastApi = generatedEditoastApi
           { type: 'scenarios', id: 'LIST' },
         ],
       },
+
+      postInfraByInfraIdObjectsAndObjectType: {
+        serializeQueryArgs: ({ endpointName }) => endpointName,
+        merge: () => {},
+        forceRefetch: () => true,
+      },
     },
   });
 

@SharglutDev SharglutDev added the severity:minor Minor severity bug label Feb 25, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area:front Work on Standard OSRD Interface modules kind:bug Something isn't working module:operational-studies Multi-train simulation with structured studies management severity:minor Minor severity bug
Projects
None yet
Development

No branches or pull requests

2 participants