All Projects โ†’ narando โ†’ nest-xray

narando / nest-xray

Licence: MIT license
Distributed tracing for Nestjs with AWS X-Ray as the backend. Instrument incoming and outgoing HTTP requests

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to nest-xray

nestjs-ioredis
IORedis module for Nest
Stars: โœญ 21 (-58%)
Mutual labels:  nest, nestjs
bundled-nest
๐Ÿ’ฅ Nest ๐Ÿ”ฐ Webpack ๐Ÿ”ฐ Docker ๐Ÿ’ฅ --- ๐Ÿฏ Now archived for historical reference โ›ฉ
Stars: โœญ 59 (+18%)
Mutual labels:  nest, nestjs
nestjs-telegraf
๐Ÿค– Powerful Nest module for easy and fast creation Telegram bots
Stars: โœญ 300 (+500%)
Mutual labels:  nest, nestjs
twitch-project
A weekly stream in which I build a web application with Neo4j and Typescript
Stars: โœญ 78 (+56%)
Mutual labels:  nest, nestjs
nestjs-session
Idiomatic Session Module for NestJS. Built on top of `express-session` ๐Ÿ˜Ž
Stars: โœญ 150 (+200%)
Mutual labels:  nest, nestjs
nest-queue
Queue manager for NestJS Framework for Redis (via bull package)
Stars: โœญ 69 (+38%)
Mutual labels:  nest, nestjs
nestjs-asyncapi
NestJS AsyncAPI module - generate the documentation of your event-based services using decorators
Stars: โœญ 88 (+76%)
Mutual labels:  nest, nestjs
Notadd
A microservice development architecture based on nest.js. โ€”โ€” ๅŸบไบŽ Nest.js ็š„ๅพฎๆœๅŠกๅผ€ๅ‘ๆžถๆž„ใ€‚
Stars: โœญ 2,556 (+5012%)
Mutual labels:  nest, nestjs
typegraphql-nestjs
TypeGraphQL integration with NestJS
Stars: โœญ 117 (+134%)
Mutual labels:  nest, nestjs
ogma
A monorepo for the ogma logger and related packages
Stars: โœญ 201 (+302%)
Mutual labels:  nest, nestjs
nestjs-ratelimiter
Distributed consistent flexible NestJS rate limiter based on Redis
Stars: โœญ 49 (-2%)
Mutual labels:  nest, nestjs
angular-chat
Angular v.9, Node.js, Nest.js v.6, Mongoose, Socket.io, Passport, Angular Universal SSR (in progress...)
Stars: โœญ 35 (-30%)
Mutual labels:  nest, nestjs
MyAPI
A template to create awesome APIs easily โšก๏ธ
Stars: โœญ 117 (+134%)
Mutual labels:  nest, nestjs
nestjs-objection
Objection module for NestJS
Stars: โœญ 24 (-52%)
Mutual labels:  nest, nestjs
Jwt
JWT utilities module based on the jsonwebtoken package ๐Ÿ”“
Stars: โœญ 232 (+364%)
Mutual labels:  nest, nestjs
prime-nestjs
A production-ready NestJS boilerplate using Typescript, Postgres, TypeORM, and Docker.
Stars: โœญ 140 (+180%)
Mutual labels:  nest, nestjs
Stator
Stator, your go-to template for the perfect stack. ๐Ÿ˜๐Ÿ™
Stars: โœญ 217 (+334%)
Mutual labels:  nest, nestjs
Nestjs Typegoose
Typegoose with NestJS
Stars: โœญ 215 (+330%)
Mutual labels:  nest, nestjs
nestjs-starter
๐Ÿš€ Nest framework starter
Stars: โœญ 30 (-40%)
Mutual labels:  nest, nestjs
discord-nestjs
๐Ÿ‘พ NestJS package for discord.js
Stars: โœญ 173 (+246%)
Mutual labels:  nest, nestjs

@narando/nest-xray

This module implements Distributed Tracing with AWS X-Ray for Nest.js services.

Features

  • Supported Environments
    • HTTP (express.js)
  • Clients
    • HttpService/HttpModule
  • Manually create new Subsegments to trace custom functions

Usage

โš ๏ธ If you want to use @narando/nest-xray with NestJS Version 6 or 7, please use the v1 release.

The v2 release is only compatible with NestJS Version 8 or 9 and @nestjs/axios >=0.0.5 <=0.1.0.

Installation

Install this module and aws-xray-sdk:

$ npm i @narando/nest-xray aws-xray-sdk

Initialization

Register the TracingModule with your app module:

import { TracingModule } from "@narando/nest-xray";

@Module({
  imports: [TracingModule.forRoot({ serviceName: "your-service-name" })],
})
export class AppModule {}

Environments

An environment is responsible for automatically reading the trace metadata from the incoming request (if available), creating a segment for the processing that happens in the service and recording additional metadata about the request.

There are multiple available environment candidates in Nest.js. By default most applications use the HTTP application model, where they define a @Controller and use express or fastify in the background.
For this application type, the HttpEnvironment tries to read an existing trace segment from the X-Amzn-Trace-Id, and then creates a new segment and adds the URL and other information about the request to the segment. This segment is then made available throughout the request, Clients can now read the segment and add subsegment for the calls that are made through them.

The HttpEnvironment is activated by default in @narando/nest-xray.

Currently no other environments are supported.

If you are interested in contributing:

Building and supporting more environments would greatly improve the usefulness of this package.

Potential environments could be:

  • @nestjs/graphql
  • @nestjs/websockets
  • @nestjs/microservices
  • AWS Lambda - where the trace metadata is presented in environment variables, see #67

Http

The HttpEnvironment checks whether the X-Amzn-Trace-Id header is set and valid, and then creates a segment that references this origin trace. When the request succeeds or fails, the environment adds the current time and the success/error status to the segment.

This environment is mostly implemented through the express middleware of the official aws-xray-sdk

Clients

To trace calls made to a different service, you can either use a premade client, or use the TracingService#createSubSegment method to manually instrument the client of your choosing. The premade clients will automatically create a subsegment for all requests made, and track the duration and response code.

HttpService

This client is a drop-in replacement for the HttpService from @nestjs/axios.

To use it, you must only replace the imports like this:

- import { HttpModule } from "@nestjs/axios"
+ import { HttpTracingModule } from "@narando/nest-xray"

 @Module({
   imports: [
-    HttpModule.registerAsync({
+    HttpTracingModule.registerAsync({
       useFactory: async (config: ConfigService) => ({
         baseURL: config.get("api.base_url"),
         timeout: config.get("api.http_timeout"),
         headers: {
           "user-agent": config.get("api.http_user_agent")
         }
       }),
       inject: [ConfigService]
     })
   ],
   providers: [APIService],
   exports: [APIService]
 })
 export class APIModule {}

Keep using HttpService as before, and all requests are traced as Subsegment and the necessary header for the downstream service is added to the the request.

Custom Tracing

If the premade clients are not sufficient or you want more control, you can use the TracingService.

You can use it to create new subsegments and to access the currently set segment and subsegment.

Once you have access to a segment/subsegment, you can add any data you want to it.

import { TracingService } from "@narando/nest-xray";

@Injectable()
export class ExternalAPIClient {
  constructor(
    private readonly client: ExternalModule,
    private readonly tracingService: TracingService
  ) {}

  async doThing() {
    // Create Subsegment for any Function
    const subSegment = this.tracingService.createSubSegment("external-doThing");

    let response;

    try {
      response = await client.doThing();
    } catch (err) {
      subSegment.close(err);
      throw err;
    }

    subSegment.close();
  }
}

Implementation

We use async_hooks to store the traces and aws-xray-sdk to interact with AWS X-Ray.

async_hooks

This module uses the Node.js API async_hooks to persist the Segment without having to explicitly pass it around to every function involved. It is what enables the "automatic" part of this module.

This API is currently not considered stable, though I have not yet seen any issues (besides slightly worse performance) from using it. This stability is currently being worked on in nodejs/diagnostics#124.

AsyncContext

AsyncContext is an experimental integration of async_hooks into the Nest.js ecosystem. It was initially developed by Kamil Mysliwiec in nestjs/nest#1407 but not merged because async_hooks are not yet stable.

I adopted his implementation into this module for following reasons:

a) It implements all the hard parts with async_hooks and provides enough functionality for our use cases. b) It was developed by the Nest.js Maintainer and is proposed to be merged into Nest.js. If this happens, we may be able to switch to the official implementation without changing any usages of the module.

TracingCoreModule

The TracingCoreModule combines the AsyncContext with the official AWSXRay client. It exports the TracingService, that can be used by other modules to implement additional tracing behaviour (e.g. tracing outgoing http requests).

Known Bugs

  • The XRay Daemon Address can only be configured through the environment variable.

License

This repository is published under the MIT License.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].