-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
feat(core): support config.httpclient.interceptors for fetch/safeFetch tracer injection
#5771
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
c5f8770
feat: support fetch clientOptions interceptors
Dipper30 602ef50
chore: interceptor type
Dipper30 ce24bbb
chore: fix tsd
Dipper30 53267db
fix: test case
Dipper30 eddb192
fix: test case
Dipper30 693cd37
fix: test case fetch ctx
Dipper30 c2b1098
Revert "fix: test case"
Dipper30 d7bf2a2
Revert "fix: test case fetch ctx"
Dipper30 dad5dbe
fix: fetch initialization
Dipper30 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| const assert = require('assert'); | ||
|
|
||
| const TRACE_ID = Symbol('TRACE_ID'); | ||
| const RPC_ID = Symbol('RPC_ID'); | ||
|
|
||
| // Simple Tracer implementation | ||
| class Tracer { | ||
| constructor(traceId, rpcId = '0') { | ||
| this.traceId = traceId; | ||
| this._rpcId = rpcId; | ||
| this._rpcIdSeq = 0; | ||
| } | ||
|
|
||
| get rpcId() { | ||
| return this._rpcId; | ||
| } | ||
|
|
||
| get rpcIdPlus() { | ||
| return `${this._rpcId}.${++this._rpcIdSeq}`; | ||
| } | ||
| } | ||
|
|
||
| module.exports = class TracerApp { | ||
| constructor(app) { | ||
| this.app = app; | ||
| assert(app.config); | ||
| // Expose Tracer class for testing | ||
| app.Tracer = Tracer; | ||
| } | ||
|
|
||
| configWillLoad() { | ||
| // Setup tracer interceptor using interceptors config | ||
| this.app.config.httpclient = this.app.config.httpclient || {}; | ||
| if (!this.app.FetchFactory) { | ||
| return; | ||
| } | ||
| const tracerConfig = this.app.config.tracer; | ||
| const HTTP_HEADER_TRACE_ID_KEY = tracerConfig.HTTP_HEADER_TRACE_ID_KEY.toLowerCase(); | ||
| const HTTP_HEADER_RPC_ID_KEY = tracerConfig.HTTP_HEADER_RPC_ID_KEY.toLowerCase(); | ||
|
|
||
| this.app.config.httpclient.interceptors = [ | ||
| dispatch => { | ||
| const app = this.app; | ||
| return async function tracerInterceptor(opts, handler) { | ||
| const tracer = app.currentContext?.tracer; | ||
| let traceId; | ||
| let rpcId; | ||
|
|
||
| try { | ||
| if (tracer) { | ||
| traceId = opts.headers[HTTP_HEADER_TRACE_ID_KEY] = tracer.traceId; | ||
| rpcId = opts.headers[HTTP_HEADER_RPC_ID_KEY] = tracer.rpcIdPlus; | ||
| } | ||
| } catch (e) { | ||
| e.message = '[egg-tracelog] set tracer header failed: ' + e.message; | ||
| app.logger.warn(e); | ||
| } | ||
|
|
||
| try { | ||
| return await dispatch(opts, handler); | ||
| } finally { | ||
| const opaque = handler.opaque; | ||
| if (opaque) { | ||
| opaque[TRACE_ID] = traceId; | ||
| opaque[RPC_ID] = rpcId; | ||
| } | ||
| } | ||
| }; | ||
| }, | ||
| ]; | ||
| } | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| module.exports = app => { | ||
| app.get('/test', async ctx => { | ||
| // Mock a tracer on the context using the Tracer class | ||
| ctx.tracer = new app.Tracer('test-trace-id-123', '0'); | ||
|
|
||
| // Store the current context so fetch can access it | ||
| app.currentContext = ctx; | ||
|
|
||
| // Make a fetch request | ||
| const response = await app.fetch(ctx.query.url); | ||
|
|
||
| const traceId = response.headers.get('x-trace-id'); | ||
| if (traceId) ctx.set('x-trace-id', traceId); | ||
| const rpcId = response.headers.get('x-rpc-id'); | ||
| if (rpcId) ctx.set('x-rpc-id', rpcId); | ||
|
|
||
| ctx.body = { | ||
| status: response.status, | ||
| ok: response.ok, | ||
| }; | ||
| }); | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| exports.keys = 'test key'; | ||
|
|
||
| exports.tracer = { | ||
| HTTP_HEADER_TRACE_ID_KEY: 'x-trace-id', | ||
| HTTP_HEADER_RPC_ID_KEY: 'x-rpc-id', | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| { | ||
| "name": "fetch-tracer" | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| const assert = require('node:assert'); | ||
| const http = require('http'); | ||
| const utils = require('../../utils'); | ||
|
|
||
| describe('test/lib/core/fetch_tracer.test.js', () => { | ||
| const version = utils.getNodeVersion(); | ||
| if (version < 20) return; | ||
|
|
||
| let app; | ||
| let mockServer; | ||
|
|
||
| before(async () => { | ||
| // Create a mock server to capture headers | ||
| mockServer = http.createServer((req, res) => { | ||
| const headers = { | ||
| 'Content-Type': 'application/json', | ||
| }; | ||
| if (req.headers['x-trace-id']) { | ||
| headers['x-trace-id'] = req.headers['x-trace-id']; | ||
| } | ||
| if (req.headers['x-rpc-id']) { | ||
| headers['x-rpc-id'] = req.headers['x-rpc-id']; | ||
| } | ||
|
|
||
| res.writeHead(200, headers); | ||
| res.end(JSON.stringify({ ok: true })); | ||
| }); | ||
|
|
||
| await new Promise(resolve => { | ||
| mockServer.listen(0, '127.0.0.1', resolve); | ||
| }); | ||
|
|
||
| app = utils.app('apps/fetch-tracer'); | ||
| await app.ready(); | ||
| }); | ||
|
|
||
| after(() => { | ||
| if (mockServer?.listening) { | ||
| mockServer.close(); | ||
| } | ||
| }); | ||
|
|
||
| it('should add tracer headers when fetch is called', async () => { | ||
| const port = mockServer.address().port; | ||
| const targetUrl = `http://127.0.0.1:${port}/mock`; | ||
|
|
||
| const response = await app.httpRequest() | ||
| .get('/test') | ||
| .query({ url: targetUrl }) | ||
| .expect(200); | ||
|
|
||
| assert.strictEqual(response.body.status, 200); | ||
| assert.strictEqual(response.body.ok, true); | ||
|
|
||
| // Verify tracer headers were added with incremented rpcId | ||
| assert.strictEqual(response.headers['x-trace-id'], 'test-trace-id-123'); | ||
| assert.strictEqual(response.headers['x-rpc-id'], '0.1'); // rpcIdPlus increments from 0 | ||
| }); | ||
|
|
||
| it('should work when tracer is not set', async () => { | ||
| // Clear currentContext | ||
| app.currentContext = null; | ||
|
|
||
| const port = mockServer.address().port; | ||
| const targetUrl = `http://127.0.0.1:${port}/mock`; | ||
|
|
||
| const response = await app.fetch(targetUrl); | ||
|
|
||
| assert.strictEqual(response.status, 200); | ||
|
|
||
| // Verify no tracer headers when tracer is not set | ||
| assert.strictEqual(response.headers.get('x-trace-id'), null); | ||
| assert.strictEqual(response.headers.get('x-rpc-id'), null); | ||
| }); | ||
|
|
||
|
|
||
| it('should handle fetch before configDidLoad completes', async () => { | ||
| // Test that lazy initialization preserves interceptors set in configDidLoad | ||
| const port = mockServer.address().port; | ||
| const targetUrl = `http://127.0.0.1:${port}/mock`; | ||
|
|
||
| const ctx = app.mockContext(); | ||
| ctx.tracer = new app.Tracer('early-trace-id', '0.1'); | ||
| app.currentContext = ctx; | ||
|
|
||
| const response = await app.fetch(targetUrl); | ||
| assert.strictEqual(response.status, 200); | ||
| assert.strictEqual(response.headers.get('x-trace-id'), 'early-trace-id'); | ||
| assert.strictEqual(response.headers.get('x-rpc-id'), '0.1.1'); // rpcIdPlus increments from 0.1 | ||
| }); | ||
|
|
||
| it('should increment rpcId on multiple fetch calls', async () => { | ||
| // Test that rpcId increments properly on each fetch | ||
| const port = mockServer.address().port; | ||
| const targetUrl = `http://127.0.0.1:${port}/mock`; | ||
|
|
||
| const ctx = app.mockContext(); | ||
| ctx.tracer = new app.Tracer('multi-trace-id', '0'); | ||
| app.currentContext = ctx; | ||
|
|
||
| // First fetch | ||
| let response = await app.fetch(targetUrl); | ||
| assert.strictEqual(response.headers.get('x-trace-id'), 'multi-trace-id'); | ||
| assert.strictEqual(response.headers.get('x-rpc-id'), '0.1'); | ||
|
|
||
| // Second fetch | ||
| response = await app.fetch(targetUrl); | ||
| assert.strictEqual(response.headers.get('x-trace-id'), 'multi-trace-id'); | ||
| assert.strictEqual(response.headers.get('x-rpc-id'), '0.2'); | ||
|
|
||
| // Third fetch | ||
| response = await app.fetch(targetUrl); | ||
| assert.strictEqual(response.headers.get('x-trace-id'), 'multi-trace-id'); | ||
| assert.strictEqual(response.headers.get('x-rpc-id'), '0.3'); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This block of code for applying interceptors is a duplicate of the logic in the
fetchfunction (lines 28-32). To improve maintainability and avoid code duplication, consider extracting this logic into a shared helper function.For example, you could define a function like this:
And then call it from both
fetchandsafeFetchinitialization blocks:This will make the code cleaner and easier to manage in the future.