PromucFlow_constructor/app/client/src/serviceWorker.ts
Diljit 01cda23c3d
chore: add etag caching in consolidated api for application view mode (#38873)
## Description
- Implement Etag caching for consolidated api in view mode.
  - Generate Etag for consolidated api in view mode
- compare the if none match header with the computed etag and respond
with either a 304 or 200
  - add span for generate etag fn
- Remove prefetching and caching of static assets in service worker  

```mermaid
sequenceDiagram
    Client->>Server: Request Consolidated API
    Server-->>Server: Compute ETag
    Server-->>Client: Respond with ETag, Cache-Control
    Client->>Server: Subsequent Request with If-None-Match
    alt ETag Matches
        Server-->>Client: 304 Not Modified
    else ETag Different
        Server-->>Client: Full Response with New ETag
    end
```

## Automation

/ok-to-test tags="@tag.All"

### 🔍 Cypress test results
<!-- This is an auto-generated comment: Cypress test results  -->
> [!TIP]
> 🟢 🟢 🟢 All cypress tests have passed! 🎉 🎉 🎉
> Workflow run:
<https://github.com/appsmithorg/appsmith/actions/runs/13046610688>
> Commit: c14d58da8a59b3bbfb10c7e308b518d2cd8e3b7d
> <a
href="https://internal.appsmith.com/app/cypress-dashboard/rundetails-65890b3c81d7400d08fa9ee5?branch=master&workflowId=13046610688&attempt=1"
target="_blank">Cypress dashboard</a>.
> Tags: `@tag.All`
> Spec:
> <hr>Thu, 30 Jan 2025 07:14:21 UTC
<!-- end of auto-generated comment: Cypress test results  -->


## Communication
Should the DevRel and Marketing teams inform users about this change?
- [ ] Yes
- [x] No


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **New Features**
- Added ETag support for consolidated API responses to improve caching
efficiency.
- Introduced a new route handler for the `/api/v1/consolidated-api/view`
endpoint.

- **Performance Improvements**
	- Optimized NGINX configuration for API responses.
	- Updated tracing endpoint for better monitoring.

- **Dependency Updates**
	- Added Jackson datatype support for Java 8 date and time handling.

- **Technical Enhancements**
	- Improved request handling in ConsolidatedAPIController.
	- Updated service worker configuration.
	- Refined feature flag handling in the client.
	- Enhanced API request headers for consolidated page load functions.
	- Simplified caching and routing logic in the service worker.
	- Adjusted service worker caching strategy for production environment.
	- Updated test specification path for Cypress limited tests.
- Modified request handling to remove unnecessary headers in feature
flag functions.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2025-01-30 13:54:34 +05:30

78 lines
2.3 KiB
TypeScript

import { clientsClaim, skipWaiting } from "workbox-core";
import { registerRoute, Route } from "workbox-routing";
import { NetworkOnly } from "workbox-strategies";
import {
cachedApiUrlRegex,
getApplicationParamsFromUrl,
getPrefetchRequests,
PrefetchApiService,
} from "ee/utils/serviceWorkerUtils";
import type { RouteHandlerCallback } from "workbox-core/types";
// eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any
const wbManifest = (self as any).__WB_MANIFEST;
// Delete the old pre-fetch cache. All static files are now cached by cache control headers.
caches.delete("appsmith-precache-v1");
self.__WB_DISABLE_DEV_LOGS = true;
skipWaiting();
clientsClaim();
const prefetchApiService = new PrefetchApiService();
/**
* Route handler callback for HTML pages.
* This callback is responsible for prefetching the API requests for the application page.
*/
const htmlRouteHandlerCallback: RouteHandlerCallback = async ({
event,
request,
url,
}) => {
// Extract application params from the URL
const applicationParams = getApplicationParamsFromUrl(url);
// If application params are present, prefetch the API requests for the application
if (applicationParams) {
const prefetchRequests = getPrefetchRequests(applicationParams);
prefetchRequests.forEach((prefetchRequest) => {
prefetchApiService.cacheApi(prefetchRequest).catch(() => {
// Silently fail
});
});
}
const networkHandler = new NetworkOnly();
return networkHandler.handle({ event, request });
};
registerRoute(
new Route(({ request, sameOrigin }) => {
return sameOrigin && request.destination === "document";
}, htmlRouteHandlerCallback),
);
// Route for fetching the API directly
registerRoute(
// Intercept requests to the consolidated API and module instances API
cachedApiUrlRegex,
async ({ event, request }) => {
// Check for cached response
const cachedResponse = await prefetchApiService.getCachedResponse(request);
// If the response is cached, return the response
if (cachedResponse) {
return cachedResponse;
}
// If the response is not cached, fetch the response
const networkHandler = new NetworkOnly();
return networkHandler.handle({ event, request });
},
"GET",
);