Skip to content

Commit

Permalink
fix:add event listeners
Browse files Browse the repository at this point in the history
Signed-off-by: pallavicoder <[email protected]>
  • Loading branch information
pallavighule committed Dec 5, 2024
1 parent d8eba9d commit 063ac8e
Show file tree
Hide file tree
Showing 6 changed files with 368 additions and 737 deletions.
2 changes: 0 additions & 2 deletions dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@ void connect({
// eslint-disable-next-line no-console
console.log('Got ngrok url:', app.url())
const url = app.url()

process.env.NODE_ENV = 'development'
process.env.USE_SOCKETDOCK = 'false'
process.env.AGENT_PORT = `${port}`
process.env.AGENT_ENDPOINTS = `${url},${url?.replace('http', 'ws')}`
process.env.SHORTENER_BASE_URL = `${url}/s`
Expand Down
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,10 @@
"postinstall": "npx patch-package"
},
"dependencies": {
"@credo-ts/askar": "0.5.6",
"@credo-ts/core": "0.5.6",
"@credo-ts/node": "0.5.6",
"@hyperledger/aries-askar-nodejs": "0.2.1",
"@credo-ts/askar": "^0.5.0",
"@credo-ts/core": "^0.5.0",
"@credo-ts/node": "^0.5.0",
"@hyperledger/aries-askar-nodejs": "^0.2.0",
"dotenv": "^16.0.1",
"express": "^4.18.1",
"prettier": "^2.8.4",
Expand Down
6 changes: 2 additions & 4 deletions src/agent.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import { AskarModule, AskarMultiWalletDatabaseScheme } from '@credo-ts/askar'
import {
Agent,
CacheModule,
ConnectionsModule,
DidCommMimeType,
HttpOutboundTransport,
InMemoryLruCache,
MediatorModule,
OutOfBandRole,
OutOfBandState,
Expand Down Expand Up @@ -113,7 +111,7 @@ export async function createAgent() {
agent.registerInboundTransport(wsInboundTransport)
agent.registerOutboundTransport(wsOutboundTransport)
} else {
agent.registerInboundTransport(new SocketDockInboundTransport(app, logger))
agent.registerInboundTransport(new SocketDockInboundTransport({ app }))
}

// Added health check endpoint
Expand All @@ -139,7 +137,7 @@ export async function createAgent() {
return res.send(outOfBandRecord.outOfBandInvitation.toJSON())
})

httpInboundTransport.app.use(express.json())
// app.use(express.json())

await agent.initialize()

Expand Down
50 changes: 26 additions & 24 deletions src/transport/SocketDockInboundTransport.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,30 @@
import { Express } from 'express'
import { Logger } from '../logger'
import { Agent, InboundTransport } from '@credo-ts/core'
import { WebSocketTransportSession } from './SocketDockTransportSession'
import type { Express } from 'express'
import { Agent, AgentEventTypes, AgentMessageReceivedEvent, InboundTransport } from '@credo-ts/core'
import { SocketDockTransportSession } from './SocketDockTransportSession'
import express from 'express'

export class SocketDockInboundTransport implements InboundTransport {
private app: Express
private logger: Logger
private activeConnections: Record<string, string> = {}

constructor(app: Express, logger: Logger) {
public constructor({ app }: { app: Express }) {
this.app = app
this.logger = logger

this.app.use(express.json())
}

public async start(agent: Agent<any>) {
public async start(agent: Agent) {
this.app.post('/connect', async (req, res) => {
this.logger.info('SocketDockInboundTransport.connect')
const connectionId = req.body.meta.connection_id
agent.config.logger.info('SocketDockInboundTransport.connect')
const { connection_id: connectionId } = req.body.meta
if (!connectionId) {
throw new Error('ConnectionId is not sent from socketDock server')
}

const socketId = this.activeConnections[connectionId]
if (!socketId) {
this.activeConnections[socketId] = socketId
this.logger.debug(`Saving new socketId : ${connectionId}`)
agent.config.logger.debug(`Saving new socketId : ${connectionId}`)
}

try {
Expand All @@ -35,24 +35,28 @@ export class SocketDockInboundTransport implements InboundTransport {
})

this.app.post('/message', async (req, res) => {
this.logger.info('SocketDockInboundTransport.message')
agent.config.logger.info('SocketDockInboundTransport.message')

const connectionId = req.body.meta.connection_id
const { connection_id: connectionId } = req.body.meta
if (!connectionId) {
throw new Error('ConnectionId is not sent from socketDock server')
}

try {
const socketId = this.activeConnections[connectionId]
const sendUrl = req.body.meta.send
const requestMimeType = req.headers['content-type']
const session = new WebSocketTransportSession(socketId, res, sendUrl, requestMimeType)
const requestMimeType = req.headers['content-type'] as string
const session = new SocketDockTransportSession(socketId, res, sendUrl, requestMimeType)
const message = req.body.message
const encryptedMessage = JSON.parse(message)
await agent.receiveMessage(encryptedMessage, session)
if (!res.headersSent) {
res.status(200).end()
}

agent.events.emit<AgentMessageReceivedEvent>(agent.context, {
type: AgentEventTypes.AgentMessageReceived,
payload: {
message: encryptedMessage,
session: session,
},
})
} catch (error) {
if (!res.headersSent) {
res.status(500).send('Error processing message')
Expand All @@ -61,19 +65,17 @@ export class SocketDockInboundTransport implements InboundTransport {
})

this.app.post('/disconnect', async (req, res) => {
this.logger.info('SocketDockInboundTransport.disconnect')
agent.config.logger.info('SocketDockInboundTransport.disconnect')
const { connection_id } = req.body
if (!connection_id) {
throw new Error('ConnectionId is not sent from socketDock server')
}

delete this.activeConnections[connection_id]
this.logger.debug(`removed connection with socketId : ${connection_id}`)
agent.config.logger.debug(`removed connection with socketId : ${connection_id}`)
res.status(200).send(`connection with socketId : ${connection_id} removed successfully`)
})
}

stop(): Promise<void> {
throw new Error('Method not implemented.')
}
public async stop(): Promise<void> {}
}
18 changes: 11 additions & 7 deletions src/transport/SocketDockTransportSession.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,38 @@
import { Agent, AgentContext, DidCommMimeType, EncryptedMessage, TransportSession } from '@credo-ts/core'
import { AgentContext, DidCommMimeType, EncryptedMessage, TransportSession } from '@credo-ts/core'
import type { Response } from 'express'
import { CredoError } from '@credo-ts/core'

import { agentDependencies } from '@credo-ts/node'

const supportedContentTypes: string[] = [DidCommMimeType.V0, DidCommMimeType.V1]
export const supportedContentTypes: string[] = [DidCommMimeType.V0, DidCommMimeType.V1]

export class WebSocketTransportSession implements TransportSession {
export class SocketDockTransportSession implements TransportSession {
public id: string
public readonly type = 'socketdock'
public res: Response
public sendUrl: any
public sendUrl: string
public requestMimeType: any

public constructor(id: string, res: Response, sendUrl: any, requestMimeType: any) {
public constructor(id: string, res: Response, sendUrl: string, requestMimeType: string) {
this.id = id
this.res = res
this.sendUrl = sendUrl
this.requestMimeType = requestMimeType
}

public async close() {}
public async close() {
if (!this.res.headersSent) {
this.res.status(200).end()
}
}

public async send(agentContext: AgentContext, encryptedMessage: EncryptedMessage): Promise<void> {
if (this.res.headersSent) {
throw new CredoError(`${this.type} transport session has been closed.`)
}

// By default we take the agent config's default DIDComm content-type
let responseMimeType = agentContext.config.didCommMimeType as string
let responseMimeType = agentContext.config.didCommMimeType

if (this.requestMimeType && supportedContentTypes.includes(this.requestMimeType)) {
responseMimeType = this.requestMimeType
Expand Down
Loading

0 comments on commit 063ac8e

Please sign in to comment.