Changeset 19718 in josm
- Timestamp:
- 2026-11-29T09:59:39+01:00 (less than one hour ago)
- Location:
- trunk
- Files:
-
- 6 edited
-
src/org/openstreetmap/josm/data/cache/JCSCachedTileLoaderJob.java (modified) (3 diffs)
-
src/org/openstreetmap/josm/data/imagery/TMSCachedTileLoaderJob.java (modified) (8 diffs)
-
src/org/openstreetmap/josm/gui/layer/AbstractTileSourceLayer.java (modified) (5 diffs)
-
test/unit/org/openstreetmap/josm/data/cache/JCSCachedTileLoaderJobTest.java (modified) (1 diff)
-
test/unit/org/openstreetmap/josm/data/imagery/TMSCachedTileLoaderJobTest.java (modified) (4 diffs)
-
test/unit/org/openstreetmap/josm/gui/layer/AbstractTileSourceLayerTest.java (modified) (2 diffs)
Legend:
- Unmodified
- Added
- Removed
-
trunk/src/org/openstreetmap/josm/data/cache/JCSCachedTileLoaderJob.java
r19709 r19718 9 9 import java.net.URL; 10 10 import java.nio.file.Files; 11 import java.security.SecureRandom;12 11 import java.util.Collections; 13 12 import java.util.List; … … 384 383 attributes = parseHeaders(urlConn); 385 384 386 for (int i = 0; i < 5; ++i) { 387 if (urlConn.getResponseCode() == HttpURLConnection.HTTP_UNAVAILABLE) { 388 Thread.sleep(5000L+new SecureRandom().nextInt(5000)); 389 continue; 385 attributes.setResponseCode(urlConn.getResponseCode()); 386 byte[] raw; 387 if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) { 388 try (InputStream is = urlConn.getContent()) { 389 raw = is.readAllBytes(); 390 390 } 391 392 attributes.setResponseCode(urlConn.getResponseCode()); 393 byte[] raw; 394 if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) { 395 try (InputStream is = urlConn.getContent()) { 396 raw = is.readAllBytes(); 391 } else { 392 raw = new byte[]{}; 393 try { 394 String data = urlConn.fetchContent(); 395 if (!data.isEmpty()) { 396 String detectErrorMessage = detectErrorMessage(data); 397 if (detectErrorMessage != null) { 398 attributes.setErrorMessage(detectErrorMessage); 399 } 397 400 } 398 } else { 399 raw = new byte[]{}; 400 try { 401 String data = urlConn.fetchContent(); 402 if (!data.isEmpty()) { 403 String detectErrorMessage = detectErrorMessage(data); 404 if (detectErrorMessage != null) { 405 attributes.setErrorMessage(detectErrorMessage); 406 } 407 } 408 } catch (IOException e) { 409 Logging.warn(e); 410 } 401 } catch (IOException e) { 402 Logging.warn(e); 411 403 } 412 413 if (isResponseLoadable(urlConn.getHeaderFields(), urlConn.getResponseCode(), raw)) { 414 // we need to check cacheEmpty, so for cases, when data is returned, but we want to store415 // as empty (eg. empty tile images) to save some space416 cacheData = createCacheEntry(raw);417 cache.put(getCacheKey(),cacheData, attributes);418 Logging.debug("JCS - downloaded key: {0}, length: {1}, url: {2}",419 getCacheKey(), raw.length, getUrl());420 return true;421 } else if (cacheAsEmpty(urlConn.getHeaderFields(), urlConn.getResponseCode())) {422 cacheData = createCacheEntry(new byte[]{});423 cache.put(getCacheKey(),cacheData, attributes);424 Logging.debug("JCS - Caching empty object {0}", getUrl());425 return true;426 } else {427 Logging.debug("JCS - failure during load - response is not loadable nor cached as empty");428 return false;429 }404 } 405 406 if (isResponseLoadable(urlConn.getHeaderFields(), urlConn.getResponseCode(), raw)) { 407 // we need to check cacheEmpty, so for cases, when data is returned, but we want to store 408 // as empty (eg. empty tile images) to save some space 409 cacheData = createCacheEntry(raw); 410 cache.put(getCacheKey(), cacheData, attributes); 411 Logging.debug("JCS - downloaded key: {0}, length: {1}, url: {2}", 412 getCacheKey(), raw.length, getUrl()); 413 return true; 414 } else if (cacheAsEmpty(urlConn.getHeaderFields(), urlConn.getResponseCode())) { 415 cacheData = createCacheEntry(new byte[]{}); 416 cache.put(getCacheKey(), cacheData, attributes); 417 Logging.debug("JCS - Caching empty object {0}", getUrl()); 418 return true; 419 } else { 420 Logging.debug("JCS - failure during load - response is not loadable nor cached as empty"); 421 return false; 430 422 } 431 423 } catch (FileNotFoundException e) { … … 450 442 return false; 451 443 } 452 453 } catch (InterruptedException e) { 454 attributes.setError(e); 455 attributes.setException(e); 456 Logging.logWithStackTrace(Logging.LEVEL_WARN, e, "JCS - Exception during download {0}", getUrlNoException()); 457 Thread.currentThread().interrupt(); 458 } 459 Logging.warn("JCS - Silent failure during download: {0}", getUrlNoException()); 460 return false; 444 } 461 445 } 462 446 -
trunk/src/org/openstreetmap/josm/data/imagery/TMSCachedTileLoaderJob.java
r19653 r19718 18 18 import java.util.concurrent.ConcurrentHashMap; 19 19 import java.util.concurrent.ConcurrentMap; 20 import java.util.concurrent.Executors; 21 import java.util.concurrent.ScheduledExecutorService; 20 22 import java.util.concurrent.ThreadPoolExecutor; 21 23 import java.util.concurrent.TimeUnit; … … 37 39 import org.openstreetmap.josm.data.imagery.vectortile.VectorTile; 38 40 import org.openstreetmap.josm.data.imagery.vectortile.mapbox.MVTFile; 41 import org.openstreetmap.josm.data.preferences.IntegerProperty; 39 42 import org.openstreetmap.josm.data.preferences.LongProperty; 40 43 import org.openstreetmap.josm.tools.HttpClient; … … 53 56 /** General minimum expires for tiles. Might be overridden by imagery settings */ 54 57 public static final LongProperty MINIMUM_EXPIRES = new LongProperty("imagery.generic.minimum_expires", TimeUnit.HOURS.toMillis(1)); 58 /** 59 * Number of times a tile is downloaded again after a transient error (5xx response or read timeout) 60 * @since 19718 61 */ 62 public static final IntegerProperty TRANSIENT_ERROR_RETRIES = new IntegerProperty("imagery.generic.transient_error_retries", 3); 63 /** 64 * Delay in milliseconds before the first retry after a transient error, doubled for each further retry 65 * @since 19718 66 */ 67 public static final LongProperty TRANSIENT_ERROR_RETRY_DELAY = new LongProperty("imagery.generic.transient_error_retry_delay", 68 TimeUnit.SECONDS.toMillis(2)); 55 69 static final Pattern SERVICE_EXCEPTION_PATTERN = Pattern.compile("(?s).+<ServiceException[^>]*>(.+)</ServiceException>.+"); 56 70 static final Pattern CDATA_PATTERN = Pattern.compile("(?s)\\s*<!\\[CDATA\\[(.+)\\]\\]>\\s*"); … … 63 77 // that way, we reduce calls to tileLoadingFinished, and general CPU load due to surplus Map repaints 64 78 private static final ConcurrentMap<String, Set<TileLoaderListener>> inProgress = new ConcurrentHashMap<>(); 79 80 // retries made so far for tiles which failed with a transient error, by cache key 81 private static final ConcurrentMap<String, Integer> retries = new ConcurrentHashMap<>(); 82 private static final ScheduledExecutorService retryScheduler = Executors.newSingleThreadScheduledExecutor(r -> { 83 Thread thread = new Thread(r, "TMS-retry"); 84 thread.setDaemon(true); 85 return thread; 86 }); 65 87 66 88 /** … … 174 196 @Override 175 197 public void submit(boolean force) { 198 if (force) { 199 retries.remove(getCacheKey()); 200 } 176 201 tile.initLoading(); 177 202 try { … … 207 232 if (httpStatusCode >= 400 && !isNoTileAtZoom()) { 208 233 status = false; 209 handleError(attributes); 234 handleError(attributes, listeners); 210 235 } 211 236 } 212 237 status &= tryLoadTileImage(object); //try to keep returned image as background 238 if (status) { 239 retries.remove(getCacheKey()); 240 } 213 241 break; 214 242 case FAILURE: 215 handleError(attributes); 243 handleError(attributes, listeners); 216 244 tryLoadTileImage(object); 217 245 break; … … 241 269 } 242 270 243 private void handleError(CacheEntryAttributes attributes) { 271 private void handleError(CacheEntryAttributes attributes, Set<TileLoaderListener> listeners) { 244 272 if (tile.hasError() && tile.getErrorMessage() != null) { 245 273 // tile has already set error message, don't overwrite it … … 253 281 tile.setError(tr("Error downloading tiles: {0}", attributes.getErrorMessage())); 254 282 } 255 if (httpStatusCode >= 500 && httpStatusCode != 599) { 256 // httpStatusCode = 599 is set by JCSCachedTileLoaderJob on IOException 257 tile.setLoaded(false); // treat 500 errors as temporary and try to load it again 258 } 259 // treat SocketTimeoutException as transient error 260 attributes.getException() 261 .filter(x -> x.isAssignableFrom(SocketTimeoutException.class)) 262 .ifPresent(x -> tile.setLoaded(false)); 283 // treat 500 errors and SocketTimeoutException as temporary and try to load the tile again 284 // httpStatusCode = 599 is set by JCSCachedTileLoaderJob on IOException 285 if ((httpStatusCode >= 500 && httpStatusCode != 599) 286 || attributes.getException().filter(x -> x.isAssignableFrom(SocketTimeoutException.class)).isPresent()) { 287 scheduleRetry(listeners); 288 } 263 289 } else { 264 290 tile.setError(tr("Problem loading tile")); 265 291 // treat unknown errors as permanent and do not try to load tile again 266 292 } 293 } 294 295 /** 296 * Lets the tile be downloaded again after a transient error, a limited number of times and with a growing delay. 297 * <p> 298 * The tile stays loaded with its error until then, so that the layer shows the error and doesn't download it again 299 * at the next repaint. When the delay has passed, the tile is marked as not loaded and the listeners are notified, 300 * so that the layer repaints and downloads it again if it's still visible (see #25133). 301 * @param listeners the listeners notified about this download, may be {@code null} 302 */ 303 private void scheduleRetry(Set<TileLoaderListener> listeners) { 304 String key = getCacheKey(); 305 int retry = retries.merge(key, 1, Integer::sum); 306 if (retry > TRANSIENT_ERROR_RETRIES.get()) { 307 // give up, the tile keeps its error until it is reloaded 308 retries.remove(key); 309 Logging.debug("JCS TMS - giving up on tile {0} after {1} retries", tile.getKey(), retry - 1); 310 return; 311 } 312 long delay = TRANSIENT_ERROR_RETRY_DELAY.get() << (retry - 1); 313 retryScheduler.schedule(() -> { 314 if (tile.hasError() && !tile.isLoading()) { 315 tile.setLoaded(false); 316 if (listeners != null) { 317 for (TileLoaderListener l: listeners) { 318 l.tileLoadingFinished(tile, false); 319 } 320 } 321 } 322 }, delay, TimeUnit.MILLISECONDS); 267 323 } 268 324 -
trunk/src/org/openstreetmap/josm/gui/layer/AbstractTileSourceLayer.java
r19701 r19718 45 45 import java.util.Set; 46 46 import java.util.TreeSet; 47 import java.util.concurrent.ConcurrentHashMap; 47 48 import java.util.concurrent.ConcurrentSkipListSet; 48 49 import java.util.concurrent.atomic.AtomicInteger; … … 208 209 private final Timer invalidateLaterTimer = new Timer(100, e -> this.invalidate()); 209 210 211 // keys of the tiles which failed to load and have not been loaded successfully since 212 private final Set<String> failedTiles = ConcurrentHashMap.newKeySet(); 213 210 214 private final MouseAdapter adapter = new MouseAdapter() { 211 215 @Override … … 323 327 success = false; 324 328 tile.setImage(null); 329 failedTiles.add(tile.getKey()); 330 } else if (success) { 331 failedTiles.remove(tile.getKey()); 325 332 } 326 333 invalidateLater(); … … 1198 1205 g.drawString(s, x, y + offset); 1199 1206 offset += g.getFontMetrics().getHeight() + 3; 1207 } 1208 } 1209 1210 /** 1211 * Returns the image which shows the state of a tile that failed to load. 1212 * <p> 1213 * Tiles which never failed get no image, so that the normal loading of tiles shows the imagery of other zoom levels 1214 * or layers, as before. Once a tile has failed, it shows the error image while it has its error, and the hourglass 1215 * while it is loaded again, until it is loaded successfully (see #25133). 1216 * @param tile the tile 1217 * @return {@link Tile#ERROR_IMAGE}, {@link Tile#LOADING_IMAGE}, or {@code null} for no image 1218 */ 1219 BufferedImage getTileStatusImage(Tile tile) { 1220 if (tile == null || !getDisplaySettings().isShowErrors() || !failedTiles.contains(tile.getKey())) { 1221 return null; 1222 } 1223 if (tile.hasError()) { 1224 return Tile.ERROR_IMAGE; 1225 } 1226 if (tile.isLoading() || !tile.isLoaded()) { 1227 return Tile.LOADING_IMAGE; 1228 } 1229 return null; 1230 } 1231 1232 private void paintTileStatus(Tile tile, Graphics2D g) { 1233 BufferedImage statusImage = getTileStatusImage(tile); 1234 if (statusImage != null) { 1235 Rectangle bounds = coordinateConverter.getTileShapeScreen(tile).getBounds(); 1236 g.drawImage(statusImage, bounds.x, bounds.y, bounds.width, bounds.height, null); 1200 1237 } 1201 1238 } … … 1698 1735 // The current zoom tileset should have all of its tiles due to the loadAllTiles(), unless it to tooLarge() 1699 1736 for (Tile t : ts.allExistingTiles()) { 1737 this.paintTileStatus(t, g); 1700 1738 this.paintTileText(t, g); 1701 1739 } -
trunk/test/unit/org/openstreetmap/josm/data/cache/JCSCachedTileLoaderJobTest.java
r19709 r19718 132 132 doTestStatusCode(501); 133 133 doTestStatusCode(502); 134 doTestStatusCode(503); 135 doTestStatusCode(504); 134 136 } 135 137 -
trunk/test/unit/org/openstreetmap/josm/data/imagery/TMSCachedTileLoaderJobTest.java
r19709 r19718 4 4 import static org.junit.jupiter.api.Assertions.assertArrayEquals; 5 5 import static org.junit.jupiter.api.Assertions.assertEquals; 6 import static org.junit.jupiter.api.Assertions.assertFalse; 6 7 import static org.junit.jupiter.api.Assertions.assertNotSame; 7 8 import static org.junit.jupiter.api.Assertions.assertTrue; … … 107 108 private CacheEntryAttributes attributes; 108 109 private boolean ready; 110 private int notifications; 109 111 private byte[] data; 110 112 … … 112 114 public synchronized void tileLoadingFinished(Tile tile, boolean success) { 113 115 ready = true; 116 notifications++; 114 117 this.notifyAll(); 118 } 119 120 synchronized boolean waitForNotifications(int count, long timeoutMillis) throws InterruptedException { 121 long end = System.currentTimeMillis() + timeoutMillis; 122 while (notifications < count) { 123 long remaining = end - System.currentTimeMillis(); 124 if (remaining <= 0) { 125 return false; 126 } 127 wait(remaining); 128 } 129 return true; 115 130 } 116 131 } … … 373 388 assertNotSame(Tile.LOADING_IMAGE, tile.getImage(), "the tile still shows the hourglass"); 374 389 } 390 391 /** 392 * A 5xx response is a transient error: the tile is downloaded again, but only after a delay and a limited number of times. 393 * Until then, the tile stays loaded with its error, so the layer neither shows nothing nor downloads it again at once. 394 * Non-regression test for #25133. 395 * @throws Exception exception 396 */ 397 @Test 398 void testTransientErrorRetriedWithDelay() throws Exception { 399 TMSCachedTileLoaderJob.TRANSIENT_ERROR_RETRY_DELAY.put(50L); 400 final int retries = TMSCachedTileLoaderJob.TRANSIENT_ERROR_RETRIES.get(); 401 wireMockRuntimeInfo.getWireMock().register( 402 WireMock.get(WireMock.urlEqualTo("/error")) 403 .willReturn(WireMock.serverError()) 404 ); 405 MockTile tile = new MockTile(wireMockRuntimeInfo.getHttpBaseUrl() + "/error"); 406 407 for (int attempt = 0; attempt <= retries; attempt++) { 408 // as the layer does at a repaint, download the tile when it is not loaded 409 assertFalse(tile.isLoaded() || tile.isLoading(), "the tile isn't due for a download"); 410 Listener listener = new Listener(); 411 new TestCachedTileLoaderJob(listener, tile, "error").submit(false); 412 assertTrue(listener.waitForNotifications(1, 10_000), "the download didn't finish"); 413 414 wireMockRuntimeInfo.getWireMock().verifyThat(attempt + 1, WireMock.getRequestedFor(WireMock.urlEqualTo("/error"))); 415 assertTrue(tile.hasError(), "the tile doesn't show the error"); 416 assertTrue(tile.isLoaded(), "the tile would be downloaded again at once"); 417 418 if (attempt < retries) { 419 // after the delay, the tile is due for a download again 420 assertTrue(listener.waitForNotifications(2, 10_000), "the tile wasn't retried"); 421 assertFalse(tile.isLoaded(), "the tile wasn't retried"); 422 } else { 423 // no more retries 424 assertFalse(listener.waitForNotifications(2, 50L << retries), "the tile was retried too often"); 425 assertTrue(tile.isLoaded(), "the tile was retried too often"); 426 } 427 } 428 } 375 429 } -
trunk/test/unit/org/openstreetmap/josm/gui/layer/AbstractTileSourceLayerTest.java
r18870 r19718 6 6 import static org.junit.jupiter.api.Assertions.assertFalse; 7 7 import static org.junit.jupiter.api.Assertions.assertNotNull; 8 import static org.junit.jupiter.api.Assertions.assertNull; 9 import static org.junit.jupiter.api.Assertions.assertSame; 8 10 import static org.junit.jupiter.api.Assertions.assertTrue; 9 11 … … 198 200 assertDoesNotThrow(() -> testLayer.new TileSourceLayerPopup(100, 100)); 199 201 } 202 203 /** 204 * Test {@link AbstractTileSourceLayer#getTileStatusImage}: a tile shows the error image or the hourglass only once 205 * it has failed, until it is loaded successfully. Non-regression test for #25133. 206 */ 207 @Test 208 void testTileStatusImage() { 209 Tile tile = new Tile(testLayer.tileSource, 1, 1, 1); 210 tile.initLoading(); 211 assertNull(testLayer.getTileStatusImage(tile), "a tile which never failed shows its normal loading"); 212 213 tile.finishLoading(); 214 tile.setError("HTTP error 503 when loading tiles"); 215 testLayer.tileLoadingFinished(tile, false); 216 assertSame(Tile.ERROR_IMAGE, testLayer.getTileStatusImage(tile)); 217 218 // the retry after a transient error 219 tile.setLoaded(false); 220 assertSame(Tile.ERROR_IMAGE, testLayer.getTileStatusImage(tile)); 221 tile.initLoading(); 222 assertSame(Tile.LOADING_IMAGE, testLayer.getTileStatusImage(tile)); 223 224 testLayer.getDisplaySettings().setShowErrors(false); 225 assertNull(testLayer.getTileStatusImage(tile), "errors are not shown"); 226 testLayer.getDisplaySettings().setShowErrors(true); 227 228 tile.finishLoading(); 229 testLayer.tileLoadingFinished(tile, true); 230 assertNull(testLayer.getTileStatusImage(tile), "a tile loaded successfully shows its image"); 231 232 // after a success, normal loading is shown again 233 tile.initLoading(); 234 assertNull(testLayer.getTileStatusImage(tile)); 235 } 200 236 }
Note:
See TracChangeset
for help on using the changeset viewer.
