Skip to content

Commit

Permalink
fix: improve api stability
Browse files Browse the repository at this point in the history
  • Loading branch information
psanders committed Aug 10, 2024
1 parent 47b285a commit 6df04f9
Show file tree
Hide file tree
Showing 10 changed files with 41 additions and 31 deletions.
2 changes: 1 addition & 1 deletion mods/common/src/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export const createServerInternalErrorResponse = (
}
}

export const createForbideenResponse = (metadata?: Record<string, string>) => {
export const createForbiddenResponse = (metadata?: Record<string, string>) => {
return {
metadata,
message: {
Expand Down
3 changes: 2 additions & 1 deletion mods/common/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@ export enum ExtraHeader {
SESSION_COUNT = "X-Session-Count",
DOD_NUMBER = "X-DOD-Number",
DOD_PRIVACY = "X-DOD-Privacy",
CONNECT_TOKEN = "X-Connect-Token"
CONNECT_TOKEN = "X-Connect-Token",
CALL_DIRECTION = "X-Call-Direction"
}

export enum Privacy {
Expand Down
6 changes: 3 additions & 3 deletions mods/connect/src/access.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export const checkAccess = async (accessRequest: {
case RoutingDirection.FROM_PSTN:
return checkAccessFromPSTN(apiClient, request, callee as CC.INumber)
case RoutingDirection.UNKNOWN:
return CR.createForbideenResponse()
return CR.createForbiddenResponse()
}
}

Expand Down Expand Up @@ -91,11 +91,11 @@ export const checkAccessFromPSTN = async (

// If the Trunk or Number doesn't exist reject the call
if (!callee || !trunk) {
return CR.createForbideenResponse()
return CR.createForbiddenResponse()
}

if (callee.trunk.ref !== trunk.ref) {
return CR.createForbideenResponse()
return CR.createForbiddenResponse()
}

// Verify that the IP is allowlist which means getting the access control list for the trunk
Expand Down
2 changes: 1 addition & 1 deletion mods/connect/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export class ServiceUnavailableError extends Error {
/**
* Throw when the route is not supported.
*/
export class UnsuportedRoutingError extends Error {
export class UnsupportedRoutingError extends Error {
code: number

/**
Expand Down
6 changes: 3 additions & 3 deletions mods/connect/src/handlers/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export const handleRegister = (
)) as CC.Peer | CC.Agent

if (!peerOrAgent) {
return res.send(CR.createForbideenResponse())
return res.send(CR.createForbiddenResponse())
}

const credentials = (
Expand Down Expand Up @@ -111,7 +111,7 @@ export const handleRegister = (
)) as Verifier.VerifyResponse

if (!payload.allowedMethods.includes(Method.REGISTER)) {
return res.send(CR.createForbideenResponse())
return res.send(CR.createForbiddenResponse())
}

await location.addRoute({
Expand All @@ -125,7 +125,7 @@ export const handleRegister = (
logger.verbose("unable to validate connect token", {
originalError: e.message
})
res.send(CR.createForbideenResponse())
res.send(CR.createForbiddenResponse())
}
} else {
res.send(CR.createUnauthorizedResponse(request.message.requestUri.host))
Expand Down
30 changes: 19 additions & 11 deletions mods/connect/src/handlers/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
* limitations under the License.
*/
import * as grpc from "@grpc/grpc-js"
import { Helper as H } from "@routr/location"
import { tailor } from "../tailor"
import {
Alterations as A,
Expand All @@ -27,11 +26,12 @@ import {
} from "@routr/processor"
import { pipe } from "fp-ts/function"
import { router } from "../router"
import { ILocationService } from "@routr/location"
import { ILocationService, Helper as H } from "@routr/location"
import {
CommonConnect as CC,
CommonTypes as CT,
Environment
Environment,
HeaderModifier
} from "@routr/common"
import { getLogger } from "@fonoster/logger"
import { RoutingDirection } from "./../types"
Expand All @@ -54,39 +54,47 @@ export const handleRequest =
route = H.createRouteFromLastMessage(req)
} else {
const routerResult = await router(location, apiClient)(req)
const direction = routerResult.direction
const direction = routerResult.direction as RoutingDirection
route = routerResult.route as CT.Route

// If direction is not present result is an error response
if (!("direction" in routerResult)) {
return res.send(routerResult as Record<string, unknown>)
return res.send(routerResult)
} else if (!route && direction === RoutingDirection.AGENT_TO_PSTN) {
return res.sendNotFound()
} else if (!routerResult.route) {
return res.sendTemporarilyUnavailable()
}

const p: HeaderModifier = {
name: CT.ExtraHeader.CALL_DIRECTION,
value: direction,
action: CT.HeaderModifierAction.ADD
}

route.headers.push(p)
}

// Forward request to peer edgeport
if (req.edgePortRef !== route.edgePortRef) {
return res.send(
pipe(
req,
A.addSelfVia(route as CT.Route),
A.addSelfRecordRoute(route as CT.Route),
A.addSelfVia(route),
A.addSelfRecordRoute(route),
// The order of the routes is important
A.addRouteToPeerEdgePort(route as CT.Route),
A.addRouteToNextHop(route as CT.Route),
A.addRouteToPeerEdgePort(route),
A.addRouteToNextHop(route),
A.addXEdgePortRef,
A.decreaseMaxForwards
)
)
}

// TODO: We should add this the Tailor API
req.metadata = route.metadata as Record<string, string>
req.metadata = route.metadata

res.send(tailor(route as CT.Route, req))
res.send(tailor(route, req))
} catch (err) {
if (err.code === grpc.status.NOT_FOUND) {
return res.sendTemporarilyUnavailable()
Expand Down
18 changes: 9 additions & 9 deletions mods/connect/src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,14 @@ import {
findNumberByTelUrl,
findResource,
getRoutingDirection,
getSIPURI,
getSipUri,
getTrunkURI,
getVerifierImpl,
hasXConnectObjectHeader
} from "./utils"
import { MessageRequest, Target as T, Extensions as E } from "@routr/processor"
import { ILocationService, Backend } from "@routr/location"
import { UnsuportedRoutingError } from "./errors"
import { UnsupportedRoutingError } from "./errors"
import { getLogger } from "@fonoster/logger"
import { checkAccess } from "./access"

Expand Down Expand Up @@ -78,7 +78,7 @@ export function router(location: ILocationService, apiClient: CC.APIClient) {
const domain = await findDomain(apiClient, payload.domain)

if (!payload.allowedMethods.includes(Method.INVITE)) {
return CR.createForbideenResponse()
return CR.createForbiddenResponse()
}

caller = {
Expand Down Expand Up @@ -116,7 +116,7 @@ export function router(location: ILocationService, apiClient: CC.APIClient) {
logger.verbose("unable to validate connect token", {
originalError: e.message
})
return CR.createForbideenResponse()
return CR.createForbiddenResponse()
}
} else {
caller = await findResource(apiClient, fromURI.host, fromURI.user)
Expand All @@ -127,12 +127,12 @@ export function router(location: ILocationService, apiClient: CC.APIClient) {

logger.verbose(
"routing request from: " +
getSIPURI(fromURI) +
getSipUri(fromURI) +
", to: " +
getSIPURI(requestURI),
getSipUri(requestURI),
{
fromURI: getSIPURI(fromURI),
requestURI: getSIPURI(requestURI),
fromURI: getSipUri(fromURI),
requestURI: getSipUri(requestURI),
routingDirection
}
)
Expand Down Expand Up @@ -206,7 +206,7 @@ export function router(location: ILocationService, apiClient: CC.APIClient) {
callee?.extended
)
default:
throw new UnsuportedRoutingError(routingDirection)
throw new UnsupportedRoutingError(routingDirection)
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion mods/connect/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ export const getTrunkURI = (
}
}

export const getSIPURI = (uri: { user?: string; host: string }) =>
export const getSipUri = (uri: { user?: string; host: string }) =>
uri.user ? `sip:${uri.user}@${uri.host}` : `sip:${uri.host}`

export const hasXConnectObjectHeader = (req: MessageRequest) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,6 @@ public class ConsolePublisher implements EventsPublisher {
private static final Logger LOG = LogManager.getLogger(ConsolePublisher.class);

public void publish(String eventName, Map<String, Object> message) {
LOG.info("event: " + eventName + " message: " + message);
LOG.debug("event: " + eventName + " message: " + message);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ public void publish(String eventName, Map<String, Object> message) {
try {
ObjectMapper mapper = new ObjectMapper();
String messageAsJson = mapper.writeValueAsString(message);
LOG.debug("event: " + eventName + " message: " + messageAsJson);
this.connection.publish(this.subject + "." + eventName, messageAsJson.getBytes());
} catch(JsonProcessingException e) {
LOG.error("error publishing event: " + e.getMessage());
Expand Down

0 comments on commit 6df04f9

Please sign in to comment.