Skip to content

Commit

Permalink
feat: Disable requests measuring time by default due to #42
Browse files Browse the repository at this point in the history
  • Loading branch information
artmizu committed Jul 23, 2024
1 parent 2069dbf commit 6fefa56
Show file tree
Hide file tree
Showing 9 changed files with 7,747 additions and 37 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ Allows you to better understand what's going on with your application and how to
## Limitations
Due to this [issue in ofetch package](https://github.com/unjs/ofetch/issues/295) @artmizu/nuxt-prometheus cannot detect network requests which take place through useFetch or $fetch, because they both use ofetch inside. So on the /metrics page, you don't see any request time related to ofetch. Future investigation will take place [here](https://github.com/artmizu/nuxt-prometheus/issues/42).

For now request measurment time is disabled by default.

## Features
* Default NodeJS metrics exported through the prometheus middleware
* Custom metrics about pages render time and external request consumption time
Expand Down Expand Up @@ -71,3 +73,8 @@ You can pass it through module options and the nuxt config property `prometheus`
- Type: `string`
- Default: no prefix
- Description: An optional prefix for metric names

### enableRequestTimeMeasure
- Type: `boolean`
- Default: `false`
- Description: Temporarily don't recommend to turn it on due to https://github.com/artmizu/nuxt-prometheus/issues/42
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
"dev": "nuxi dev playground",
"dev:build": "nuxi build playground",
"dev:prepare": "nuxt-module-build prepare && nuxt-module-build build && nuxi prepare playground",
"test": "vitest",
"test": "yarn playwright-core install && vitest",
"test:type": "vitest --typecheck.only --typecheck.ignoreSourceErrors",
"lint": "eslint .",
"typecheck": "tsc --noEmit",
Expand Down
2 changes: 2 additions & 0 deletions playground/nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,6 @@ export default defineNuxtConfig({
prometheus: {
prefix: 'playground_',
},

compatibilityDate: '2024-07-23',

Check failure on line 10 in playground/nuxt.config.ts

View workflow job for this annotation

GitHub Actions / typecheck

Object literal may only specify known properties, and 'compatibilityDate' does not exist in type 'InputConfig<NuxtConfig, ConfigLayerMeta>'.
})
1 change: 1 addition & 0 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const module: NuxtModule<Partial<AnalyticsModuleParams>> = defineNuxtModule<Part
healthCheck: true,
prometheusPath: '/metrics',
healthCheckPath: '/health',
enableRequestTimeMeasure: false,
},
async setup(options, nuxt) {
const moduleOptions = defu(
Expand Down
73 changes: 39 additions & 34 deletions src/runtime/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,49 @@ export default defineNuxtPlugin((ctx) => {

const path = router.currentRoute.value?.matched?.[0]?.path || 'empty'
const name = router.currentRoute.value?.name || 'empty'
const interceptor = new BatchInterceptor({
name: 'nuxt-prometheus',
interceptors: [
new XMLHttpRequestInterceptor(),
new ClientRequestInterceptor(),
new FetchInterceptor(),
],
})
interceptor.apply()

const state: AnalyticsModuleState = {
start: Date.now(),
path: `${String(name)}: ${path}`,
requests: {},
interceptor,
interceptor: null,
}

if (params.enableRequestTimeMeasure) {
state.interceptor = new BatchInterceptor({
name: 'nuxt-prometheus',
interceptors: [
new XMLHttpRequestInterceptor(),
new ClientRequestInterceptor(),
new FetchInterceptor(),
],
})

state.interceptor.apply()

state.interceptor.on('request', (req) => {
const url = new URL(req.request.url)

/**
* Exclude Nuxt requests to parts of the application, it's not about business-logic
*/
const isNuxtRequest = /^\/__/.test(url.pathname)
if (isNuxtRequest)
return

state.requests[req.request.url] = {
start: Date.now(),
end: Date.now(),
}

if (params.verbose)
consola.info(`[nuxt-prometheus] request: ${req.request.url}, ${new Date().toISOString()}`)
})

state.interceptor.on('response', ({ response }) => {
if (state.requests[response.url])
state.requests[response.url].end = Date.now()
})
}

ctx.hook('app:rendered', () => {
Expand All @@ -45,28 +74,4 @@ export default defineNuxtPlugin((ctx) => {
consola.info('[nuxt-prometheus] total time:', time.total)
}
})

interceptor.on('request', (req) => {
const url = new URL(req.request.url)

/**
* Exclude Nuxt requests to parts of the application, it's not about business-logic
*/
const isNuxtRequest = /^\/__/.test(url.pathname)
if (isNuxtRequest)
return

state.requests[req.request.url] = {
start: Date.now(),
end: Date.now(),
}

if (params.verbose)
consola.info(`[nuxt-prometheus] request: ${req.request.url}, ${new Date().toISOString()}`)
})

interceptor.on('response', ({ response }) => {
if (state.requests[response.url])
state.requests[response.url].end = Date.now()
})
})
7 changes: 6 additions & 1 deletion src/runtime/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export interface AnalyticsModuleState {
end: number
}
}
interceptor?: BatchInterceptor<(ClientRequestInterceptor | XMLHttpRequestInterceptor | FetchInterceptor)[], HttpRequestEventMap>
interceptor: BatchInterceptor<(ClientRequestInterceptor | XMLHttpRequestInterceptor | FetchInterceptor)[], HttpRequestEventMap> | null
}

export interface AnalyticsModuleParams {
Expand Down Expand Up @@ -43,4 +43,9 @@ export interface AnalyticsModuleParams {
* @default no prefix
*/
prefix?: string
/**
* Temporarily don't recommend to turn it on,
* due to https://github.com/artmizu/nuxt-prometheus/issues/42
*/
enableRequestTimeMeasure?: boolean
}
7 changes: 6 additions & 1 deletion test/nuxt.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ import { createPage, setup, useTestContext } from '@nuxt/test-utils/e2e'
describe('module tests', async () => {
await setup({
rootDir: fileURLToPath(new URL('../playground', import.meta.url)),
nuxtConfig: {
prometheus: {
enableRequestTimeMeasure: true,
},
},
})

it('health page check', async () => {
Expand Down Expand Up @@ -45,7 +50,7 @@ describe('module tests', async () => {
expect(content).toMatch(/page_total_time\{path=\"b: \/b\"}\ \d+/gm)
})

// TODO
// TODO https://github.com/artmizu/nuxt-prometheus/issues/42
// it('check the useFetch measuring time on /b route', async () => {
// const ctx = useTestContext()
// const page = await createPage('/')
Expand Down
1 change: 1 addition & 0 deletions test/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ it('calculateTime check', () => {
end: 410,
},
},
interceptor: null,
})

expect(time).toEqual({ request: 310, render: 190, total: 500 })
Expand Down
Loading

0 comments on commit 6fefa56

Please sign in to comment.