You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
separate reader and writer to easier support two scenarios of 1. create and query and 2. load and query
I am not sure if this is the optimal separation. I think what should be separated from each other is creating/loading the graph&preparations and using the graph (routing). For example LM/CHPreparationHandler mixes both: Its partly about creating the preparations (reading prepare.ch/lm.weightings configuration, creating CH/LMProfile, creating the PrepareLandmark/ContractionHierarchies classes and even doing the actual preparation (using thread executioner etc.). And then they are used also to create the algorithms which is something different imo. In many cases you probably do the import/preparation once and from this point you are just loading the graph and use it to do the routing. In a Desktop/mobile setup you might even do this on two different devices (import server and mobile app). So in my opinion this is where we should start splitting the code into two different parts. Starting with PrepareLandmark/PrepareContractionHierarchies and LM/CHPreparationHandler and then extracting a class from GraphHopper that receives the loaded graph+preparations and just does the routing. I started doing this here #1901
Disclaimer: Thinking out loud and writing down a few findings for later reference here
I think the next thing that we need to fix is that GraphHopper uses the same code for importing a new graph and loading an existing one. Take a look at what we currently do:
First we call GraphHopper#init() or GraphHopper#setXYZ. These are the two ways we can use to initialize a GraphHopper instance. This is probably also something that we should change, but not the main issue IMO. Mixing these two is not supported (even though this is not really enforced), except a few exceptions. For example we have to use the setter to set the TagParserFactory even when we use init() for everything else. An important detail is that init() builds the EncodingManager, but when we use the setters it is built later in load().
Next we call importOrLoad (or just load). There is no import() method yet. But let's take a look at what importOrLoad does: if (!load()) process(false). So let's take a closer look at load() and process:
If the ghLocation is a .ghz file we unpack it. Skipping the discussion whether this feature is needed here or not, note that this only makes sense if we are loading, but at this point we don't know whether we are loading or importing, so we need to write code that handles both situations. Imagine we wanted to add a forceOverwrite option to delete and overwrite an existing -gh folder instead of throwing an error in case the given folder already existed. If we knew that we were on the 'import path' this would totally make sense, but on the 'loading path' this parameter would be pointless. And there are many more such parameters that only make sense for one of the two cases as we will see.
Not entirely sure about this one, but if we knew we would be loading anything other than read-only would not make sense anyway, and if we knew we were importing read-only, or allowWrites=false would be non-sensical.
Now it gets interesting: First of all the encodingManager == null check is equivalent to checking whether or not init() was called or not. So staring at this code we not only have to consider the two scenarios (load or import), but we also need to consider whether we used the init() method or not (and probably used the various setters instead). The properties.loadExisting check is used to find out whether we are importing or loading. We could easily get rid of this if we knew what we were doing. Also note that in case we did use init() we completely ignore the properties file up until now and then need to check whether the 'encoding matches' later... Why? Because we run init() again not knowing whether we do an import or we are loading an existing graph. There is more to discuss about this code, c.f. #2438, but let's continue.
hasElevation() only depends on the GraphHopper configuration and ignores whether or not a (possibly) existing graph is 3D or not. If we knew whether we were importing or loading we could decide whether the stored elevation or the configured value should be used. Better yet, if we knew we were loading there should not even be a hasElevation configuration flag in the configuration, because this can not be changed anymore anyway. Same with turn cost support and segment size. We are loading data from disk that has this information, but we have to provide that information so it matches the existing data. Unfortunately this situation occurs frequently in GraphHopper code. Let's ignore the todo here as this is again something else to discuss (see #2388).
Oh, we are in the load method and after doing all of the above, we now realize there is nothing to load. So let's take a little detour: We return from this method and go back to importOrLoad where we call process. process is rather straight-forward (in the context of what I am explaining here), it basically runs the OSM import and calls postProcessing.
Meanwhile in load (in case there was something to load) we do:
// create locks only if writes are allowed, if they are not allowed a lock cannot be created
// (e.g. on a read only filesystem locks would fail)
if (ghStorage.getDirectory().getDefaultType().isStoring() && isAllowWrites()) {
lockFactory.setLockDir(newFile(ghLocation));
lock = lockFactory.create(fileLockName, false);
if (!lock.tryLock())
thrownewRuntimeException("To avoid reading partial data we need to obtain the read lock but it failed. In " + ghLocation, lock.getObtainFailedReason());
}
if (!ghStorage.loadExisting())
returnfalse;
Ignoring the lockfile, we basically load the existing graph data (makes sense, because we already checked we are not running a fresh import before).
for (CHProfileprofile : chPreparationHandler.getCHProfiles()) {
if (!getProfileVersion(profile.getProfile()).equals("" + profilesByName.get(profile.getProfile()).getVersion()))
thrownewIllegalArgumentException("CH preparation of " + profile.getProfile() + " already exists in storage and doesn't match configuration");
}
} else {
prepareCH(closeEarly);
}
}
initLocationIndex, importPublicTransit, loadOrPrepareLM all apply some kind of "if there is data already do this and otherwise do that" logic, with the same consequences that I mentioned above: At any point of the code we have to keep in mind that we might be on one or the other code path and there are lots of parameters, objects etc. around that only make sense in one of the two cases.
It is basically impossible to read/understand this code without reading it line by line and considering what has happened before we got to a certain line. And really I see no reason why we have to do this. The code paths should just be separated from the very beginning:
if (GHexists)
load()
elseimport()
This is the one thing I think we should be aiming for right now when we consider refactoring the GraphHopper class. Once we have this it should be trivial to export an Importer class that just gets an import configuration and does the import and some code that loads an existing -gh folder. And once we have this I think the GraphHopper class will be so trivial that we can either delete it entirely or use it as minimal high-level convenience code with hardly any functionality. To do this the biggest tasks will probably be splitting 'loading' from 'importing' code in EncodingManager, FlagEncoder, CH/LMPreparationHandler and GraphHopperStorage. So far I think we can at least achieve this without touching the create/loadExisting() pattern in DataAccess, but eventually I like to get rid of the 'import or load' theme on this level as well.
We should either remove all the setters and initialize the import (or router) using a configuration object (GraphHopperConfig currently), or we should provide setters (or similar) for everything and use some code snippet that reads the config file and translates this into calls of these setters.
And actually we are making progress here. I think once we stop building the encoding manager in init() here: #2607 it should be possible to split GraphHopper into Importer and Loader.
Activity
easbar commentedon Feb 12, 2020
I am not sure if this is the optimal separation. I think what should be separated from each other is creating/loading the graph&preparations and using the graph (routing). For example
LM/CHPreparationHandlermixes both: Its partly about creating the preparations (readingprepare.ch/lm.weightingsconfiguration, creatingCH/LMProfile, creating thePrepareLandmark/ContractionHierarchiesclasses and even doing the actual preparation (using thread executioner etc.). And then they are used also to create the algorithms which is something different imo. In many cases you probably do the import/preparation once and from this point you are just loading the graph and use it to do the routing. In a Desktop/mobile setup you might even do this on two different devices (import server and mobile app). So in my opinion this is where we should start splitting the code into two different parts. Starting withPrepareLandmark/PrepareContractionHierarchiesandLM/CHPreparationHandlerand then extracting a class fromGraphHopperthat receives the loaded graph+preparations and just does the routing. I started doing this here #1901easbar commentedon Oct 21, 2021
Disclaimer: Thinking out loud and writing down a few findings for later reference here
I think the next thing that we need to fix is that
GraphHopperuses the same code for importing a new graph and loading an existing one. Take a look at what we currently do:First we call
GraphHopper#init()orGraphHopper#setXYZ. These are the two ways we can use to initialize aGraphHopperinstance. This is probably also something that we should change, but not the main issue IMO. Mixing these two is not supported (even though this is not really enforced), except a few exceptions. For example we have to use the setter to set theTagParserFactoryeven when we useinit()for everything else. An important detail is thatinit()builds theEncodingManager, but when we use the setters it is built later inload().Next we call
importOrLoad(or justload). There is noimport()method yet. But let's take a look at whatimportOrLoaddoes:if (!load()) process(false). So let's take a closer look atload()andprocess:graphhopper/core/src/main/java/com/graphhopper/GraphHopper.java
Lines 708 to 714 in 14bd13a
Ok (whatever...)
graphhopper/core/src/main/java/com/graphhopper/GraphHopper.java
Lines 715 to 728 in 14bd13a
If the
ghLocationis a.ghzfile we unpack it. Skipping the discussion whether this feature is needed here or not, note that this only makes sense if we are loading, but at this point we don't know whether we are loading or importing, so we need to write code that handles both situations. Imagine we wanted to add aforceOverwriteoption to delete and overwrite an existing-ghfolder instead of throwing an error in case the given folder already existed. If we knew that we were on the 'import path' this would totally make sense, but on the 'loading path' this parameter would be pointless. And there are many more such parameters that only make sense for one of the two cases as we will see.graphhopper/core/src/main/java/com/graphhopper/GraphHopper.java
Lines 730 to 731 in 14bd13a
Not entirely sure about this one, but if we knew we would be loading anything other than read-only would not make sense anyway, and if we knew we were importing read-only, or
allowWrites=falsewould be non-sensical.graphhopper/core/src/main/java/com/graphhopper/GraphHopper.java
Lines 732 to 737 in 14bd13a
Now it gets interesting: First of all the
encodingManager == nullcheck is equivalent to checking whether or notinit()was called or not. So staring at this code we not only have to consider the two scenarios (load or import), but we also need to consider whether we used theinit()method or not (and probably used the various setters instead). Theproperties.loadExistingcheck is used to find out whether we are importing or loading. We could easily get rid of this if we knew what we were doing. Also note that in case we did useinit()we completely ignore the properties file up until now and then need to check whether the 'encoding matches' later... Why? Because we run init() again not knowing whether we do an import or we are loading an existing graph. There is more to discuss about this code, c.f. #2438, but let's continue.graphhopper/core/src/main/java/com/graphhopper/GraphHopper.java
Lines 739 to 747 in 14bd13a
hasElevation()only depends on theGraphHopperconfiguration and ignores whether or not a (possibly) existing graph is 3D or not. If we knew whether we were importing or loading we could decide whether the stored elevation or the configured value should be used. Better yet, if we knew we were loading there should not even be ahasElevationconfiguration flag in the configuration, because this can not be changed anymore anyway. Same with turn cost support and segment size. We are loading data from disk that has this information, but we have to provide that information so it matches the existing data. Unfortunately this situation occurs frequently in GraphHopper code. Let's ignore the todo here as this is again something else to discuss (see #2388).graphhopper/core/src/main/java/com/graphhopper/GraphHopper.java
Lines 749 to 750 in 14bd13a
Oh, we are in the
loadmethod and after doing all of the above, we now realize there is nothing to load. So let's take a little detour: We return from this method and go back toimportOrLoadwhere we callprocess.processis rather straight-forward (in the context of what I am explaining here), it basically runs the OSM import and callspostProcessing.Meanwhile in
load(in case there was something to load) we do:graphhopper/core/src/main/java/com/graphhopper/GraphHopper.java
Lines 752 to 764 in 14bd13a
Ignoring the lockfile, we basically load the existing graph data (makes sense, because we already checked we are not running a fresh import before).
graphhopper/core/src/main/java/com/graphhopper/GraphHopper.java
Line 766 in 14bd13a
Now the 'import' and 'load' paths are back together in
postProcessingand we have to keep on writing code that handles both situations:graphhopper/core/src/main/java/com/graphhopper/GraphHopper.java
Lines 881 to 899 in 14bd13a
initLocationIndex,importPublicTransit,loadOrPrepareLMall apply some kind of "if there is data already do this and otherwise do that" logic, with the same consequences that I mentioned above: At any point of the code we have to keep in mind that we might be on one or the other code path and there are lots of parameters, objects etc. around that only make sense in one of the two cases.It is basically impossible to read/understand this code without reading it line by line and considering what has happened before we got to a certain line. And really I see no reason why we have to do this. The code paths should just be separated from the very beginning:
This is the one thing I think we should be aiming for right now when we consider refactoring the
GraphHopperclass. Once we have this it should be trivial to export anImporterclass that just gets an import configuration and does the import and some code that loads an existing-ghfolder. And once we have this I think theGraphHopperclass will be so trivial that we can either delete it entirely or use it as minimal high-level convenience code with hardly any functionality. To do this the biggest tasks will probably be splitting 'loading' from 'importing' code inEncodingManager,FlagEncoder,CH/LMPreparationHandlerandGraphHopperStorage. So far I think we can at least achieve this without touching thecreate/loadExisting()pattern inDataAccess, but eventually I like to get rid of the 'import or load' theme on this level as well.easbar commentedon Jun 20, 2022
This is also something that needs to be fixed:
c79bb96
We should either remove all the setters and initialize the import (or router) using a configuration object (GraphHopperConfig currently), or we should provide setters (or similar) for everything and use some code snippet that reads the config file and translates this into calls of these setters.
And actually we are making progress here. I think once we stop building the encoding manager in
init()here: #2607 it should be possible to split GraphHopper into Importer and Loader.