or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

application-context.mdhost-communication.mdindex.mdmessage-utilities.mdrunner-execution.mdstream-processing.md

application-context.mddocs/

0

# Application Context

1

2

The RunnerAppContext provides the runtime context for sequences, implementing the AppContext interface with lifecycle management, event handling, and host integration APIs.

3

4

## Core Imports

5

6

```typescript

7

import { RunnerAppContext } from "@scramjet/runner/src/runner-app-context";

8

```

9

10

## Capabilities

11

12

### RunnerAppContext Class

13

14

Application context for sequences providing comprehensive runtime APIs including configuration access, lifecycle handlers, monitoring, and communication with the Transform Hub.

15

16

```typescript { .api }

17

/**

18

* Application context for sequences, implementing AppContext interface

19

*/

20

class RunnerAppContext<AppConfigType extends AppConfig, State extends any>

21

implements AppContext<AppConfigType, State> {

22

constructor(

23

config: AppConfigType,

24

monitorStream: WritableStream<any>,

25

emitter: EventEmitter,

26

runner: RunnerProxy,

27

hostClient: HostClient,

28

spaceClient: ManagerClient,

29

id: string

30

);

31

32

/** Application configuration */

33

config: AppConfigType;

34

35

/** Error constructor for application errors */

36

AppError!: AppErrorConstructor;

37

38

/** Monitoring stream for sending status updates */

39

monitorStream: WritableStream<any>;

40

41

/** Event emitter for sequence events */

42

emitter: EventEmitter;

43

44

/** Initial state (optional) */

45

initialState?: State;

46

47

/** Exit timeout in milliseconds (default: 10000) */

48

exitTimeout: number;

49

50

/** Context logger instance */

51

logger: IObjectLogger;

52

53

/** Host API client for Transform Hub operations */

54

hub: HostClient;

55

56

/** Manager API client for space operations */

57

space: ManagerClient;

58

59

/** Instance identifier */

60

instanceId: string;

61

62

/** Function definition metadata */

63

readonly definition: FunctionDefinition;

64

}

65

```

66

67

**Usage Example:**

68

69

```typescript

70

// In a sequence function

71

export default function(this: RunnerAppContext<any, any>, input: DataStream) {

72

// Access configuration

73

const config = this.config;

74

75

// Set up lifecycle handlers

76

this.addStopHandler(async (timeout, canKeepAlive) => {

77

console.log(`Stopping with timeout: ${timeout}`);

78

// Cleanup logic here

79

});

80

81

// Send keep-alive if needed

82

this.keepAlive(5000);

83

84

// Emit events

85

this.emit("progress", { completed: 0.5 });

86

87

return input.map(item => ({ ...item, processed: true }));

88

}

89

```

90

91

### Lifecycle Management

92

93

Handler registration and execution for sequence lifecycle events.

94

95

```typescript { .api }

96

/**

97

* Add handler for kill requests (immediate termination)

98

* @param handler - Function to execute on kill

99

* @returns this for method chaining

100

*/

101

addKillHandler(handler: KillHandler): this;

102

103

/**

104

* Execute all registered kill handlers

105

*/

106

killHandler(): void;

107

108

/**

109

* Add handler for stop requests (graceful termination)

110

* @param handler - Function to execute on stop with timeout and keepalive options

111

* @returns this for method chaining

112

*/

113

addStopHandler(handler: StopHandler): this;

114

115

/**

116

* Execute all registered stop handlers

117

* @param timeout - Timeout in milliseconds for graceful stop

118

* @param canCallKeepalive - Whether keepalive can be called during stop

119

*/

120

stopHandler(timeout: number, canCallKeepalive: boolean): Promise<void>;

121

```

122

123

### Health Monitoring

124

125

Health monitoring and status reporting functionality.

126

127

```typescript { .api }

128

/**

129

* Add handler for health monitoring checks

130

* @param handler - Function that returns health status

131

* @returns this for method chaining

132

*/

133

addMonitoringHandler(handler: MonitoringHandler): this;

134

135

/**

136

* Execute all monitoring handlers and aggregate health status

137

* @param initialMessage - Initial health message (default: { healthy: true })

138

* @returns Promise resolving to aggregated health status

139

*/

140

monitor(initialMessage?: MonitoringMessageFromRunnerData): Promise<MonitoringMessageFromRunnerData>;

141

```

142

143

### Sequence Control

144

145

Methods for controlling sequence execution and communicating with the host.

146

147

```typescript { .api }

148

/**

149

* Send keep-alive message to extend sequence lifetime

150

* @param milliseconds - Keep-alive duration in milliseconds (default: 0)

151

* @returns this for method chaining

152

*/

153

keepAlive(milliseconds?: number): this;

154

155

/**

156

* End sequence execution normally

157

* @returns this for method chaining

158

*/

159

end(): this;

160

161

/**

162

* Destroy sequence with error

163

* @param error - Optional error to report

164

* @returns this for method chaining

165

*/

166

destroy(error?: AppError): this;

167

```

168

169

### Event Handling

170

171

Event emission and subscription for sequence communication.

172

173

```typescript { .api }

174

/**

175

* Subscribe to events from the host or other sequences

176

* @param eventName - Name of the event to listen for

177

* @param handler - Function to handle the event

178

* @returns this for method chaining

179

*/

180

on(eventName: string, handler: (message?: any) => void): this;

181

182

/**

183

* Emit event to the host

184

* @param eventName - Name of the event

185

* @param message - Optional message data

186

* @returns this for method chaining

187

*/

188

emit(eventName: string, message?: any): this;

189

```

190

191

### Function Description

192

193

Metadata management for sequence functions.

194

195

```typescript { .api }

196

/**

197

* Describe the sequence function with metadata

198

* @param definition - Function definition with mode, name, and other properties

199

* @returns this for method chaining

200

*/

201

describe(definition: FunctionDefinition): this;

202

```

203

204

### State Management

205

206

State persistence functionality (placeholder implementation).

207

208

```typescript { .api }

209

/**

210

* Save sequence state (not currently implemented)

211

* @param state - State to save

212

* @returns this for method chaining

213

*/

214

save(state: State): this;

215

```

216

217

**Usage Example:**

218

219

```typescript

220

export default function(this: RunnerAppContext<any, any>, input: DataStream) {

221

// Describe the function

222

this.describe({

223

mode: "stream",

224

name: "data-processor",

225

description: "Processes incoming data stream"

226

});

227

228

// Add monitoring

229

this.addMonitoringHandler(async (message) => {

230

const memUsage = process.memoryUsage();

231

return {

232

healthy: memUsage.heapUsed < 100 * 1024 * 1024, // 100MB limit

233

memoryUsage: memUsage

234

};

235

});

236

237

// Handle graceful stop

238

let processing = true;

239

this.addStopHandler(async (timeout, canKeepAlive) => {

240

processing = false;

241

if (canKeepAlive) {

242

this.keepAlive(timeout);

243

}

244

});

245

246

return input

247

.filter(() => processing)

248

.map(item => {

249

this.emit("item-processed", { id: item.id });

250

return { ...item, timestamp: Date.now() };

251

});

252

}

253

```

254

255

## Supporting Types

256

257

```typescript { .api }

258

interface AppContext<AppConfigType extends AppConfig, State extends any> {

259

config: AppConfigType;

260

logger: IObjectLogger;

261

hub: HostClient;

262

space: ManagerClient;

263

instanceId: string;

264

definition: FunctionDefinition;

265

266

addKillHandler(handler: KillHandler): this;

267

addStopHandler(handler: StopHandler): this;

268

addMonitoringHandler(handler: MonitoringHandler): this;

269

keepAlive(milliseconds?: number): this;

270

end(): this;

271

destroy(error?: AppError): this;

272

on(eventName: string, handler: (message?: any) => void): this;

273

emit(eventName: string, message?: any): this;

274

describe(definition: FunctionDefinition): this;

275

save(state: State): this;

276

}

277

278

interface AppError {

279

message: string;

280

code?: string;

281

stack?: string;

282

}

283

284

type AppErrorConstructor = new (message: string) => AppError;

285

286

interface HostClient {

287

// API client for Transform Hub operations

288

[key: string]: any;

289

}

290

291

interface ManagerClient {

292

// API client for space/manager operations

293

[key: string]: any;

294

}

295

```