Skip to content

Commit

Permalink
Internal core changes (#407)
Browse files Browse the repository at this point in the history
* make safeParseJson generic

* add encode/decode protected method to BaseSession to allow override

* remove exports from internal types

* update decode signature and review types for inbound ws messages

* add changeset
  • Loading branch information
Edoardo Gallo authored Jan 13, 2022
1 parent 90e87bf commit 7c688bb
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 26 deletions.
5 changes: 5 additions & 0 deletions .changeset/olive-cameras-kick.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@signalwire/core': patch
---

[internal] Add encode/decode protected methods to BaseSession
52 changes: 33 additions & 19 deletions packages/core/src/BaseSession.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import { PayloadAction } from '@reduxjs/toolkit'
import { uuid, getLogger } from './utils'
import {
uuid,
getLogger,
checkWebSocketHost,
timeoutPromise,
parseRPCResponse,
safeParseJson,
isJSONRPCResponse,
} from './utils'
import { DEFAULT_HOST, WebSocketState } from './utils/constants'
import {
RPCConnect,
Expand All @@ -19,13 +27,6 @@ import {
WebSocketClient,
SessionStatus,
} from './utils/interfaces'

import {
checkWebSocketHost,
timeoutPromise,
parseRPCResponse,
safeParseJson,
} from './utils'
import {
closeConnectionAction,
authErrorAction,
Expand Down Expand Up @@ -201,7 +202,7 @@ export class BaseSession {
}

this.logger.wsTraffic({ type: 'send', payload: msg })
this._socket!.send(JSON.stringify(msg))
this._socket!.send(this.encode(msg))

return timeoutPromise(
promise,
Expand Down Expand Up @@ -263,17 +264,22 @@ export class BaseSession {
}

protected _onSocketMessage(event: MessageEvent) {
const payload: any = safeParseJson(event.data)
const payload = this.decode<JSONRPCRequest | JSONRPCResponse>(event.data)
this.logger.wsTraffic({ type: 'recv', payload })
const request = this._requests.get(payload.id)
if (request) {
const { rpcRequest, resolve, reject } = request
this._requests.delete(payload.id)
const { result, error } = parseRPCResponse({
response: payload,
request: rpcRequest,
})
return error ? reject(error) : resolve(result)

if (isJSONRPCResponse(payload)) {
const request = this._requests.get(payload.id)
if (request) {
const { rpcRequest, resolve, reject } = request
this._requests.delete(payload.id)
const { result, error } = parseRPCResponse({
response: payload,
request: rpcRequest,
})
return error ? reject(error) : resolve(result)
}

return this.logger.warn('Unknown request for', payload)
}

switch (payload.method) {
Expand Down Expand Up @@ -322,6 +328,14 @@ export class BaseSession {
)
}

protected encode<T>(input: T): Parameters<WebSocketClient['send']>[0] {
return JSON.stringify(input)
}

protected decode<T>(input: any): T {
return safeParseJson(input)
}

private async _pingHandler(payload: JSONRPCRequest) {
clearTimeout(this._checkPingTimer)
this._checkPingTimer = setTimeout(() => {
Expand Down
13 changes: 7 additions & 6 deletions packages/core/src/internal/InternalRPC.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,34 +6,35 @@ import { makeRPCResponse } from '../RPCMessages/helpers'
* @internal
*/
export type InternalRPCMethods =
| 'blade.ping'
| 'blade.connect'
| 'blade.execute'
| 'blade.protocol'

/**
* @internal
*/
export const JSONRPCParseError = -32700 as const
const JSONRPCParseError = -32700 as const
/**
* @internal
*/
export const JSONRPCInvalidRequest = -32600 as const
const JSONRPCInvalidRequest = -32600 as const
/**
* @internal
*/
export const JSONRPCMethodNotFound = -32601 as const
/**
* @internal
*/
export const JSONRPCInvalidParams = -32602 as const
const JSONRPCInvalidParams = -32602 as const
/**
* @internal
*/
export const JSONRPCInternalError = -32603 as const
const JSONRPCInternalError = -32603 as const
/**
* @internal
*/
export type JSONRPCErrorCodes =
type JSONRPCErrorCodes =
| typeof JSONRPCParseError
| typeof JSONRPCInvalidRequest
| typeof JSONRPCMethodNotFound
Expand All @@ -43,7 +44,7 @@ export type JSONRPCErrorCodes =
/**
* @internal
*/
export type InternalRPCResponseProperties = {
type InternalRPCResponseProperties = {
result: Record<string, any>
error: {
code: JSONRPCErrorCodes
Expand Down
15 changes: 14 additions & 1 deletion packages/core/src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { JSONRPCRequest, JSONRPCResponse } from '..'
import {
STORAGE_PREFIX,
GLOBAL_VIDEO_EVENTS,
Expand All @@ -16,7 +17,7 @@ export * from './eventTransformUtils'

export const mutateStorageKey = (key: string) => `${STORAGE_PREFIX}${key}`

export const safeParseJson = (value: string): string | Object => {
export const safeParseJson = <T>(value: T): T | Object => {
if (typeof value !== 'string') {
return value
}
Expand Down Expand Up @@ -156,3 +157,15 @@ export const toLocalEvent = <T extends string>(event: string): T => {
}, [] as string[])
.join('.') as T
}

export const isJSONRPCRequest = (
e: JSONRPCRequest | JSONRPCResponse
): e is JSONRPCRequest => {
return Boolean((e as JSONRPCRequest).method)
}

export const isJSONRPCResponse = (
e: JSONRPCRequest | JSONRPCResponse
): e is JSONRPCResponse => {
return !isJSONRPCRequest(e)
}

0 comments on commit 7c688bb

Please sign in to comment.