CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-scramjet--api-client

API Client for use with Scramjet Transform Hub providing typed interfaces for managing sequences, instances, and Hub operations

Pending
Overview
Eval results
Files

instance-client.mddocs/

Instance Control

The InstanceClient provides comprehensive management of running sequence instances including lifecycle control, streaming I/O, and event handling.

Capabilities

Instance Client Creation

Create an InstanceClient for managing a specific running instance.

/**
 * Creates InstanceClient for a specific instance
 * @param id - Instance identifier
 * @param host - ClientProvider (typically HostClient) for API communication
 * @returns New InstanceClient instance
 */
class InstanceClient {
  readonly id: string;
  
  static from(id: string, host: ClientProvider): InstanceClient;
  private constructor(id: string, host: ClientProvider);
}

Usage Example:

import { HostClient } from "@scramjet/api-client";

const host = new HostClient("http://localhost:8000/api/v1");
const instance = host.getInstanceClient("instance-id");
// or
const instance = InstanceClient.from("instance-id", host);

Lifecycle Management

Control instance execution and lifecycle.

/**
 * Gracefully stops the instance
 * @param timeout - Maximum time to wait for graceful shutdown (milliseconds)
 * @param canCallKeepalive - Whether the instance can extend its lifetime
 * @returns Promise resolving to stop operation result
 */
stop(
  timeout: number,
  canCallKeepalive: boolean
): Promise<STHRestAPI.SendStopInstanceResponse>;

/**
 * Forcibly kills the instance
 * @param opts - Kill options
 * @param opts.removeImmediately - Bypass instance lifetime extension delay
 * @returns Promise resolving to kill operation result
 */
kill(opts?: KillMessageData): Promise<STHRestAPI.SendKillInstanceResponse>;

/**
 * Gets current instance health status
 * @returns Promise resolving to health information
 */
getHealth(): Promise<STHRestAPI.GetHealthResponse>;

/**
 * Gets detailed instance information
 * @returns Promise resolving to instance details
 */
getInfo(): Promise<STHRestAPI.GetInstanceResponse>;

Usage Examples:

// Graceful shutdown with 10 second timeout
await instance.stop(10000, false);

// Force kill immediately
await instance.kill({ removeImmediately: true });

// Check instance health
const health = await instance.getHealth();
console.log(`Instance status: ${health.status}`);

Stream I/O Operations

Send and receive data streams to/from the instance.

/**
 * Gets an output stream from the instance
 * @param streamId - Output stream identifier
 * @returns Promise resolving to readable stream
 */
getStream(streamId: InstanceOutputStream): ReturnType<HttpClient["getStream"]>;

/**
 * Sends data to an instance input stream
 * @param streamId - Input stream identifier
 * @param stream - Data to send (stream or string)
 * @param requestInit - Optional request configuration
 * @param options - Stream options
 * @returns Promise resolving to send operation result
 */
sendStream(
  streamId: InstanceInputStream,
  stream: Parameters<HttpClient["sendStream"]>[1] | string,
  requestInit?: RequestInit,
  options?: SendStreamOptions
): Promise<STHRestAPI.SendStreamResponse>;

/**
 * Convenient method to send data to the instance input stream
 * @param stream - Data to send (stream or string)
 * @param requestInit - Optional request configuration
 * @param options - Stream options
 * @returns Promise resolving to send operation result
 */
sendInput(
  stream: Parameters<HttpClient["sendStream"]>[1] | string,
  requestInit?: RequestInit,
  options?: SendStreamOptions
): Promise<STHRestAPI.SendStreamResponse>;

/**
 * Convenient method to send data to the instance stdin
 * @param stream - Data to send (stream or string)
 * @returns Promise resolving to send operation result
 */
sendStdin(stream: Parameters<HttpClient["sendStream"]>[1] | string): Promise<STHRestAPI.SendStreamResponse>;

/**
 * Bidirectional stream operation (send and receive simultaneously)
 * @param stream - Input data stream
 * @param requestInit - Optional request configuration
 * @param options - Stream options
 * @returns Promise resolving to response stream
 */
inout(
  stream: Parameters<HttpClient["sendStream"]>[1],
  requestInit?: RequestInit,
  options?: SendStreamOptions
): Promise<any>;

/**
 * Convenient method to get instance log stream
 * @returns Promise resolving to log stream
 */
getLogStream(): Promise<Readable>;

Usage Examples:

import { Readable } from "stream";

// Get instance output and pipe to console
const outputStream = await instance.getStream("output");
outputStream.pipe(process.stdout);

// Send string data to instance
await instance.sendInput("Hello, World!\n");

// Send stream data
const dataStream = Readable.from(["line 1\n", "line 2\n", "line 3\n"]);
await instance.sendStream("input", dataStream);

// Monitor instance logs
const logStream = await instance.getLogStream();
logStream.on('data', (chunk) => {
  console.log('Instance log:', chunk.toString());
});

// Bidirectional communication
const inputStream = Readable.from(["query 1\n", "query 2\n"]);
const responseStream = await instance.inout(inputStream);
responseStream.pipe(process.stdout);

Event Handling

Send events to instances and receive events from them.

/**
 * Sends an event to the instance
 * @param eventName - Name of the event
 * @param message - Event data/message
 * @returns Promise resolving to send event result
 */
sendEvent(eventName: string, message: string): Promise<STHRestAPI.SendEventResponse>;

/**
 * Waits for and returns the next occurrence of a specific event
 * @param eventName - Name of the event to wait for
 * @returns Promise resolving to event data
 */
getNextEvent(eventName: string): Promise<STHRestAPI.GetEventResponse>;

/**
 * Gets the last data from a specific event (waits if event never fired)
 * @param eventName - Name of the event
 * @returns Promise resolving to event data
 */
getEvent(eventName: string): Promise<STHRestAPI.GetEventResponse>;

/**
 * Gets a continuous stream of events of a specific type
 * @param eventName - Name of the event type
 * @returns Promise resolving to event stream
 */
getEventStream(eventName: string): Promise<Readable>;

Usage Examples:

// Send a custom event to the instance
await instance.sendEvent("config-update", JSON.stringify({
  setting: "debug",
  value: true
}));

// Wait for instance to send a "ready" event
const readyEvent = await instance.getNextEvent("ready");
console.log("Instance is ready:", readyEvent.data);

// Monitor progress events
const progressStream = await instance.getEventStream("progress");
progressStream.on('data', (chunk) => {
  const event = JSON.parse(chunk.toString());
  console.log(`Progress: ${event.percentage}%`);
});

// Get last error event
try {
  const lastError = await instance.getEvent("error");
  console.log("Last error:", lastError.data);
} catch (error) {
  console.log("No error events received yet");
}

Stream Types

/**
 * Valid input stream identifiers for sending data to instances
 */
type InstanceInputStream = "stdin" | "input";

/**
 * Valid output stream identifiers for receiving data from instances
 */
type InstanceOutputStream = "stdout" | "stderr" | "output" | "log";

Response Types

interface STHRestAPI {
  SendStopInstanceResponse: {
    message: string;
    acknowledged: boolean;
  };
  
  SendKillInstanceResponse: {
    message: string;
    killed: boolean;
  };
  
  SendEventResponse: {
    eventName: string;
    message: string;
    sent: boolean;
  };
  
  GetEventResponse: {
    eventName: string;
    data: any;
    timestamp: string;
  };
  
  GetHealthResponse: {
    status: "healthy" | "unhealthy" | "unknown";
    message?: string;
    uptime?: number;
    [key: string]: any;
  };
  
  GetInstanceResponse: {
    id: string;
    sequence: string;
    status: "starting" | "running" | "stopping" | "stopped" | "crashed";
    ports: { [key: string]: number };
    created: string;
    started?: string;
    ended?: string;
    [key: string]: any;
  };
  
  SendStreamResponse: {
    bytesWritten: number;
    status: "success" | "error";
    message?: string;
  };
}

interface KillMessageData {
  removeImmediately?: boolean;
}

interface SendStreamOptions {
  type?: string;
  end?: boolean;
  parseResponse?: "json" | "text" | "stream";
  json?: boolean;
  parse?: "json" | "text" | "stream";
}

Error Handling

Instance operations may throw various errors. Common error scenarios:

try {
  await instance.stop(5000, false);
} catch (error) {
  if (error.code === 'INSTANCE_NOT_FOUND') {
    console.log('Instance no longer exists');
  } else if (error.code === 'STOP_TIMEOUT') {
    console.log('Instance did not stop gracefully, consider using kill()');
  } else {
    console.log('Unexpected error:', error.message);
  }
}

Install with Tessl CLI

npx tessl i tessl/npm-scramjet--api-client

docs

host-client.md

index.md

instance-client.md

manager-client.md

sequence-client.md

topics.md

tile.json