@kinotic-ai/core 5.0.0-beta.11 → 5.0.0-beta.13

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
@@ -79,6 +79,7 @@ __export(exports_src, {
79
79
  SessionKeepAliveMode: () => SessionKeepAliveMode,
80
80
  SessionCredentialsResolver: () => SessionCredentialsResolver,
81
81
  ServiceRegistry: () => ServiceRegistry,
82
+ ServiceIdentifier: () => ServiceIdentifier,
82
83
  ServerInfo: () => ServerInfo,
83
84
  ScopeOptional: () => ScopeOptional,
84
85
  Scope: () => Scope,
@@ -108,6 +109,7 @@ __export(exports_src, {
108
109
  ChainedCredentialsResolver: () => ChainedCredentialsResolver,
109
110
  BearerCredentialsResolver: () => BearerCredentialsResolver,
110
111
  BasicCredentialsResolver: () => BasicCredentialsResolver,
112
+ AuthorizationException: () => AuthorizationException,
111
113
  AbstractIterablePage: () => AbstractIterablePage
112
114
  });
113
115
  module.exports = __toCommonJS(exports_src);
@@ -136,6 +138,7 @@ var EventConstants;
136
138
  EventConstants2["CONTENT_TYPE_HEADER"] = "content-type";
137
139
  EventConstants2["CONTENT_LENGTH_HEADER"] = "content-length";
138
140
  EventConstants2["REPLY_TO_HEADER"] = "reply-to";
141
+ EventConstants2["SENDER_HEADER"] = "sender";
139
142
  EventConstants2["CONNECTED_INFO_HEADER"] = "connected-info";
140
143
  EventConstants2["SESSION_KEEP_ALIVE_HEADER"] = "session-keep-alive";
141
144
  EventConstants2["CORRELATION_ID_HEADER"] = "__correlation-id";
@@ -237,7 +240,7 @@ var SESSION_CHECK_PATH = "/api/auth/me";
237
240
  class StompConnectionManager {
238
241
  lastWebsocketError = null;
239
242
  maxConnectionAttemptsReached = false;
240
- connectionLostHandler = null;
243
+ connectionEndedHandler = null;
241
244
  rxStomp = new import_rx_stomp.RxStomp;
242
245
  activation = null;
243
246
  teardown = null;
@@ -246,8 +249,7 @@ class StompConnectionManager {
246
249
  MAX_RECONNECT_DELAY = 120000;
247
250
  connectionAttempts = 0;
248
251
  debugLogger = import_debug2.default("kinotic:stomp");
249
- fatalErrorsSubject = new import_rxjs.Subject;
250
- _fatalErrors = this.fatalErrorsSubject.asObservable();
252
+ connectionEstablishedSubject = new import_rxjs.Subject;
251
253
  initialConnectionSuccessful = false;
252
254
  rxStompHasConnected = false;
253
255
  _replyToCri = null;
@@ -260,8 +262,8 @@ class StompConnectionManager {
260
262
  get connected() {
261
263
  return this.activation !== null && this.rxStomp.connected();
262
264
  }
263
- get fatalErrors() {
264
- return this._fatalErrors;
265
+ get connectionEstablished() {
266
+ return this.connectionEstablishedSubject.asObservable();
265
267
  }
266
268
  async activate(options) {
267
269
  if (!options?.server?.host) {
@@ -339,12 +341,12 @@ class StompConnectionManager {
339
341
  this.lastWebsocketError = value;
340
342
  if (!activation.ended && options?.maxConnectionAttempts && this.connectionAttempts >= options.maxConnectionAttempts) {
341
343
  this.maxConnectionAttemptsReached = true;
342
- 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 }));
343
345
  }
344
346
  }));
345
347
  activation.own(this.rxStomp.stompErrors$.subscribe(async (frame) => {
346
348
  const stompError = new Error(frame.headers["message"], { cause: frame });
347
- await this.signalFatal(activation, new Error("STOMP connection error", { cause: stompError }));
349
+ await this.failConnection(activation, new Error("STOMP connection error", { cause: stompError }));
348
350
  }));
349
351
  activation.own(this.rxStomp.connected$.subscribe(() => {
350
352
  activation.established();
@@ -357,16 +359,14 @@ class StompConnectionManager {
357
359
  const connectedInfoJson = value["connected-info" /* CONNECTED_INFO_HEADER */];
358
360
  if (connectedInfoJson == null) {
359
361
  if (!this.initialConnectionSuccessful) {
360
- activation.failIfPending(new Error("Server did not return proper data for successful login"));
361
- await this.deactivate();
362
+ await this.deactivate(undefined, new Error("Server did not return proper data for successful login"));
362
363
  }
363
364
  return;
364
365
  }
365
366
  const connectedInfo = JSON.parse(connectedInfoJson);
366
367
  if (connectedInfo.replyToId == null) {
367
368
  if (!this.initialConnectionSuccessful) {
368
- activation.failIfPending(new Error("Server did not return a replyToId for successful login"));
369
- await this.deactivate();
369
+ await this.deactivate(undefined, new Error("Server did not return a replyToId for successful login"));
370
370
  }
371
371
  return;
372
372
  }
@@ -375,11 +375,12 @@ class StompConnectionManager {
375
375
  if (!this.initialConnectionSuccessful) {
376
376
  resolve(connectedInfo);
377
377
  }
378
+ this.connectionEstablishedSubject.next(connectedInfo);
378
379
  }));
379
380
  let previousState = this.rxStomp.connectionState$.getValue();
380
381
  activation.own(this.rxStomp.connectionState$.subscribe((state) => {
381
382
  if (state === import_rx_stomp.RxStompState.CLOSED && previousState === import_rx_stomp.RxStompState.OPEN && this.activation === activation) {
382
- this.connectionLostHandler?.();
383
+ this.connectionEndedHandler?.(null);
383
384
  }
384
385
  previousState = state;
385
386
  }));
@@ -396,7 +397,7 @@ class StompConnectionManager {
396
397
  try {
397
398
  const res = await fetch(sessionCheckUrl, { credentials: "include" });
398
399
  if (res.status === 401) {
399
- await this.signalFatal(activation, new Error("Authentication required"));
400
+ await this.failConnection(activation, new Error("Authentication required"));
400
401
  return;
401
402
  }
402
403
  } catch (e) {
@@ -407,7 +408,7 @@ class StompConnectionManager {
407
408
  this.connectionAttempts++;
408
409
  if (this.connectionAttempts > options.maxConnectionAttempts) {
409
410
  this.maxConnectionAttemptsReached = true;
410
- 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 }));
411
412
  return;
412
413
  } else {
413
414
  await this.connectionJitterDelay(activation);
@@ -422,19 +423,19 @@ class StompConnectionManager {
422
423
  try {
423
424
  activation.preparedSocket = await userWebSocketFactory();
424
425
  } catch (e) {
425
- await this.signalFatal(activation, new Error("WebSocket factory failed", { cause: e }));
426
+ await this.failConnection(activation, new Error("WebSocket factory failed", { cause: e }));
426
427
  }
427
428
  } else if (headerAuth) {
428
429
  try {
429
430
  const resolved = await credentialsResolver.resolve(server);
430
431
  if (resolved?.authHeaders == null) {
431
- 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));
432
433
  } else {
433
434
  const WS = WebSocket;
434
435
  activation.preparedSocket = new WS(url, { headers: resolved.authHeaders });
435
436
  }
436
437
  } catch (e) {
437
- await this.signalFatal(activation, new Error("Credential resolution failed", { cause: e }));
438
+ await this.failConnection(activation, new Error("Credential resolution failed", { cause: e }));
438
439
  }
439
440
  }
440
441
  if (activation.ended && activation.preparedSocket) {
@@ -442,7 +443,7 @@ class StompConnectionManager {
442
443
  activation.preparedSocket = null;
443
444
  }
444
445
  }
445
- deactivate(force) {
446
+ deactivate(force, reason = null) {
446
447
  const activation = this.activation;
447
448
  let ret;
448
449
  if (activation) {
@@ -450,17 +451,17 @@ class StompConnectionManager {
450
451
  activation.end();
451
452
  const wasOpen = this.rxStomp.connected();
452
453
  this._replyToCri = null;
453
- activation.failIfPending(new Error("Deactivated before the connection was established"));
454
+ activation.failIfPending(reason ?? new Error("Deactivated before the connection was established"));
454
455
  activation.preparedSocket?.close();
455
456
  activation.preparedSocket = null;
456
457
  const teardown = this.rxStomp.deactivate({ force }).then(() => activation.attempt ?? undefined).finally(() => {
457
458
  activation.unsubscribeAll();
458
459
  this.teardown = null;
459
- if (wasOpen) {
460
- this.connectionLostHandler?.();
461
- }
462
460
  });
463
461
  this.teardown = teardown;
462
+ if (wasOpen || reason !== null) {
463
+ this.connectionEndedHandler?.(reason);
464
+ }
464
465
  ret = teardown;
465
466
  } else {
466
467
  ret = this.teardown ?? Promise.resolve();
@@ -474,12 +475,10 @@ class StompConnectionManager {
474
475
  await activation.delay(randomJitter);
475
476
  }
476
477
  }
477
- async signalFatal(activation, err) {
478
+ async failConnection(activation, err) {
478
479
  if (!activation.ended) {
479
- this.debugLogger("Fatal error, deactivating connection: %O", err);
480
- activation.failIfPending(err);
481
- await this.deactivate();
482
- this.fatalErrorsSubject.next(err);
480
+ this.debugLogger("Connection failed, ending it: %O", err);
481
+ await this.deactivate(undefined, err);
483
482
  }
484
483
  }
485
484
  }
@@ -574,20 +573,22 @@ class EventBus {
574
573
  requestRepliesSubscription = null;
575
574
  activeCorrelationIds = new Set;
576
575
  recentlyReaped = new Set;
577
- connectionLostSubject = new import_rxjs2.Subject;
576
+ connectionEndedSubject = new import_rxjs2.Subject;
578
577
  static REAP_DEBOUNCE_MS = 5000;
579
578
  constructor() {
580
- this.stompConnectionManager.fatalErrors.subscribe(() => this.serverInfo = null);
581
- this.stompConnectionManager.connectionLostHandler = () => {
579
+ this.stompConnectionManager.connectionEndedHandler = (reason) => {
582
580
  this.resetRequestReplies("Connection lost");
583
- this.connectionLostSubject.next();
581
+ if (!this.stompConnectionManager.active) {
582
+ this.serverInfo = null;
583
+ }
584
+ this.connectionEndedSubject.next(reason);
584
585
  };
585
586
  }
586
- get fatalErrors() {
587
- return this.stompConnectionManager.fatalErrors;
587
+ get connectionEnded() {
588
+ return this.connectionEndedSubject.asObservable();
588
589
  }
589
- get connectionLost() {
590
- return this.connectionLostSubject.asObservable();
590
+ get connectionEstablished() {
591
+ return this.stompConnectionManager.connectionEstablished;
591
592
  }
592
593
  isConnectionActive() {
593
594
  return this.stompConnectionManager.active;
@@ -1296,7 +1297,7 @@ var import_api2 = __toESM(require("@opentelemetry/api"));
1296
1297
  // packages/core/package.json
1297
1298
  var package_default = {
1298
1299
  name: "@kinotic-ai/core",
1299
- version: "5.0.0-beta.11",
1300
+ version: "5.0.0-beta.13",
1300
1301
  type: "module",
1301
1302
  files: [
1302
1303
  "dist"
@@ -1391,7 +1392,7 @@ class ServiceInvocationSupervisor {
1391
1392
  methodSubscription = null;
1392
1393
  unscopedSubscription = null;
1393
1394
  activeStreams = new Map;
1394
- connectionLostSubscription = null;
1395
+ connectionEndedSubscription = null;
1395
1396
  connectionGeneration = 0;
1396
1397
  methodMap;
1397
1398
  scopeOptionalMethods;
@@ -1441,7 +1442,7 @@ class ServiceInvocationSupervisor {
1441
1442
  this.unscopedSubscription = this.subscribeAt(unscopedBase);
1442
1443
  this.log.info(`ServiceInvocationSupervisor also listening for ScopeOptional methods at ${unscopedBase}`);
1443
1444
  }
1444
- this.connectionLostSubscription = this._eventBus.connectionLost.subscribe(() => {
1445
+ this.connectionEndedSubscription = this._eventBus.connectionEnded.subscribe(() => {
1445
1446
  this.connectionGeneration++;
1446
1447
  for (const stream of this.activeStreams.values()) {
1447
1448
  stream.subscription.unsubscribe();
@@ -1472,8 +1473,8 @@ class ServiceInvocationSupervisor {
1472
1473
  this.methodSubscription = null;
1473
1474
  this.unscopedSubscription?.unsubscribe();
1474
1475
  this.unscopedSubscription = null;
1475
- this.connectionLostSubscription?.unsubscribe();
1476
- this.connectionLostSubscription = null;
1476
+ this.connectionEndedSubscription?.unsubscribe();
1477
+ this.connectionEndedSubscription = null;
1477
1478
  const serviceName = this.serviceIdentifier.qualifiedName();
1478
1479
  for (const stream of this.activeStreams.values()) {
1479
1480
  this.handleException(stream.request, new Error(`Service ${serviceName} stopped while producing the stream`));
@@ -1548,6 +1549,10 @@ class ServiceInvocationSupervisor {
1548
1549
  const args = this.argumentResolver.resolveArguments(event);
1549
1550
  const injectContext = receivesContext(this.serviceInstance, methodName);
1550
1551
  let serviceContext = {};
1552
+ const sender = event.getHeader("sender" /* SENDER_HEADER */);
1553
+ if (sender) {
1554
+ serviceContext.participant = JSON.parse(sender);
1555
+ }
1551
1556
  const interceptor = this.interceptorProvider();
1552
1557
  if (interceptor) {
1553
1558
  try {
@@ -2128,6 +2133,13 @@ class Order {
2128
2133
  class Sort {
2129
2134
  orders = [];
2130
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
+ }
2131
2143
  // packages/core/src/api/security/ConnectedInfo.ts
2132
2144
  class ConnectedInfo {
2133
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, 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, 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.11",
1184
+ version: "5.0.0-beta.13",
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;
@@ -2046,6 +2056,7 @@ export {
2046
2056
  SessionKeepAliveMode,
2047
2057
  SessionCredentialsResolver,
2048
2058
  ServiceRegistry,
2059
+ ServiceIdentifier,
2049
2060
  ServerInfo,
2050
2061
  ScopeOptional,
2051
2062
  Scope,
@@ -2075,5 +2086,6 @@ export {
2075
2086
  ChainedCredentialsResolver,
2076
2087
  BearerCredentialsResolver,
2077
2088
  BasicCredentialsResolver,
2089
+ AuthorizationException,
2078
2090
  AbstractIterablePage
2079
2091
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kinotic-ai/core",
3
- "version": "5.0.0-beta.11",
3
+ "version": "5.0.0-beta.13",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "dist"