From 1e702c2a993162a9c3867cbde1357a380da89989 Mon Sep 17 00:00:00 2001
From: Sergei Zharinov <zharinov@users.noreply.github.com>
Date: Mon, 10 Feb 2025 13:15:35 -0300
Subject: [PATCH] feat(http): Create memory cache provider (#33900)

---
 .../cache/memory-http-cache-provider.spec.ts  | 39 +++++++++++++++++++
 .../http/cache/memory-http-cache-provider.ts  | 21 ++++++++++
 2 files changed, 60 insertions(+)
 create mode 100644 lib/util/http/cache/memory-http-cache-provider.spec.ts
 create mode 100644 lib/util/http/cache/memory-http-cache-provider.ts

diff --git a/lib/util/http/cache/memory-http-cache-provider.spec.ts b/lib/util/http/cache/memory-http-cache-provider.spec.ts
new file mode 100644
index 0000000000..365a7aa8a1
--- /dev/null
+++ b/lib/util/http/cache/memory-http-cache-provider.spec.ts
@@ -0,0 +1,39 @@
+import { Http } from '..';
+import * as httpMock from '../../../../test/http-mock';
+import * as memCache from '../../cache/memory';
+import { memCacheProvider as cacheProvider } from './memory-http-cache-provider';
+
+describe('util/http/cache/memory-http-cache-provider', () => {
+  beforeEach(() => {
+    memCache.init();
+  });
+
+  afterEach(() => {
+    memCache.reset();
+  });
+
+  const http = new Http('test');
+
+  it('reuses data with etag', async () => {
+    const scope = httpMock.scope('https://example.com');
+
+    scope.get('/foo/bar').reply(200, { msg: 'Hello, world!' }, { etag: '123' });
+    const res1 = await http.getJsonUnchecked('https://example.com/foo/bar', {
+      cacheProvider,
+    });
+    expect(res1).toMatchObject({
+      statusCode: 200,
+      body: { msg: 'Hello, world!' },
+      authorization: false,
+    });
+
+    const res2 = await http.getJsonUnchecked('https://example.com/foo/bar', {
+      cacheProvider,
+    });
+    expect(res2).toMatchObject({
+      statusCode: 200,
+      body: { msg: 'Hello, world!' },
+      authorization: false,
+    });
+  });
+});
diff --git a/lib/util/http/cache/memory-http-cache-provider.ts b/lib/util/http/cache/memory-http-cache-provider.ts
new file mode 100644
index 0000000000..86ca660733
--- /dev/null
+++ b/lib/util/http/cache/memory-http-cache-provider.ts
@@ -0,0 +1,21 @@
+import * as memCache from '../../cache/memory';
+import { AbstractHttpCacheProvider } from './abstract-http-cache-provider';
+import type { HttpCache } from './schema';
+
+export class MemoryHttpCacheProvider extends AbstractHttpCacheProvider {
+  private cacheKey(url: string): string {
+    return `memory-cache-http-provider:${url}`;
+  }
+
+  protected override load(url: string): Promise<unknown> {
+    const data = memCache.get<HttpCache>(this.cacheKey(url));
+    return Promise.resolve(data);
+  }
+
+  protected override persist(url: string, data: HttpCache): Promise<void> {
+    memCache.set(this.cacheKey(url), data);
+    return Promise.resolve();
+  }
+}
+
+export const memCacheProvider = new MemoryHttpCacheProvider();
-- 
GitLab