@push.rocks/smartcontext

A module to enrich logs with context, featuring async log contexts and scope management.

Install

To install the @push.rocks/smartcontext module, you can use npm. Make sure you have Node.js and npm installed on your system. Navigate to your project directory and run the following command:

npm install @push.rocks/smartcontext

This command will download and install the module and its dependencies into your project's node_modules directory.

Usage

The @push.rocks/smartcontext module provides an efficient way to enrich your logging with contextual information. It features asynchronous log contexts and scope management, especially useful in complex asynchronous workflows in Node.js applications. This documentation will guide you through its core components: AsyncContext and AsyncStore.

Setting Up and Basic Usage

First, import the necessary classes from the module in your TypeScript application:

import { AsyncContext, AsyncStore } from '@push.rocks/smartcontext';

Creating a Context

You can create an AsyncContext for managing scope-based data sharing. Each context maintains a top-level AsyncStore instance. Lets create a simple context and store some data:

const mainContext = new AsyncContext();

// Add some data to the store
mainContext.store.add('username', 'john_doe');
mainContext.store.add('role', 'admin');

console.log(mainContext.store.get('username')); // Outputs: 'john_doe'
console.log(mainContext.store.get('role'));     // Outputs: 'admin'

This mainContext acts as a container for contextual data throughout the lifecycle of your application or a specific code block.

Scoping with runScoped

The runScoped method allows you to run a function within a specific child AsyncStore scope. This is vital for isolating child data during asynchronous operations, while still having access to any relevant parent data:

await mainContext.runScoped(async (childStore: AsyncStore) => {
  childStore.add('transactionId', 'txn_123456');
  
  console.log(childStore.get('transactionId')); // Outputs: 'txn_123456'
  // Child store can also access data from the parent context:
  console.log(childStore.get('username'));       // Outputs: 'john_doe'
  console.log(childStore.get('role'));           // Outputs: 'admin'
});

Changes made within this child store do not leak back to the parent unless explicitly intended.

Isolating Data in Scoped Functions

Data added within a child scope is only stored locally, unless you decide to propagate it to the parent. Additionally, you can delete data in the child without affecting the parent:

await mainContext.runScoped(async (childStore: AsyncStore) => {
  childStore.add('temporaryData', 'tempValue');
  console.log(childStore.get('temporaryData')); // Outputs: 'tempValue'
  
  // Delete data in child scope
  childStore.delete('temporaryData');
  console.log(childStore.get('temporaryData')); // Outputs: undefined
});

In this example, temporaryData is never propagated to the parent. Once deleted within the scope, its gone for that child context.

Advanced Usage

Below are some patterns to demonstrate more advanced scenarios.

Handling Complex Asynchronous Flows

Consider a scenario where you process a list of user requests asynchronously, assigning each request its own temporary data:

import { AsyncContext } from '@push.rocks/smartcontext';
import { v4 as uuidv4 } from 'uuid';

async function processUserRequests(users: string[], asyncContext: AsyncContext) {
  for (const user of users) {
    await asyncContext.runScoped(async (childStore: AsyncStore) => {
      // Assign a unique request ID
      const requestId = uuidv4();
      childStore.add('currentUser', user);
      childStore.add('requestId', requestId);

      console.log(`Processing user: ${childStore.get('currentUser')} with Request ID: ${childStore.get('requestId')}`);

      // Simulate an async operation
      await new Promise((resolve) => setTimeout(resolve, 1000));

      console.log(`Completed processing for user: ${childStore.get('currentUser')}`);
    });
  }
}

const mainContext = new AsyncContext();
processUserRequests(['alice', 'bob'], mainContext);

Each users scope remains neatly contained while still sharing any parent data (if present). This is highly beneficial in servers that handle multiple requests or tasks in parallel.

Sharing Data Across Scopes

Occasionally, you may want the child scope to add or modify data that persists in the parent. By default, childStore only extends the parent for lookup; changes remain local to the child. If you need truly shared data, you can write data directly to the parent store as well:

const newContext = new AsyncContext();
await newContext.runScoped(async (childStore: AsyncStore) => {
  // This affects only the child store
  childStore.add('childMessage', 'I am a child.');

  // Directly manipulate the parent store if needed:
  newContext.store.add('parentMessage', 'I am the parent (updated).');
});

// Checking the parent store:
console.log(newContext.store.get('parentMessage')); // Outputs: 'I am the parent (updated)'
console.log(newContext.store.get('childMessage'));  // Outputs: undefined (child-only)

This approach helps you maintain clarity on what data belongs to the parent vs. a transient child operation.

Parallel Scopes

When dealing with parallel asynchronous operations, each scope can be maintained independently. For instance, multiple login operations can be handled by the same parent context yet remain separate at runtime:

import { AsyncContext } from '@push.rocks/smartcontext';

const userContext = new AsyncContext();
userContext.store.add('appVersion', '1.2.0');

async function handleUserLogin(userId: string, context: AsyncContext) {
  await context.runScoped(async (childStore: AsyncStore) => {
    childStore.add('sessionUser', userId);

    console.log(`User: ${childStore.get('sessionUser')}, App: ${childStore.get('appVersion')}`);
    // More processing for the user...
  });
}

await Promise.all([
  handleUserLogin('user123', userContext),
  handleUserLogin('user456', userContext),
]);

In this example, the userContext store data (like appVersion) is accessible within each child scope, but each user session remains isolated. The parents data is shared and read-only for the children, unless children write specifically to the parent context.

Error Handling and Context-Enriched Logging

By leveraging contextual data, your logs can capture additional diagnostic details automatically:

async function performTaskWithLogging(taskId: string, context: AsyncContext) {
  try {
    await context.runScoped(async (childStore: AsyncStore) => {
      childStore.add('taskId', taskId);
      // Simulate some failing operation
      throw new Error('Task failed due to unexpected error');
    });
  } catch (error) {
    console.error(`[Error] Task ID: ${context.store.get('taskId')}, Error: ${error.message}`);
  }
}

const loggingContext = new AsyncContext();
performTaskWithLogging('task_789', loggingContext);

In the example above, we track taskId in the context store, ensuring that any error logs or additional logging statements automatically include that identifying information.

Managing Contexts Across Modules

In large applications, you might want different modules to read or update shared context data without tight coupling between modules. One pattern is to define an AsyncContext in a root or shared location and pass it as needed:

// main.ts
import { AsyncContext } from '@push.rocks/smartcontext';
import { userModule } from './userModule';
import { billingModule } from './billingModule';

const globalContext = new AsyncContext();
globalContext.store.add('appName', 'SmartContextApp');

userModule(globalContext);
billingModule(globalContext);

Then, each module file can utilize that shared context:

// userModule.ts
export async function userModule(context: AsyncContext) {
  await context.runScoped(async (childStore) => {
    childStore.add('moduleName', 'UserModule');
    console.log(`[UserModule] appName: ${childStore.get('appName')}`);
  });
}
// billingModule.ts
export async function billingModule(context: AsyncContext) {
  await context.runScoped(async (childStore) => {
    childStore.add('moduleName', 'BillingModule');
    console.log(`[BillingModule] appName: ${childStore.get('appName')}`);
  });
}

This approach keeps the code cleaner and ensures each module has access to shared data while retaining isolation where needed.

@push.rocks/smartcontext equips developers with a sophisticated asynchronous context management system, helping maintain clarity and consistency in logging and context sharing. Heres a recap of the benefits:

  • Scoped Data: Run logical operations within isolated child scopes, reducing contamination of global or parent-level data.
  • Asynchronous Safety: Each asynchronous operation can track its own context, preventing race conditions on shared state.
  • Enhanced Logging: Include relevant contextual data in your logs automatically for easier debugging and tracing.
  • Module-Friendly: Share contexts without introducing deep module interdependencies.

These features simplify building robust Node.js applications, where concurrency and context tracking can otherwise become unwieldy. Enjoy exploring the breadth of this modules functionality, and tailor it to meet your projects unique challenges.

This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the license file within this repository.

Please note: The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.

Trademarks

This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.

Company Information

Task Venture Capital GmbH
Registered at District Court Bremen HRB 35230 HB, Germany

For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.

By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

Description
A module to enrich logs with context, featuring async log contexts and scope management.
Readme 797 KiB
Languages
TypeScript 100%