From 2c2693b55edf658bc73a98c5bbf2fc59922e7cb5 Mon Sep 17 00:00:00 2001
From: Sergei Zharinov <zharinov@users.noreply.github.com>
Date: Fri, 25 Mar 2022 07:17:08 +0300
Subject: [PATCH] refactor(packagist): Use cache decorator for datasource
 (#14768)

---
 lib/modules/datasource/packagist/index.ts | 57 ++++++++++++-----------
 1 file changed, 30 insertions(+), 27 deletions(-)

diff --git a/lib/modules/datasource/packagist/index.ts b/lib/modules/datasource/packagist/index.ts
index 6ccbf40d9d..af4a71b3fa 100644
--- a/lib/modules/datasource/packagist/index.ts
+++ b/lib/modules/datasource/packagist/index.ts
@@ -95,37 +95,40 @@ export class PackagistDatasource extends Datasource {
     return meta;
   }
 
-  private async getPackagistFile(
+  private static isPrivatePackage(regUrl: string): boolean {
+    const opts = PackagistDatasource.getHostOpts(regUrl);
+    return !!opts.password || !!opts.headers?.authorization;
+  }
+
+  private static getPackagistFileUrl(
     regUrl: string,
-    file: RegistryFile
-  ): Promise<PackagistFile> {
-    const { key, sha256 } = file;
+    regFile: RegistryFile
+  ): string {
+    const { key, sha256 } = regFile;
     const fileName = key.replace('%hash%', sha256);
+    const url = `${regUrl}/${fileName}`;
+    return url;
+  }
+
+  @cache({
+    namespace: `datasource-${PackagistDatasource.id}-public-files`,
+    key: (regUrl: string, regFile: RegistryFile) =>
+      PackagistDatasource.getPackagistFileUrl(regUrl, regFile),
+    cacheable: (regUrl: string) =>
+      !PackagistDatasource.isPrivatePackage(regUrl),
+    ttlMinutes: 1440,
+  })
+  async getPackagistFile(
+    regUrl: string,
+    regFile: RegistryFile
+  ): Promise<PackagistFile> {
+    const url = PackagistDatasource.getPackagistFileUrl(regUrl, regFile);
     const opts = PackagistDatasource.getHostOpts(regUrl);
-    if (opts.password || opts.headers?.authorization) {
-      return (
-        await this.http.getJson<PackagistFile>(regUrl + '/' + fileName, opts)
-      ).body;
-    }
-    const cacheNamespace = 'datasource-packagist-files';
-    const cacheKey = regUrl + key;
-    // Check the persistent cache for public registries
-    const cachedResult = await packageCache.get(cacheNamespace, cacheKey);
-    // istanbul ignore if
-    if (cachedResult && cachedResult.sha256 === sha256) {
-      return cachedResult.res as Promise<PackagistFile>;
-    }
-    const res = (
-      await this.http.getJson<PackagistFile>(regUrl + '/' + fileName, opts)
-    ).body;
-    const cacheMinutes = 1440; // 1 day
-    await packageCache.set(
-      cacheNamespace,
-      cacheKey,
-      { res, sha256 },
-      cacheMinutes
+    const { body: packagistFile } = await this.http.getJson<PackagistFile>(
+      url,
+      opts
     );
-    return res;
+    return packagistFile;
   }
 
   private static extractDepReleases(versions: RegistryFile): ReleaseResult {
-- 
GitLab