import { type ISendEventResponse, type SendDelayedEventResponse } from "../@types/requests.ts"; import { type EmptyObject } from "../@types/common.ts"; import type { MatrixClient } from "../client.ts"; import { type Logger } from "../logger.ts"; import { type Room } from "../models/room.ts"; import { type CallMembership } from "./CallMembership.ts"; import { type Transport, type RTCCallCapability, type RTCCallIntent, Status, type SlotDescription } from "./types.ts"; import { type MembershipConfig, type SessionConfig } from "./MatrixRTCSession.ts"; import { type ActionUpdate } from "./MembershipManagerActionScheduler.ts"; import { TypedEventEmitter } from "../models/typed-event-emitter.ts"; import { MembershipManagerEvent, type IMembershipManager, type MembershipManagerEventHandlerMap } from "./IMembershipManager.ts"; import { type RtcLeftMembershipData, type RtcMembershipData, type SessionMembershipData } from "./membershipData/index.ts"; /** * The different types of actions the MembershipManager can take. * @internal */ export declare enum MembershipActionType { SendDelayedEvent = "SendDelayedEvent", SendJoinEvent = "SendJoinEvent", RestartDelayedEvent = "RestartDelayedEvent", UpdateExpiry = "UpdateExpiry", SendScheduledDelayedLeaveEvent = "SendScheduledDelayedLeaveEvent", SendLeaveEvent = "SendLeaveEvent" } /** * @internal */ export interface MembershipManagerState { /** The delayId we got when successfully sending the delayed leave event. * Gets set to undefined if the server claims it cannot find the delayed event anymore. */ delayId?: string; /** Stores how often we have update the `expires` field. * `expireUpdateIterations` * `membershipEventExpiryTimeout` resolves to the value the expires field should contain next */ expireUpdateIterations: number; /** The time at which we send the first state event. The time the call started from the DAG point of view. * This is used to compute the local sleep timestamps when to next update the member event with a new expires value. */ startTime: number; /** The manager is in the state where its actually connected to the session. */ hasMemberStateEvent: boolean; /** Retry counter for rate limits */ rateLimitRetries: Map; /** Retry counter for other errors */ networkErrorRetries: Map; /** The time at which we expect the server to send the delayed leave event. */ expectedServerDelayLeaveTs?: number; /** The time at which the membership we last sent stops being valid for other clients. * Recorded when sending, see `membershipExpiryTsOf`. */ membershipExpiryTs: number; /** This is used to track if the client expects the scheduled delayed leave event to have * been sent because restarting failed during the available time. * Once we resend the delayed event or successfully restarted it will get unset. */ probablyLeft: boolean; } type MembershipManagerClient = Pick; /** * This class is responsible for sending all events relating to the own membership of a matrixRTC call. * It has the following tasks: * - Send the users leave delayed event before sending the membership * - Send the users membership if the state machine is started * - Check if the delayed event was canceled due to sending the membership * - update the delayed event (`restart`) * - Update the state event every ~5h = `DEFAULT_EXPIRE_DURATION` (so it does not get treated as expired) * - When the state machine is stopped: * - Disconnect the member * - Stop the timer for the delay refresh * - Stop the timer for updating the state event */ export declare class MembershipManager extends TypedEventEmitter implements IMembershipManager { private readonly joinConfig; protected readonly room: Pick; protected readonly client: MembershipManagerClient; readonly slotDescription: SlotDescription; private activated; private readonly logger; /** * The intent of the call from the perspective of this user. This may be an audio call, video call or * something else. * * This carries the stable identifiers (`m.audio`, `m.video`) */ protected callIntent: RTCCallIntent | undefined; protected callCapabilities: RTCCallCapability[] | undefined; protected applicationData: Record | undefined; isActivated(): boolean; isJoined(): boolean; /** * Puts the MembershipManager in a state where it tries to be joined. * It will send delayed events and membership events * @param publishedTransports the list of transports on which the member is publishing. * @param onError This will be called once the membership manager encounters an unrecoverable error. * This should bubble up the the frontend to communicate that the call does not work in the current environment. * The original underlying error is preserved as `error.cause`, so consumers can `instanceof`-check the typed * cause. */ join(publishedTransports: Transport[], onError?: (error: unknown) => void): void; /** * Leave from the call (Send an rtc session event with content: `{}`) * @param timeout the maximum duration this promise will take to resolve * @returns true if it managed to leave and false if the timeout condition happened. */ leave(timeout?: number): Promise; private leavePromiseResolvers?; onRTCSessionMemberUpdate(memberships: CallMembership[]): Promise; updateCallIntent(callIntent: RTCCallIntent): Promise; updateApplicationData(applicationData: Record): Promise; /** Drops the keys the SDK writes itself from an application data record. */ private stripReservedApplicationData; /** * @throws if the client does not return user or device id. * @param joinConfig * @param room * @param client */ constructor(joinConfig: (SessionConfig & MembershipConfig) | undefined, room: Pick, client: MembershipManagerClient, slotDescription: SlotDescription, parentLogger?: Logger); private _ownMembership?; get ownMembership(): CallMembership | undefined; private oldStatus?; private scheduler; private state; private static get defaultState(); protected deviceId: string; protected userId: string; protected stateKey: string; protected publishedTransports: Transport[]; private delayedLeaveEventDelayMsOverride?; private capabilitiesUnreachableUntil; private get networkErrorRetryMs(); private get membershipEventExpiryMs(); private get membershipEventExpiryHeadroomMs(); private computeNextExpiryActionTs; protected get delayedLeaveEventDelayMs(): number; private get delayedLeaveEventRestartMs(); private get maximumRateLimitRetryCount(); private get maximumNetworkErrorRetryCount(); private get delayedLeaveEventRestartLocalTimeoutMs(); private membershipLoopHandler; protected clientSendDelayedDisconnectMembership: () => Promise; private sendOrResendDelayedLeaveEvent; private cancelKnownDelayIdBeforeSendDelayedEvent; private setAndEmitProbablyLeft; private setAndEmitDelayId; /** * Attempts to restart the delayed leave event and keeps everything that depends on it in sync. * * @param delayId the id of the delayed leave event to restart * @returns the outcome of the attempt. */ private tryRestartDelayedEvent; private restartDelayedEvent; private sendScheduledDelayedLeaveEventOrFallbackToSendLeaveEvent; protected clientSendMembership: (myMembership: RtcMembershipData | SessionMembershipData | EmptyObject) => Promise; /** Sends the event that marks our membership as left. */ protected clientSendLeaveMembership: () => Promise; private sendJoinEvent; /** * The timestamp at which a membership we send stops being valid for other clients. * * State events are valid until `created_ts + expires`. `makeMyMembership` inherits `created_ts` from our previous * membership when we have one, otherwise the event's own timestamp counts. * @param sent the membership as we sent it */ protected membershipExpiryTsOf(sent: SessionMembershipData | RtcMembershipData): number; /** * Gives up on our current membership and starts a fresh join. * * We forget our own membership so that the next state event does not inherit its `created_ts`. That would keep * the identity of the membership we are giving up while `expires` starts over from a single iteration, which can * put the absolute expiry in the past. * @param reason why we are not keeping the current membership. Only used for logging. */ private rejoinFromScratch; /** * Schedules another attempt at the expiry update. Once our membership has expired we stop trying to keep it alive * and rejoin instead, so that we never end up silently expired. * @param delayMs how long to wait before trying again. Clamped so that we always get a last attempt at the moment * the membership expires, and never schedule one beyond it. * @param reason why we cannot update the expiry right now. Only used for logging. * @param resendDelayedEvent whether to schedule a replacement delayed leave event first, with the retry running * right after it. */ private deferExpiryUpdate; /** * Makes sure a delayed leave event is scheduled that will outlive the membership update we are about to send. * * Re-sending our membership is only safe while our delayed leave event is still scheduled: if the server has * already sent it (e.g. because the device was asleep and no restarts reached the server), the membership we * would send would come back to life without any delayed leave event to clean it up, and stay until `expires` * runs out. So we restart the delayed event first. A success guarantees it will outlive the membership update; * if it is gone instead, we have to work out why. * @returns `undefined` if the membership can be sent, otherwise the action to take instead. */ private ensureDelayedLeaveEventProtectsMembership; /** * Without a delay id, a `SendDelayedEvent` action may be queued that has not succeeded yet. Then we wait for it * rather than put the membership back on the server with nothing to clean it up. The retry gets the same * timestamp, and actions with the same timestamp run in insertion order, so it runs right after that attempt: * straight away if the delayed event is there, or to wait for the next attempt if it rescheduled. * * Without such an action queued we are not using delayed events at all, because the homeserver does not support * them. Then there is also no delayed leave event that could have removed our membership, and nothing to protect * it from. * @returns `undefined` if the membership can be sent, otherwise the deferred expiry update. */ private waitForPendingDelayedLeaveEvent; /** * The server does not know our delayed leave event anymore. Whether it sent it or lost it decides whether we * still have a membership to extend. */ private recoverFromGoneDelayedLeaveEvent; /** * Restarting our delayed leave event failed with something other than the delayed event being gone. * @param error what the restart failed with * @returns `undefined` if the membership can be sent regardless, otherwise the action to take instead. * @throws the error if it is not one we retry on. */ private recoverFromFailedDelayedLeaveEventRestart; private updateExpiryOnJoinedEvent; private sendFallbackLeaveEvent; /** * this creates `${localUserId}_${localDeviceId}_${this.slotDescription.application}${this.slotDescription.id}` * which is not compatible with membershipID of session type member events. They have to be `${localUserId}:${localDeviceId}` */ private makeMembershipStateKey; /** * Constructs our own membership * @returns Only returns `SessionMembershipData` */ protected makeMyMembership(expires: number): SessionMembershipData | RtcMembershipData; /** * Check if its a NOT_FOUND error * @param error the error causing this handler check/execution * @returns true if its a not found error */ private isNotFoundError; /** * Check if its a 409 (conflict) error. * A homeserver answers a delayed event management action (restart, cancel, send) with a 409 if the delayed event * is already finalised with an outcome that conflicts with the action * (MSC4140 — https://github.com/matrix-org/matrix-spec-proposals/blob/main/proposals/4140-delayed-events-futures.md). * The MSC does not mandate an errcode for this case, so we only check the http status. * @param error the error causing this handler check/execution * @returns true if its a conflict error */ private isConflictError; /** * Check if the error tells us that the delayed event we tried to manage is gone: either the homeserver does not * know about it anymore (404) or it is already finalised with an outcome that conflicts with our action (409). * In both cases the delayed event will not do what we asked, so the `delayId` is stale and needs to be replaced. * @param error the error causing this handler check/execution * @returns true if the delayed event is gone */ private isDelayedEventGoneError; /** * Check if the server rejected the delay of a delayed event for exceeding its maximum * @param error the error causing this handler check/execution * @returns true if its a delay too large error */ private isDelayTooLargeError; /** * Apply the limits of the delayed events capability ([MSC4140](https://github.com/matrix-org/matrix-spec-proposals/blob/main/proposals/4140-delayed-events-futures.md)) * by clamping the delay of the delayed leave event to the advertised maximum. * @param capabilities the homeserver capabilities, or undefined if they are not known. * @returns false if the capabilities do not advertise delayed events or say that they are disabled, true * otherwise (also if the capabilities are not known). */ private applyDelayedEventsCapability; /** * Check if this is a DelayExceeded timeout and update the TimeoutOverride for the next try * @param error the error causing this handler check/execution * @returns true if its a delay exceeded error and we updated the local TimeoutOverride */ private manageMaxDelayExceededSituation; protected actionUpdateFromErrors(error: unknown, type: MembershipActionType, method: string): ActionUpdate | undefined; /** * Check if we have a rate limit error and schedule the same action again if we dont exceed the rate limit retry count yet. * @param error the error causing this handler check/execution * @param method the method used for the throw message * @param type which MembershipActionType we reschedule because of a rate limit. * @throws If it is a rate limit error and the retry count got exceeded * @returns Returns true if we handled the error by rescheduling the correct next action. * Returns false if it is not a network error. */ private actionUpdateFromRateLimitError; /** * FIXME Don't Check the error and retry the same MembershipAction again in the configured time and for the configured retry count. * @param error the error causing this handler check/execution * @param type the action type that we need to repeat because of the error * @throws If it is a network error and the retry count got exceeded * @returns * Returns true if we handled the error by rescheduling the correct next action. * Returns false if it is not a network error. */ private actionUpdateFromNetworkErrorRetry; /** * Check if its an UnsupportedDelayedEventsEndpointError and which implies that we cannot do any delayed event logic * @param error The error to check * @returns true it its an UnsupportedDelayedEventsEndpointError */ private isUnsupportedDelayedEndpoint; private resetRateLimitCounter; get status(): Status; get probablyLeft(): boolean; get delayId(): string | undefined; } /** * Implementation of the Membership manager that uses sticky events * rather than state events. */ export declare class StickyEventMembershipManager extends MembershipManager { private readonly clientWithSticky; private readonly memberId; constructor(joinConfig: (SessionConfig & MembershipConfig) | undefined, room: Pick, clientWithSticky: MembershipManagerClient & Pick, sessionDescription: SlotDescription, memberId: string, parentLogger?: Logger); protected clientSendDelayedDisconnectMembership: () => Promise; protected clientSendMembership: (myMembership: RtcMembershipData | SessionMembershipData | EmptyObject) => Promise; protected clientSendLeaveMembership: () => Promise; private static nameMap; protected actionUpdateFromErrors(e: unknown, t: MembershipActionType, m: string): ActionUpdate | undefined; /** A sticky event vanishes `MEMBERSHIP_STICKY_DURATION_MS` after it was sent, whatever its content says. */ protected membershipExpiryTsOf(): number; /** * * @returns Only returns `RtcMembershipData` */ protected makeMyMembership(): RtcMembershipData; /** * The content of the `m.rtc.member` event that marks our membership as left. */ protected makeMyLeftMembership(): RtcLeftMembershipData; } export {}; //# sourceMappingURL=MembershipManager.d.ts.map