im-connection-store-operations.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. import { KeyedOperationLane } from '@mavis/shared/keyed-operation-lane';
  2. import { mutateDurableYaml, readYamlDocument } from './durable-yaml.js';
  3. import type { ChannelPlatform } from './route-api.js';
  4. import {
  5. assertMessageFiltersDocument,
  6. findBindingForConnection,
  7. findBindingForTransportClient,
  8. invalidImStorage,
  9. readBindingData,
  10. readLegacyImMigrationTombstones,
  11. requireBindingSessionState,
  12. writeBindingData,
  13. } from './im-connection-store-data.js';
  14. import type { LocalImBindingOperations } from './im-connection-store-conversations.js';
  15. import {
  16. LocalImConnectionError,
  17. type LocalImAuthorizationState,
  18. type LocalImConnection,
  19. type LocalImConnectionDeletionSnapshot,
  20. type LocalImConnectionStoreOptions,
  21. type LocalImPhysicalBinding,
  22. } from './im-connection-types.js';
  23. /** Durable state and lanes shared by the focused IM store operation helpers. */
  24. export interface LocalImConnectionStoreOperations {
  25. readonly bindingsPath: string;
  26. readonly routesPath: string;
  27. readonly connectionLane: KeyedOperationLane<string>;
  28. readonly bindingLane: KeyedOperationLane<string>;
  29. readonly bindingSessionLane: KeyedOperationLane<string>;
  30. readonly authorizations: Map<string, LocalImAuthorizationState>;
  31. readonly options: LocalImConnectionStoreOptions;
  32. }
  33. export function getImAuthorization(
  34. operations: LocalImConnectionStoreOperations,
  35. connectionId: string,
  36. ): LocalImAuthorizationState | undefined {
  37. const authorization = operations.authorizations.get(connectionId);
  38. if (!authorization) return undefined;
  39. if (
  40. authorization.expiresAt !== undefined &&
  41. authorization.expiresAt <= operations.options.nowMs()
  42. ) {
  43. operations.authorizations.delete(connectionId);
  44. return undefined;
  45. }
  46. return authorization;
  47. }
  48. export function findImAuthorizationByPlatformSession(
  49. operations: LocalImConnectionStoreOperations,
  50. channel: ChannelPlatform,
  51. platformSessionId: string,
  52. ): string | undefined {
  53. for (const [connectionId] of operations.authorizations) {
  54. const authorization = getImAuthorization(operations, connectionId);
  55. if (
  56. authorization?.channel === channel &&
  57. authorization.platformSessionId === platformSessionId
  58. ) {
  59. return connectionId;
  60. }
  61. }
  62. return undefined;
  63. }
  64. export async function getImConnection(
  65. operations: LocalImConnectionStoreOperations,
  66. connectionId: string,
  67. ): Promise<LocalImConnection | undefined> {
  68. return readBindingData(
  69. await readYamlDocument(operations.bindingsPath),
  70. operations.options.nowMs(),
  71. ).connections.get(connectionId);
  72. }
  73. export async function requireImConnection(
  74. operations: LocalImConnectionStoreOperations,
  75. connectionId: string,
  76. ): Promise<LocalImConnection> {
  77. const connection = await getImConnection(operations, connectionId);
  78. if (!connection) {
  79. throw new LocalImConnectionError(
  80. 404,
  81. 'CHANNEL_CONNECTION_NOT_FOUND',
  82. 'Channel Connection not found.',
  83. );
  84. }
  85. return connection;
  86. }
  87. export function assertImBindingRuntimeState(
  88. binding: LocalImPhysicalBinding,
  89. connection: LocalImConnection,
  90. ): ReturnType<typeof requireBindingSessionState> {
  91. if (binding.connectionId !== connection.connectionId || binding.channel !== connection.channel) {
  92. throw invalidImStorage('physicalBindings', binding.bindingId);
  93. }
  94. const state = requireBindingSessionState(binding);
  95. if (state.resolvedProjectKey !== connection.resolvedProjectKey) {
  96. throw new LocalImConnectionError(
  97. 409,
  98. 'CHANNEL_IM_BINDING_PROJECT_MISMATCH',
  99. 'The IM Binding Project does not match its Connection.',
  100. );
  101. }
  102. return state;
  103. }
  104. export async function readImBindingState(operations: LocalImConnectionStoreOperations) {
  105. const bindingsDocument = await readYamlDocument(operations.bindingsPath);
  106. const bindingData = readBindingData(bindingsDocument, operations.options.nowMs());
  107. const tombstones = readLegacyImMigrationTombstones(bindingsDocument, operations.options.nowMs());
  108. return { bindingData, tombstones };
  109. }
  110. export function bindingConversationOperations(
  111. operations: LocalImConnectionStoreOperations,
  112. ): LocalImBindingOperations {
  113. return {
  114. bindingsPath: operations.bindingsPath,
  115. bindingSessionLane: operations.bindingSessionLane,
  116. options: operations.options,
  117. };
  118. }
  119. export async function clearImPendingLegacyMigration(
  120. operations: LocalImConnectionStoreOperations,
  121. connectionId: string,
  122. ): Promise<void> {
  123. await mutateDurableYaml(operations.bindingsPath, (document) => {
  124. const data = readBindingData(document, operations.options.nowMs());
  125. const connection = data.connections.get(connectionId);
  126. if (!connection?.pendingLegacyRouteKeys?.length) {
  127. return { changed: false, value: undefined };
  128. }
  129. data.connections.set(connectionId, {
  130. ...connection,
  131. pendingLegacyRouteKeys: undefined,
  132. updatedAt: operations.options.nowMs(),
  133. });
  134. writeBindingData(document, data);
  135. return { changed: true, value: undefined };
  136. });
  137. }
  138. export async function getImBindingForConnection(
  139. operations: LocalImConnectionStoreOperations,
  140. connectionId: string,
  141. ): Promise<LocalImPhysicalBinding | undefined> {
  142. const data = readBindingData(
  143. await readYamlDocument(operations.bindingsPath),
  144. operations.options.nowMs(),
  145. );
  146. return findBindingForConnection(data.physicalBindings, connectionId);
  147. }
  148. export async function getImBindingForTransportClient(
  149. operations: LocalImConnectionStoreOperations,
  150. channel: ChannelPlatform,
  151. clientName: string,
  152. ): Promise<LocalImPhysicalBinding | undefined> {
  153. const data = readBindingData(
  154. await readYamlDocument(operations.bindingsPath),
  155. operations.options.nowMs(),
  156. );
  157. return findBindingForTransportClient(data.physicalBindings, channel, clientName);
  158. }
  159. export async function getImDeletionSnapshot(
  160. operations: LocalImConnectionStoreOperations,
  161. connectionId: string,
  162. ): Promise<LocalImConnectionDeletionSnapshot | undefined> {
  163. const document = await readYamlDocument(operations.bindingsPath);
  164. const data = readBindingData(document, operations.options.nowMs());
  165. const connection = data.connections.get(connectionId);
  166. if (!connection) return undefined;
  167. const binding = findBindingForConnection(data.physicalBindings, connectionId);
  168. // Validate before external cleanup, so malformed local data cannot cause a partial unbind.
  169. if (binding) assertMessageFiltersDocument(document);
  170. const authorization = getImAuthorization(operations, connectionId);
  171. return {
  172. connection,
  173. ...(binding ? { binding } : {}),
  174. ...(authorization ? { authorization } : {}),
  175. };
  176. }
  177. export function normalizeLegacyRouteKeys(keys: readonly string[] | undefined): readonly string[] {
  178. if (!keys) return [];
  179. const normalized = keys.map((key) => key.trim());
  180. if (normalized.some((key) => !key)) {
  181. throw new LocalImConnectionError(
  182. 400,
  183. 'CHANNEL_CONNECTION_MIGRATION_INVALID',
  184. 'Legacy migration receipt keys must be non-empty.',
  185. );
  186. }
  187. return [...new Set(normalized)].sort((left, right) => left.localeCompare(right));
  188. }
  189. export function sameLegacyRouteKeys(
  190. current: readonly string[] | undefined,
  191. next: readonly string[],
  192. ): boolean {
  193. const normalizedCurrent = normalizeLegacyRouteKeys(current);
  194. return (
  195. normalizedCurrent.length === next.length &&
  196. normalizedCurrent.every((key, index) => key === next[index])
  197. );
  198. }