"description":"A module providing advanced asynchronous context management to enrich logs with context and manage scope effectively in Node.js applications.",
@ -4,249 +4,218 @@ A module to enrich logs with context, featuring async log contexts and scope man
## 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:
Make sure you have Node.js and npm installed, then run:
```bash
npm install @push.rocks/smartcontext
```
This command will download and install the module and its dependencies into your project's`node_modules`directory.
This will install the library and its dependencies into your local`node_modules`folder.
## 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`.
The `@push.rocks/smartcontext` module provides an efficient way to enrich your code (often for logging) with contextual information. It uses asynchronous context management to support hierarchical scopes—particularly helpful in complex or nested asynchronous operations in Node.js.
### Setting Up and Basic Usage
First, import the necessary classes from the module in your TypeScript application:
You can create an `AsyncContext` for managing scope-based data sharing. Each context maintains a top-level `AsyncStore` instance. Let’s create a simple context and store some data:
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:
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:
console.log(`Completed processing for user: ${childStore.get('currentUser')}`);
});
}
}
constmainContext=newAsyncContext();
processUserRequests(['alice','bob'],mainContext);
```
Each user’s 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:
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:
When you call `asyncContext.runScoped(async () => { ... })`, the library automatically creates a **child**`AsyncStore`. Inside that scoped function, `asyncContext.store` refers to the child store. Any data you add or delete there is isolated from the parent store. However, you can still read parent data if it hasn’t been overridden.
```typescript
awaitasyncContext.runScoped(async()=>{
// Inside this callback, `asyncContext.store` is a *child* store
Because each call to `runScoped` returns control to the parent store afterward, any keys added in a child scope disappear once the scope completes (unless you explicitly move them to the parent). This mechanism keeps data from leaking between scopes.
If the child deletes a key that exists in the parent, it will only remove it from the child’s view of the store. Once the scope completes, the parent store is unaffected.
console.log(asyncContext.store.get('deletableKey'));// undefined in child
});
console.log(asyncContext.store.get('deletableKey'));// 'originalValue' remains in parent
```
### Parallel or Sequential Scopes
You can call `runScoped` multiple times, whether sequentially or in parallel (with `Promise.all`). Each invocation creates its own isolated child store, preventing data collisions across asynchronous tasks.
The following is a complete test script (using [tapbundle](https://www.npmjs.com/package/@push.rocks/tapbundle)) demonstrating how child stores inherit data from the parent but remain isolated. After each scoped block, new child keys vanish, and any parent keys deleted inside the child remain intact in the parent.
In this example, the `userContext` store data (like `appVersion`) is accessible within each child scope, but each user session remains isolated. The parent’s 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:
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:
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. Here’s a recap of the benefits:
### Conclusion
- **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.
With this updated `runScoped` design, there’s no need to explicitly instantiate or manage child stores. The context automatically switches from the parent store to the child store while within the callback, then reverts back to the parent store afterwards. This structure makes it easy to:
These features simplify building robust Node.js applications, where concurrency and context tracking can otherwise become unwieldy. Enjoy exploring the breadth of this module’s functionality, and tailor it to meet your project’s unique challenges.
- Keep each async operation’s state isolated
- Preserve read-access to parent context data
- Avoid overwriting or polluting other operations’ data
This pattern works particularly well for logging or any scenario where you need to pass metadata through deeply nested async calls without manually juggling that data everywhere in your code.
## License and Legal Information
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](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.
This repository is under the [MIT License](./license). Please note that the MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as necessary for reasonable use in describing the origin of the work.
### 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.
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. 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
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.
For any legal inquiries, please contact us at hello@task.vc. By using this repository, you acknowledge that you have read this section and agree to comply with its terms.
description:'A module providing advanced asynchronous context management to enrich logs with context and manage scope effectively in Node.js applications.'
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.