Graftcode Context Libraries

Graftcode Context Libraries

Graftcode Context provides a standardized way to access request context (headers and metadata) during Graftcode invocations. The library is available for multiple platforms and programming languages.

Overview

The RequestContext class provides a thread-safe (or context-aware) singleton that allows you to retrieve headers and custom metadata anywhere in your code during the request lifecycle.

Note

On the server side, headers are automatically set by Graftcode Gateway which hosts your code. On the client side (in Grafts), headers can be set using the GraftConfig class.

This is essential for accessing authentication tokens, correlation IDs, tenant information, and other request-scoped data propagated through Graftcode service calls.


Setting Headers in Grafts (Client Libraries)

Grafts are client libraries generated by Graftcode that allow you to call remote services. Unlike server-side code where headers are set automatically by Graftcode Gateway, in Grafts you need to set headers explicitly using the GraftConfig class.

The GraftConfig class is automatically generated as part of every Graft package by graftcode-code-generator projects. It provides two methods for setting headers:

GraftConfig.setHeaders

Sets headers globally for all subsequent Graft invocations. Use this when you want to set headers once (e.g., at application startup or after authentication) and have them applied to all calls.

GraftConfig.invokeWithHeaders

Sets headers only for a specific function invocation. The headers are scoped to that single call and do not affect other invocations. Use this when you need different headers for different calls or want to temporarily override global headers.

Examples by Technology

Node.js

import { GraftConfig, MyService } from '@graft/nuget-MyService';

// Set headers globally
GraftConfig.setHeaders({
  'Authorization': 'Bearer token123',
  'X-Correlation-Id': 'abc-123'
});

// Or set headers for a specific invocation
const result = GraftConfig.invokeWithHeaders(
  () => MyService.doSomething(),
  { 'Authorization': 'Bearer different-token' }
);

.NET

using graft.nuget.MyService;

// Set headers globally
GraftConfig.SetHeaders(new Dictionary<string, string>
{
    { "Authorization", "Bearer token123" },
    { "X-Correlation-Id", "abc-123" }
});

// Or set headers for a specific invocation
var result = GraftConfig.InvokeWithHeaders(
    () => MyService.DoSomething(),
    new Dictionary<string, string> { { "Authorization", "Bearer different-token" } }
);

// Async version
var asyncResult = await GraftConfig.InvokeWithHeadersAsync(
    async () => await MyService.DoSomethingAsync(),
    new Dictionary<string, string> { { "Authorization", "Bearer different-token" } }
);

Java

import graft.nuget.GraftConfig;
import graft.nuget.MyService;
import java.util.Map;
import java.util.HashMap;

// Set headers globally
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer token123");
headers.put("X-Correlation-Id", "abc-123");
GraftConfig.setHeaders(headers);

// Or set headers for a specific invocation
var result = GraftConfig.invokeWithHeaders(
    () -> MyService.doSomething(),
    Map.of("Authorization", "Bearer different-token")
);

Python

from graft_nuget_myservice import GraftConfig, MyService

# Set headers globally
GraftConfig.set_headers({
    'Authorization': 'Bearer token123',
    'X-Correlation-Id': 'abc-123'
})

# Or set headers for a specific invocation
result = GraftConfig.invoke_with_headers(
    lambda: MyService.do_something(),
    {'Authorization': 'Bearer different-token'}
)

# Async version
result = await GraftConfig.invoke_with_headers_async(
    lambda: MyService.do_something_async(),
    {'Authorization': 'Bearer different-token'}
)

PHP

<?php

use MyGraftPackage\GraftConfig;
use MyGraftPackage\MyService;

// Set headers globally
GraftConfig::setHeaders([
    'Authorization' => 'Bearer token123',
    'X-Correlation-Id' => 'abc-123'
]);

// Or set headers for a specific invocation
$result = GraftConfig::invokeWithHeaders(
    fn() => MyService::doSomething(),
    ['Authorization' => 'Bearer different-token']
);

Ruby

require 'graft_nuget_mypackage'

# Set headers globally
GraftConfig.set_headers({
  'Authorization' => 'Bearer token123',
  'X-Correlation-Id' => 'abc-123'
})

# Or set headers for a specific invocation
result = GraftConfig.invoke_with_headers(
  -> { MyService.do_something },
  { 'Authorization' => 'Bearer different-token' }
)

Available Libraries

TechnologyPackage NamePackage URL
Node.jsgraftcode-contextnpmjs.com/package/graftcode-context
.NETGraftcode.Contextnuget.org/packages/Graftcode.Context
Javacom.graftcode:graftcode-contextcentral.sonatype.com/artifact/com.graftcode/graftcode-context
Pythongraftcode-contextpypi.org/project/graftcode-context
PHPgraftcode/graftcode-contextpackagist.org/packages/graftcode/graftcode-context
Rubygraftcode-contextrubygems.org/gems/graftcode-context

Node.js / TypeScript

Installation

npm install graftcode-context

Requirements: Node.js >= 22.0.0

Usage

import { RequestContext } from 'graftcode-context';

const headers = RequestContext.current.getHeaders();

const authToken = headers['Authorization'];
const correlationId = headers['X-Correlation-Id'];
const tenantId = headers['X-Tenant-Id'];

.NET

Installation

dotnet add package Graftcode.Context

Or via Package Manager Console:

Install-Package Graftcode.Context

Target Frameworks: .NET Standard 2.1, .NET 8.0

Usage

using Graftcode.Context;

var headers = RequestContext.Current.GetHeaders();

var authToken = headers["Authorization"];
var correlationId = headers["X-Correlation-Id"];
var tenantId = headers["X-Tenant-Id"];

Note

The RequestContext.Current property uses [ThreadStatic] attribute to ensure thread safety in multi-threaded applications.


Java / JVM

Installation (Maven)

Add to your pom.xml:

<dependency>
    <groupId>com.graftcode</groupId>
    <artifactId>graftcode-context</artifactId>
    <version>1.0.0</version>
</dependency>

Installation (Gradle)

implementation 'com.graftcode:graftcode-context:1.0.0'

Requirements: Java 8+

Usage

import com.graftcode.context.RequestContext;
import java.util.Map;

Map<String, String> headers = RequestContext.current().getHeaders();

String authToken = headers.get("Authorization");
String correlationId = headers.get("X-Correlation-Id");
String tenantId = headers.get("X-Tenant-Id");

Note

The implementation uses ThreadLocal to ensure thread safety.


Python

Installation

pip install graftcode-context

Requirements: Python >= 3.9

Usage

from graftcode.context import RequestContext

headers = RequestContext.current().get_headers()

auth_token = headers.get('Authorization')
correlation_id = headers.get('X-Correlation-Id')
tenant_id = headers.get('X-Tenant-Id')

Note

The Python implementation uses contextvars.ContextVar for async-safe context propagation, making it compatible with asyncio and other async frameworks.


PHP

Installation

composer require graftcode/graftcode-context

Requirements: PHP >= 7.4 or PHP >= 8.0

Usage

<?php

use Graftcode\Context\RequestContext;

$headers = RequestContext::current()->getHeaders();

$authToken = $headers['Authorization'] ?? null;
$correlationId = $headers['X-Correlation-Id'] ?? null;
$tenantId = $headers['X-Tenant-Id'] ?? null;

Ruby

Installation

Add to your Gemfile:

gem 'graftcode-context'

Then run:

bundle install

Or install directly:

gem install graftcode-context

Requirements: Ruby >= 3.1.0

Usage

require 'graftcode/context'

headers = Graftcode::Context::RequestContext.current.get_headers

auth_token = headers['Authorization']
correlation_id = headers['X-Correlation-Id']
tenant_id = headers['X-Tenant-Id']