Changeset 19718 in josm


Ignore:
Timestamp:
2026-11-29T09:59:39+01:00 (less than one hour ago)
Author:
GerdP
Message:

fix #25133: WMS Continued retries after response 500

  • Improve error handling with WMS (return codes 500,503)
  • tile-retry-backoff.patch by wangi
Location:
trunk
Files:
6 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/org/openstreetmap/josm/data/cache/JCSCachedTileLoaderJob.java

    r19709 r19718  
    99import java.net.URL;
    1010import java.nio.file.Files;
    11 import java.security.SecureRandom;
    1211import java.util.Collections;
    1312import java.util.List;
    … …  
    384383            attributes = parseHeaders(urlConn);
    385384
    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();
    390390                }
    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                        }
    397400                    }
    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);
    411403                }
    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 store
    415                     // as empty (eg. empty tile images) to save some space
    416                     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;
    430422            }
    431423        } catch (FileNotFoundException e) {
    … …  
    450442                return false;
    451443            }
    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        }
    461445    }
    462446
  • trunk/src/org/openstreetmap/josm/data/imagery/TMSCachedTileLoaderJob.java

    r19653 r19718  
    1818import java.util.concurrent.ConcurrentHashMap;
    1919import java.util.concurrent.ConcurrentMap;
     20import java.util.concurrent.Executors;
     21import java.util.concurrent.ScheduledExecutorService;
    2022import java.util.concurrent.ThreadPoolExecutor;
    2123import java.util.concurrent.TimeUnit;
    … …  
    3739import org.openstreetmap.josm.data.imagery.vectortile.VectorTile;
    3840import org.openstreetmap.josm.data.imagery.vectortile.mapbox.MVTFile;
     41import org.openstreetmap.josm.data.preferences.IntegerProperty;
    3942import org.openstreetmap.josm.data.preferences.LongProperty;
    4043import org.openstreetmap.josm.tools.HttpClient;
    … …  
    5356    /** General minimum expires for tiles. Might be overridden by imagery settings */
    5457    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));
    5569    static final Pattern SERVICE_EXCEPTION_PATTERN = Pattern.compile("(?s).+<ServiceException[^>]*>(.+)</ServiceException>.+");
    5670    static final Pattern CDATA_PATTERN = Pattern.compile("(?s)\\s*<!\\[CDATA\\[(.+)\\]\\]>\\s*");
    … …  
    6377    // that way, we reduce calls to tileLoadingFinished, and general CPU load due to surplus Map repaints
    6478    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    });
    6587
    6688    /**
    … …  
    174196    @Override
    175197    public void submit(boolean force) {
     198        if (force) {
     199            retries.remove(getCacheKey());
     200        }
    176201        tile.initLoading();
    177202        try {
    … …  
    207232                    if (httpStatusCode >= 400 && !isNoTileAtZoom()) {
    208233                        status = false;
    209                         handleError(attributes);
     234                        handleError(attributes, listeners);
    210235                    }
    211236                }
    212237                status &= tryLoadTileImage(object); //try to keep returned image as background
     238                if (status) {
     239                    retries.remove(getCacheKey());
     240                }
    213241                break;
    214242            case FAILURE:
    215                 handleError(attributes);
     243                handleError(attributes, listeners);
    216244                tryLoadTileImage(object);
    217245                break;
    … …  
    241269    }
    242270
    243     private void handleError(CacheEntryAttributes attributes) {
     271    private void handleError(CacheEntryAttributes attributes, Set<TileLoaderListener> listeners) {
    244272        if (tile.hasError() && tile.getErrorMessage() != null) {
    245273            // tile has already set error message, don't overwrite it
    … …  
    253281                tile.setError(tr("Error downloading tiles: {0}", attributes.getErrorMessage()));
    254282            }
    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            }
    263289        } else {
    264290            tile.setError(tr("Problem loading tile"));
    265291            // treat unknown errors as permanent and do not try to load tile again
    266292        }
     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);
    267323    }
    268324
  • trunk/src/org/openstreetmap/josm/gui/layer/AbstractTileSourceLayer.java

    r19701 r19718  
    4545import java.util.Set;
    4646import java.util.TreeSet;
     47import java.util.concurrent.ConcurrentHashMap;
    4748import java.util.concurrent.ConcurrentSkipListSet;
    4849import java.util.concurrent.atomic.AtomicInteger;
    … …  
    208209    private final Timer invalidateLaterTimer = new Timer(100, e -> this.invalidate());
    209210
     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
    210214    private final MouseAdapter adapter = new MouseAdapter() {
    211215        @Override
    … …  
    323327            success = false;
    324328            tile.setImage(null);
     329            failedTiles.add(tile.getKey());
     330        } else if (success) {
     331            failedTiles.remove(tile.getKey());
    325332        }
    326333        invalidateLater();
    … …  
    11981205            g.drawString(s, x, y + offset);
    11991206            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);
    12001237        }
    12011238    }
    … …  
    16981735        // The current zoom tileset should have all of its tiles due to the loadAllTiles(), unless it to tooLarge()
    16991736        for (Tile t : ts.allExistingTiles()) {
     1737            this.paintTileStatus(t, g);
    17001738            this.paintTileText(t, g);
    17011739        }
  • trunk/test/unit/org/openstreetmap/josm/data/cache/JCSCachedTileLoaderJobTest.java

    r19709 r19718  
    132132        doTestStatusCode(501);
    133133        doTestStatusCode(502);
     134        doTestStatusCode(503);
     135        doTestStatusCode(504);
    134136    }
    135137
  • trunk/test/unit/org/openstreetmap/josm/data/imagery/TMSCachedTileLoaderJobTest.java

    r19709 r19718  
    44import static org.junit.jupiter.api.Assertions.assertArrayEquals;
    55import static org.junit.jupiter.api.Assertions.assertEquals;
     6import static org.junit.jupiter.api.Assertions.assertFalse;
    67import static org.junit.jupiter.api.Assertions.assertNotSame;
    78import static org.junit.jupiter.api.Assertions.assertTrue;
    … …  
    107108        private CacheEntryAttributes attributes;
    108109        private boolean ready;
     110        private int notifications;
    109111        private byte[] data;
    110112
    … …  
    112114        public synchronized void tileLoadingFinished(Tile tile, boolean success) {
    113115            ready = true;
     116            notifications++;
    114117            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;
    115130        }
    116131    }
    … …  
    373388        assertNotSame(Tile.LOADING_IMAGE, tile.getImage(), "the tile still shows the hourglass");
    374389    }
     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    }
    375429}
  • trunk/test/unit/org/openstreetmap/josm/gui/layer/AbstractTileSourceLayerTest.java

    r18870 r19718  
    66import static org.junit.jupiter.api.Assertions.assertFalse;
    77import static org.junit.jupiter.api.Assertions.assertNotNull;
     8import static org.junit.jupiter.api.Assertions.assertNull;
     9import static org.junit.jupiter.api.Assertions.assertSame;
    810import static org.junit.jupiter.api.Assertions.assertTrue;
    911
    … …  
    198200        assertDoesNotThrow(() -> testLayer.new TileSourceLayerPopup(100, 100));
    199201    }
     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    }
    200236}
Note: See TracChangeset for help on using the changeset viewer.