fcr-core
Version:
Core APIs for building online scenes
465 lines (455 loc) • 23.1 kB
JavaScript
import "core-js/modules/es.array.push.js";
import "core-js/modules/esnext.function.metadata.js";
import "core-js/modules/esnext.symbol.metadata.js";
let _initProto, _startPeerSessionDecs, _stopPeerSessionDecs, _endPeerSessionDecs, _acceptPeerSessionDecs, _rejectPeerSessionDecs;
import "core-js/modules/es.json.stringify.js";
import "core-js/modules/esnext.map.delete-all.js";
import "core-js/modules/esnext.map.emplace.js";
import "core-js/modules/esnext.map.every.js";
import "core-js/modules/esnext.map.filter.js";
import "core-js/modules/esnext.map.find.js";
import "core-js/modules/esnext.map.find-key.js";
import "core-js/modules/esnext.map.includes.js";
import "core-js/modules/esnext.map.key-of.js";
import "core-js/modules/esnext.map.map-keys.js";
import "core-js/modules/esnext.map.map-values.js";
import "core-js/modules/esnext.map.merge.js";
import "core-js/modules/esnext.map.reduce.js";
import "core-js/modules/esnext.map.some.js";
import "core-js/modules/esnext.map.update.js";
function _applyDecs(e, t, r, n, o, a) { function i(e, t, r) { return function (n, o) { return r && r(n), e[t].call(n, o); }; } function c(e, t) { for (var r = 0; r < e.length; r++) e[r].call(t); return t; } function s(e, t, r, n) { if ("function" != typeof e && (n || void 0 !== e)) throw new TypeError(t + " must " + (r || "be") + " a function" + (n ? "" : " or undefined")); return e; } function applyDec(e, t, r, n, o, a, c, u, l, f, p, d, h) { function m(e) { if (!h(e)) throw new TypeError("Attempted to access private element on non-instance"); } var y, v = t[0], g = t[3], b = !u; if (!b) { r || Array.isArray(v) || (v = [v]); var w = {}, S = [], A = 3 === o ? "get" : 4 === o || d ? "set" : "value"; f ? (p || d ? w = { get: _setFunctionName(function () { return g(this); }, n, "get"), set: function (e) { t[4](this, e); } } : w[A] = g, p || _setFunctionName(w[A], n, 2 === o ? "" : A)) : p || (w = Object.getOwnPropertyDescriptor(e, n)); } for (var P = e, j = v.length - 1; j >= 0; j -= r ? 2 : 1) { var D = v[j], E = r ? v[j - 1] : void 0, I = {}, O = { kind: ["field", "accessor", "method", "getter", "setter", "class"][o], name: n, metadata: a, addInitializer: function (e, t) { if (e.v) throw Error("attempted to call addInitializer after decoration was finished"); s(t, "An initializer", "be", !0), c.push(t); }.bind(null, I) }; try { if (b) (y = s(D.call(E, P, O), "class decorators", "return")) && (P = y);else { var k, F; O.static = l, O.private = f, f ? 2 === o ? k = function (e) { return m(e), w.value; } : (o < 4 && (k = i(w, "get", m)), 3 !== o && (F = i(w, "set", m))) : (k = function (e) { return e[n]; }, (o < 2 || 4 === o) && (F = function (e, t) { e[n] = t; })); var N = O.access = { has: f ? h.bind() : function (e) { return n in e; } }; if (k && (N.get = k), F && (N.set = F), P = D.call(E, d ? { get: w.get, set: w.set } : w[A], O), d) { if ("object" == typeof P && P) (y = s(P.get, "accessor.get")) && (w.get = y), (y = s(P.set, "accessor.set")) && (w.set = y), (y = s(P.init, "accessor.init")) && S.push(y);else if (void 0 !== P) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0"); } else s(P, (p ? "field" : "method") + " decorators", "return") && (p ? S.push(P) : w[A] = P); } } finally { I.v = !0; } } return (p || d) && u.push(function (e, t) { for (var r = S.length - 1; r >= 0; r--) t = S[r].call(e, t); return t; }), p || b || (f ? d ? u.push(i(w, "get"), i(w, "set")) : u.push(2 === o ? w[A] : i.call.bind(w[A])) : Object.defineProperty(e, n, w)), P; } function u(e, t) { return Object.defineProperty(e, Symbol.metadata || Symbol.for("Symbol.metadata"), { configurable: !0, enumerable: !0, value: t }); } if (arguments.length >= 6) var l = a[Symbol.metadata || Symbol.for("Symbol.metadata")]; var f = Object.create(null == l ? null : l), p = function (e, t, r, n) { var o, a, i = [], s = function (t) { return _checkInRHS(t) === e; }, u = new Map(); function l(e) { e && i.push(c.bind(null, e)); } for (var f = 0; f < t.length; f++) { var p = t[f]; if (Array.isArray(p)) { var d = p[1], h = p[2], m = p.length > 3, y = 16 & d, v = !!(8 & d), g = 0 == (d &= 7), b = h + "/" + v; if (!g && !m) { var w = u.get(b); if (!0 === w || 3 === w && 4 !== d || 4 === w && 3 !== d) throw Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + h); u.set(b, !(d > 2) || d); } applyDec(v ? e : e.prototype, p, y, m ? "#" + h : _toPropertyKey(h), d, n, v ? a = a || [] : o = o || [], i, v, m, g, 1 === d, v && m ? s : r); } } return l(o), l(a), i; }(e, t, o, f); return r.length || u(e, f), { e: p, get c() { var t = []; return r.length && [u(applyDec(e, [r], n, e.name, 5, f, t), f), c.bind(null, t, e)]; } }; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _setFunctionName(e, t, n) { "symbol" == typeof t && (t = (t = t.description) ? "[" + t + "]" : ""); try { Object.defineProperty(e, "name", { configurable: !0, value: n ? n + " " + t : t }); } catch (e) {} return e; }
function _checkInRHS(e) { if (Object(e) !== e) throw TypeError("right-hand side of 'in' should be an object, got " + (null !== e ? typeof e : "null")); return e; }
import { AgoraObservable, md5, Duration, ActionWhenTaskFail, AgoraScheduler, trace, ErrorModuleCode, DetailErrorCode } from '../imports';
import { generateFcrCoreClientError, generateFcrCoreServerError } from '../utilities/error';
import { createLogger, generateLogObserver } from '../utilities/logger';
import { fcrPeerSessionParamsSchema, fcrSessionBaseSchema, stringKeyUnknownValueSchema, stringSchema } from '../schema';
import validateParams from '../utilities/validate-params';
/**
* The multiplier of the keepalive timeout.
*/
export const KEEPALIVE_TIMEOUT_MULTIPLIER = 2;
/**
* @internal
*/
export class FcrPeerSessionControlImpl {
static {
[_initProto] = _applyDecs(this, [[_startPeerSessionDecs, 2, "startPeerSession"], [_stopPeerSessionDecs, 2, "stopPeerSession"], [_endPeerSessionDecs, 2, "endPeerSession"], [_acceptPeerSessionDecs, 2, "acceptPeerSession"], [_rejectPeerSessionDecs, 2, "rejectPeerSession"], [trace, 2, "release"]], []).e;
}
//@internal
[(_startPeerSessionDecs = [trace(['params']), validateParams(fcrPeerSessionParamsSchema)], _stopPeerSessionDecs = [trace(['sessionId']), validateParams(stringSchema)], _endPeerSessionDecs = [trace(['sessionId', 'cause']), validateParams(stringSchema, stringKeyUnknownValueSchema.optional())], _acceptPeerSessionDecs = [trace(['session', 'cause']), validateParams(fcrSessionBaseSchema, stringKeyUnknownValueSchema.optional())], _rejectPeerSessionDecs = [trace(['session', 'cause']), validateParams(fcrSessionBaseSchema, stringKeyUnknownValueSchema.optional())], "logger")] = (_initProto(this), createLogger({
prefix: 'FcrPeerSessionControlImpl'
}));
//@internal
_observable = new AgoraObservable();
//@internal
_taskInterval = Duration.second(1);
//@internal
//@internal
_scheduleMap = new Map();
//@internal
_receivedMap = new Map();
//@internal
_engineObserver = {
onPeerMessageReceived: this._handlePeerMessage.bind(this)
};
constructor(_rteEngine, _api, _userId) {
this._rteEngine = _rteEngine;
this._api = _api;
this._userId = _userId;
this._addLogObserver();
this._executeTask = this._executeTask.bind(this);
this._rteEngine.addObserver(this._engineObserver);
this._task = AgoraScheduler.shared.addPollingTask(this._executeTask, this._taskInterval, true, () => ActionWhenTaskFail.CONTINUE);
}
async startPeerSession(params) {
try {
const session = {
sessionId: md5(`${Date.now()}`),
sessionKey: params.sessionKey,
payload: params.payload,
duration: params.duration,
sender: this._userId,
keepAlive: params.keepAlive
};
// 如果会话已存在,则抛出错误(这种情况不应该发生,因为会话id是唯一的, 也可能是keepAlive的会话, 但是如果再次调用startPeerSession, 则说明有bug)
if (this._scheduleMap.has(session.sessionId)) {
throw generateFcrCoreClientError(ErrorModuleCode.FCR_PEER_SESSION, DetailErrorCode.PEER_SESSION_ALREADY_EXISTS, 'peer session already exists');
}
const {
data: {
interval
}
} = await this._api.updatePeerSession({
userId: this._userId,
sessionId: session.sessionId,
sessionKey: session.sessionKey,
duration: session.duration,
payload: session.payload,
targetId: params.receiverId,
keepAlive: params.keepAlive,
action: 0
});
const nextTs = Date.now() + interval;
this._scheduleMap.set(session.sessionId, {
...params,
nextTs,
startTs: Date.now(),
action: 0
});
this.logger.info(`[PeerSession] put into session schedule: ${session.sessionId}, next ts: ${nextTs}, remain: ${nextTs - Date.now()}ms`);
return session.sessionId;
} catch (e) {
throw generateFcrCoreServerError(DetailErrorCode.LOCAL_HTTP_REQUEST_FAILED, 'start peer session failed');
}
}
stopPeerSession(sessionId) {
return this._scheduleMap.delete(sessionId) || this._receivedMap.delete(sessionId);
}
async endPeerSession(sessionId, cause) {
const scheduleSession = this._scheduleMap.get(sessionId);
const receivedSession = this._receivedMap.get(sessionId);
const session = scheduleSession || receivedSession;
if (session && session.keepAlive) {
try {
await this._api.deletePeerSession({
userId: this._userId,
sessionId: sessionId,
sessionKey: session.sessionKey,
receiverIds: scheduleSession ? [scheduleSession.receiverId] : [receivedSession.senderId],
action: 3,
payload: {
cause
}
}).then(() => {
this.stopPeerSession(sessionId);
this._observable.notifyObservers('onPeerSessionEnded', sessionId, this._userId, cause);
});
} catch (e) {
throw generateFcrCoreServerError(DetailErrorCode.LOCAL_HTTP_REQUEST_FAILED, 'end peer session failed');
}
} else {
this.stopPeerSession(sessionId);
}
}
async acceptPeerSession(session, cause) {
if (this._isSessionExpired(session)) {
throw generateFcrCoreClientError(ErrorModuleCode.FCR_PEER_SESSION, DetailErrorCode.EXPIRED, 'accept peer session failed: session expired');
}
try {
if (session.keepAlive) {
const params = this._receivedMap.get(session.sessionId);
if (params) {
const {
data: {
interval
}
} = await this._api.updatePeerSession({
userId: this._userId,
sessionId: session.sessionId,
sessionKey: session.sessionKey,
duration: session.duration,
payload: session.payload,
targetId: session.senderId,
keepAlive: session.keepAlive,
action: 1
});
const _now = Date.now();
this._receivedMap.set(session.sessionId, {
...params,
nextTs: _now + interval,
startTs: _now,
action: 1
});
return;
}
}
// 非keepAlive的会话, 需要通过删除会话请求来表示接受会话的响应
return this._api.deletePeerSession({
userId: this._userId,
sessionId: session.sessionId,
sessionKey: session.sessionKey,
receiverIds: [session.senderId],
action: 1,
payload: {
cause
}
}).then(() => {
this.stopPeerSession(session.sessionId);
});
} catch (e) {
throw generateFcrCoreServerError(DetailErrorCode.LOCAL_HTTP_REQUEST_FAILED, 'accept peer session failed');
}
}
async rejectPeerSession(session, cause) {
if (this._isSessionExpired(session)) {
throw generateFcrCoreClientError(ErrorModuleCode.FCR_PEER_SESSION, DetailErrorCode.EXPIRED, 'reject peer session failed: session expired');
}
try {
await this._api.deletePeerSession({
userId: this._userId,
sessionId: session.sessionId,
sessionKey: session.sessionKey,
receiverIds: [session.senderId],
action: 2,
payload: {
cause
}
}).then(() => {
this.stopPeerSession(session.sessionId);
});
} catch (e) {
throw generateFcrCoreServerError(DetailErrorCode.LOCAL_HTTP_REQUEST_FAILED, 'reject peer session failed');
}
}
addObserver(observer) {
this._observable.addObserver(observer);
}
removeObserver(observer) {
this._observable.removeObserver(observer);
}
release() {
// Stop the scheduled task
if (this._task) {
this._task.stop();
this._task = undefined;
}
// Remove engine observer
this._rteEngine.removeObserver(this._engineObserver);
// Clear session maps
this._scheduleMap.clear();
this._receivedMap.clear();
// Clear observers
this._observable.removeAllObservers();
}
//@internal
async _executeTask() {
// ping sessions (sender side)
for (const key of this._scheduleMap.keys()) {
const params = this._scheduleMap.get(key);
const session = {
sessionId: key,
sessionKey: params.sessionKey,
payload: params.payload,
duration: params.duration,
senderId: this._userId,
timestamp: params.startTs,
interval: 0,
keepAlive: params.keepAlive,
action: params.action
};
if (this._isSessionExpired(session)) {
this.logger.info(`peer session expired, removed: ${session.sessionId}`);
if (session.keepAlive) {
await this.endPeerSession(session.sessionId);
}
if (this._scheduleMap.has(session.sessionId)) {
this._scheduleMap.delete(session.sessionId);
}
continue;
}
// check timeout
if (params.nextTs < Date.now()) {
this.logger.info(`ping session: ${session.sessionId}`);
try {
const {
data: {
interval
}
} = await this._api.updatePeerSession({
userId: this._userId,
sessionId: session.sessionId,
sessionKey: session.sessionKey,
duration: params.duration,
payload: session.payload,
targetId: params.receiverId,
keepAlive: params.keepAlive,
action: params.action
});
const nextTs = Date.now() + interval;
if (this._scheduleMap.has(session.sessionId)) {
this._scheduleMap.set(session.sessionId, {
...params,
nextTs
});
this.logger.info(`[PeerSession] refresh session schedule: ${session.sessionId}, next ts: ${nextTs}`);
}
} catch (e) {
this.logger.error(`ping session failed: ${e}`);
}
}
}
// clear expired sessions (receiver side)
for (const key of this._receivedMap.keys()) {
const session = this._receivedMap.get(key);
if (this._isSessionExpired(session)) {
this.logger.info(`peer session expired, removed: ${key}`);
if (session.keepAlive) {
await this.endPeerSession(key);
}
if (this._receivedMap.has(key)) {
this._receivedMap.delete(key);
}
continue;
}
// 如果会话是keepAlive的,并且距离上次ping的时间超过2倍interval,则认为会话已过期(可能因为对方或己方已经掉线),需要结束会话
if (session.keepAlive && session.nextTs + session.interval * KEEPALIVE_TIMEOUT_MULTIPLIER < Date.now()) {
await this.endPeerSession(key);
this.logger.info(`peer session has not been pinged, removed: ${key}`);
}
}
}
//@internal
async _handlePeerMessage(message) {
const {
senderId,
payload
} = message;
const {
data,
cmd
} = payload;
const logContext = `cmd=${cmd}, sessionKey=${data.sessionKey}, sessionId=${data.sessionUuid}, ` + `action=${String(data.action)}, senderId=${senderId}, keepAlive=${!!data.keepAlive}`;
this.logger.info(`[PeerSession] received peer message: ${logContext}, payload=${JSON.stringify(data.payload ?? {})}`);
if (cmd === '1001') {
const session = {
sessionId: data.sessionUuid,
sessionKey: data.sessionKey,
senderId,
duration: data.duration,
timestamp: message.timestamp,
interval: data.interval,
payload: data.payload,
keepAlive: !!data.keepAlive,
action: data.action
};
const sessionCache = this._receivedMap.get(session.sessionId);
if (sessionCache) {
session.timestamp = sessionCache.timestamp;
}
if (!this._isSessionExpired(session)) {
if (data.action === 1) {
if (this._scheduleMap.has(session.sessionId)) {
const sessionResponse = {
sessionId: session.sessionId,
sessionKey: session.sessionKey,
responderId: senderId,
payload: session.payload ?? {},
cause: data.payload?.cause ?? {},
keepAlive: !!session.keepAlive
};
const params = this._scheduleMap.get(session.sessionId);
this._scheduleMap.set(session.sessionId, {
...params,
action: 1
});
this.logger.info(`[PeerSession] forward peer session accepted to observers: ${logContext}`);
this._observable.notifyObservers('onPeerSessionAccepted', sessionResponse);
} else {
this.logger.info(`[PeerSession] ignore peer session accepted without local schedule: ${logContext}`);
}
if (this._receivedMap.has(session.sessionId)) {
this._receivedMap.set(session.sessionId, {
...session,
nextTs: Date.now() + data.interval,
startTs: Date.now(),
action: 1
});
}
return;
} else {
if (!this._receivedMap.has(session.sessionId)) {
this.logger.info(`[PeerSession] forward peer session request to observers: ${logContext}`);
this._observable.notifyObservers('onPeerSessionReceived', session);
} else {
this.logger.info(`[PeerSession] peer session request already cached, update cache only: ${logContext}`);
}
this._receivedMap.set(session.sessionId, {
...session,
nextTs: Date.now() + data.interval,
startTs: Date.now(),
action: 0
});
}
} else {
this.logger.info(`[PeerSession] ignore expired peer session message: ${logContext}, ` + `timestamp=${session.timestamp}, duration=${session.duration}`);
}
} else if (cmd === '1002') {
if (data.action === 1) {
if (this._scheduleMap.has(data.sessionUuid)) {
const session = this._scheduleMap.get(data.sessionUuid);
const sessionResponse = {
sessionId: data.sessionUuid,
sessionKey: data.sessionKey,
responderId: senderId,
// FIXME: session may be lost when the client refreshes
// get payload from original session
payload: session.payload ?? {},
cause: data.payload?.cause ?? {},
keepAlive: !!data.keepAlive
};
this._scheduleMap.delete(data.sessionUuid);
this.logger.info(`[PeerSession] forward peer session accepted to observers: ${logContext}`);
this._observable.notifyObservers('onPeerSessionAccepted', sessionResponse);
} else {
this.logger.info(`[PeerSession] ignore peer session accepted without local schedule: ${logContext}`);
}
} else if (data.action === 2) {
if (this._scheduleMap.has(data.sessionUuid)) {
const session = this._scheduleMap.get(data.sessionUuid);
const sessionResponse = {
sessionId: data.sessionUuid,
sessionKey: data.sessionKey,
responderId: senderId,
// FIXME: session may be lost when the client refreshes
// get payload from original session
payload: session.payload ?? {},
cause: data.payload?.cause ?? {},
keepAlive: !!data.keepAlive
};
if (this._scheduleMap.has(data.sessionUuid)) {
this._scheduleMap.delete(data.sessionUuid);
this.logger.info(`[PeerSession] forward peer session rejected to observers: ${logContext}`);
this._observable.notifyObservers('onPeerSessionRejected', sessionResponse);
}
} else {
this.logger.info(`[PeerSession] ignore peer session rejected without local schedule: ${logContext}`);
}
} else if (data.action === 3) {
const scheduleSession = this._scheduleMap.get(data.sessionUuid);
const receivedSession = this._receivedMap.get(data.sessionUuid);
const session = scheduleSession || receivedSession;
if (session) {
const params = {
sessionId: data.sessionUuid,
fromUserId: senderId,
cause: data.payload?.cause ?? {}
};
if (scheduleSession) {
this._scheduleMap.delete(data.sessionUuid);
}
if (receivedSession) {
this._receivedMap.delete(data.sessionUuid);
}
this._observable.notifyObservers('onPeerSessionEnded', params.sessionId, params.fromUserId, params.cause);
this.logger.info(`[PeerSession] forward peer session ended to observers: ${logContext}`);
} else {
this.logger.info(`[PeerSession] ignore peer session ended without cached session: ${logContext}`);
}
} else {
this.logger.info(`[PeerSession] ignore peer session response with unknown action: ${logContext}`);
}
} else {
this.logger.info(`[PeerSession] ignore unsupported peer session cmd: ${logContext}`);
}
}
//@internal
_isSessionExpired(session) {
return session.timestamp + session.duration * Duration.second(1) < Date.now();
}
_addLogObserver() {
this.addObserver(generateLogObserver(this.logger, [['onPeerSessionAccepted', ['session']], ['onPeerSessionReceived', ['session']], ['onPeerSessionRejected', ['session']], ['onPeerSessionEnded', ['sessionId', 'fromUserId', 'reason']]]));
}
}