Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add an application cache for REST API #9173

Closed
wants to merge 48 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
48 commits
Select commit Hold shift + click to select a range
d1e61c4
Initial implementation using Express middleware cached response handler.
Aug 27, 2024
5bbb6bf
some main middleware cleanup.
Aug 27, 2024
67458f9
Merge remote-tracking branch 'origin/main' into 9111-add-an-applicati…
Aug 27, 2024
9b8ede9
Updated cache implementation and added tests.
Aug 29, 2024
126142f
responseHandler is no longer last middleware in chain, so provide non…
Aug 29, 2024
0c78e48
Initial implementation of responseCacheHandler.test.js and basic cach…
Sep 2, 2024
cfc4734
Merge remote-tracking branch 'origin/main' into 9111-add-an-applicati…
Sep 2, 2024
38361ef
Clean up. Ditched settable cache key generator. Sort out test Cache i…
Sep 4, 2024
9542641
Merge remote-tracking branch 'origin/main' into 9111-add-an-applicati…
Sep 4, 2024
6b41d1f
Utilize Redis ttl to set cached response max-age. Set Redist expiry b…
Sep 5, 2024
fc40177
Set cached response cache control header value appropriately.
Sep 5, 2024
e075c1f
Merge remote-tracking branch 'origin/main' into 9111-add-an-applicati…
Sep 5, 2024
c3cd594
Implementation and test improvements.
Sep 6, 2024
3b7f584
Fixed fetching of cached HTTP status code. Some clean up.
Sep 8, 2024
2d013c8
Merge remote-tracking branch 'origin/main' into 9111-add-an-applicati…
Sep 8, 2024
7c4f881
On cache hit remove content-encoding header so that compression middl…
Sep 8, 2024
5323542
Updatetd cache hit test, and added new cache bypass attempt test.
Sep 8, 2024
7551614
Cleanly shutdown responseCacheHandler test.
Sep 9, 2024
d9d9eb9
More test cleanup. Added inital cache update (back-end) tests.
Sep 9, 2024
926a774
More tidying up. Made cache bypass logging at debug level.
Sep 9, 2024
c6d07a5
Added test for cache update of valid response. Other clean up.
Sep 9, 2024
20da06c
Add config option to enable application response cache.
Sep 10, 2024
2aa6b77
Merge remote-tracking branch 'origin/main' into 9111-add-an-applicati…
Sep 10, 2024
f9bb37f
Also cache response on 304.
Sep 10, 2024
f7bd738
Removed cache bypass logging. Not too useful at debug level. Removed …
Sep 10, 2024
7faac24
One more Snyk test.
Sep 10, 2024
f80f575
Restore functionality. Remove cache bypass test.
Sep 10, 2024
d996fe3
Merge remote-tracking branch 'origin/main' into 9111-add-an-applicati…
Sep 10, 2024
baa51b2
Added application-cache.test.js to verify HEAD requests.
Sep 10, 2024
f49b926
Merge remote-tracking branch 'origin/main' into 9111-add-an-applicati…
Sep 11, 2024
28bef13
Minor clean up.
Sep 11, 2024
b9cd216
Exclude responseCacheHander.js from Snyk.
Sep 11, 2024
f7bb252
Significant reworking.
Sep 12, 2024
c89ceb6
Merge remote-tracking branch 'origin/main' into 9111-add-an-applicati…
Sep 13, 2024
05ecaa6
Some clean up.
Sep 13, 2024
854c908
Merge remote-tracking branch 'origin/main' into 9111-add-an-applicati…
Sep 13, 2024
7b2d5d1
Document new property. Minor cleanup.
Sep 16, 2024
af63771
Merge remote-tracking branch 'origin/main' into 9111-add-an-applicati…
Sep 17, 2024
254efad
Share Redis connection among Cache instances. Some test restructuring.
Sep 19, 2024
5270504
Merge remote-tracking branch 'origin/main' into 9111-add-an-applicati…
Sep 19, 2024
474d3c0
Test clean up.
Sep 19, 2024
c9e2934
Define Redis URL appropriately.
Sep 19, 2024
f856876
Merge remote-tracking branch 'origin/main' into 9111-add-an-applicati…
Sep 23, 2024
9ee4839
Merge remote-tracking branch 'origin/main' into 9111-add-an-applicati…
Sep 25, 2024
3523158
Fix connection ready state.
Sep 25, 2024
b087e5f
Restore REST Cache to its former, non-shared Redis, glory.
Sep 27, 2024
7ac1c76
Merge remote-tracking branch 'origin/main' into 9111-add-an-applicati…
Sep 27, 2024
2b65162
Merge remote-tracking branch 'origin/main' into 9111-add-an-applicati…
Sep 30, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions hedera-mirror-rest/cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,23 @@
return this.redis.flushall();
}

async getSingle(key) {
if (key === undefined || !this.ready) {
return undefined;
}

const value = this.redis.get(key);

Check warning on line 81 in hedera-mirror-rest/cache.js

View check run for this annotation

Codecov / codecov/patch

hedera-mirror-rest/cache.js#L81

Added line #L81 was not covered by tests
return value === undefined ? value : JSONParse(value);
}

async setSingle(key, value, expiry) {
if (key === undefined || !this.ready) {
return undefined;
}

return this.redis.setex(key, expiry, JSONStringify(value));

Check warning on line 90 in hedera-mirror-rest/cache.js

View check run for this annotation

Codecov / codecov/patch

hedera-mirror-rest/cache.js#L90

Added line #L90 was not covered by tests
}

async get(keys, loader, keyMapper = (k) => (k ? k.toString() : k)) {
if (_.isEmpty(keys)) {
return [];
Expand Down
4 changes: 4 additions & 0 deletions hedera-mirror-rest/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ const requestIdLabel = 'requestId';
const requestPathLabel = 'requestPath';
const requestStartTime = 'requestStartTime';
const responseContentType = 'responseContentType';
const responseBodyLabel = 'responseBody';
const responseCacheKeyLabel = 'responseCacheKey';
const responseDataLabel = 'responseData';

const orderFilterValues = {
Expand Down Expand Up @@ -250,6 +252,8 @@ export {
requestIdLabel,
requestPathLabel,
requestStartTime,
responseBodyLabel,
responseCacheKeyLabel,
responseContentType,
responseDataLabel,
tokenTypeFilter,
Expand Down
1 change: 1 addition & 0 deletions hedera-mirror-rest/middleware/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@ export {handleError} from './httpErrorHandler';
export * from './metricsHandler';
export {openApiValidator, serveSwaggerDocs} from './openapiHandler';
export * from './requestHandler';
export {responseCacheCheckHandler, responseCacheUpdateHandler} from './responseCacheHandler.js';
export {default as responseHandler} from './responseHandler';
60 changes: 60 additions & 0 deletions hedera-mirror-rest/middleware/responseCacheHandler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* Copyright (C) 2024 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import {Cache} from '../cache';
import CachedApiResponse from '../model/cachedApiResponse.js';
import {requestStartTime, responseCacheKeyLabel} from '../constants.js';

const cache = new Cache();

const responseCacheCheckHandler = async (req, res, next) => {
const responseCacheKey = req.path; // Call Edwin's function here
const cachedResponse = await cache.getSingle(responseCacheKey);

if (cachedResponse === undefined) {
logger.debug(`Cache miss: ${responseCacheKey}`);
res.locals[responseCacheKeyLabel] = responseCacheKey;
next();
} else {
logger.debug(`Cache hit: ${responseCacheKey}`);

Check warning on line 32 in hedera-mirror-rest/middleware/responseCacheHandler.js

View check run for this annotation

Codecov / codecov/patch

hedera-mirror-rest/middleware/responseCacheHandler.js#L31-L32

Added lines #L31 - L32 were not covered by tests
// TODO adjust cache-control header and decrement time it's been locally cached.
res.set(cachedResponse.headers);
res.status(cachedResponse.status);
res.send(cachedResponse.body);

Check warning on line 36 in hedera-mirror-rest/middleware/responseCacheHandler.js

View check run for this annotation

Codecov / codecov/patch

hedera-mirror-rest/middleware/responseCacheHandler.js#L34-L36

Added lines #L34 - L36 were not covered by tests

const startTime = res.locals[requestStartTime];

Check warning on line 38 in hedera-mirror-rest/middleware/responseCacheHandler.js

View check run for this annotation

Codecov / codecov/patch

hedera-mirror-rest/middleware/responseCacheHandler.js#L38

Added line #L38 was not covered by tests
const elapsed = startTime ? Date.now() - startTime : 0;
logger.info(`Cached - ${req.ip} ${req.method} ${req.originalUrl} in ${elapsed} ms: ${code}`);

Check warning on line 40 in hedera-mirror-rest/middleware/responseCacheHandler.js

View check run for this annotation

Codecov / codecov/patch

hedera-mirror-rest/middleware/responseCacheHandler.js#L40

Added line #L40 was not covered by tests
}
};

// Response middleware that caches the completed response.
// Next param is required to ensure express maps to this middleware and can also be used to pass onto future middleware
const responseCacheUpdateHandler = async (req, res, next) => {
const responseCacheKey = res.locals[responseCacheKeyLabel];
if (responseCacheKey === undefined) {
return; // Response is not to be cached

Check warning on line 49 in hedera-mirror-rest/middleware/responseCacheHandler.js

View check run for this annotation

Codecov / codecov/patch

hedera-mirror-rest/middleware/responseCacheHandler.js#L49

Added line #L49 was not covered by tests
}

const cachedResponse = new CachedApiResponse(res);
const headers = res.getHeaders();
const cacheControlHeader = headers['cache-control'];
// Grok header value to set expiry below.

cache.setSingle(responseCacheKey, cachedResponse, 300);
};

export {responseCacheCheckHandler, responseCacheUpdateHandler};
17 changes: 11 additions & 6 deletions hedera-mirror-rest/middleware/responseHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,13 @@
*/

import config from '../config';
import {requestPathLabel, requestStartTime, responseContentType, responseDataLabel} from '../constants';
import {
requestPathLabel,
requestStartTime,
responseBodyLabel,
responseContentType,
responseDataLabel,
} from '../constants';
import {NotFoundError} from '../errors';
import {JSONStringify} from '../utils';

Expand Down Expand Up @@ -50,16 +56,15 @@
res.set(LINK_NEXT_HEADER, linkNextHeaderValue(linksNext));
}

if (contentType === APPLICATION_JSON) {
res.send(JSONStringify(responseData));
} else {
res.send(responseData);
}
res.locals[responseBodyLabel] = contentType === APPLICATION_JSON ? JSONStringify(responseData) : responseData;
res.send(res.locals[responseBodyLabel]);

const startTime = res.locals[requestStartTime];
const elapsed = startTime ? Date.now() - startTime : 0;
logger.info(`${req.ip} ${req.method} ${req.originalUrl} in ${elapsed} ms: ${code}`);
}

next();

Check failure on line 67 in hedera-mirror-rest/middleware/responseHandler.js

View workflow job for this annotation

GitHub Actions / Build (rest, v1)

Response middleware › Custom headers

TypeError: next is not a function at next (middleware/responseHandler.js:67:3) at Object.responseHandler (__tests__/middleware/responseHandler.test.js:59:11)

Check failure on line 67 in hedera-mirror-rest/middleware/responseHandler.js

View workflow job for this annotation

GitHub Actions / Build (rest, v1)

Response middleware › Default headers

TypeError: next is not a function at next (middleware/responseHandler.js:67:3) at Object.responseHandler (__tests__/middleware/responseHandler.test.js:69:11)

Check failure on line 67 in hedera-mirror-rest/middleware/responseHandler.js

View workflow job for this annotation

GitHub Actions / Build (rest, v1)

Response middleware › Custom Content-Type

TypeError: next is not a function at next (middleware/responseHandler.js:67:3) at Object.responseHandler (__tests__/middleware/responseHandler.test.js:80:11)

Check failure on line 67 in hedera-mirror-rest/middleware/responseHandler.js

View workflow job for this annotation

GitHub Actions / Build (rest, v1)

Response middleware › should set the Link next header and confirm it exists

TypeError: next is not a function at next (middleware/responseHandler.js:67:3) at Object.responseHandler (__tests__/middleware/responseHandler.test.js:92:11)

Check failure on line 67 in hedera-mirror-rest/middleware/responseHandler.js

View workflow job for this annotation

GitHub Actions / Build (rest, v1)

Response middleware › should NOT set the Link next header and confirm it exists

TypeError: next is not a function at next (middleware/responseHandler.js:67:3) at Object.responseHandler (__tests__/middleware/responseHandler.test.js:97:11)
};

export default responseHandler;
31 changes: 31 additions & 0 deletions hedera-mirror-rest/model/cachedApiResponse.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* Copyright (C) 2024 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import {responseBodyLabel} from '../constants.js';

/**
* API response cached in Redis.
*/
class CachedApiResponse {
constructor(res) {
this.body = res.locals[responseBodyLabel];
this.cacheTime = Date.now();
this.headers = res.getHeaders();
this.status = res.statusCode;
}
}

export default CachedApiResponse;
2 changes: 2 additions & 0 deletions hedera-mirror-rest/model/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import AddressBook from './addressBook';
import AddressBookEntry from './addressBookEntry';
import AddressBookServiceEndpoint from './addressBookServiceEndpoint';
import AssessedCustomFee from './assessedCustomFee';
import CachedApiResponse from './cachedApiResponse';
import CachedToken from './cachedToken';
import Contract from './contract';
import CryptoAllowance from './cryptoAllowance';
Expand Down Expand Up @@ -66,6 +67,7 @@ export {
AddressBookEntry,
AddressBookServiceEndpoint,
AssessedCustomFee,
CachedApiResponse,
CachedToken,
Contract,
CryptoAllowance,
Expand Down
6 changes: 6 additions & 0 deletions hedera-mirror-rest/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ import {
recordIpAndEndpoint,
requestLogger,
requestQueryParser,
responseCacheCheckHandler,
responseCacheUpdateHandler,
responseHandler,
serveSwaggerDocs,
} from './middleware';
Expand Down Expand Up @@ -125,6 +127,9 @@ if (config.metrics.enabled) {
app.use(metricsHandler());
}

// Check for cached response
app.use(responseCacheCheckHandler);
jascks marked this conversation as resolved.
Show resolved Hide resolved

// accounts routes
app.getAsync(`${apiPrefix}/accounts`, accounts.getAccounts);
app.getAsync(`${apiPrefix}/accounts/:${constants.filterKeys.ID_OR_ALIAS_OR_EVM_ADDRESS}`, accounts.getOneAccount);
Expand Down Expand Up @@ -178,6 +183,7 @@ if (config.metrics.ipMetrics) {

// response data handling middleware
app.useAsync(responseHandler);
app.useAsync(responseCacheUpdateHandler);

// response error handling middleware
app.useAsync(handleError);
Expand Down
Loading