@kinotic-ai/core 5.0.0-beta.12 → 5.0.0-beta.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -109,6 +109,7 @@ __export(exports_src, {
109
109
  ChainedCredentialsResolver: () => ChainedCredentialsResolver,
110
110
  BearerCredentialsResolver: () => BearerCredentialsResolver,
111
111
  BasicCredentialsResolver: () => BasicCredentialsResolver,
112
+ AuthorizationException: () => AuthorizationException,
112
113
  AbstractIterablePage: () => AbstractIterablePage
113
114
  });
114
115
  module.exports = __toCommonJS(exports_src);
@@ -137,6 +138,7 @@ var EventConstants;
137
138
  EventConstants2["CONTENT_TYPE_HEADER"] = "content-type";
138
139
  EventConstants2["CONTENT_LENGTH_HEADER"] = "content-length";
139
140
  EventConstants2["REPLY_TO_HEADER"] = "reply-to";
141
+ EventConstants2["SENDER_HEADER"] = "sender";
140
142
  EventConstants2["CONNECTED_INFO_HEADER"] = "connected-info";
141
143
  EventConstants2["SESSION_KEEP_ALIVE_HEADER"] = "session-keep-alive";
142
144
  EventConstants2["CORRELATION_ID_HEADER"] = "__correlation-id";
@@ -238,7 +240,7 @@ var SESSION_CHECK_PATH = "/api/auth/me";
238
240
  class StompConnectionManager {
239
241
  lastWebsocketError = null;
240
242
  maxConnectionAttemptsReached = false;
241
- connectionLostHandler = null;
243
+ connectionEndedHandler = null;
242
244
  rxStomp = new import_rx_stomp.RxStomp;
243
245
  activation = null;
244
246
  teardown = null;
@@ -247,8 +249,7 @@ class StompConnectionManager {
247
249
  MAX_RECONNECT_DELAY = 120000;
248
250
  connectionAttempts = 0;
249
251
  debugLogger = import_debug2.default("kinotic:stomp");
250
- fatalErrorsSubject = new import_rxjs.Subject;
251
- _fatalErrors = this.fatalErrorsSubject.asObservable();
252
+ connectionEstablishedSubject = new import_rxjs.Subject;
252
253
  initialConnectionSuccessful = false;
253
254
  rxStompHasConnected = false;
254
255
  _replyToCri = null;
@@ -261,8 +262,8 @@ class StompConnectionManager {
261
262
  get connected() {
262
263
  return this.activation !== null && this.rxStomp.connected();
263
264
  }
264
- get fatalErrors() {
265
- return this._fatalErrors;
265
+ get connectionEstablished() {
266
+ return this.connectionEstablishedSubject.asObservable();
266
267
  }
267
268
  async activate(options) {
268
269
  if (!options?.server?.host) {
@@ -340,12 +341,12 @@ class StompConnectionManager {
340
341
  this.lastWebsocketError = value;
341
342
  if (!activation.ended && options?.maxConnectionAttempts && this.connectionAttempts >= options.maxConnectionAttempts) {
342
343
  this.maxConnectionAttemptsReached = true;
343
- await this.signalFatal(activation, new Error("Max number of reconnection attempts reached", { cause: value ?? undefined }));
344
+ await this.failConnection(activation, new Error("Max number of reconnection attempts reached", { cause: value ?? undefined }));
344
345
  }
345
346
  }));
346
347
  activation.own(this.rxStomp.stompErrors$.subscribe(async (frame) => {
347
348
  const stompError = new Error(frame.headers["message"], { cause: frame });
348
- await this.signalFatal(activation, new Error("STOMP connection error", { cause: stompError }));
349
+ await this.failConnection(activation, new Error("STOMP connection error", { cause: stompError }));
349
350
  }));
350
351
  activation.own(this.rxStomp.connected$.subscribe(() => {
351
352
  activation.established();
@@ -358,16 +359,14 @@ class StompConnectionManager {
358
359
  const connectedInfoJson = value["connected-info" /* CONNECTED_INFO_HEADER */];
359
360
  if (connectedInfoJson == null) {
360
361
  if (!this.initialConnectionSuccessful) {
361
- activation.failIfPending(new Error("Server did not return proper data for successful login"));
362
- await this.deactivate();
362
+ await this.deactivate(undefined, new Error("Server did not return proper data for successful login"));
363
363
  }
364
364
  return;
365
365
  }
366
366
  const connectedInfo = JSON.parse(connectedInfoJson);
367
367
  if (connectedInfo.replyToId == null) {
368
368
  if (!this.initialConnectionSuccessful) {
369
- activation.failIfPending(new Error("Server did not return a replyToId for successful login"));
370
- await this.deactivate();
369
+ await this.deactivate(undefined, new Error("Server did not return a replyToId for successful login"));
371
370
  }
372
371
  return;
373
372
  }
@@ -376,11 +375,12 @@ class StompConnectionManager {
376
375
  if (!this.initialConnectionSuccessful) {
377
376
  resolve(connectedInfo);
378
377
  }
378
+ this.connectionEstablishedSubject.next(connectedInfo);
379
379
  }));
380
380
  let previousState = this.rxStomp.connectionState$.getValue();
381
381
  activation.own(this.rxStomp.connectionState$.subscribe((state) => {
382
382
  if (state === import_rx_stomp.RxStompState.CLOSED && previousState === import_rx_stomp.RxStompState.OPEN && this.activation === activation) {
383
- this.connectionLostHandler?.();
383
+ this.connectionEndedHandler?.(null);
384
384
  }
385
385
  previousState = state;
386
386
  }));
@@ -397,7 +397,7 @@ class StompConnectionManager {
397
397
  try {
398
398
  const res = await fetch(sessionCheckUrl, { credentials: "include" });
399
399
  if (res.status === 401) {
400
- await this.signalFatal(activation, new Error("Authentication required"));
400
+ await this.failConnection(activation, new Error("Authentication required"));
401
401
  return;
402
402
  }
403
403
  } catch (e) {
@@ -408,7 +408,7 @@ class StompConnectionManager {
408
408
  this.connectionAttempts++;
409
409
  if (this.connectionAttempts > options.maxConnectionAttempts) {
410
410
  this.maxConnectionAttemptsReached = true;
411
- await this.signalFatal(activation, new Error("Max number of reconnection attempts reached", { cause: this.lastWebsocketError ?? undefined }));
411
+ await this.failConnection(activation, new Error("Max number of reconnection attempts reached", { cause: this.lastWebsocketError ?? undefined }));
412
412
  return;
413
413
  } else {
414
414
  await this.connectionJitterDelay(activation);
@@ -423,19 +423,19 @@ class StompConnectionManager {
423
423
  try {
424
424
  activation.preparedSocket = await userWebSocketFactory();
425
425
  } catch (e) {
426
- await this.signalFatal(activation, new Error("WebSocket factory failed", { cause: e }));
426
+ await this.failConnection(activation, new Error("WebSocket factory failed", { cause: e }));
427
427
  }
428
428
  } else if (headerAuth) {
429
429
  try {
430
430
  const resolved = await credentialsResolver.resolve(server);
431
431
  if (resolved?.authHeaders == null) {
432
- await this.signalFatal(activation, new Error("Credentials resolver no longer supplies auth headers: " + credentialsResolver.name));
432
+ await this.failConnection(activation, new Error("Credentials resolver no longer supplies auth headers: " + credentialsResolver.name));
433
433
  } else {
434
434
  const WS = WebSocket;
435
435
  activation.preparedSocket = new WS(url, { headers: resolved.authHeaders });
436
436
  }
437
437
  } catch (e) {
438
- await this.signalFatal(activation, new Error("Credential resolution failed", { cause: e }));
438
+ await this.failConnection(activation, new Error("Credential resolution failed", { cause: e }));
439
439
  }
440
440
  }
441
441
  if (activation.ended && activation.preparedSocket) {
@@ -443,7 +443,7 @@ class StompConnectionManager {
443
443
  activation.preparedSocket = null;
444
444
  }
445
445
  }
446
- deactivate(force) {
446
+ deactivate(force, reason = null) {
447
447
  const activation = this.activation;
448
448
  let ret;
449
449
  if (activation) {
@@ -451,17 +451,17 @@ class StompConnectionManager {
451
451
  activation.end();
452
452
  const wasOpen = this.rxStomp.connected();
453
453
  this._replyToCri = null;
454
- activation.failIfPending(new Error("Deactivated before the connection was established"));
454
+ activation.failIfPending(reason ?? new Error("Deactivated before the connection was established"));
455
455
  activation.preparedSocket?.close();
456
456
  activation.preparedSocket = null;
457
457
  const teardown = this.rxStomp.deactivate({ force }).then(() => activation.attempt ?? undefined).finally(() => {
458
458
  activation.unsubscribeAll();
459
459
  this.teardown = null;
460
- if (wasOpen) {
461
- this.connectionLostHandler?.();
462
- }
463
460
  });
464
461
  this.teardown = teardown;
462
+ if (wasOpen || reason !== null) {
463
+ this.connectionEndedHandler?.(reason);
464
+ }
465
465
  ret = teardown;
466
466
  } else {
467
467
  ret = this.teardown ?? Promise.resolve();
@@ -475,12 +475,10 @@ class StompConnectionManager {
475
475
  await activation.delay(randomJitter);
476
476
  }
477
477
  }
478
- async signalFatal(activation, err) {
478
+ async failConnection(activation, err) {
479
479
  if (!activation.ended) {
480
- this.debugLogger("Fatal error, deactivating connection: %O", err);
481
- activation.failIfPending(err);
482
- await this.deactivate();
483
- this.fatalErrorsSubject.next(err);
480
+ this.debugLogger("Connection failed, ending it: %O", err);
481
+ await this.deactivate(undefined, err);
484
482
  }
485
483
  }
486
484
  }
@@ -575,20 +573,22 @@ class EventBus {
575
573
  requestRepliesSubscription = null;
576
574
  activeCorrelationIds = new Set;
577
575
  recentlyReaped = new Set;
578
- connectionLostSubject = new import_rxjs2.Subject;
576
+ connectionEndedSubject = new import_rxjs2.Subject;
579
577
  static REAP_DEBOUNCE_MS = 5000;
580
578
  constructor() {
581
- this.stompConnectionManager.fatalErrors.subscribe(() => this.serverInfo = null);
582
- this.stompConnectionManager.connectionLostHandler = () => {
579
+ this.stompConnectionManager.connectionEndedHandler = (reason) => {
583
580
  this.resetRequestReplies("Connection lost");
584
- this.connectionLostSubject.next();
581
+ if (!this.stompConnectionManager.active) {
582
+ this.serverInfo = null;
583
+ }
584
+ this.connectionEndedSubject.next(reason);
585
585
  };
586
586
  }
587
- get fatalErrors() {
588
- return this.stompConnectionManager.fatalErrors;
587
+ get connectionEnded() {
588
+ return this.connectionEndedSubject.asObservable();
589
589
  }
590
- get connectionLost() {
591
- return this.connectionLostSubject.asObservable();
590
+ get connectionEstablished() {
591
+ return this.stompConnectionManager.connectionEstablished;
592
592
  }
593
593
  isConnectionActive() {
594
594
  return this.stompConnectionManager.active;
@@ -1297,7 +1297,7 @@ var import_api2 = __toESM(require("@opentelemetry/api"));
1297
1297
  // packages/core/package.json
1298
1298
  var package_default = {
1299
1299
  name: "@kinotic-ai/core",
1300
- version: "5.0.0-beta.12",
1300
+ version: "5.0.0-beta.17",
1301
1301
  type: "module",
1302
1302
  files: [
1303
1303
  "dist"
@@ -1392,7 +1392,7 @@ class ServiceInvocationSupervisor {
1392
1392
  methodSubscription = null;
1393
1393
  unscopedSubscription = null;
1394
1394
  activeStreams = new Map;
1395
- connectionLostSubscription = null;
1395
+ connectionEndedSubscription = null;
1396
1396
  connectionGeneration = 0;
1397
1397
  methodMap;
1398
1398
  scopeOptionalMethods;
@@ -1442,7 +1442,7 @@ class ServiceInvocationSupervisor {
1442
1442
  this.unscopedSubscription = this.subscribeAt(unscopedBase);
1443
1443
  this.log.info(`ServiceInvocationSupervisor also listening for ScopeOptional methods at ${unscopedBase}`);
1444
1444
  }
1445
- this.connectionLostSubscription = this._eventBus.connectionLost.subscribe(() => {
1445
+ this.connectionEndedSubscription = this._eventBus.connectionEnded.subscribe(() => {
1446
1446
  this.connectionGeneration++;
1447
1447
  for (const stream of this.activeStreams.values()) {
1448
1448
  stream.subscription.unsubscribe();
@@ -1473,8 +1473,8 @@ class ServiceInvocationSupervisor {
1473
1473
  this.methodSubscription = null;
1474
1474
  this.unscopedSubscription?.unsubscribe();
1475
1475
  this.unscopedSubscription = null;
1476
- this.connectionLostSubscription?.unsubscribe();
1477
- this.connectionLostSubscription = null;
1476
+ this.connectionEndedSubscription?.unsubscribe();
1477
+ this.connectionEndedSubscription = null;
1478
1478
  const serviceName = this.serviceIdentifier.qualifiedName();
1479
1479
  for (const stream of this.activeStreams.values()) {
1480
1480
  this.handleException(stream.request, new Error(`Service ${serviceName} stopped while producing the stream`));
@@ -1549,6 +1549,10 @@ class ServiceInvocationSupervisor {
1549
1549
  const args = this.argumentResolver.resolveArguments(event);
1550
1550
  const injectContext = receivesContext(this.serviceInstance, methodName);
1551
1551
  let serviceContext = {};
1552
+ const sender = event.getHeader("sender" /* SENDER_HEADER */);
1553
+ if (sender) {
1554
+ serviceContext.participant = JSON.parse(sender);
1555
+ }
1552
1556
  const interceptor = this.interceptorProvider();
1553
1557
  if (interceptor) {
1554
1558
  try {
@@ -2129,6 +2133,13 @@ class Order {
2129
2133
  class Sort {
2130
2134
  orders = [];
2131
2135
  }
2136
+ // packages/core/src/api/security/AuthorizationException.ts
2137
+ class AuthorizationException extends Error {
2138
+ constructor(message = "Access denied") {
2139
+ super(message);
2140
+ this.name = "AuthorizationException";
2141
+ }
2142
+ }
2132
2143
  // packages/core/src/api/security/ConnectedInfo.ts
2133
2144
  class ConnectedInfo {
2134
2145
  replyToId;
package/dist/index.d.cts CHANGED
@@ -222,17 +222,20 @@ interface IEvent {
222
222
  */
223
223
  interface IEventBus {
224
224
  /**
225
- * Any errors emitted by this observable will be fatal and the connection will be closed.
226
- * You will need to resolve the problem and reconnect.
225
+ * Emits when the connection ends: an established connection drops before any reconnect, a failure
226
+ * closes it, or {@link disconnect} is called. It carries the failure that ended the connection, or
227
+ * null when nothing failed. The server releases everything it held for the connection at that moment:
228
+ * every request made on it is failed to its caller, and every invocation it was serving is failed to
229
+ * its requester. An end the client reconnects from leaves {@link IEventBus#isConnectionActive} true;
230
+ * one that needs a fresh {@link IEventBus#connect} leaves it false.
227
231
  */
228
- fatalErrors: Observable<Error>;
232
+ connectionEnded: Observable<Error | null>;
229
233
  /**
230
- * Emits when the connection ends: an established connection drops before any reconnect, a fatal error
231
- * closes it, or {@link disconnect} is called. The server releases everything it held for the connection
232
- * at that moment: every request made on it is failed to its caller, and every invocation it was serving
233
- * is failed to its requester.
234
+ * Emits each time a connection is established: the first {@link connect}, and every reconnect the
235
+ * client makes after one ends. It carries the {@link ConnectedInfo} the server issued for that
236
+ * connection, which names the session the requests made on it belong to.
234
237
  */
235
- connectionLost: Observable<void>;
238
+ connectionEstablished: Observable<ConnectedInfo>;
236
239
  /**
237
240
  * The {@link ServerInfo} used when connecting, if connected or null
238
241
  */
@@ -313,6 +316,12 @@ declare enum EventConstants {
313
316
  CONTENT_LENGTH_HEADER = "content-length",
314
317
  REPLY_TO_HEADER = "reply-to",
315
318
  /**
319
+ * The participant that sent the event, as JSON. The gateway writes it on every event it delivers to a
320
+ * client, from the participant authenticated on the connection the event came from, and drops any a
321
+ * client supplies; an event that originated inside the platform with no participant bound carries none.
322
+ */
323
+ SENDER_HEADER = "sender",
324
+ /**
316
325
  * Header provided by the server on connection to provide the {@link ConnectedInfo} as a JSON string
317
326
  */
318
327
  CONNECTED_INFO_HEADER = "connected-info",
@@ -374,16 +383,25 @@ declare enum EventConstants {
374
383
  TRACESTATE_HEADER = "tracestate"
375
384
  }
376
385
  /**
377
- * Interface for the service context, extendable by users for type-safe context data.
386
+ * The request context a {@link Context} method receives as its final parameter: the calling participant,
387
+ * plus whatever the registered {@link ContextInterceptor} adds. Extend it for type-safe context data.
378
388
  *
379
389
  * @author Navid Mitchell 🤝Grok
380
390
  * @since 3/25/2025
381
391
  */
382
392
  interface ServiceContext {
393
+ /**
394
+ * The participant that invoked the service method, as authenticated by the gateway on the calling
395
+ * connection. Absent when the invocation originated inside the platform with no participant bound,
396
+ * such as a scheduled job.
397
+ */
398
+ participant?: Participant;
383
399
  [key: string]: any;
384
400
  }
385
401
  /**
386
402
  * Interface for interceptors that create or modify the ServiceContext before service method invocation.
403
+ * The context handed in already carries the calling participant; the context returned is the one the
404
+ * method receives.
387
405
  *
388
406
  * @author Navid Mitchell 🤝Grok
389
407
  * @since 3/25/2025
@@ -1262,11 +1280,11 @@ declare class EventBus implements IEventBus {
1262
1280
  private requestRepliesSubscription;
1263
1281
  private readonly activeCorrelationIds;
1264
1282
  private readonly recentlyReaped;
1265
- private readonly connectionLostSubject;
1283
+ private readonly connectionEndedSubject;
1266
1284
  private static readonly REAP_DEBOUNCE_MS;
1267
1285
  constructor();
1268
- get fatalErrors(): Observable3<Error>;
1269
- get connectionLost(): Observable3<void>;
1286
+ get connectionEnded(): Observable3<Error | null>;
1287
+ get connectionEstablished(): Observable3<ConnectedInfo>;
1270
1288
  isConnectionActive(): boolean;
1271
1289
  isConnected(): boolean;
1272
1290
  connect(options: ConnectOptions): Promise<ConnectedInfo>;
@@ -1333,6 +1351,14 @@ declare class RpcError extends Error {
1333
1351
  static fromEvent(reply: IEvent): RpcError;
1334
1352
  }
1335
1353
  /**
1354
+ * Thrown when the calling participant is not permitted to do what it asked. A service that throws it
1355
+ * fails the invocation with an error reply named {@code AuthorizationException}, the name a Java
1356
+ * service's refusal carries, so a caller reads both the same way.
1357
+ */
1358
+ declare class AuthorizationException extends Error {
1359
+ constructor(message?: string);
1360
+ }
1361
+ /**
1336
1362
  * Kinotic client credentials: a clientId/clientSecret pair presented as upgrade headers —
1337
1363
  * a user's email and password, or a machine identity's id and provisioned secret. Scope is
1338
1364
  * structural, determined by which ids are given: neither → SYSTEM, organizationId only →
@@ -1400,4 +1426,4 @@ declare class ParticipantConstants {
1400
1426
  /** The clientId TestSecurityService (clienttest profile) maps to the ANONYMOUS role in core package tests. */
1401
1427
  static readonly CLI_PARTICIPANT_ID: string;
1402
1428
  }
1403
- export { validateZone, validateLabel, scopeOptionalMethodNames, receivesContext, isAdvertised, createCRI, buildServerUrl, buildBrokerUrl, Zone, WebSocketFactory, Version, TextEventFactory, Sort, SessionKeepAliveMode, SessionCredentialsResolver, ServiceRegistry, ServiceIdentifier, ServiceContext, ServerInfo, ScopeOptional, Scope, RpcError, ResolvedCredentials, Publish, ParticipantConstants, Participant, Pageable, Page, Order, OffsetPageable, NullHandling, KinoticSingleton, KinoticPlugin, Kinotic, JsonEventFactory, IterablePage, Identifiable, IWebSocket, IServiceRegistry, IServiceProxy, IParticipant, IKinotic, IEventFactory, IEventBus, IEvent, IEditableDataSource, IDataSource, ICrudServiceProxyFactory, ICrudServiceProxy, FunctionalIterablePage, EventConstants, EventBus, Event, EnvCredentialsResolver, Direction, DefaultCRI, DataSourceUtils, CursorPageable, CrudServiceProxyFactory, CrudServiceProxy, CredentialsResolver, ContextInterceptor, Context, ConnectedInfo, ConnectOptions, ChainedCredentialsResolver, CRI, BearerCredentialsResolver, BasicCredentialsResolver, AbstractIterablePage };
1429
+ export { validateZone, validateLabel, scopeOptionalMethodNames, receivesContext, isAdvertised, createCRI, buildServerUrl, buildBrokerUrl, Zone, WebSocketFactory, Version, TextEventFactory, Sort, SessionKeepAliveMode, SessionCredentialsResolver, ServiceRegistry, ServiceIdentifier, ServiceContext, ServerInfo, ScopeOptional, Scope, RpcError, ResolvedCredentials, Publish, ParticipantConstants, Participant, Pageable, Page, Order, OffsetPageable, NullHandling, KinoticSingleton, KinoticPlugin, Kinotic, JsonEventFactory, IterablePage, Identifiable, IWebSocket, IServiceRegistry, IServiceProxy, IParticipant, IKinotic, IEventFactory, IEventBus, IEvent, IEditableDataSource, IDataSource, ICrudServiceProxyFactory, ICrudServiceProxy, FunctionalIterablePage, EventConstants, EventBus, Event, EnvCredentialsResolver, Direction, DefaultCRI, DataSourceUtils, CursorPageable, CrudServiceProxyFactory, CrudServiceProxy, CredentialsResolver, ContextInterceptor, Context, ConnectedInfo, ConnectOptions, ChainedCredentialsResolver, CRI, BearerCredentialsResolver, BasicCredentialsResolver, AuthorizationException, AbstractIterablePage };
package/dist/index.d.ts CHANGED
@@ -222,17 +222,20 @@ interface IEvent {
222
222
  */
223
223
  interface IEventBus {
224
224
  /**
225
- * Any errors emitted by this observable will be fatal and the connection will be closed.
226
- * You will need to resolve the problem and reconnect.
225
+ * Emits when the connection ends: an established connection drops before any reconnect, a failure
226
+ * closes it, or {@link disconnect} is called. It carries the failure that ended the connection, or
227
+ * null when nothing failed. The server releases everything it held for the connection at that moment:
228
+ * every request made on it is failed to its caller, and every invocation it was serving is failed to
229
+ * its requester. An end the client reconnects from leaves {@link IEventBus#isConnectionActive} true;
230
+ * one that needs a fresh {@link IEventBus#connect} leaves it false.
227
231
  */
228
- fatalErrors: Observable<Error>;
232
+ connectionEnded: Observable<Error | null>;
229
233
  /**
230
- * Emits when the connection ends: an established connection drops before any reconnect, a fatal error
231
- * closes it, or {@link disconnect} is called. The server releases everything it held for the connection
232
- * at that moment: every request made on it is failed to its caller, and every invocation it was serving
233
- * is failed to its requester.
234
+ * Emits each time a connection is established: the first {@link connect}, and every reconnect the
235
+ * client makes after one ends. It carries the {@link ConnectedInfo} the server issued for that
236
+ * connection, which names the session the requests made on it belong to.
234
237
  */
235
- connectionLost: Observable<void>;
238
+ connectionEstablished: Observable<ConnectedInfo>;
236
239
  /**
237
240
  * The {@link ServerInfo} used when connecting, if connected or null
238
241
  */
@@ -313,6 +316,12 @@ declare enum EventConstants {
313
316
  CONTENT_LENGTH_HEADER = "content-length",
314
317
  REPLY_TO_HEADER = "reply-to",
315
318
  /**
319
+ * The participant that sent the event, as JSON. The gateway writes it on every event it delivers to a
320
+ * client, from the participant authenticated on the connection the event came from, and drops any a
321
+ * client supplies; an event that originated inside the platform with no participant bound carries none.
322
+ */
323
+ SENDER_HEADER = "sender",
324
+ /**
316
325
  * Header provided by the server on connection to provide the {@link ConnectedInfo} as a JSON string
317
326
  */
318
327
  CONNECTED_INFO_HEADER = "connected-info",
@@ -374,16 +383,25 @@ declare enum EventConstants {
374
383
  TRACESTATE_HEADER = "tracestate"
375
384
  }
376
385
  /**
377
- * Interface for the service context, extendable by users for type-safe context data.
386
+ * The request context a {@link Context} method receives as its final parameter: the calling participant,
387
+ * plus whatever the registered {@link ContextInterceptor} adds. Extend it for type-safe context data.
378
388
  *
379
389
  * @author Navid Mitchell 🤝Grok
380
390
  * @since 3/25/2025
381
391
  */
382
392
  interface ServiceContext {
393
+ /**
394
+ * The participant that invoked the service method, as authenticated by the gateway on the calling
395
+ * connection. Absent when the invocation originated inside the platform with no participant bound,
396
+ * such as a scheduled job.
397
+ */
398
+ participant?: Participant;
383
399
  [key: string]: any;
384
400
  }
385
401
  /**
386
402
  * Interface for interceptors that create or modify the ServiceContext before service method invocation.
403
+ * The context handed in already carries the calling participant; the context returned is the one the
404
+ * method receives.
387
405
  *
388
406
  * @author Navid Mitchell 🤝Grok
389
407
  * @since 3/25/2025
@@ -1262,11 +1280,11 @@ declare class EventBus implements IEventBus {
1262
1280
  private requestRepliesSubscription;
1263
1281
  private readonly activeCorrelationIds;
1264
1282
  private readonly recentlyReaped;
1265
- private readonly connectionLostSubject;
1283
+ private readonly connectionEndedSubject;
1266
1284
  private static readonly REAP_DEBOUNCE_MS;
1267
1285
  constructor();
1268
- get fatalErrors(): Observable3<Error>;
1269
- get connectionLost(): Observable3<void>;
1286
+ get connectionEnded(): Observable3<Error | null>;
1287
+ get connectionEstablished(): Observable3<ConnectedInfo>;
1270
1288
  isConnectionActive(): boolean;
1271
1289
  isConnected(): boolean;
1272
1290
  connect(options: ConnectOptions): Promise<ConnectedInfo>;
@@ -1333,6 +1351,14 @@ declare class RpcError extends Error {
1333
1351
  static fromEvent(reply: IEvent): RpcError;
1334
1352
  }
1335
1353
  /**
1354
+ * Thrown when the calling participant is not permitted to do what it asked. A service that throws it
1355
+ * fails the invocation with an error reply named {@code AuthorizationException}, the name a Java
1356
+ * service's refusal carries, so a caller reads both the same way.
1357
+ */
1358
+ declare class AuthorizationException extends Error {
1359
+ constructor(message?: string);
1360
+ }
1361
+ /**
1336
1362
  * Kinotic client credentials: a clientId/clientSecret pair presented as upgrade headers —
1337
1363
  * a user's email and password, or a machine identity's id and provisioned secret. Scope is
1338
1364
  * structural, determined by which ids are given: neither → SYSTEM, organizationId only →
@@ -1400,4 +1426,4 @@ declare class ParticipantConstants {
1400
1426
  /** The clientId TestSecurityService (clienttest profile) maps to the ANONYMOUS role in core package tests. */
1401
1427
  static readonly CLI_PARTICIPANT_ID: string;
1402
1428
  }
1403
- export { validateZone, validateLabel, scopeOptionalMethodNames, receivesContext, isAdvertised, createCRI, buildServerUrl, buildBrokerUrl, Zone, WebSocketFactory, Version, TextEventFactory, Sort, SessionKeepAliveMode, SessionCredentialsResolver, ServiceRegistry, ServiceIdentifier, ServiceContext, ServerInfo, ScopeOptional, Scope, RpcError, ResolvedCredentials, Publish, ParticipantConstants, Participant, Pageable, Page, Order, OffsetPageable, NullHandling, KinoticSingleton, KinoticPlugin, Kinotic, JsonEventFactory, IterablePage, Identifiable, IWebSocket, IServiceRegistry, IServiceProxy, IParticipant, IKinotic, IEventFactory, IEventBus, IEvent, IEditableDataSource, IDataSource, ICrudServiceProxyFactory, ICrudServiceProxy, FunctionalIterablePage, EventConstants, EventBus, Event, EnvCredentialsResolver, Direction, DefaultCRI, DataSourceUtils, CursorPageable, CrudServiceProxyFactory, CrudServiceProxy, CredentialsResolver, ContextInterceptor, Context, ConnectedInfo, ConnectOptions, ChainedCredentialsResolver, CRI, BearerCredentialsResolver, BasicCredentialsResolver, AbstractIterablePage };
1429
+ export { validateZone, validateLabel, scopeOptionalMethodNames, receivesContext, isAdvertised, createCRI, buildServerUrl, buildBrokerUrl, Zone, WebSocketFactory, Version, TextEventFactory, Sort, SessionKeepAliveMode, SessionCredentialsResolver, ServiceRegistry, ServiceIdentifier, ServiceContext, ServerInfo, ScopeOptional, Scope, RpcError, ResolvedCredentials, Publish, ParticipantConstants, Participant, Pageable, Page, Order, OffsetPageable, NullHandling, KinoticSingleton, KinoticPlugin, Kinotic, JsonEventFactory, IterablePage, Identifiable, IWebSocket, IServiceRegistry, IServiceProxy, IParticipant, IKinotic, IEventFactory, IEventBus, IEvent, IEditableDataSource, IDataSource, ICrudServiceProxyFactory, ICrudServiceProxy, FunctionalIterablePage, EventConstants, EventBus, Event, EnvCredentialsResolver, Direction, DefaultCRI, DataSourceUtils, CursorPageable, CrudServiceProxyFactory, CrudServiceProxy, CredentialsResolver, ContextInterceptor, Context, ConnectedInfo, ConnectOptions, ChainedCredentialsResolver, CRI, BearerCredentialsResolver, BasicCredentialsResolver, AuthorizationException, AbstractIterablePage };
package/dist/index.js CHANGED
@@ -22,6 +22,7 @@ var EventConstants;
22
22
  EventConstants2["CONTENT_TYPE_HEADER"] = "content-type";
23
23
  EventConstants2["CONTENT_LENGTH_HEADER"] = "content-length";
24
24
  EventConstants2["REPLY_TO_HEADER"] = "reply-to";
25
+ EventConstants2["SENDER_HEADER"] = "sender";
25
26
  EventConstants2["CONNECTED_INFO_HEADER"] = "connected-info";
26
27
  EventConstants2["SESSION_KEEP_ALIVE_HEADER"] = "session-keep-alive";
27
28
  EventConstants2["CORRELATION_ID_HEADER"] = "__correlation-id";
@@ -123,7 +124,7 @@ var SESSION_CHECK_PATH = "/api/auth/me";
123
124
  class StompConnectionManager {
124
125
  lastWebsocketError = null;
125
126
  maxConnectionAttemptsReached = false;
126
- connectionLostHandler = null;
127
+ connectionEndedHandler = null;
127
128
  rxStomp = new RxStomp;
128
129
  activation = null;
129
130
  teardown = null;
@@ -132,8 +133,7 @@ class StompConnectionManager {
132
133
  MAX_RECONNECT_DELAY = 120000;
133
134
  connectionAttempts = 0;
134
135
  debugLogger = debug2("kinotic:stomp");
135
- fatalErrorsSubject = new Subject;
136
- _fatalErrors = this.fatalErrorsSubject.asObservable();
136
+ connectionEstablishedSubject = new Subject;
137
137
  initialConnectionSuccessful = false;
138
138
  rxStompHasConnected = false;
139
139
  _replyToCri = null;
@@ -146,8 +146,8 @@ class StompConnectionManager {
146
146
  get connected() {
147
147
  return this.activation !== null && this.rxStomp.connected();
148
148
  }
149
- get fatalErrors() {
150
- return this._fatalErrors;
149
+ get connectionEstablished() {
150
+ return this.connectionEstablishedSubject.asObservable();
151
151
  }
152
152
  async activate(options) {
153
153
  if (!options?.server?.host) {
@@ -225,12 +225,12 @@ class StompConnectionManager {
225
225
  this.lastWebsocketError = value;
226
226
  if (!activation.ended && options?.maxConnectionAttempts && this.connectionAttempts >= options.maxConnectionAttempts) {
227
227
  this.maxConnectionAttemptsReached = true;
228
- await this.signalFatal(activation, new Error("Max number of reconnection attempts reached", { cause: value ?? undefined }));
228
+ await this.failConnection(activation, new Error("Max number of reconnection attempts reached", { cause: value ?? undefined }));
229
229
  }
230
230
  }));
231
231
  activation.own(this.rxStomp.stompErrors$.subscribe(async (frame) => {
232
232
  const stompError = new Error(frame.headers["message"], { cause: frame });
233
- await this.signalFatal(activation, new Error("STOMP connection error", { cause: stompError }));
233
+ await this.failConnection(activation, new Error("STOMP connection error", { cause: stompError }));
234
234
  }));
235
235
  activation.own(this.rxStomp.connected$.subscribe(() => {
236
236
  activation.established();
@@ -243,16 +243,14 @@ class StompConnectionManager {
243
243
  const connectedInfoJson = value["connected-info" /* CONNECTED_INFO_HEADER */];
244
244
  if (connectedInfoJson == null) {
245
245
  if (!this.initialConnectionSuccessful) {
246
- activation.failIfPending(new Error("Server did not return proper data for successful login"));
247
- await this.deactivate();
246
+ await this.deactivate(undefined, new Error("Server did not return proper data for successful login"));
248
247
  }
249
248
  return;
250
249
  }
251
250
  const connectedInfo = JSON.parse(connectedInfoJson);
252
251
  if (connectedInfo.replyToId == null) {
253
252
  if (!this.initialConnectionSuccessful) {
254
- activation.failIfPending(new Error("Server did not return a replyToId for successful login"));
255
- await this.deactivate();
253
+ await this.deactivate(undefined, new Error("Server did not return a replyToId for successful login"));
256
254
  }
257
255
  return;
258
256
  }
@@ -261,11 +259,12 @@ class StompConnectionManager {
261
259
  if (!this.initialConnectionSuccessful) {
262
260
  resolve(connectedInfo);
263
261
  }
262
+ this.connectionEstablishedSubject.next(connectedInfo);
264
263
  }));
265
264
  let previousState = this.rxStomp.connectionState$.getValue();
266
265
  activation.own(this.rxStomp.connectionState$.subscribe((state) => {
267
266
  if (state === RxStompState.CLOSED && previousState === RxStompState.OPEN && this.activation === activation) {
268
- this.connectionLostHandler?.();
267
+ this.connectionEndedHandler?.(null);
269
268
  }
270
269
  previousState = state;
271
270
  }));
@@ -282,7 +281,7 @@ class StompConnectionManager {
282
281
  try {
283
282
  const res = await fetch(sessionCheckUrl, { credentials: "include" });
284
283
  if (res.status === 401) {
285
- await this.signalFatal(activation, new Error("Authentication required"));
284
+ await this.failConnection(activation, new Error("Authentication required"));
286
285
  return;
287
286
  }
288
287
  } catch (e) {
@@ -293,7 +292,7 @@ class StompConnectionManager {
293
292
  this.connectionAttempts++;
294
293
  if (this.connectionAttempts > options.maxConnectionAttempts) {
295
294
  this.maxConnectionAttemptsReached = true;
296
- await this.signalFatal(activation, new Error("Max number of reconnection attempts reached", { cause: this.lastWebsocketError ?? undefined }));
295
+ await this.failConnection(activation, new Error("Max number of reconnection attempts reached", { cause: this.lastWebsocketError ?? undefined }));
297
296
  return;
298
297
  } else {
299
298
  await this.connectionJitterDelay(activation);
@@ -308,19 +307,19 @@ class StompConnectionManager {
308
307
  try {
309
308
  activation.preparedSocket = await userWebSocketFactory();
310
309
  } catch (e) {
311
- await this.signalFatal(activation, new Error("WebSocket factory failed", { cause: e }));
310
+ await this.failConnection(activation, new Error("WebSocket factory failed", { cause: e }));
312
311
  }
313
312
  } else if (headerAuth) {
314
313
  try {
315
314
  const resolved = await credentialsResolver.resolve(server);
316
315
  if (resolved?.authHeaders == null) {
317
- await this.signalFatal(activation, new Error("Credentials resolver no longer supplies auth headers: " + credentialsResolver.name));
316
+ await this.failConnection(activation, new Error("Credentials resolver no longer supplies auth headers: " + credentialsResolver.name));
318
317
  } else {
319
318
  const WS = WebSocket;
320
319
  activation.preparedSocket = new WS(url, { headers: resolved.authHeaders });
321
320
  }
322
321
  } catch (e) {
323
- await this.signalFatal(activation, new Error("Credential resolution failed", { cause: e }));
322
+ await this.failConnection(activation, new Error("Credential resolution failed", { cause: e }));
324
323
  }
325
324
  }
326
325
  if (activation.ended && activation.preparedSocket) {
@@ -328,7 +327,7 @@ class StompConnectionManager {
328
327
  activation.preparedSocket = null;
329
328
  }
330
329
  }
331
- deactivate(force) {
330
+ deactivate(force, reason = null) {
332
331
  const activation = this.activation;
333
332
  let ret;
334
333
  if (activation) {
@@ -336,17 +335,17 @@ class StompConnectionManager {
336
335
  activation.end();
337
336
  const wasOpen = this.rxStomp.connected();
338
337
  this._replyToCri = null;
339
- activation.failIfPending(new Error("Deactivated before the connection was established"));
338
+ activation.failIfPending(reason ?? new Error("Deactivated before the connection was established"));
340
339
  activation.preparedSocket?.close();
341
340
  activation.preparedSocket = null;
342
341
  const teardown = this.rxStomp.deactivate({ force }).then(() => activation.attempt ?? undefined).finally(() => {
343
342
  activation.unsubscribeAll();
344
343
  this.teardown = null;
345
- if (wasOpen) {
346
- this.connectionLostHandler?.();
347
- }
348
344
  });
349
345
  this.teardown = teardown;
346
+ if (wasOpen || reason !== null) {
347
+ this.connectionEndedHandler?.(reason);
348
+ }
350
349
  ret = teardown;
351
350
  } else {
352
351
  ret = this.teardown ?? Promise.resolve();
@@ -360,12 +359,10 @@ class StompConnectionManager {
360
359
  await activation.delay(randomJitter);
361
360
  }
362
361
  }
363
- async signalFatal(activation, err) {
362
+ async failConnection(activation, err) {
364
363
  if (!activation.ended) {
365
- this.debugLogger("Fatal error, deactivating connection: %O", err);
366
- activation.failIfPending(err);
367
- await this.deactivate();
368
- this.fatalErrorsSubject.next(err);
364
+ this.debugLogger("Connection failed, ending it: %O", err);
365
+ await this.deactivate(undefined, err);
369
366
  }
370
367
  }
371
368
  }
@@ -460,20 +457,22 @@ class EventBus {
460
457
  requestRepliesSubscription = null;
461
458
  activeCorrelationIds = new Set;
462
459
  recentlyReaped = new Set;
463
- connectionLostSubject = new Subject2;
460
+ connectionEndedSubject = new Subject2;
464
461
  static REAP_DEBOUNCE_MS = 5000;
465
462
  constructor() {
466
- this.stompConnectionManager.fatalErrors.subscribe(() => this.serverInfo = null);
467
- this.stompConnectionManager.connectionLostHandler = () => {
463
+ this.stompConnectionManager.connectionEndedHandler = (reason) => {
468
464
  this.resetRequestReplies("Connection lost");
469
- this.connectionLostSubject.next();
465
+ if (!this.stompConnectionManager.active) {
466
+ this.serverInfo = null;
467
+ }
468
+ this.connectionEndedSubject.next(reason);
470
469
  };
471
470
  }
472
- get fatalErrors() {
473
- return this.stompConnectionManager.fatalErrors;
471
+ get connectionEnded() {
472
+ return this.connectionEndedSubject.asObservable();
474
473
  }
475
- get connectionLost() {
476
- return this.connectionLostSubject.asObservable();
474
+ get connectionEstablished() {
475
+ return this.stompConnectionManager.connectionEstablished;
477
476
  }
478
477
  isConnectionActive() {
479
478
  return this.stompConnectionManager.active;
@@ -1182,7 +1181,7 @@ import opentelemetry, { context as context2, propagation as propagation2, trace,
1182
1181
  // packages/core/package.json
1183
1182
  var package_default = {
1184
1183
  name: "@kinotic-ai/core",
1185
- version: "5.0.0-beta.12",
1184
+ version: "5.0.0-beta.17",
1186
1185
  type: "module",
1187
1186
  files: [
1188
1187
  "dist"
@@ -1277,7 +1276,7 @@ class ServiceInvocationSupervisor {
1277
1276
  methodSubscription = null;
1278
1277
  unscopedSubscription = null;
1279
1278
  activeStreams = new Map;
1280
- connectionLostSubscription = null;
1279
+ connectionEndedSubscription = null;
1281
1280
  connectionGeneration = 0;
1282
1281
  methodMap;
1283
1282
  scopeOptionalMethods;
@@ -1327,7 +1326,7 @@ class ServiceInvocationSupervisor {
1327
1326
  this.unscopedSubscription = this.subscribeAt(unscopedBase);
1328
1327
  this.log.info(`ServiceInvocationSupervisor also listening for ScopeOptional methods at ${unscopedBase}`);
1329
1328
  }
1330
- this.connectionLostSubscription = this._eventBus.connectionLost.subscribe(() => {
1329
+ this.connectionEndedSubscription = this._eventBus.connectionEnded.subscribe(() => {
1331
1330
  this.connectionGeneration++;
1332
1331
  for (const stream of this.activeStreams.values()) {
1333
1332
  stream.subscription.unsubscribe();
@@ -1358,8 +1357,8 @@ class ServiceInvocationSupervisor {
1358
1357
  this.methodSubscription = null;
1359
1358
  this.unscopedSubscription?.unsubscribe();
1360
1359
  this.unscopedSubscription = null;
1361
- this.connectionLostSubscription?.unsubscribe();
1362
- this.connectionLostSubscription = null;
1360
+ this.connectionEndedSubscription?.unsubscribe();
1361
+ this.connectionEndedSubscription = null;
1363
1362
  const serviceName = this.serviceIdentifier.qualifiedName();
1364
1363
  for (const stream of this.activeStreams.values()) {
1365
1364
  this.handleException(stream.request, new Error(`Service ${serviceName} stopped while producing the stream`));
@@ -1434,6 +1433,10 @@ class ServiceInvocationSupervisor {
1434
1433
  const args = this.argumentResolver.resolveArguments(event);
1435
1434
  const injectContext = receivesContext(this.serviceInstance, methodName);
1436
1435
  let serviceContext = {};
1436
+ const sender = event.getHeader("sender" /* SENDER_HEADER */);
1437
+ if (sender) {
1438
+ serviceContext.participant = JSON.parse(sender);
1439
+ }
1437
1440
  const interceptor = this.interceptorProvider();
1438
1441
  if (interceptor) {
1439
1442
  try {
@@ -2017,6 +2020,13 @@ class Order {
2017
2020
  class Sort {
2018
2021
  orders = [];
2019
2022
  }
2023
+ // packages/core/src/api/security/AuthorizationException.ts
2024
+ class AuthorizationException extends Error {
2025
+ constructor(message = "Access denied") {
2026
+ super(message);
2027
+ this.name = "AuthorizationException";
2028
+ }
2029
+ }
2020
2030
  // packages/core/src/api/security/ConnectedInfo.ts
2021
2031
  class ConnectedInfo {
2022
2032
  replyToId;
@@ -2076,5 +2086,6 @@ export {
2076
2086
  ChainedCredentialsResolver,
2077
2087
  BearerCredentialsResolver,
2078
2088
  BasicCredentialsResolver,
2089
+ AuthorizationException,
2079
2090
  AbstractIterablePage
2080
2091
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kinotic-ai/core",
3
- "version": "5.0.0-beta.12",
3
+ "version": "5.0.0-beta.17",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "dist"