Skip to content
Merged
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
26 changes: 23 additions & 3 deletions src/repositories/baseOrgRepositoryHelpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const SecretariatOrgModel = require('../model/secretariatorg')
const RootOrgModel = require('../model/rootorg')
const { createOrgRelationships, ORG_RELATIONSHIP_PROJECTION } = require('./orgRelationships')
const AUDIT_METADATA_FIELDS = ['_id', '__v', '__t', 'createdAt', 'updatedAt']
const AUDIT_ORG_BATCH_SIZE = 500

// Match published response cleanup, retaining null only when it clears a value.
// This is a view/comparison copy; stored proposals must retain their original data.
Expand Down Expand Up @@ -208,15 +209,34 @@ async function createAuditLogEntry (registryOrg, originalRegistryOrgObject, requ
return createAuditLogEntries([{ before: originalRegistryOrgObject, after, preserveMetadata }], requestingUserUUID, options)
}

// DocumentDB requires each transactional find to finish in its first batch.
async function findOrgsForAudit (filter, projection, session) {
const options = {
session,
sort: { _id: 1 },
limit: AUDIT_ORG_BATCH_SIZE,
batchSize: AUDIT_ORG_BATCH_SIZE,
singleBatch: true
}
const orgs = []
let pageFilter = filter
while (true) {
const page = await BaseOrgModel.find(pageFilter, projection, options).lean()
if (!page.length) return orgs
orgs.push(...page)
// A batch can reach its byte limit before reaching the document limit.
pageFilter = { ...filter, _id: { $gt: page[page.length - 1]._id } }
}
}

// A reparenting operation changes several stored documents. Resolve its entire
// before/after graph together, never an intermediate detached relationship.
async function createAuditLogEntries (changes, requestingUserUUID, options = {}) {
if (!requestingUserUUID) return
try {
const AuditRepository = require('./auditRepository')
const auditRepo = new AuditRepository()
const readOptions = { session: options.session }
const orgs = await BaseOrgModel.find({}, ORG_RELATIONSHIP_PROJECTION, readOptions).lean()
const orgs = await findOrgsForAudit({}, { ...ORG_RELATIONSHIP_PROJECTION, _id: true }, options.session)
const beforeGraph = new Map(orgs.map(org => [org.UUID, org]))
const afterGraph = new Map(beforeGraph)
const changedUUIDs = new Set()
Expand Down Expand Up @@ -247,7 +267,7 @@ async function createAuditLogEntries (changes, requestingUserUUID, options = {})

// Fetch full documents only for organizations whose derived fields changed.
const affectedOrgs = affectedUUIDs.length
? await BaseOrgModel.find({ UUID: { $in: affectedUUIDs } }, null, readOptions).lean()
? await findOrgsForAudit({ UUID: { $in: affectedUUIDs } }, null, options.session)
: []
const snapshots = [...changes, ...affectedOrgs.map(org => ({ before: org, after: org }))]
const buildSnapshot = (org, relationships, preserveMetadata) => ({
Expand Down
8 changes: 8 additions & 0 deletions test/integration-tests/audit/registryOrgCreatesAuditTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,15 @@ describe('Create and Update Audit Collection with Org Endpoints', () => {
}
})
const before = await Promise.all(orgs.map(history))
// Force affected documents into separate batches even for this small subtree.
const find = BaseOrg.find
sinon.stub(BaseOrg, 'find').callsFake(function (filter, ...args) {
const query = find.call(this, filter, ...args)
return filter?.UUID?.$in ? query.batchSize(1) : query
})
const getMore = sinon.spy(BaseOrg.base.mongo.FindCursor.prototype, 'getMore')
await relate(orgs[1], orgs[2])
expect(getMore.callCount, 'DocumentDB forbids cursor continuation in transactions').to.equal(0)
for (let i = 0; i < 4; i++) {
const after = await expectCurrentSnapshot(orgs[i])
expect(after).to.have.lengthOf(before[i].length + 1)
Expand Down
2 changes: 1 addition & 1 deletion test/unit-tests/org/baseOrgRepositoryHelpersTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ describe('Testing BaseOrgRepository helper functions', () => {
await helpers.createAuditLogEntry(org, null, null, { session })
expect(BaseOrgModel.find.notCalled).to.equal(true)
await helpers.createAuditLogEntry(org, null, 'author-uuid', { session })
expect(BaseOrgModel.find.firstCall.args[2]).to.deep.equal({ session })
expect(BaseOrgModel.find.firstCall.args[2].session).to.equal(session)
const append = AuditRepository.prototype.appendToAuditHistoryForOrg.firstCall.args
expect(append[1].top_level_root).to.equal('root')
expect(append[3].session).to.equal(session)
Expand Down
Loading