Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Cached tentant record for context #2025

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages/tenants/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@
},
"dependencies": {
"@credo-ts/core": "workspace:*",
"async-mutex": "^0.4.0"
"async-mutex": "^0.4.0",
"tsyringe": "^4.8.0"
},
"devDependencies": {
"@credo-ts/node": "workspace:*",
Expand Down
23 changes: 20 additions & 3 deletions packages/tenants/src/context/TenantAgentContextProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
isValidJweStructure,
JsonEncoder,
isJsonObject,
CacheModuleConfig,
} from '@credo-ts/core'

import { TenantAgent } from '../TenantAgent'
Expand Down Expand Up @@ -55,13 +56,25 @@ export class TenantAgentContextProvider implements AgentContextProvider {
}

public async getAgentContextForContextCorrelationId(contextCorrelationId: string) {
this.logger.debug('Inside getAgentContextForContextCorrelationId')
// It could be that the root agent context is requested, in that case we return the root agent context
if (contextCorrelationId === this.rootAgentContext.contextCorrelationId) {
return this.rootAgentContext
}

// TODO: maybe we can look at not having to retrieve the tenant record if there's already a context available.
const tenantRecord = await this.tenantRecordService.getTenantById(this.rootAgentContext, contextCorrelationId)
const cache = this.rootAgentContext.dependencyManager.resolve(CacheModuleConfig).cache
let isTenantRecordCached = true

this.logger.debug(`Getting tenantRecord with id ${contextCorrelationId} from cache`)
let tenantRecord: TenantRecord | null = await cache.get(
this.rootAgentContext,
`contextCorrelationId-${contextCorrelationId}`
)
if (!tenantRecord) {
isTenantRecordCached = false
this.logger.debug(`TenantRecord with id ${contextCorrelationId} not found in cache`)
tenantRecord = await this.tenantRecordService.getTenantById(this.rootAgentContext, contextCorrelationId)
}
const shouldUpdate = !isStorageUpToDate(tenantRecord.storageVersion)

// If the tenant storage is not up to date, and autoUpdate is disabled we throw an error
Expand All @@ -77,9 +90,13 @@ export class TenantAgentContextProvider implements AgentContextProvider {
const agentContext = await this.tenantSessionCoordinator.getContextForSession(tenantRecord, {
runInMutex: shouldUpdate ? (agentContext) => this._updateTenantStorage(tenantRecord, agentContext) : undefined,
})

this.logger.debug(`Created tenant agent context for tenant '${contextCorrelationId}'`)

if (!isTenantRecordCached) {
await cache.set(this.rootAgentContext, `contextCorrelationId-${contextCorrelationId}`, tenantRecord)
this.logger.debug(`Cached tenantRecord with id'${contextCorrelationId}'`)
}

return agentContext
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { AgentContext } from '@credo-ts/core'

import { Key } from '@credo-ts/core'
import { CacheModuleConfig, InMemoryLruCache, Key } from '@credo-ts/core'
import { container } from 'tsyringe'

import { EventEmitter } from '../../../../core/src/agent/EventEmitter'
import { getAgentConfig, getAgentContext, mockFunction } from '../../../../core/tests/helpers'
Expand Down Expand Up @@ -46,6 +47,16 @@ describe('TenantAgentContextProvider', () => {
jest.clearAllMocks()
})

beforeEach(() => {
// Re-register the instance of CacheModuleConfig with a fresh cache before each test
container.registerInstance(
CacheModuleConfig,
new CacheModuleConfig({
cache: new InMemoryLruCache({ limit: 100 }), // Fresh cache for each test
})
)
})

describe('getAgentContextForContextCorrelationId', () => {
test('retrieves the tenant and calls tenant session coordinator', async () => {
const tenantRecord = new TenantRecord({
Expand Down
Loading
Loading