@kinotic-ai/core 5.0.0-beta.30 → 5.0.0-beta.31

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
@@ -100,6 +100,7 @@ __export(exports_src, {
100
100
  ServiceIdentifier: () => ServiceIdentifier,
101
101
  ServiceRegistry: () => ServiceRegistry,
102
102
  SessionCredentialsResolver: () => SessionCredentialsResolver,
103
+ SessionEndType: () => SessionEndType,
103
104
  SessionKeepAliveMode: () => SessionKeepAliveMode,
104
105
  Sort: () => Sort,
105
106
  TextEventFactory: () => TextEventFactory,
@@ -188,6 +189,17 @@ var import_rxjs = require("rxjs");
188
189
  var import_operators = require("rxjs/operators");
189
190
  var import_uuid = require("uuid");
190
191
 
192
+ // packages/core/src/internal/api/SessionRoutes.ts
193
+ var SESSION_CHECK_PATH = "/api/auth/me";
194
+ var LOGOUT_PATH = "/api/auth/logout";
195
+ async function holdsLogin(server, signal) {
196
+ const response = await fetch(buildServerUrl(server, "http") + SESSION_CHECK_PATH, { credentials: "include", signal });
197
+ return response.status !== 401;
198
+ }
199
+ async function endLogin(server, signal) {
200
+ await fetch(buildServerUrl(server, "http") + LOGOUT_PATH, { method: "POST", credentials: "include", signal });
201
+ }
202
+
191
203
  // packages/core/src/internal/api/StompActivation.ts
192
204
  class StompActivation {
193
205
  _ended = false;
@@ -244,8 +256,6 @@ class StompActivation {
244
256
  }
245
257
 
246
258
  // packages/core/src/internal/api/StompConnectionManager.ts
247
- var SESSION_CHECK_PATH = "/api/auth/me";
248
-
249
259
  class StompConnectionManager {
250
260
  lastWebsocketError = null;
251
261
  maxConnectionAttemptsReached = false;
@@ -413,18 +423,14 @@ class StompConnectionManager {
413
423
  const usesPreparedSocket = userWebSocketFactory != null || headerAuth;
414
424
  const url = buildBrokerUrl(server);
415
425
  if (!usesPreparedSocket) {
416
- const sessionCheckUrl = buildServerUrl(server, "http") + SESSION_CHECK_PATH;
417
426
  try {
418
- const res = await fetch(sessionCheckUrl, {
419
- credentials: "include",
420
- signal: AbortSignal.any([activation.signal, AbortSignal.timeout(this.CONNECTION_TIMEOUT)])
421
- });
422
- if (res.status === 401) {
427
+ const signedIn = await holdsLogin(server, AbortSignal.any([activation.signal, AbortSignal.timeout(this.CONNECTION_TIMEOUT)]));
428
+ if (!signedIn) {
423
429
  this.failConnection(activation, new Error("Authentication required"));
424
430
  return;
425
431
  }
426
432
  } catch (e) {
427
- this.debugLogger("Session check at %s failed: %O", sessionCheckUrl, e);
433
+ this.debugLogger("Session check of %s failed: %O", server.host, e);
428
434
  }
429
435
  }
430
436
  if (options?.maxConnectionAttempts) {
@@ -952,8 +958,119 @@ class Util {
952
958
  }
953
959
  }
954
960
 
955
- // packages/core/src/api/ServiceRegistry.ts
961
+ // packages/core/src/internal/api/Session.ts
956
962
  var import_debug3 = __toESM(require("debug"), 1);
963
+ var import_rxjs3 = require("rxjs");
964
+
965
+ // packages/core/src/api/security/SessionEndType.ts
966
+ var SessionEndType;
967
+ ((SessionEndType) => {
968
+ SessionEndType["SIGNED_OUT"] = "SIGNED_OUT";
969
+ SessionEndType["CONNECTION_LOST"] = "CONNECTION_LOST";
970
+ })(SessionEndType ||= {});
971
+
972
+ // packages/core/src/internal/api/Session.ts
973
+ var SESSION_REQUEST_TIMEOUT_MS = 5000;
974
+
975
+ class Session {
976
+ kinotic;
977
+ _connectedInfo = null;
978
+ server = null;
979
+ inFlight = Promise.resolve();
980
+ requests = 0;
981
+ subscriptions = new import_rxjs3.Subscription;
982
+ endedSubject = new import_rxjs3.Subject;
983
+ debugLogger = import_debug3.default("kinotic:session");
984
+ constructor(kinotic) {
985
+ this.kinotic = kinotic;
986
+ this.observe(kinotic.eventBus);
987
+ }
988
+ get connectedInfo() {
989
+ return this._connectedInfo;
990
+ }
991
+ get ended() {
992
+ return this.endedSubject.asObservable();
993
+ }
994
+ release() {
995
+ this._connectedInfo = null;
996
+ }
997
+ observe(eventBus) {
998
+ this.subscriptions.unsubscribe();
999
+ this.subscriptions = new import_rxjs3.Subscription;
1000
+ this.subscriptions.add(eventBus.connectionEstablished.subscribe((connectedInfo) => {
1001
+ if (this._connectedInfo !== null) {
1002
+ this._connectedInfo = connectedInfo;
1003
+ }
1004
+ }));
1005
+ this.subscriptions.add(eventBus.connectionEnded.subscribe((reason) => {
1006
+ if (this._connectedInfo !== null && !this.kinotic.eventBus.isConnectionActive()) {
1007
+ this._connectedInfo = null;
1008
+ if (reason !== null) {
1009
+ this.classifyEnd(reason);
1010
+ }
1011
+ }
1012
+ }));
1013
+ }
1014
+ resume(options) {
1015
+ this.requests++;
1016
+ return this.serialize(async () => {
1017
+ this._connectedInfo = null;
1018
+ try {
1019
+ await this.kinotic.disconnect();
1020
+ } catch (e) {
1021
+ this.debugLogger("Closing the previous connection failed: %O", e);
1022
+ }
1023
+ const resolved = Util.resolveConnectOptions(options);
1024
+ this.server = resolved.server;
1025
+ let ret;
1026
+ try {
1027
+ ret = await this.kinotic.connect(resolved);
1028
+ } catch (e) {
1029
+ await this.kinotic.disconnect().catch((error) => this.debugLogger("Closing the failed connection failed: %O", error));
1030
+ throw e;
1031
+ }
1032
+ this._connectedInfo = ret;
1033
+ return ret;
1034
+ });
1035
+ }
1036
+ logout() {
1037
+ this.requests++;
1038
+ return this.serialize(async () => {
1039
+ this._connectedInfo = null;
1040
+ const server = this.kinotic.eventBus.serverInfo ?? this.server ?? Util.resolveConnectOptions().server;
1041
+ try {
1042
+ await endLogin(server, AbortSignal.timeout(SESSION_REQUEST_TIMEOUT_MS));
1043
+ } catch (e) {
1044
+ this.debugLogger("The logout request failed: %O", e);
1045
+ }
1046
+ try {
1047
+ await this.kinotic.disconnect();
1048
+ } catch (e) {
1049
+ this.debugLogger("Closing the connection failed: %O", e);
1050
+ }
1051
+ });
1052
+ }
1053
+ async classifyEnd(cause) {
1054
+ const requestsAtEnd = this.requests;
1055
+ let signedOut = false;
1056
+ try {
1057
+ signedOut = !await holdsLogin(this.server, AbortSignal.timeout(SESSION_REQUEST_TIMEOUT_MS));
1058
+ } catch (e) {
1059
+ this.debugLogger("The session check failed: %O", e);
1060
+ }
1061
+ if (this.requests === requestsAtEnd) {
1062
+ this.endedSubject.next({ type: signedOut ? "SIGNED_OUT" /* SIGNED_OUT */ : "CONNECTION_LOST" /* CONNECTION_LOST */, cause });
1063
+ }
1064
+ }
1065
+ serialize(operation) {
1066
+ const result = this.inFlight.then(operation);
1067
+ this.inFlight = result.catch(() => {});
1068
+ return result;
1069
+ }
1070
+ }
1071
+
1072
+ // packages/core/src/api/ServiceRegistry.ts
1073
+ var import_debug4 = __toESM(require("debug"), 1);
957
1074
 
958
1075
  // packages/core/src/api/event/DefaultCRI.ts
959
1076
  var ZONE_DELIMITER = "~";
@@ -1147,7 +1264,7 @@ class BasicReturnValueConverter {
1147
1264
  }
1148
1265
 
1149
1266
  // packages/core/src/internal/api/ServiceInvocationSupervisor.ts
1150
- var import_rxjs3 = require("rxjs");
1267
+ var import_rxjs4 = require("rxjs");
1151
1268
  var import_operators3 = require("rxjs/operators");
1152
1269
 
1153
1270
  // packages/core/src/api/ServiceIdentifier.ts
@@ -1329,7 +1446,7 @@ var import_api2 = __toESM(require("@opentelemetry/api"), 1);
1329
1446
  // packages/core/package.json
1330
1447
  var package_default = {
1331
1448
  name: "@kinotic-ai/core",
1332
- version: "5.0.0-beta.30",
1449
+ version: "5.0.0-beta.31",
1333
1450
  type: "module",
1334
1451
  files: [
1335
1452
  "dist"
@@ -1656,7 +1773,7 @@ class ServiceInvocationSupervisor {
1656
1773
  processMethodInvocationResult(event, result, span, generation) {
1657
1774
  if (!this.replyOwed(generation)) {
1658
1775
  span.end();
1659
- } else if (import_rxjs3.isObservable(result)) {
1776
+ } else if (import_rxjs4.isObservable(result)) {
1660
1777
  this.streamResult(event, result, span);
1661
1778
  } else {
1662
1779
  const reply = this.returnValueConverter.convert(event.headers, result);
@@ -1851,7 +1968,7 @@ class ServiceRegistry {
1851
1968
  supervisors = new Map;
1852
1969
  entries = new Map;
1853
1970
  contextInterceptor = null;
1854
- debugLogger = import_debug3.default("kinotic:serviceRegistry");
1971
+ debugLogger = import_debug4.default("kinotic:serviceRegistry");
1855
1972
  constructor(eventBus) {
1856
1973
  this._eventBus = eventBus;
1857
1974
  }
@@ -1980,11 +2097,16 @@ class ServiceProxy {
1980
2097
  class KinoticSingleton {
1981
2098
  _eventBus;
1982
2099
  serviceRegistry;
2100
+ _session;
1983
2101
  zonePrefix = null;
1984
2102
  defaultZone = null;
1985
2103
  constructor() {
1986
2104
  this._eventBus = new EventBus;
1987
2105
  this.serviceRegistry = new ServiceRegistry(this._eventBus);
2106
+ this._session = new Session(this);
2107
+ }
2108
+ get session() {
2109
+ return this._session;
1988
2110
  }
1989
2111
  get eventBus() {
1990
2112
  return this._eventBus;
@@ -1992,6 +2114,7 @@ class KinoticSingleton {
1992
2114
  set eventBus(eventBus) {
1993
2115
  this._eventBus = eventBus;
1994
2116
  this.serviceRegistry.eventBus = eventBus;
2117
+ this._session.observe(eventBus);
1995
2118
  }
1996
2119
  async connect(options) {
1997
2120
  const ret = await this._eventBus.connect(Util.resolveConnectOptions(options));
@@ -1999,6 +2122,7 @@ class KinoticSingleton {
1999
2122
  return ret;
2000
2123
  }
2001
2124
  disconnect(force) {
2125
+ this._session.release();
2002
2126
  return this._eventBus.disconnect(force);
2003
2127
  }
2004
2128
  serviceProxy(serviceIdentifier) {
package/dist/index.d.cts CHANGED
@@ -103,8 +103,10 @@ interface ConnectOptions {
103
103
  */
104
104
  webSocketFactory?: WebSocketFactory;
105
105
  /**
106
- * The maximum number of connection attempts to make during the {@link IEventBus} initial connection request.
107
- * If the limit is reached the {@link IEventBus} will return an error to the caller of {@link IEventBus#connect}
106
+ * The maximum number of attempts to make for a connection: for the initial connection request, and
107
+ * again for each reconnect of an established connection. When the initial request reaches the limit
108
+ * the {@link IEventBus} returns an error to the caller of {@link IEventBus#connect}; when a reconnect
109
+ * does, the connection ends for good and {@link IEventBus#connectionEnded} carries the failure.
108
110
  * Set to 0, undefined, or null to try forever
109
111
  */
110
112
  maxConnectionAttempts?: number | null;
@@ -422,6 +424,58 @@ interface ServiceContext {
422
424
  interface ContextInterceptor<T extends ServiceContext> {
423
425
  intercept(event: IEvent, context: T): Promise<T> | T;
424
426
  }
427
+ import { Observable as Observable2 } from "rxjs";
428
+ /**
429
+ * How a session ended when its client did not end it.
430
+ */
431
+ declare enum SessionEndType {
432
+ /** The gateway holds no login for the page any more: the session expired, the user signed out elsewhere, or the user was disabled. */
433
+ SIGNED_OUT = "SIGNED_OUT",
434
+ /** The connection ended for good while the gateway still holds the page's login, or while it gives no answer. */
435
+ CONNECTION_LOST = "CONNECTION_LOST"
436
+ }
437
+ /**
438
+ * The end of a session that its client did not ask for.
439
+ */
440
+ interface SessionEnd {
441
+ /** Whether the page was signed out or only its connection was lost. */
442
+ type: SessionEndType;
443
+ /** The failure that ended the connection; its {@code cause} chain leads to the server's own reason. */
444
+ cause: Error;
445
+ }
446
+ /**
447
+ * The browser session of a page: the login a gateway's REST sign-in established for it, held in the
448
+ * session cookie, and the connection opened on that login. Calls to {@link resume} and {@link logout}
449
+ * run one at a time, in the order they were made.
450
+ */
451
+ interface ISession {
452
+ /**
453
+ * The {@link ConnectedInfo} of the session's connection, following each reconnect, or null while
454
+ * the session holds no connection.
455
+ */
456
+ readonly connectedInfo: ConnectedInfo | null;
457
+ /**
458
+ * Opens the connection on the page's session cookie; rejects when the gateway holds no login for it.
459
+ * A connection the client already holds is closed first, and a rejected call leaves none open. A
460
+ * gateway that gives no answer is retried, so the call stays pending until it answers unless
461
+ * {@link ConnectOptions#maxConnectionAttempts} bounds it.
462
+ * @param options the server to reach and the connection's settings, resolved as {@link IKinotic#connect} resolves them
463
+ * @return the {@link ConnectedInfo} of the connection
464
+ */
465
+ resume(options?: ConnectOptions): Promise<ConnectedInfo>;
466
+ /**
467
+ * Ends the page's login on the gateway the client is connected to, or last resumed on, then closes
468
+ * the connection. Resolves once both were tried, whether or not either succeeded.
469
+ */
470
+ logout(): Promise<void>;
471
+ /**
472
+ * Emits when the session ends without this client asking, classified once: a failure ended the
473
+ * session's connection for good, and the client has made no {@link resume} or {@link logout}
474
+ * since. The gateway is asked which end it was: it ended the login, or the connection was lost
475
+ * while the login lives.
476
+ */
477
+ readonly ended: Observable2<SessionEnd>;
478
+ }
425
479
  /**
426
480
  * `CRI` is a Kinotic Resource Identifier used by Kinotic to route requests appropriately.
427
481
  *
@@ -589,7 +643,7 @@ declare class ServiceIdentifier {
589
643
  */
590
644
  unscopedCri(): CRI;
591
645
  }
592
- import { Observable as Observable2 } from "rxjs";
646
+ import { Observable as Observable3 } from "rxjs";
593
647
  /**
594
648
  * Provides an interface to allow the {@link IServiceProxy} creator the ability to have fine grain control of the outgoing {@link IEvent}
595
649
  */
@@ -623,7 +677,7 @@ interface IServiceProxy {
623
677
  * @param eventFactory IEventFactory or undefined or null, if not undefined or null this is the {@link IEventFactory} to use when creating {@link IEvent}'s to send
624
678
  * @return a {@link Observable} that will resolve to the result from the invocation
625
679
  */
626
- invokeStream(methodIdentifier: string, args?: any[] | null | undefined, scope?: string | null | undefined, eventFactory?: IEventFactory | null | undefined): Observable2<any>;
680
+ invokeStream(methodIdentifier: string, args?: any[] | null | undefined, scope?: string | null | undefined, eventFactory?: IEventFactory | null | undefined): Observable3<any>;
627
681
  }
628
682
  /**
629
683
  * Provides the functionality to register services as well as create proxies for those services
@@ -716,6 +770,11 @@ interface IKinotic {
716
770
  serviceRegistry: IServiceRegistry;
717
771
  eventBus: IEventBus;
718
772
  /**
773
+ * The browser session of the page this client runs in, for a client that signs in through a gateway's
774
+ * REST login rather than with credentials of its own.
775
+ */
776
+ readonly session: ISession;
777
+ /**
719
778
  * The zone prefix every service published by this client registers under, such as
720
779
  * `app.<organizationId>.<applicationId>` for an application or `system` for a system
721
780
  * workload. Must be set from static configuration before service classes are instantiated.
@@ -765,9 +824,11 @@ declare class KinoticSingleton implements IKinotic {
765
824
  * The {@link ServiceRegistry} that is used to manage the services that are available
766
825
  */
767
826
  readonly serviceRegistry: ServiceRegistry;
827
+ private readonly _session;
768
828
  zonePrefix: string | null;
769
829
  defaultZone: string | null;
770
830
  constructor();
831
+ get session(): ISession;
771
832
  get eventBus(): IEventBus;
772
833
  set eventBus(eventBus: IEventBus);
773
834
  /**
@@ -1309,7 +1370,7 @@ declare class DefaultCRI implements CRI {
1309
1370
  private static parseRaw;
1310
1371
  private static buildRaw;
1311
1372
  }
1312
- import { Observable as Observable3 } from "rxjs";
1373
+ import { Observable as Observable4 } from "rxjs";
1313
1374
  import { Optional as Optional2 } from "typescript-optional";
1314
1375
  /**
1315
1376
  * Default IEvent implementation
@@ -1343,9 +1404,9 @@ declare class EventBus implements IEventBus {
1343
1404
  private readonly connectionEndedSubject;
1344
1405
  private static readonly REAP_DEBOUNCE_MS;
1345
1406
  constructor();
1346
- get connectionEnded(): Observable3<Error | null>;
1347
- get connectionEstablished(): Observable3<ConnectedInfo>;
1348
- get connectionAttemptFailed(): Observable3<void>;
1407
+ get connectionEnded(): Observable4<Error | null>;
1408
+ get connectionEstablished(): Observable4<ConnectedInfo>;
1409
+ get connectionAttemptFailed(): Observable4<void>;
1349
1410
  isConnectionActive(): boolean;
1350
1411
  isConnected(): boolean;
1351
1412
  connect(options: ConnectOptions): Promise<ConnectedInfo>;
@@ -1354,9 +1415,9 @@ declare class EventBus implements IEventBus {
1354
1415
  private serializeLifecycle;
1355
1416
  send(event: IEvent): void;
1356
1417
  request(event: IEvent): Promise<IEvent>;
1357
- requestStream(event: IEvent, sendControlEvents?: boolean): Observable3<IEvent>;
1418
+ requestStream(event: IEvent, sendControlEvents?: boolean): Observable4<IEvent>;
1358
1419
  listen(_serverInfo: ServerInfo): Promise<void>;
1359
- observe(cri: string): Observable3<IEvent>;
1420
+ observe(cri: string): Observable4<IEvent>;
1360
1421
  /**
1361
1422
  * Cancels a server stream whose reply arrived for a correlationId we no longer track. The server can't
1362
1423
  * detect this itself since all requests share one reply destination, so the cancel is sent to the
@@ -1487,4 +1548,4 @@ declare class ParticipantConstants {
1487
1548
  /** The clientId the test server's TestSecurityService maps to the ANONYMOUS role in core package tests. */
1488
1549
  static readonly CLI_PARTICIPANT_ID: string;
1489
1550
  }
1490
- export { AbstractIterablePage, AuthorizationException, BasicCredentialsResolver, BearerCredentialsResolver, CRI, ChainedCredentialsResolver, ConnectOptions, ConnectedInfo, Context, ContextInterceptor, CredentialsResolver, CrudServiceProxy, CrudServiceProxyFactory, CursorPageable, DataSourceUtils, DefaultCRI, Direction, EnvCredentialsResolver, Event, EventBus, EventConstants, FunctionalIterablePage, ICrudServiceProxy, ICrudServiceProxyFactory, IDataSource, IEditableDataSource, IEvent, IEventBus, IEventFactory, IKinotic, IParticipant, IServiceProxy, IServiceRegistry, IWebSocket, Identifiable, IterablePage, JsonEventFactory, Kinotic, KinoticPlugin, KinoticSingleton, NullHandling, OffsetPageable, Order, Page, Pageable, Participant, ParticipantConstants, Publish, ResolvedCredentials, RpcError, Scope, ScopeOptional, ServerInfo, ServiceContext, ServiceDirectoryEntry, ServiceIdentifier, ServiceRegistry, SessionCredentialsResolver, SessionKeepAliveMode, Sort, TextEventFactory, Version, WebSocketFactory, Zone, buildBrokerUrl, buildServerUrl, createCRI, declareServiceDefinitions, isAdvertised, receivesContext, scopeOptionalMethodNames, validateLabel, validateZone };
1551
+ export { AbstractIterablePage, AuthorizationException, BasicCredentialsResolver, BearerCredentialsResolver, CRI, ChainedCredentialsResolver, ConnectOptions, ConnectedInfo, Context, ContextInterceptor, CredentialsResolver, CrudServiceProxy, CrudServiceProxyFactory, CursorPageable, DataSourceUtils, DefaultCRI, Direction, EnvCredentialsResolver, Event, EventBus, EventConstants, FunctionalIterablePage, ICrudServiceProxy, ICrudServiceProxyFactory, IDataSource, IEditableDataSource, IEvent, IEventBus, IEventFactory, IKinotic, IParticipant, IServiceProxy, IServiceRegistry, ISession, IWebSocket, Identifiable, IterablePage, JsonEventFactory, Kinotic, KinoticPlugin, KinoticSingleton, NullHandling, OffsetPageable, Order, Page, Pageable, Participant, ParticipantConstants, Publish, ResolvedCredentials, RpcError, Scope, ScopeOptional, ServerInfo, ServiceContext, ServiceDirectoryEntry, ServiceIdentifier, ServiceRegistry, SessionCredentialsResolver, SessionEnd, SessionEndType, SessionKeepAliveMode, Sort, TextEventFactory, Version, WebSocketFactory, Zone, buildBrokerUrl, buildServerUrl, createCRI, declareServiceDefinitions, isAdvertised, receivesContext, scopeOptionalMethodNames, validateLabel, validateZone };
package/dist/index.d.ts CHANGED
@@ -103,8 +103,10 @@ interface ConnectOptions {
103
103
  */
104
104
  webSocketFactory?: WebSocketFactory;
105
105
  /**
106
- * The maximum number of connection attempts to make during the {@link IEventBus} initial connection request.
107
- * If the limit is reached the {@link IEventBus} will return an error to the caller of {@link IEventBus#connect}
106
+ * The maximum number of attempts to make for a connection: for the initial connection request, and
107
+ * again for each reconnect of an established connection. When the initial request reaches the limit
108
+ * the {@link IEventBus} returns an error to the caller of {@link IEventBus#connect}; when a reconnect
109
+ * does, the connection ends for good and {@link IEventBus#connectionEnded} carries the failure.
108
110
  * Set to 0, undefined, or null to try forever
109
111
  */
110
112
  maxConnectionAttempts?: number | null;
@@ -422,6 +424,58 @@ interface ServiceContext {
422
424
  interface ContextInterceptor<T extends ServiceContext> {
423
425
  intercept(event: IEvent, context: T): Promise<T> | T;
424
426
  }
427
+ import { Observable as Observable2 } from "rxjs";
428
+ /**
429
+ * How a session ended when its client did not end it.
430
+ */
431
+ declare enum SessionEndType {
432
+ /** The gateway holds no login for the page any more: the session expired, the user signed out elsewhere, or the user was disabled. */
433
+ SIGNED_OUT = "SIGNED_OUT",
434
+ /** The connection ended for good while the gateway still holds the page's login, or while it gives no answer. */
435
+ CONNECTION_LOST = "CONNECTION_LOST"
436
+ }
437
+ /**
438
+ * The end of a session that its client did not ask for.
439
+ */
440
+ interface SessionEnd {
441
+ /** Whether the page was signed out or only its connection was lost. */
442
+ type: SessionEndType;
443
+ /** The failure that ended the connection; its {@code cause} chain leads to the server's own reason. */
444
+ cause: Error;
445
+ }
446
+ /**
447
+ * The browser session of a page: the login a gateway's REST sign-in established for it, held in the
448
+ * session cookie, and the connection opened on that login. Calls to {@link resume} and {@link logout}
449
+ * run one at a time, in the order they were made.
450
+ */
451
+ interface ISession {
452
+ /**
453
+ * The {@link ConnectedInfo} of the session's connection, following each reconnect, or null while
454
+ * the session holds no connection.
455
+ */
456
+ readonly connectedInfo: ConnectedInfo | null;
457
+ /**
458
+ * Opens the connection on the page's session cookie; rejects when the gateway holds no login for it.
459
+ * A connection the client already holds is closed first, and a rejected call leaves none open. A
460
+ * gateway that gives no answer is retried, so the call stays pending until it answers unless
461
+ * {@link ConnectOptions#maxConnectionAttempts} bounds it.
462
+ * @param options the server to reach and the connection's settings, resolved as {@link IKinotic#connect} resolves them
463
+ * @return the {@link ConnectedInfo} of the connection
464
+ */
465
+ resume(options?: ConnectOptions): Promise<ConnectedInfo>;
466
+ /**
467
+ * Ends the page's login on the gateway the client is connected to, or last resumed on, then closes
468
+ * the connection. Resolves once both were tried, whether or not either succeeded.
469
+ */
470
+ logout(): Promise<void>;
471
+ /**
472
+ * Emits when the session ends without this client asking, classified once: a failure ended the
473
+ * session's connection for good, and the client has made no {@link resume} or {@link logout}
474
+ * since. The gateway is asked which end it was: it ended the login, or the connection was lost
475
+ * while the login lives.
476
+ */
477
+ readonly ended: Observable2<SessionEnd>;
478
+ }
425
479
  /**
426
480
  * `CRI` is a Kinotic Resource Identifier used by Kinotic to route requests appropriately.
427
481
  *
@@ -589,7 +643,7 @@ declare class ServiceIdentifier {
589
643
  */
590
644
  unscopedCri(): CRI;
591
645
  }
592
- import { Observable as Observable2 } from "rxjs";
646
+ import { Observable as Observable3 } from "rxjs";
593
647
  /**
594
648
  * Provides an interface to allow the {@link IServiceProxy} creator the ability to have fine grain control of the outgoing {@link IEvent}
595
649
  */
@@ -623,7 +677,7 @@ interface IServiceProxy {
623
677
  * @param eventFactory IEventFactory or undefined or null, if not undefined or null this is the {@link IEventFactory} to use when creating {@link IEvent}'s to send
624
678
  * @return a {@link Observable} that will resolve to the result from the invocation
625
679
  */
626
- invokeStream(methodIdentifier: string, args?: any[] | null | undefined, scope?: string | null | undefined, eventFactory?: IEventFactory | null | undefined): Observable2<any>;
680
+ invokeStream(methodIdentifier: string, args?: any[] | null | undefined, scope?: string | null | undefined, eventFactory?: IEventFactory | null | undefined): Observable3<any>;
627
681
  }
628
682
  /**
629
683
  * Provides the functionality to register services as well as create proxies for those services
@@ -716,6 +770,11 @@ interface IKinotic {
716
770
  serviceRegistry: IServiceRegistry;
717
771
  eventBus: IEventBus;
718
772
  /**
773
+ * The browser session of the page this client runs in, for a client that signs in through a gateway's
774
+ * REST login rather than with credentials of its own.
775
+ */
776
+ readonly session: ISession;
777
+ /**
719
778
  * The zone prefix every service published by this client registers under, such as
720
779
  * `app.<organizationId>.<applicationId>` for an application or `system` for a system
721
780
  * workload. Must be set from static configuration before service classes are instantiated.
@@ -765,9 +824,11 @@ declare class KinoticSingleton implements IKinotic {
765
824
  * The {@link ServiceRegistry} that is used to manage the services that are available
766
825
  */
767
826
  readonly serviceRegistry: ServiceRegistry;
827
+ private readonly _session;
768
828
  zonePrefix: string | null;
769
829
  defaultZone: string | null;
770
830
  constructor();
831
+ get session(): ISession;
771
832
  get eventBus(): IEventBus;
772
833
  set eventBus(eventBus: IEventBus);
773
834
  /**
@@ -1309,7 +1370,7 @@ declare class DefaultCRI implements CRI {
1309
1370
  private static parseRaw;
1310
1371
  private static buildRaw;
1311
1372
  }
1312
- import { Observable as Observable3 } from "rxjs";
1373
+ import { Observable as Observable4 } from "rxjs";
1313
1374
  import { Optional as Optional2 } from "typescript-optional";
1314
1375
  /**
1315
1376
  * Default IEvent implementation
@@ -1343,9 +1404,9 @@ declare class EventBus implements IEventBus {
1343
1404
  private readonly connectionEndedSubject;
1344
1405
  private static readonly REAP_DEBOUNCE_MS;
1345
1406
  constructor();
1346
- get connectionEnded(): Observable3<Error | null>;
1347
- get connectionEstablished(): Observable3<ConnectedInfo>;
1348
- get connectionAttemptFailed(): Observable3<void>;
1407
+ get connectionEnded(): Observable4<Error | null>;
1408
+ get connectionEstablished(): Observable4<ConnectedInfo>;
1409
+ get connectionAttemptFailed(): Observable4<void>;
1349
1410
  isConnectionActive(): boolean;
1350
1411
  isConnected(): boolean;
1351
1412
  connect(options: ConnectOptions): Promise<ConnectedInfo>;
@@ -1354,9 +1415,9 @@ declare class EventBus implements IEventBus {
1354
1415
  private serializeLifecycle;
1355
1416
  send(event: IEvent): void;
1356
1417
  request(event: IEvent): Promise<IEvent>;
1357
- requestStream(event: IEvent, sendControlEvents?: boolean): Observable3<IEvent>;
1418
+ requestStream(event: IEvent, sendControlEvents?: boolean): Observable4<IEvent>;
1358
1419
  listen(_serverInfo: ServerInfo): Promise<void>;
1359
- observe(cri: string): Observable3<IEvent>;
1420
+ observe(cri: string): Observable4<IEvent>;
1360
1421
  /**
1361
1422
  * Cancels a server stream whose reply arrived for a correlationId we no longer track. The server can't
1362
1423
  * detect this itself since all requests share one reply destination, so the cancel is sent to the
@@ -1487,4 +1548,4 @@ declare class ParticipantConstants {
1487
1548
  /** The clientId the test server's TestSecurityService maps to the ANONYMOUS role in core package tests. */
1488
1549
  static readonly CLI_PARTICIPANT_ID: string;
1489
1550
  }
1490
- export { AbstractIterablePage, AuthorizationException, BasicCredentialsResolver, BearerCredentialsResolver, CRI, ChainedCredentialsResolver, ConnectOptions, ConnectedInfo, Context, ContextInterceptor, CredentialsResolver, CrudServiceProxy, CrudServiceProxyFactory, CursorPageable, DataSourceUtils, DefaultCRI, Direction, EnvCredentialsResolver, Event, EventBus, EventConstants, FunctionalIterablePage, ICrudServiceProxy, ICrudServiceProxyFactory, IDataSource, IEditableDataSource, IEvent, IEventBus, IEventFactory, IKinotic, IParticipant, IServiceProxy, IServiceRegistry, IWebSocket, Identifiable, IterablePage, JsonEventFactory, Kinotic, KinoticPlugin, KinoticSingleton, NullHandling, OffsetPageable, Order, Page, Pageable, Participant, ParticipantConstants, Publish, ResolvedCredentials, RpcError, Scope, ScopeOptional, ServerInfo, ServiceContext, ServiceDirectoryEntry, ServiceIdentifier, ServiceRegistry, SessionCredentialsResolver, SessionKeepAliveMode, Sort, TextEventFactory, Version, WebSocketFactory, Zone, buildBrokerUrl, buildServerUrl, createCRI, declareServiceDefinitions, isAdvertised, receivesContext, scopeOptionalMethodNames, validateLabel, validateZone };
1551
+ export { AbstractIterablePage, AuthorizationException, BasicCredentialsResolver, BearerCredentialsResolver, CRI, ChainedCredentialsResolver, ConnectOptions, ConnectedInfo, Context, ContextInterceptor, CredentialsResolver, CrudServiceProxy, CrudServiceProxyFactory, CursorPageable, DataSourceUtils, DefaultCRI, Direction, EnvCredentialsResolver, Event, EventBus, EventConstants, FunctionalIterablePage, ICrudServiceProxy, ICrudServiceProxyFactory, IDataSource, IEditableDataSource, IEvent, IEventBus, IEventFactory, IKinotic, IParticipant, IServiceProxy, IServiceRegistry, ISession, IWebSocket, Identifiable, IterablePage, JsonEventFactory, Kinotic, KinoticPlugin, KinoticSingleton, NullHandling, OffsetPageable, Order, Page, Pageable, Participant, ParticipantConstants, Publish, ResolvedCredentials, RpcError, Scope, ScopeOptional, ServerInfo, ServiceContext, ServiceDirectoryEntry, ServiceIdentifier, ServiceRegistry, SessionCredentialsResolver, SessionEnd, SessionEndType, SessionKeepAliveMode, Sort, TextEventFactory, Version, WebSocketFactory, Zone, buildBrokerUrl, buildServerUrl, createCRI, declareServiceDefinitions, isAdvertised, receivesContext, scopeOptionalMethodNames, validateLabel, validateZone };
package/dist/index.js CHANGED
@@ -69,6 +69,17 @@ import { Subject } from "rxjs";
69
69
  import { skip } from "rxjs/operators";
70
70
  import { v4 as uuidv4 } from "uuid";
71
71
 
72
+ // packages/core/src/internal/api/SessionRoutes.ts
73
+ var SESSION_CHECK_PATH = "/api/auth/me";
74
+ var LOGOUT_PATH = "/api/auth/logout";
75
+ async function holdsLogin(server, signal) {
76
+ const response = await fetch(buildServerUrl(server, "http") + SESSION_CHECK_PATH, { credentials: "include", signal });
77
+ return response.status !== 401;
78
+ }
79
+ async function endLogin(server, signal) {
80
+ await fetch(buildServerUrl(server, "http") + LOGOUT_PATH, { method: "POST", credentials: "include", signal });
81
+ }
82
+
72
83
  // packages/core/src/internal/api/StompActivation.ts
73
84
  class StompActivation {
74
85
  _ended = false;
@@ -125,8 +136,6 @@ class StompActivation {
125
136
  }
126
137
 
127
138
  // packages/core/src/internal/api/StompConnectionManager.ts
128
- var SESSION_CHECK_PATH = "/api/auth/me";
129
-
130
139
  class StompConnectionManager {
131
140
  lastWebsocketError = null;
132
141
  maxConnectionAttemptsReached = false;
@@ -294,18 +303,14 @@ class StompConnectionManager {
294
303
  const usesPreparedSocket = userWebSocketFactory != null || headerAuth;
295
304
  const url = buildBrokerUrl(server);
296
305
  if (!usesPreparedSocket) {
297
- const sessionCheckUrl = buildServerUrl(server, "http") + SESSION_CHECK_PATH;
298
306
  try {
299
- const res = await fetch(sessionCheckUrl, {
300
- credentials: "include",
301
- signal: AbortSignal.any([activation.signal, AbortSignal.timeout(this.CONNECTION_TIMEOUT)])
302
- });
303
- if (res.status === 401) {
307
+ const signedIn = await holdsLogin(server, AbortSignal.any([activation.signal, AbortSignal.timeout(this.CONNECTION_TIMEOUT)]));
308
+ if (!signedIn) {
304
309
  this.failConnection(activation, new Error("Authentication required"));
305
310
  return;
306
311
  }
307
312
  } catch (e) {
308
- this.debugLogger("Session check at %s failed: %O", sessionCheckUrl, e);
313
+ this.debugLogger("Session check of %s failed: %O", server.host, e);
309
314
  }
310
315
  }
311
316
  if (options?.maxConnectionAttempts) {
@@ -833,8 +838,119 @@ class Util {
833
838
  }
834
839
  }
835
840
 
836
- // packages/core/src/api/ServiceRegistry.ts
841
+ // packages/core/src/internal/api/Session.ts
837
842
  import debug3 from "debug";
843
+ import { Subject as Subject3, Subscription as Subscription2 } from "rxjs";
844
+
845
+ // packages/core/src/api/security/SessionEndType.ts
846
+ var SessionEndType;
847
+ ((SessionEndType) => {
848
+ SessionEndType["SIGNED_OUT"] = "SIGNED_OUT";
849
+ SessionEndType["CONNECTION_LOST"] = "CONNECTION_LOST";
850
+ })(SessionEndType ||= {});
851
+
852
+ // packages/core/src/internal/api/Session.ts
853
+ var SESSION_REQUEST_TIMEOUT_MS = 5000;
854
+
855
+ class Session {
856
+ kinotic;
857
+ _connectedInfo = null;
858
+ server = null;
859
+ inFlight = Promise.resolve();
860
+ requests = 0;
861
+ subscriptions = new Subscription2;
862
+ endedSubject = new Subject3;
863
+ debugLogger = debug3("kinotic:session");
864
+ constructor(kinotic) {
865
+ this.kinotic = kinotic;
866
+ this.observe(kinotic.eventBus);
867
+ }
868
+ get connectedInfo() {
869
+ return this._connectedInfo;
870
+ }
871
+ get ended() {
872
+ return this.endedSubject.asObservable();
873
+ }
874
+ release() {
875
+ this._connectedInfo = null;
876
+ }
877
+ observe(eventBus) {
878
+ this.subscriptions.unsubscribe();
879
+ this.subscriptions = new Subscription2;
880
+ this.subscriptions.add(eventBus.connectionEstablished.subscribe((connectedInfo) => {
881
+ if (this._connectedInfo !== null) {
882
+ this._connectedInfo = connectedInfo;
883
+ }
884
+ }));
885
+ this.subscriptions.add(eventBus.connectionEnded.subscribe((reason) => {
886
+ if (this._connectedInfo !== null && !this.kinotic.eventBus.isConnectionActive()) {
887
+ this._connectedInfo = null;
888
+ if (reason !== null) {
889
+ this.classifyEnd(reason);
890
+ }
891
+ }
892
+ }));
893
+ }
894
+ resume(options) {
895
+ this.requests++;
896
+ return this.serialize(async () => {
897
+ this._connectedInfo = null;
898
+ try {
899
+ await this.kinotic.disconnect();
900
+ } catch (e) {
901
+ this.debugLogger("Closing the previous connection failed: %O", e);
902
+ }
903
+ const resolved = Util.resolveConnectOptions(options);
904
+ this.server = resolved.server;
905
+ let ret;
906
+ try {
907
+ ret = await this.kinotic.connect(resolved);
908
+ } catch (e) {
909
+ await this.kinotic.disconnect().catch((error) => this.debugLogger("Closing the failed connection failed: %O", error));
910
+ throw e;
911
+ }
912
+ this._connectedInfo = ret;
913
+ return ret;
914
+ });
915
+ }
916
+ logout() {
917
+ this.requests++;
918
+ return this.serialize(async () => {
919
+ this._connectedInfo = null;
920
+ const server = this.kinotic.eventBus.serverInfo ?? this.server ?? Util.resolveConnectOptions().server;
921
+ try {
922
+ await endLogin(server, AbortSignal.timeout(SESSION_REQUEST_TIMEOUT_MS));
923
+ } catch (e) {
924
+ this.debugLogger("The logout request failed: %O", e);
925
+ }
926
+ try {
927
+ await this.kinotic.disconnect();
928
+ } catch (e) {
929
+ this.debugLogger("Closing the connection failed: %O", e);
930
+ }
931
+ });
932
+ }
933
+ async classifyEnd(cause) {
934
+ const requestsAtEnd = this.requests;
935
+ let signedOut = false;
936
+ try {
937
+ signedOut = !await holdsLogin(this.server, AbortSignal.timeout(SESSION_REQUEST_TIMEOUT_MS));
938
+ } catch (e) {
939
+ this.debugLogger("The session check failed: %O", e);
940
+ }
941
+ if (this.requests === requestsAtEnd) {
942
+ this.endedSubject.next({ type: signedOut ? "SIGNED_OUT" /* SIGNED_OUT */ : "CONNECTION_LOST" /* CONNECTION_LOST */, cause });
943
+ }
944
+ }
945
+ serialize(operation) {
946
+ const result = this.inFlight.then(operation);
947
+ this.inFlight = result.catch(() => {});
948
+ return result;
949
+ }
950
+ }
951
+
952
+ // packages/core/src/api/ServiceRegistry.ts
953
+ import debug4 from "debug";
838
954
 
839
955
  // packages/core/src/api/event/DefaultCRI.ts
840
956
  var ZONE_DELIMITER = "~";
@@ -1210,7 +1326,7 @@ import opentelemetry, { context as context2, propagation as propagation2, trace,
1210
1326
  // packages/core/package.json
1211
1327
  var package_default = {
1212
1328
  name: "@kinotic-ai/core",
1213
- version: "5.0.0-beta.30",
1329
+ version: "5.0.0-beta.31",
1214
1330
  type: "module",
1215
1331
  files: [
1216
1332
  "dist"
@@ -1735,7 +1851,7 @@ class ServiceRegistry {
1735
1851
  supervisors = new Map;
1736
1852
  entries = new Map;
1737
1853
  contextInterceptor = null;
1738
- debugLogger = debug3("kinotic:serviceRegistry");
1854
+ debugLogger = debug4("kinotic:serviceRegistry");
1739
1855
  constructor(eventBus) {
1740
1856
  this._eventBus = eventBus;
1741
1857
  }
@@ -1864,11 +1980,16 @@ class ServiceProxy {
1864
1980
  class KinoticSingleton {
1865
1981
  _eventBus;
1866
1982
  serviceRegistry;
1983
+ _session;
1867
1984
  zonePrefix = null;
1868
1985
  defaultZone = null;
1869
1986
  constructor() {
1870
1987
  this._eventBus = new EventBus;
1871
1988
  this.serviceRegistry = new ServiceRegistry(this._eventBus);
1989
+ this._session = new Session(this);
1990
+ }
1991
+ get session() {
1992
+ return this._session;
1872
1993
  }
1873
1994
  get eventBus() {
1874
1995
  return this._eventBus;
@@ -1876,6 +1997,7 @@ class KinoticSingleton {
1876
1997
  set eventBus(eventBus) {
1877
1998
  this._eventBus = eventBus;
1878
1999
  this.serviceRegistry.eventBus = eventBus;
2000
+ this._session.observe(eventBus);
1879
2001
  }
1880
2002
  async connect(options) {
1881
2003
  const ret = await this._eventBus.connect(Util.resolveConnectOptions(options));
@@ -1883,6 +2005,7 @@ class KinoticSingleton {
1883
2005
  return ret;
1884
2006
  }
1885
2007
  disconnect(force) {
2008
+ this._session.release();
1886
2009
  return this._eventBus.disconnect(force);
1887
2010
  }
1888
2011
  serviceProxy(serviceIdentifier) {
@@ -2181,6 +2304,7 @@ export {
2181
2304
  ServiceIdentifier,
2182
2305
  ServiceRegistry,
2183
2306
  SessionCredentialsResolver,
2307
+ SessionEndType,
2184
2308
  SessionKeepAliveMode,
2185
2309
  Sort,
2186
2310
  TextEventFactory,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kinotic-ai/core",
3
- "version": "5.0.0-beta.30",
3
+ "version": "5.0.0-beta.31",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "dist"