Skip to content
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

improve api telemetry #2769

Merged
merged 2 commits into from
Feb 18, 2025
Merged

improve api telemetry #2769

merged 2 commits into from
Feb 18, 2025

Conversation

imolorhe
Copy link
Collaborator

@imolorhe imolorhe commented Feb 18, 2025

Fixes

Checks

  • Ran yarn test-build
  • Updated relevant documentations
  • Updated matching config options in altair-static

Changes proposed in this pull request:

Summary by Sourcery

This pull request introduces telemetry to track the usage of various API endpoints using New Relic. It adds metrics for email sending, query creation, query listing, query collection creation, team membership changes, team creation, credit balance, and authentication events. The New Relic agent is now initialized and accessed through the getAgent function, allowing for conditional usage based on the NEW_RELIC_APP_NAME environment variable.

Enhancements:

  • Added telemetry to track the usage of various API endpoints using New Relic.
  • Added metrics for email sending, query creation, query listing, query collection creation, team membership changes, team creation, credit balance, and authentication events.

Chores:

  • Introduced a newrelic module to encapsulate New Relic agent functionality.
  • The New Relic agent is now initialized and accessed through the getAgent function, allowing for conditional usage based on the NEW_RELIC_APP_NAME environment variable.

Copy link

sourcery-ai bot commented Feb 18, 2025

Reviewer's Guide by Sourcery

This pull request introduces New Relic telemetry to track the usage and performance of various features, and refactors email sending logic into a private method.

Sequence diagram for creating a query

sequenceDiagram
    participant QueriesService
    participant PrismaService
    participant EventService
    QueriesService->>QueriesService: create(userId, createQueryDto)
    QueriesService->>PrismaService: queryItem.create(data)
    PrismaService-->>QueriesService: res
    QueriesService->>EventService: emit(EVENTS.QUERY_UPDATE, { id: res.id })
    QueriesService->>QueriesService: agent?.incrementMetric('query.create')
    EventService-->>QueriesService: 
    PrismaService-->>QueriesService: res
Loading

Sequence diagram for creating a query collection

sequenceDiagram
    participant QueryCollectionsService
    participant PrismaService
    participant EventService
    QueryCollectionsService->>QueryCollectionsService: create(userId, createQueryCollectionDto)
    QueryCollectionsService->>PrismaService: queryCollection.create(data)
    PrismaService-->>QueryCollectionsService: res
    QueryCollectionsService->>EventService: emit(EVENTS.COLLECTION_UPDATE, { id: res.id })
    QueryCollectionsService->>QueryCollectionsService: agent?.incrementMetric('query_collection.create')
    EventService-->>QueryCollectionsService: 
    PrismaService-->>QueryCollectionsService: res
Loading

Sequence diagram for adding a team membership

sequenceDiagram
    participant TeamMembershipsService
    participant PrismaService
    TeamMembershipsService->>TeamMembershipsService: create(userId, createTeamMembershipDto)
    TeamMembershipsService->>PrismaService: teamMembership.create(data)
    PrismaService-->>TeamMembershipsService: res
    TeamMembershipsService->>TeamMembershipsService: updateSubscriptionQuantity(userId)
    TeamMembershipsService->>TeamMembershipsService: agent?.incrementMetric('team.membership.added')
    PrismaService-->>TeamMembershipsService: res
Loading

Sequence diagram for creating a team

sequenceDiagram
    participant TeamsService
    participant PrismaService
    TeamsService->>TeamsService: create(userId, createTeamDto)
    TeamsService->>PrismaService: team.create(data)
    PrismaService-->>TeamsService: res
    TeamsService->>TeamsService: agent?.incrementMetric('team.created')
    PrismaService-->>TeamsService: res
Loading

Sequence diagram for listing all teams

sequenceDiagram
    participant TeamsService
    participant PrismaService
    TeamsService->>TeamsService: findAll(userId)
    TeamsService->>PrismaService: team.findMany(where)
    PrismaService-->>TeamsService: res
    TeamsService->>TeamsService: agent?.recordMetric('team.list.count', res.length)
    PrismaService-->>TeamsService: res
Loading

Sequence diagram for refilling monthly credits

sequenceDiagram
    participant CreditService
    participant UserService
    participant PrismaService
    CreditService->>CreditService: refillMonthlyCredits()
    CreditService->>UserService: getProUsers()
    UserService-->>CreditService: proUsers
    loop for each proUser
        CreditService->>PrismaService: creditBalance.update(where, data)
        PrismaService-->>CreditService: creditBalanceRecords
    end
    CreditService->>CreditService: agent?.recordMetric('credit.monthly.refill_count', proUsers.length)
    PrismaService-->>CreditService: creditBalanceRecords
Loading

Sequence diagram for getting pro users

sequenceDiagram
    participant UserService
    participant PrismaService
    UserService->>UserService: getProUsers()
    UserService->>PrismaService: user.findMany(where)
    PrismaService-->>UserService: proUsers
    UserService->>UserService: agent?.recordMetric('users.pro.count', proUsers.length)
    PrismaService-->>UserService: proUsers
Loading

Sequence diagram for generating events token

sequenceDiagram
    participant AuthService
    AuthService->>AuthService: getShortLivedEventsToken(userId)
    AuthService->>AuthService: agent?.incrementMetric('auth.events_token.generate')
Loading

File-Level Changes

Change Details Files
Introduces New Relic telemetry to track the usage and performance of various features.
  • Initialized the New Relic agent in several services.
  • Added metrics for email sending success and failure.
  • Added metrics for query creation, listing, and revision operations.
  • Added metrics for query collection creation and listing.
  • Added metrics for team membership changes.
  • Added metrics for team creation and listing.
  • Added metrics for credit balance retrieval and monthly refills.
  • Added metrics for user authentication and event token generation.
  • Added metrics for workspace listing.
  • Added metrics for pro users count.
packages/altair-api/src/email/email.service.ts
packages/altair-api/src/queries/queries.service.ts
packages/altair-api/src/query-collections/query-collections.service.ts
packages/altair-api/src/team-memberships/team-memberships.service.ts
packages/altair-api/src/teams/teams.service.ts
packages/altair-api/src/credit/credit.service.ts
packages/altair-api/src/newrelic/newrelic.interceptor.ts
packages/altair-api/src/workspaces/workspaces.service.ts
packages/altair-api/src/auth/user/user.service.ts
packages/altair-api/src/auth/auth.service.ts
packages/altair-api/src/newrelic/newrelic.ts
Refactors email sending logic into a private method.
  • Created a private sendEmail method to encapsulate the email sending logic.
  • Moved the resend.emails.send call and error handling into the sendEmail method.
  • Replaced direct resend.emails.send calls in sendWelcomeEmail and sendGoodbyeEmail with calls to the new sendEmail method.
packages/altair-api/src/email/email.service.ts

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @imolorhe - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Consider creating a base class or shared utility for accessing the NewRelic agent to avoid duplication.
  • The agent should be initialized once and then injected, rather than calling getAgent() in each service.
Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟡 Complexity: 1 issue found
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@@ -85,6 +87,8 @@ export class QueriesService {

this.eventService.emit(EVENTS.QUERY_UPDATE, { id: res.id });

this.agent?.incrementMetric('query.create');
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (complexity): Consider centralizing the metric reporting logic using a decorator to wrap service methods.

Consider centralizing the metric reporting to reduce the interleaved instrumentation code. For example, you might create a decorator to wrap your service methods. This way, you can remove repetitive metric calls from the business logic while keeping the behavior intact. For instance:

function withMetric(metricName: string, action: "increment" | "record", countFn?: (result: any) => number) {
  return function (_target: any, _propertyKey: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;
    descriptor.value = async function (...args: any[]) {
      const result = await originalMethod.apply(this, args);
      if (action === "increment") {
        this.agent?.incrementMetric(metricName);
      } else if (action === "record") {
        const count = countFn ? countFn(result) : (Array.isArray(result) ? result.length : 0);
        this.agent?.recordMetric(metricName, count);
      }
      return result;
    }
    return descriptor;
  }
}

Then annotate your service methods accordingly:

class QueriesService {
  private readonly agent = getAgent();

  constructor( /* ... */ ) {}

  @withMetric('query.create', 'increment')
  async create(userId: string, createQueryDto: CreateQueryDto) {
    // business logic...
  }

  @withMetric('query.list.count', 'record', res => res.length)
  async findAll(userId: string) {
    return await this.prisma.queryItem.findMany({
      where: { ...queryItemWhereOwnerOrMember(userId) },
    });
  }

  @withMetric('query.revision.list.count', 'record', res => res.length)
  async listRevisions(userId: string, queryId: string) {
    return await this.prisma.queryItemRevision.findMany({
      // query...
    });
  }

  @withMetric('query.revision.create', 'increment')
  async createRevision(/* ... */) {
    // revision logic...
  }
}

This decorator-based approach reduces duplication and clearly separates concerns while keeping functionality unchanged.

Copy link

github-actions bot commented Feb 18, 2025

Visit the preview URL for this PR (updated for commit d5691c2):

https://altair-gql--pr2769-imolorhe-improve-api-780eu871.web.app

(expires Tue, 25 Feb 2025 19:28:57 GMT)

🔥 via Firebase Hosting GitHub Action 🌎

Sign: 02d6323d75a99e532a38922862e269d63351a6cf

@imolorhe imolorhe added this pull request to the merge queue Feb 18, 2025
Merged via the queue into master with commit 89c4596 Feb 18, 2025
15 checks passed
@imolorhe imolorhe deleted the imolorhe/improve-api-telemetry branch February 18, 2025 20:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant