| | | 1 | | using System; |
| | | 2 | | using System.Collections.Concurrent; |
| | | 3 | | using System.Collections.Generic; |
| | | 4 | | using System.Threading; |
| | | 5 | | using Itinero.Network.DataStructures; |
| | | 6 | | using Itinero.Network.Tiles; |
| | | 7 | | using Itinero.Network.Writer; |
| | | 8 | | |
| | | 9 | | namespace Itinero.Network; |
| | | 10 | | |
| | | 11 | | public sealed partial class RoutingNetwork |
| | | 12 | | { |
| | 866 | 13 | | private readonly object _writeSync = new(); |
| | | 14 | | private RoutingNetworkWriter? _writer; |
| | | 15 | | |
| | | 16 | | /// <summary> |
| | | 17 | | /// Concurrent tile-insert writers currently open. |
| | | 18 | | /// </summary> |
| | | 19 | | /// <remarks> |
| | | 20 | | /// Tile insertion is the one write that happens constantly and from many threads, so it gets |
| | | 21 | | /// its own admission rule: any number at once, but never alongside the exclusive writer. |
| | | 22 | | /// |
| | | 23 | | /// That exclusion is not new behaviour, it is the old behaviour made explicit. Tile insertion |
| | | 24 | | /// used to call <see cref="GetWriter"/>, so an open mutator made it throw — the two were |
| | | 25 | | /// already mutually exclusive, by exception rather than by design. Counting the tile writers |
| | | 26 | | /// keeps that guarantee while letting them run in parallel with each other. |
| | | 27 | | /// </remarks> |
| | | 28 | | private int _tileWriters; |
| | | 29 | | |
| | | 30 | | /// <summary> |
| | | 31 | | /// A lock per tile, created on demand. |
| | | 32 | | /// </summary> |
| | | 33 | | /// <remarks> |
| | | 34 | | /// Writes to one tile cannot overlap: a NetworkTile is an append-only byte buffer with its own |
| | | 35 | | /// offsets, so two threads appending at once corrupt it. Different tiles are independent, |
| | | 36 | | /// which is what makes concurrent insertion possible at all. |
| | | 37 | | /// |
| | | 38 | | /// Never grows beyond the tiles actually written, and the entries are plain objects. |
| | | 39 | | /// </remarks> |
| | | 40 | | /// <summary> |
| | | 41 | | /// Striped write locks, indexed by tile id modulo the stripe count. |
| | | 42 | | /// </summary> |
| | | 43 | | /// <remarks> |
| | | 44 | | /// Striped rather than one lock per tile, because both obvious alternatives are worse. A |
| | | 45 | | /// <c>ConcurrentDictionary</c> keyed by tile id put 31% of warm blocked time inside its own |
| | | 46 | | /// <c>GetOrAdd</c> — the lookup cost more than the work it guarded. A flat array indexed by |
| | | 47 | | /// tile id is far worse: local tile ids at zoom 14 run to 2^28, and a country's tiles sit |
| | | 48 | | /// around id 90,000,000, so the array grows to ~134M references — about 1 GB — to guard some |
| | | 49 | | /// 7,000 real tiles. That is exactly why the tiles themselves live in a |
| | | 50 | | /// <see cref="SparseArray{T}"/>. |
| | | 51 | | /// |
| | | 52 | | /// Stripes give bounded memory and an index calculation instead of a hash lookup. Two |
| | | 53 | | /// unrelated tiles sharing a stripe is harmless: it over-excludes, briefly serialising two |
| | | 54 | | /// writes that need not have been, and never under-excludes. |
| | | 55 | | /// </remarks> |
| | | 56 | | private const int TileLockStripes = 4096; |
| | | 57 | | |
| | 866 | 58 | | private readonly object[] _tileLocks = CreateTileLocks(); |
| | | 59 | | |
| | | 60 | | private static object[] CreateTileLocks() |
| | 866 | 61 | | { |
| | 866 | 62 | | var locks = new object[TileLockStripes]; |
| | 10643140 | 63 | | for (var i = 0; i < locks.Length; i++) locks[i] = new object(); |
| | | 64 | | |
| | 866 | 65 | | return locks; |
| | 866 | 66 | | } |
| | | 67 | | |
| | | 68 | | /// <summary> |
| | | 69 | | /// Returns true if there is already a writer. |
| | | 70 | | /// </summary> |
| | 0 | 71 | | public bool HasWriter => _writer != null; |
| | | 72 | | |
| | | 73 | | /// <summary> |
| | | 74 | | /// Gets a writer. |
| | | 75 | | /// </summary> |
| | | 76 | | /// <returns>The writer.</returns> |
| | | 77 | | public RoutingNetworkWriter GetWriter() |
| | 97 | 78 | | { |
| | 97 | 79 | | lock (_writeSync) |
| | 97 | 80 | | { |
| | 97 | 81 | | if (_writer != null) throw new InvalidOperationException($"Only one writer is allowed at one time." + |
| | 0 | 82 | | $"Check {nameof(this.HasWriter)} for a current writer."); |
| | 97 | 83 | | if (_tileWriters > 0) |
| | 0 | 84 | | { |
| | 0 | 85 | | throw new InvalidOperationException( |
| | 0 | 86 | | $"Cannot open a writer while {_tileWriters} tile-insert writer(s) are open."); |
| | | 87 | | } |
| | | 88 | | |
| | 97 | 89 | | _writer = new RoutingNetworkWriter(this); |
| | 97 | 90 | | return _writer; |
| | | 91 | | } |
| | 97 | 92 | | } |
| | | 93 | | |
| | | 94 | | /// <summary> |
| | | 95 | | /// Gets a writer for inserting a tile, which may run concurrently with other tile inserts. |
| | | 96 | | /// </summary> |
| | | 97 | | /// <remarks> |
| | | 98 | | /// Any number of these may be open at once; none may be open alongside the exclusive |
| | | 99 | | /// <see cref="GetWriter"/>, and vice versa. |
| | | 100 | | /// |
| | | 101 | | /// Safe to use concurrently without taking any lock yourself: the write methods on the |
| | | 102 | | /// returned writer take the tile locks they need, in ascending tile id, which is what keeps |
| | | 103 | | /// concurrent inserts from deadlocking on a shared boundary. |
| | | 104 | | /// |
| | | 105 | | /// Intended for loading tiles into a live network, which is the one write that happens |
| | | 106 | | /// continuously and from many threads. Anything that mutates existing data still wants the |
| | | 107 | | /// exclusive writer. |
| | | 108 | | /// </remarks> |
| | | 109 | | public RoutingNetworkWriter GetTileInsertWriter() |
| | 1870 | 110 | | { |
| | 1870 | 111 | | lock (_writeSync) |
| | 1870 | 112 | | { |
| | 1870 | 113 | | if (_writer != null) |
| | 0 | 114 | | { |
| | 0 | 115 | | throw new InvalidOperationException( |
| | 0 | 116 | | "Cannot insert a tile while an exclusive writer is open."); |
| | | 117 | | } |
| | | 118 | | |
| | 1870 | 119 | | _tileWriters++; |
| | 1870 | 120 | | return new RoutingNetworkWriter(this, exclusive: false); |
| | | 121 | | } |
| | 1870 | 122 | | } |
| | | 123 | | |
| | | 124 | | void IRoutingNetworkWritable.ClearWriter() |
| | 97 | 125 | | { |
| | 97 | 126 | | _writer = null; |
| | 97 | 127 | | } |
| | | 128 | | |
| | | 129 | | void IRoutingNetworkWritable.ReleaseTileWriter() |
| | 1870 | 130 | | { |
| | 1870 | 131 | | lock (_writeSync) |
| | 1870 | 132 | | { |
| | 1870 | 133 | | _tileWriters--; |
| | 1870 | 134 | | } |
| | 1870 | 135 | | } |
| | | 136 | | |
| | | 137 | | int IRoutingNetworkWritable.TileLockIndex(uint localTileId) => |
| | 9320 | 138 | | (int)(localTileId & (TileLockStripes - 1)); |
| | | 139 | | |
| | 9320 | 140 | | object IRoutingNetworkWritable.GetTileLockByIndex(int index) => _tileLocks[index]; |
| | | 141 | | |
| | | 142 | | (NetworkTile tile, Func<IEnumerable<(string key, string value)>, uint> func) IRoutingNetworkWritable. |
| | | 143 | | GetTileForWrite(uint localTileId) |
| | 8453 | 144 | | { |
| | | 145 | | // No lock here. Every caller already holds this tile's stripe — the write methods on |
| | | 146 | | // RoutingNetworkWriter all go through WithTileLocks, which is where the ordering invariant |
| | | 147 | | // lives. Taking it again was correct (Monitor is re-entrant) but not free, and this is |
| | | 148 | | // called several times per inserted tile. |
| | | 149 | | // |
| | | 150 | | // ensure minimum size. |
| | 8453 | 151 | | _tiles.EnsureMinimumSize(localTileId); |
| | | 152 | | |
| | 8453 | 153 | | var edgeTypeMap = this.RouterDb.GetEdgeTypeMap(); |
| | 8453 | 154 | | var tile = _tiles[localTileId]; |
| | 8453 | 155 | | if (tile != null) |
| | 8408 | 156 | | { |
| | 8408 | 157 | | if (tile.EdgeTypeMapId != edgeTypeMap.id) |
| | 0 | 158 | | { |
| | 0 | 159 | | tile = tile.CloneForEdgeTypeMap(edgeTypeMap); |
| | 0 | 160 | | _tiles[localTileId] = tile; |
| | 0 | 161 | | } |
| | | 162 | | else |
| | 8408 | 163 | | { |
| | | 164 | | // check if there is a mutable graph. |
| | 8408 | 165 | | this.CloneTileIfNeededForMutator(tile); |
| | 8408 | 166 | | } |
| | | 167 | | |
| | 8408 | 168 | | return (tile, edgeTypeMap.func); |
| | | 169 | | } |
| | | 170 | | |
| | | 171 | | // create a new tile. |
| | 45 | 172 | | tile = new NetworkTile(this.Zoom, localTileId, edgeTypeMap.id); |
| | 45 | 173 | | _tiles[localTileId] = tile; |
| | | 174 | | |
| | 45 | 175 | | return (tile, edgeTypeMap.func); |
| | 8453 | 176 | | } |
| | | 177 | | |
| | | 178 | | void IRoutingNetworkWritable.SetTile(NetworkTile tile) |
| | 1928 | 179 | | { |
| | 1928 | 180 | | var edgeTypeMap = this.RouterDb.GetEdgeTypeMap(); |
| | 1928 | 181 | | if (tile.EdgeTypeMapId != edgeTypeMap.id) throw new ArgumentException("Cannot add an entire tile without a match |
| | | 182 | | |
| | | 183 | | // No lock: the caller holds this tile's stripe for the whole write session. Check-then-set |
| | | 184 | | // is still one step under that lock, which is what keeps two inserts of the same tile from |
| | | 185 | | // losing one — though the caller also dedupes in-flight loads per tile, so it should not |
| | | 186 | | // arise. |
| | | 187 | | // |
| | | 188 | | // ensure minimum size. |
| | 1928 | 189 | | _tiles.EnsureMinimumSize(tile.TileId); |
| | | 190 | | |
| | | 191 | | // set tile if not yet there. |
| | 1928 | 192 | | var existingTile = _tiles[tile.TileId]; |
| | 1928 | 193 | | if (existingTile != null) throw new ArgumentException("Cannot overwrite a tile"); |
| | 1928 | 194 | | _tiles[tile.TileId] = tile; |
| | 1928 | 195 | | } |
| | | 196 | | |
| | | 197 | | private void CloneTileIfNeededForMutator(NetworkTile tile) |
| | 8408 | 198 | | { |
| | | 199 | | // this is weird right? |
| | | 200 | | // |
| | | 201 | | // the combination these features make this needed: |
| | | 202 | | // - we don't want to clone every tile when we read data in the mutable graph so we use the exiting tiles. |
| | | 203 | | // - a graph can be written to at all times (to lazy load data) but can be mutated at any time too. |
| | | 204 | | // |
| | | 205 | | // this makes it possible the graph is being written to and mutated at the same time. |
| | | 206 | | // we need to check, when writing to a graph, a mutator doesn't have the tile in use or |
| | | 207 | | // data from the write could bleed into the mutator creating an invalid state. |
| | | 208 | | // so **we have to clone tiles before writing to them and give them to the mutator** |
| | 8408 | 209 | | var mutableGraph = _graphMutator; |
| | 8408 | 210 | | if (mutableGraph != null && !mutableGraph.HasTile(tile.TileId)) |
| | 0 | 211 | | { |
| | 0 | 212 | | mutableGraph.SetTile(tile.Clone()); |
| | 0 | 213 | | } |
| | 8408 | 214 | | } |
| | | 215 | | } |