Skip to content

Commit

Permalink
fix: fix trace context pattern, remove trace id and respect logging s…
Browse files Browse the repository at this point in the history
…pan id field. (#667)
  • Loading branch information
liuyunnnn authored Dec 26, 2024
1 parent a40b32a commit 0fb00a5
Show file tree
Hide file tree
Showing 9 changed files with 36 additions and 60 deletions.
27 changes: 0 additions & 27 deletions docs/generated/api.json
Original file line number Diff line number Diff line change
Expand Up @@ -1952,33 +1952,6 @@
"startIndex": 1,
"endIndex": 2
}
},
{
"kind": "PropertySignature",
"canonicalReference": "@google-cloud/functions-framework!Request_2#traceId:member",
"docComment": "/**\n * Cloud Trace trace ID.\n */\n",
"excerptTokens": [
{
"kind": "Content",
"text": "traceId?: "
},
{
"kind": "Content",
"text": "string"
},
{
"kind": "Content",
"text": ";"
}
],
"isReadonly": false,
"isOptional": true,
"releaseTag": "Public",
"name": "traceId",
"propertyTypeTokenRange": {
"startIndex": 1,
"endIndex": 2
}
}
],
"extendsTokenRanges": [
Expand Down
1 change: 0 additions & 1 deletion docs/generated/api.md.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,6 @@ interface Request_2 extends Request_3 {
executionId?: string;
rawBody?: Buffer;
spanId?: string;
traceId?: string;
}
export { Request_2 as Request }

Expand Down
2 changes: 0 additions & 2 deletions src/async_local_storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import type {AsyncLocalStorage} from 'node:async_hooks';

export interface ExecutionContext {
executionId?: string;
traceId?: string;
spanId?: string;
}

Expand All @@ -32,7 +31,6 @@ export async function asyncLocalStorageMiddleware(
asyncLocalStorage.run(
{
executionId: req.executionId,
traceId: req.traceId,
spanId: req.spanId,
},
() => {
Expand Down
6 changes: 2 additions & 4 deletions src/execution_context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const FUNCTION_EXECUTION_ID_HEADER_KEY = 'function-execution-id';
const TRACE_CONTEXT_HEADER_KEY = 'X-Cloud-Trace-Context';

const TRACE_CONTEXT_PATTERN =
/^(?<traceId>\w+)\/(?<spanId>\d+);o=(?<options>.+)$/;
/^(?<traceId>\w+)\/(?<spanId>\d+)(?:;o=(?<options>.+))?$/;

function generateExecutionId() {
const timestampPart = Date.now().toString(36).slice(-6);
Expand All @@ -28,9 +28,7 @@ export const executionContextMiddleware = (
if (cloudTraceContext) {
const match = cloudTraceContext.match(TRACE_CONTEXT_PATTERN);
if (match?.groups) {
const {traceId, spanId} = match.groups;
req.traceId = traceId;
req.spanId = spanId;
req.spanId = match.groups.spanId;
}
}
next();
Expand Down
4 changes: 0 additions & 4 deletions src/functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,6 @@ export interface Request extends ExpressRequest {
* Request-specified execution ID.
*/
executionId?: string;
/**
* Cloud Trace trace ID.
*/
traceId?: string;
/**
* Cloud Trace span ID.
*/
Expand Down
12 changes: 4 additions & 8 deletions src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import {getCurrentContext, ExecutionContext} from './async_local_storage';
import {Buffer} from 'buffer';

export const EXECUTION_CONTEXT_LABELS_KEY = 'logging.googleapis.com/labels';
export const EXECUTION_CONTEXT_TRACE_KEY = 'logging.googleapis.com/trace';
export const EXECUTION_CONTEXT_SPAN_ID_KEY = 'logging.googleapis.com/spanId';
const SEVERITY = 'severity';

Expand Down Expand Up @@ -132,7 +131,6 @@ export function getModifiedData(
let dataWithContext: {
message: string | Uint8Array;
'logging.googleapis.com/labels': {execution_id: string | undefined};
'logging.googleapis.com/trace': string | undefined;
'logging.googleapis.com/spanId': string | undefined;
severity?: string | undefined;
};
Expand All @@ -155,7 +153,6 @@ function getTextWithContext(
return {
message: data,
[EXECUTION_CONTEXT_LABELS_KEY]: {execution_id: context.executionId},
[EXECUTION_CONTEXT_TRACE_KEY]: context.traceId,
[EXECUTION_CONTEXT_SPAN_ID_KEY]: context.spanId,
};
}
Expand All @@ -167,11 +164,10 @@ function getJSONWithContext(json: any, context: ExecutionContext) {
} else {
json[EXECUTION_CONTEXT_LABELS_KEY] = {execution_id: context.executionId};
}
return {
...json,
[EXECUTION_CONTEXT_TRACE_KEY]: context.traceId,
[EXECUTION_CONTEXT_SPAN_ID_KEY]: context.spanId,
};
if (!(EXECUTION_CONTEXT_SPAN_ID_KEY in json)) {
json[EXECUTION_CONTEXT_SPAN_ID_KEY] = context.spanId;
}
return json;
}

function processData(data: Uint8Array | string, encoding?: BufferEncoding) {
Expand Down
2 changes: 0 additions & 2 deletions test/async_local_storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ describe('asyncLocalStorageMiddleware', () => {
const req = {
body: 'test body',
executionId: 'testExecutionId',
traceId: 'testtrace',
spanId: 'testSpanId',
};
let executionContext;
Expand All @@ -25,7 +24,6 @@ describe('asyncLocalStorageMiddleware', () => {
assert(executionContext);
assert.strictEqual(executionContext.executionId, req.executionId);
assert.strictEqual(executionContext.spanId, req.spanId);
assert.strictEqual(executionContext.traceId, req.traceId);
};

await asyncLocalStorageMiddleware(
Expand Down
20 changes: 11 additions & 9 deletions test/execution_context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,29 +19,32 @@ describe('executionContextMiddleware', () => {
const testSpanId = '123';
const testTrace = 'testtrace';
const validExecutionId = 'xn1h9xdgv6zw';
const headers = {
'X-Cloud-Trace-Context': `${testTrace}/${testSpanId};o=1`,
'function-execution-id': validExecutionId,
};

it('uses execution ID in header', () => {
const req = createRequest({}, headers);
const req = createRequest(
{},
{
'X-Cloud-Trace-Context': `${testTrace}/${testSpanId};o=1`,
'function-execution-id': validExecutionId,
}
);

executionContextMiddleware(req as Request, {} as Response, next);

assert.strictEqual(req.executionId, validExecutionId);
assert.strictEqual(req.spanId, testSpanId);
assert.strictEqual(req.traceId, testTrace);
});

it('generates execution ID if not in header', () => {
const req = createRequest({}, headers);
const req = createRequest(
{},
{'X-Cloud-Trace-Context': `${testTrace}/${testSpanId}`}
);

executionContextMiddleware(req as Request, {} as Response, next);

assert(req.executionId);
assert.strictEqual(req.spanId, testSpanId);
assert.strictEqual(req.traceId, testTrace);
});

it('req trace undefined if not in header', () => {
Expand All @@ -51,6 +54,5 @@ describe('executionContextMiddleware', () => {

assert(req.executionId);
assert.strictEqual(req.spanId, undefined);
assert.strictEqual(req.traceId, undefined);
});
});
22 changes: 19 additions & 3 deletions test/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,12 @@ describe('getModifiedData', () => {
const sampleUint8Arr = new Uint8Array(Buffer.from(sampleText));
const expectedExecutionContext = {
executionId: 'testExecutionId',
traceId: 'testTraceId',
spanId: 'testSpanId',
};
const expectedMetadata = {
'logging.googleapis.com/labels': {
execution_id: 'testExecutionId',
},
'logging.googleapis.com/trace': 'testTraceId',
'logging.googleapis.com/spanId': 'testSpanId',
};
const expectedTextOutput =
Expand Down Expand Up @@ -102,13 +100,31 @@ describe('getModifiedData', () => {
user_label_1: 'value_1',
execution_id: 'testExecutionId',
},
'logging.googleapis.com/trace': 'testTraceId',
'logging.googleapis.com/spanId': 'testSpanId',
}) + '\n';
const modifiedData = getModifiedData(data);
assert.equal(modifiedData, expectedOutput);
});

it('json with user span id', () => {
const data = JSON.stringify({
text: 'default text.',
component: 'arbitrary-property',
'logging.googleapis.com/spanId': 'mySpanId',
});
const expectedOutput =
JSON.stringify({
text: 'default text.',
component: 'arbitrary-property',
'logging.googleapis.com/spanId': 'mySpanId',
'logging.googleapis.com/labels': {
execution_id: 'testExecutionId',
},
}) + '\n';
const modifiedData = getModifiedData(data);
assert.equal(modifiedData, expectedOutput);
});

it('uint8array', () => {
const modifiedData = getModifiedData(sampleUint8Arr);
assert.equal(modifiedData, expectedTextOutput);
Expand Down

0 comments on commit 0fb00a5

Please sign in to comment.