Skip to content

Commit

Permalink
automatically add timestamps to spans when starting/ending and keep t…
Browse files Browse the repository at this point in the history
…rack of parent spans.
  • Loading branch information
psykhi committed Apr 8, 2024
1 parent c8eda3f commit 9299168
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 9 deletions.
6 changes: 2 additions & 4 deletions examples/tracing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,19 +42,17 @@ const happify = fn({
const span: Span = {
uuid: uuid.v4(),
name: "Translate",
start_time: new Date(),
input: JSON.stringify(input),
}
await client.traces.startSpan(span);
await client.spans.startSpan(span);

// Call translate and happify like any other function
const result = await translate(input);
console.log(result);
const happified = await happify(result);

span.output = JSON.stringify(happified);
span.end_time = new Date();
await client.traces.endSpan(span);
await client.spans.endSpan(span);

console.log(happified);
})();
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "opperai",
"version": "0.4.1",
"version": "0.4.2",
"description": "The official Node library for the OpperAi API",
"main": "dist/index.js",
"types": "dist/index.js",
Expand Down
16 changes: 14 additions & 2 deletions src/spans.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,20 @@ export function getCurrentSpanId(): string | undefined {
class Spans extends APIResource {

/**
* This method is used to start a new span.
* It sends a POST request to the spans endpoint with the provided span data.
* Helper method to start a new span and set the current span context.
* @param span - The span data to be created.
* @returns A promise that resolves to the UUID of the created span.
* @throws {APIError} If the response status is not 200.
*/
public async startSpan(span: Span) {
const spanId = span.uuid;
if (!span.start_time) {
span.start_time = new Date();
}
const currentSpanId = getCurrentSpanId();
if (currentSpanId && !span.parent_uuid) {
span.parent_uuid = currentSpanId;
}
spanContextStorage.enterWith({ spanId });
return this.create(span);
}
Expand All @@ -39,6 +45,12 @@ class Spans extends APIResource {
* @throws {APIError} If the response status is not 200.
*/
public async endSpan(span: Span) {
if (!span.end_time) {
span.end_time = new Date();
}
if (span.parent_uuid) {
spanContextStorage.run({ spanId: span.parent_uuid }, () => { });
}
spanContextStorage.run({ spanId: '' }, () => { });
return this.update(span.uuid, span);
}
Expand Down

0 comments on commit 9299168

Please sign in to comment.