Skip to content

WIP: CF SDK: Modified SignalWire Client with auth states #1192

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 32 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 27 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
2c05e0f
CF SDK: Modified SignalWireClient with auth states
iAmmar7 Mar 21, 2025
824a793
merge with main
iAmmar7 Mar 21, 2025
279bfe1
expose auth state via callback
iAmmar7 Mar 25, 2025
bfe1376
add call id as a param to reattach method
iAmmar7 Mar 27, 2025
d703ca3
modified SAT session
iAmmar7 Mar 31, 2025
d78f6e6
fix unit tests
iAmmar7 Mar 31, 2025
10d7378
rename auth states in the store
iAmmar7 Mar 31, 2025
60470b1
update playground
iAmmar7 Mar 31, 2025
dbf2cab
remove on off from the interface
iAmmar7 Mar 31, 2025
088278b
rename session auth handler
iAmmar7 Mar 31, 2025
d28a255
add a unit test for the session slice
iAmmar7 Mar 31, 2025
5aaf78c
use SwAuthorizationState
iAmmar7 Mar 31, 2025
d8f2df8
refactor
iAmmar7 Mar 31, 2025
b6ddccb
introduce v4 modules
iAmmar7 Apr 1, 2025
e221e5d
merge with main
iAmmar7 Apr 1, 2025
113bdd1
include V4 WSClient and SATSession
iAmmar7 Apr 1, 2025
554a38a
store origin call id in the store
iAmmar7 Apr 1, 2025
17a0f8f
trigger callback with new worker
iAmmar7 Apr 2, 2025
71d1b3a
fix the build
iAmmar7 Apr 3, 2025
7b4fd14
fix reattach with new client
iAmmar7 Apr 3, 2025
27038b8
move v4 client to a dedicated folder
iAmmar7 Apr 3, 2025
df93dab
remove localstorage changes from the playground
iAmmar7 Apr 3, 2025
a13fb98
remove unused base component getters
iAmmar7 Apr 3, 2025
6244825
fallback the conversation changes
iAmmar7 Apr 3, 2025
be83732
refactor types
iAmmar7 Apr 3, 2025
8c06d87
refactor v4 client
iAmmar7 Apr 3, 2025
bfbdc88
create multi instance v4 client
iAmmar7 Apr 4, 2025
27a2987
reattach with v4 client
iAmmar7 Apr 7, 2025
fb07355
add one more test
iAmmar7 Apr 7, 2025
f415740
playwright project for both v3 and v4 clients
iAmmar7 Apr 8, 2025
df81f98
revert the protected select method
iAmmar7 Apr 8, 2025
5b5df3f
merge with main
iAmmar7 Apr 16, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions internal/playground-js/src/fabric/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { SignalWire, buildVideoElement } from '@signalwire/js'
import { SignalWire, SignalWireV4, buildVideoElement } from '@signalwire/js'
import {
enumerateDevices,
checkPermissions,
Expand Down Expand Up @@ -251,11 +251,15 @@ function restoreUI() {
window.connect = async () => {
connectStatus.innerHTML = 'Connecting...'

client = await SignalWire({
client = await SignalWireV4({
host: document.getElementById('host').value,
token: document.getElementById('token').value,
logLevel: 'debug',
debug: { logWsTraffic: true },
authState: sessionStorage.getItem('fabric.ws.authState'),
onAuthStateChange: (authState) => {
sessionStorage.setItem('fabric.ws.authState', authState)
},
})
window.__client = client

Expand Down
17 changes: 9 additions & 8 deletions packages/core/src/BaseComponent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import {
} from './types'
import {
getAuthError,
getAuthState,
getAuthorization,
getAuthStatus,
} from './redux/features/session/sessionSelectors'
import { AuthError } from './CustomErrors'
Expand Down Expand Up @@ -164,6 +164,7 @@ export class BaseComponent<
return this.emitter.listenerCount(event)
}

/** @internal */
destroy() {
this._destroyer?.()
this.removeAllListeners()
Expand Down Expand Up @@ -235,7 +236,7 @@ export class BaseComponent<
}

/** @internal */
select<T>(selectorFn: (state: SDKState) => T) {
protected select<T>(selectorFn: (state: SDKState) => T) {
return selectorFn(this.store.getState())
}

Expand All @@ -247,17 +248,17 @@ export class BaseComponent<

/** @internal */
protected get _sessionAuthStatus(): SessionAuthStatus {
return getAuthStatus(this.store.getState())
return this.select(getAuthStatus)
}

/** @internal */
protected get _sessionAuthState(): Authorization | undefined {
return getAuthState(this.store.getState())
protected get _sessionAuthorization(): Authorization | undefined {
return this.select(getAuthorization)
}

/** @internal */
protected _waitUntilSessionAuthorized(): Promise<this> {
const authStatus = getAuthStatus(this.store.getState())
const authStatus = this.select(getAuthStatus)

switch (authStatus) {
case 'authorized':
Expand All @@ -277,8 +278,8 @@ export class BaseComponent<
case 'authorizing':
return new Promise((resolve, reject) => {
const unsubscribe = this.store.subscribe(() => {
const authStatus = getAuthStatus(this.store.getState())
const authError = getAuthError(this.store.getState())
const authStatus = this.select(getAuthStatus)
const authError = this.select(getAuthError)

if (authStatus === 'authorized') {
resolve(this)
Expand Down
6 changes: 2 additions & 4 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import {
asyncRetry,
increasingDelay,
decreasingDelay,
constDelay
constDelay,
} from './utils'
import { WEBRTC_EVENT_TYPES, isWebrtcEventType } from './utils/common'
import { BaseSession } from './BaseSession'
Expand All @@ -34,7 +34,6 @@ import { BaseComponent } from './BaseComponent'
import { BaseConsumer } from './BaseConsumer'
import { EventEmitter, getEventEmitter } from './utils/EventEmitter'
import * as sessionSelectors from './redux/features/session/sessionSelectors'
import { findNamespaceInPayload } from './redux/features/shared/namespace'
import { GLOBAL_VIDEO_EVENTS } from './utils/constants'
import {
MEMBER_UPDATED_EVENTS,
Expand Down Expand Up @@ -67,7 +66,6 @@ export {
GLOBAL_VIDEO_EVENTS,
MEMBER_UPDATED_EVENTS,
INTERNAL_MEMBER_UPDATED_EVENTS,
findNamespaceInPayload,
timeoutPromise,
debounce,
SWCloseEvent,
Expand All @@ -81,7 +79,7 @@ export {
asyncRetry,
increasingDelay,
decreasingDelay,
constDelay
constDelay,
}

export * from './redux/features/component/componentSlice'
Expand Down
12 changes: 8 additions & 4 deletions packages/core/src/pubSub/BasePubSub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
validateEventsToSubscribe,
BaseConsumer,
} from '..'
import { getAuthState } from '../redux/features/session/sessionSelectors'
import { getAuthorization } from '../redux/features/session/sessionSelectors'
import type {
PubSubChannel,
InternalPubSubChannel,
Expand Down Expand Up @@ -196,9 +196,13 @@ export class BasePubSubConsumer<
// `realtime-api`
async getAllowedChannels() {
await this._waitUntilSessionAuthorized()
const authState = this.select(getAuthState)
if (authState && 'channels' in authState && authState.channels) {
return authState.channels
const authorization = this.select(getAuthorization)
if (
authorization &&
'channels' in authorization &&
authorization.channels
) {
return authorization.channels
}
return {}
}
Expand Down
17 changes: 13 additions & 4 deletions packages/core/src/redux/features/component/componentSaga.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,11 @@ describe('componentCleanupSaga', () => {
},
})
})
it('should cleanup unused components from the store', () => {
return expectSaga(componentCleanupSagaWorker)

it('should cleanup unused components from the store', async () => {
jest.useFakeTimers()

const sagaPromise = expectSaga(componentCleanupSagaWorker)
.withReducer(rootReducer, store.getState())
.hasFinalState({
components: {
Expand All @@ -43,11 +46,17 @@ describe('componentCleanupSaga', () => {
protocol: '',
iceServers: [],
authStatus: 'unknown',
authState: undefined,
authorization: undefined,
authorizationState: undefined,
authError: undefined,
authCount: 0,
},
})
.run()
.run({ silenceTimeout: true })

jest.runAllTimers()
await sagaPromise

jest.useRealTimers()
})
})
14 changes: 11 additions & 3 deletions packages/core/src/redux/features/session/sessionSaga.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@ import type {
VideoAPIEvent,
SwEventParams,
WebRTCMessageParams,
SwAuthorizationStateParams,
SwAuthorizationStateEvent,
} from '../../../types'
import type { SessionChannel, SwEventChannel } from '../../interfaces'
import { createCatchableSaga } from '../../utils/sagaHelpers'
import { socketMessageAction } from '../../actions'
import { getLogger, isWebrtcEventType, toInternalAction } from '../../../utils'
import { sessionActions } from './sessionSlice'

type SessionSagaParams = {
session: BaseSession
Expand All @@ -29,7 +30,7 @@ const isVideoEvent = (e: SwEventParams): e is VideoAPIEvent => {
}
const isSwAuthorizationState = (
e: SwEventParams
): e is SwAuthorizationStateParams => {
): e is SwAuthorizationStateEvent => {
return e?.event_type === 'signalwire.authorization.state'
}

Expand All @@ -54,17 +55,24 @@ export function* sessionChannelWatcher({
/**
* After connecting to the SignalWire network, it sends the `authorization_state`
* through the `signalwire.authorization.state` event. We store this value in
* the storage since it is required for reconnect.
* the browser storage for JWT and in Redux store for SAT since it is required for reconnect.
*/
if (isSwAuthorizationState(broadcastParams)) {
session.onSwAuthorizationState(broadcastParams.params.authorization_state)
yield put(
sessionActions.updateAuthorizationState(
broadcastParams.params.authorization_state
)
)
return
}

/**
* Put actions with `event_type` to trigger all the children sagas
* This should replace all the isWebrtcEvent/isVideoEvent guards below
* since we'll move that logic on a separate package.
*
* TODO: We no longer need this and it can be removed
*/
yield put({ type: broadcastParams.event_type, payload: broadcastParams })
}
Expand Down
12 changes: 10 additions & 2 deletions packages/core/src/redux/features/session/sessionSelectors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@ export const getAuthError = ({ session }: SDKState) => {
return session.authError
}

export const getAuthState = ({ session }: SDKState) => {
return session.authState
export const getAuthorization = ({ session }: SDKState) => {
return session.authorization
}

export const getAuthorizationState = ({ session }: SDKState) => {
return session.authorizationState
}

export const getProtocol = ({ session }: SDKState) => {
return session.protocol
}
12 changes: 11 additions & 1 deletion packages/core/src/redux/features/session/sessionSlice.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ describe('SessionState Tests', () => {
protocol: rpcConnectResultVRT.protocol,
iceServers: rpcConnectResultVRT.ice_servers,
authStatus: 'authorized',
authState: {
authorization: {
media_allowed: 'all',
audio_allowed: 'both',
join_as: 'member',
Expand All @@ -40,6 +40,7 @@ describe('SessionState Tests', () => {
video_allowed: 'both',
meta: {},
},
authorizationState: undefined,
authError: undefined,
authCount: 1,
})
Expand All @@ -62,4 +63,13 @@ describe('SessionState Tests', () => {
store.dispatch(reauthAction({ token: 'foo' }))
expect(getAuthStatus(store.getState())).toEqual('authorizing')
})

it('should set authorizationState on sessionActions.updateAuthorizationState', () => {
store.dispatch(sessionActions.updateAuthorizationState('foo'))

expect(store.getState().session).toStrictEqual({
...initialSessionState,
authorizationState: 'foo',
})
})
})
15 changes: 11 additions & 4 deletions packages/core/src/redux/features/session/sessionSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ export const initialSessionState: DeepReadonly<SessionState> = {
protocol: '',
iceServers: [],
authStatus: 'unknown',
authState: undefined,
authorization: undefined,
authorizationState: undefined,
authError: undefined,
authCount: 0,
}
Expand All @@ -32,7 +33,7 @@ const sessionSlice = createDestroyableSlice({
return {
...state,
authStatus: 'authorized',
authState: payload?.authorization,
authorization: payload?.authorization,
authCount: state.authCount + 1,
protocol: payload?.protocol ?? '',
iceServers: payload?.ice_servers ?? [],
Expand All @@ -44,10 +45,16 @@ const sessionSlice = createDestroyableSlice({
authStatus: payload,
}
},
updateAuthState: (state, { payload }: PayloadAction<Authorization>) => {
updateAuthorization: (state, { payload }: PayloadAction<Authorization>) => {
return {
...state,
authState: payload,
authorization: payload,
}
},
updateAuthorizationState: (state, { payload }: PayloadAction<string>) => {
return {
...state,
authorizationState: payload,
}
},
},
Expand Down
Loading
Loading