From d234bb1a86a94f03f7a4cb3fd6abe6e1b0c3ba55 Mon Sep 17 00:00:00 2001 From: yantian Date: Mon, 9 Dec 2024 11:29:33 +0800 Subject: [PATCH] get token expires at by token file modify time --- .../BearTokenFileCredentialsProvider.java | 25 +++++++++++++------ 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/paimon-core/src/main/java/org/apache/paimon/rest/auth/BearTokenFileCredentialsProvider.java b/paimon-core/src/main/java/org/apache/paimon/rest/auth/BearTokenFileCredentialsProvider.java index 4e8246498fb2..6fb4fc6e53c9 100644 --- a/paimon-core/src/main/java/org/apache/paimon/rest/auth/BearTokenFileCredentialsProvider.java +++ b/paimon-core/src/main/java/org/apache/paimon/rest/auth/BearTokenFileCredentialsProvider.java @@ -18,8 +18,10 @@ package org.apache.paimon.rest.auth; +import org.apache.paimon.utils.Pair; import org.apache.paimon.utils.StringUtils; +import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -39,13 +41,16 @@ public class BearTokenFileCredentialsProvider extends BaseBearTokenCredentialsPr public BearTokenFileCredentialsProvider(String tokenFilePath) { this.tokenFilePath = tokenFilePath; - this.token = getTokenFromFile(); + Pair token2GenerateTime = getTokenAndGenerateTimeFromFile(); + this.token = token2GenerateTime.getLeft(); } public BearTokenFileCredentialsProvider(String tokenFilePath, Long expiresInMills) { - this(tokenFilePath); + this.tokenFilePath = tokenFilePath; + Pair token2GenerateTime = getTokenAndGenerateTimeFromFile(); + this.token = token2GenerateTime.getLeft(); + this.expiresAtMillis = token2GenerateTime.getRight() + expiresInMills; this.keepRefreshed = true; - this.expiresAtMillis = -1L; this.expiresInMills = expiresInMills; } @@ -57,8 +62,9 @@ String token() { @Override public boolean refresh() { long start = System.currentTimeMillis(); - this.token = getTokenFromFile(); - this.expiresAtMillis = start + this.expiresInMills; + Pair token2GenerateTime = getTokenAndGenerateTimeFromFile(); + this.token = token2GenerateTime.getLeft(); + this.expiresAtMillis = Math.min(token2GenerateTime.getRight(), start) + this.expiresInMills; if (StringUtils.isNullOrWhitespaceOnly(this.token)) { return false; } @@ -95,10 +101,15 @@ public Optional expiresInMills() { return Optional.ofNullable(this.expiresInMills); } - private String getTokenFromFile() { + private Pair getTokenAndGenerateTimeFromFile() { try { // todo: handle exception - return new String(Files.readAllBytes(Paths.get(tokenFilePath)), StandardCharsets.UTF_8); + File file = new File(tokenFilePath); + long modified = file.lastModified(); + String token = + new String( + Files.readAllBytes(Paths.get(tokenFilePath)), StandardCharsets.UTF_8); + return Pair.of(token, modified); } catch (IOException e) { throw new RuntimeException(e); }