fix: refactor scopes for service token

This commit is contained in:
Christel Westerberg
2024-10-07 16:48:23 +02:00
parent 2ea0adbf98
commit 71b03143ce
8 changed files with 128 additions and 110 deletions
+39 -11
View File
@@ -1,13 +1,28 @@
import { metrics } from "@opentelemetry/api"
import { revalidateTag, unstable_cache } from "next/cache"
import { env } from "@/env/server"
import { generateServiceTokenTag } from "@/utils/generateTag"
import { ServiceTokenScope } from "@/types/enums/serviceToken"
import { ServiceTokenScopeEnum } from "@/types/enums/serviceToken"
import { ServiceTokenResponse } from "@/types/tokens"
async function getServiceToken(scopes: ServiceTokenScope[]) {
// OpenTelemetry metrics: Service token
const meter = metrics.getMeter("trpc.context.serviceToken")
const getServiceTokenCounter = meter.createCounter(
"trpc.context.serviceToken.get-new-token"
)
const getTempServiceTokenCounter = meter.createCounter(
"trpc.context.serviceToken.get-temporary"
)
const getServiceTokenFailCounter = meter.createCounter(
"trpc.context.serviceToken.get-fail"
)
async function getServiceToken() {
getServiceTokenCounter.add(1)
const scopes = Object.keys(ServiceTokenScopeEnum)
const response = await fetch(`${env.CURITY_ISSUER_USER}/oauth/v2/token`, {
method: "POST",
headers: {
@@ -23,32 +38,45 @@ async function getServiceToken(scopes: ServiceTokenScope[]) {
})
if (!response.ok) {
getServiceTokenFailCounter.add(1, {
error_type: "http_error",
error: JSON.stringify({
status: response.status,
statusText: response.statusText,
}),
})
throw new Error("Failed to obtain service token")
}
return response.json()
}
export async function fetchServiceToken(
scopes: ServiceTokenScope[]
): Promise<ServiceTokenResponse> {
export async function fetchServiceToken(): Promise<ServiceTokenResponse> {
try {
const tag = generateServiceTokenTag(scopes)
const tag = generateServiceTokenTag()
const getCachedJwt = unstable_cache(
async (scopes) => {
const jwt = await getServiceToken(scopes)
async () => {
const jwt = await getServiceToken()
const expiresAt = Date.now() + jwt.expires_in * 1000
return { expiresAt, jwt }
},
scopes,
[],
{ tags: [tag] }
)
const cachedJwt = await getCachedJwt(scopes)
const cachedJwt = await getCachedJwt()
if (cachedJwt.expiresAt < Date.now()) {
console.log(
"trpc.context.serviceToken: Service token expired, revalidating tag"
)
revalidateTag(tag)
const newToken = await getServiceToken(scopes)
console.log(
"trpc.context.serviceToken: Fetching new temporary service token."
)
getTempServiceTokenCounter.add(1)
const newToken = await getServiceToken()
return newToken
}