diff --git a/documentation/en/user/source/configuration/storage.rst b/documentation/en/user/source/configuration/storage.rst
index f47ab11c2d..6310b00848 100644
--- a/documentation/en/user/source/configuration/storage.rst
+++ b/documentation/en/user/source/configuration/storage.rst
@@ -510,3 +510,228 @@ Additional Information:
* The package makes use of the open source multi-cloud toolkit `jclouds `_
* Jclouds documentation for `getting started with Openstack `_
* Jclouds documentation for `OpenStack Keystone V3 Support `_ used in config
+
+In-memory tile cache
+--------------------
+
+The in-memory tile cache keeps the most requested tiles in memory, in front of the blob stores. It is meant for layers whose tiles
+expire quickly and are requested by many clients at once, where reading each tile from disk or from a cloud store costs more than
+rendering time saved. In particular, it allows to share the tiles among all the nodes of a cluster, so that a tile rendered by one
+node is served by every other node until it expires.
+
+The cache is configured once in :file:`geowebcache.xml`, with the ``memoryCache`` element after ``blobStores``, or through the
+:ref:`REST API `, and used by the layers that set ``memoryCached`` to ``true``. For example:
+
+.. code-block:: xml
+
+
+ true
+ 300
+ true
+ 300
+
+ 64
+
+
+
+* **enabled**: whether the cache is used, defaults to ``false``.
+* **timeToLive**: seconds a tile stays in the cache when its layer sets no ``expireCache``, defaults to 300. A layer ``expireCache``
+ applies instead, whether shorter or longer. A tile read from the blob store with passthrough on is kept for what is left of
+ the layer ``expireCache``, and at most ``timeToLive``, so that a read racing a truncate cannot bring back a removed tile for
+ longer than that.
+* **passthrough**: whether tiles are also written to, and read from, the blob store. Defaults to ``true``. When ``false``, tiles live in
+ the cache only, and an expired or evicted tile is rendered again. Truncating a tile, an area or a gridset then leaves the blob store
+ alone, so tiles it still holds from before are kept: truncate the whole layer before turning ``passthrough`` back on.
+* **statsInterval**: seconds between two statistics lines per layer in the log, defaults to 300. ``0`` turns them off.
+* **backend**: where the tiles are kept, named by the ``class`` attribute. Defaults to ``heapKeyValueStore``. When the module of the backend
+ is removed, GeoWebCache still starts: the cache is unusable, with the reason in the log, truncates run on the blob store only, and the
+ backend settings are kept as they are, so that installing the module again restores them.
+
+Each layer opts in with ``memoryCached``, off by default, placed before the layer ``name``:
+
+.. code-block:: xml
+
+
+ true
+ topp:states
+ ...
+
+
+**Nodes sharing one** :file:`geowebcache.xml` **read the** ``memoryCache`` **settings when they start or reload**: after changing them,
+reload or restart every other node. It is to be noted that until then, another node saving its configuration (a blob store or a
+gridset change) writes its old ``memoryCache`` settings back over the change.
+
+Layer metadata and parameter mappings always stay in the blob store. The cache only holds tiles.
+
+When the backend cannot be reached, tiles are served without the cache, and the log reports when the cache goes down and when
+it comes back. A tile request never fails because of the cache. While the cache is down, tile requests do not wait for it: each node
+tries it again from time to time, from every second at the start of the outage up to every 30 seconds for long ones. A cache that keeps
+going down and up again is reported once with its error, then with a short "unreachable again" line each time.
+
+A truncate of a layer using the cache removes its tiles from both the cache and the blob store. **While the cache is down, or when it
+fails to remove the tiles, the truncate is not run at all**, blob store included, and reports an error: retry it once the cache is back,
+since the tiles cached before the outage are served again when it recovers. Deletes of single tiles or bounding boxes, as disk quota
+runs, are the exception with passthrough on: they still delete from the blob store, so that disk quota frees space during a long outage,
+and the copies cached before it are served until they expire. The log reports it once per outage. If the cache fails only after the blob store was truncated, an error is reported and cached tiles may stay stale up to
+their time to live. Removing a layer always deletes its tiles from the blob store, even with the cache down; its cached tiles then expire
+with their time to live. Layers not using the cache are truncated in the blob store as usual, whatever the state of the cache.
+
+Heap backend
+++++++++++++
+
+The ``heapKeyValueStore`` backend keeps tiles in the memory of each node, **not shared** with other nodes. ``maxSizeMB`` (defaults to 64)
+bounds the memory used, the least used tiles are dropped first.
+
+Hazelcast backends
+++++++++++++++++++
+
+The Hazelcast backends keep tiles in a `Hazelcast `_ map, shared by all the nodes. There are two of them:
+
+* ``hazelcastClientKeyValueStore`` connects to a separate Hazelcast cluster, which holds the tiles. Nodes stay small and stateless, and the
+ cluster is sized and restarted on its own.
+* ``hazelcastEmbeddedKeyValueStore`` makes each node a member of the cluster, holding a share of the tiles in its own memory. There is no
+ separate service to run, at the cost of a larger memory footprint per node.
+
+**Hazelcast open source has no authentication nor encryption**. The cluster must only be reachable from the GeoWebCache nodes, for example
+on a private network or with network policies, as anyone reaching it can read and change the tiles.
+
+Client backend
+~~~~~~~~~~~~~~
+
+.. code-block:: xml
+
+
+ dev
+ hazelcast-1:5701, hazelcast-2:5701
+ gwc-tiles
+
+
+* **clusterName**: the name of the cluster, defaults to ``gwc``.
+* **members**: comma separated ``host:port`` list of cluster members to connect to, defaults to ``localhost:5701``. One reachable member
+ is enough, the client then finds the others.
+* **mapName**: the map holding the tiles, defaults to ``gwc-tiles``. It must be declared on the cluster, see below.
+
+**clusterName and members apply on restart only**: the client connects once, the first time the cache is used, and keeps that
+connection until GeoWebCache stops. Saving new values, or reloading the configuration, does not change it. ``mapName`` applies on save.
+
+GeoWebCache starts even when the cluster is down. Tiles are then served without the cache, and the client keeps trying to connect in the
+background, waiting up to 30 seconds between attempts. Reading or writing a tile gives up after 2 seconds, and the cache is then treated
+as down; each cluster call of a truncate gives up after 10 seconds, and the truncate then reports an error. The limits can be changed with
+the ``GWC_MEMORYCACHE_CALL_TIMEOUT`` and ``GWC_MEMORYCACHE_BULK_TIMEOUT`` system properties, servlet context parameters or environment
+variables, in milliseconds. Copying a tile read from the blob store into the cache, with passthrough on, follows the tile limit too, and
+is skipped while too many copies are still waiting on a member that stopped answering. The cluster-wide locks have no such limit: they
+wait until the connection is declared dead, 60 seconds by default.
+
+For settings not covered above, such as discovery or timeouts, a :file:`hazelcast-client.xml` file can be placed in the same directory as
+:file:`geowebcache.xml`. When present, it **replaces** ``clusterName``, ``members`` and the connection defaults, following the
+`Hazelcast client configuration `_. It is to be noted that
+the client always starts in the background and retries forever, whatever the file says, so that an unreachable cluster never stops
+GeoWebCache: a finite ``cluster-connect-timeout-millis`` is ignored, with a warning in the log. ``mapName`` is still taken from
+:file:`geowebcache.xml`. The file also keeps the 5 seconds request timeout and the retry ``multiplier`` (2) and ``jitter`` (0.2) of
+the cache, unless it sets ``hazelcast.client.invocation.timeout.seconds``, ``multiplier`` or ``jitter`` itself. Changes to the file
+apply on restart only.
+
+Embedded backend
+~~~~~~~~~~~~~~~~
+
+.. code-block:: xml
+
+
+ gwc-tiles
+
+
+* **mapName**: the map holding the tiles, defaults to ``gwc-tiles``.
+
+The member is configured by a :file:`hazelcast.xml` file, **mandatory**, in the same directory as :file:`geowebcache.xml`, following the
+`Hazelcast member configuration `_. Changes to the file
+apply on restart.
+
+It is to be noted that the member joins the cluster in the background when the cache is first used. Tile requests do not wait for it, they
+are served without the cache until the member has joined, and the log reports the cache unreachable then reachable again. A missing
+file, or a file not declaring the map, leaves the cache unusable, with the reason in the log, while tiles keep being served without it.
+A member that fails to start, or stops later, for example after running out of memory or through a cluster shutdown, is started again
+when the cache is next tried, at most every 30 seconds.
+
+The following example fits a Kubernetes deployment, where members find each other through a service. The pods need permission to read
+endpoints and pods in their namespace:
+
+.. code-block:: xml
+
+
+ gwc
+
+
+
+
+ gwc
+ gwc-hazelcast
+
+
+
+
+
+
+Declaring the map
+~~~~~~~~~~~~~~~~~
+
+With both backends, the map must be declared in the cluster configuration with an eviction policy and a size bound. **A map without
+them grows until the members run out of memory**, as Hazelcast keeps every entry by default. The embedded backend refuses to start on an
+undeclared map. The client backend cannot check it, so the cluster configuration must be reviewed by hand.
+
+The time to live does not need to be declared, as each tile is stored with its own.
+
+``backup-count`` sets how many other members keep a copy of each tile. With ``1``, losing a member loses no tiles, at the cost of twice
+the memory. With ``0``, tiles of a lost member are rendered again.
+
+The first truncate adds a sorted index on the map keys, so that removing the tiles of a layer, gridset or parameter set looks up the
+matching keys instead of reading every tile on the members. The index costs some memory per tile on the members and a little time on
+every write, so size the members for it: an entry count limit does not account for it. To keep the cluster configuration under your
+control, declare it with the map instead:
+
+.. code-block:: xml
+
+
+
+An index added by GeoWebCache is lost when the whole cluster restarts, and added again by the next truncate. If it cannot be added, for
+example when the cluster configuration refuses it, truncates still run without it, reading every tile on the members, with a warning in
+the log, and the next truncate tries again.
+
+Truncating a bounding box reads the keys of each affected zoom level, for one parameter set and format, into the memory of the node doing
+it, and removes the tiles inside the box. **Above 100,000 tiles in a zoom level it removes the whole zoom level instead**, with a line in
+the log, so that the node memory stays bounded: the extra tiles are rendered again when requested. The limit can be changed with the
+``GWC_MEMORYCACHE_MATCHING_LIMIT`` system property, servlet context parameter or environment variable, ``0`` always removing the whole
+zoom level; it applies when the cache settings are next saved or on restart.
+
+Cluster-wide tile locks
+~~~~~~~~~~~~~~~~~~~~~~~
+
+When a tile is missing, a node renders its whole metatile, and other requests for the same metatile on that node wait for it. Separate
+nodes do not: when several of them miss the same metatile at once, for example right after its tiles expired, each of them renders it.
+With a Hazelcast backend, the nodes can lock on the cluster instead, so that one node renders the metatile and the others wait, then serve
+its tiles from the shared cache. Name ``hazelcastLock`` as the lock provider in :file:`geowebcache.xml`, after ``backendTimeout``:
+
+.. code-block:: xml
+
+ 120
+ hazelcastLock
+
+* **It needs the cache enabled with a Hazelcast backend**, as the locks are kept on the same cluster, in a map named after the tile map
+ with a ``.locks`` suffix, ``gwc-tiles.locks`` by default, which needs no declaration. Otherwise each node locks on its own, with a
+ warning in the log. Switching the cache to another backend takes the nodes back to their own locks as soon as the settings are saved.
+* A node never fails a request because of these locks. When the cluster cannot be reached, or while the cache considers it down after a
+ failed call, nodes lock on their own at once until it is back, and a metatile may then be rendered once per node. A node waits for a lock at most the number of seconds set by the ``GWC_LOCK_TIMEOUT``
+ system property, 120 by default, then goes on anyway with a warning in the log. A node stopping while it holds a lock keeps it at most
+ that long.
+* It is to be noted that the blob stores use the same lock provider. **The S3 blob store holds a lock for the whole of a bulk delete**,
+ often longer than ``GWC_LOCK_TIMEOUT``, so the lock can expire under it and another node can start the same delete meanwhile.
diff --git a/documentation/en/user/source/rest/index.rst b/documentation/en/user/source/rest/index.rst
index 778032c80e..554a8f23ae 100644
--- a/documentation/en/user/source/rest/index.rst
+++ b/documentation/en/user/source/rest/index.rst
@@ -15,6 +15,7 @@ This section will discuss the GeoWebCache REST API.
seed.rst
diskquota.rst
masstruncate.rst
+ memorycache.rst
diff --git a/documentation/en/user/source/rest/memorycache.rst b/documentation/en/user/source/rest/memorycache.rst
new file mode 100644
index 0000000000..b41edc4b1b
--- /dev/null
+++ b/documentation/en/user/source/rest/memorycache.rst
@@ -0,0 +1,83 @@
+.. _rest.memorycache:
+
+Managing the In-memory Tile Cache through the REST API
+======================================================
+
+The REST API for the in-memory tile cache allows to view and replace its settings, the ``memoryCache`` element of
+:file:`geowebcache.xml` described in :ref:`configuration.storage`.
+
+Operations
+----------
+
+``/rest/memorycache``
+
+.. list-table::
+ :header-rows: 1
+
+ * - Method
+ - Action
+ - Return Code
+ - Formats
+ * - GET
+ - Return the saved settings
+ - 200
+ - XML, JSON
+ * - POST
+ -
+ - 405
+ -
+ * - PUT
+ - Replace the settings
+ - 200, 400
+ - XML, JSON
+ * - DELETE
+ -
+ - 405
+ -
+
+GET returns the settings as saved: a value missing from the response takes its default.
+
+PUT replaces all the settings, **a value left out goes back to its default**, it does not keep its current value. Changing the
+settings empties the cache, while sending the same settings again leaves it as it is. Settings the cache could not start with,
+a ``timeToLive`` below 1 or a ``backend`` class that is not installed, are rejected with a 400 and not saved.
+
+The ``backend`` element takes the same ``class`` and settings as in :file:`geowebcache.xml`, for example ``hazelcastClientKeyValueStore``
+for the Hazelcast client backend when that module is installed. Saving does not connect to the backend: it is reached the next time the
+cache is used, and an unreachable one is then reported in the log.
+
+As for any other change of :file:`geowebcache.xml`, other nodes sharing the file only see the new settings after a reload or a restart.
+
+cURL Examples
+-------------
+
+Get the settings:
+
+.. code-block:: bash
+
+ curl -u geowebcache:secured "http://localhost:8080/geowebcache/rest/memorycache.xml"
+
+Or if using the GeoServer integrated version of GeoWebCache:
+
+.. code-block:: bash
+
+ curl -u user:password "http://localhost:8080/geoserver/gwc/rest/memorycache.xml"
+
+Given a :file:`memorycache.xml` file as the following:
+
+.. code-block:: xml
+
+
+ true
+ 120
+
+ 256
+
+
+
+replace the settings with:
+
+.. code-block:: bash
+
+ curl -u geowebcache:secured -XPUT -H "Content-type: text/xml" -d @memorycache.xml "http://localhost:8080/geowebcache/rest/memorycache.xml"
+
+This turns the cache on, with tiles kept 120 seconds in up to 256 MB of heap, and ``passthrough`` and ``statsInterval`` back to their defaults.
diff --git a/geowebcache/azureblob/src/main/java/org/geowebcache/azure/AzureBlobStore.java b/geowebcache/azureblob/src/main/java/org/geowebcache/azure/AzureBlobStore.java
index 530fbafd6b..c935b12ef4 100644
--- a/geowebcache/azureblob/src/main/java/org/geowebcache/azure/AzureBlobStore.java
+++ b/geowebcache/azureblob/src/main/java/org/geowebcache/azure/AzureBlobStore.java
@@ -372,7 +372,8 @@ private String getMimeType(TileObject obj) {
return mimeType;
}
- private void putParametersMetadata(String layerName, String parametersId, Map parameters) {
+ @Override
+ public void putParametersMetadata(String layerName, String parametersId, Map parameters) {
assert (isNull(parametersId) == isNull(parameters));
if (isNull(parametersId)) {
return;
diff --git a/geowebcache/core/src/main/java/org/geowebcache/config/GeoWebCacheConfiguration.java b/geowebcache/core/src/main/java/org/geowebcache/config/GeoWebCacheConfiguration.java
index ff7487b528..65c1125d25 100644
--- a/geowebcache/core/src/main/java/org/geowebcache/config/GeoWebCacheConfiguration.java
+++ b/geowebcache/core/src/main/java/org/geowebcache/config/GeoWebCacheConfiguration.java
@@ -21,6 +21,7 @@
import org.geowebcache.locks.LockProvider;
import org.geowebcache.locks.MemoryLockProvider;
import org.geowebcache.mime.FormatModifier;
+import org.geowebcache.storage.memorycache.MemoryCacheInfo;
/**
* POJO for geowebcache.xml configuration
@@ -70,6 +71,9 @@ public class GeoWebCacheConfiguration {
private List blobStores;
+ // volatile, as tile requests read it while a save replaces it; the instance is never changed once set
+ private volatile MemoryCacheInfo memoryCache;
+
private List gridSets;
private Boolean fullWMS;
@@ -226,6 +230,16 @@ public List getBlobStores() {
return blobStores;
}
+ /** The {@code } settings, null when the element is absent. */
+ public MemoryCacheInfo getMemoryCache() {
+ return memoryCache;
+ }
+
+ /** Replaces the {@code } settings, null removes the element. */
+ public void setMemoryCache(MemoryCacheInfo memoryCache) {
+ this.memoryCache = memoryCache;
+ }
+
/** @return the gridSets */
public List getGridSets() {
return gridSets;
diff --git a/geowebcache/core/src/main/java/org/geowebcache/config/ServerConfiguration.java b/geowebcache/core/src/main/java/org/geowebcache/config/ServerConfiguration.java
index e9ae405436..f73ffb941d 100644
--- a/geowebcache/core/src/main/java/org/geowebcache/config/ServerConfiguration.java
+++ b/geowebcache/core/src/main/java/org/geowebcache/config/ServerConfiguration.java
@@ -16,6 +16,7 @@
import java.io.IOException;
import org.geowebcache.config.meta.ServiceInformation;
import org.geowebcache.locks.LockProvider;
+import org.geowebcache.storage.memorycache.MemoryCacheInfo;
/**
* Interface for managing global server configuration information.
@@ -55,6 +56,11 @@ public interface ServerConfiguration extends BaseConfiguration {
/** Set the lock provider for this configuration. */
void setLockProvider(LockProvider lockProvider) throws IOException;
+ /** The tile cache settings, or null when this configuration does not hold them. */
+ default MemoryCacheInfo getMemoryCache() {
+ return null;
+ }
+
/**
* Used for getting the "fullWMS" parameter from GeoWebCacheConfigration if present
*
diff --git a/geowebcache/core/src/main/java/org/geowebcache/config/XMLConfiguration.java b/geowebcache/core/src/main/java/org/geowebcache/config/XMLConfiguration.java
index 381b789808..abfa812bce 100644
--- a/geowebcache/core/src/main/java/org/geowebcache/config/XMLConfiguration.java
+++ b/geowebcache/core/src/main/java/org/geowebcache/config/XMLConfiguration.java
@@ -87,6 +87,9 @@
import org.geowebcache.seed.TruncateLayerRequest;
import org.geowebcache.storage.DefaultStorageFinder;
import org.geowebcache.storage.UnsuitableStorageException;
+import org.geowebcache.storage.memorycache.HeapKeyValueStoreInfo;
+import org.geowebcache.storage.memorycache.MemoryCacheInfo;
+import org.geowebcache.storage.memorycache.UnresolvedKeyValueStoreInfo;
import org.geowebcache.util.ApplicationContextProvider;
import org.geowebcache.util.ExceptionUtils;
import org.geowebcache.util.URLs;
@@ -374,6 +377,9 @@ public static XStream getConfiguredXStreamWithContext(
xs.alias("blobStores", new ArrayList().getClass());
xs.alias("FileBlobStore", FileBlobStoreInfo.class);
+ xs.alias("heapKeyValueStore", HeapKeyValueStoreInfo.class);
+ // a removed backend module must not fail the whole configuration
+ UnresolvedKeyValueStoreInfo.register(xs);
xs.aliasAttribute(BlobStoreInfo.class, "_default", "default");
// Alias added to retain XML backwards-compatibility.
// TODO: Would be nice to be able to use name for consistency
@@ -1246,6 +1252,17 @@ public void setLockProvider(LockProvider lockProvider) throws IOException {
save();
}
+ @Override
+ public MemoryCacheInfo getMemoryCache() {
+ return getGwcConfig().getMemoryCache();
+ }
+
+ /** Saves the tile cache settings; pass a new instance, the cache is rebuilt only when the instance changes. */
+ public void setMemoryCache(MemoryCacheInfo memoryCache) throws IOException {
+ getGwcConfig().setMemoryCache(memoryCache);
+ save();
+ }
+
private GeoWebCacheConfiguration getGwcConfig() {
try {
if (gwcConfig == null) {
diff --git a/geowebcache/core/src/main/java/org/geowebcache/layer/AbstractTileLayer.java b/geowebcache/core/src/main/java/org/geowebcache/layer/AbstractTileLayer.java
index 6cdaf7ffdf..3e8fc9b7de 100644
--- a/geowebcache/core/src/main/java/org/geowebcache/layer/AbstractTileLayer.java
+++ b/geowebcache/core/src/main/java/org/geowebcache/layer/AbstractTileLayer.java
@@ -51,6 +51,8 @@ public abstract class AbstractTileLayer extends TileLayer {
@Nullable
protected String blobStoreId;
+ protected Boolean memoryCached;
+
protected Boolean enabled;
protected Boolean advertised;
@@ -159,6 +161,16 @@ public void setBlobStoreId(@Nullable String blobStoreId) {
this.blobStoreId = blobStoreId;
}
+ @Override
+ public boolean isMemoryCached() {
+ return Boolean.TRUE.equals(memoryCached);
+ }
+
+ /** Sets whether the tiles of this layer go through the in-memory tile cache. */
+ public void setMemoryCached(boolean memoryCached) {
+ this.memoryCached = memoryCached;
+ }
+
/** Then name of the layer */
@Override
public String getName() {
diff --git a/geowebcache/core/src/main/java/org/geowebcache/layer/TileLayer.java b/geowebcache/core/src/main/java/org/geowebcache/layer/TileLayer.java
index 786ce3dda9..7963a69fbf 100644
--- a/geowebcache/core/src/main/java/org/geowebcache/layer/TileLayer.java
+++ b/geowebcache/core/src/main/java/org/geowebcache/layer/TileLayer.java
@@ -94,6 +94,11 @@ public abstract class TileLayer implements Info {
public abstract void setBlobStoreId(@Nullable String blobStoreId);
+ /** Whether the tiles of this layer go through the in-memory tile cache, when one is configured. */
+ public boolean isMemoryCached() {
+ return false;
+ }
+
/** Then name of the layer */
@Override
public abstract String getName();
diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/BlobStore.java b/geowebcache/core/src/main/java/org/geowebcache/storage/BlobStore.java
index 1f469aea7d..fb1350d5b0 100644
--- a/geowebcache/core/src/main/java/org/geowebcache/storage/BlobStore.java
+++ b/geowebcache/core/src/main/java/org/geowebcache/storage/BlobStore.java
@@ -163,6 +163,15 @@ public default Set getParameterIds(String layerName) throws StorageExcep
*/
Map>> getParametersMapping(String layerName);
+ /**
+ * Records the parameter combination used by a tile, so that {@link #getParametersMapping} lists it. Called from
+ * {@link #put(TileObject)}, and by a cache whose tiles do not reach this store.
+ */
+ default void putParametersMetadata(String layerName, String parametersId, Map parameters)
+ throws StorageException {
+ // stores that do not track parameter mappings ignore this
+ }
+
/** If the given layer is cached, remove */
public default boolean purgeOrphans(TileLayer layer) throws StorageException {
// TODO maybe do purging based on gridset and format
diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/CompositeBlobStore.java b/geowebcache/core/src/main/java/org/geowebcache/storage/CompositeBlobStore.java
index c3dfa365cc..9ed5ae21bb 100644
--- a/geowebcache/core/src/main/java/org/geowebcache/storage/CompositeBlobStore.java
+++ b/geowebcache/core/src/main/java/org/geowebcache/storage/CompositeBlobStore.java
@@ -18,6 +18,7 @@
import com.google.common.base.Strings;
import java.util.HashMap;
import java.util.Map;
+import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@@ -39,6 +40,8 @@
import org.geowebcache.layer.TileLayerDispatcher;
import org.geowebcache.locks.LockProvider;
import org.geowebcache.storage.blobstore.file.FileBlobStore;
+import org.geowebcache.storage.memorycache.MemoryCache;
+import org.geowebcache.storage.memorycache.MemoryCacheInfo;
/**
* A composite {@link BlobStore} that multiplexes tile operations to configured blobstores based on
@@ -78,6 +81,10 @@ public class CompositeBlobStore implements BlobStore, BlobStoreConfigurationList
private final BlobStoreListenerList listeners = new BlobStoreListenerList();
+ private final ServerConfiguration serverConfiguration;
+
+ private volatile MemoryCache memoryCache;
+
@VisibleForTesting
static final class LiveStore {
BlobStoreInfo config;
@@ -137,6 +144,7 @@ public CompositeBlobStore(
this.layers = layers;
this.defaultStorageFinder = defaultStorageFinder;
this.lockProvider = serverConfiguration.getLockProvider();
+ this.serverConfiguration = serverConfiguration;
this.blobStoreConfigs = blobStoreAggregator;
StoreSuitabilityCheck oldCheck = storeSuitability.get();
// Disable suitability checks when loading during startup.
@@ -188,6 +196,7 @@ public void clear() throws StorageException {
@Override
public synchronized void destroy() {
destroy(blobStores);
+ if (memoryCache != null) memoryCache.close();
}
private void destroy(Map blobStores) {
@@ -235,15 +244,19 @@ public boolean removeListener(BlobStoreListener listener) {
@Override
public boolean rename(String oldLayerName, String newLayerName) throws StorageException {
return readFunctionUnsafe(() -> {
+ boolean renamed = false;
for (LiveStore bs : blobStores.values()) {
BlobStoreInfo config = bs.config;
if (config.isEnabled()) {
if (bs.liveInstance.rename(oldLayerName, newLayerName)) {
- return true;
+ renamed = true;
+ break;
}
}
}
- return false;
+ // even when no store had tiles, as with passthrough off they are all in the cache
+ memoryCache().layerRenamed(oldLayerName, newLayerName);
+ return renamed;
});
}
@@ -267,9 +280,11 @@ public boolean layerExists(String layerName) {
private BlobStore store(String layerId) throws StorageException {
+ TileLayer layer;
LiveStore store;
try {
- store = forLayer(layerId);
+ layer = layers.getTileLayer(layerId);
+ store = forLayer(layer);
} catch (GeoWebCacheException e) {
throw new StorageException(e.getMessage(), e);
}
@@ -277,20 +292,27 @@ private BlobStore store(String layerId) throws StorageException {
throw new StorageException("Attempted to use a blob store that's disabled: " + store.config.getName());
}
- return store.liveInstance;
+ return memoryCache().wrap(layer, store.liveInstance);
+ }
+
+ /** The cache for the current settings, rebuilt when they change, closing the previous one. */
+ private MemoryCache memoryCache() {
+ // a reload replaces the settings with equal ones, which must keep the cached tiles and the connection;
+ // Objects.equals checks identity first, so the per-request check stays cheap
+ MemoryCacheInfo info = serverConfiguration.getMemoryCache();
+ MemoryCache cache = memoryCache;
+ if (cache != null && Objects.equals(cache.getInfo(), info)) return cache;
+ synchronized (this) {
+ MemoryCache previous = memoryCache;
+ if (previous != null && Objects.equals(previous.getInfo(), info)) return previous;
+ memoryCache = new MemoryCache(info, layers);
+ if (previous != null) previous.close();
+ return memoryCache;
+ }
}
- /**
- * @throws StorageException if the blobstore is not enabled or does not exist
- * @throws GeoWebCacheException if the layer is not found
- */
- private LiveStore forLayer(String layerName) throws StorageException, GeoWebCacheException {
- TileLayer layer;
- try {
- layer = layers.getTileLayer(layerName);
- } catch (GeoWebCacheException e) {
- throw e;
- }
+ /** @throws StorageException if the blobstore is not enabled or does not exist */
+ private LiveStore forLayer(TileLayer layer) throws StorageException {
String storeId = layer.getBlobStoreId();
LiveStore store;
if (null == storeId) {
diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/blobstore/file/FileBlobStore.java b/geowebcache/core/src/main/java/org/geowebcache/storage/blobstore/file/FileBlobStore.java
index 3eb201cd78..94ca16d167 100644
--- a/geowebcache/core/src/main/java/org/geowebcache/storage/blobstore/file/FileBlobStore.java
+++ b/geowebcache/core/src/main/java/org/geowebcache/storage/blobstore/file/FileBlobStore.java
@@ -489,13 +489,16 @@ public void put(TileObject stObj) throws StorageException {
}
}
- private void putParametersMetadata(String layerName, String parametersId, Map parameters)
+ @Override
+ public void putParametersMetadata(String layerName, String parametersId, Map parameters)
throws StorageException {
// check if we even need to use any IO
if (parametersId == null || parameters == null || parameters.isEmpty()) return;
File parametersFile = parametersFile(layerName, parametersId);
if (parametersFile.exists()) return;
+ // a tile put creates the layer directory, a tile cache with passthrough off never does
+ parametersFile.getParentFile().mkdirs();
writeFile(parametersFile, false, file -> {
Properties properties = new Properties();
@@ -820,10 +823,9 @@ private static Map propertiesToMap(Properties properties) {
@Override
public Set getParameterIds(String layerName) {
- try (Stream layerChildStream = layerChildStream(layerName, (p) -> Files.isDirectory(p))) {
+ try (Stream layerChildStream = layerChildStream(layerName, p -> true)) {
return layerChildStream
- .map(p -> p.getFileName().toString())
- .map(s -> s.substring(s.lastIndexOf('_') + 1))
+ .map(FileBlobStore::parameterId)
.filter(s -> s.length() == paramIdLength) // Zoom level should never be the same
// length so this should be safe
.collect(Collectors.toSet());
@@ -831,4 +833,16 @@ public Set getParameterIds(String layerName) {
throw new UncheckedIOException(e);
}
}
+
+ /** The id ending a tile directory name, or held in a mapping file name; empty for any other file. */
+ private static String parameterId(Path child) {
+ String name = child.getFileName().toString();
+ if (Files.isDirectory(child)) return name.substring(name.lastIndexOf('_') + 1);
+ // mapping files exist without tile directories when a tile cache keeps the tiles
+ if (!name.startsWith(PARAMETERS_METADATA_OBJECT_PREFIX) || !name.endsWith(PARAMETERS_METADATA_OBJECT_SUFFIX)) {
+ return "";
+ }
+ return name.substring(
+ PARAMETERS_METADATA_OBJECT_PREFIX.length(), name.length() - PARAMETERS_METADATA_OBJECT_SUFFIX.length());
+ }
}
diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/CachingBlobStore.java b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/CachingBlobStore.java
new file mode 100644
index 0000000000..11c33e3d59
--- /dev/null
+++ b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/CachingBlobStore.java
@@ -0,0 +1,512 @@
+/**
+ * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General
+ * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
+ * later version.
+ *
+ *
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
+ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+ *
+ *
You should have received a copy of the GNU Lesser General Public License along with this program. If not, see
+ * .
+ *
+ *
Cache failures never fail a tile request: a failed read is a miss, a failed write is dropped. A truncate of a
+ * memory cached layer fails before the store while the cache is down or refuses the removal; a layer removal deletes
+ * the store anyway, then throws.
+ */
+class CachingBlobStore implements BlobStore {
+
+ private static final Logger LOGGER = Logging.getLogger(CachingBlobStore.class.getName());
+
+ // value layout: format version, creation time in epoch millis, tile bytes
+ private static final byte FORMAT_VERSION = 1;
+
+ private static final int HEADER_SIZE = Byte.BYTES + Long.BYTES;
+
+ /** Returned by {@link #cacheGet} when the cache failed, told apart from a miss by identity. */
+ private static final byte[] FAILED = {};
+
+ /**
+ * Locks of the parameter mapping writes, by layer id and parameters id; static, so that a cache rebuilt by a
+ * settings save and the one it replaces do not write the same mapping at once.
+ */
+ private static final Striped MAPPING_LOCKS = Striped.lazyWeakLock(256);
+
+ private final BlobStore delegate;
+
+ private final MemoryCache cache;
+
+ private final TMSKeyBuilder keys;
+
+ private final TileLayer layer;
+
+ /** Whether the layer's tiles go through the cache, false when only its bulk truncates do. */
+ private final boolean cached;
+
+ /** Null when not {@link #cached}. */
+ private final LayerStats stats;
+
+ /** Every tile operation must target {@code layer}. */
+ CachingBlobStore(BlobStore delegate, MemoryCache cache, TileLayer layer, boolean cached) {
+ this.delegate = delegate;
+ this.cache = cache;
+ this.keys = cache.getKeys();
+ this.layer = layer;
+ this.cached = cached;
+ this.stats = cached ? cache.getStats().forLayer(layer.getName()) : null;
+ }
+
+ /** True when the store behind holds the tiles: passthrough on, or a layer not using the cache. */
+ private boolean storeHoldsTiles() {
+ return cache.isPassthrough() || !cached;
+ }
+
+ @Override
+ public boolean get(TileObject obj) throws StorageException {
+ if (!cached) return delegate.get(obj);
+ long start = System.nanoTime();
+ String key = keys.forTile(obj, layer.getId());
+ Result result = decode(obj, cacheGet(key));
+ boolean found = result == HIT || result == EXPIRED;
+ if (!found && cache.isPassthrough() && delegate.get(obj)) {
+ // never over a newer tile a concurrent put cached meanwhile
+ cachePut(key, obj, obj.getCreated(), true);
+ found = true;
+ // a failed cache read stays an error even when the store had the tile
+ if (result == MISS) result = STORE;
+ }
+ stats.read(result);
+ logRead(obj, result, start);
+ cache.getStats().report();
+ return found;
+ }
+
+ /** Fills {@code obj} from a cache value, which is null on a miss and {@link #FAILED} when the read failed. */
+ private Result decode(TileObject obj, byte[] value) {
+ if (value == FAILED) return ERROR;
+ if (value == null || value.length < HEADER_SIZE || value[0] != FORMAT_VERSION) return MISS;
+ long created = ByteBuffer.wrap(value, 1, Long.BYTES).getLong();
+ obj.setCreated(created);
+ int length = value.length - HEADER_SIZE;
+ // the offset constructor rejects an empty tile
+ obj.setBlob(
+ length > 0 ? new ByteArrayResource(value, HEADER_SIZE, length) : new ByteArrayResource(new byte[0]));
+ // the time to live already ends there, unless the writing node's clock is behind this one
+ int expireCache = expireCache(obj);
+ return expireCache > 0 && System.currentTimeMillis() - created > expireCache * 1000L ? EXPIRED : HIT;
+ }
+
+ private static void logRead(TileObject obj, Result result, long start) {
+ long[] xyz = obj.getXYZ();
+ LOGGER.fine(() -> String.format(
+ Locale.ROOT,
+ "In-memory tile cache %s for layer %s, gridset %s, z/x/y %d/%d/%d in %.2f ms",
+ result.name().toLowerCase(Locale.ROOT),
+ obj.getLayerName(),
+ obj.getGridSetId(),
+ xyz[2],
+ xyz[0],
+ xyz[1],
+ (System.nanoTime() - start) / 1_000_000.0));
+ }
+
+ @Override
+ public void put(TileObject obj) throws StorageException {
+ if (!cached) {
+ delegate.put(obj);
+ return;
+ }
+ // first, as building the key also sets the parameters id the mapping write needs
+ String key = keys.forTile(obj, layer.getId());
+ if (cache.isPassthrough()) {
+ delegate.put(obj);
+ } else {
+ putParametersMetadataOnce(obj, key);
+ }
+ cachePut(key, obj, System.currentTimeMillis(), false);
+ cache.getStats().report();
+ }
+
+ /**
+ * Writes the mapping the store behind would record on put, unless the cache holds a marker saying it is there.
+ * Never throws: a failed write is retried by the next put of the parameter set.
+ */
+ private void putParametersMetadataOnce(TileObject obj, String tileKey) {
+ String parametersId = obj.getParametersId();
+ if (parametersId == null) return;
+ // shared by every node: a truncate removing the mapping from the store removes the marker with the tiles
+ String marker = markerKey(tileKey, parametersId);
+ byte[] storeId = String.valueOf(layer.getBlobStoreId()).getBytes(UTF_8);
+ Lock lock = MAPPING_LOCKS.get(layer.getId() + "/" + parametersId);
+ // one check at a time: the tiles of a metatile are saved in parallel, and concurrent writers of one file make
+ // it briefly disappear on Windows, where a rename deletes the target first; the marker is written before the
+ // lock is released, so the threads waiting on it find the marker and return
+ lock.lock();
+ try {
+ byte[] written = cacheGet(marker);
+ // with the cache down the tile is not cached either, so it needs no mapping
+ if (written == FAILED || Arrays.equals(written, storeId)) return;
+ delegate.putParametersMetadata(obj.getLayerName(), parametersId, obj.getParameters());
+ cacheWrite(marker, storeId, cache.getTtlSeconds(), false);
+ if (cache.getMappingWritesFailing().compareAndSet(true, false)) {
+ LOGGER.severe("In-memory tile cache records parameter mappings in the blob stores again");
+ }
+ } catch (StorageException | RuntimeException e) {
+ // the tile is cached anyway: failing the put would render every request while the store is down
+ if (cache.getMappingWritesFailing().compareAndSet(false, true)) {
+ // SEVERE as the outage lines, production logging keeps org.geowebcache at error
+ String message = "In-memory tile cache could not record parameters " + parametersId + " of layer "
+ + obj.getLayerName() + " in its blob store, retrying on the next tiles: until then truncates"
+ + " by parameters or bounding box miss the tiles cached meanwhile";
+ LOGGER.log(Level.SEVERE, message, e);
+ }
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ /**
+ * The marker of a parameter set mapping, {@code ////mapping}: under the
+ * prefixes of layer, gridset and parameters truncates, outside those of the zoom levels a bounding box truncate
+ * removes.
+ */
+ private static String markerKey(String tileKey, String parametersId) {
+ String segment = "/" + parametersId + "/";
+ return tileKey.substring(0, tileKey.indexOf(segment) + segment.length()) + "mapping";
+ }
+
+ private byte[] cacheGet(String key) {
+ try {
+ return cache.getStore().get(key);
+ } catch (RuntimeException e) {
+ // logged by the guarded store, once per outage
+ return FAILED;
+ }
+ }
+
+ /**
+ * Caches the tile. A read through from the store is capped at the global time to live: read before a concurrent
+ * truncate, it can land after it, and must not be served for the layer's whole expire server cache.
+ */
+ private void cachePut(String key, TileObject obj, long created, boolean readThrough) {
+ long ttl = ttlSeconds(obj, created);
+ if (readThrough) ttl = Math.min(ttl, cache.getTtlSeconds());
+ // a tile read through from the store can be already past the layer's expire server cache
+ if (ttl <= 0) return;
+ byte[] value;
+ try {
+ value = encode(obj.getBlob(), created);
+ } catch (IOException e) {
+ // a lazy store resource whose file a truncate removed after the read
+ LOGGER.log(Level.FINE, "Could not read tile " + key + " to cache it", e);
+ stats.failedPut();
+ return;
+ }
+ if (!cacheWrite(key, value, ttl, readThrough)) stats.failedPut();
+ }
+
+ /** Writes a value, unless present when {@code ifAbsent}, returning false when the cache failed. */
+ private boolean cacheWrite(String key, byte[] value, long ttl, boolean ifAbsent) {
+ try {
+ if (ifAbsent) cache.getStore().putIfAbsent(key, value, ttl);
+ else cache.getStore().put(key, value, ttl);
+ return true;
+ } catch (RuntimeException e) {
+ return false;
+ }
+ }
+
+ // reads the stream rather than trusting the declared size, which a lazy resource computes apart from its content
+ private static byte[] encode(Resource blob, long created) throws IOException {
+ try (InputStream in = blob.getInputStream()) {
+ byte[] tile = in.readAllBytes();
+ return ByteBuffer.allocate(HEADER_SIZE + tile.length)
+ .put(FORMAT_VERSION)
+ .putLong(created)
+ .put(tile)
+ .array();
+ }
+ }
+
+ /**
+ * What is left of the layer's expire server cache since {@code created}, or the global time to live when the layer
+ * sets none. Zero or negative when nothing is left.
+ */
+ private long ttlSeconds(TileObject obj, long created) {
+ int expireCache = expireCache(obj);
+ if (expireCache <= 0) return cache.getTtlSeconds();
+ // not capped by the global time to live: a tile evicted before its expiry would only be rendered again
+ return expireCache - MILLISECONDS.toSeconds(System.currentTimeMillis() - created);
+ }
+
+ /** The layer's expire server cache in seconds at the tile's zoom level, positive only when the layer sets one. */
+ private int expireCache(TileObject obj) {
+ // zero and negative values are "unset", "never expire" or "use the backend value"
+ return layer.getExpireCache((int) obj.getXYZ()[2]);
+ }
+
+ @Override
+ public boolean delete(String layerName) throws StorageException {
+ String prefix = keys.forLayer(layerName);
+ Consumer removeFromCache = store -> store.removeByPrefix(prefix);
+ StoreTruncate deleteStore = () -> delegate.delete(layerName);
+ if (!truncateNeedsCache()) return truncate(removeFromCache, deleteStore);
+ // only a layer removal deletes a whole layer, truncates go gridset by gridset: the layer is gone and nobody can
+ // retry, so its store is deleted whatever the cache, whose leftovers expire with their time to live
+ cacheRemovalFailure(removeFromCache);
+ return truncateStoreThenCache(removeFromCache, deleteStore);
+ }
+
+ @Override
+ public boolean deleteByGridsetId(String layerName, String gridSetId) throws StorageException {
+ String prefix = keys.forGridset(layerName, gridSetId);
+ return truncateTiles(
+ store -> store.removeByPrefix(prefix), () -> delegate.deleteByGridsetId(layerName, gridSetId));
+ }
+
+ @Override
+ public boolean deleteByParametersId(String layerName, String parametersId) throws StorageException {
+ Set prefixes = keys.forParameters(layerName, parametersId);
+ return truncate(
+ store -> prefixes.forEach(store::removeByPrefix),
+ () -> delegate.deleteByParametersId(layerName, parametersId));
+ }
+
+ @Override
+ public boolean delete(TileObject obj) throws StorageException {
+ // disk quota deletes tile by tile, two cache calls each are not worth one stale tile of a former cached layer
+ if (!cached) return delegate.delete(obj);
+ String key = keys.forTile(obj, layer.getId());
+ return deleteTiles(store -> store.remove(key), () -> delegate.delete(obj));
+ }
+
+ @Override
+ public boolean delete(TileRange range) throws StorageException {
+ // prefixes first, so that only store failures count as a cache outage
+ List prefixes = IntStream.rangeClosed(range.getZoomStart(), range.getZoomStop())
+ .mapToObj(z -> keys.forZoomLevel(range, z))
+ .toList();
+ return deleteTiles(store -> removeRange(store, range, prefixes), () -> delegate.delete(range));
+ }
+
+ /**
+ * A {@link #truncateTiles} that, with passthrough on, still deletes from the store behind while the cache is down,
+ * so that disk quota frees space during an outage; the cached copies are then served until they expire.
+ */
+ private boolean deleteTiles(Consumer removeFromCache, StoreTruncate truncateStore)
+ throws StorageException {
+ // with passthrough off the store holds no tiles, there is no space to free: fail as the other truncates
+ if (!truncateNeedsCache() || !storeHoldsTiles()) return truncateTiles(removeFromCache, truncateStore);
+ if (cacheRemovalFailure(removeFromCache) != null) {
+ if (cache.getDeletesSkippingCache().compareAndSet(false, true)) {
+ // SEVERE as the outage lines, production logging keeps org.geowebcache at error
+ LOGGER.severe("In-memory tile cache is unreachable, tile deletes of layer " + layer.getName()
+ + " run on the blob store only, cached copies are served until they expire");
+ }
+ return truncateStore.run();
+ }
+ cache.getDeletesSkippingCache().set(false);
+ return truncateStoreThenCache(removeFromCache, truncateStore);
+ }
+
+ /** Removes the range from the cache, {@code prefixes} holding the key prefix of each of its zoom levels. */
+ private static void removeRange(KeyValueStore store, TileRange range, List prefixes) {
+ for (int i = 0; i < prefixes.size(); i++) {
+ int z = range.getZoomStart() + i;
+ store.removeMatching(prefixes.get(i), key -> inRange(range, key, z));
+ }
+ }
+
+ /** Checks a key ending with {@code /.} against the range; a key of any other shape is in it. */
+ private static boolean inRange(TileRange range, String key, int z) {
+ int dot = key.lastIndexOf('.');
+ int ySlash = key.lastIndexOf('/', dot);
+ int xSlash = key.lastIndexOf('/', ySlash - 1);
+ try {
+ long x = Long.parseLong(key, xSlash + 1, ySlash, 10);
+ long y = Long.parseLong(key, ySlash + 1, dot, 10);
+ return range.contains(x, y, z);
+ } catch (NumberFormatException | IndexOutOfBoundsException e) {
+ // removing more than asked is allowed, throwing would turn one stray key into a cache outage
+ return true;
+ }
+ }
+
+ @Override
+ public void clear() throws StorageException {
+ truncate(KeyValueStore::clear, () -> {
+ delegate.clear();
+ return true;
+ });
+ }
+
+ /**
+ * A {@link #truncate} of tiles only, leaving the store behind alone when it holds no tiles. Layer and parameters
+ * truncates still reach it, since they also remove metadata and mappings.
+ */
+ private boolean truncateTiles(Consumer removeFromCache, StoreTruncate truncateStore)
+ throws StorageException {
+ // with passthrough off nothing reads through, so the second removal protects nothing, kept to share one
+ // failure path
+ return truncate(removeFromCache, () -> !storeHoldsTiles() || truncateStore.run());
+ }
+
+ /**
+ * Removes the truncated tiles from the cache, truncates the store behind, then removes them from the cache again.
+ *
+ * @param removeFromCache removes the keys of the truncated tiles, run twice
+ * @param truncateStore the same truncate on the store behind, whose result is returned
+ * @throws StorageException for a memory cached layer, before the store when the first removal fails or is refused,
+ * a retry then truncates both; after it when the second removal fails
+ */
+ private boolean truncate(Consumer removeFromCache, StoreTruncate truncateStore)
+ throws StorageException {
+ if (!truncateNeedsCache()) {
+ // only leftovers there, which nothing reads; refused at once while the cache is down
+ cacheRemovalFailure(removeFromCache);
+ return truncateStore.run();
+ }
+ // truncating the store alone would leave the cached tiles, served again once the cache is back
+ RuntimeException failure = cacheRemovalFailure(removeFromCache);
+ if (failure != null) {
+ String message = "In-memory tile cache is unreachable, truncate of layer " + layer.getName()
+ + " not run, retry once it recovers";
+ throw new StorageException(message, failure);
+ }
+ return truncateStoreThenCache(removeFromCache, truncateStore);
+ }
+
+ /**
+ * Whether a cache failure fails a truncate: not for a layer not using the cache, whose tiles never go there, nor
+ * for an unusable cache, which never held any.
+ */
+ private boolean truncateNeedsCache() {
+ return cached && !cache.getStore().isUnusable();
+ }
+
+ /**
+ * Truncates the store, then removes from the cache again, so that a tile read through from the store while it was
+ * being truncated does not survive.
+ *
+ * @throws StorageException when the removal fails, the store being truncated already
+ */
+ private boolean truncateStoreThenCache(Consumer removeFromCache, StoreTruncate truncateStore)
+ throws StorageException {
+ boolean result = truncateStore.run();
+ RuntimeException failure = cacheRemovalFailure(removeFromCache);
+ if (failure != null) {
+ String message = "In-memory tile cache removal failed after the blob store truncate of layer "
+ + layer.getName() + ", cached tiles may be stale until they expire";
+ throw new StorageException(message, failure);
+ }
+ // with passthrough off the store behind holds no tiles, so its false only means it had nothing to delete
+ return result || !storeHoldsTiles();
+ }
+
+ /** Runs the removal on the cache; the failure, null on success. */
+ @Nullable
+ private RuntimeException cacheRemovalFailure(Consumer removeFromCache) {
+ try {
+ removeFromCache.accept(cache.getStore());
+ return null;
+ } catch (RuntimeException e) {
+ return e;
+ }
+ }
+
+ /** A truncate of the store behind, true when it removed something. */
+ @FunctionalInterface
+ private interface StoreTruncate {
+ boolean run() throws StorageException;
+ }
+
+ @Override
+ public boolean rename(String oldLayerName, String newLayerName) throws StorageException {
+ // cache keys use the layer id, which a rename keeps
+ return delegate.rename(oldLayerName, newLayerName);
+ }
+
+ @Override
+ public void destroy() {
+ delegate.destroy();
+ }
+
+ @Override
+ public void addListener(BlobStoreListener listener) {
+ delegate.addListener(listener);
+ }
+
+ @Override
+ public boolean removeListener(BlobStoreListener listener) {
+ return delegate.removeListener(listener);
+ }
+
+ @Override
+ public String getLayerMetadata(String layerName, String key) {
+ return delegate.getLayerMetadata(layerName, key);
+ }
+
+ @Override
+ public void putLayerMetadata(String layerName, String key, String value) {
+ delegate.putLayerMetadata(layerName, key, value);
+ }
+
+ @Override
+ public boolean layerExists(String layerName) {
+ return delegate.layerExists(layerName);
+ }
+
+ @Override
+ public Set getParameterIds(String layerName) throws StorageException {
+ return delegate.getParameterIds(layerName);
+ }
+
+ @Override
+ public Map>> getParametersMapping(String layerName) {
+ return delegate.getParametersMapping(layerName);
+ }
+}
diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/GuardedStore.java b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/GuardedStore.java
new file mode 100644
index 0000000000..baf1c3ee80
--- /dev/null
+++ b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/GuardedStore.java
@@ -0,0 +1,269 @@
+/**
+ * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General
+ * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
+ * later version.
+ *
+ *
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
+ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+ *
+ *
You should have received a copy of the GNU Lesser General Public License along with this program. If not, see
+ * .
+ *
+ *
Copyright 2026
+ */
+package org.geowebcache.storage.memorycache;
+
+import static java.util.concurrent.TimeUnit.NANOSECONDS;
+import static java.util.concurrent.TimeUnit.SECONDS;
+
+import com.google.common.base.Ticker;
+import java.io.Serial;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.function.Predicate;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import javax.annotation.Nullable;
+import org.geotools.util.logging.Logging;
+
+/**
+ * Stops calling a failing backend for a while, so that a stalled cluster does not cost every tile request a full
+ * timeout. Failures, and calls refused meanwhile, throw {@link UnavailableException}; the backend hears of each change
+ * through {@link KeyValueStore#reachable}. Thread safe.
+ *
+ *
+ * UP --fail--> DOWN --wait over--> PROBING --ok--> UP
+ * ^ |
+ * +-------fail----------+
+ *
+ *
+ *
While probing, a single call tests the backend. The wait grows with the outage, and a failure soon after a
+ * recovery continues the same outage. A call that started before the last change does not move the state.
+ */
+class GuardedStore implements KeyValueStore {
+
+ private static final Logger LOGGER = Logging.getLogger(GuardedStore.class.getName());
+
+ /** Shortest wait between two probes. */
+ private static final long MIN_RETRY = SECONDS.toNanos(1);
+
+ /** Longest wait between two probes, also how long a recovery must hold before a failure starts a new outage. */
+ private static final long MAX_RETRY = SECONDS.toNanos(30);
+
+ /** The backend health, all times in ticker nanos. */
+ private sealed interface State permits Up, Down, Probing {}
+
+ /** Calls go through. {@code outageSince} and {@code recoveredAt} describe the last outage. */
+ private record Up(long outageSince, long recoveredAt) implements State {}
+
+ /** Calls are refused until {@code retryAt}. */
+ private record Down(long since, long retryAt) implements State {}
+
+ /**
+ * One call, granted at {@code grantedAt}, is testing the backend. Others are refused until it reports, or until
+ * {@code deadline} if it never does (a hung or lost probe), when the next caller probes instead.
+ */
+ private record Probing(long since, long grantedAt, long deadline) implements State {}
+
+ private final AtomicReference state;
+
+ /** Null when unusable. */
+ private final KeyValueStore delegate;
+
+ /** Why the backend could not be built, null when usable. */
+ private final String unusableReason;
+
+ private final Ticker ticker;
+
+ GuardedStore(KeyValueStore delegate, Ticker ticker) {
+ this(delegate, null, ticker);
+ }
+
+ private GuardedStore(@Nullable KeyValueStore delegate, @Nullable String unusableReason, Ticker ticker) {
+ this.delegate = delegate;
+ this.unusableReason = unusableReason;
+ this.ticker = ticker;
+ // as if recovered long enough ago: every later failure starts a new outage
+ this.state = new AtomicReference<>(new Up(0, ticker.read() - MAX_RETRY));
+ }
+
+ /** A store refusing every call, for settings that cannot work until they change. Logs the reason once. */
+ static GuardedStore unusable(String reason, @Nullable Throwable cause) {
+ LOGGER.log(Level.SEVERE, "In-memory tile cache unusable, " + reason, cause);
+ return new GuardedStore(null, reason, Ticker.systemTicker());
+ }
+
+ /** Whether the settings left no backend: the store never held tiles, and never recovers until they change. */
+ boolean isUnusable() {
+ return delegate == null;
+ }
+
+ /**
+ * Whether a call may go to the backend now. DOWN, or a PROBING past its deadline, moves to PROBING for one caller.
+ */
+ private boolean mayCall() {
+ State current = state.get();
+ if (current instanceof Up) return true;
+ long now = ticker.read();
+ long since;
+ if (current instanceof Down down && now - down.retryAt() >= 0) {
+ since = down.since();
+ } else if (current instanceof Probing probing && now - probing.deadline() >= 0) {
+ since = probing.since();
+ } else {
+ return false;
+ }
+ // the caller winning the swap is the probe, the others keep being refused
+ return state.compareAndSet(current, new Probing(since, now, now + backoff(since, now)));
+ }
+
+ /** DOWN or PROBING to UP, unless the call started before the outage. */
+ private void succeeded(long start) {
+ State current = state.get();
+ long since;
+ if (current instanceof Down down) {
+ since = down.since();
+ } else if (current instanceof Probing probing) {
+ since = probing.since();
+ } else {
+ return;
+ }
+ // on a cluster a call can answer after a newer one failed on another member: it says nothing about the outage
+ if (start - since < 0) return;
+ long now = ticker.read();
+ if (state.compareAndSet(current, new Up(since, now))) {
+ LOGGER.severe("In-memory tile cache is reachable again after " + NANOSECONDS.toSeconds(now - since) + " s");
+ reportState();
+ }
+ }
+
+ /** UP to DOWN, starting or resuming an outage; a failed probe back to DOWN with a longer wait. */
+ private void failed(long start, RuntimeException e) {
+ long now = ticker.read();
+ while (true) {
+ State current = state.get();
+ long since;
+ boolean resumed;
+ if (current instanceof Probing probing && start - probing.grantedAt() >= 0) {
+ since = probing.since();
+ resumed = false;
+ } else if (current instanceof Up up && start - up.recoveredAt() >= 0) {
+ resumed = now - up.recoveredAt() < MAX_RETRY;
+ since = resumed ? up.outageSince() : now;
+ } else {
+ // already DOWN, or a call started before the last change, failing on the state before it
+ return;
+ }
+ if (state.compareAndSet(current, new Down(since, now + backoff(since, now)))) {
+ logFailure(current, resumed, e);
+ // a failed probe stays unreachable, nothing to report
+ if (current instanceof Up) reportState();
+ return;
+ }
+ }
+ }
+
+ /**
+ * Tells the backend whether it is reachable. Reads the state under the lock, so that two changes racing cannot
+ * leave the older one reported last.
+ */
+ private synchronized void reportState() {
+ delegate.reachable(state.get() instanceof Up);
+ }
+
+ /**
+ * Logs an outage start or resume at SEVERE, as production logging keeps org.geowebcache at error and an outage
+ * start without its end cannot be read; a failed probe is not logged, the outage is already.
+ */
+ private static void logFailure(State previous, boolean resumed, RuntimeException e) {
+ if (!(previous instanceof Up)) return;
+ if (resumed) {
+ LOGGER.severe("In-memory tile cache is unreachable again");
+ return;
+ }
+ LOGGER.log(
+ Level.SEVERE, "In-memory tile cache is unreachable, tiles are served without it until it recovers", e);
+ }
+
+ /** Half the outage age within the retry bounds, with 20% jitter so that nodes do not probe in lockstep. */
+ private static long backoff(long since, long now) {
+ long wait = Math.min(Math.max((now - since) / 2, MIN_RETRY), MAX_RETRY);
+ return (long) (wait * ThreadLocalRandom.current().nextDouble(0.8, 1.2));
+ }
+
+ /** Thrown for every failed or refused call. No stack trace: while down it is thrown once per tile request. */
+ static class UnavailableException extends RuntimeException {
+
+ @Serial
+ private static final long serialVersionUID = 1L;
+
+ UnavailableException(String message, @Nullable Throwable cause) {
+ super(message, cause, false, false);
+ }
+ }
+
+ private T call(Function operation) {
+ // permanent, outside the state machine: no probe, no outage log, the reason was logged on creation
+ if (delegate == null) throw new UnavailableException("In-memory tile cache unusable, " + unusableReason, null);
+ if (!mayCall()) throw new UnavailableException("In-memory tile cache is down", null);
+ long start = ticker.read();
+ try {
+ T result = operation.apply(delegate);
+ succeeded(start);
+ return result;
+ } catch (RuntimeException e) {
+ failed(start, e);
+ throw new UnavailableException("In-memory tile cache call failed", e);
+ }
+ }
+
+ private void run(Consumer operation) {
+ call(store -> {
+ operation.accept(store);
+ return null;
+ });
+ }
+
+ @Override
+ public byte[] get(String key) {
+ return call(store -> store.get(key));
+ }
+
+ @Override
+ public void put(String key, byte[] value, long ttlSeconds) {
+ run(store -> store.put(key, value, ttlSeconds));
+ }
+
+ @Override
+ public void putIfAbsent(String key, byte[] value, long ttlSeconds) {
+ run(store -> store.putIfAbsent(key, value, ttlSeconds));
+ }
+
+ @Override
+ public void remove(String key) {
+ run(store -> store.remove(key));
+ }
+
+ @Override
+ public void removeByPrefix(String prefix) {
+ run(store -> store.removeByPrefix(prefix));
+ }
+
+ @Override
+ public void removeMatching(String prefix, Predicate remove) {
+ run(store -> store.removeMatching(prefix, remove));
+ }
+
+ @Override
+ public void clear() {
+ run(KeyValueStore::clear);
+ }
+
+ /** Closes the backend store; requests still running on it see failures, handled as misses. */
+ @Override
+ public void close() {
+ if (delegate != null) delegate.close();
+ }
+}
diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/HeapKeyValueStore.java b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/HeapKeyValueStore.java
new file mode 100644
index 0000000000..711ae54fb7
--- /dev/null
+++ b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/HeapKeyValueStore.java
@@ -0,0 +1,102 @@
+/**
+ * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General
+ * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
+ * later version.
+ *
+ *
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
+ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+ *
+ *
You should have received a copy of the GNU Lesser General Public License along with this program. If not, see
+ * .
+ *
+ *
Copyright 2026
+ */
+package org.geowebcache.storage.memorycache;
+
+import static java.util.concurrent.TimeUnit.SECONDS;
+
+import com.google.common.base.Ticker;
+import com.google.common.cache.Cache;
+import com.google.common.cache.CacheBuilder;
+import java.util.function.Predicate;
+
+/** {@link KeyValueStore} in the local JVM heap, bounded by the total size of its values. */
+public class HeapKeyValueStore implements KeyValueStore {
+
+ /** Guava only expires per cache, so the per-entry deadline is checked on read. */
+ private record Entry(byte[] value, long expiresAtNanos) {}
+
+ private final Cache cache;
+
+ private final Ticker ticker;
+
+ /**
+ * Creates a store holding at most {@code maxBytes} of values; an expired entry keeps its memory until read or
+ * evicted.
+ */
+ public HeapKeyValueStore(long maxBytes) {
+ this(maxBytes, Ticker.systemTicker());
+ }
+
+ HeapKeyValueStore(long maxBytes, Ticker ticker) {
+ this.ticker = ticker;
+ this.cache = CacheBuilder.newBuilder()
+ .maximumWeight(maxBytes)
+ .weigher((String key, Entry entry) -> entry.value.length)
+ .build();
+ }
+
+ @Override
+ public byte[] get(String key) {
+ Entry entry = cache.getIfPresent(key);
+ if (entry == null) return null;
+ if (expired(entry)) {
+ cache.asMap().remove(key, entry);
+ return null;
+ }
+ return entry.value;
+ }
+
+ @Override
+ public void put(String key, byte[] value, long ttlSeconds) {
+ cache.put(key, new Entry(value, ticker.read() + SECONDS.toNanos(ttlSeconds)));
+ }
+
+ @Override
+ public void putIfAbsent(String key, byte[] value, long ttlSeconds) {
+ Entry entry = new Entry(value, ticker.read() + SECONDS.toNanos(ttlSeconds));
+ Entry current = cache.asMap().putIfAbsent(key, entry);
+ // an expired entry counts as absent, as get reports it so
+ if (current != null && expired(current)) cache.asMap().replace(key, current, entry);
+ }
+
+ private boolean expired(Entry entry) {
+ // nanoTime-style values can overflow, compare the difference
+ return ticker.read() - entry.expiresAtNanos >= 0;
+ }
+
+ @Override
+ public void remove(String key) {
+ cache.invalidate(key);
+ }
+
+ @Override
+ public void removeByPrefix(String prefix) {
+ cache.asMap().keySet().removeIf(key -> key.startsWith(prefix));
+ }
+
+ @Override
+ public void removeMatching(String prefix, Predicate remove) {
+ cache.asMap().keySet().removeIf(key -> key.startsWith(prefix) && remove.test(key));
+ }
+
+ @Override
+ public void clear() {
+ cache.invalidateAll();
+ }
+
+ @Override
+ public void close() {
+ // nothing to release, the entries go with the instance
+ }
+}
diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/HeapKeyValueStoreInfo.java b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/HeapKeyValueStoreInfo.java
new file mode 100644
index 0000000000..5d99c32adc
--- /dev/null
+++ b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/HeapKeyValueStoreInfo.java
@@ -0,0 +1,55 @@
+/**
+ * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General
+ * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
+ * later version.
+ *
+ *
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
+ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+ *
+ *
You should have received a copy of the GNU Lesser General Public License along with this program. If not, see
+ * .
+ *
+ *
Copyright 2026
+ */
+package org.geowebcache.storage.memorycache;
+
+import java.io.Serial;
+
+/**
+ * Settings of the {@link HeapKeyValueStore}, tiles in the heap of each node; an absent element reads as its default.
+ */
+public class HeapKeyValueStoreInfo implements KeyValueStoreInfo {
+
+ @Serial
+ private static final long serialVersionUID = 1L;
+
+ static final int DEFAULT_MAX_SIZE_MB = 64;
+
+ private Integer maxSizeMB;
+
+ /** Maximum total size of the cached tiles on each node, in megabytes, 64 by default. */
+ public int getMaxSizeMB() {
+ return maxSizeMB == null ? DEFAULT_MAX_SIZE_MB : maxSizeMB;
+ }
+
+ /** Sets the maximum total size of the cached tiles on each node, in megabytes. */
+ public void setMaxSizeMB(int maxSizeMB) {
+ this.maxSizeMB = maxSizeMB;
+ }
+
+ @Override
+ public KeyValueStore createStore() {
+ return new HeapKeyValueStore(getMaxSizeMB() * 1024L * 1024L);
+ }
+
+ /** Equal when the effective settings are, an absent value matching its default. */
+ @Override
+ public boolean equals(Object o) {
+ return o instanceof HeapKeyValueStoreInfo other && getMaxSizeMB() == other.getMaxSizeMB();
+ }
+
+ @Override
+ public int hashCode() {
+ return getMaxSizeMB();
+ }
+}
diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/KeyValueStore.java b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/KeyValueStore.java
new file mode 100644
index 0000000000..c139cae275
--- /dev/null
+++ b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/KeyValueStore.java
@@ -0,0 +1,65 @@
+/**
+ * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General
+ * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
+ * later version.
+ *
+ *
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
+ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+ *
+ *
You should have received a copy of the GNU Lesser General Public License along with this program. If not, see
+ * .
+ *
+ *
Copyright 2026
+ */
+package org.geowebcache.storage.memorycache;
+
+import java.util.function.Predicate;
+
+/**
+ * Stores byte arrays under string keys, a key prefix naming a set of entries.
+ *
+ *
Entries expire after the time to live given by the caller, and may be dropped earlier, so never keep state here
+ * that must survive. Keys and values are opaque to implementations, which must be thread safe and throw an unchecked
+ * exception when their backend cannot be reached.
+ */
+public interface KeyValueStore extends AutoCloseable {
+
+ /** Returns the value, or null when the key is absent or expired. */
+ byte[] get(String key);
+
+ /** Stores the value for at most {@code ttlSeconds}, positive. */
+ void put(String key, byte[] value, long ttlSeconds);
+
+ /** Stores the value as {@link #put} does, unless the key already holds one. Atomic. */
+ void putIfAbsent(String key, byte[] value, long ttlSeconds);
+
+ /** Removes the entry, if any. */
+ void remove(String key);
+
+ /** Removes every entry whose key starts with the prefix. Other nodes see the removal on return. */
+ void removeByPrefix(String prefix);
+
+ /**
+ * Removes the entries under the prefix that the predicate accepts.
+ *
+ *
An implementation may remove more than that and log it. Callers already have to accept losing entries at any
+ * time, since storage is ephemeral.
+ */
+ void removeMatching(String prefix, Predicate remove);
+
+ /** Removes every entry, including entries other nodes wrote. */
+ void clear();
+
+ /**
+ * Told whether the cache now considers this store reachable, when that changes. Calls may repeat a value but never
+ * overlap, and the last one carries the current state. Must return quickly. Does nothing by default.
+ */
+ default void reachable(boolean reachable) {}
+
+ /**
+ * Releases what this store owns. Entries are left in place, and a connection shared with other callers outlives the
+ * call.
+ */
+ @Override
+ void close();
+}
diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/KeyValueStoreInfo.java b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/KeyValueStoreInfo.java
new file mode 100644
index 0000000000..bdb3d481b9
--- /dev/null
+++ b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/KeyValueStoreInfo.java
@@ -0,0 +1,26 @@
+/**
+ * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General
+ * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
+ * later version.
+ *
+ *
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
+ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+ *
+ *
You should have received a copy of the GNU Lesser General Public License along with this program. If not, see
+ * .
+ *
+ *
Copyright 2026
+ */
+package org.geowebcache.storage.memorycache;
+
+import java.io.Serializable;
+
+/**
+ * Settings of one cache backend, persisted as the {@code } of {@code }, and the factory of its
+ * {@link KeyValueStore}; each implementation needs an XStream alias, registered by its module.
+ */
+public interface KeyValueStoreInfo extends Serializable {
+
+ /** Returns a new store for these settings; the caller closes it. */
+ KeyValueStore createStore();
+}
diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/MemoryCache.java b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/MemoryCache.java
new file mode 100644
index 0000000000..d02a079d9d
--- /dev/null
+++ b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/MemoryCache.java
@@ -0,0 +1,153 @@
+/**
+ * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General
+ * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
+ * later version.
+ *
+ *
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
+ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+ *
+ *
You should have received a copy of the GNU Lesser General Public License along with this program. If not, see
+ * .
+ *
+ *
Copyright 2026
+ */
+package org.geowebcache.storage.memorycache;
+
+import com.google.common.base.Ticker;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.logging.Logger;
+import javax.annotation.Nullable;
+import org.geotools.util.logging.Logging;
+import org.geowebcache.layer.TileLayer;
+import org.geowebcache.layer.TileLayerDispatcher;
+import org.geowebcache.storage.BlobStore;
+import org.geowebcache.util.TMSKeyBuilder;
+
+/**
+ * In-memory tile cache shared by all cached layers of this node, built from one {@link MemoryCacheInfo}: its
+ * {@link KeyValueStore}, guarded against outages. Thread safe.
+ */
+public class MemoryCache implements AutoCloseable {
+
+ private static final Logger LOGGER = Logging.getLogger(MemoryCache.class.getName());
+
+ private final MemoryCacheInfo info;
+
+ /** Null when the cache is disabled, refusing every call when enabled but unusable. */
+ private final GuardedStore store;
+
+ private final TMSKeyBuilder keys;
+
+ /** Whether the last parameter mapping write failed, so that a store outage is logged once, not per tile. */
+ private final AtomicBoolean mappingWritesFailing = new AtomicBoolean();
+
+ /** Whether the last tile delete ran on the blob store only, so that a cache outage is logged once, not per tile. */
+ private final AtomicBoolean deletesSkippingCache = new AtomicBoolean();
+
+ private final MemoryCacheStats stats;
+
+ /**
+ * Builds the cache for {@code info}, disabled when null. Invalid settings or a backend that cannot be created are
+ * logged, not thrown, and leave the cache unusable: cached layers then miss and drop writes.
+ */
+ public MemoryCache(@Nullable MemoryCacheInfo info, TileLayerDispatcher layers) {
+ this(info, layers, Ticker.systemTicker());
+ }
+
+ MemoryCache(@Nullable MemoryCacheInfo info, TileLayerDispatcher layers, Ticker ticker) {
+ this.info = info;
+ this.store = info != null && info.isEnabled() ? createStore(info, ticker) : null;
+ // no key prefix, the cache holds tiles only
+ this.keys = new TMSKeyBuilder(null, layers);
+ this.stats = new MemoryCacheStats(info == null ? 0 : info.getStatsInterval(), ticker);
+ }
+
+ // never null: falling back to the layer's own store would write tiles there with passthrough off
+ private static GuardedStore createStore(MemoryCacheInfo info, Ticker ticker) {
+ if (info.getTimeToLive() < 1) {
+ return GuardedStore.unusable("time to live must be at least 1 second, got " + info.getTimeToLive(), null);
+ }
+ KeyValueStoreInfo settings = info.getBackend();
+ if (settings instanceof UnresolvedKeyValueStoreInfo unresolved) {
+ return GuardedStore.unusable("backend " + unresolved.getAlias() + " is not installed", null);
+ }
+ try {
+ return new GuardedStore(settings.createStore(), ticker);
+ } catch (RuntimeException | LinkageError e) {
+ // a LinkageError comes from a backend jar missing its library or built against another version of it;
+ // left to escape, it would fail every blob store call, as the cache is built again on each of them
+ return GuardedStore.unusable(
+ "could not create backend " + settings.getClass().getSimpleName(), e);
+ }
+ }
+
+ /** The settings this cache was built from, null if none. */
+ @Nullable
+ public MemoryCacheInfo getInfo() {
+ return info;
+ }
+
+ /**
+ * Returns {@code store} unchanged when the cache is disabled, otherwise a store serving the layer tiles from the
+ * cache if the layer uses it. Truncates clear the layer tiles from the cache either way.
+ */
+ public BlobStore wrap(TileLayer layer, BlobStore store) {
+ return this.store == null ? store : new CachingBlobStore(store, this, layer, layer.isMemoryCached());
+ }
+
+ /**
+ * Drops the tiles cached under the old name of a renamed layer, which a new layer with that name would serve
+ * otherwise. Does nothing when layer ids are not their names, as in GeoServer. Never throws.
+ */
+ public void layerRenamed(String oldName, String newName) {
+ if (store == null) return;
+ try {
+ // keys start with the layer id: one that survives the rename leaves nothing under the old name
+ if (!newName.equals(keys.layerId(newName))) return;
+ } catch (RuntimeException e) {
+ // layer not found, remove to be safe
+ }
+ // the TMSKeyBuilder.forLayer layout, which cannot be used as no layer has that name any more
+ String prefix = oldName + "/";
+ try {
+ store.removeByPrefix(prefix);
+ } catch (RuntimeException e) {
+ LOGGER.warning("In-memory tile cache could not remove the tiles of renamed layer " + oldName
+ + ", a new layer with that name may serve them until they expire");
+ }
+ }
+
+ /** Closes the backend store; requests still running on it see failures, handled as misses. */
+ @Override
+ public void close() {
+ if (store != null) store.close();
+ }
+
+ GuardedStore getStore() {
+ return store;
+ }
+
+ long getTtlSeconds() {
+ return info.getTimeToLive();
+ }
+
+ boolean isPassthrough() {
+ return info.isPassthrough();
+ }
+
+ TMSKeyBuilder getKeys() {
+ return keys;
+ }
+
+ AtomicBoolean getMappingWritesFailing() {
+ return mappingWritesFailing;
+ }
+
+ AtomicBoolean getDeletesSkippingCache() {
+ return deletesSkippingCache;
+ }
+
+ MemoryCacheStats getStats() {
+ return stats;
+ }
+}
diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/MemoryCacheInfo.java b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/MemoryCacheInfo.java
new file mode 100644
index 0000000000..d8cc8cf554
--- /dev/null
+++ b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/MemoryCacheInfo.java
@@ -0,0 +1,105 @@
+/**
+ * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General
+ * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
+ * later version.
+ *
+ *
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
+ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+ *
+ *
You should have received a copy of the GNU Lesser General Public License along with this program. If not, see
+ * .
+ *
+ *
Copyright 2026
+ */
+package org.geowebcache.storage.memorycache;
+
+import java.io.Serial;
+import java.io.Serializable;
+import java.util.Objects;
+
+/** The {@code } settings of {@code geowebcache.xml}; an absent element reads as its default. */
+public class MemoryCacheInfo implements Serializable {
+
+ @Serial
+ private static final long serialVersionUID = 1L;
+
+ static final long DEFAULT_TIME_TO_LIVE = 300;
+
+ static final long DEFAULT_STATS_INTERVAL = 300;
+
+ private Boolean enabled;
+
+ private Long timeToLive;
+
+ private Boolean passthrough;
+
+ private Long statsInterval;
+
+ private KeyValueStoreInfo backend;
+
+ /** Whether cached layers go through the cache, false by default. */
+ public boolean isEnabled() {
+ return Boolean.TRUE.equals(enabled);
+ }
+
+ /** Turns the cache on or off for every cached layer. */
+ public void setEnabled(boolean enabled) {
+ this.enabled = enabled;
+ }
+
+ /** Time to live in seconds of the tiles of layers without an expire server cache, 300 by default. */
+ public long getTimeToLive() {
+ return timeToLive == null ? DEFAULT_TIME_TO_LIVE : timeToLive;
+ }
+
+ /** Sets the time to live of the tiles of layers without an expire server cache, in seconds and positive. */
+ public void setTimeToLive(long timeToLive) {
+ this.timeToLive = timeToLive;
+ }
+
+ /** Whether tiles are also written to, and read through from, the layer's own blob store, true by default. */
+ public boolean isPassthrough() {
+ return passthrough == null || passthrough;
+ }
+
+ /** Sets whether tiles are also written to, and read through from, the layer's own blob store. */
+ public void setPassthrough(boolean passthrough) {
+ this.passthrough = passthrough;
+ }
+
+ /** Seconds between two statistics lines per layer in the log, 300 by default, 0 when turned off. */
+ public long getStatsInterval() {
+ return statsInterval == null ? DEFAULT_STATS_INTERVAL : statsInterval;
+ }
+
+ /** Sets the seconds between two statistics lines per layer in the log, 0 turns them off. */
+ public void setStatsInterval(long statsInterval) {
+ this.statsInterval = statsInterval;
+ }
+
+ /** The backend settings, the heap backend with its defaults when absent. */
+ public KeyValueStoreInfo getBackend() {
+ return backend == null ? new HeapKeyValueStoreInfo() : backend;
+ }
+
+ /** Sets the backend settings, which create the store of the cache. */
+ public void setBackend(KeyValueStoreInfo backend) {
+ this.backend = backend;
+ }
+
+ /** Equal when the effective settings are, an absent value matching its default. */
+ @Override
+ public boolean equals(Object o) {
+ return o instanceof MemoryCacheInfo other
+ && isEnabled() == other.isEnabled()
+ && getTimeToLive() == other.getTimeToLive()
+ && isPassthrough() == other.isPassthrough()
+ && getStatsInterval() == other.getStatsInterval()
+ && getBackend().equals(other.getBackend());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(isEnabled(), getTimeToLive(), isPassthrough(), getStatsInterval(), getBackend());
+ }
+}
diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/MemoryCacheStats.java b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/MemoryCacheStats.java
new file mode 100644
index 0000000000..ee84784ed3
--- /dev/null
+++ b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/MemoryCacheStats.java
@@ -0,0 +1,136 @@
+/**
+ * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General
+ * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
+ * later version.
+ *
+ *
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
+ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+ *
+ *
You should have received a copy of the GNU Lesser General Public License along with this program. If not, see
+ * .
+ *
+ *
Copyright 2026
+ */
+package org.geowebcache.storage.memorycache;
+
+import static java.util.concurrent.TimeUnit.NANOSECONDS;
+import static java.util.concurrent.TimeUnit.SECONDS;
+
+import com.google.common.base.Ticker;
+import java.util.EnumMap;
+import java.util.Locale;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.LongAdder;
+import java.util.logging.Logger;
+import org.geotools.util.logging.Logging;
+
+/** Per-layer read results and failed puts, logged at INFO and reset by the first {@link #report()} of each interval. */
+class MemoryCacheStats {
+
+ private static final Logger LOGGER = Logging.getLogger(MemoryCacheStats.class.getName());
+
+ /** Outcome of a tile read. */
+ enum Result {
+ /** Served from the cache. */
+ HIT,
+ /** Not in the cache, read through from the store behind. */
+ STORE,
+ /** Neither in the cache nor, with passthrough on, in the store behind. */
+ MISS,
+ /** Served from the cache, but older than the layer's expire server cache, so the layer renders it again. */
+ EXPIRED,
+ /** The cache read failed. */
+ ERROR
+ }
+
+ private final long intervalNanos;
+
+ private final Ticker ticker;
+
+ private final AtomicLong nextReport;
+
+ private final Map layers = new ConcurrentHashMap<>();
+
+ /** Counters shared by every layer when reports are off, never read. */
+ private final LayerStats discarded = new LayerStats();
+
+ /** No report is ever logged with an interval of 0. */
+ MemoryCacheStats(long intervalSeconds, Ticker ticker) {
+ this.intervalNanos = SECONDS.toNanos(intervalSeconds);
+ this.ticker = ticker;
+ this.nextReport = new AtomicLong(ticker.read() + intervalNanos);
+ }
+
+ LayerStats forLayer(String layerName) {
+ // never reported, so never pruned: keeping them per layer would only grow with removed and renamed layers
+ if (intervalNanos <= 0) return discarded;
+ return layers.computeIfAbsent(layerName, name -> new LayerStats());
+ }
+
+ /**
+ * Logs and resets the counters of every layer with traffic when the interval is over, cheap otherwise. A layer
+ * without traffic in the interval is dropped, so removed and renamed layers do not stay; a read racing the drop may
+ * go uncounted.
+ */
+ void report() {
+ if (intervalNanos <= 0) return;
+ long now = ticker.read();
+ long next = nextReport.get();
+ // one caller wins the interval, the others go on serving tiles
+ if (now - next < 0 || !nextReport.compareAndSet(next, now + intervalNanos)) return;
+ long elapsedSeconds = NANOSECONDS.toSeconds(now - next + intervalNanos);
+ layers.forEach((name, stats) -> {
+ if (!stats.report(name, elapsedSeconds)) layers.remove(name, stats);
+ });
+ }
+
+ /** Counters of one layer, each reset on its own, so a call racing with a report may count in the next interval. */
+ static class LayerStats {
+
+ /** Filled in the constructor and never changed after, so reads need no lock. */
+ private final Map reads = new EnumMap<>(Result.class);
+
+ private final LongAdder failedPuts = new LongAdder();
+
+ LayerStats() {
+ for (Result result : Result.values()) reads.put(result, new LongAdder());
+ }
+
+ void read(Result result) {
+ reads.get(result).increment();
+ }
+
+ void failedPut() {
+ failedPuts.increment();
+ }
+
+ /** Logs and resets the counters, returning false, with nothing logged, when there was no traffic. */
+ private boolean report(String layerName, long elapsedSeconds) {
+ Map counts = new EnumMap<>(Result.class);
+ reads.forEach((result, adder) -> counts.put(result, adder.sumThenReset()));
+ long total = counts.values().stream().mapToLong(Long::longValue).sum();
+ long failed = failedPuts.sumThenReset();
+ if (total + failed == 0) return false;
+
+ long hits = counts.get(Result.HIT);
+ String message = String.format(
+ Locale.ROOT,
+ "In-memory tile cache stats for layer %s over %d s: %d reads (hit %d, store %d, miss %d,"
+ + " expired %d, error %d), hit ratio %.1f%%, %d failed puts",
+ layerName,
+ elapsedSeconds,
+ total,
+ hits,
+ counts.get(Result.STORE),
+ counts.get(Result.MISS),
+ counts.get(Result.EXPIRED),
+ counts.get(Result.ERROR),
+ total == 0 ? 0 : 100.0 * hits / total,
+ failed);
+ LOGGER.info(message);
+ return true;
+ }
+ }
+}
diff --git a/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/UnresolvedKeyValueStoreInfo.java b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/UnresolvedKeyValueStoreInfo.java
new file mode 100644
index 0000000000..f5b9998ffa
--- /dev/null
+++ b/geowebcache/core/src/main/java/org/geowebcache/storage/memorycache/UnresolvedKeyValueStoreInfo.java
@@ -0,0 +1,135 @@
+/**
+ * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General
+ * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
+ * later version.
+ *
+ *
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
+ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+ *
+ *
You should have received a copy of the GNU Lesser General Public License along with this program. If not, see
+ * .
+ *
+ *
Copyright 2026
+ */
+package org.geowebcache.storage.memorycache;
+
+import com.thoughtworks.xstream.XStream;
+import com.thoughtworks.xstream.converters.Converter;
+import com.thoughtworks.xstream.converters.MarshallingContext;
+import com.thoughtworks.xstream.converters.UnmarshallingContext;
+import com.thoughtworks.xstream.converters.reflection.ReflectionConverter;
+import com.thoughtworks.xstream.io.HierarchicalStreamReader;
+import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
+import com.thoughtworks.xstream.io.copy.HierarchicalStreamCopier;
+import com.thoughtworks.xstream.io.xml.CompactWriter;
+import com.thoughtworks.xstream.io.xml.DomDriver;
+import com.thoughtworks.xstream.mapper.CannotResolveClassException;
+import com.thoughtworks.xstream.mapper.Mapper;
+import com.thoughtworks.xstream.mapper.MapperWrapper;
+import java.io.Serial;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.util.Objects;
+
+/**
+ * Backend settings whose class is unknown, as when the backend module was removed: the cache is unusable, and the
+ * settings are saved back as they were read, so that reinstalling the module restores them.
+ */
+public class UnresolvedKeyValueStoreInfo implements KeyValueStoreInfo {
+
+ @Serial
+ private static final long serialVersionUID = 1L;
+
+ private static final String CLASS = "class";
+
+ private final String alias;
+
+ /** The whole {@code } element. */
+ private final String xml;
+
+ UnresolvedKeyValueStoreInfo(String alias, String xml) {
+ this.alias = alias;
+ this.xml = xml;
+ }
+
+ /** The {@code class} attribute of the backend element, null when missing. */
+ public String getAlias() {
+ return alias;
+ }
+
+ /** Always fails, as the class of these settings is not installed. */
+ @Override
+ public KeyValueStore createStore() {
+ throw new IllegalStateException("Backend " + alias + " is not installed");
+ }
+
+ /** Equal when both hold the same backend element. */
+ @Override
+ public boolean equals(Object o) {
+ return o instanceof UnresolvedKeyValueStoreInfo other && xml.equals(other.xml);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(xml);
+ }
+
+ /**
+ * Lets {@code xs} read {@code } with an unknown backend instead of failing the whole configuration.
+ */
+ public static void register(XStream xs) {
+ // an unknown class attribute fails in the reflection converter, before any converter of the field runs, so
+ // MemoryCacheInfo gets a reflection converter of its own resolving it to this class
+ Mapper mapper = new MapperWrapper(xs.getMapper()) {
+ @Override
+ public Class realClass(String elementName) {
+ try {
+ return super.realClass(elementName);
+ } catch (CannotResolveClassException e) {
+ return UnresolvedKeyValueStoreInfo.class;
+ }
+ }
+
+ // no class attribute written for this class, the converter writes the original one
+ @Override
+ public Class defaultImplementationOf(Class type) {
+ if (type == KeyValueStoreInfo.class) return UnresolvedKeyValueStoreInfo.class;
+ return super.defaultImplementationOf(type);
+ }
+ };
+ xs.registerConverter(new ReflectionConverter(mapper, xs.getReflectionProvider(), MemoryCacheInfo.class));
+ xs.registerConverter(new RawConverter());
+ }
+
+ /** Copies the backend element as raw XML. */
+ private static class RawConverter implements Converter {
+
+ @Override
+ public boolean canConvert(Class type) {
+ return type == UnresolvedKeyValueStoreInfo.class;
+ }
+
+ @Override
+ public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
+ StringWriter xml = new StringWriter();
+ CompactWriter writer = new CompactWriter(xml);
+ new HierarchicalStreamCopier().copy(reader, writer);
+ // the writer buffers
+ writer.flush();
+ return new UnresolvedKeyValueStoreInfo(reader.getAttribute(CLASS), xml.toString());
+ }
+
+ @Override
+ public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
+ UnresolvedKeyValueStoreInfo info = (UnresolvedKeyValueStoreInfo) source;
+ HierarchicalStreamReader reader = new DomDriver().createReader(new StringReader(info.xml));
+ if (info.alias != null) writer.addAttribute(CLASS, info.alias);
+ HierarchicalStreamCopier copier = new HierarchicalStreamCopier();
+ while (reader.hasMoreChildren()) {
+ reader.moveDown();
+ copier.copy(reader, writer);
+ reader.moveUp();
+ }
+ }
+ }
+}
diff --git a/geowebcache/core/src/main/java/org/geowebcache/util/TMSKeyBuilder.java b/geowebcache/core/src/main/java/org/geowebcache/util/TMSKeyBuilder.java
index edb120ca9a..90f9d10b82 100644
--- a/geowebcache/core/src/main/java/org/geowebcache/util/TMSKeyBuilder.java
+++ b/geowebcache/core/src/main/java/org/geowebcache/util/TMSKeyBuilder.java
@@ -90,11 +90,15 @@ public Set layerFormats(String layerName) {
public String forTile(TileObject obj) {
checkNotNull(obj.getLayerName());
+ return forTile(obj, layerId(obj.getLayerName()));
+ }
+
+ /** Same as {@link #forTile(TileObject)}, for a caller that already knows the id of the tile's layer. */
+ public String forTile(TileObject obj, String layer) {
checkNotNull(obj.getGridSetId());
checkNotNull(obj.getBlobFormat());
checkNotNull(obj.getXYZ());
- String layer = layerId(obj.getLayerName());
String gridset = obj.getGridSetId();
String shortFormat;
String parametersId = obj.getParametersId();
diff --git a/geowebcache/core/src/main/resources/org/geowebcache/config/geowebcache.xsd b/geowebcache/core/src/main/resources/org/geowebcache/config/geowebcache.xsd
index c73d04ea9c..2437d82d7b 100644
--- a/geowebcache/core/src/main/resources/org/geowebcache/config/geowebcache.xsd
+++ b/geowebcache/core/src/main/resources/org/geowebcache/config/geowebcache.xsd
@@ -167,6 +167,15 @@
+
+
+
+
+ The shared in-memory tile cache, used by the layers that set memoryCached. Layer metadata and parameter
+ mappings stay in the layer's blob store.
+
+
+
@@ -207,6 +216,53 @@
+
+
+
+
+ Whether the cache is used. Defaults to false.
+
+
+
+
+
+ Seconds a tile stays in the cache at most. Defaults to 300. A shorter expireCache on the layer applies
+ instead.
+
+
+
+
+
+
+ Whether tiles are also written to, and read through from, the layer's blob store. Defaults to true. When
+ false, tiles live in the cache only.
+
+
+
+
+
+
+ Seconds between two statistics lines per layer in the log. Defaults to 300, 0 turns them off.
+
+
+
+
+
+
+ The backend settings, named by the class attribute. Defaults to class="heapKeyValueStore", which keeps tiles
+ in the memory of each node, not shared, with maxSizeMB (default 64) as its size limit.
+
+
+
+
+
+
+
+
+
+
+
+
@@ -366,6 +422,13 @@
+
+
+
+ Whether the tiles of this layer go through the in-memory tile cache, when enabled. Defaults to false.
+
+
+
diff --git a/geowebcache/core/src/test/java/org/geowebcache/config/XMLConfigurationTest.java b/geowebcache/core/src/test/java/org/geowebcache/config/XMLConfigurationTest.java
index e921fad229..9e0b345802 100644
--- a/geowebcache/core/src/test/java/org/geowebcache/config/XMLConfigurationTest.java
+++ b/geowebcache/core/src/test/java/org/geowebcache/config/XMLConfigurationTest.java
@@ -19,6 +19,7 @@
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
+import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
@@ -28,6 +29,7 @@
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
+import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
@@ -40,8 +42,10 @@
import java.io.FileInputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
+import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
+import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -72,6 +76,9 @@
import org.geowebcache.layer.TileLayer;
import org.geowebcache.layer.wms.WMSLayer;
import org.geowebcache.storage.UnsuitableStorageException;
+import org.geowebcache.storage.memorycache.HeapKeyValueStoreInfo;
+import org.geowebcache.storage.memorycache.MemoryCacheInfo;
+import org.geowebcache.storage.memorycache.UnresolvedKeyValueStoreInfo;
import org.geowebcache.util.TestUtils;
import org.junit.Assume;
import org.junit.Before;
@@ -760,4 +767,86 @@ public void loadFromEmptyReadOnlyDirectoryFails() throws GeoWebCacheException, I
roEmptyDir.setWritable(true);
}
}
+
+ @Test
+ public void testMemoryCacheAbsentByDefault() {
+ assertNull(config.getMemoryCache());
+ WMSLayer layer = (WMSLayer)
+ config.getLayer(config.getLayerNames().iterator().next()).get();
+ assertFalse(layer.isMemoryCached());
+ }
+
+ @Test
+ public void testSaveMemoryCache() throws Exception {
+ HeapKeyValueStoreInfo heap = new HeapKeyValueStoreInfo();
+ heap.setMaxSizeMB(128);
+ MemoryCacheInfo memoryCache = new MemoryCacheInfo();
+ memoryCache.setEnabled(true);
+ memoryCache.setTimeToLive(120);
+ memoryCache.setPassthrough(false);
+ memoryCache.setStatsInterval(60);
+ memoryCache.setBackend(heap);
+
+ config.setMemoryCache(memoryCache);
+
+ assertValidAgainstSchema();
+ MemoryCacheInfo reloaded = reload().getMemoryCache();
+ assertTrue(reloaded.isEnabled());
+ assertEquals(120, reloaded.getTimeToLive());
+ assertFalse(reloaded.isPassthrough());
+ assertEquals(60, reloaded.getStatsInterval());
+ assertEquals(128, ((HeapKeyValueStoreInfo) reloaded.getBackend()).getMaxSizeMB());
+ }
+
+ @Test
+ public void testUnknownBackendKeptAsIs() throws Exception {
+ MemoryCacheInfo memoryCache = new MemoryCacheInfo();
+ memoryCache.setEnabled(true);
+ memoryCache.setBackend(new HeapKeyValueStoreInfo());
+ config.setMemoryCache(memoryCache);
+ // as left by a removed backend module
+ String xml = Files.readString(configFile.toPath())
+ .replaceAll(
+ "(?s)|>.*?)",
+ "cache-15701");
+ Files.writeString(configFile.toPath(), xml);
+
+ XMLConfiguration reloaded = reload();
+ UnresolvedKeyValueStoreInfo backend =
+ (UnresolvedKeyValueStoreInfo) reloaded.getMemoryCache().getBackend();
+ assertEquals("removedTileCache", backend.getAlias());
+
+ // saved back as it was, so reinstalling the module restores it
+ reloaded.setMemoryCache(reloaded.getMemoryCache());
+ assertValidAgainstSchema();
+ String saved = Files.readString(configFile.toPath());
+ assertThat(saved, containsString(""));
+ assertThat(saved, containsString("cache-1"));
+ assertThat(saved, containsString("5701"));
+ }
+
+ @Test
+ public void testSaveMemoryCachedLayer() throws Exception {
+ String name = config.getLayerNames().iterator().next();
+ WMSLayer layer = (WMSLayer) config.getLayer(name).get();
+ layer.setMemoryCached(true);
+
+ config.modifyLayer(layer);
+
+ assertValidAgainstSchema();
+ assertTrue(reload().getLayer(name).get().isMemoryCached());
+ }
+
+ private void assertValidAgainstSchema() throws Exception {
+ try (InputStream in = new FileInputStream(configFile)) {
+ XMLConfiguration.validate(XMLConfiguration.loadDocument(in));
+ }
+ }
+
+ private XMLConfiguration reload() throws Exception {
+ XMLConfiguration reloaded = new XMLConfiguration(null, configDir.getAbsolutePath());
+ reloaded.setGridSetBroker(gridSetBroker);
+ reloaded.afterPropertiesSet();
+ return reloaded;
+ }
}
diff --git a/geowebcache/core/src/test/java/org/geowebcache/storage/memorycache/AbstractKeyValueStoreTest.java b/geowebcache/core/src/test/java/org/geowebcache/storage/memorycache/AbstractKeyValueStoreTest.java
new file mode 100644
index 0000000000..03b89a6818
--- /dev/null
+++ b/geowebcache/core/src/test/java/org/geowebcache/storage/memorycache/AbstractKeyValueStoreTest.java
@@ -0,0 +1,206 @@
+/**
+ * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General
+ * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
+ * later version.
+ *
+ *
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
+ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+ *
+ *
You should have received a copy of the GNU Lesser General Public License along with this program. If not, see
+ * .
+ *
+ *
Copyright 2026
+ */
+package org.geowebcache.storage.memorycache;
+
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsInAnyOrder;
+import static org.hamcrest.Matchers.empty;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.Queue;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+/** {@link KeyValueStore} contract every backend must pass; subclasses provide an empty store. */
+public abstract class AbstractKeyValueStoreTest {
+
+ /** "layer/a0/1" sits right after the "layer/a/" range, as '0' follows '/'. */
+ private static final List KEYS = List.of("layer/a/1", "layer/a/2", "layer/a0/1", "layer/ab/1", "other/1");
+
+ private static final int THREADS = 4;
+
+ private static final int ROUNDS = 200;
+
+ private static final int VALUE_SIZE = 16 * 1024;
+
+ protected KeyValueStore store;
+
+ private final ExecutorService executor = Executors.newCachedThreadPool();
+
+ /** Released once every task of a test is submitted, so that they start together. */
+ private final CountDownLatch go = new CountDownLatch(1);
+
+ /** Returns a store holding no entries. */
+ protected abstract KeyValueStore createStore() throws Exception;
+
+ @Before
+ public void setUpStore() throws Exception {
+ store = createStore();
+ }
+
+ @After
+ public void closeStore() {
+ executor.shutdownNow();
+ // null when createStore failed, keep that failure as the only one reported
+ if (store != null) store.close();
+ }
+
+ @Test
+ public void testPutOverwrites() {
+ store.put("key", new byte[] {1}, 300);
+ store.put("key", new byte[] {2}, 300);
+
+ assertArrayEquals(new byte[] {2}, store.get("key"));
+ assertNull(store.get("missing"));
+ }
+
+ @Test
+ public void testRemove() {
+ store.put("key", new byte[] {1}, 300);
+
+ store.remove("key");
+ store.remove("key");
+ assertNull(store.get("key"));
+ }
+
+ @Test
+ public void testRemoveByPrefix() {
+ putKeys();
+
+ store.removeByPrefix("layer/a/");
+
+ assertThat(presentKeys(), containsInAnyOrder("layer/a0/1", "layer/ab/1", "other/1"));
+ }
+
+ @Test
+ public void testRemoveMatching() {
+ putKeys();
+
+ store.removeMatching("layer/", key -> key.endsWith("/1"));
+
+ assertThat(presentKeys(), containsInAnyOrder("layer/a/2", "other/1"));
+ }
+
+ @Test
+ public void testClear() {
+ putKeys();
+
+ store.clear();
+
+ assertThat(presentKeys(), empty());
+ }
+
+ @Test
+ public void testPutIfAbsentKeepsPresentValue() {
+ store.put("key", new byte[] {1}, 300);
+ store.putIfAbsent("key", new byte[] {2}, 300);
+ store.putIfAbsent("other", new byte[] {3}, 300);
+
+ assertArrayEquals(new byte[] {1}, store.get("key"));
+ assertArrayEquals(new byte[] {3}, store.get("other"));
+ }
+
+ @Test
+ public void testConcurrentGetsAndPutsGiveWholeValues() throws Exception {
+ List> tasks = new ArrayList<>();
+ AtomicInteger broken = new AtomicInteger();
+ for (int t = 1; t <= THREADS; t++) {
+ byte[] value = new byte[VALUE_SIZE];
+ Arrays.fill(value, (byte) t);
+ tasks.add(submit(() -> {
+ for (int i = 0; i < ROUNDS; i++) store.put("key", value.clone(), 300);
+ }));
+ tasks.add(submit(() -> {
+ for (int i = 0; i < ROUNDS; i++) if (!isWhole(store.get("key"))) broken.incrementAndGet();
+ }));
+ }
+ go.countDown();
+ for (Future> task : tasks) task.get(60, SECONDS);
+
+ assertEquals(0, broken.get());
+ }
+
+ /** Null, or the value of one writer: full length, every byte its id. */
+ private static boolean isWhole(byte[] value) {
+ if (value == null) return true;
+ if (value.length != VALUE_SIZE || value[0] == 0) return false;
+ for (byte b : value) if (b != value[0]) return false;
+ return true;
+ }
+
+ @Test
+ public void testRemoveByPrefixDuringPutsLeavesNoEarlierEntry() throws Exception {
+ AtomicBoolean removing = new AtomicBoolean();
+ AtomicBoolean done = new AtomicBoolean();
+ Queue before = new ConcurrentLinkedQueue<>();
+ CountDownLatch warm = new CountDownLatch(THREADS);
+ List> writers = new ArrayList<>();
+ for (int t = 0; t < THREADS; t++) {
+ String prefix = "layer/a/" + t + "/";
+ writers.add(submit(() -> {
+ for (int i = 0; !done.get(); i++) {
+ store.put(prefix + i, new byte[] {1}, 300);
+ // false after the put returned: it ended before the removal started
+ if (!removing.get()) before.add(prefix + i);
+ if (i == ROUNDS / 4) warm.countDown();
+ }
+ }));
+ }
+ go.countDown();
+ assertTrue(warm.await(60, SECONDS));
+ removing.set(true);
+ store.removeByPrefix("layer/a/");
+ done.set(true);
+ for (Future> writer : writers) writer.get(60, SECONDS);
+
+ assertThat(present(before), empty());
+ }
+
+ private Future> submit(Runnable task) {
+ return executor.submit((Callable) () -> {
+ go.await();
+ task.run();
+ return null;
+ });
+ }
+
+ private void putKeys() {
+ KEYS.forEach(key -> store.put(key, new byte[] {1}, 300));
+ }
+
+ private List presentKeys() {
+ return present(KEYS);
+ }
+
+ private List present(Collection keys) {
+ return keys.stream().filter(key -> store.get(key) != null).toList();
+ }
+}
diff --git a/geowebcache/core/src/test/java/org/geowebcache/storage/memorycache/CachingBlobStoreTest.java b/geowebcache/core/src/test/java/org/geowebcache/storage/memorycache/CachingBlobStoreTest.java
new file mode 100644
index 0000000000..b81501d954
--- /dev/null
+++ b/geowebcache/core/src/test/java/org/geowebcache/storage/memorycache/CachingBlobStoreTest.java
@@ -0,0 +1,1071 @@
+/**
+ * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General
+ * Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any
+ * later version.
+ *
+ *
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
+ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+ *
+ *
You should have received a copy of the GNU Lesser General Public License along with this program. If not, see
+ * .
+ *
+ *
Copyright 2026
+ */
+package org.geowebcache.storage.memorycache;
+
+import static java.util.concurrent.TimeUnit.SECONDS;
+import static org.awaitility.Awaitility.await;
+import static org.easymock.EasyMock.anyInt;
+import static org.easymock.EasyMock.createNiceMock;
+import static org.easymock.EasyMock.expect;
+import static org.easymock.EasyMock.replay;
+import static org.geowebcache.util.TMSKeyBuilder.PARAMETERS_METADATA_OBJECT_PREFIX;
+import static org.geowebcache.util.TMSKeyBuilder.PARAMETERS_METADATA_OBJECT_SUFFIX;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.allOf;
+import static org.hamcrest.Matchers.contains;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.empty;
+import static org.hamcrest.Matchers.greaterThanOrEqualTo;
+import static org.hamcrest.Matchers.hasEntry;
+import static org.hamcrest.Matchers.hasItem;
+import static org.hamcrest.Matchers.lessThanOrEqualTo;
+import static org.hamcrest.Matchers.startsWith;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
+
+import com.google.common.base.Ticker;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Queue;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.Predicate;
+import java.util.logging.Level;
+import org.geowebcache.config.ServerConfiguration;
+import org.geowebcache.filter.parameters.ParametersUtils;
+import org.geowebcache.io.ByteArrayResource;
+import org.geowebcache.layer.TileLayer;
+import org.geowebcache.layer.TileLayerDispatcher;
+import org.geowebcache.mime.ImageMime;
+import org.geowebcache.storage.BlobStore;
+import org.geowebcache.storage.BlobStoreAggregator;
+import org.geowebcache.storage.CompositeBlobStore;
+import org.geowebcache.storage.DefaultStorageFinder;
+import org.geowebcache.storage.StorageException;
+import org.geowebcache.storage.TileObject;
+import org.geowebcache.storage.TileRange;
+import org.geowebcache.storage.blobstore.file.FileBlobStore;
+import org.geowebcache.util.TMSKeyBuilder;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+/** Tile cache in front of a {@link FileBlobStore}, through {@link CompositeBlobStore} as in production. */
+public class CachingBlobStoreTest {
+
+ private static final String LAYER = "roads";
+
+ private static final String GRIDSET = "EPSG:4326";
+
+ private static final String OTHER_GRIDSET = "EPSG:900913";
+
+ private static final Map STYLE_A = Map.of("STYLES", "a");
+
+ private static final Map STYLE_B = Map.of("STYLES", "b");
+
+ @Rule
+ public TemporaryFolder temp = new TemporaryFolder();
+
+ @Rule
+ public LogLines log = new LogLines(CachingBlobStore.class, Level.FINE);
+
+ @Rule
+ public LogLines stateLog = new LogLines(GuardedStore.class, Level.INFO);
+
+ private final AtomicLong now = new AtomicLong();
+
+ private final Ticker ticker = new Ticker() {
+ @Override
+ public long read() {
+ return now.get();
+ }
+ };
+
+ private final FailingStore kv = new FailingStore(new HeapKeyValueStore(1_000_000, ticker));
+
+ private int expireCache;
+
+ private boolean memoryCached = true;
+
+ /** The layer's blob store id, null for the default store. */
+ private String blobStoreId;
+
+ // volatile: the concurrency tests replace the settings while other threads read them
+ private volatile MemoryCacheInfo memoryCacheInfo;
+
+ private final ExecutorService executor = Executors.newCachedThreadPool();
+
+ /** Built by {@link #newCache}, closed after the test. */
+ private final List caches = new ArrayList<>();
+
+ private TileLayer layer;
+
+ private TileLayerDispatcher layers;
+
+ private CompositeBlobStore store;
+
+ @Before
+ public void setUp() throws Exception {
+ layer = createNiceMock(TileLayer.class);
+ expect(layer.getName()).andStubReturn(LAYER);
+ expect(layer.getId()).andStubReturn("layer-id");
+ expect(layer.isMemoryCached()).andStubAnswer(() -> memoryCached);
+ expect(layer.getBlobStoreId()).andStubAnswer(() -> blobStoreId);
+ expect(layer.getExpireCache(anyInt())).andStubAnswer(() -> expireCache);
+ expect(layer.getGridSubsets()).andStubReturn(Set.of(GRIDSET, OTHER_GRIDSET));
+ expect(layer.getMimeTypes()).andStubReturn(List.of(ImageMime.png));
+ // a standalone layer, whose id is its name
+ TileLayer renamed = createNiceMock(TileLayer.class);
+ expect(renamed.getId()).andStubReturn("renamed");
+ layers = createNiceMock(TileLayerDispatcher.class);
+ expect(layers.getTileLayer(LAYER)).andStubReturn(layer);
+ expect(layers.getTileLayer("renamed")).andStubReturn(renamed);
+ DefaultStorageFinder storageFinder = createNiceMock(DefaultStorageFinder.class);
+ expect(storageFinder.getDefaultPath()).andStubReturn(temp.getRoot().getAbsolutePath());
+ BlobStoreAggregator aggregator = createNiceMock(BlobStoreAggregator.class);
+ expect(aggregator.getBlobStores()).andStubReturn(List.of());
+ ServerConfiguration serverConfig = createNiceMock(ServerConfiguration.class);
+ expect(serverConfig.getMemoryCache()).andStubAnswer(() -> memoryCacheInfo);
+ replay(layer, renamed, layers, storageFinder, aggregator, serverConfig);
+
+ store = new CompositeBlobStore(layers, storageFinder, serverConfig, aggregator);
+ // tests writing to the store alone first set the settings to null
+ enableCache(false);
+ }
+
+ @After
+ public void tearDown() {
+ executor.shutdownNow();
+ caches.forEach(MemoryCache::close);
+ }
+
+ @Test
+ public void testPassthroughOffServesTilesFromCacheOnly() throws Exception {
+ long before = System.currentTimeMillis();
+ store.put(tile(0, 0, 0));
+ long after = System.currentTimeMillis();
+
+ TileObject read = tile(0, 0, 0);
+ assertTrue(store.get(read));
+ assertArrayEquals(new byte[] {1, 2, 3}, ((ByteArrayResource) read.getBlob()).getContents());
+ assertThat(read.getCreated(), allOf(greaterThanOrEqualTo(before), lessThanOrEqualTo(after)));
+ assertFalse(inStore(tile(0, 0, 0)));
+ }
+
+ @Test
+ public void testPassthroughOnWritesAndReadsThroughStore() throws Exception {
+ memoryCacheInfo = null;
+ store.put(tile(0, 0, 0));
+ enableCache(true);
+ assertTrue(store.get(tile(0, 0, 0)));
+
+ // remove from the store only, the cache still has it
+ memoryCacheInfo = null;
+ store.delete(tile(0, 0, 0));
+ enableCache(true);
+ assertTrue(store.get(tile(0, 0, 0)));
+
+ store.put(tile(1, 0, 1));
+ assertTrue(inStore(tile(1, 0, 1)));
+ }
+
+ @Test
+ public void testNoReadThroughWithPassthroughOff() throws Exception {
+ memoryCacheInfo = null;
+ store.put(tile(0, 0, 0));
+ enableCache(false);
+
+ assertFalse(store.get(tile(0, 0, 0)));
+ }
+
+ @Test
+ public void testLayerExpireCacheSetsTimeToLive() throws Exception {
+ // shorter than the global time to live, then longer
+ expireCache = 10;
+ store.put(tile(0, 0, 0));
+ expireCache = 3600;
+ store.put(tile(1, 0, 1));
+
+ now.set(SECONDS.toNanos(10));
+ assertFalse(store.get(tile(0, 0, 0)));
+ now.set(SECONDS.toNanos(memoryCacheInfo.getTimeToLive() + 1));
+ assertTrue(store.get(tile(1, 0, 1)));
+ now.set(SECONDS.toNanos(3600));
+ assertFalse(store.get(tile(1, 0, 1)));
+ }
+
+ @Test
+ public void testDeleteLayer() throws Exception {
+ store.put(tile(0, 0, 0));
+ store.put(tile(OTHER_GRIDSET, STYLE_B, 0, 0, 0));
+
+ store.delete(LAYER);
+
+ assertFalse(store.get(tile(0, 0, 0)));
+ assertFalse(store.get(tile(OTHER_GRIDSET, STYLE_B, 0, 0, 0)));
+ }
+
+ @Test
+ public void testRenameDropsTilesOnlyWhenIdChanges() throws Exception {
+ // no parameters, so no mapping file, and no layer directory for the file store rename to trip on
+ store.put(tile(GRIDSET, null, 0, 0, 0));
+ int calls = kv.calls.get();
+
+ // as in GeoServer: the new name resolves to an id the rename keeps
+ store.rename("old-name", LAYER);
+ assertEquals(calls, kv.calls.get());
+ assertTrue(store.get(tile(GRIDSET, null, 0, 0, 0)));
+
+ // standalone layer ids are their names, so the old name is the id the tiles were cached under
+ store.rename("layer-id", "renamed");
+ assertFalse(store.get(tile(GRIDSET, null, 0, 0, 0)));
+ }
+
+ @Test
+ public void testDeleteGridset() throws Exception {
+ store.put(tile(0, 0, 0));
+ store.put(tile(OTHER_GRIDSET, STYLE_A, 0, 0, 0));
+
+ store.deleteByGridsetId(LAYER, GRIDSET);
+
+ assertFalse(store.get(tile(0, 0, 0)));
+ assertTrue(store.get(tile(OTHER_GRIDSET, STYLE_A, 0, 0, 0)));
+ }
+
+ @Test
+ public void testDeleteParameters() throws Exception {
+ store.put(tile(0, 0, 0));
+ store.put(tile(OTHER_GRIDSET, STYLE_A, 0, 0, 0));
+ store.put(tile(GRIDSET, STYLE_B, 0, 0, 0));
+
+ store.deleteByParameters(LAYER, STYLE_A);
+
+ assertFalse(store.get(tile(0, 0, 0)));
+ assertFalse(store.get(tile(OTHER_GRIDSET, STYLE_A, 0, 0, 0)));
+ assertTrue(store.get(tile(GRIDSET, STYLE_B, 0, 0, 0)));
+ }
+
+ @Test
+ public void testTruncateSucceedsOnEmptyStoreWithPassthroughOff() throws Exception {
+ // no parameters, so no mapping file and no layer directory in the store behind
+ store.put(tile(GRIDSET, null, 0, 0, 0));
+
+ assertTrue(store.deleteByGridsetId(LAYER, GRIDSET));
+ assertFalse(store.get(tile(GRIDSET, null, 0, 0, 0)));
+ }
+
+ @Test
+ public void testTileTruncatesSkipStoreWithPassthroughOff() throws Exception {
+ enableCache(true);
+ store.put(tile(0, 0, 1));
+ enableCache(false);
+
+ assertTrue(store.delete(tile(0, 0, 1)));
+ assertTrue(store.delete(range()));
+ assertTrue(store.deleteByGridsetId(LAYER, GRIDSET));
+
+ // the store behind was not called: the tile written before passthrough was turned off is still there
+ assertTrue(inStore(tile(0, 0, 1)));
+ assertTrue(mappingFile().exists());
+
+ // a layer truncate still reaches it, removing tiles and mappings
+ enableCache(false);
+ store.delete(LAYER);
+ assertFalse(inStore(tile(0, 0, 1)));
+ assertFalse(mappingFile().exists());
+ }
+
+ @Test
+ public void testDeleteTile() throws Exception {
+ store.put(tile(0, 0, 1));
+ store.put(tile(1, 0, 1));
+
+ store.delete(tile(0, 0, 1));
+
+ assertFalse(store.get(tile(0, 0, 1)));
+ assertTrue(store.get(tile(1, 0, 1)));
+ }
+
+ @Test
+ public void testDeleteRange() throws Exception {
+ store.put(tile(0, 0, 1));
+ store.put(tile(1, 1, 1));
+ store.put(tile(10, 10, 2));
+ // a key that is not a tile, under a zoom level of the range
+ String tileKey = key(tile(0, 0, 1));
+ String stray = tileKey.substring(0, tileKey.lastIndexOf('/') + 1) + "stray";
+ kv.put(stray, new byte[] {1}, 300);
+
+ assertTrue(store.delete(range()));
+
+ // zoom 2 is outside the range, x 1 is outside its bounds at zoom 1
+ assertFalse(store.get(tile(0, 0, 1)));
+ assertTrue(store.get(tile(1, 1, 1)));
+ assertTrue(store.get(tile(10, 10, 2)));
+ assertNull(kv.get(stray));
+ }
+
+ @Test
+ public void testReadResultsLogged() throws Exception {
+ memoryCacheInfo = null;
+ store.put(tile(0, 0, 0));
+ enableCache(true);
+ expireCache = 10;
+ // written by a node whose clock is 60 s behind, so already past the layer's expire server cache
+ kv.put(key(tile(1, 0, 1)), cacheValue((byte) 1, System.currentTimeMillis() - 60_000), 300);
+
+ store.get(tile(2, 0, 1));
+ store.get(tile(0, 0, 0));
+ store.get(tile(0, 0, 0));
+ store.get(tile(1, 0, 1));
+ kv.failing = true;
+ store.get(tile(0, 0, 0));
+
+ List results =
+ log.lines.stream().map(line -> line.split(" ")[3]).toList();
+ assertThat(results, contains("miss", "store", "hit", "expired", "error"));
+ assertThat(
+ log.lines.get(0),
+ startsWith("In-memory tile cache miss for layer roads, gridset EPSG:4326, z/x/y 1/2/0 in "));
+ }
+
+ @Test
+ public void testReadThroughKeepsOnlyRemainingLifetime() throws Exception {
+ memoryCacheInfo = null;
+ long millis = System.currentTimeMillis();
+ TileObject old = tile(0, 0, 0);
+ old.setCreated(millis - 60_000);
+ store.put(old);
+ TileObject recent = tile(1, 0, 1);
+ recent.setCreated(millis - 4_000);
+ store.put(recent);
+ enableCache(true);
+ expireCache = 10;
+
+ assertTrue(store.get(tile(0, 0, 0)));
+ assertTrue(store.get(tile(1, 0, 1)));
+
+ // the old tile is past the expire server cache, the recent one has at most 6 s left
+ assertNull(kv.get(key(tile(0, 0, 0))));
+ assertNotNull(kv.get(key(tile(1, 0, 1))));
+ now.addAndGet(SECONDS.toNanos(6));
+ assertNull(kv.get(key(tile(1, 0, 1))));
+ }
+
+ @Test
+ public void testMappingWrittenOnceUntilTruncated() throws Exception {
+ store.put(tile(0, 0, 0));
+ // listed, so that truncates by parameters can still find it
+ assertThat(store.getParametersMapping(LAYER), hasEntry(ParametersUtils.getId(STYLE_A), Optional.of(STYLE_A)));
+ assertTrue(mappingFile().delete());
+
+ store.put(tile(1, 0, 1));
+ assertFalse(mappingFile().exists());
+
+ store.deleteByParameters(LAYER, STYLE_A);
+ store.put(tile(1, 0, 1));
+ assertTrue(mappingFile().exists());
+
+ // a layer truncate forgets the mappings too
+ store.delete(LAYER);
+ store.put(tile(0, 0, 0));
+ assertTrue(mappingFile().exists());
+ }
+
+ @Test
+ public void testConcurrentPutsWriteMappingOnce() throws Exception {
+ MappingCountingStore delegate = new MappingCountingStore();
+ BlobStore cached = newCache().wrap(layer, delegate);
+ List> puts = new ArrayList<>();
+ for (int x = 0; x < 16; x++) {
+ TileObject tile = tile(x, 0, 4);
+ puts.add(executor.submit(() -> {
+ cached.put(tile);
+ return null;
+ }));
+ }
+ for (Future