Skip to content

Commit

Permalink
fix: di and config mgmt (#38)
Browse files Browse the repository at this point in the history
Signed-off-by: Jason C. Leach <[email protected]>
  • Loading branch information
jleach authored Jan 19, 2025
1 parent b4cb51d commit 215ffa7
Show file tree
Hide file tree
Showing 17 changed files with 190 additions and 84 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ DS_Store
build
node_modules
.env
.env.local
.env.local
.pnpm-store/
3 changes: 3 additions & 0 deletions biome.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@
"correctness": {
"recommended": true,
"noUnusedImports": "error"
},
"style": {
"useImportType": "off"
}
}
},
Expand Down
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"test": "jest",
"build": "tsc -p tsconfig.build.json",
"prepublishOnly": "pnpm build",
"dev": "ts-node --env-file=.env.development --env-file .env.local dev",
"dev": "ts-node src/index.ts",
"start": "NODE_ENV=production node build/index.js"
},
"dependencies": {
Expand All @@ -28,7 +28,9 @@
"@hyperledger/aries-askar-nodejs": "^0.2.3",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"dotenv": "^16.4.7",
"express": "^4.21.2",
"nconf": "^0.12.1",
"tslog": "^3.3.3",
"tsyringe": "^4.8.0",
"ws": "^8.17.1"
Expand All @@ -39,6 +41,7 @@
"@ngrok/ngrok": "^1.2.0",
"@types/express": "^4.17.13",
"@types/jest": "^29.2.0",
"@types/nconf": "^0.10.7",
"@types/node": "^20.14.9",
"@types/ws": "^8.5.13",
"jest": "^29.2.2",
Expand Down
68 changes: 66 additions & 2 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

31 changes: 22 additions & 9 deletions src/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { ariesAskar } from '@hyperledger/aries-askar-nodejs'
import express from 'express'
import { Server } from 'ws'

import { AGENT_ENDPOINTS, AGENT_NAME, AGENT_PORT, LOG_LEVEL, POSTGRES_HOST, WALLET_KEY, WALLET_NAME } from './constants'
import config from './config'
import { askarPostgresConfig } from './database'
import { Logger } from './logger'
import { PushNotificationsFcmModule } from './push-notifications/fcm'
Expand Down Expand Up @@ -48,14 +48,14 @@ export async function createAgent() {
const app = express()
const socketServer = new Server({ noServer: true })

const logger = new Logger(LOG_LEVEL)
const logger = new Logger(config.get('agent:logLevel'))

// Only load postgres database in production
const storageConfig = POSTGRES_HOST ? askarPostgresConfig : undefined
const storageConfig = config.get('db:host') ? askarPostgresConfig : undefined

const walletConfig: WalletConfig = {
id: WALLET_NAME,
key: WALLET_KEY,
id: config.get('wallet:name'),
key: config.get('wallet:key'),
storage: storageConfig,
}

Expand All @@ -72,8 +72,8 @@ export async function createAgent() {

const agent = new Agent({
config: {
label: AGENT_NAME,
endpoints: AGENT_ENDPOINTS,
label: config.get('agent:name'),
endpoints: config.get('agent:endpoints'),
walletConfig: walletConfig,
useDidSovPrefixWhereAllowed: true,
logger: logger,
Expand All @@ -88,7 +88,7 @@ export async function createAgent() {
})

// Create all transports
const httpInboundTransport = new HttpInboundTransport({ app, port: AGENT_PORT })
const httpInboundTransport = new HttpInboundTransport({ app, port: config.get('agent:port') })
const httpOutboundTransport = new HttpOutboundTransport()
const wsInboundTransport = new WsInboundTransport({ server: socketServer })
const wsOutboundTransport = new WsOutboundTransport()
Expand All @@ -101,7 +101,7 @@ export async function createAgent() {

// Added health check endpoint
httpInboundTransport.app.get('/health', async (_req, res) => {
res.status(200).send('Ok')
res.sendStatus(202)
})

httpInboundTransport.app.get('/invite', async (req, res) => {
Expand All @@ -118,11 +118,24 @@ export async function createAgent() {
) {
return res.status(400).send(`No invitation found for _oobid ${req.query._oobid}`)
}

return res.send(outOfBandRecord.outOfBandInvitation.toJSON())
})

await agent.initialize()

httpInboundTransport.server?.on('listening', () => {
logger.info(`Agent listening on port ${config.get('agent:port')}`)
})

httpInboundTransport.server?.on('error', (err) => {
logger.error(`Agent failed to start on port ${config.get('agent:port')}`, err)
})

httpInboundTransport.server?.on('close', () => {
logger.info(`Agent stopped listening on port ${config.get('agent:port')}`)
})

// When an 'upgrade' to WS is made on our http server, we forward the
// request to the WS server
httpInboundTransport.server?.on('upgrade', (request, socket, head) => {
Expand Down
57 changes: 57 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import path from 'node:path'
import { LogLevel } from '@credo-ts/core'
import dotenv from 'dotenv'
import nconf from 'nconf'

const dirName = __dirname
const configFileName = 'config.json'
const env = process.env.NODE_ENV ?? 'development'

if (env === 'development') {
dotenv.config()
}

/**
* These settings contain sensitive information and should not be
* stored in the repo. They are extracted from environment variables
* and added to the config.
*/

const agentPort = Number(process.env.AGENT_PORT ?? 3110)

// overrides are always as defined
nconf.overrides({
db: {
host: process.env.POSTGRES_HOST,
user: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
adminUser: process.env.POSTGRES_ADMIN_USER,
adminPassword: process.env.POSTGRES_ADMIN_PASSWORD,
},
agent: {
port: agentPort,
endpoints: process.env.AGENT_ENDPOINTS
? process.env.AGENT_ENDPOINTS.split(',')
: [`http://localhost:${agentPort}`, `ws://localhost:${agentPort}`],
name: process.env.AGENT_NAME ?? 'My Mediator',
invitationUrl: process.env.INVITATION_URL,
logLevel: process.env.LOG_LEVEL ?? LogLevel.debug,
usePushNotifications: process.env.USE_PUSH_NOTIFICATIONS === 'true',
notificationWebhookUrl: process.env.NOTIFICATION_WEBHOOK_URL,
},
wallet: {
name: process.env.WALLET_NAME ?? 'mediator-dev',
key: process.env.WALLET_KEY ?? 'blarbzzz',
},
})

// load other properties from file.
nconf
.argv({ parseValues: true })
.env()
.file({ file: path.join(dirName, '../', configFileName) })

// if nothing else is set, use defaults. This will be set
// if they do not exist in overrides or the config file.

export default nconf
26 changes: 0 additions & 26 deletions src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,26 +0,0 @@
import { LogLevel } from '@credo-ts/core'

export const AGENT_PORT = process.env.AGENT_PORT ? Number(process.env.AGENT_PORT) : 3000
export const AGENT_NAME = process.env.AGENT_NAME || 'Credo Mediator'
export const WALLET_NAME = process.env.WALLET_NAME || 'credo-mediator-dev'
export const WALLET_KEY = process.env.WALLET_KEY || 'credo-mediator-dev'
export const AGENT_ENDPOINTS = process.env.AGENT_ENDPOINTS?.split(',') ?? [
`http://localhost:${AGENT_PORT}`,
`ws://localhost:${AGENT_PORT}`,
]

export const POSTGRES_HOST = process.env.POSTGRES_HOST
export const POSTGRES_USER = process.env.POSTGRES_USER
export const POSTGRES_PASSWORD = process.env.POSTGRES_PASSWORD
export const POSTGRES_ADMIN_USER = process.env.POSTGRES_ADMIN_USER
export const POSTGRES_ADMIN_PASSWORD = process.env.POSTGRES_ADMIN_PASSWORD

export const INVITATION_URL = process.env.INVITATION_URL

export const LOG_LEVEL = LogLevel.debug

export const IS_DEV = process.env.NODE_ENV === 'development'

export const USE_PUSH_NOTIFICATIONS = process.env.USE_PUSH_NOTIFICATIONS === 'true'

export const NOTIFICATION_WEBHOOK_URL = process.env.NOTIFICATION_WEBHOOK_URL || 'http://localhost:5000'
Loading

0 comments on commit 215ffa7

Please sign in to comment.