From 7c37578bbb673c7b2141b2497cbf37df8203ce6c Mon Sep 17 00:00:00 2001 From: Ariel Gentile Date: Mon, 27 Jan 2025 17:30:43 -0300 Subject: [PATCH] refactor: references to cloud agent to mediator Signed-off-by: Ariel Gentile --- README.md | 64 ++++++------- docker-compose-lb.yml | 24 ++--- docker-compose.yml | 14 +-- ...{CloudAgent.ts => DidCommMediatorAgent.ts} | 22 +++-- ...udAgent.ts => initDidCommMediatorAgent.ts} | 95 +++++++++---------- src/config/constants.ts | 6 +- src/index.ts | 8 +- .../LocalFcmNotificationSender.ts | 14 +-- .../InMemoryMessagePickupRepository.ts | 18 ++-- ...sport.ts => MediatorWsInboundTransport.ts} | 2 +- .../test => test}/Client-Agent/ClientAgent.ts | 0 .../Client-Agent/Multiple_Agents.ts | 0 {src/test => test}/Client-Agent/README.md | 2 +- {src/test => test}/Send-Messages/README.md | 0 .../Send-Messages/send-massive-message.ts | 0 15 files changed, 131 insertions(+), 138 deletions(-) rename src/agent/{CloudAgent.ts => DidCommMediatorAgent.ts} (79%) rename src/agent/{initCloudAgent.ts => initDidCommMediatorAgent.ts} (92%) rename src/transport/{CloudWsInboundTransport.ts => MediatorWsInboundTransport.ts} (98%) rename {src/test => test}/Client-Agent/ClientAgent.ts (100%) rename {src/test => test}/Client-Agent/Multiple_Agents.ts (100%) rename {src/test => test}/Client-Agent/README.md (95%) rename {src/test => test}/Send-Messages/README.md (100%) rename {src/test => test}/Send-Messages/send-massive-message.ts (100%) diff --git a/README.md b/README.md index 8a695f3..cfd5e20 100644 --- a/README.md +++ b/README.md @@ -2,21 +2,22 @@ ## Configuration -### Mediator + +### Environment variables At the moment, all configuration is done by environment variables. All of them are optional | Variable | Description | Default value | | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | -| AGENT_NAME | Label to show to other DIDComm agents | Test Cloud Agent | +| AGENT_NAME | Label to show to other DIDComm agents | Test DIDComm Mediator | | AGENT_ENDPOINTS | Comma-separated public endpoint list where agent DIDComm endpoints will be accessible (including protocol and port) | ws://localhost:4000 | | AGENT_PUBLIC_DID | Agent's public DID (in did:web format) | None | | AGENT_PORT | Port where DIDComm agent will be running | 4000 | | AGENT_LOG_LEVEL | Agent log level | 2 (debug) | | HTTP_SUPPORT | Enable support of incoming DIDComm messages through HTTP transport | true | | WS_SUPPORT | Enable support of incoming DIDComm messages through WebSocket transport | true | -| WALLET_NAME | Wallet (database) name | test-cloud-agent | -| WALLET_KEY | Wallet base encryption key | 'Test Cloud Agent' | +| WALLET_NAME | Wallet (database) name | test-didcomm-mediator | +| WALLET_KEY | Wallet base encryption key | 'Test DIDComm Mediator' | | KEY_DERIVATION_METHOD | Wallet key derivation method | ARGON2I_MOD | | POSTGRES_HOST | PosgreSQL database host | None (use SQLite) | | POSTGRES_USER | PosgreSQL database username | None | @@ -29,13 +30,29 @@ At the moment, all configuration is done by environment variables. All of them a These variables might be set also in `.env` file in the form of KEY=VALUE (one per line). +### Message Pickup modes + +This apps supports a flexible configuration for Message Pickup repositories, allowing users to choose between different persistence methods depending on their needs. This enhancement provides seamless integration with the following repository options: + +- **MessagePickupRepositoryClient**: A WebSocket-based repository for distributed environments. It requires a specific server +- **PostgresMessagePickupRepository**: A PostgreSQL-based repository for persistent storage. It is meant for simplicity, so it uses the same Postgres host than mediator's wallet. +- **InMemoryMessagePickupRepository**: An in-memory repository for lightweight setups or testing purposes. It only works when SQLite is used for mediator wallet. + +### How to configure + +The repository configuration is controlled by these environment variables. The mediator will automatically detect the active variable and initialize the appropriate repository. + +1. WebSocket-Based Repository (MessagePickupRepositoryClient): Set the `MPR_WS_URL` environment variable to the WebSocket server URL. +2. PostgreSQL-Based Repository (PostgresMessagePickupRepository): Set the `POSTGRES_HOST` environment variable to the PostgreSQL connection string and `MPR_WS_URL` is null +3. In-Memory Repository (InMemoryMessagePickupRepository): If neither `MPR_WS_URL` and `POSTGRES_HOST` is set, the mediator will default to InMemoryMessagePickupRepository. + ## Deploy and run -2060-cloud-agent can be run both locally or containerized. +The DIDComm mediator can be run both locally or containerized. ### Locally -2060-cloud-agent mediator can be built and run on localhost by just setting the corresponding variables and executing: +DIDComm mediator can be built and run on localhost by just setting the corresponding variables and executing: ``` yarn build @@ -45,7 +62,7 @@ yarn start Upon a successful start, the following lines should be read in log: ``` -INFO: Cloud Agent initialized OK +INFO: DIDComm Mediator Agent initialized OK ``` ### Using docker @@ -53,34 +70,32 @@ INFO: Cloud Agent initialized OK First of all, a docker image must be created by doing: ``` -docker build -t 2060-cloud-agent:[tag] . +docker build -t didcomm-mediator:[tag] . ``` Then, a container can be created and deployed: ``` -docker run -e AGENT_NAME=... -e AGENT_ENDPOINT=... -e AGENT_PUBLIC_DID=yyy -e AGENT_PORT=xxx -p yyy:xxx 2060-cloud-agent:[tag] +docker run -e AGENT_NAME=... -e AGENT_ENDPOINT=... -e AGENT_PUBLIC_DID=yyy -e AGENT_PORT=xxx -p yyy:xxx didcomm-mediator:[tag] ``` where yyy is an publicly accesible port from the host machine. -This one will run default command, which launches the mediator. If you want to run a VDR Proxy, you can override this command and use `yarn vdrproxy`. +## How to test -# How to testing - -## Testing with Agent Clients +### Testing with Agent Clients For more details, see the [Client-Agent test](/src/test/Client-Agent/README.md). -## Testing massive message between Agents Clients +### Testing massive message between Agents Clients For more details, see the [Massive Message Sender test](/src/test/Send-Messages/README.md). -## Test Load balancer with Cloud agent live mode with message repository DB pub/sub and postgres wallets +### Test a load balancer with multiple agent instances supporting Message Pickup in Live mode -- The porpuse is to be able to test the cloud agent live mode implemented with postgres for storage messagePickup, pub/sub for comunication instances and postgres for storage wallets, to do this you must do running docker compose locate on root of project file called [docker-comopose-lb.yml] +The purpose is to be able to test DIDComm mediator in a multi-instance environment, using Postgres as a backend for both Agent wallet and Message Pickup queue. -### Setup +#### Setup 1. You should be set IP local in the file nginx.conf locate on ngnix folder a section upstream @@ -97,18 +112,3 @@ server IP-HOST:4002; docker compose -f docker-compose-lb.yml up --build ``` -## Didcomm Mediator: Configurable Message Pickup Repository - -The Didcomm Mediator now supports flexible configuration for message pickup repositories, allowing users to choose between different persistence methods depending on their needs. This enhancement provides seamless integration with the following repository options: - -- MessagePickupRepositoryClient: A WebSocket-based repository for distributed environments. -- PostgresMessagePickupRepository: A PostgreSQL-based repository for persistent storage. It is meant for simplicity, so it uses the same Postgres host than mediator's wallet. -- InMemoryMessagePickupRepository: An in-memory repository for lightweight setups or testing purposes. It only works when SQLite is used for mediator wallet. - -### How to configure - -The repository configuration is controlled by these environment variables. The mediator will automatically detect the active variable and initialize the appropriate repository. - -1. WebSocket-Based Repository (MessagePickupRepositoryClient): Set the `MPR_WS_URL` environment variable to the WebSocket server URL. -2. PostgreSQL-Based Repository (PostgresMessagePickupRepository): Set the `POSTGRES_HOST` environment variable to the PostgreSQL connection string and `MPR_WS_URL` is null -3. In-Memory Repository (InMemoryMessagePickupRepository): If neither `MPR_WS_URL` and `POSTGRES_HOST` is set, the mediator will default to InMemoryMessagePickupRepository. diff --git a/docker-compose-lb.yml b/docker-compose-lb.yml index f47e862..5059156 100644 --- a/docker-compose-lb.yml +++ b/docker-compose-lb.yml @@ -8,8 +8,8 @@ services: volumes: - ~/data/dm/postgres:/var/lib/postgresql/data environment: - - POSTGRES_PASSWORD=cloud-agent - - POSTGRES_USER=cloud-agent + - POSTGRES_PASSWORD=didcomm-mediator + - POSTGRES_USER=didcomm-mediator didcomm-mediator-1: build: . @@ -19,12 +19,12 @@ services: environment: #- AGENT_PUBLIC_DID=did:web:10.82.14.176%3A4000 #- AGENT_ENDPOINTS=ws://10.82.14.176:4000 - - AGENT_NAME=2060 Cloud Agent - Dev - - WALLET_NAME=2060-cloud-agent-dev - - WALLET_KEY=2060-cloud-agent-dev + - AGENT_NAME=2060 DIDComm mediator - Dev + - WALLET_NAME=2060-didcomm-mediator-dev + - WALLET_KEY=2060-didcomm-mediator-dev - POSTGRES_HOST=postgres - - POSTGRES_USER=cloud-agent - - POSTGRES_PASSWORD=cloud-agent + - POSTGRES_USER=didcomm-mediator + - POSTGRES_PASSWORD=didcomm-mediator - KEY_DERIVATION_METHOD=ARGON2I_MOD #- MPR_WS_URL=ws://192.168.10.13:3100 #- MAX_RECEIVE_BYTES=1000000 @@ -47,12 +47,12 @@ services: environment: #- AGENT_PUBLIC_DID=did:web:10.82.14.176%3A4000 #- AGENT_ENDPOINTS=ws://10.82.14.176:4000 - - AGENT_NAME=2060 Cloud Agent - Dev - - WALLET_NAME=2060-cloud-agent-dev - - WALLET_KEY=2060-cloud-agent-dev + - AGENT_NAME=2060 DIDComm Mediator - Dev + - WALLET_NAME=2060-didcomm-mediator-dev + - WALLET_KEY=2060-didcomm-mediator-dev - POSTGRES_HOST=postgres - - POSTGRES_USER=cloud-agent - - POSTGRES_PASSWORD=cloud-agent + - POSTGRES_USER=didcomm-mediator + - POSTGRES_PASSWORD=didcomm-mediator - KEY_DERIVATION_METHOD=ARGON2I_MOD #- MPR_WS_URL=ws://192.168.10.13:3100 #- MAX_RECEIVE_BYTES=1000000 diff --git a/docker-compose.yml b/docker-compose.yml index f53234f..4442eaa 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -8,8 +8,8 @@ services: volumes: - ~/data/dm/postgres:/var/lib/postgresql/data environment: - - POSTGRES_PASSWORD=cloud-agent - - POSTGRES_USER=cloud-agent + - POSTGRES_PASSWORD=didcomm-mediator + - POSTGRES_USER=didcomm-mediator didcomm-mediator-1: build: . @@ -19,12 +19,12 @@ services: environment: #- AGENT_PUBLIC_DID=did:web:10.82.14.176%3A4000 #- AGENT_ENDPOINTS=ws://10.82.14.176:4000 - - AGENT_NAME=2060 Cloud Agent - Dev - - WALLET_NAME=2060-cloud-agent-dev - - WALLET_KEY=2060-cloud-agent-dev + - AGENT_NAME=2060 DIDComm Mediator - Dev + - WALLET_NAME=2060-didcomm-mediator-dev + - WALLET_KEY=2060-didcomm-mediator-dev - POSTGRES_HOST=postgres - - POSTGRES_USER=cloud-agent - - POSTGRES_PASSWORD=cloud-agent + - POSTGRES_USER=didcomm-mediator + - POSTGRES_PASSWORD=didcomm-mediator - KEY_DERIVATION_METHOD=ARGON2I_MOD - FIREBASE_CFG_FILE=/config/firebase-cfg.json #- MPR_WS_URL=ws://192.168.10.13:3100 diff --git a/src/agent/CloudAgent.ts b/src/agent/DidCommMediatorAgent.ts similarity index 79% rename from src/agent/CloudAgent.ts rename to src/agent/DidCommMediatorAgent.ts index ae8abfe..6c59dd4 100644 --- a/src/agent/CloudAgent.ts +++ b/src/agent/DidCommMediatorAgent.ts @@ -14,7 +14,7 @@ import { ariesAskar } from '@hyperledger/aries-askar-nodejs' import { PushNotificationsFcmModule } from '@credo-ts/push-notifications' import { MessageForwardingStrategy } from '@credo-ts/core/build/modules/routing/MessageForwardingStrategy' -type CloudAgentModules = { +type DidCommMediatorAgentModules = { askar: AskarModule connections: ConnectionsModule mediator: MediatorModule @@ -22,16 +22,20 @@ type CloudAgentModules = { pushNotifications: PushNotificationsFcmModule } -interface AgentOptions { +interface AgentOptions { config: InitConfig - modules?: ServiceAgentModules + modules?: Modules dependencies: AgentDependencies } -export class CloudAgent extends Agent { +export class DidCommMediatorAgent extends Agent { public did?: string - public constructor(options: AgentOptions, did?: string, dependencyManager?: DependencyManager) { + public constructor( + options: AgentOptions, + did?: string, + dependencyManager?: DependencyManager + ) { super(options, dependencyManager) this.did = did } @@ -49,14 +53,14 @@ export interface CloudAgentOptions { postgresUser?: string postgresPassword?: string postgresHost?: string - postgresMessagePickupDatabaseName?: string + messagePickupPostgresDatabaseName?: string } -export const createCloudAgent = ( +export const createMediator = ( options: CloudAgentOptions, messagePickupRepository: MessagePickupRepository -): CloudAgent => { - return new CloudAgent( +): DidCommMediatorAgent => { + return new DidCommMediatorAgent( { config: options.config, dependencies: options.dependencies, diff --git a/src/agent/initCloudAgent.ts b/src/agent/initDidCommMediatorAgent.ts similarity index 92% rename from src/agent/initCloudAgent.ts rename to src/agent/initDidCommMediatorAgent.ts index 60320b4..86a41b9 100644 --- a/src/agent/initCloudAgent.ts +++ b/src/agent/initDidCommMediatorAgent.ts @@ -27,14 +27,14 @@ import { RoutingEventTypes, HangupMessage, MessagePickupRepository, + utils, } from '@credo-ts/core' import WebSocket from 'ws' import { Socket } from 'net' -import { CloudAgentOptions, createCloudAgent } from './CloudAgent' -import { CloudWsInboundTransport } from '../transport/CloudWsInboundTransport' +import { CloudAgentOptions, createMediator } from './DidCommMediatorAgent' +import { MediatorWsInboundTransport } from '../transport/MediatorWsInboundTransport' import { HttpInboundTransport } from '../transport/HttpInboundTransport' -import { uuid } from '@credo-ts/core/build/utils/uuid' import express from 'express' import cors from 'cors' import { PushNotificationsFcmSetDeviceInfoMessage } from '@credo-ts/push-notifications' @@ -45,7 +45,7 @@ import { MessagePickupRepositoryClient } from '@2060.io/message-pickup-repositor import { ConnectionInfo } from '@2060.io/message-pickup-repository-client/build/interfaces' import { PostgresMessagePickupRepository } from '@2060.io/credo-ts-message-pickup-repository-pg' -export const initCloudAgent = async (config: CloudAgentOptions) => { +export const initMediator = async (config: CloudAgentOptions) => { const logger = config.config.logger ?? new ConsoleLogger(LogLevel.off) const publicDid = config.did @@ -79,7 +79,7 @@ export const initCloudAgent = async (config: CloudAgentOptions) => { throw new Error('No transport has been enabled. Set at least one of HTTP and WS') } - const agent = createCloudAgent(config, messageRepository) + const agent = createMediator(config, messageRepository) if (messageRepository instanceof MessagePickupRepositoryClient) { await messageRepository.connect() @@ -158,10 +158,31 @@ export const initCloudAgent = async (config: CloudAgentOptions) => { if (config.enableWs) { webSocketServer = new WebSocket.Server({ noServer: true }) - agent.registerInboundTransport(new CloudWsInboundTransport({ server: webSocketServer })) + agent.registerInboundTransport(new MediatorWsInboundTransport({ server: webSocketServer })) agent.registerOutboundTransport(new WsOutboundTransport()) } + app.get('/invitation', async (req, res) => { + logger.info(`Invitation requested`) + + const outOfBandInvitation = agent.did + ? new OutOfBandInvitation({ + id: agent.did, + services: [agent.did], + label: agent.config.label, + handshakeProtocols: [HandshakeProtocol.DidExchange, HandshakeProtocol.Connections], + imageUrl: process.env.AGENT_INVITATION_IMAGE_URL, + }) + : ( + await agent.oob.createInvitation({ + imageUrl: process.env.AGENT_INVITATION_IMAGE_URL, + }) + ).outOfBandInvitation + res.send({ + url: outOfBandInvitation.toUrl({ domain: process.env.AGENT_INVITATION_BASE_URL ?? 'https://2060.io/i' }), + }) + }) + await agent.initialize() logger.info('agent initialized') @@ -180,7 +201,7 @@ export const initCloudAgent = async (config: CloudAgentOptions) => { const connectionId = data.payload.session.connectionId const sessionId = data.payload.session.id await messageRepository.addLiveSession({ connectionId, sessionId }) - logger.debug(`*** addLiveSession succesfull ${data.payload.session.connectionId} ***`) + logger.debug(`*** addLiveSession successful for ${data.payload.session.connectionId} ***`) } }) @@ -201,48 +222,12 @@ export const initCloudAgent = async (config: CloudAgentOptions) => { if (config.enableWs) { server?.on('upgrade', (request, socket, head) => { webSocketServer.handleUpgrade(request, socket as Socket, head, (socketParam) => { - const socketId = uuid() + const socketId = utils.uuid() webSocketServer.emit('connection', socketParam, request, socketId) }) }) } - app.get('/.well-known/did.json', async (req, res) => { - logger.info(`Public DidDocument requested`) - if (agent.did) { - const [didRecord] = await agent.dids.getCreatedDids({ did: agent.did }) - - const didDocument = didRecord.didDocument?.toJSON() - - if (didDocument) { - res.send(didDocument) - } - } else { - res.send({ error: 'not found' }) - } - }) - - app.get('/invitation', async (req, res) => { - logger.info(`Invitation requested`) - - const outOfBandInvitation = agent.did - ? new OutOfBandInvitation({ - id: agent.did, - services: [agent.did], - label: agent.config.label, - handshakeProtocols: [HandshakeProtocol.DidExchange, HandshakeProtocol.Connections], - imageUrl: process.env.AGENT_INVITATION_IMAGE_URL, - }) - : ( - await agent.oob.createInvitation({ - imageUrl: process.env.AGENT_INVITATION_IMAGE_URL, - }) - ).outOfBandInvitation - res.send({ - url: outOfBandInvitation.toUrl({ domain: process.env.AGENT_INVITATION_BASE_URL ?? 'https://2060.io/i' }), - }) - }) - agent.events.on(AgentEventTypes.AgentMessageProcessed, async (data) => { logger.info(`Message processed for connection id ${data.payload.connection?.id} Type: ${data.payload.message.type}`) @@ -265,6 +250,20 @@ export const initCloudAgent = async (config: CloudAgentOptions) => { }) if (publicDid) { + app.get('/.well-known/did.json', async (req, res) => { + logger.info(`Public DidDocument requested`) + + const [didRecord] = await agent.dids.getCreatedDids({ did: agent.did }) + + const didDocument = didRecord.didDocument?.toJSON() + + if (didDocument) { + res.send(didDocument) + } else { + res.status(404).end() + } + }) + // If a public did is specified, check if it's already stored in the wallet. If it's not the case, // create a new one and generate keys for DIDComm (if there are endpoints configured) // TODO: Make DIDComm version, keys, etc. configurable. Keys can also be imported @@ -352,13 +351,5 @@ export const initCloudAgent = async (config: CloudAgentOptions) => { } } - const outOfBandRecord = await agent.oob.createInvitation({ - multiUseInvitation: true, - }) - - const multiuseInvitation = outOfBandRecord.outOfBandInvitation.toUrl({ domain: 'https://2060.io/i' }) - - logger.info(`multiuseInvitation: ${multiuseInvitation}`) - return { app, agent } } diff --git a/src/config/constants.ts b/src/config/constants.ts index 65539f6..3a065fd 100644 --- a/src/config/constants.ts +++ b/src/config/constants.ts @@ -6,15 +6,15 @@ dotenv.config() export const AGENT_PORT = Number(process.env.AGENT_PORT || 4000) export const AGENT_LOG_LEVEL = process.env.AGENT_LOG_LEVEL ? Number(process.env.AGENT_LOG_LEVEL) : LogLevel.debug -export const AGENT_NAME = process.env.AGENT_NAME || 'Test Cloud Agent' +export const AGENT_NAME = process.env.AGENT_NAME || 'Test DIDComm Mediator' export const AGENT_ENDPOINTS = process.env.AGENT_ENDPOINTS?.replace(' ', '').split(',') || ['ws://localhost:4000'] export const AGENT_PUBLIC_DID = process.env.AGENT_PUBLIC_DID export const HTTP_SUPPORT = Boolean(process.env.HTTP_SUPPORT ?? true) export const WS_SUPPORT = Boolean(process.env.WS_SUPPORT ?? true) // Wallet -export const WALLET_NAME = process.env.WALLET_NAME || 'test-cloud-agent' -export const WALLET_KEY = process.env.WALLET_KEY || 'Test Cloud Agent' +export const WALLET_NAME = process.env.WALLET_NAME || 'test-didcomm-mediator' +export const WALLET_KEY = process.env.WALLET_KEY || 'Test DIDComm Mediator' export const KEY_DERIVATION_METHOD = process.env.KEY_DERIVATION_METHOD export const POSTGRES_HOST = process.env.POSTGRES_HOST export const POSTGRES_USER = process.env.POSTGRES_USER diff --git a/src/index.ts b/src/index.ts index 4418f9a..178f325 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,5 @@ import { ConsoleLogger, KeyDerivationMethod } from '@credo-ts/core' -import { initCloudAgent } from './agent/initCloudAgent' +import { initMediator } from './agent/initDidCommMediatorAgent' import { agentDependencies } from '@credo-ts/node' import { AgentLogger } from './config/logger' import { @@ -27,7 +27,7 @@ const logger = new ConsoleLogger(AGENT_LOG_LEVEL) async function run() { logger.info(`Cloud Agent started on port ${AGENT_PORT}`) try { - await initCloudAgent({ + await initMediator({ config: { label: AGENT_NAME, endpoints: AGENT_ENDPOINTS, @@ -51,14 +51,14 @@ async function run() { postgresUser: POSTGRES_USER, postgresPassword: POSTGRES_PASSWORD, postgresHost: POSTGRES_HOST, - postgresMessagePickupDatabaseName: MPR_POSTGRES_DATABASE_NAME, + messagePickupPostgresDatabaseName: MPR_POSTGRES_DATABASE_NAME, }) } catch (error) { logger.error(`${error}`) process.exit(1) } - logger.info(`Cloud Agent initialized OK`) + logger.info(`DIDComm mediator initialized OK`) } run() diff --git a/src/notifications/LocalFcmNotificationSender.ts b/src/notifications/LocalFcmNotificationSender.ts index 9882ba6..5584d44 100644 --- a/src/notifications/LocalFcmNotificationSender.ts +++ b/src/notifications/LocalFcmNotificationSender.ts @@ -8,9 +8,9 @@ import { FIREBASE_CFG_FILE } from '../config/constants' export class LocalFcmNotificationSender implements FcmNotificationSender { private fcmApp: FcmApp | null = null - private logger: Logger + private logger?: Logger - public constructor(logger: Logger) { + public constructor(logger?: Logger) { this.logger = logger try { @@ -18,9 +18,9 @@ export class LocalFcmNotificationSender implements FcmNotificationSender { this.fcmApp = initializeApp({ credential: credential.cert(configPath), }) - this.logger.debug('[LocalFcmNotificationSender] Firebase-admin initialized successfully') + this.logger?.debug('[LocalFcmNotificationSender] Firebase-admin initialized successfully') } catch (error) { - this.logger.warn( + this.logger?.warn( '[LocalFcmNotificationSender] Failed to initialize Firebase Admin. Notifications will be disabled:', error.message ) @@ -31,7 +31,7 @@ export class LocalFcmNotificationSender implements FcmNotificationSender { public async sendMessage(registrationToken: string, messageId: string) { try { if (!this.fcmApp) { - this.logger.warn('Firebase Admin is not initialized. Skipping notification.') + this.logger?.warn('Firebase Admin is not initialized. Skipping notification.') return false } const response = await getMessaging(this.fcmApp).send({ @@ -51,10 +51,10 @@ export class LocalFcmNotificationSender implements FcmNotificationSender { }, apns: { payload: { aps: { contentAvailable: true } } }, }) - this.logger.debug(`Message sent successfully: ${response}`) + this.logger?.debug(`Message sent successfully: ${response}`) return true } catch (error) { - this.logger.error('Error while sending notification:', error.message) + this.logger?.error('Error while sending notification:', error.message) return false } } diff --git a/src/storage/InMemoryMessagePickupRepository.ts b/src/storage/InMemoryMessagePickupRepository.ts index 32a0ed2..d4f4a33 100644 --- a/src/storage/InMemoryMessagePickupRepository.ts +++ b/src/storage/InMemoryMessagePickupRepository.ts @@ -6,11 +6,9 @@ import type { RemoveMessagesOptions, TakeFromQueueOptions, } from '@credo-ts/core' -import { injectable } from '@credo-ts/core' -import { CloudAgent } from '../agent/CloudAgent' +import { injectable, MessagePickupRepository, utils } from '@credo-ts/core' +import { DidCommMediatorAgent } from '../agent/DidCommMediatorAgent' import { FcmNotificationSender } from '../notifications/FcmNotificationSender' -import { MessagePickupRepository } from '@credo-ts/core' -import { uuid } from '@credo-ts/core/build/utils/uuid' interface InMemoryQueuedMessage extends QueuedMessage { connectionId: string @@ -21,7 +19,7 @@ interface InMemoryQueuedMessage extends QueuedMessage { export class InMemoryMessagePickupRepository implements MessagePickupRepository { private logger?: Logger private messages: InMemoryQueuedMessage[] - private agent?: CloudAgent + private agent?: DidCommMediatorAgent private notificationSender: FcmNotificationSender | undefined public constructor(notificationSender: FcmNotificationSender, logger?: Logger) { @@ -30,7 +28,7 @@ export class InMemoryMessagePickupRepository implements MessagePickupRepository this.messages = [] } - public setAgent(agent: CloudAgent) { + public setAgent(agent: DidCommMediatorAgent) { this.agent = agent } @@ -54,7 +52,7 @@ export class InMemoryMessagePickupRepository implements MessagePickupRepository const messagesToTake = limit ?? messages.length this.logger?.debug( - `[CustomMessageRepository] Taking ${messagesToTake} messages from queue for connection ${connectionId}` + `[InMemoryMessagePickupRepository] Taking ${messagesToTake} messages from queue for connection ${connectionId}` ) if (deleteMessages) { this.removeMessages({ connectionId, messageIds: messages.map((msg) => msg.id) }) @@ -65,9 +63,9 @@ export class InMemoryMessagePickupRepository implements MessagePickupRepository public async addMessage(options: AddMessageOptions) { const { connectionId, recipientDids, payload } = options - this.logger?.info(`[CustomMessageRepository] Adding message for connection ${connectionId}`) + this.logger?.info(`[InMemoryMessagePickupRepository] Adding message for connection ${connectionId}`) - const id = uuid() + const id = utils.uuid() this.messages.push({ id, connectionId, @@ -81,7 +79,7 @@ export class InMemoryMessagePickupRepository implements MessagePickupRepository const token = connectionRecord?.getTag('device_token') as string | null if (token) { - this.logger?.info(`[CustomMessageRepository] Send notification for connection ${connectionId}`) + this.logger?.info(`[InMemoryMessagePickupRepository] Send notification for connection ${connectionId}`) if (this.notificationSender) await this.notificationSender.sendMessage(token, 'messageId') } } diff --git a/src/transport/CloudWsInboundTransport.ts b/src/transport/MediatorWsInboundTransport.ts similarity index 98% rename from src/transport/CloudWsInboundTransport.ts rename to src/transport/MediatorWsInboundTransport.ts index af45139..a4066b1 100644 --- a/src/transport/CloudWsInboundTransport.ts +++ b/src/transport/MediatorWsInboundTransport.ts @@ -17,7 +17,7 @@ interface ExtWebSocket extends WebSocket { isAlive: boolean } -export class CloudWsInboundTransport implements InboundTransport { +export class MediatorWsInboundTransport implements InboundTransport { private socketServer: Server private logger!: Logger diff --git a/src/test/Client-Agent/ClientAgent.ts b/test/Client-Agent/ClientAgent.ts similarity index 100% rename from src/test/Client-Agent/ClientAgent.ts rename to test/Client-Agent/ClientAgent.ts diff --git a/src/test/Client-Agent/Multiple_Agents.ts b/test/Client-Agent/Multiple_Agents.ts similarity index 100% rename from src/test/Client-Agent/Multiple_Agents.ts rename to test/Client-Agent/Multiple_Agents.ts diff --git a/src/test/Client-Agent/README.md b/test/Client-Agent/README.md similarity index 95% rename from src/test/Client-Agent/README.md rename to test/Client-Agent/README.md index 6b48aa8..80c4784 100644 --- a/src/test/Client-Agent/README.md +++ b/test/Client-Agent/README.md @@ -83,5 +83,5 @@ After run clientAgents you select 2 connections that are connected with diferent ## Notes - The client agent automatically accepts incoming connections (autoAcceptConnections is set to true). -- Mediation is initiated if no default mediator is found. The mediator's - - invitation URL is fetched from http://localhost:4000/invitation. You can change this url to that of the cloud-agent locate to cloud an connect with Mobile Agent. +- Mediation is initiated if no default mediator is found. The mediator's - - invitation URL is fetched from http://localhost:4000/invitation. You can change this url to that of the didcomm-mediator locate to cloud an connect with Mobile Agent. - The agent utilizes WebSocket (WsOutboundTransport) for outbound transport. diff --git a/src/test/Send-Messages/README.md b/test/Send-Messages/README.md similarity index 100% rename from src/test/Send-Messages/README.md rename to test/Send-Messages/README.md diff --git a/src/test/Send-Messages/send-massive-message.ts b/test/Send-Messages/send-massive-message.ts similarity index 100% rename from src/test/Send-Messages/send-massive-message.ts rename to test/Send-Messages/send-massive-message.ts