Skip to content

Commit b912734

Browse files
committed
[docs] Document the Batcher and CacheKey features
1 parent b3ea063 commit b912734

2 files changed

Lines changed: 159 additions & 0 deletions

File tree

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
---
2+
title: Caching
3+
tags:
4+
- Routing
5+
- Caching
6+
- Performance
7+
---
8+
9+
<Since version="6.0" issueNumber="MDL-82652" />
10+
11+
Routes which return static, public assets (such as language strings and templates) can be made cacheable by browsers and reverse proxies by setting the `cachelifetime` property of the `\core\router\route` attribute.
12+
13+
## Declaring a cacheable route {/* #declaring-a-cacheable-route */}
14+
15+
`cachelifetime` accepts any relative time string understood by [`DateInterval::createFromDateString()`](https://www.php.net/manual/en/dateinterval.createfromdatestring.php), for example `'90 days'`.
16+
17+
```php title="A cacheable route"
18+
#[\core\router\route(
19+
path: '/strings/{language}/{component}[/{identifier:.*}]',
20+
method: ['GET'],
21+
security: [],
22+
cachelifetime: '90 days',
23+
pathtypes: [
24+
new \core\router\parameters\path_language(),
25+
new \core\router\parameters\path_component(),
26+
],
27+
)]
28+
```
29+
30+
:::danger
31+
32+
Responses are cached as `public` and `immutable`. Only use `cachelifetime` for routes whose response is identical for every user and which never contains private data.
33+
34+
:::
35+
36+
## The cache key {/* #the-cache-key */}
37+
38+
When `cachelifetime` is set, the route automatically gains an optional `cachekey` path parameter (`\core\router\parameters\path_cachekey`), which is a Unix timestamp placed at the start of the path:
39+
40+
```text
41+
/api/rest/v2/strings/en/core # No cache key - not cached
42+
/api/rest/v2/cachekey:1737584047/strings/en/core # Cacheable
43+
```
44+
45+
Because the cache key forms part of the URI, changing it (typically by using the current JavaScript/theme revision) invalidates every cached copy of the resource. You do not need to declare the parameter yourself.
46+
47+
## Cache headers {/* #cache-headers */}
48+
49+
The `\core\router\middleware\cache_control_middleware` adds the following headers when all of these are true:
50+
51+
- the request method is `GET`;
52+
- the response status is 2xx;
53+
- the route has a `cachelifetime`;
54+
- a numeric `cachekey` was supplied, and it is not in the future (to prevent cache poisoning); and
55+
- the lifetime resolves to a positive number of seconds.
56+
57+
| Header | Value |
58+
| --- | --- |
59+
| `Cache-Control` | `public, max-age=<seconds>, immutable` |
60+
| `Expires` | The current time plus the lifetime |
61+
| `Pragma` | _(empty)_ |
62+
| `Accept-Ranges` | `none` |
63+
64+
The expiry is calculated from the current time, not from the cache key, so cached content does not expire early because an old key was used.
65+
66+
If any condition is not met, no caching headers are added.
67+
68+
## Fetching cacheable routes from JavaScript {/* #fetching-cacheable-routes-from-JavaScript */}
69+
70+
Pass the `cachekey` option to the [`core/fetch`](../../../guides/javascript/ajax/batcher.md) module:
71+
72+
```js
73+
import Fetch from 'core/fetch';
74+
75+
const response = await Fetch.performGet('core', `strings/en/core`, {cachekey: M.cfg.jsrev});
76+
```
77+
78+
Requests with a cache key bypass the [batcher](../../../guides/javascript/ajax/batcher.md) by default, so that every URL can be cached individually.
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
---
2+
title: The Fetch batcher
3+
tags:
4+
- Javascript
5+
- AJAX
6+
- Fetch
7+
- Routing
8+
---
9+
10+
<Since version="6.0" issueNumber="MDL-82652" />
11+
12+
The `core/fetch` module makes requests to the Moodle [REST API (routes)](../../../apis/subsystems/routing/index.md). In addition to immediate requests, it can queue several requests and send them as a single HTTP `$batch` request, reducing the number of round trips.
13+
14+
## Immediate requests {/* #immediate-requests */}
15+
16+
Static methods perform a single request immediately:
17+
18+
```js
19+
import Fetch from 'core/fetch';
20+
21+
const response = await Fetch.performGet('mod_example', 'animals', {params: {type: 'mammal'}});
22+
```
23+
24+
`performGet`, `performHead`, `performPost`, `performPut`, `performPatch` and `performDelete` are available.
25+
26+
## Batching requests {/* #batching-requests */}
27+
28+
The same methods are available on an _instance_. Instance calls are queued and sent together.
29+
30+
### The automatic batcher {/* #the-automatic-batcher */}
31+
32+
`Fetch.getBatcher()` returns a shared singleton which automatically executes the queue 50ms after the last request was added.
33+
34+
```js
35+
import Fetch from 'core/fetch';
36+
37+
const batcher = Fetch.getBatcher();
38+
const [mammals, reptiles] = await Promise.all([
39+
batcher.performGet('mod_example', 'animals', {params: {type: 'mammal'}}),
40+
batcher.performGet('mod_example', 'animals', {params: {type: 'reptile'}}),
41+
batcher.performDelete('mod_example', `animals/${pig.id}`),
42+
]);
43+
```
44+
45+
Each call returns a `Promise` resolving to a standard `Response` for that sub-request, and failures reject only the individual promise.
46+
47+
### A manual batcher {/* #a-manual-batcher */}
48+
49+
Create an instance yourself and call `execute()` when ready. An optional constructor argument sets an auto-execute delay in milliseconds.
50+
51+
```js
52+
const batcher = new Fetch();
53+
const results = Promise.all([
54+
batcher.performGet('mod_example', 'animals', {params: {type: 'mammal'}}),
55+
batcher.performGet('mod_example', 'animals', {params: {type: 'reptile'}}),
56+
]);
57+
58+
batcher.execute();
59+
await results;
60+
```
61+
62+
## Behaviour notes {/* #behaviour-notes */}
63+
64+
- If a batch contains a single request, the batch endpoint is _not_ used; it is sent as a normal request.
65+
- The queue is flushed automatically once it holds more than 20 requests.
66+
- If the `$CFG->batch_fetch_requests` setting (JS: `M.cfg.batchFetchRequests`, default `true`) is disabled, each request is executed immediately instead of being queued.
67+
68+
## Cacheable requests bypass the batcher {/* #cacheable-requests-bypass-the-batcher */}
69+
70+
Requests made with a `cachekey` (see [route caching](../../../apis/subsystems/routing/caching.md)) are sent individually, even via a batcher. Hiding them inside a generic `$batch` request would prevent browsers and reverse proxies caching each URL.
71+
72+
```js
73+
const response = await Fetch.getBatcher().performGet('core', 'strings/en/core', {cachekey: M.cfg.jsrev});
74+
```
75+
76+
To batch these requests anyway, set `$CFG->batch_api_asset_requests = true` (JS: `M.cfg.batchApiAssetRequests`).
77+
78+
## See also {/* #see-also */}
79+
80+
- [AJAX](./index.md)
81+
- [Routing: Caching](../../../apis/subsystems/routing/caching.md)

0 commit comments

Comments
 (0)