Extension SDK
Calculation functions
Compute values the engine needs from your inputs — travel times, dynamic costs, capacity-adjusted scores.
Key points
- Calculation functions return a single value — number, string, or object — from typed inputs
- They’re called from constraints, alternative ranking, and other extensions
- Default timeout is 5 seconds; bound to the request path so keep them fast
- Inject service clients via the manifest; never instantiate HTTP clients inline
The interface
Every calculation function implements ICalculationFunction. The interface is deliberately small — you declare a name, a version, and a single async method:
ICalculationFunctionComputes a typed value from inputs. Called inline during constraint evaluation, allocator scoring, and from other extensions.
Required properties
namestring— Stable identifier referenced from templatesversionstring— Semver; pinned in templates explicitly
calculateCompute the return value from the provided inputs. Must be deterministic and bounded by the configured timeout.
calculate(
ctx: CalculationContext,
params: TParams,
): Promise<TResult>TParams and TResult are interface generics — you declare them when implementing. The runtime validates the params against your declared shape before calling.
A complete example
Here’s the TravelTimeCalculator used by the Home Care template. It demonstrates the full pattern — typed params, an injected service client, mobility- specific buffers, time-of-day adjustments, and rounding for scheduling cleanliness:
import {
ICalculationFunction,
CalculationContext,
} from '@flexischeduler/extension-sdk';
interface TravelTimeParams {
origin: GeoLocation;
destination: GeoLocation;
mobility_type: 'ambulatory' | 'wheelchair' | 'stretcher' | 'hoyer_lift';
time_of_day?: Date;
}
export class TravelTimeCalculator implements ICalculationFunction {
name = 'TravelTimeCalculator';
version = '1.2.0';
async calculate(
ctx: CalculationContext,
params: TravelTimeParams,
): Promise<number> {
// Pull base travel time from the mapping service injected by the runtime
const route = await ctx.googleMaps.directions({
origin: params.origin,
destination: params.destination,
departureTime: params.time_of_day ?? new Date(),
mode: 'driving',
});
let minutes = route.durationMinutes;
// Add mobility-specific buffer
const buffers = {
ambulatory: 5,
wheelchair: 15,
stretcher: 25,
hoyer_lift: 30,
} as const;
minutes += buffers[params.mobility_type];
// Rush hour adjustment
const hour = (params.time_of_day ?? new Date()).getHours();
if (hour >= 7 && hour <= 9) minutes *= 1.3;
else if (hour >= 16 && hour <= 18) minutes *= 1.25;
// Round up to nearest 5 minutes for scheduling cleanliness
return Math.ceil(minutes / 5) * 5;
}
}How it’s called
Calculation functions don’t run on their own — they’re invoked by something else in the request path. Most commonly, constraints reference them with uses_extension:
{
"constraints": [
{
"id": "daily_hour_limit",
"type": "time_based",
"rule": "SUM(event.duration + travel_time) <= participant.daily_hour_limit",
"uses_extension": "TravelTimeCalculator",
"extension_inputs": {
"origin": "previous_event.location",
"destination": "event.location",
"mobility_type": "participant.mobility_requirements"
}
}
]
}The constraint engine evaluates the rule, hits the travel_time reference, and dispatches to the calculator. The calculator’s return value is bound to the rule expression, then the rule resolves.
Allocators and other extensions can also invoke calculators directly via ctx.callExtension(...) — the runtime handles the cross-extension dispatch with appropriate timeout enforcement on each hop.
The CalculationContext
Every calculate call receives a context object as the first argument. The context carries injected service clients, observability hooks, and runtime helpers:
interface CalculationContext {
// Injected service clients (declared in flexi.config.json)
googleMaps?: GoogleMapsClient;
netSmart?: NetSmartClient;
customCrm?: CustomCrmClient;
// Standard runtime services
logger: Logger;
trace: { spanId: string; traceId: string };
metrics: MetricsClient;
// Cache helpers — extensions can opt in to result caching
cache: {
get<T>(key: string): Promise<T | null>;
set<T>(key: string, value: T, ttlSeconds: number): Promise<void>;
};
}Service clients (googleMaps, netSmart, etc.) only appear if your manifest declares them. The runtime injects credentials from the customer’s integration configuration; you never see the raw keys.
Common patterns
Cache aggressively
Calculations are deterministic by design. If your inputs are the same, the output should be too — and that means cache hits are free quality wins. Use the runtime cache:
async calculate(ctx, params) {
const key = `travel:${params.origin.lat},${params.origin.lng}:${params.destination.lat},${params.destination.lng}`;
const cached = await ctx.cache.get<number>(key);
if (cached !== null) return cached;
const result = await this.computeFresh(ctx, params);
await ctx.cache.set(key, result, 86400); // 24h TTL
return result;
}The cache is shared across customer requests. Pick keys that don’t leak customer-specific data (location coordinates are fine; participant IDs are not).
Compose calculators
A calculator can call another calculator via ctx.callExtension. Useful when you have a primitive (travel time) used by a composite (route cost). The runtime handles cross-call timeouts; outer call timeout is your timeout, inner is the inner extension’s.
Caveats
- Determinism matters. Calculators are cached and replayed. Returning different values for the same input will surface as mysterious scheduling drift.
- Stay under the timeout. Default is 5 seconds. The constraint chain short-circuits on hard fails, but slow calculators slow every request that depends on them.
- External calls are timeout-bounded too. A slow Google Maps call burns your calculator’s budget. Use cache aggressively and set short HTTP timeouts on injected clients.
- No side effects. Don’t mutate state. Don’t fire-and-forget. The runtime treats calculators as pure functions.
Need to mutate state