channels.shared.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import type { CancellationToken, Event } from "./foundation.js";
  2. export interface IChannel {
  3. call<T>(command: string, arg?: any, cancellationToken?: CancellationToken): Promise<T>;
  4. listen<T>(event: string, arg?: any): Event<T>;
  5. }
  6. export interface IServerChannel<TContext = string> {
  7. call<T>(
  8. ctx: TContext,
  9. command: string,
  10. arg?: any,
  11. cancellationToken?: CancellationToken,
  12. ): Promise<T>;
  13. listen<T>(ctx: TContext, event: string, arg?: any): Event<T>;
  14. }
  15. export const enum RequestType {
  16. Promise = 100,
  17. PromiseCancel = 101,
  18. EventListen = 102,
  19. EventDispose = 103,
  20. }
  21. export const enum ResponseType {
  22. Initialize = 200,
  23. PromiseSuccess = 201,
  24. PromiseError = 202,
  25. PromiseErrorObj = 203,
  26. EventFire = 204,
  27. EventError = 205,
  28. }
  29. export type IRawResponse =
  30. | { type: ResponseType.Initialize }
  31. | { type: ResponseType.PromiseSuccess; id: number; data: any }
  32. | {
  33. type: ResponseType.PromiseError;
  34. id: number;
  35. data: {
  36. message: string;
  37. name: string;
  38. stack: string[] | undefined;
  39. code?: unknown;
  40. kind?: unknown;
  41. status?: unknown;
  42. retryAfterMs?: unknown;
  43. data?: unknown;
  44. detail?: unknown;
  45. details?: unknown;
  46. taskId?: unknown;
  47. traceId?: unknown;
  48. retryable?: unknown;
  49. profileId?: unknown;
  50. };
  51. }
  52. | { type: ResponseType.PromiseErrorObj; id: number; data: any }
  53. | { type: ResponseType.EventFire; id: number; data: any }
  54. | {
  55. type: ResponseType.EventError;
  56. id: number;
  57. data: { name: string; message: string; stack?: string[] };
  58. };
  59. export type IHandler = (response: IRawResponse) => void;
  60. export interface IChannelServer<TContext = string> {
  61. registerChannel(channelName: string, channel: IServerChannel<TContext>): void;
  62. ready?(): void;
  63. }
  64. export interface IChannelClient {
  65. getChannel<T extends IChannel>(channelName: string): T;
  66. }