Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/fix/track-background-revalidation'
Browse files Browse the repository at this point in the history
  • Loading branch information
pieh committed Jun 20, 2024
2 parents 4b6de32 + e88dd8c commit 476b973
Show file tree
Hide file tree
Showing 5 changed files with 69 additions and 13 deletions.
28 changes: 21 additions & 7 deletions src/run/handlers/cache.cts
Original file line number Diff line number Diff line change
Expand Up @@ -326,19 +326,33 @@ export class NetlifyCacheHandler implements CacheHandler {
if (requestContext?.didPagesRouterOnDemandRevalidate) {
const tag = `_N_T_${key === '/index' ? '/' : key}`
getLogger().debug(`Purging CDN cache for: [${tag}]`)
purgeCache({ tags: [tag] }).catch((error) => {
// TODO: add reporting here
getLogger()
.withError(error)
.error(`[NetlifyCacheHandler]: Purging the cache for tag ${tag} failed`)
})
requestContext.trackBackgroundWork(
purgeCache({ tags: [tag] }).catch((error) => {
// TODO: add reporting here
getLogger()
.withError(error)
.error(`[NetlifyCacheHandler]: Purging the cache for tag ${tag} failed`)
}),
)
}
}
})
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
async revalidateTag(tagOrTags: string | string[], ...args: any) {
const revalidateTagPromise = this.doRevalidateTag(tagOrTags, ...args)

const requestContext = getRequestContext()
if (requestContext) {
requestContext.trackBackgroundWork(revalidateTagPromise)
}

return revalidateTagPromise
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
private async doRevalidateTag(tagOrTags: string | string[], ...args: any) {
getLogger().withFields({ tagOrTags, args }).debug('NetlifyCacheHandler.revalidateTag')

const tags = Array.isArray(tagOrTags) ? tagOrTags : [tagOrTags]
Expand All @@ -357,7 +371,7 @@ export class NetlifyCacheHandler implements CacheHandler {
}),
)

purgeCache({ tags }).catch((error) => {
await purgeCache({ tags }).catch((error) => {
// TODO: add reporting here
getLogger()
.withError(error)
Expand Down
9 changes: 8 additions & 1 deletion src/run/revalidate.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { ServerResponse } from 'node:http'
import { isPromise } from 'node:util/types'

import type { RequestContext } from './handlers/request-context.cjs'

Expand All @@ -12,7 +13,13 @@ export const nextResponseProxy = (res: ServerResponse, requestContext: RequestCo
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return async function newRevalidate(...args: any[]) {
requestContext.didPagesRouterOnDemandRevalidate = true
return originalValue?.apply(target, args)

const result = originalValue?.apply(target, args)
if (result && isPromise(result)) {
requestContext.trackBackgroundWork(result)
}

return result
}
}
return originalValue
Expand Down
2 changes: 1 addition & 1 deletion tests/fixtures/page-router/pages/api/revalidate.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export default async function handler(req, res) {
try {
const pathToPurge = req.query.path ?? '/static/revalidate-manual'
await res.revalidate(pathToPurge)
res.revalidate(pathToPurge)
return res.json({ code: 200, message: 'success' })
} catch (err) {
return res.status(500).send({ code: 500, message: err.message })
Expand Down
22 changes: 20 additions & 2 deletions tests/utils/fixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -364,14 +364,24 @@ export async function invokeFunction(
NETLIFY_BLOBS_CONTEXT: createBlobContext(ctx),
...(env || {}),
}

const envVarsToRestore = {}

// We are not using lambda-local's environment variable setting because it cleans up
// environment vars to early (before stream is closed)
Object.keys(environment).forEach(function (key) {
if (typeof process.env[key] !== 'undefined') {
envVarsToRestore[key] = process.env[key]
}
process.env[key] = environment[key]
})

const response = (await execute({
event: {
headers: headers || {},
httpMethod: httpMethod || 'GET',
rawUrl: new URL(url || '/', 'https://example.netlify').href,
},
environment,
envdestroy: true,
lambdaFunc: { handler },
timeoutMs: 4_000,
})) as LambdaResponse
Expand All @@ -386,6 +396,14 @@ export async function invokeFunction(

const bodyBuffer = await streamToBuffer(response.body)

Object.keys(environment).forEach(function (key) {
if (typeof envVarsToRestore[key] !== 'undefined') {
process.env[key] = envVarsToRestore[key]
} else {
delete process.env[key]
}
})

return {
statusCode: response.statusCode,
bodyBuffer,
Expand Down
21 changes: 19 additions & 2 deletions tests/utils/sandbox-child.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -48,14 +48,23 @@ process.on('message', async (msg) => {
...(env || {}),
}

const envVarsToRestore = {}

// We are not using lambda-local's environment variable setting because it cleans up
// environment vars to early (before stream is closed)
Object.keys(environment).forEach(function (key) {
if (typeof process.env[key] !== 'undefined') {
envVarsToRestore[key] = process.env[key]
}
process.env[key] = environment[key]
})

const response = await execute({
event: {
headers: headers || {},
httpMethod: httpMethod || 'GET',
rawUrl: new URL(url || '/', 'https://example.netlify').href,
},
environment,
envdestroy: true,
lambdaFunc: { handler },
timeoutMs: 4_000,
})
Expand All @@ -70,6 +79,14 @@ process.on('message', async (msg) => {

const bodyBuffer = await streamToBuffer(response.body)

Object.keys(environment).forEach(function (key) {
if (typeof envVarsToRestore[key] !== 'undefined') {
process.env[key] = envVarsToRestore[key]
} else {
delete process.env[key]
}
})

const result = {
statusCode: response.statusCode,
bodyBuffer,
Expand Down

0 comments on commit 476b973

Please sign in to comment.