Rayfin

@microsoft/rayfin-connectors

Connector runtime APIs — connectorsService for RayfinClient.create, typed connector configs and markers, host selection, timeouts, Category A entity clients, errors, and middleware.

@microsoft/rayfin-connectors is the runtime kernel behind client.connectors. It registers connectors on the Rayfin client, creates the typed connector proxy, chooses the transport for each connector category, and defines the shared operation, error, host, and middleware types. See the Connectors guide for concepts and setup flow.

Changed in 1.36

Connectors are stable in 1.36. Connector-only Category A helpers that used to live under @microsoft/rayfin-core/experimental, including Source and AutoGenerated, now live in this package.

Changed in 2.0

In 2.0, connectorsService registers connectors on RayfinClient.create, and this package owns the connector types that @microsoft/rayfin-client used to re-export, such as ConnectorConfig, ConnectorsSchema, and ConnectorMarker.

Installation

npm install @microsoft/rayfin-connectors@2.0.0

Changed in 2.0

@microsoft/rayfin-client 2.0 depends only on @microsoft/rayfin-lib, so this package no longer arrives transitively. Declare it directly; rayfin connector add includes it in the pinned install command it prints. Keep it on the same version as every other @microsoft/rayfin-* package.

connectorsService

New in 2.0

connectorsService returns the service factory you register as services.connectors in RayfinClient.create:

function connectorsService<TSchema extends ConnectorsSchema>(
  options: ConnectorsServiceOptions<TSchema>,
): ClientServiceFactory<TypedConnectorsApi<TSchema>>;

interface ConnectorsServiceOptions<TSchema extends ConnectorsSchema> {
  configs: ConnectorConfigs<TSchema>;
  runtime?: ConnectorsRuntime;
  host?: HostEnvironment;
}
src/services/rayfinClient.ts
import { RayfinClient } from '@microsoft/rayfin-client';
import { browserSession } from '@microsoft/rayfin-auth';
import { connectorsService } from '@microsoft/rayfin-connectors';
import { fabricSemanticModel } from '@microsoft/rayfin-connector-fabric-semanticmodel';
import {
  connectorConfig as salesdbConfig,
  type SalesdbSchema,
} from '../../rayfin/connectors/salesdb/schema';
import {
  connectorConfig as salesmodelConfig,
  type SalesmodelSchema,
} from '../../rayfin/connectors/salesmodel/schema';

type AppConnectorsSchema = {
  salesdb: SalesdbSchema;
  salesmodel: SalesmodelSchema;
};

export const rayfinClient = RayfinClient.create({
  baseUrl: import.meta.env.VITE_RAYFIN_API_URL,
  publishableKey: import.meta.env.VITE_RAYFIN_PUBLISHABLE_KEY,
  auth: browserSession({ storage: true }),
  services: {
    connectors: connectorsService<AppConnectorsSchema>({
      configs: { salesdb: salesdbConfig, salesmodel: salesmodelConfig },
      runtime: { salesmodel: fabricSemanticModel() },
    }),
  },
});

export type AppClient = typeof rayfinClient;
  • configs is required and exhaustive: every connector in the schema needs an entry, keyed by its rayfin.yml name, and each entry must match that connector marker's configuration type.
  • runtime holds per-connector hooks for Category B connectors. Category A connectors take no entry.
  • host defaults to { type: 'standalone' } in browsers and in Node.js. Pass { type: 'cli' } only for an actual CLI-run local script, and { type: 'embedded' } only for a verified Fabric embedded host.

ConnectorsRayfinClient

Removed in 2.0

ConnectorsRayfinClient is removed from @microsoft/rayfin-client, together with the @microsoft/rayfin-client/experimental subpath that re-exported it. Map its arguments onto connectorsService:

Rayfin 1.36Rayfin 2.0
new ConnectorsRayfinClient<Data, Functions, Connectors>(config, runtime)RayfinClient.create({ ..., services: { connectors: connectorsService<Connectors>({ configs, runtime }) } })
The connectors config optionconfigs
The second constructor argumentruntime
The host config optionhost
host omitted in Node.js, which detected clihost: { type: 'cli' } when a local script needs CLI middleware; omitted means standalone

See Wiring connectors into your app for complete files.

createConnectorsApi

createConnectorsApi is the low-level factory behind connectorsService. Use it directly only when you already own an ApiClient:

function createConnectorsApi<TSchema extends ConnectorsSchema = ConnectorsSchema>(
  apiClient: ApiClient,
  configs: ConnectorConfigs<TSchema>,
  runtime?: ConnectorsRuntime,
  host?: HostEnvironment,
): TypedConnectorsApi<TSchema>;

Changed in 2.0

configs is typed ConnectorConfigs<TSchema>, so each entry is checked against its marker. When host is omitted, this factory still calls detectHost(), unlike connectorsService.

The dispatcher reads configs[name].connector when a connector is first accessed. The Category A types fabric-sqlanalytics, fabric-warehouse, and fabric-sqldatabase get a GraphQLConnectorClient, so the surface is client.connectors.<name>.<Entity>. All other connector types get a SemanticConnectorClient, so the surface is client.connectors.<name>.<operation>(input, options?).

Changed in 2.0

Connector names resolve case-insensitively. An exact key wins; otherwise the one key that differs only by case is used, and every spelling returns the same client, created under the configured key. Several keys that differ only by case throw ConnectorsError with code AMBIGUOUS_CONNECTOR, and a name with no match in any casing throws UNKNOWN_CONNECTOR.

Schema, config, and operation types

The package exports the shared type vocabulary consumed by connector marker packages:

type ConnectorsSchema = Record<string, ConnectorMarker>;

interface ConnectorMarker<TClient = unknown, TConfig extends ConnectorConfig = ConnectorConfig> {
  readonly __client?: TClient;
  readonly __config?: TConfig;
}

type ConnectorConfigs<TSchema extends ConnectorsSchema> = {
  [K in keyof TSchema & string]: TSchema[K] extends ConnectorMarker<unknown, infer TConfig>
    ? TConfig
    : never;
};

interface ConnectorConfig {
  connector: ConnectorType;
  operations?: readonly CrudOperation[];
  entities?: Record<string, EntityClass | readonly string[]>;
}

interface OperationDef<TInput = unknown, TOutput = unknown> {
  readonly __input?: TInput;
  readonly __output?: TOutput;
}

type OperationCatalog = Record<string, OperationDef<unknown, unknown>>;

interface InvokeOptions {
  headers?: Record<string, string>;
  timeoutMs?: number;
}

Changed in 2.0

ConnectorMarker carries the configuration type each connector accepts, and ConnectorConfigs<TSchema> checks every config against it: an Eventhouse marker cannot receive a semantic-model config, and a GraphQLBackedConnector marker needs its generated connectorConfig, with its literal connector and operations. Declare a separate config map with satisfies ConnectorConfigs<AppConnectorsSchema>. A custom marker can require its own config fields with ConnectorMarker<TClient, TConfig>; omitting TConfig keeps the shared ConnectorConfig contract.

TypedConnectorClient<TCatalog> maps each operation of a Category B catalog to a method that takes the operation's input and an optional InvokeOptions, and resolves to its output. TypedConnectorsApi<TSchema> resolves each connector name to its marker's client shape.

ConnectorType is the connector type union shared with the CLI, and CrudOperation is the Category A verb union. ConnectorConfig.operations gates Category A CRUD methods at runtime; ConnectorConfig.entities supplies default selections and relationship metadata for entity connectors.

Request timeouts

Changed in 2.0

A Category B operation waits up to CONNECTOR_INVOKE_TIMEOUT_MS (5 minutes, exported by @microsoft/rayfin-lib), the deadline the backend enforces for connector calls, instead of the client's generic 30-second timeout. InvokeOptions.timeoutMs shortens it for one call: a larger value is capped at 5 minutes, and a value of zero or less uses the default.

src/features/sales/loadTopSales.ts
import { rayfinClient } from '../../services/rayfinClient';

export function loadTopSales() {
  return rayfinClient.connectors.salesmodel.executeQuery(
    { query: "EVALUATE TOPN(10, 'Sales')" },
    { timeoutMs: 20_000 },
  );
}

Source and AutoGenerated

Changed in 1.36

Category A connector entities extend Source(options) instead of a Rayfin-owned data base class. Source and the AutoGenerated<T> marker are exported from @microsoft/rayfin-connectors:

rayfin/connectors/orders/Order.ts
import { entity, int, text } from '@microsoft/rayfin-core';
import { Source } from '@microsoft/rayfin-connectors';
import type { AutoGenerated } from '@microsoft/rayfin-connectors';

@entity()
export class Order extends Source({ schema: 'dbo', table: 'Order', primaryKey: ['id'] }) {
  @int({ column: 'Id' })
  id!: AutoGenerated<number>;

  @text({ max: 256 })
  customerEmail!: string;
}

SourceOptions includes schema, table, and primaryKey. primaryKey: [] marks a keyless source entity, removing findByKey, update, and delete from the typed client.

Host detection

interface HostEnvironment {
  type: 'embedded' | 'standalone' | 'cli';
}

const DEFAULT_HOST_ENVIRONMENT: HostEnvironment;

function detectHost(): HostEnvironment;

DEFAULT_HOST_ENVIRONMENT is the standalone environment. detectHost() returns 'cli' when there is no browser DOM and 'standalone' in browsers. It never auto-detects 'embedded'; a host package must assert that environment by passing an explicit host.

Changed in 2.0

Only createConnectorsApi calls detectHost(). connectorsService defaults to standalone everywhere, so a Node.js app deployed behind the Rayfin backend keeps backend routing and authorization. The host selects middleware behavior only; it never acquires tokens.

Category A entity clients

ConnectorEntityClient is the entity surface behind Category A connectors. It supports the read chain select, where, orderBy, first, and after, terminal reads findMany, findFirst, and findByKey, mutations create, update, and delete, and the aggregation entry points groupBy and aggregate. See Fabric SQL sources for usage patterns and Aggregations for aggregation shapes.

CRUD operations map to client methods through METHODS_FOR_CRUD_OPERATION:

CRUD operationMethods
readselect, where, orderBy, first, groupBy, aggregate, findMany, findFirst, findByKey
createcreate
updateupdate
deletedelete

Changed in 2.0

Read result types follow the selection. A literal field list — in select, in findMany(fields, filter?), in findFirst(fields, filter?), or as the scalar selection of findByKey(key, fields) — returns exactly those fields. A read without a selection returns ConnectorDefaultReadResult<T>: every scalar field optional, no relationships. Selected Date fields are typed Date | string, and booleans boolean | 'true' | 'false'.

type ConnectorDefaultReadResult<T> = GraphQLResponseValue<Partial<Pick<T, ScalarLeafKeys<T>>>>;

type MutationResult<TDialect extends ConnectorType, TRecord> =
  TDialect extends 'fabric-warehouse' ? DbOperationResult : ConnectorDefaultReadResult<TRecord>;

interface DbOperationResult {
  readonly result: string;
}

Fabric Warehouse mutations return DbOperationResult, because that dialect does not read the mutated row back. Other writable dialects return the registered scalar columns, each optional.

Errors

Connector failures use a shared result contract:

type ConnectorErrorCategory = 'network' | 'api' | 'query' | 'overflow' | 'unknown';

interface ConnectorError {
  message: string;
  code?: string;
  category?: ConnectorErrorCategory;
  details?: string;
  recoveryHint?: string;
}

interface ConnectorErrorResult {
  status: 'error';
  error: ConnectorError;
}

function isConnectorError(value: unknown): value is ConnectorErrorResult;

isConnectorError narrows normalized operation results that satisfy the shared failed shape. ConnectorsError, which extends SdkError, is thrown by SDK-side routing and validation failures. Branch on its code:

CodeThrown when
UNKNOWN_CONNECTORNo configured connector matches the name in any casing.
AMBIGUOUS_CONNECTORSeveral configured connector keys differ from the name only by case. New in 2.0
OPERATION_NOT_ALLOWEDA Category A CRUD method outside connectorConfig.operations was called.
SELECTION_REQUIREDA query chain reached execute() without select(), or a no-selection findMany or findFirst ran without connectorConfig.entities.
ENTITIES_REQUIRED_FOR_RELATIONSHIP_SELECTA dotted relationship path was selected without entity classes in connectorConfig.entities.
INVALID_RELATIONSHIP_SELECTIONA segment of a dotted path is not a @one or @many field.

A Category B call that the backend refuses throws a NetworkError from @microsoft/rayfin-client; its serverErrorCode carries the service's code when one was sent.

Runtime middleware

Connector-specific packages add behavior with ConnectorRuntime:

type ConnectorsRuntime = Record<string, ConnectorRuntime>;

interface ConnectorRuntime {
  operations?: Record<string, OperationRuntime>;
}

interface OperationRuntime {
  decodeBinary?: (data: ArrayBuffer) => unknown;
  invoke?: (ctx: InvokeContext, next: InvokeNext) => Promise<unknown>;
}

interface InvokeContext {
  readonly connectorName: string;
  readonly operation: string;
  readonly input?: unknown;
  readonly options?: InvokeOptions;
  readonly responseType?: 'raw';
  readonly signal?: AbortSignal;
  readonly timeout?: number;
  readonly host: HostEnvironment;
  readonly connectorConfig?: ConnectorConfig;
  readonly http?: InvokeHttpClient;
}

type InvokeNext = (ctx: InvokeContext) => Promise<unknown>;

interface InvokeHttpClient {
  fetch(input: Request | string | URL, init?: RequestInit): Promise<Response>;
}

invoke can handle a call itself or call next(ctx) to use the default transport. decodeBinary runs only for binary payloads returned through the operation proxy.

New in 2.0

Protocol-aware middleware can set responseType: 'raw' on the context it passes to next to receive the unconsumed HTTP Response, with signal for cancellation and timeout in milliseconds. Raw responses are never retried or decoded automatically: the middleware must consume or cancel the body and handle non-success status codes. The default transport is unchanged.

Note

client.connectors.<name>.invoke('op', input) is a raw escape hatch. It uses the default standalone transport and bypasses middleware and decodeBinary. For decoded output, call the named operation method such as client.connectors.salesmodel.executeQuery(input).

Something wrong on this page?Report an issueEdit this page

On this page