Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 | 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 18x 27x 75x 75x 3x 24x 37x 37x 23x 23x 19x 19x 17x 37x 37x 10x 10x 13x 11x 11x 4x 4x 7x 2x 2x 5x 5x 4x 1x 1x 14x 14x 10x 10x 10x 5x 5x 5x 8x 5x 2x 1x 1x 1x 2x 1x 1x 18x 18x 8x 8x 8x 8x 4x 4x 4x 4x 2x 2x 4x 4x 3x 3x 3x 3x 2x 1x 2x 2x 9x 9x 2x 2x 2x 3x 3x 6x 6x 6x 7x 6x 6x 3x 4x 7x | // @implements UC-SPACE-005.1, UC-SPACE-006.1, UC-SPACE-006.2
/**
* A member's membership items: their items in the flow's membership entity
* (`space.join.entityId`), found through its member field. They outlive the
* membership when a former member state is set: a member who leaves is moved
* to it, and the item is reused when they are approved again. A member who
* joins by invitation gets one too (ensureMembershipItem).
* See docs/architecture/FLOW_SPACE.md "Former members" and "Invited members".
*/
const { GetCommand, QueryCommand } = require('@aws-sdk/lib-dynamodb')
const { findMatchingItems } = require('./cascadeItemFieldValue')
const { formerMemberState } = require('./spaceJoin')
const { writeItemUpdate, finishItemUpdate } = require('../items/itemUpdate')
const {
validateMandatoryFields,
validateFieldConstraints,
validateFieldTypes
} = require('../items/field-validation')
const { createItem } = require('../items/createItem')
const { prepareNewItemData } = require('../items/newItemData')
const { scheduleWakeUpSafely } = require('./wakeUpScheduler')
const { batchWrite } = require('./batchWrite')
const { adjustCounters } = require('./referenceCounters')
/** The actor recorded for a write the system makes (same as workflow-transitions.js) */
const SYSTEM_ACTOR = 'system'
/** A write lost to a concurrent one is tried again on the fresh item, this many times */
const MAX_ATTEMPTS = 2
const lastWrite = (item) => item.updatedAt || item.createdAt || ''
/** Validates a membership item's data against the entity as it is now; first error or null */
function membershipDataError(fields, data) {
for (const check of [validateMandatoryFields, validateFieldConstraints, validateFieldTypes]) {
const result = check(fields, data)
if (!result.valid) {
return { error: result.error || 'MANDATORY_FIELD_MISSING', fieldId: result.fieldId }
}
}
return null
}
/**
* The flow's membership entity and its member field, or null when joining has
* none (or it no longer fits: deleted entity, member field gone or retyped).
*/
async function loadMembershipEntity(docClient, flow) {
const join = flow?.space?.join
if (!join?.entityId) return null
const { Item: entity } = await docClient.send(
new GetCommand({ TableName: process.env.ENTITIES_TABLE_NAME, Key: { id: join.entityId } })
)
if (!entity || entity.flowId !== flow.id) return null
const userField = (entity.fields || []).find((field) => field.fieldId === join.userFieldId)
if (userField?.type !== 'user') return null
return { join, entity, userField }
}
/**
* The user's items of the membership entity, most recently written first.
* A bounded Query of the entity's partition (as the member-removal cascade).
*/
async function findMembershipItems({ docClient, itemsTableName, entityId, userField, userId }) {
const items = await findMatchingItems({
docClient,
itemsTableName,
entityId,
field: userField,
matchValue: userId
})
return items.sort((a, b) => lastWrite(b).localeCompare(lastWrite(a)))
}
/** Moves one item to `stateId` (by the system), retrying once on the fresh item if it changed meanwhile */
async function moveItemToState({
docClient,
itemsTableName,
entity,
item,
field,
stateId,
flowId
}) {
let current = item
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
if (current[field.fieldId] === stateId) return true
const written = await writeItemUpdate({
docClient,
itemsTableName,
entityId: entity.id,
existing: current,
fields: entity.fields || [],
changes: { [field.fieldId]: stateId },
actor: SYSTEM_ACTOR,
flowId,
now: new Date().toISOString()
})
if (written.status === 'ok') {
await finishItemUpdate({
docClient,
entityId: entity.id,
existing: current,
fields: entity.fields || [],
item: written.item,
flowId
})
return true
}
if (written.status !== 'modified') {
console.error('Failed to move a membership item to another state:', {
itemId: item.id,
stateId,
status: written.status,
error: written.error
})
return false
}
const fresh = await docClient.send(
new GetCommand({ TableName: itemsTableName, Key: { entityId: entity.id, id: item.id } })
)
if (!fresh.Item) return false
current = fresh.Item
}
console.error('Membership item kept changing, not moved to another state:', {
itemId: item.id,
stateId
})
return false
}
/**
* When the flow has a former member state, moves the removed member's
* membership items to it. The system makes the move: no transition to that
* state is needed, and the automatic transitions and timers leaving it apply.
*
* @returns {Promise<{ keep: { entityId: string, fieldId: string } | null }>}
* `keep`: the member field the member-removal cascade must leave as is, so
* the items still show who they were for; null when there is no former
* member state (the field is then cleared like any other).
*/
async function markFormerMember({ docClient, itemsTableName, flow, userId }) {
const join = flow?.space?.join
if (!join?.entityId || !join.formerMemberStateId) return { keep: null }
const membership = await loadMembershipEntity(docClient, flow)
const state = membership && formerMemberState(join, membership.entity)
if (!state) return { keep: null }
const { entity, userField } = membership
const items = await findMembershipItems({
docClient,
itemsTableName,
entityId: entity.id,
userField,
userId
})
for (const item of items) {
await moveItemToState({
docClient,
itemsTableName,
entity,
item,
field: state.field,
stateId: state.stateId,
flowId: flow.id
})
}
return { keep: { entityId: entity.id, fieldId: userField.fieldId } }
}
/** Index rows and reference counters of a new item, best-effort as in items/create.js */
async function finishNewItem({ docClient, flowId, textSearchRequests, referencedEntityIds }) {
if (textSearchRequests.length > 0) {
try {
await batchWrite(docClient, process.env.FIELD_VALUE_INDEX_TABLE_NAME, textSearchRequests)
} catch (textSearchError) {
console.error('Failed to write text-search index rows:', textSearchError)
}
}
if (process.env.ENTITY_REFERENCE_COUNTERS_TABLE_NAME && referencedEntityIds.size > 0) {
await adjustCounters(
docClient,
process.env.ENTITY_REFERENCE_COUNTERS_TABLE_NAME,
flowId,
new Map([...referencedEntityIds].map((refEntityId) => [refEntityId, 1]))
)
}
}
/**
* Gives a member who joined by invitation their membership item
* (UC-SPACE-006.2), as an approved request would, but with no answers:
* - a former member's item, in the former member state, goes back to the
* workflow's start state (the other fields are kept);
* - another existing item is left as it is;
* - else a new item holding the member field only (workflow fields at their
* start state), unless the entity has another mandatory field: a flow
* member then creates it from the Members page.
* The system writes it: not charged, like the move to the former member
* state. `createdBy` is who invited the member, as the approver for a request.
*
* @returns {Promise<{ status: 'created' | 'reactivated' | 'exists' | 'skipped', itemId?: string }>}
*/
async function ensureMembershipItem({ docClient, itemsTableName, flow, userId, createdBy }) {
const membership = await loadMembershipEntity(docClient, flow)
if (!membership) return { status: 'skipped' }
const { join, entity, userField } = membership
const fields = entity.fields || []
const [existing] = await findMembershipItems({
docClient,
itemsTableName,
entityId: entity.id,
userField,
userId
})
if (existing) {
const state = formerMemberState(join, entity)
const startStateId = state?.field.workflowDefinition.startStateId
const isFormer = state && startStateId && existing[state.field.fieldId] === state.stateId
if (!isFormer) return { status: 'exists', itemId: existing.id }
const moved = await moveItemToState({
docClient,
itemsTableName,
entity,
item: existing,
field: state.field,
stateId: startStateId,
flowId: flow.id
})
return { status: moved ? 'reactivated' : 'exists', itemId: existing.id }
}
const data = { [userField.fieldId]: userField.reference?.multiple ? [userId] : userId }
if (membershipDataError(fields, data)) return { status: 'skipped' }
const now = new Date().toISOString()
const { wakeUpAt } = await prepareNewItemData({
docClient,
fields,
data,
actor: SYSTEM_ACTOR,
now,
flowId: flow.id
})
const { conflictFieldId, item, textSearchRequests, referencedEntityIds } = await createItem({
docClient,
itemsTableName,
fieldValueIndexTableName: process.env.FIELD_VALUE_INDEX_TABLE_NAME,
entityItemCountTableName: process.env.ENTITY_ITEM_COUNT_TABLE_NAME,
entityId: entity.id,
flowId: flow.id,
fields,
data,
createdBy: createdBy || SYSTEM_ACTOR,
createdAt: now
})
if (conflictFieldId) return { status: 'skipped' }
if (wakeUpAt) {
await scheduleWakeUpSafely({
entityId: entity.id,
itemId: item.id,
wakeUpAt,
docClient,
itemsTableName
})
}
await finishNewItem({ docClient, flowId: flow.id, textSearchRequests, referencedEntityIds })
return { status: 'created', itemId: item.id }
}
/**
* The most recent membership item id of each member, for the Members page
* (UC-SPACE-006.2): one paginated Query of the membership entity's partition,
* projected on the member field. Empty when the flow has no membership entity.
*
* @returns {Promise<Map<string, string> | null>} userId -> itemId; null without a membership entity
*/
async function membershipItemIdsByUser({ docClient, itemsTableName, flow }) {
const membership = await loadMembershipEntity(docClient, flow)
if (!membership) return null
const { entity, userField } = membership
const latest = new Map()
let ExclusiveStartKey
do {
const result = await docClient.send(
new QueryCommand({
TableName: itemsTableName,
KeyConditionExpression: 'entityId = :eid',
ProjectionExpression: 'id, #f, createdAt, updatedAt',
ExpressionAttributeNames: { '#f': userField.fieldId },
ExpressionAttributeValues: { ':eid': entity.id },
ExclusiveStartKey
})
)
for (const item of result.Items || []) {
const value = item[userField.fieldId]
const userIds = Array.isArray(value) ? value : [value]
for (const userId of userIds) {
if (typeof userId !== 'string') continue
const current = latest.get(userId)
if (!current || lastWrite(item) > lastWrite(current)) latest.set(userId, item)
}
}
ExclusiveStartKey = result.LastEvaluatedKey
} while (ExclusiveStartKey)
return new Map([...latest].map(([userId, item]) => [userId, item.id]))
}
module.exports = {
findMembershipItems,
markFormerMember,
ensureMembershipItem,
membershipItemIdsByUser,
membershipDataError
}
|