matrix-js-sdk 37.2.0 → 37.3.0-rc.0

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.
Files changed (83) hide show
  1. package/git-revision.txt +1 -1
  2. package/lib/client.d.ts +8 -2
  3. package/lib/client.d.ts.map +1 -1
  4. package/lib/client.js +11 -3
  5. package/lib/client.js.map +1 -1
  6. package/lib/common-crypto/CryptoBackend.d.ts +8 -0
  7. package/lib/common-crypto/CryptoBackend.d.ts.map +1 -1
  8. package/lib/common-crypto/CryptoBackend.js.map +1 -1
  9. package/lib/http-api/errors.d.ts +8 -0
  10. package/lib/http-api/errors.d.ts.map +1 -1
  11. package/lib/http-api/errors.js +14 -0
  12. package/lib/http-api/errors.js.map +1 -1
  13. package/lib/http-api/fetch.d.ts.map +1 -1
  14. package/lib/http-api/fetch.js +3 -3
  15. package/lib/http-api/fetch.js.map +1 -1
  16. package/lib/matrixrtc/LegacyMembershipManager.d.ts +9 -1
  17. package/lib/matrixrtc/LegacyMembershipManager.d.ts.map +1 -1
  18. package/lib/matrixrtc/LegacyMembershipManager.js +20 -0
  19. package/lib/matrixrtc/LegacyMembershipManager.js.map +1 -1
  20. package/lib/matrixrtc/MatrixRTCSession.d.ts.map +1 -1
  21. package/lib/matrixrtc/MatrixRTCSession.js.map +1 -1
  22. package/lib/matrixrtc/NewMembershipManager.d.ts +7 -58
  23. package/lib/matrixrtc/NewMembershipManager.d.ts.map +1 -1
  24. package/lib/matrixrtc/NewMembershipManager.js +130 -137
  25. package/lib/matrixrtc/NewMembershipManager.js.map +1 -1
  26. package/lib/matrixrtc/NewMembershipManagerActionScheduler.js +3 -3
  27. package/lib/matrixrtc/NewMembershipManagerActionScheduler.js.map +1 -1
  28. package/lib/matrixrtc/index.d.ts +1 -0
  29. package/lib/matrixrtc/index.d.ts.map +1 -1
  30. package/lib/matrixrtc/index.js +1 -0
  31. package/lib/matrixrtc/index.js.map +1 -1
  32. package/lib/matrixrtc/types.d.ts +77 -1
  33. package/lib/matrixrtc/types.d.ts.map +1 -1
  34. package/lib/matrixrtc/types.js +40 -1
  35. package/lib/matrixrtc/types.js.map +1 -1
  36. package/lib/models/room-summary.d.ts +30 -0
  37. package/lib/models/room-summary.d.ts.map +1 -1
  38. package/lib/models/room-summary.js +11 -0
  39. package/lib/models/room-summary.js.map +1 -1
  40. package/lib/models/room.d.ts +37 -1
  41. package/lib/models/room.d.ts.map +1 -1
  42. package/lib/models/room.js +133 -28
  43. package/lib/models/room.js.map +1 -1
  44. package/lib/oidc/tokenRefresher.d.ts.map +1 -1
  45. package/lib/oidc/tokenRefresher.js +8 -1
  46. package/lib/oidc/tokenRefresher.js.map +1 -1
  47. package/lib/pushprocessor.d.ts +10 -1
  48. package/lib/pushprocessor.d.ts.map +1 -1
  49. package/lib/pushprocessor.js +24 -9
  50. package/lib/pushprocessor.js.map +1 -1
  51. package/lib/rust-crypto/OutgoingRequestProcessor.d.ts.map +1 -1
  52. package/lib/rust-crypto/OutgoingRequestProcessor.js +6 -1
  53. package/lib/rust-crypto/OutgoingRequestProcessor.js.map +1 -1
  54. package/lib/rust-crypto/rust-crypto.d.ts +4 -1
  55. package/lib/rust-crypto/rust-crypto.d.ts.map +1 -1
  56. package/lib/rust-crypto/rust-crypto.js +55 -46
  57. package/lib/rust-crypto/rust-crypto.js.map +1 -1
  58. package/lib/sliding-sync-sdk.d.ts.map +1 -1
  59. package/lib/sliding-sync-sdk.js +86 -75
  60. package/lib/sliding-sync-sdk.js.map +1 -1
  61. package/lib/sliding-sync.d.ts +23 -60
  62. package/lib/sliding-sync.d.ts.map +1 -1
  63. package/lib/sliding-sync.js +62 -321
  64. package/lib/sliding-sync.js.map +1 -1
  65. package/package.json +6 -6
  66. package/src/client.ts +12 -5
  67. package/src/common-crypto/CryptoBackend.ts +9 -0
  68. package/src/http-api/errors.ts +14 -0
  69. package/src/http-api/fetch.ts +3 -4
  70. package/src/matrixrtc/LegacyMembershipManager.ts +27 -1
  71. package/src/matrixrtc/MatrixRTCSession.ts +2 -1
  72. package/src/matrixrtc/NewMembershipManager.ts +120 -165
  73. package/src/matrixrtc/NewMembershipManagerActionScheduler.ts +3 -3
  74. package/src/matrixrtc/index.ts +1 -0
  75. package/src/matrixrtc/types.ts +84 -1
  76. package/src/models/room-summary.ts +31 -0
  77. package/src/models/room.ts +133 -23
  78. package/src/oidc/tokenRefresher.ts +8 -2
  79. package/src/pushprocessor.ts +25 -16
  80. package/src/rust-crypto/OutgoingRequestProcessor.ts +6 -0
  81. package/src/rust-crypto/rust-crypto.ts +7 -1
  82. package/src/sliding-sync-sdk.ts +28 -28
  83. package/src/sliding-sync.ts +38 -329
@@ -1 +1 @@
1
- {"version":3,"file":"NewMembershipManager.js","names":["EventType","UpdateDelayedEventAction","UnsupportedDelayedEventsEndpointError","ConnectionError","HTTPError","MatrixError","logger","rootLogger","defer","DEFAULT_EXPIRE_DURATION","isLivekitFocusActive","ActionScheduler","getChild","MembershipActionType","Status","MembershipManager","isJoined","activated","join","fociPreferred","focusActive","onError","scheduler","running","error","leavePromiseDefer","undefined","state","defaultState","startWithJoin","then","_this$leavePromiseDef","resolve","catch","e","finally","leave","timeout","warn","Promise","initiateLeave","setTimeout","_this$leavePromiseDef2","promise","onRTCSessionMemberUpdate","memberships","_this","_asyncToGenerator","isMyMembership","m","sender","client","getUserId","deviceId","getDeviceId","some","sendingMembershipActions","SendFirstDelayedEvent","SendJoinEvent","actions","find","a","includes","type","hasMemberStateEvent","initiateJoin","getActiveFocus","focus_selection","oldestMembership","getOldestMembership","getPreferredFoci","constructor","joinConfig","room","_defineProperty","oldStatus","debug","concat","status","membershipLoopHandler","userId","Error","stateKey","makeMembershipStateKey","delayId","startTime","rateLimitRetries","Map","networkErrorRetries","expireUpdateIterations","callMemberEventRetryDelayMinimum","_this$joinConfig$call","_this$joinConfig","membershipEventExpiryTimeout","_this$joinConfig$memb","_this$joinConfig2","membershipExpiryTimeout","membershipEventExpiryTimeoutHeadroom","_this$joinConfig$memb2","_this$joinConfig3","membershipExpiryTimeoutHeadroom","computeNextExpiryActionTs","iteration","membershipServerSideExpiryTimeout","_ref","_this$membershipServe","_this$joinConfig4","membershipServerSideExpiryTimeoutOverride","membershipKeepAlivePeriod","_this$joinConfig$memb3","_this$joinConfig5","maximumRateLimitRetryCount","_this$joinConfig$maxi","_this$joinConfig6","maximumNetworkErrorRetryCount","_this$joinConfig$maxi2","_this$joinConfig7","_this2","sendFirstDelayedLeaveEvent","cancelKnownDelayIdBeforeSendFirstDelayedEvent","RestartDelayedEvent","createInsertActionUpdate","SendMainDelayedEvent","restartDelayedEvent","sendMainDelayedEvent","SendScheduledDelayedLeaveEvent","replace","sendScheduledDelayedLeaveEventOrFallbackToSendLeaveEvent","SendLeaveEvent","sendJoinEvent","UpdateExpiry","updateExpiryOnJoinedEvent","sendFallbackLeaveEvent","_this3","_unstable_sendDelayedStateEvent","roomId","delay","GroupCallMemberPrefix","response","set","delay_id","repeatActionType","manageMaxDelayExceededSituation","update","actionUpdateFromErrors","isUnsupportedDelayedEndpoint","info","_this4","_unstable_updateDelayedEvent","Cancel","resetRateLimitCounter","createReplaceActionUpdate","isNotFoundError","_this5","Restart","_this6","_this7","Send","_this8","sendStateEvent","makeMyMembership","Date","now","insert","ts","_this9","nextExpireUpdateIteration","_this10","localUserId","localDeviceId","exec","getVersion","expires","_this$fociPreferred","call_id","scope","application","device_id","focus_active","foci_preferred","errcode","data","maxDelayAllowed","method","updateLimit","actionUpdateFromRateLimitError","updateNetwork","actionUpdateFromNetworkErrorRetry","_this$state$rateLimit","isRateLimitError","get","resendDelay","defaultMs","_error$getRetryAfterM","getRetryAfterMs","_this$state$networkEr","retries","retryDurationString","retryCounterString","name","message","httpStatus","length","Connecting","Connected","Disconnecting","types","map","filter","t","Disconnected","Unknown","offset"],"sources":["../../src/matrixrtc/NewMembershipManager.ts"],"sourcesContent":["/*\nCopyright 2025 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { EventType } from \"../@types/event.ts\";\nimport { UpdateDelayedEventAction } from \"../@types/requests.ts\";\nimport { type MatrixClient } from \"../client.ts\";\nimport { UnsupportedDelayedEventsEndpointError } from \"../errors.ts\";\nimport { ConnectionError, HTTPError, MatrixError } from \"../http-api/errors.ts\";\nimport { logger as rootLogger } from \"../logger.ts\";\nimport { type Room } from \"../models/room.ts\";\nimport { defer, type IDeferred } from \"../utils.ts\";\nimport { type CallMembership, DEFAULT_EXPIRE_DURATION, type SessionMembershipData } from \"./CallMembership.ts\";\nimport { type Focus } from \"./focus.ts\";\nimport { isLivekitFocusActive } from \"./LivekitFocus.ts\";\nimport { type MembershipConfig } from \"./MatrixRTCSession.ts\";\nimport { ActionScheduler, type ActionUpdate } from \"./NewMembershipManagerActionScheduler.ts\";\n\nconst logger = rootLogger.getChild(\"MatrixRTCSession\");\n\n/**\n * This interface defines what a MembershipManager uses and exposes.\n * This interface is what we use to write tests and allows changing the actual implementation\n * without breaking tests because of some internal method renaming.\n *\n * @internal\n */\nexport interface IMembershipManager {\n /**\n * If we are trying to join, or have successfully joined the session.\n * It does not reflect if the room state is already configured to represent us being joined.\n * It only means that the Manager should be trying to connect or to disconnect running.\n * The Manager is still running right after isJoined becomes false to send the disconnect events.\n * (A more accurate name would be `isActivated`)\n * @returns true if we intend to be participating in the MatrixRTC session\n */\n isJoined(): boolean;\n /**\n * Start sending all necessary events to make this user participate in the RTC session.\n * @param fociPreferred the list of preferred foci to use in the joined RTC membership event.\n * @param fociActive the active focus to use in the joined RTC membership event.\n * @throws can throw if it exceeds a configured maximum retry.\n */\n join(fociPreferred: Focus[], fociActive?: Focus, onError?: (error: unknown) => void): void;\n /**\n * Send all necessary events to make this user leave the RTC session.\n * @param timeout the maximum duration in ms until the promise is forced to resolve.\n * @returns It resolves with true in case the leave was sent successfully.\n * It resolves with false in case we hit the timeout before sending successfully.\n */\n leave(timeout?: number): Promise<boolean>;\n /**\n * Call this if the MatrixRTC session members have changed.\n */\n onRTCSessionMemberUpdate(memberships: CallMembership[]): Promise<void>;\n /**\n * The used active focus in the currently joined session.\n * @returns the used active focus in the currently joined session or undefined if not joined.\n */\n getActiveFocus(): Focus | undefined;\n}\n\n/* MembershipActionTypes:\n ▼\n ┌─────────────────────┐\n │SendFirstDelayedEvent│\n └─────────────────────┘\n │\n ▼\n ┌─────────────┐\n ┌────────────│SendJoinEvent│────────────┐\n │ └─────────────┘ │\n │ ┌─────┐ ┌──────┐ │ ┌──────┐\n ▼ ▼ │ │ ▼ ▼ ▼ │\n┌────────────┐ │ │ ┌───────────────────┐ │\n│UpdateExpiry│ │ │ │RestartDelayedEvent│ │\n└────────────┘ │ │ └───────────────────┘ │\n │ │ │ │ │ │\n └─────┘ └──────┘ │ │\n │ │\n ┌────────────────────┐ │ │\n │SendMainDelayedEvent│◄───────┘ │\n └───────────────────┬┘ │\n │ │\n └─────────────────────┘\n STOP ALL ABOVE\n ▼\n ┌───────────────────────────────┐\n │ SendScheduledDelayedLeaveEvent│\n └───────────────────────────────┘\n │\n ▼\n ┌──────────────┐\n │SendLeaveEvent│\n └──────────────┘\n\n*/\n/**\n * The different types of actions the MembershipManager can take.\n * @internal\n */\nexport enum MembershipActionType {\n SendFirstDelayedEvent = \"SendFirstDelayedEvent\",\n // -> MembershipActionType.SendJoinEvent if successful\n // -> DelayedLeaveActionType.SendFirstDelayedEvent on error, retry sending the first delayed event.\n SendJoinEvent = \"SendJoinEvent\",\n // -> MembershipActionType.SendJoinEvent if we run into a rate limit and need to retry\n // -> MembershipActionType.Update if we successfully send the join event then schedule the expire event update\n // -> DelayedLeaveActionType.RestartDelayedEvent to recheck the delayed event\n RestartDelayedEvent = \"RestartDelayedEvent\",\n // -> DelayedLeaveActionType.SendMainDelayedEvent on missing delay id but there is a rtc state event\n // -> DelayedLeaveActionType.SendFirstDelayedEvent on missing delay id and there is no state event\n // -> DelayedLeaveActionType.RestartDelayedEvent on success we schedule the next restart\n UpdateExpiry = \"UpdateExpiry\",\n // -> MembershipActionType.Update if the timeout has passed so the next update is required.\n SendMainDelayedEvent = \"SendMainDelayedEvent\",\n // -> DelayedLeaveActionType.RestartDelayedEvent on success start updating the delayed event\n // -> DelayedLeaveActionType.SendMainDelayedEvent on error try again\n SendScheduledDelayedLeaveEvent = \"SendScheduledDelayedLeaveEvent\",\n // -> MembershipActionType.SendLeaveEvent on failiour (not found) we need to send the leave manually and cannot use the scheduled delayed event\n // -> DelayedLeaveActionType.SendScheduledDelayedLeaveEvent on error we try again.\n SendLeaveEvent = \"SendLeaveEvent\",\n // -> MembershipActionType.SendLeaveEvent\n}\n\n/**\n * @internal\n */\nexport interface ActionSchedulerState {\n /** The delayId we got when successfully sending the delayed leave event.\n * Gets set to undefined if the server claims it cannot find the delayed event anymore. */\n delayId?: string;\n /** Stores how often we have update the `expires` field.\n * `expireUpdateIterations` * `membershipEventExpiryTimeout` resolves to the value the expires field should contain next */\n expireUpdateIterations: number;\n /** The time at which we send the first state event. The time the call started from the DAG point of view.\n * This is used to compute the local sleep timestamps when to next update the member event with a new expires value. */\n startTime: number;\n /** The manager is in the state where its actually connected to the session. */\n hasMemberStateEvent: boolean;\n // There can be multiple retries at once so we need to store counters per action\n // e.g. the send update membership and the restart delayed could be rate limited at the same time.\n /** Retry counter for rate limits */\n rateLimitRetries: Map<MembershipActionType, number>;\n /** Retry counter for other errors */\n networkErrorRetries: Map<MembershipActionType, number>;\n}\n\nenum Status {\n Disconnected = \"Disconnected\",\n Connecting = \"Connecting\",\n ConnectingFailed = \"ConnectingFailed\",\n Connected = \"Connected\",\n Reconnecting = \"Reconnecting\",\n Disconnecting = \"Disconnecting\",\n Stuck = \"Stuck\",\n Unknown = \"Unknown\",\n}\n\n/**\n * This class is responsible for sending all events relating to the own membership of a matrixRTC call.\n * It has the following tasks:\n * - Send the users leave delayed event before sending the membership\n * - Send the users membership if the state machine is started\n * - Check if the delayed event was canceled due to sending the membership\n * - update the delayed event (`restart`)\n * - Update the state event every ~5h = `DEFAULT_EXPIRE_DURATION` (so it does not get treated as expired)\n * - When the state machine is stopped:\n * - Disconnect the member\n * - Stop the timer for the delay refresh\n * - Stop the timer for updating the state event\n */\nexport class MembershipManager implements IMembershipManager {\n private activated = false;\n public isJoined(): boolean {\n return this.activated;\n }\n\n /**\n * Puts the MembershipManager in a state where it tries to be joined.\n * It will send delayed events and membership events\n * @param fociPreferred\n * @param focusActive\n * @param onError This will be called once the membership manager encounters an unrecoverable error.\n * This should bubble up the the frontend to communicate that the call does not work in the current environment.\n */\n public join(fociPreferred: Focus[], focusActive?: Focus, onError?: (error: unknown) => void): void {\n if (this.scheduler.running) {\n logger.error(\"MembershipManager is already running. Ignoring join request.\");\n return;\n }\n this.fociPreferred = fociPreferred;\n this.focusActive = focusActive;\n this.leavePromiseDefer = undefined;\n this.activated = true;\n\n this.state = MembershipManager.defaultState;\n\n this.scheduler\n .startWithJoin()\n .then(() => {\n if (!this.scheduler.running) {\n this.leavePromiseDefer?.resolve(true);\n this.leavePromiseDefer = undefined;\n }\n })\n .catch((e) => {\n logger.error(\"MembershipManager stopped because: \", e);\n onError?.(e);\n })\n // Should already be set to false when calling `leave` in non error cases.\n .finally(() => (this.activated = false));\n }\n\n /**\n * Leave from the call (Send an rtc session event with content: `{}`)\n * @param timeout the maximum duration this promise will take to resolve\n * @returns true if it managed to leave and false if the timeout condition happened.\n */\n public leave(timeout?: number): Promise<boolean> {\n if (!this.scheduler.running) {\n logger.warn(\"Called MembershipManager.leave() even though the MembershipManager is not running\");\n return Promise.resolve(true);\n }\n\n // We use the promise to track if we already scheduled a leave event\n // So we do not check scheduler.actions/scheduler.insertions\n if (!this.leavePromiseDefer) {\n // reset scheduled actions so we will not do any new actions.\n this.leavePromiseDefer = defer<boolean>();\n this.activated = false;\n this.scheduler.initiateLeave();\n if (timeout) setTimeout(() => this.leavePromiseDefer?.resolve(false), timeout);\n }\n return this.leavePromiseDefer.promise;\n }\n private leavePromiseDefer?: IDeferred<boolean>;\n\n public async onRTCSessionMemberUpdate(memberships: CallMembership[]): Promise<void> {\n const isMyMembership = (m: CallMembership): boolean =>\n m.sender === this.client.getUserId() && m.deviceId === this.client.getDeviceId();\n\n if (this.isJoined() && !memberships.some(isMyMembership)) {\n // If one of these actions are scheduled or are getting inserted in the next iteration, we should already\n // take care of our missing membership.\n const sendingMembershipActions = [\n MembershipActionType.SendFirstDelayedEvent,\n MembershipActionType.SendJoinEvent,\n ];\n logger.warn(\"Missing own membership: force re-join\");\n if (this.scheduler.actions.find((a) => sendingMembershipActions.includes(a.type as MembershipActionType))) {\n logger.error(\n \"NewMembershipManger tried adding another `SendFirstDelayedEvent` actions even though we already have one in the Queue\\nActionQueueOnMemberUpdate:\",\n this.scheduler.actions,\n );\n } else {\n // Only react to our own membership missing if we have not already scheduled sending a new membership DirectMembershipManagerAction.Join\n this.state.hasMemberStateEvent = false;\n this.scheduler.initiateJoin();\n }\n }\n return Promise.resolve();\n }\n\n public getActiveFocus(): Focus | undefined {\n if (this.focusActive) {\n // A livekit active focus\n if (isLivekitFocusActive(this.focusActive)) {\n if (this.focusActive.focus_selection === \"oldest_membership\") {\n const oldestMembership = this.getOldestMembership();\n return oldestMembership?.getPreferredFoci()[0];\n }\n } else {\n logger.warn(\"Unknown own ActiveFocus type. This makes it impossible to connect to an SFU.\");\n }\n } else {\n // We do not understand the membership format (could be legacy). We default to oldestMembership\n // Once there are other methods this is a hard error!\n const oldestMembership = this.getOldestMembership();\n return oldestMembership?.getPreferredFoci()[0];\n }\n }\n\n /**\n * @throws if the client does not return user or device id.\n * @param joinConfig\n * @param room\n * @param client\n * @param getOldestMembership\n */\n public constructor(\n private joinConfig: MembershipConfig | undefined,\n private room: Pick<Room, \"getLiveTimeline\" | \"roomId\" | \"getVersion\">,\n private client: Pick<\n MatrixClient,\n | \"getUserId\"\n | \"getDeviceId\"\n | \"sendStateEvent\"\n | \"_unstable_sendDelayedStateEvent\"\n | \"_unstable_updateDelayedEvent\"\n >,\n private getOldestMembership: () => CallMembership | undefined,\n ) {\n const [userId, deviceId] = [this.client.getUserId(), this.client.getDeviceId()];\n if (userId === null) throw Error(\"Missing userId in client\");\n if (deviceId === null) throw Error(\"Missing deviceId in client\");\n this.deviceId = deviceId;\n this.stateKey = this.makeMembershipStateKey(userId, deviceId);\n this.state = MembershipManager.defaultState;\n }\n\n // MembershipManager mutable state.\n private state: ActionSchedulerState;\n private static get defaultState(): ActionSchedulerState {\n return {\n hasMemberStateEvent: false,\n delayId: undefined,\n\n startTime: 0,\n rateLimitRetries: new Map(),\n networkErrorRetries: new Map(),\n expireUpdateIterations: 1,\n };\n }\n // Membership Event static parameters:\n private deviceId: string;\n private stateKey: string;\n private fociPreferred?: Focus[];\n private focusActive?: Focus;\n\n // Config:\n private membershipServerSideExpiryTimeoutOverride?: number;\n\n private get callMemberEventRetryDelayMinimum(): number {\n return this.joinConfig?.callMemberEventRetryDelayMinimum ?? 3_000;\n }\n private get membershipEventExpiryTimeout(): number {\n return this.joinConfig?.membershipExpiryTimeout ?? DEFAULT_EXPIRE_DURATION;\n }\n private get membershipEventExpiryTimeoutHeadroom(): number {\n return this.joinConfig?.membershipExpiryTimeoutHeadroom ?? 5_000;\n }\n private computeNextExpiryActionTs(iteration: number): number {\n return (\n this.state.startTime +\n this.membershipEventExpiryTimeout * iteration -\n this.membershipEventExpiryTimeoutHeadroom\n );\n }\n private get membershipServerSideExpiryTimeout(): number {\n return (\n this.membershipServerSideExpiryTimeoutOverride ??\n this.joinConfig?.membershipServerSideExpiryTimeout ??\n 8_000\n );\n }\n private get membershipKeepAlivePeriod(): number {\n return this.joinConfig?.membershipKeepAlivePeriod ?? 5_000;\n }\n private get maximumRateLimitRetryCount(): number {\n return this.joinConfig?.maximumRateLimitRetryCount ?? 10;\n }\n private get maximumNetworkErrorRetryCount(): number {\n return this.joinConfig?.maximumNetworkErrorRetryCount ?? 10;\n }\n\n // Scheduler:\n private oldStatus?: Status;\n private scheduler = new ActionScheduler((type): Promise<ActionUpdate> => {\n if (this.oldStatus) {\n // we put this at the beginning of the actions scheduler loop handle callback since it is a loop this\n // is equivalent to running it at the end of the loop. (just after applying the status/action list changes)\n logger.debug(`MembershipManager applied action changes. Status: ${this.oldStatus} -> ${this.status}`);\n }\n this.oldStatus = this.status;\n logger.debug(`MembershipManager before processing action. status=${this.oldStatus}`);\n return this.membershipLoopHandler(type);\n });\n\n // LOOP HANDLER:\n private async membershipLoopHandler(type: MembershipActionType): Promise<ActionUpdate> {\n this.oldStatus = this.status;\n switch (type) {\n case MembershipActionType.SendFirstDelayedEvent: {\n // Before we start we check if we come from a state where we have a delay id.\n if (!this.state.delayId) {\n return this.sendFirstDelayedLeaveEvent(); // Normal case without any previous delayed id.\n } else {\n // This can happen if someone else (or another client) removes our own membership event.\n // It will trigger `onRTCSessionMemberUpdate` queue `MembershipActionType.SendFirstDelayedEvent`.\n // We might still have our delayed event from the previous participation and dependent on the server this might not\n // get automatically removed if the state changes. Hence It would remove our membership unexpectedly shortly after the rejoin.\n //\n // In this block we will try to cancel this delayed event before setting up a new one.\n\n return this.cancelKnownDelayIdBeforeSendFirstDelayedEvent(this.state.delayId);\n }\n }\n case MembershipActionType.RestartDelayedEvent: {\n if (!this.state.delayId) {\n // Delay id got reset. This action was used to check if the hs canceled the delayed event when the join state got sent.\n return createInsertActionUpdate(\n this.state.hasMemberStateEvent\n ? MembershipActionType.SendMainDelayedEvent\n : MembershipActionType.SendFirstDelayedEvent,\n );\n }\n return this.restartDelayedEvent(this.state.delayId);\n }\n case MembershipActionType.SendMainDelayedEvent: {\n return this.sendMainDelayedEvent();\n }\n case MembershipActionType.SendScheduledDelayedLeaveEvent: {\n // We are already good\n if (!this.state.hasMemberStateEvent) {\n return { replace: [] };\n }\n if (this.state.delayId) {\n return this.sendScheduledDelayedLeaveEventOrFallbackToSendLeaveEvent(this.state.delayId);\n } else {\n return createInsertActionUpdate(MembershipActionType.SendLeaveEvent);\n }\n }\n case MembershipActionType.SendJoinEvent: {\n return this.sendJoinEvent();\n }\n case MembershipActionType.UpdateExpiry: {\n return this.updateExpiryOnJoinedEvent();\n }\n case MembershipActionType.SendLeaveEvent: {\n // We are good already\n if (!this.state.hasMemberStateEvent) {\n return { replace: [] };\n }\n // This is only a fallback in case we do not have working delayed events support.\n // first we should try to just send the scheduled leave event\n return this.sendFallbackLeaveEvent();\n }\n }\n }\n\n // HANDLERS (used in the membershipLoopHandler)\n private async sendFirstDelayedLeaveEvent(): Promise<ActionUpdate> {\n return await this.client\n ._unstable_sendDelayedStateEvent(\n this.room.roomId,\n {\n delay: this.membershipServerSideExpiryTimeout,\n },\n EventType.GroupCallMemberPrefix,\n {}, // leave event\n this.stateKey,\n )\n .then((response) => {\n // On success we reset retries and set delayId.\n this.state.rateLimitRetries.set(MembershipActionType.SendFirstDelayedEvent, 0);\n this.state.networkErrorRetries.set(MembershipActionType.SendFirstDelayedEvent, 0);\n this.state.delayId = response.delay_id;\n return createInsertActionUpdate(MembershipActionType.SendJoinEvent);\n })\n .catch((e) => {\n const repeatActionType = MembershipActionType.SendFirstDelayedEvent;\n if (this.manageMaxDelayExceededSituation(e)) {\n return createInsertActionUpdate(repeatActionType);\n }\n const update = this.actionUpdateFromErrors(e, repeatActionType, \"sendDelayedStateEvent\");\n if (update) return update;\n\n // log and fall through\n if (this.isUnsupportedDelayedEndpoint(e)) {\n logger.info(\"Not using delayed event because the endpoint is not supported\");\n } else {\n logger.info(\"Not using delayed event because: \" + e);\n }\n // On any other error we fall back to not using delayed events and send the join state event immediately\n return createInsertActionUpdate(MembershipActionType.SendJoinEvent);\n });\n }\n\n private async cancelKnownDelayIdBeforeSendFirstDelayedEvent(delayId: string): Promise<ActionUpdate> {\n // Remove all running updates and restarts\n return await this.client\n ._unstable_updateDelayedEvent(delayId, UpdateDelayedEventAction.Cancel)\n .then(() => {\n this.state.delayId = undefined;\n this.resetRateLimitCounter(MembershipActionType.SendFirstDelayedEvent);\n return createReplaceActionUpdate(MembershipActionType.SendFirstDelayedEvent);\n })\n .catch((e) => {\n const repeatActionType = MembershipActionType.SendFirstDelayedEvent;\n const update = this.actionUpdateFromErrors(e, repeatActionType, \"updateDelayedEvent\");\n if (update) return update;\n\n if (this.isNotFoundError(e)) {\n // If we get a M_NOT_FOUND we know that the delayed event got already removed.\n // This means we are good and can set it to undefined and run this again.\n this.state.delayId = undefined;\n return createReplaceActionUpdate(repeatActionType);\n }\n if (this.isUnsupportedDelayedEndpoint(e)) {\n return createReplaceActionUpdate(MembershipActionType.SendJoinEvent);\n }\n // We do not just ignore and log this error since we would also need to reset the delayId.\n\n // This becomes an unrecoverable error case since something is significantly off if we don't hit any of the above cases\n // when state.delayId !== undefined\n // We do not just ignore and log this error since we would also need to reset the delayId.\n // It is cleaner if we, the frontend, rejoins instead of resetting the delayId here and behaving like in the success case.\n throw Error(\n \"We failed to cancel a delayed event where we already had a delay id with an error we cannot automatically handle\",\n );\n });\n }\n\n private async restartDelayedEvent(delayId: string): Promise<ActionUpdate> {\n return await this.client\n ._unstable_updateDelayedEvent(delayId, UpdateDelayedEventAction.Restart)\n .then(() => {\n this.resetRateLimitCounter(MembershipActionType.RestartDelayedEvent);\n return createInsertActionUpdate(\n MembershipActionType.RestartDelayedEvent,\n this.membershipKeepAlivePeriod,\n );\n })\n .catch((e) => {\n const repeatActionType = MembershipActionType.RestartDelayedEvent;\n if (this.isNotFoundError(e)) {\n this.state.delayId = undefined;\n return createInsertActionUpdate(MembershipActionType.SendMainDelayedEvent);\n }\n // If the HS does not support delayed events we wont reschedule.\n if (this.isUnsupportedDelayedEndpoint(e)) return {};\n\n // TODO this also needs a test: get rate limit while checking id delayed event is scheduled\n const update = this.actionUpdateFromErrors(e, repeatActionType, \"updateDelayedEvent\");\n if (update) return update;\n\n // In other error cases we have no idea what is happening\n throw Error(\"Could not restart delayed event, even though delayed events are supported. \" + e);\n });\n }\n\n private async sendMainDelayedEvent(): Promise<ActionUpdate> {\n return await this.client\n ._unstable_sendDelayedStateEvent(\n this.room.roomId,\n {\n delay: this.membershipServerSideExpiryTimeout,\n },\n EventType.GroupCallMemberPrefix,\n {}, // leave event\n this.stateKey,\n )\n .then((response) => {\n this.state.delayId = response.delay_id;\n this.resetRateLimitCounter(MembershipActionType.SendMainDelayedEvent);\n return createInsertActionUpdate(\n MembershipActionType.RestartDelayedEvent,\n this.membershipKeepAlivePeriod,\n );\n })\n .catch((e) => {\n const repeatActionType = MembershipActionType.SendMainDelayedEvent;\n // Don't do any other delayed event work if its not supported.\n if (this.isUnsupportedDelayedEndpoint(e)) return {};\n\n if (this.manageMaxDelayExceededSituation(e)) {\n return createInsertActionUpdate(repeatActionType);\n }\n const update = this.actionUpdateFromErrors(e, repeatActionType, \"updateDelayedEvent\");\n if (update) return update;\n\n throw Error(\"Could not send delayed event, even though delayed events are supported. \" + e);\n });\n }\n\n private async sendScheduledDelayedLeaveEventOrFallbackToSendLeaveEvent(delayId: string): Promise<ActionUpdate> {\n return await this.client\n ._unstable_updateDelayedEvent(delayId, UpdateDelayedEventAction.Send)\n .then(() => {\n this.state.hasMemberStateEvent = false;\n this.resetRateLimitCounter(MembershipActionType.SendScheduledDelayedLeaveEvent);\n\n return { replace: [] };\n })\n .catch((e) => {\n const repeatActionType = MembershipActionType.SendLeaveEvent;\n if (this.isUnsupportedDelayedEndpoint(e)) return {};\n if (this.isNotFoundError(e)) {\n this.state.delayId = undefined;\n return createInsertActionUpdate(repeatActionType);\n }\n const update = this.actionUpdateFromErrors(e, repeatActionType, \"updateDelayedEvent\");\n if (update) return update;\n\n // On any other error we fall back to SendLeaveEvent (this includes hard errors from rate limiting)\n logger.warn(\n \"Encountered unexpected error during SendScheduledDelayedLeaveEvent. Falling back to SendLeaveEvent\",\n e,\n );\n return createInsertActionUpdate(repeatActionType);\n });\n }\n\n private async sendJoinEvent(): Promise<ActionUpdate> {\n return await this.client\n .sendStateEvent(\n this.room.roomId,\n EventType.GroupCallMemberPrefix,\n this.makeMyMembership(this.membershipEventExpiryTimeout),\n this.stateKey,\n )\n .then(() => {\n this.state.startTime = Date.now();\n // The next update should already use twice the membershipEventExpiryTimeout\n this.state.expireUpdateIterations = 1;\n this.state.hasMemberStateEvent = true;\n this.resetRateLimitCounter(MembershipActionType.SendJoinEvent);\n return {\n insert: [\n { ts: Date.now(), type: MembershipActionType.RestartDelayedEvent },\n {\n ts: this.computeNextExpiryActionTs(this.state.expireUpdateIterations),\n type: MembershipActionType.UpdateExpiry,\n },\n ],\n };\n })\n .catch((e) => {\n const update = this.actionUpdateFromErrors(e, MembershipActionType.SendJoinEvent, \"sendStateEvent\");\n if (update) return update;\n throw e;\n });\n }\n\n private async updateExpiryOnJoinedEvent(): Promise<ActionUpdate> {\n const nextExpireUpdateIteration = this.state.expireUpdateIterations + 1;\n return await this.client\n .sendStateEvent(\n this.room.roomId,\n EventType.GroupCallMemberPrefix,\n this.makeMyMembership(this.membershipEventExpiryTimeout * nextExpireUpdateIteration),\n this.stateKey,\n )\n .then(() => {\n // Success, we reset retries and schedule update.\n this.resetRateLimitCounter(MembershipActionType.UpdateExpiry);\n this.state.expireUpdateIterations = nextExpireUpdateIteration;\n return {\n insert: [\n {\n ts: this.computeNextExpiryActionTs(nextExpireUpdateIteration),\n type: MembershipActionType.UpdateExpiry,\n },\n ],\n };\n })\n .catch((e) => {\n const update = this.actionUpdateFromErrors(e, MembershipActionType.UpdateExpiry, \"sendStateEvent\");\n if (update) return update;\n\n throw e;\n });\n }\n private async sendFallbackLeaveEvent(): Promise<ActionUpdate> {\n return await this.client\n .sendStateEvent(this.room.roomId, EventType.GroupCallMemberPrefix, {}, this.stateKey)\n .then(() => {\n this.resetRateLimitCounter(MembershipActionType.SendLeaveEvent);\n this.state.hasMemberStateEvent = false;\n return { replace: [] };\n })\n .catch((e) => {\n const update = this.actionUpdateFromErrors(e, MembershipActionType.SendLeaveEvent, \"sendStateEvent\");\n if (update) return update;\n throw e;\n });\n }\n\n // HELPERS\n private makeMembershipStateKey(localUserId: string, localDeviceId: string): string {\n const stateKey = `${localUserId}_${localDeviceId}`;\n if (/^org\\.matrix\\.msc(3757|3779)\\b/.exec(this.room.getVersion())) {\n return stateKey;\n } else {\n return `_${stateKey}`;\n }\n }\n\n /**\n * Constructs our own membership\n */\n private makeMyMembership(expires: number): SessionMembershipData {\n return {\n call_id: \"\",\n scope: \"m.room\",\n application: \"m.call\",\n device_id: this.deviceId,\n expires,\n focus_active: { type: \"livekit\", focus_selection: \"oldest_membership\" },\n foci_preferred: this.fociPreferred ?? [],\n };\n }\n\n // Error checks and handlers\n\n /**\n * Check if its a NOT_FOUND error\n * @param error the error causing this handler check/execution\n * @returns true if its a not found error\n */\n private isNotFoundError(error: unknown): boolean {\n return error instanceof MatrixError && error.errcode === \"M_NOT_FOUND\";\n }\n\n /**\n * Check if this is a DelayExceeded timeout and update the TimeoutOverride for the next try\n * @param error the error causing this handler check/execution\n * @returns true if its a delay exceeded error and we updated the local TimeoutOverride\n */\n private manageMaxDelayExceededSituation(error: unknown): boolean {\n if (\n error instanceof MatrixError &&\n error.errcode === \"M_UNKNOWN\" &&\n error.data[\"org.matrix.msc4140.errcode\"] === \"M_MAX_DELAY_EXCEEDED\"\n ) {\n const maxDelayAllowed = error.data[\"org.matrix.msc4140.max_delay\"];\n if (typeof maxDelayAllowed === \"number\" && this.membershipServerSideExpiryTimeout > maxDelayAllowed) {\n this.membershipServerSideExpiryTimeoutOverride = maxDelayAllowed;\n }\n logger.warn(\"Retry sending delayed disconnection event due to server timeout limitations:\", error);\n return true;\n }\n return false;\n }\n\n private actionUpdateFromErrors(\n error: unknown,\n type: MembershipActionType,\n method: string,\n ): ActionUpdate | undefined {\n const updateLimit = this.actionUpdateFromRateLimitError(error, method, type);\n if (updateLimit) return updateLimit;\n const updateNetwork = this.actionUpdateFromNetworkErrorRetry(error, type);\n if (updateNetwork) return updateNetwork;\n }\n /**\n * Check if we have a rate limit error and schedule the same action again if we dont exceed the rate limit retry count yet.\n * @param error the error causing this handler check/execution\n * @param method the method used for the throw message\n * @param type which MembershipActionType we reschedule because of a rate limit.\n * @throws If it is a rate limit error and the retry count got exceeded\n * @returns Returns true if we handled the error by rescheduling the correct next action.\n * Returns false if it is not a network error.\n */\n private actionUpdateFromRateLimitError(\n error: unknown,\n method: string,\n type: MembershipActionType,\n ): ActionUpdate | undefined {\n // \"Is rate limit\"-boundary\n if (!((error instanceof HTTPError || error instanceof MatrixError) && error.isRateLimitError())) {\n return undefined;\n }\n\n // retry boundary\n const rateLimitRetries = this.state.rateLimitRetries.get(type) ?? 0;\n if (rateLimitRetries < this.maximumRateLimitRetryCount) {\n let resendDelay: number;\n const defaultMs = 5000;\n try {\n resendDelay = error.getRetryAfterMs() ?? defaultMs;\n logger.info(`Rate limited by server, retrying in ${resendDelay}ms`);\n } catch (e) {\n logger.warn(\n `Error while retrieving a rate-limit retry delay, retrying after default delay of ${defaultMs}`,\n e,\n );\n resendDelay = defaultMs;\n }\n this.state.rateLimitRetries.set(type, rateLimitRetries + 1);\n return createInsertActionUpdate(type, resendDelay);\n }\n\n throw Error(\"Exceeded maximum retries for \" + type + \" attempts (client.\" + method + \"): \" + (error as Error));\n }\n\n /**\n * FIXME Don't Check the error and retry the same MembershipAction again in the configured time and for the configured retry count.\n * @param error the error causing this handler check/execution\n * @param type the action type that we need to repeat because of the error\n * @throws If it is a network error and the retry count got exceeded\n * @returns\n * Returns true if we handled the error by rescheduling the correct next action.\n * Returns false if it is not a network error.\n */\n private actionUpdateFromNetworkErrorRetry(error: unknown, type: MembershipActionType): ActionUpdate | undefined {\n // \"Is a network error\"-boundary\n const retries = this.state.networkErrorRetries.get(type) ?? 0;\n const retryDurationString = this.callMemberEventRetryDelayMinimum / 1000 + \"s\";\n const retryCounterString = \"(\" + retries + \"/\" + this.maximumNetworkErrorRetryCount + \")\";\n if (error instanceof Error && error.name === \"AbortError\") {\n logger.warn(\n \"Network local timeout error while sending event, retrying in \" +\n retryDurationString +\n \" \" +\n retryCounterString,\n error,\n );\n } else if (error instanceof Error && error.message.includes(\"updating delayed event\")) {\n // TODO: We do not want error message matching here but instead the error should be a typed HTTPError\n // and be handled below automatically (the same as in the SPA case).\n //\n // The error originates because of https://github.com/matrix-org/matrix-widget-api/blob/5d81d4a26ff69e4bd3ddc79a884c9527999fb2f4/src/ClientWidgetApi.ts#L698-L701\n // uses `e` instance of HttpError (and not MatrixError)\n // The element web widget driver (only checks for MatrixError) is then failing to process (`processError`) it as a typed error: https://github.com/element-hq/element-web/blob/471712cbf06a067e5499bd5d2d7a75f693d9a12d/src/stores/widgets/StopGapWidgetDriver.ts#L711-L715\n // So it will not call: `error.asWidgetApiErrorData()` which is also missing for `HttpError`\n //\n // A proper fix would be to either find a place to convert the `HttpError` into a `MatrixError` and the `processError`\n // method to handle it as expected or to adjust `processError` to also process `HttpError`'s.\n logger.warn(\n \"delayed event update timeout error, retrying in \" + retryDurationString + \" \" + retryCounterString,\n error,\n );\n } else if (error instanceof ConnectionError) {\n logger.warn(\n \"Network connection error while sending event, retrying in \" +\n retryDurationString +\n \" \" +\n retryCounterString,\n error,\n );\n } else if (\n (error instanceof HTTPError || error instanceof MatrixError) &&\n typeof error.httpStatus === \"number\" &&\n error.httpStatus >= 500 &&\n error.httpStatus < 600\n ) {\n logger.warn(\n \"Server error while sending event, retrying in \" + retryDurationString + \" \" + retryCounterString,\n error,\n );\n } else {\n return undefined;\n }\n\n // retry boundary\n if (retries < this.maximumNetworkErrorRetryCount) {\n this.state.networkErrorRetries.set(type, retries + 1);\n return createInsertActionUpdate(type, this.callMemberEventRetryDelayMinimum);\n }\n\n // Failure\n throw Error(\n \"Reached maximum (\" + this.maximumNetworkErrorRetryCount + \") retries cause by: \" + (error as Error),\n );\n }\n\n /**\n * Check if its an UnsupportedDelayedEventsEndpointError and which implies that we cannot do any delayed event logic\n * @param error The error to check\n * @returns true it its an UnsupportedDelayedEventsEndpointError\n */\n private isUnsupportedDelayedEndpoint(error: unknown): boolean {\n return error instanceof UnsupportedDelayedEventsEndpointError;\n }\n\n private resetRateLimitCounter(type: MembershipActionType): void {\n this.state.rateLimitRetries.set(type, 0);\n this.state.networkErrorRetries.set(type, 0);\n }\n\n public get status(): Status {\n const actions = this.scheduler.actions;\n if (actions.length === 1) {\n const { type } = actions[0];\n switch (type) {\n case MembershipActionType.SendFirstDelayedEvent:\n case MembershipActionType.SendJoinEvent:\n case MembershipActionType.SendMainDelayedEvent:\n return Status.Connecting;\n case MembershipActionType.UpdateExpiry: // where no delayed events\n return Status.Connected;\n case MembershipActionType.SendScheduledDelayedLeaveEvent:\n case MembershipActionType.SendLeaveEvent:\n return Status.Disconnecting;\n default:\n // pass through as not expected\n }\n } else if (actions.length === 2) {\n const types = actions.map((a) => a.type);\n // normal state for connected with delayed events\n if (\n (types.includes(MembershipActionType.RestartDelayedEvent) ||\n types.includes(MembershipActionType.SendMainDelayedEvent)) &&\n types.includes(MembershipActionType.UpdateExpiry)\n ) {\n return Status.Connected;\n }\n } else if (actions.length === 3) {\n const types = actions.map((a) => a.type);\n // It is a correct connected state if we already schedule the next Restart but have not yet cleaned up\n // the current restart.\n if (\n types.filter((t) => t === MembershipActionType.RestartDelayedEvent).length === 2 &&\n types.includes(MembershipActionType.UpdateExpiry)\n ) {\n return Status.Connected;\n }\n }\n\n if (!this.scheduler.running) {\n return Status.Disconnected;\n }\n\n logger.error(\"MembershipManager has an unknown state. Actions: \", actions);\n return Status.Unknown;\n }\n}\n\nfunction createInsertActionUpdate(type: MembershipActionType, offset?: number): ActionUpdate {\n return {\n insert: [{ ts: Date.now() + (offset ?? 0), type }],\n };\n}\n\nfunction createReplaceActionUpdate(type: MembershipActionType, offset?: number): ActionUpdate {\n return {\n replace: [{ ts: Date.now() + (offset ?? 0), type }],\n };\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA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C,IAAIkD,MAAM,aAANA,MAAM,cAANA,MAAM,GAAI,CAAC,CAAC;MAAErJ;IAAK,CAAC;EACrD,CAAC;AACL;AAEA,SAASwF,yBAAyBA,CAACxF,IAA0B,EAAEqJ,MAAe,EAAgB;EAC1F,OAAO;IACHtF,OAAO,EAAE,CAAC;MAAEsC,EAAE,EAAEH,IAAI,CAACC,GAAG,CAAC,CAAC,IAAIkD,MAAM,aAANA,MAAM,cAANA,MAAM,GAAI,CAAC,CAAC;MAAErJ;IAAK,CAAC;EACtD,CAAC;AACL","ignoreList":[]}
1
+ {"version":3,"file":"NewMembershipManager.js","names":["EventType","UpdateDelayedEventAction","UnsupportedDelayedEventsEndpointError","ConnectionError","HTTPError","MatrixError","logger","rootLogger","defer","DEFAULT_EXPIRE_DURATION","MembershipManagerEvent","Status","isLivekitFocusActive","ActionScheduler","TypedEventEmitter","getChild","MembershipActionType","MembershipManager","isActivated","activated","isJoined","join","fociPreferred","focusActive","onError","scheduler","running","error","leavePromiseDefer","undefined","oldStatus","status","state","defaultState","startWithJoin","catch","e","finally","emit","StatusChanged","_this$leavePromiseDef","resolve","leave","timeout","warn","Promise","initiateLeave","setTimeout","_this$leavePromiseDef2","promise","onRTCSessionMemberUpdate","memberships","_this","_asyncToGenerator","isMyMembership","m","sender","client","getUserId","deviceId","getDeviceId","some","sendingMembershipActions","SendDelayedEvent","SendJoinEvent","actions","find","a","includes","type","hasMemberStateEvent","initiateJoin","getActiveFocus","focus_selection","oldestMembership","getOldestMembership","getPreferredFoci","constructor","joinConfig","room","_defineProperty","debug","concat","membershipLoopHandler","userId","Error","stateKey","makeMembershipStateKey","delayId","startTime","rateLimitRetries","Map","networkErrorRetries","expireUpdateIterations","callMemberEventRetryDelayMinimum","_this$joinConfig$call","_this$joinConfig","membershipEventExpiryTimeout","_this$joinConfig$memb","_this$joinConfig2","membershipExpiryTimeout","membershipEventExpiryTimeoutHeadroom","_this$joinConfig$memb2","_this$joinConfig3","membershipExpiryTimeoutHeadroom","computeNextExpiryActionTs","iteration","membershipServerSideExpiryTimeout","_ref","_this$membershipServe","_this$joinConfig4","membershipServerSideExpiryTimeoutOverride","membershipKeepAlivePeriod","_this$joinConfig$memb3","_this$joinConfig5","maximumRateLimitRetryCount","_this$joinConfig$maxi","_this$joinConfig6","maximumNetworkErrorRetryCount","_this$joinConfig$maxi2","_this$joinConfig7","_this2","sendOrResendDelayedLeaveEvent","cancelKnownDelayIdBeforeSendFirstDelayedEvent","RestartDelayedEvent","createInsertActionUpdate","restartDelayedEvent","SendScheduledDelayedLeaveEvent","replace","sendScheduledDelayedLeaveEventOrFallbackToSendLeaveEvent","SendLeaveEvent","sendJoinEvent","UpdateExpiry","updateExpiryOnJoinedEvent","sendFallbackLeaveEvent","_this3","_unstable_sendDelayedStateEvent","roomId","delay","GroupCallMemberPrefix","then","response","resetRateLimitCounter","delay_id","repeatActionType","manageMaxDelayExceededSituation","update","actionUpdateFromErrors","isUnsupportedDelayedEndpoint","info","_this4","_unstable_updateDelayedEvent","Cancel","createReplaceActionUpdate","isNotFoundError","_this5","Restart","_this6","Send","_this7","sendStateEvent","makeMyMembership","Date","now","insert","ts","_this8","nextExpireUpdateIteration","_this9","localUserId","localDeviceId","exec","getVersion","expires","_this$fociPreferred","call_id","scope","application","device_id","focus_active","foci_preferred","errcode","data","maxDelayAllowed","method","updateLimit","actionUpdateFromRateLimitError","updateNetwork","actionUpdateFromNetworkErrorRetry","_this$state$rateLimit","isRateLimitError","get","resendDelay","defaultMs","_error$getRetryAfterM","getRetryAfterMs","set","_this$state$networkEr","retries","retryDurationString","retryCounterString","name","message","httpStatus","length","Connecting","Connected","Disconnecting","types","map","filter","t","Disconnected","Unknown","offset"],"sources":["../../src/matrixrtc/NewMembershipManager.ts"],"sourcesContent":["/*\nCopyright 2025 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { EventType } from \"../@types/event.ts\";\nimport { UpdateDelayedEventAction } from \"../@types/requests.ts\";\nimport { type MatrixClient } from \"../client.ts\";\nimport { UnsupportedDelayedEventsEndpointError } from \"../errors.ts\";\nimport { ConnectionError, HTTPError, MatrixError } from \"../http-api/errors.ts\";\nimport { logger as rootLogger } from \"../logger.ts\";\nimport { type Room } from \"../models/room.ts\";\nimport { defer, type IDeferred } from \"../utils.ts\";\nimport { type CallMembership, DEFAULT_EXPIRE_DURATION, type SessionMembershipData } from \"./CallMembership.ts\";\nimport { type Focus } from \"./focus.ts\";\nimport {\n type IMembershipManager,\n type MembershipManagerEventHandlerMap,\n MembershipManagerEvent,\n Status,\n} from \"./types.ts\";\nimport { isLivekitFocusActive } from \"./LivekitFocus.ts\";\nimport { type MembershipConfig } from \"./MatrixRTCSession.ts\";\nimport { ActionScheduler, type ActionUpdate } from \"./NewMembershipManagerActionScheduler.ts\";\nimport { TypedEventEmitter } from \"../models/typed-event-emitter.ts\";\n\nconst logger = rootLogger.getChild(\"MatrixRTCSession\");\n\n/* MembershipActionTypes:\n \nOn Join: ───────────────┐ ┌───────────────(1)───────────┐\n ▼ ▼ │\n ┌────────────────┐ │\n │SendDelayedEvent│ ──────(2)───┐ │\n └────────────────┘ │ │ \n │(3) │ │\n ▼ │ │\n ┌─────────────┐ │ │\n ┌──────(4)───│SendJoinEvent│────(4)─────┐ │ │\n │ └─────────────┘ │ │ │\n │ ┌─────┐ ┌──────┐ │ │ │\n ▼ ▼ │ │ ▼ ▼ ▼ │\n┌────────────┐ │ │ ┌───────────────────┐ │\n│UpdateExpiry│ (s) (s)|RestartDelayedEvent│ │\n└────────────┘ │ │ └───────────────────┘ │\n │ │ │ │ │ │ \n └─────┘ └──────┘ └───────┘ \n \nOn Leave: ───────── STOP ALL ABOVE\n ▼\n ┌────────────────────────────────┐\n │ SendScheduledDelayedLeaveEvent │\n └────────────────────────────────┘\n │(5)\n ▼\n ┌──────────────┐\n │SendLeaveEvent│\n └──────────────┘\n(1) [Not found error] results in resending the delayed event\n(2) [hasMemberEvent = true] Sending the delayed event if we\n already have a call member event results jumping to the\n RestartDelayedEvent loop directly\n(3) [hasMemberEvent = false] if there is not call member event\n sending it is the next step\n(4) Both (UpdateExpiry and RestartDelayedEvent) actions are\n scheduled when successfully sending the state event\n(5) Only if delayed event sending failed (fallback)\n(s) Successful restart/resend\n*/\n\n/**\n * The different types of actions the MembershipManager can take.\n * @internal\n */\nexport enum MembershipActionType {\n SendDelayedEvent = \"SendDelayedEvent\",\n // -> MembershipActionType.SendJoinEvent if successful\n // -> DelayedLeaveActionType.SendDelayedEvent on error, retry sending the first delayed event.\n // -> DelayedLeaveActionType.RestartDelayedEvent on success start updating the delayed event\n SendJoinEvent = \"SendJoinEvent\",\n // -> MembershipActionType.SendJoinEvent if we run into a rate limit and need to retry\n // -> MembershipActionType.Update if we successfully send the join event then schedule the expire event update\n // -> DelayedLeaveActionType.RestartDelayedEvent to recheck the delayed event\n RestartDelayedEvent = \"RestartDelayedEvent\",\n // -> DelayedLeaveActionType.SendMainDelayedEvent on missing delay id but there is a rtc state event\n // -> DelayedLeaveActionType.SendDelayedEvent on missing delay id and there is no state event\n // -> DelayedLeaveActionType.RestartDelayedEvent on success we schedule the next restart\n UpdateExpiry = \"UpdateExpiry\",\n // -> MembershipActionType.Update if the timeout has passed so the next update is required.\n SendScheduledDelayedLeaveEvent = \"SendScheduledDelayedLeaveEvent\",\n // -> MembershipActionType.SendLeaveEvent on failiour (not found) we need to send the leave manually and cannot use the scheduled delayed event\n // -> DelayedLeaveActionType.SendScheduledDelayedLeaveEvent on error we try again.\n SendLeaveEvent = \"SendLeaveEvent\",\n // -> MembershipActionType.SendLeaveEvent\n}\n\n/**\n * @internal\n */\nexport interface MembershipManagerState {\n /** The delayId we got when successfully sending the delayed leave event.\n * Gets set to undefined if the server claims it cannot find the delayed event anymore. */\n delayId?: string;\n /** Stores how often we have update the `expires` field.\n * `expireUpdateIterations` * `membershipEventExpiryTimeout` resolves to the value the expires field should contain next */\n expireUpdateIterations: number;\n /** The time at which we send the first state event. The time the call started from the DAG point of view.\n * This is used to compute the local sleep timestamps when to next update the member event with a new expires value. */\n startTime: number;\n /** The manager is in the state where its actually connected to the session. */\n hasMemberStateEvent: boolean;\n // There can be multiple retries at once so we need to store counters per action\n // e.g. the send update membership and the restart delayed could be rate limited at the same time.\n /** Retry counter for rate limits */\n rateLimitRetries: Map<MembershipActionType, number>;\n /** Retry counter for other errors */\n networkErrorRetries: Map<MembershipActionType, number>;\n}\n\n/**\n * This class is responsible for sending all events relating to the own membership of a matrixRTC call.\n * It has the following tasks:\n * - Send the users leave delayed event before sending the membership\n * - Send the users membership if the state machine is started\n * - Check if the delayed event was canceled due to sending the membership\n * - update the delayed event (`restart`)\n * - Update the state event every ~5h = `DEFAULT_EXPIRE_DURATION` (so it does not get treated as expired)\n * - When the state machine is stopped:\n * - Disconnect the member\n * - Stop the timer for the delay refresh\n * - Stop the timer for updating the state event\n */\nexport class MembershipManager\n extends TypedEventEmitter<MembershipManagerEvent, MembershipManagerEventHandlerMap>\n implements IMembershipManager\n{\n private activated = false;\n public isActivated(): boolean {\n return this.activated;\n }\n // DEPRECATED use isActivated\n public isJoined(): boolean {\n return this.isActivated();\n }\n\n /**\n * Puts the MembershipManager in a state where it tries to be joined.\n * It will send delayed events and membership events\n * @param fociPreferred\n * @param focusActive\n * @param onError This will be called once the membership manager encounters an unrecoverable error.\n * This should bubble up the the frontend to communicate that the call does not work in the current environment.\n */\n public join(fociPreferred: Focus[], focusActive?: Focus, onError?: (error: unknown) => void): void {\n if (this.scheduler.running) {\n logger.error(\"MembershipManager is already running. Ignoring join request.\");\n return;\n }\n this.fociPreferred = fociPreferred;\n this.focusActive = focusActive;\n this.leavePromiseDefer = undefined;\n this.activated = true;\n this.oldStatus = this.status;\n this.state = MembershipManager.defaultState;\n\n this.scheduler\n .startWithJoin()\n .catch((e) => {\n logger.error(\"MembershipManager stopped because: \", e);\n onError?.(e);\n })\n .finally(() => {\n // Should already be set to false when calling `leave` in non error cases.\n this.activated = false;\n // Here the scheduler is not running anymore so we the `membershipLoopHandler` is not called to emit.\n if (this.oldStatus && this.oldStatus !== this.status) {\n this.emit(MembershipManagerEvent.StatusChanged, this.oldStatus, this.status);\n }\n if (!this.scheduler.running) {\n this.leavePromiseDefer?.resolve(true);\n this.leavePromiseDefer = undefined;\n }\n });\n }\n\n /**\n * Leave from the call (Send an rtc session event with content: `{}`)\n * @param timeout the maximum duration this promise will take to resolve\n * @returns true if it managed to leave and false if the timeout condition happened.\n */\n public leave(timeout?: number): Promise<boolean> {\n if (!this.scheduler.running) {\n logger.warn(\"Called MembershipManager.leave() even though the MembershipManager is not running\");\n return Promise.resolve(true);\n }\n\n // We use the promise to track if we already scheduled a leave event\n // So we do not check scheduler.actions/scheduler.insertions\n if (!this.leavePromiseDefer) {\n // reset scheduled actions so we will not do any new actions.\n this.leavePromiseDefer = defer<boolean>();\n this.activated = false;\n this.scheduler.initiateLeave();\n if (timeout) setTimeout(() => this.leavePromiseDefer?.resolve(false), timeout);\n }\n return this.leavePromiseDefer.promise;\n }\n private leavePromiseDefer?: IDeferred<boolean>;\n\n public async onRTCSessionMemberUpdate(memberships: CallMembership[]): Promise<void> {\n const isMyMembership = (m: CallMembership): boolean =>\n m.sender === this.client.getUserId() && m.deviceId === this.client.getDeviceId();\n\n if (this.isJoined() && !memberships.some(isMyMembership)) {\n // If one of these actions are scheduled or are getting inserted in the next iteration, we should already\n // take care of our missing membership.\n const sendingMembershipActions = [\n MembershipActionType.SendDelayedEvent,\n MembershipActionType.SendJoinEvent,\n ];\n logger.warn(\"Missing own membership: force re-join\");\n if (this.scheduler.actions.find((a) => sendingMembershipActions.includes(a.type as MembershipActionType))) {\n logger.error(\n \"NewMembershipManger tried adding another `SendFirstDelayedEvent` actions even though we already have one in the Queue\\nActionQueueOnMemberUpdate:\",\n this.scheduler.actions,\n );\n } else {\n // Only react to our own membership missing if we have not already scheduled sending a new membership DirectMembershipManagerAction.Join\n this.state.hasMemberStateEvent = false;\n this.scheduler.initiateJoin();\n }\n }\n return Promise.resolve();\n }\n\n public getActiveFocus(): Focus | undefined {\n if (this.focusActive) {\n // A livekit active focus\n if (isLivekitFocusActive(this.focusActive)) {\n if (this.focusActive.focus_selection === \"oldest_membership\") {\n const oldestMembership = this.getOldestMembership();\n return oldestMembership?.getPreferredFoci()[0];\n }\n } else {\n logger.warn(\"Unknown own ActiveFocus type. This makes it impossible to connect to an SFU.\");\n }\n } else {\n // We do not understand the membership format (could be legacy). We default to oldestMembership\n // Once there are other methods this is a hard error!\n const oldestMembership = this.getOldestMembership();\n return oldestMembership?.getPreferredFoci()[0];\n }\n }\n\n /**\n * @throws if the client does not return user or device id.\n * @param joinConfig\n * @param room\n * @param client\n * @param getOldestMembership\n */\n public constructor(\n private joinConfig: MembershipConfig | undefined,\n private room: Pick<Room, \"getLiveTimeline\" | \"roomId\" | \"getVersion\">,\n private client: Pick<\n MatrixClient,\n | \"getUserId\"\n | \"getDeviceId\"\n | \"sendStateEvent\"\n | \"_unstable_sendDelayedStateEvent\"\n | \"_unstable_updateDelayedEvent\"\n >,\n private getOldestMembership: () => CallMembership | undefined,\n ) {\n super();\n const [userId, deviceId] = [this.client.getUserId(), this.client.getDeviceId()];\n if (userId === null) throw Error(\"Missing userId in client\");\n if (deviceId === null) throw Error(\"Missing deviceId in client\");\n this.deviceId = deviceId;\n this.stateKey = this.makeMembershipStateKey(userId, deviceId);\n this.state = MembershipManager.defaultState;\n }\n\n // MembershipManager mutable state.\n private state: MembershipManagerState;\n private static get defaultState(): MembershipManagerState {\n return {\n hasMemberStateEvent: false,\n delayId: undefined,\n\n startTime: 0,\n rateLimitRetries: new Map(),\n networkErrorRetries: new Map(),\n expireUpdateIterations: 1,\n };\n }\n // Membership Event static parameters:\n private deviceId: string;\n private stateKey: string;\n private fociPreferred?: Focus[];\n private focusActive?: Focus;\n\n // Config:\n private membershipServerSideExpiryTimeoutOverride?: number;\n\n private get callMemberEventRetryDelayMinimum(): number {\n return this.joinConfig?.callMemberEventRetryDelayMinimum ?? 3_000;\n }\n private get membershipEventExpiryTimeout(): number {\n return this.joinConfig?.membershipExpiryTimeout ?? DEFAULT_EXPIRE_DURATION;\n }\n private get membershipEventExpiryTimeoutHeadroom(): number {\n return this.joinConfig?.membershipExpiryTimeoutHeadroom ?? 5_000;\n }\n private computeNextExpiryActionTs(iteration: number): number {\n return (\n this.state.startTime +\n this.membershipEventExpiryTimeout * iteration -\n this.membershipEventExpiryTimeoutHeadroom\n );\n }\n private get membershipServerSideExpiryTimeout(): number {\n return (\n this.membershipServerSideExpiryTimeoutOverride ??\n this.joinConfig?.membershipServerSideExpiryTimeout ??\n 8_000\n );\n }\n private get membershipKeepAlivePeriod(): number {\n return this.joinConfig?.membershipKeepAlivePeriod ?? 5_000;\n }\n private get maximumRateLimitRetryCount(): number {\n return this.joinConfig?.maximumRateLimitRetryCount ?? 10;\n }\n private get maximumNetworkErrorRetryCount(): number {\n return this.joinConfig?.maximumNetworkErrorRetryCount ?? 10;\n }\n\n // Scheduler:\n private oldStatus?: Status;\n private scheduler = new ActionScheduler((type): Promise<ActionUpdate> => {\n if (this.oldStatus) {\n // we put this at the beginning of the actions scheduler loop handle callback since it is a loop this\n // is equivalent to running it at the end of the loop. (just after applying the status/action list changes)\n // This order is required because this method needs to return the action updates.\n logger.debug(`MembershipManager applied action changes. Status: ${this.oldStatus} -> ${this.status}`);\n if (this.oldStatus !== this.status) {\n this.emit(MembershipManagerEvent.StatusChanged, this.oldStatus, this.status);\n }\n }\n this.oldStatus = this.status;\n logger.debug(`MembershipManager before processing action. status=${this.oldStatus}`);\n return this.membershipLoopHandler(type);\n });\n\n // LOOP HANDLER:\n private async membershipLoopHandler(type: MembershipActionType): Promise<ActionUpdate> {\n switch (type) {\n case MembershipActionType.SendDelayedEvent: {\n // Before we start we check if we come from a state where we have a delay id.\n if (!this.state.delayId) {\n return this.sendOrResendDelayedLeaveEvent(); // Normal case without any previous delayed id.\n } else {\n // This can happen if someone else (or another client) removes our own membership event.\n // It will trigger `onRTCSessionMemberUpdate` queue `MembershipActionType.SendFirstDelayedEvent`.\n // We might still have our delayed event from the previous participation and dependent on the server this might not\n // get removed automatically if the state changes. Hence, it would remove our membership unexpectedly shortly after the rejoin.\n //\n // In this block we will try to cancel this delayed event before setting up a new one.\n\n return this.cancelKnownDelayIdBeforeSendFirstDelayedEvent(this.state.delayId);\n }\n }\n case MembershipActionType.RestartDelayedEvent: {\n if (!this.state.delayId) {\n // Delay id got reset. This action was used to check if the hs canceled the delayed event when the join state got sent.\n return createInsertActionUpdate(MembershipActionType.SendDelayedEvent);\n }\n return this.restartDelayedEvent(this.state.delayId);\n }\n case MembershipActionType.SendScheduledDelayedLeaveEvent: {\n // We are already good\n if (!this.state.hasMemberStateEvent) {\n return { replace: [] };\n }\n if (this.state.delayId) {\n return this.sendScheduledDelayedLeaveEventOrFallbackToSendLeaveEvent(this.state.delayId);\n } else {\n return createInsertActionUpdate(MembershipActionType.SendLeaveEvent);\n }\n }\n case MembershipActionType.SendJoinEvent: {\n return this.sendJoinEvent();\n }\n case MembershipActionType.UpdateExpiry: {\n return this.updateExpiryOnJoinedEvent();\n }\n case MembershipActionType.SendLeaveEvent: {\n // We are good already\n if (!this.state.hasMemberStateEvent) {\n return { replace: [] };\n }\n // This is only a fallback in case we do not have working delayed events support.\n // first we should try to just send the scheduled leave event\n return this.sendFallbackLeaveEvent();\n }\n }\n }\n\n // HANDLERS (used in the membershipLoopHandler)\n private async sendOrResendDelayedLeaveEvent(): Promise<ActionUpdate> {\n // We can reach this at the start of a call (where we do not yet have a membership: state.hasMemberStateEvent=false)\n // or during a call if the state event canceled our delayed event or caused by an unexpected error that removed our delayed event.\n // (Another client could have canceled it, the homeserver might have removed/lost it due to a restart, ...)\n // In the `then` and `catch` block we treat both cases differently. \"if (this.state.hasMemberStateEvent) {} else {}\"\n return await this.client\n ._unstable_sendDelayedStateEvent(\n this.room.roomId,\n {\n delay: this.membershipServerSideExpiryTimeout,\n },\n EventType.GroupCallMemberPrefix,\n {}, // leave event\n this.stateKey,\n )\n .then((response) => {\n // On success we reset retries and set delayId.\n this.resetRateLimitCounter(MembershipActionType.SendDelayedEvent);\n this.state.delayId = response.delay_id;\n if (this.state.hasMemberStateEvent) {\n // This action was scheduled because the previous delayed event was cancelled\n // due to lack of https://github.com/element-hq/synapse/pull/17810\n return createInsertActionUpdate(\n MembershipActionType.RestartDelayedEvent,\n this.membershipKeepAlivePeriod,\n );\n } else {\n // This action was scheduled because we are in the process of joining\n return createInsertActionUpdate(MembershipActionType.SendJoinEvent);\n }\n })\n .catch((e) => {\n const repeatActionType = MembershipActionType.SendDelayedEvent;\n if (this.manageMaxDelayExceededSituation(e)) {\n return createInsertActionUpdate(repeatActionType);\n }\n const update = this.actionUpdateFromErrors(e, repeatActionType, \"sendDelayedStateEvent\");\n if (update) return update;\n\n if (this.state.hasMemberStateEvent) {\n // This action was scheduled because the previous delayed event was cancelled\n // due to lack of https://github.com/element-hq/synapse/pull/17810\n\n // Don't do any other delayed event work if its not supported.\n if (this.isUnsupportedDelayedEndpoint(e)) return {};\n throw Error(\"Could not send delayed event, even though delayed events are supported. \" + e);\n } else {\n // This action was scheduled because we are in the process of joining\n // log and fall through\n if (this.isUnsupportedDelayedEndpoint(e)) {\n logger.info(\"Not using delayed event because the endpoint is not supported\");\n } else {\n logger.info(\"Not using delayed event because: \" + e);\n }\n // On any other error we fall back to not using delayed events and send the join state event immediately\n return createInsertActionUpdate(MembershipActionType.SendJoinEvent);\n }\n });\n }\n\n private async cancelKnownDelayIdBeforeSendFirstDelayedEvent(delayId: string): Promise<ActionUpdate> {\n // Remove all running updates and restarts\n return await this.client\n ._unstable_updateDelayedEvent(delayId, UpdateDelayedEventAction.Cancel)\n .then(() => {\n this.state.delayId = undefined;\n this.resetRateLimitCounter(MembershipActionType.SendDelayedEvent);\n return createReplaceActionUpdate(MembershipActionType.SendDelayedEvent);\n })\n .catch((e) => {\n const repeatActionType = MembershipActionType.SendDelayedEvent;\n const update = this.actionUpdateFromErrors(e, repeatActionType, \"updateDelayedEvent\");\n if (update) return update;\n\n if (this.isNotFoundError(e)) {\n // If we get a M_NOT_FOUND we know that the delayed event got already removed.\n // This means we are good and can set it to undefined and run this again.\n this.state.delayId = undefined;\n return createReplaceActionUpdate(repeatActionType);\n }\n if (this.isUnsupportedDelayedEndpoint(e)) {\n return createReplaceActionUpdate(MembershipActionType.SendJoinEvent);\n }\n // We do not just ignore and log this error since we would also need to reset the delayId.\n\n // This becomes an unrecoverable error case since something is significantly off if we don't hit any of the above cases\n // when state.delayId !== undefined\n // We do not just ignore and log this error since we would also need to reset the delayId.\n // It is cleaner if we, the frontend, rejoins instead of resetting the delayId here and behaving like in the success case.\n throw Error(\n \"We failed to cancel a delayed event where we already had a delay id with an error we cannot automatically handle\",\n );\n });\n }\n\n private async restartDelayedEvent(delayId: string): Promise<ActionUpdate> {\n return await this.client\n ._unstable_updateDelayedEvent(delayId, UpdateDelayedEventAction.Restart)\n .then(() => {\n this.resetRateLimitCounter(MembershipActionType.RestartDelayedEvent);\n return createInsertActionUpdate(\n MembershipActionType.RestartDelayedEvent,\n this.membershipKeepAlivePeriod,\n );\n })\n .catch((e) => {\n const repeatActionType = MembershipActionType.RestartDelayedEvent;\n if (this.isNotFoundError(e)) {\n this.state.delayId = undefined;\n return createInsertActionUpdate(MembershipActionType.SendDelayedEvent);\n }\n // If the HS does not support delayed events we wont reschedule.\n if (this.isUnsupportedDelayedEndpoint(e)) return {};\n\n // TODO this also needs a test: get rate limit while checking id delayed event is scheduled\n const update = this.actionUpdateFromErrors(e, repeatActionType, \"updateDelayedEvent\");\n if (update) return update;\n\n // In other error cases we have no idea what is happening\n throw Error(\"Could not restart delayed event, even though delayed events are supported. \" + e);\n });\n }\n\n private async sendScheduledDelayedLeaveEventOrFallbackToSendLeaveEvent(delayId: string): Promise<ActionUpdate> {\n return await this.client\n ._unstable_updateDelayedEvent(delayId, UpdateDelayedEventAction.Send)\n .then(() => {\n this.state.hasMemberStateEvent = false;\n this.resetRateLimitCounter(MembershipActionType.SendScheduledDelayedLeaveEvent);\n\n return { replace: [] };\n })\n .catch((e) => {\n const repeatActionType = MembershipActionType.SendLeaveEvent;\n if (this.isUnsupportedDelayedEndpoint(e)) return {};\n if (this.isNotFoundError(e)) {\n this.state.delayId = undefined;\n return createInsertActionUpdate(repeatActionType);\n }\n const update = this.actionUpdateFromErrors(e, repeatActionType, \"updateDelayedEvent\");\n if (update) return update;\n\n // On any other error we fall back to SendLeaveEvent (this includes hard errors from rate limiting)\n logger.warn(\n \"Encountered unexpected error during SendScheduledDelayedLeaveEvent. Falling back to SendLeaveEvent\",\n e,\n );\n return createInsertActionUpdate(repeatActionType);\n });\n }\n\n private async sendJoinEvent(): Promise<ActionUpdate> {\n return await this.client\n .sendStateEvent(\n this.room.roomId,\n EventType.GroupCallMemberPrefix,\n this.makeMyMembership(this.membershipEventExpiryTimeout),\n this.stateKey,\n )\n .then(() => {\n this.state.startTime = Date.now();\n // The next update should already use twice the membershipEventExpiryTimeout\n this.state.expireUpdateIterations = 1;\n this.state.hasMemberStateEvent = true;\n this.resetRateLimitCounter(MembershipActionType.SendJoinEvent);\n return {\n insert: [\n { ts: Date.now(), type: MembershipActionType.RestartDelayedEvent },\n {\n ts: this.computeNextExpiryActionTs(this.state.expireUpdateIterations),\n type: MembershipActionType.UpdateExpiry,\n },\n ],\n };\n })\n .catch((e) => {\n const update = this.actionUpdateFromErrors(e, MembershipActionType.SendJoinEvent, \"sendStateEvent\");\n if (update) return update;\n throw e;\n });\n }\n\n private async updateExpiryOnJoinedEvent(): Promise<ActionUpdate> {\n const nextExpireUpdateIteration = this.state.expireUpdateIterations + 1;\n return await this.client\n .sendStateEvent(\n this.room.roomId,\n EventType.GroupCallMemberPrefix,\n this.makeMyMembership(this.membershipEventExpiryTimeout * nextExpireUpdateIteration),\n this.stateKey,\n )\n .then(() => {\n // Success, we reset retries and schedule update.\n this.resetRateLimitCounter(MembershipActionType.UpdateExpiry);\n this.state.expireUpdateIterations = nextExpireUpdateIteration;\n return {\n insert: [\n {\n ts: this.computeNextExpiryActionTs(nextExpireUpdateIteration),\n type: MembershipActionType.UpdateExpiry,\n },\n ],\n };\n })\n .catch((e) => {\n const update = this.actionUpdateFromErrors(e, MembershipActionType.UpdateExpiry, \"sendStateEvent\");\n if (update) return update;\n\n throw e;\n });\n }\n private async sendFallbackLeaveEvent(): Promise<ActionUpdate> {\n return await this.client\n .sendStateEvent(this.room.roomId, EventType.GroupCallMemberPrefix, {}, this.stateKey)\n .then(() => {\n this.resetRateLimitCounter(MembershipActionType.SendLeaveEvent);\n this.state.hasMemberStateEvent = false;\n return { replace: [] };\n })\n .catch((e) => {\n const update = this.actionUpdateFromErrors(e, MembershipActionType.SendLeaveEvent, \"sendStateEvent\");\n if (update) return update;\n throw e;\n });\n }\n\n // HELPERS\n private makeMembershipStateKey(localUserId: string, localDeviceId: string): string {\n const stateKey = `${localUserId}_${localDeviceId}`;\n if (/^org\\.matrix\\.msc(3757|3779)\\b/.exec(this.room.getVersion())) {\n return stateKey;\n } else {\n return `_${stateKey}`;\n }\n }\n\n /**\n * Constructs our own membership\n */\n private makeMyMembership(expires: number): SessionMembershipData {\n return {\n call_id: \"\",\n scope: \"m.room\",\n application: \"m.call\",\n device_id: this.deviceId,\n expires,\n focus_active: { type: \"livekit\", focus_selection: \"oldest_membership\" },\n foci_preferred: this.fociPreferred ?? [],\n };\n }\n\n // Error checks and handlers\n\n /**\n * Check if its a NOT_FOUND error\n * @param error the error causing this handler check/execution\n * @returns true if its a not found error\n */\n private isNotFoundError(error: unknown): boolean {\n return error instanceof MatrixError && error.errcode === \"M_NOT_FOUND\";\n }\n\n /**\n * Check if this is a DelayExceeded timeout and update the TimeoutOverride for the next try\n * @param error the error causing this handler check/execution\n * @returns true if its a delay exceeded error and we updated the local TimeoutOverride\n */\n private manageMaxDelayExceededSituation(error: unknown): boolean {\n if (\n error instanceof MatrixError &&\n error.errcode === \"M_UNKNOWN\" &&\n error.data[\"org.matrix.msc4140.errcode\"] === \"M_MAX_DELAY_EXCEEDED\"\n ) {\n const maxDelayAllowed = error.data[\"org.matrix.msc4140.max_delay\"];\n if (typeof maxDelayAllowed === \"number\" && this.membershipServerSideExpiryTimeout > maxDelayAllowed) {\n this.membershipServerSideExpiryTimeoutOverride = maxDelayAllowed;\n }\n logger.warn(\"Retry sending delayed disconnection event due to server timeout limitations:\", error);\n return true;\n }\n return false;\n }\n\n private actionUpdateFromErrors(\n error: unknown,\n type: MembershipActionType,\n method: string,\n ): ActionUpdate | undefined {\n const updateLimit = this.actionUpdateFromRateLimitError(error, method, type);\n if (updateLimit) return updateLimit;\n const updateNetwork = this.actionUpdateFromNetworkErrorRetry(error, type);\n if (updateNetwork) return updateNetwork;\n }\n /**\n * Check if we have a rate limit error and schedule the same action again if we dont exceed the rate limit retry count yet.\n * @param error the error causing this handler check/execution\n * @param method the method used for the throw message\n * @param type which MembershipActionType we reschedule because of a rate limit.\n * @throws If it is a rate limit error and the retry count got exceeded\n * @returns Returns true if we handled the error by rescheduling the correct next action.\n * Returns false if it is not a network error.\n */\n private actionUpdateFromRateLimitError(\n error: unknown,\n method: string,\n type: MembershipActionType,\n ): ActionUpdate | undefined {\n // \"Is rate limit\"-boundary\n if (!((error instanceof HTTPError || error instanceof MatrixError) && error.isRateLimitError())) {\n return undefined;\n }\n\n // retry boundary\n const rateLimitRetries = this.state.rateLimitRetries.get(type) ?? 0;\n if (rateLimitRetries < this.maximumRateLimitRetryCount) {\n let resendDelay: number;\n const defaultMs = 5000;\n try {\n resendDelay = error.getRetryAfterMs() ?? defaultMs;\n logger.info(`Rate limited by server, retrying in ${resendDelay}ms`);\n } catch (e) {\n logger.warn(\n `Error while retrieving a rate-limit retry delay, retrying after default delay of ${defaultMs}`,\n e,\n );\n resendDelay = defaultMs;\n }\n this.state.rateLimitRetries.set(type, rateLimitRetries + 1);\n return createInsertActionUpdate(type, resendDelay);\n }\n\n throw Error(\"Exceeded maximum retries for \" + type + \" attempts (client.\" + method + \"): \" + (error as Error));\n }\n\n /**\n * FIXME Don't Check the error and retry the same MembershipAction again in the configured time and for the configured retry count.\n * @param error the error causing this handler check/execution\n * @param type the action type that we need to repeat because of the error\n * @throws If it is a network error and the retry count got exceeded\n * @returns\n * Returns true if we handled the error by rescheduling the correct next action.\n * Returns false if it is not a network error.\n */\n private actionUpdateFromNetworkErrorRetry(error: unknown, type: MembershipActionType): ActionUpdate | undefined {\n // \"Is a network error\"-boundary\n const retries = this.state.networkErrorRetries.get(type) ?? 0;\n const retryDurationString = this.callMemberEventRetryDelayMinimum / 1000 + \"s\";\n const retryCounterString = \"(\" + retries + \"/\" + this.maximumNetworkErrorRetryCount + \")\";\n if (error instanceof Error && error.name === \"AbortError\") {\n logger.warn(\n \"Network local timeout error while sending event, retrying in \" +\n retryDurationString +\n \" \" +\n retryCounterString,\n error,\n );\n } else if (error instanceof Error && error.message.includes(\"updating delayed event\")) {\n // TODO: We do not want error message matching here but instead the error should be a typed HTTPError\n // and be handled below automatically (the same as in the SPA case).\n //\n // The error originates because of https://github.com/matrix-org/matrix-widget-api/blob/5d81d4a26ff69e4bd3ddc79a884c9527999fb2f4/src/ClientWidgetApi.ts#L698-L701\n // uses `e` instance of HttpError (and not MatrixError)\n // The element web widget driver (only checks for MatrixError) is then failing to process (`processError`) it as a typed error: https://github.com/element-hq/element-web/blob/471712cbf06a067e5499bd5d2d7a75f693d9a12d/src/stores/widgets/StopGapWidgetDriver.ts#L711-L715\n // So it will not call: `error.asWidgetApiErrorData()` which is also missing for `HttpError`\n //\n // A proper fix would be to either find a place to convert the `HttpError` into a `MatrixError` and the `processError`\n // method to handle it as expected or to adjust `processError` to also process `HttpError`'s.\n logger.warn(\n \"delayed event update timeout error, retrying in \" + retryDurationString + \" \" + retryCounterString,\n error,\n );\n } else if (error instanceof ConnectionError) {\n logger.warn(\n \"Network connection error while sending event, retrying in \" +\n retryDurationString +\n \" \" +\n retryCounterString,\n error,\n );\n } else if (\n (error instanceof HTTPError || error instanceof MatrixError) &&\n typeof error.httpStatus === \"number\" &&\n error.httpStatus >= 500 &&\n error.httpStatus < 600\n ) {\n logger.warn(\n \"Server error while sending event, retrying in \" + retryDurationString + \" \" + retryCounterString,\n error,\n );\n } else {\n return undefined;\n }\n\n // retry boundary\n if (retries < this.maximumNetworkErrorRetryCount) {\n this.state.networkErrorRetries.set(type, retries + 1);\n return createInsertActionUpdate(type, this.callMemberEventRetryDelayMinimum);\n }\n\n // Failure\n throw Error(\n \"Reached maximum (\" + this.maximumNetworkErrorRetryCount + \") retries cause by: \" + (error as Error),\n );\n }\n\n /**\n * Check if its an UnsupportedDelayedEventsEndpointError and which implies that we cannot do any delayed event logic\n * @param error The error to check\n * @returns true it its an UnsupportedDelayedEventsEndpointError\n */\n private isUnsupportedDelayedEndpoint(error: unknown): boolean {\n return error instanceof UnsupportedDelayedEventsEndpointError;\n }\n\n private resetRateLimitCounter(type: MembershipActionType): void {\n this.state.rateLimitRetries.set(type, 0);\n this.state.networkErrorRetries.set(type, 0);\n }\n\n public get status(): Status {\n const actions = this.scheduler.actions;\n if (actions.length === 1) {\n const { type } = actions[0];\n switch (type) {\n case MembershipActionType.SendDelayedEvent:\n case MembershipActionType.SendJoinEvent:\n return Status.Connecting;\n case MembershipActionType.UpdateExpiry: // where no delayed events\n return Status.Connected;\n case MembershipActionType.SendScheduledDelayedLeaveEvent:\n case MembershipActionType.SendLeaveEvent:\n return Status.Disconnecting;\n default:\n // pass through as not expected\n }\n } else if (actions.length === 2) {\n const types = actions.map((a) => a.type);\n // normal state for connected with delayed events\n if (\n (types.includes(MembershipActionType.RestartDelayedEvent) ||\n (types.includes(MembershipActionType.SendDelayedEvent) && this.state.hasMemberStateEvent)) &&\n types.includes(MembershipActionType.UpdateExpiry)\n ) {\n return Status.Connected;\n }\n } else if (actions.length === 3) {\n const types = actions.map((a) => a.type);\n // It is a correct connected state if we already schedule the next Restart but have not yet cleaned up\n // the current restart.\n if (\n types.filter((t) => t === MembershipActionType.RestartDelayedEvent).length === 2 &&\n types.includes(MembershipActionType.UpdateExpiry)\n ) {\n return Status.Connected;\n }\n }\n\n if (!this.scheduler.running) {\n return Status.Disconnected;\n }\n\n logger.error(\"MembershipManager has an unknown state. Actions: \", actions);\n return Status.Unknown;\n }\n}\n\nfunction createInsertActionUpdate(type: MembershipActionType, offset?: number): ActionUpdate {\n return {\n insert: [{ ts: Date.now() + (offset ?? 0), type }],\n };\n}\n\nfunction createReplaceActionUpdate(type: MembershipActionType, offset?: number): ActionUpdate {\n return {\n replace: [{ ts: Date.now() + (offset ?? 0), type }],\n };\n}\n"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,SAAS,QAAQ,oBAAoB;AAC9C,SAASC,wBAAwB,QAAQ,uBAAuB;AAEhE,SAASC,qCAAqC,QAAQ,cAAc;AACpE,SAASC,eAAe,EAAEC,SAAS,EAAEC,WAAW,QAAQ,uBAAuB;AAC/E,SAASC,MAAM,IAAIC,UAAU,QAAQ,cAAc;AAEnD,SAASC,KAAK,QAAwB,aAAa;AACnD,SAA8BC,uBAAuB,QAAoC,qBAAqB;AAE9G,SAGIC,sBAAsB,EACtBC,MAAM,QACH,YAAY;AACnB,SAASC,oBAAoB,QAAQ,mBAAmB;AAExD,SAASC,eAAe,QAA2B,0CAA0C;AAC7F,SAASC,iBAAiB,QAAQ,kCAAkC;AAEpE,IAAMR,MAAM,GAAGC,UAAU,CAACQ,QAAQ,CAAC,kBAAkB,CAAC;;AAEtD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;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AAC,CAAC;MAAEjJ;IAAK,CAAC;EACrD,CAAC;AACL;AAEA,SAASoF,yBAAyBA,CAACpF,IAA0B,EAAEiJ,MAAe,EAAgB;EAC1F,OAAO;IACHtF,OAAO,EAAE,CAAC;MAAEqC,EAAE,EAAEH,IAAI,CAACC,GAAG,CAAC,CAAC,IAAImD,MAAM,aAANA,MAAM,cAANA,MAAM,GAAI,CAAC,CAAC;MAAEjJ;IAAK,CAAC;EACtD,CAAC;AACL","ignoreList":[]}
@@ -54,7 +54,7 @@ export class ActionScheduler {
54
54
  _this.running = true;
55
55
  _this._actions = [{
56
56
  ts: Date.now(),
57
- type: MembershipActionType.SendFirstDelayedEvent
57
+ type: MembershipActionType.SendDelayedEvent
58
58
  }];
59
59
  try {
60
60
  var _loop = function* _loop() {
@@ -75,7 +75,7 @@ export class ActionScheduler {
75
75
  if (!wakeupUpdate) {
76
76
  logger.debug("Current MembershipManager processing: ".concat(nextAction.type, "\nQueue:"), _this._actions, "\nDate.now: \"".concat(Date.now()));
77
77
  try {
78
- // `this.wakeup` can also be called and sets the `wakupUpdate` object while we are in the handler.
78
+ // `this.wakeup` can also be called and sets the `wakeupUpdate` object while we are in the handler.
79
79
  handlerResult = yield _this.membershipLoopHandler(nextAction.type);
80
80
  } catch (e) {
81
81
  throw Error("The MembershipManager shut down because of the end condition: ".concat(e));
@@ -107,7 +107,7 @@ export class ActionScheduler {
107
107
  (_this$wakeup = this.wakeup) === null || _this$wakeup === void 0 || _this$wakeup.call(this, {
108
108
  replace: [{
109
109
  ts: Date.now(),
110
- type: MembershipActionType.SendFirstDelayedEvent
110
+ type: MembershipActionType.SendDelayedEvent
111
111
  }]
112
112
  });
113
113
  }
@@ -1 +1 @@
1
- {"version":3,"file":"NewMembershipManagerActionScheduler.js","names":["logger","rootLogger","sleep","MembershipActionType","getChild","ActionScheduler","constructor","membershipLoopHandler","_defineProperty","update","error","actions","_actions","startWithJoin","_this","_asyncToGenerator","running","ts","Date","now","type","SendFirstDelayedEvent","_loop","sort","a","b","nextAction","wakeupUpdate","undefined","wakeupPromise","Promise","resolve","wakeup","race","handlerResult","debug","concat","e","Error","splice","actionUpdate","replace","push","insert","length","initiateJoin","_this$wakeup","call","initiateLeave","_this$wakeup2","SendScheduledDelayedLeaveEvent"],"sources":["../../src/matrixrtc/NewMembershipManagerActionScheduler.ts"],"sourcesContent":["import { logger as rootLogger } from \"../logger.ts\";\nimport { type EmptyObject } from \"../matrix.ts\";\nimport { sleep } from \"../utils.ts\";\nimport { MembershipActionType } from \"./NewMembershipManager.ts\";\n\nconst logger = rootLogger.getChild(\"MatrixRTCSession\");\n\n/** @internal */\nexport interface Action {\n /**\n * When this action should be executed\n */\n ts: number;\n /**\n * The state of the different loops\n * can also be thought of as the type of the action\n */\n type: MembershipActionType;\n}\n\n/** @internal */\nexport type ActionUpdate =\n | {\n /** Replace all existing scheduled actions with this new array */\n replace: Action[];\n }\n | {\n /** Add these actions to the existing scheduled actions */\n insert: Action[];\n }\n | EmptyObject;\n\n/**\n * This scheduler tracks the state of the current membership participation\n * and runs one central timer that wakes up a handler callback with the correct action + state\n * whenever necessary.\n *\n * It can also be awakened whenever a new action is added which is\n * earlier then the current \"next awake\".\n * @internal\n */\nexport class ActionScheduler {\n /**\n * This is tracking the state of the scheduler loop.\n * Only used to prevent starting the loop twice.\n */\n public running = false;\n\n public constructor(\n /** This is the callback called for each scheduled action (`this.addAction()`) */\n private membershipLoopHandler: (type: MembershipActionType) => Promise<ActionUpdate>,\n ) {}\n\n // function for the wakeup mechanism (in case we add an action externally and need to leave the current sleep)\n private wakeup: (update: ActionUpdate) => void = (update: ActionUpdate): void => {\n logger.error(\"Cannot call wakeup before calling `startWithJoin()`\");\n };\n private _actions: Action[] = [];\n public get actions(): Action[] {\n return this._actions;\n }\n\n /**\n * This starts the main loop of the membership manager that handles event sending, delayed event sending and delayed event restarting.\n * @param initialActions The initial actions the manager will start with. It should be enough to pass: DelayedLeaveActionType.Initial\n * @returns Promise that resolves once all actions have run and no more are scheduled.\n * @throws This throws an error if one of the actions throws.\n * In most other error cases the manager will try to handle any server errors by itself.\n */\n public async startWithJoin(): Promise<void> {\n if (this.running) {\n logger.error(\"Cannot call startWithJoin() on NewMembershipActionScheduler while already running\");\n return;\n }\n this.running = true;\n this._actions = [{ ts: Date.now(), type: MembershipActionType.SendFirstDelayedEvent }];\n try {\n while (this._actions.length > 0) {\n // Sort so next (smallest ts) action is at the beginning\n this._actions.sort((a, b) => a.ts - b.ts);\n const nextAction = this._actions[0];\n let wakeupUpdate: ActionUpdate | undefined = undefined;\n\n // while we await for the next action, wakeup has to resolve the wakeupPromise\n const wakeupPromise = new Promise<void>((resolve) => {\n this.wakeup = (update: ActionUpdate): void => {\n wakeupUpdate = update;\n resolve();\n };\n });\n if (nextAction.ts > Date.now()) await Promise.race([wakeupPromise, sleep(nextAction.ts - Date.now())]);\n\n let handlerResult: ActionUpdate = {};\n if (!wakeupUpdate) {\n logger.debug(\n `Current MembershipManager processing: ${nextAction.type}\\nQueue:`,\n this._actions,\n `\\nDate.now: \"${Date.now()}`,\n );\n try {\n // `this.wakeup` can also be called and sets the `wakupUpdate` object while we are in the handler.\n handlerResult = await this.membershipLoopHandler(nextAction.type as MembershipActionType);\n } catch (e) {\n throw Error(`The MembershipManager shut down because of the end condition: ${e}`);\n }\n }\n // remove the processed action only after we are done processing\n this._actions.splice(0, 1);\n // The wakeupUpdate always wins since that is a direct external update.\n const actionUpdate = wakeupUpdate ?? handlerResult;\n\n if (\"replace\" in actionUpdate) {\n this._actions = actionUpdate.replace;\n } else if (\"insert\" in actionUpdate) {\n this._actions.push(...actionUpdate.insert);\n }\n }\n } finally {\n // Set the rtc session running state since we cannot recover from here and the consumer user of the\n // MatrixRTCSession class needs to manually rejoin.\n this.running = false;\n }\n\n logger.debug(\"Leave MembershipManager ActionScheduler loop (no more actions)\");\n }\n\n public initiateJoin(): void {\n this.wakeup?.({ replace: [{ ts: Date.now(), type: MembershipActionType.SendFirstDelayedEvent }] });\n }\n public initiateLeave(): void {\n this.wakeup?.({ replace: [{ ts: Date.now(), type: MembershipActionType.SendScheduledDelayedLeaveEvent }] });\n }\n}\n"],"mappings":";;AAAA,SAASA,MAAM,IAAIC,UAAU,QAAQ,cAAc;AAEnD,SAASC,KAAK,QAAQ,aAAa;AACnC,SAASC,oBAAoB,QAAQ,2BAA2B;AAEhE,IAAMH,MAAM,GAAGC,UAAU,CAACG,QAAQ,CAAC,kBAAkB,CAAC;;AAEtD;;AAaA;;AAYA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,eAAe,CAAC;EAOlBC,WAAWA,CACd;EACQC,qBAA4E,EACtF;IAAA,KADUA,qBAA4E,GAA5EA,qBAA4E;IARxF;AACJ;AACA;AACA;IAHIC,eAAA,kBAIiB,KAAK;IAOtB;IAAAA,eAAA,iBACkDC,MAAoB,IAAW;MAC7ET,MAAM,CAACU,KAAK,CAAC,qDAAqD,CAAC;IACvE,CAAC;IAAAF,eAAA,mBAC4B,EAAE;EAN5B;EAOH,IAAWG,OAAOA,CAAA,EAAa;IAC3B,OAAO,IAAI,CAACC,QAAQ;EACxB;;EAEA;AACJ;AACA;AACA;AACA;AACA;AACA;EACiBC,aAAaA,CAAA,EAAkB;IAAA,IAAAC,KAAA;IAAA,OAAAC,iBAAA;MACxC,IAAID,KAAI,CAACE,OAAO,EAAE;QACdhB,MAAM,CAACU,KAAK,CAAC,mFAAmF,CAAC;QACjG;MACJ;MACAI,KAAI,CAACE,OAAO,GAAG,IAAI;MACnBF,KAAI,CAACF,QAAQ,GAAG,CAAC;QAAEK,EAAE,EAAEC,IAAI,CAACC,GAAG,CAAC,CAAC;QAAEC,IAAI,EAAEjB,oBAAoB,CAACkB;MAAsB,CAAC,CAAC;MACtF,IAAI;QAAA,IAAAC,KAAA,aAAAA,MAAA,EACiC;UAC7B;UACAR,KAAI,CAACF,QAAQ,CAACW,IAAI,CAAC,CAACC,CAAC,EAAEC,CAAC,KAAKD,CAAC,CAACP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AC,MAAM,IAAI,QAAQ,IAAID,YAAY,EAAE;YACjC1B,KAAI,CAACF,QAAQ,CAAC8B,IAAI,CAAC,GAAGF,YAAY,CAACG,MAAM,CAAC;UAC9C;QACJ,CAAC;QAvCD,OAAO7B,KAAI,CAACF,QAAQ,CAACgC,MAAM,GAAG,CAAC;UAAA,OAAAtB,KAAA;QAAA;MAwCnC,CAAC,SAAS;QACN;QACA;QACAR,KAAI,CAACE,OAAO,GAAG,KAAK;MACxB;MAEAhB,MAAM,CAACmC,KAAK,CAAC,gEAAgE,CAAC;IAAC;EACnF;EAEOU,YAAYA,CAAA,EAAS;IAAA,IAAAC,YAAA;IACxB,CAAAA,YAAA,OAAI,CAACd,MAAM,cAAAc,YAAA,eAAXA,YAAA,CAAAC,IAAA,KAAI,EAAU;MAAEN,OAAO,EAAE,CAAC;QAAExB,EAAE,EAAEC,IAAI,CAACC,GAAG,CAAC,CAAC;QAAEC,IAAI,EAAEjB,oBAAoB,CAACkB;MAAsB,CAAC;IAAE,CAAC,CAAC;EACtG;EACO2B,aAAaA,CAAA,EAAS;IAAA,IAAAC,aAAA;IACzB,CAAAA,aAAA,OAAI,CAACjB,MAAM,cAAAiB,aAAA,eAAXA,aAAA,CAAAF,IAAA,KAAI,EAAU;MAAEN,OAAO,EAAE,CAAC;QAAExB,EAAE,EAAEC,IAAI,CAACC,GAAG,CAAC,CAAC;QAAEC,IAAI,EAAEjB,oBAAoB,CAAC+C;MAA+B,CAAC;IAAE,CAAC,CAAC;EAC/G;AACJ","ignoreList":[]}
1
+ {"version":3,"file":"NewMembershipManagerActionScheduler.js","names":["logger","rootLogger","sleep","MembershipActionType","getChild","ActionScheduler","constructor","membershipLoopHandler","_defineProperty","update","error","actions","_actions","startWithJoin","_this","_asyncToGenerator","running","ts","Date","now","type","SendDelayedEvent","_loop","sort","a","b","nextAction","wakeupUpdate","undefined","wakeupPromise","Promise","resolve","wakeup","race","handlerResult","debug","concat","e","Error","splice","actionUpdate","replace","push","insert","length","initiateJoin","_this$wakeup","call","initiateLeave","_this$wakeup2","SendScheduledDelayedLeaveEvent"],"sources":["../../src/matrixrtc/NewMembershipManagerActionScheduler.ts"],"sourcesContent":["import { logger as rootLogger } from \"../logger.ts\";\nimport { type EmptyObject } from \"../matrix.ts\";\nimport { sleep } from \"../utils.ts\";\nimport { MembershipActionType } from \"./NewMembershipManager.ts\";\n\nconst logger = rootLogger.getChild(\"MatrixRTCSession\");\n\n/** @internal */\nexport interface Action {\n /**\n * When this action should be executed\n */\n ts: number;\n /**\n * The state of the different loops\n * can also be thought of as the type of the action\n */\n type: MembershipActionType;\n}\n\n/** @internal */\nexport type ActionUpdate =\n | {\n /** Replace all existing scheduled actions with this new array */\n replace: Action[];\n }\n | {\n /** Add these actions to the existing scheduled actions */\n insert: Action[];\n }\n | EmptyObject;\n\n/**\n * This scheduler tracks the state of the current membership participation\n * and runs one central timer that wakes up a handler callback with the correct action + state\n * whenever necessary.\n *\n * It can also be awakened whenever a new action is added which is\n * earlier then the current \"next awake\".\n * @internal\n */\nexport class ActionScheduler {\n /**\n * This is tracking the state of the scheduler loop.\n * Only used to prevent starting the loop twice.\n */\n public running = false;\n\n public constructor(\n /** This is the callback called for each scheduled action (`this.addAction()`) */\n private membershipLoopHandler: (type: MembershipActionType) => Promise<ActionUpdate>,\n ) {}\n\n // function for the wakeup mechanism (in case we add an action externally and need to leave the current sleep)\n private wakeup: (update: ActionUpdate) => void = (update: ActionUpdate): void => {\n logger.error(\"Cannot call wakeup before calling `startWithJoin()`\");\n };\n private _actions: Action[] = [];\n public get actions(): Action[] {\n return this._actions;\n }\n\n /**\n * This starts the main loop of the membership manager that handles event sending, delayed event sending and delayed event restarting.\n * @param initialActions The initial actions the manager will start with. It should be enough to pass: DelayedLeaveActionType.Initial\n * @returns Promise that resolves once all actions have run and no more are scheduled.\n * @throws This throws an error if one of the actions throws.\n * In most other error cases the manager will try to handle any server errors by itself.\n */\n public async startWithJoin(): Promise<void> {\n if (this.running) {\n logger.error(\"Cannot call startWithJoin() on NewMembershipActionScheduler while already running\");\n return;\n }\n this.running = true;\n this._actions = [{ ts: Date.now(), type: MembershipActionType.SendDelayedEvent }];\n try {\n while (this._actions.length > 0) {\n // Sort so next (smallest ts) action is at the beginning\n this._actions.sort((a, b) => a.ts - b.ts);\n const nextAction = this._actions[0];\n let wakeupUpdate: ActionUpdate | undefined = undefined;\n\n // while we await for the next action, wakeup has to resolve the wakeupPromise\n const wakeupPromise = new Promise<void>((resolve) => {\n this.wakeup = (update: ActionUpdate): void => {\n wakeupUpdate = update;\n resolve();\n };\n });\n if (nextAction.ts > Date.now()) await Promise.race([wakeupPromise, sleep(nextAction.ts - Date.now())]);\n\n let handlerResult: ActionUpdate = {};\n if (!wakeupUpdate) {\n logger.debug(\n `Current MembershipManager processing: ${nextAction.type}\\nQueue:`,\n this._actions,\n `\\nDate.now: \"${Date.now()}`,\n );\n try {\n // `this.wakeup` can also be called and sets the `wakeupUpdate` object while we are in the handler.\n handlerResult = await this.membershipLoopHandler(nextAction.type as MembershipActionType);\n } catch (e) {\n throw Error(`The MembershipManager shut down because of the end condition: ${e}`);\n }\n }\n // remove the processed action only after we are done processing\n this._actions.splice(0, 1);\n // The wakeupUpdate always wins since that is a direct external update.\n const actionUpdate = wakeupUpdate ?? handlerResult;\n\n if (\"replace\" in actionUpdate) {\n this._actions = actionUpdate.replace;\n } else if (\"insert\" in actionUpdate) {\n this._actions.push(...actionUpdate.insert);\n }\n }\n } finally {\n // Set the rtc session running state since we cannot recover from here and the consumer user of the\n // MatrixRTCSession class needs to manually rejoin.\n this.running = false;\n }\n\n logger.debug(\"Leave MembershipManager ActionScheduler loop (no more actions)\");\n }\n\n public initiateJoin(): void {\n this.wakeup?.({ replace: [{ ts: Date.now(), type: MembershipActionType.SendDelayedEvent }] });\n }\n public initiateLeave(): void {\n this.wakeup?.({ replace: [{ ts: Date.now(), type: MembershipActionType.SendScheduledDelayedLeaveEvent }] });\n }\n}\n"],"mappings":";;AAAA,SAASA,MAA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AC;UAC9C;QACJ,CAAC;QAvCD,OAAO7B,KAAI,CAACF,QAAQ,CAACgC,MAAM,GAAG,CAAC;UAAA,OAAAtB,KAAA;QAAA;MAwCnC,CAAC,SAAS;QACN;QACA;QACAR,KAAI,CAACE,OAAO,GAAG,KAAK;MACxB;MAEAhB,MAAM,CAACmC,KAAK,CAAC,gEAAgE,CAAC;IAAC;EACnF;EAEOU,YAAYA,CAAA,EAAS;IAAA,IAAAC,YAAA;IACxB,CAAAA,YAAA,OAAI,CAACd,MAAM,cAAAc,YAAA,eAAXA,YAAA,CAAAC,IAAA,KAAI,EAAU;MAAEN,OAAO,EAAE,CAAC;QAAExB,EAAE,EAAEC,IAAI,CAACC,GAAG,CAAC,CAAC;QAAEC,IAAI,EAAEjB,oBAAoB,CAACkB;MAAiB,CAAC;IAAE,CAAC,CAAC;EACjG;EACO2B,aAAaA,CAAA,EAAS;IAAA,IAAAC,aAAA;IACzB,CAAAA,aAAA,OAAI,CAACjB,MAAM,cAAAiB,aAAA,eAAXA,aAAA,CAAAF,IAAA,KAAI,EAAU;MAAEN,OAAO,EAAE,CAAC;QAAExB,EAAE,EAAEC,IAAI,CAACC,GAAG,CAAC,CAAC;QAAEC,IAAI,EAAEjB,oBAAoB,CAAC+C;MAA+B,CAAC;IAAE,CAAC,CAAC;EAC/G;AACJ","ignoreList":[]}
@@ -4,4 +4,5 @@ export * from "./LivekitFocus.ts";
4
4
  export * from "./MatrixRTCSession.ts";
5
5
  export * from "./MatrixRTCSessionManager.ts";
6
6
  export type * from "./types.ts";
7
+ export { Status, MembershipManagerEvent } from "./types.ts";
7
8
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/matrixrtc/index.ts"],"names":[],"mappings":"AAgBA,cAAc,qBAAqB,CAAC;AACpC,mBAAmB,YAAY,CAAC;AAChC,cAAc,mBAAmB,CAAC;AAClC,cAAc,uBAAuB,CAAC;AACtC,cAAc,8BAA8B,CAAC;AAC7C,mBAAmB,YAAY,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/matrixrtc/index.ts"],"names":[],"mappings":"AAgBA,cAAc,qBAAqB,CAAC;AACpC,mBAAmB,YAAY,CAAC;AAChC,cAAc,mBAAmB,CAAC;AAClC,cAAc,uBAAuB,CAAC;AACtC,cAAc,8BAA8B,CAAC;AAC7C,mBAAmB,YAAY,CAAC;AAChC,OAAO,EAAE,MAAM,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC"}
@@ -18,4 +18,5 @@ export * from "./CallMembership.js";
18
18
  export * from "./LivekitFocus.js";
19
19
  export * from "./MatrixRTCSession.js";
20
20
  export * from "./MatrixRTCSessionManager.js";
21
+ export { Status, MembershipManagerEvent } from "./types.js";
21
22
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/matrixrtc/index.ts"],"sourcesContent":["/*\nCopyright 2024 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport * from \"./CallMembership.ts\";\nexport type * from \"./focus.ts\";\nexport * from \"./LivekitFocus.ts\";\nexport * from \"./MatrixRTCSession.ts\";\nexport * from \"./MatrixRTCSessionManager.ts\";\nexport type * from \"./types.ts\";\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,cAAc,qBAAqB;AAEnC,cAAc,mBAAmB;AACjC,cAAc,uBAAuB;AACrC,cAAc,8BAA8B","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["Status","MembershipManagerEvent"],"sources":["../../src/matrixrtc/index.ts"],"sourcesContent":["/*\nCopyright 2024 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport * from \"./CallMembership.ts\";\nexport type * from \"./focus.ts\";\nexport * from \"./LivekitFocus.ts\";\nexport * from \"./MatrixRTCSession.ts\";\nexport * from \"./MatrixRTCSessionManager.ts\";\nexport type * from \"./types.ts\";\nexport { Status, MembershipManagerEvent } from \"./types.ts\";\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,cAAc,qBAAqB;AAEnC,cAAc,mBAAmB;AACjC,cAAc,uBAAuB;AACrC,cAAc,8BAA8B;AAE5C,SAASA,MAAM,EAAEC,sBAAsB,QAAQ,YAAY","ignoreList":[]}
@@ -1,4 +1,6 @@
1
- import { type IMentions } from "../matrix.ts";
1
+ import type { IMentions } from "../matrix.ts";
2
+ import type { CallMembership } from "./CallMembership.ts";
3
+ import type { Focus } from "./focus.ts";
2
4
  export interface EncryptionKeyEntry {
3
5
  index: number;
4
6
  key: string;
@@ -16,4 +18,78 @@ export interface ICallNotifyContent {
16
18
  "notify_type": CallNotifyType;
17
19
  "call_id": string;
18
20
  }
21
+ export declare enum Status {
22
+ Disconnected = "Disconnected",
23
+ Connecting = "Connecting",
24
+ ConnectingFailed = "ConnectingFailed",
25
+ Connected = "Connected",
26
+ Reconnecting = "Reconnecting",
27
+ Disconnecting = "Disconnecting",
28
+ Stuck = "Stuck",
29
+ Unknown = "Unknown"
30
+ }
31
+ export declare enum MembershipManagerEvent {
32
+ StatusChanged = "StatusChanged"
33
+ }
34
+ export type MembershipManagerEventHandlerMap = {
35
+ [MembershipManagerEvent.StatusChanged]: (prefStatus: Status, newStatus: Status) => void;
36
+ };
37
+ /**
38
+ * This interface defines what a MembershipManager uses and exposes.
39
+ * This interface is what we use to write tests and allows changing the actual implementation
40
+ * without breaking tests because of some internal method renaming.
41
+ *
42
+ * @internal
43
+ */
44
+ export interface IMembershipManager {
45
+ /**
46
+ * If we are trying to join, or have successfully joined the session.
47
+ * It does not reflect if the room state is already configured to represent us being joined.
48
+ * It only means that the Manager should be trying to connect or to disconnect running.
49
+ * The Manager is still running right after isJoined becomes false to send the disconnect events.
50
+ * @returns true if we intend to be participating in the MatrixRTC session
51
+ * @deprecated This name is confusing and replaced by `isActivated()`. (Returns the same as `isActivated()`)
52
+ */
53
+ isJoined(): boolean;
54
+ /**
55
+ * If the manager is activated. This means it tries to do its job to join the call, resend state events...
56
+ * It does not imply that the room state is already configured to represent being joined.
57
+ * It means that the Manager tries to connect or is connected. ("the manager is still active")
58
+ * Once `leave()` is called the manager is not activated anymore but still running until `leave()` resolves.
59
+ * @returns `true` if we intend to be participating in the MatrixRTC session
60
+ */
61
+ isActivated(): boolean;
62
+ /**
63
+ * Get the actual connection status of the manager.
64
+ */
65
+ get status(): Status;
66
+ /**
67
+ * The current status while the manager is activated
68
+ */
69
+ /**
70
+ * Start sending all necessary events to make this user participate in the RTC session.
71
+ * @param fociPreferred the list of preferred foci to use in the joined RTC membership event.
72
+ * @param fociActive the active focus to use in the joined RTC membership event.
73
+ * @throws can throw if it exceeds a configured maximum retry.
74
+ */
75
+ join(fociPreferred: Focus[], fociActive?: Focus, onError?: (error: unknown) => void): void;
76
+ /**
77
+ * Send all necessary events to make this user leave the RTC session.
78
+ * @param timeout the maximum duration in ms until the promise is forced to resolve.
79
+ * @returns It resolves with true in case the leave was sent successfully.
80
+ * It resolves with false in case we hit the timeout before sending successfully.
81
+ */
82
+ leave(timeout?: number): Promise<boolean>;
83
+ /**
84
+ * Call this if the MatrixRTC session members have changed.
85
+ */
86
+ onRTCSessionMemberUpdate(memberships: CallMembership[]): Promise<void>;
87
+ /**
88
+ * The used active focus in the currently joined session.
89
+ * @returns the used active focus in the currently joined session or undefined if not joined.
90
+ */
91
+ getActiveFocus(): Focus | undefined;
92
+ on(event: MembershipManagerEvent.StatusChanged, listener: (oldStatus: Status, newStatus: Status) => void): this;
93
+ off(event: MembershipManagerEvent.StatusChanged, listener: (oldStatus: Status, newStatus: Status) => void): this;
94
+ }
19
95
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/matrixrtc/types.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,KAAK,SAAS,EAAE,MAAM,cAAc,CAAC;AAC9C,MAAM,WAAW,kBAAkB;IAC/B,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,0BAA0B;IACvC,IAAI,EAAE,kBAAkB,EAAE,CAAC;IAC3B,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,MAAM,cAAc,GAAG,MAAM,GAAG,QAAQ,CAAC;AAE/C,MAAM,WAAW,kBAAkB;IAC/B,aAAa,EAAE,MAAM,CAAC;IACtB,YAAY,EAAE,SAAS,CAAC;IACxB,aAAa,EAAE,cAAc,CAAC;IAC9B,SAAS,EAAE,MAAM,CAAC;CACrB"}
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/matrixrtc/types.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AA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OAKG;IACH,KAAK,CAAC,OAAO,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAC1C;;OAEG;IACH,wBAAwB,CAAC,WAAW,EAAE,cAAc,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACvE;;;OAGG;IACH,cAAc,IAAI,KAAK,GAAG,SAAS,CAAC;IAGpC,EAAE,CAAC,KAAK,EAAE,sBAAsB,CAAC,aAAa,EAAE,QAAQ,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,KAAK,IAAI,GAAG,IAAI,CAAC;IAChH,GAAG,CAAC,KAAK,EAAE,sBAAsB,CAAC,aAAa,EAAE,QAAQ,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,KAAK,IAAI,GAAG,IAAI,CAAC;CACpH"}
@@ -1 +1,40 @@
1
- export {};
1
+ /*
2
+ Copyright 2023 The Matrix.org Foundation C.I.C.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+
17
+ export var Status = /*#__PURE__*/function (Status) {
18
+ Status["Disconnected"] = "Disconnected";
19
+ Status["Connecting"] = "Connecting";
20
+ Status["ConnectingFailed"] = "ConnectingFailed";
21
+ Status["Connected"] = "Connected";
22
+ Status["Reconnecting"] = "Reconnecting";
23
+ Status["Disconnecting"] = "Disconnecting";
24
+ Status["Stuck"] = "Stuck";
25
+ Status["Unknown"] = "Unknown";
26
+ return Status;
27
+ }({});
28
+ export var MembershipManagerEvent = /*#__PURE__*/function (MembershipManagerEvent) {
29
+ MembershipManagerEvent["StatusChanged"] = "StatusChanged";
30
+ return MembershipManagerEvent;
31
+ }({});
32
+
33
+ /**
34
+ * This interface defines what a MembershipManager uses and exposes.
35
+ * This interface is what we use to write tests and allows changing the actual implementation
36
+ * without breaking tests because of some internal method renaming.
37
+ *
38
+ * @internal
39
+ */
40
+ //# sourceMappingURL=types.js.map