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 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 | 10x 10x 10x 10x 10x 10x 10x 6x 28x 41x 1x 1x 5x 5x 11x 1x 10x 10x 8x 2x 7x 8x 8x 8x 2x 5x 4x 6x 6x 3x 4x 4x 3x 3x 2x 3x 3x 2x 1x 2x 2x 24x 21x 19x 13x 10x 3x 1x 5x 5x 6x 6x 1x 5x 4x 4x 1x 3x 1x 66x 66x 67x 67x 5x 67x 66x 33x 33x 10x | const {
QueryCommand,
GetCommand,
BatchGetCommand,
UpdateCommand,
TransactWriteCommand
} = require('@aws-sdk/lib-dynamodb')
const { MAX_DAILY_MESSAGE_REQUESTS } = require('./constants')
const { batchDelete } = require('./batchWrite')
/**
* Direct Message rules (docs/architecture/requirements/messages.req.md).
*
* Anyone can write to anyone, except when the recipient's `dmPolicy` says
* otherwise or either user blocked the other. Whether a new conversation goes
* straight to the recipient's inbox or waits in their Requests tab depends on
* whether the recipient is *connected* with the sender: the recipient follows
* the sender, or they share a flow.
*
* A conversation's `status` is 'accepted' (absent on conversations created
* before message requests existed), 'pending' (a request not answered yet) or
* 'declined'. A request's `requesterId` can send exactly one message
* (`requestSentAt` marks it sent) until the other participant accepts.
*/
const DM_POLICIES = ['everyone', 'connections', 'nobody']
const DEFAULT_DM_POLICY = 'everyone'
// DynamoDB BatchGetItem accepts at most 100 keys per table per request.
const BATCH_GET_LIMIT = 100
const MAX_BATCH_GET_ATTEMPTS = 5
function buildParticipantsKey(userIdA, userIdB) {
return [userIdA, userIdB].sort().join('#')
}
/** The user's "who can message me" setting, defaulting to everyone. */
function getDmPolicy(user) {
return DM_POLICIES.includes(user?.dmPolicy) ? user.dmPolicy : DEFAULT_DM_POLICY
}
function conversationStatus(conversation) {
return conversation?.status || 'accepted'
}
/**
* Whether `userId` blocked `otherUserId` and/or the other way around — the
* two directions are reported apart because only the blocker is told about a
* block (UC-DM-009.1 AC-4).
*/
async function getBlockState(docClient, blocksTableName, userId, otherUserId) {
const [byUser, byOther] = await Promise.all([
docClient.send(
new GetCommand({
TableName: blocksTableName,
Key: { blockerId: userId, blockedId: otherUserId }
})
),
docClient.send(
new GetCommand({
TableName: blocksTableName,
Key: { blockerId: otherUserId, blockedId: userId }
})
)
])
return { blockedByUser: !!byUser.Item, blockedByOther: !!byOther.Item }
}
/** Whether `userId` is a member of at least one of `flowIds` (≤ 100). */
async function isMemberOfAny(docClient, membershipsTableName, userId, flowIds) {
let keys = flowIds.map((flowId) => ({ userId, flowId }))
for (let attempt = 0; keys.length > 0; attempt++) {
if (attempt === MAX_BATCH_GET_ATTEMPTS) {
throw new Error('FlowMemberships BatchGet kept returning unprocessed keys')
}
const result = await docClient.send(
new BatchGetCommand({
RequestItems: {
[membershipsTableName]: { Keys: keys, ProjectionExpression: 'flowId' }
}
})
)
if ((result.Responses?.[membershipsTableName] || []).length > 0) return true
keys = result.UnprocessedKeys?.[membershipsTableName]?.Keys || []
}
return false
}
/**
* Whether the two users share a flow. Walks `iteratedUserId`'s memberships a
* page of 100 at a time and probes `probedUserId`'s membership of each page
* with one BatchGet, stopping at the first hit — so the cost grows with the
* iterated user's flow count only. Callers iterate the *sender's* flows, so a
* user in many flows only makes their own requests slower.
*/
async function sharesFlow(docClient, membershipsTableName, iteratedUserId, probedUserId) {
let exclusiveStartKey
do {
const page = await docClient.send(
new QueryCommand({
TableName: membershipsTableName,
KeyConditionExpression: 'userId = :userId',
ExpressionAttributeValues: { ':userId': iteratedUserId },
ProjectionExpression: 'flowId',
Limit: BATCH_GET_LIMIT,
ExclusiveStartKey: exclusiveStartKey
})
)
const flowIds = (page.Items || []).map((item) => item.flowId)
if (
flowIds.length > 0 &&
(await isMemberOfAny(docClient, membershipsTableName, probedUserId, flowIds))
) {
return true
}
exclusiveStartKey = page.LastEvaluatedKey
} while (exclusiveStartKey)
return false
}
/**
* Whether `otherUserId` is one of `userId`'s connections: `userId` follows
* them, or they share a flow.
*
* @param {{ userFollowsTableName: string, flowMembershipsTableName: string }} tables
*/
async function isConnected(docClient, tables, userId, otherUserId) {
const follow = await docClient.send(
new GetCommand({
TableName: tables.userFollowsTableName,
Key: { followerId: userId, followeeId: otherUserId }
})
)
if (follow.Item) return true
return sharesFlow(docClient, tables.flowMembershipsTableName, otherUserId, userId)
}
/**
* Whether `senderId` may start a new conversation with `recipient` (their
* UsersTable row), given the recipient's `dmPolicy`, and if so whether it
* goes straight to the recipient's inbox (`direct`) or is a request. Blocks
* are not checked here: see getBlockState.
*/
async function evaluateNewConversation(docClient, tables, senderId, recipient) {
const policy = getDmPolicy(recipient)
if (policy === 'nobody') return { allowed: false, direct: false }
const connected = await isConnected(docClient, tables, recipient.id, senderId)
if (policy === 'connections' && !connected) return { allowed: false, direct: false }
return { allowed: true, direct: connected }
}
/**
* Whether `senderId` may start a new conversation with `recipient`, without
* working out whether it would be direct — which only the "my connections"
* setting needs, so the default setting costs no lookup at all.
*/
async function canStartConversation(docClient, tables, senderId, recipient) {
const policy = getDmPolicy(recipient)
if (policy === 'everyone') return true
if (policy === 'nobody') return false
return isConnected(docClient, tables, recipient.id, senderId)
}
/** The conversation between the two users, if any, via `participantsKeyIndex`. */
async function findConversation(docClient, conversationsTableName, userIdA, userIdB) {
const result = await docClient.send(
new QueryCommand({
TableName: conversationsTableName,
IndexName: 'participantsKeyIndex',
KeyConditionExpression: 'participantsKey = :participantsKey',
ExpressionAttributeValues: { ':participantsKey': buildParticipantsKey(userIdA, userIdB) },
Limit: 1
})
)
return result.Items?.[0] || null
}
/**
* What `callerId` can do in `conversation` right now:
* - 'ok': send freely
* - 'request_first_message': send the one message of their request
* - 'awaiting_acceptance': their request is sent, nothing more until accepted
* (also after a decline, which the requester is never told about)
* - 'request_received': answer the other participant's request first
* - 'blocked_by_you' / 'unavailable': a block applies, by the caller or by
* the other participant — the latter is not told apart from other refusals
*/
function describeSendState(conversation, callerId, blockState) {
if (blockState.blockedByUser) return 'blocked_by_you'
if (blockState.blockedByOther) return 'unavailable'
if (conversationStatus(conversation) === 'accepted') return 'ok'
if (conversation.requesterId === callerId) {
return conversation.requestSentAt ? 'awaiting_acceptance' : 'request_first_message'
}
return 'request_received'
}
/**
* Accepts a pending or declined request on behalf of its recipient: the
* conversation and both inbox rows become 'accepted', and the recipient's row
* moves from the Requests tab (`requestedAt`) to the top of the Inbox
* (`lastMessageAt`). Throws a TransactionCanceledException when the
* conversation is no longer a request to `accepterId`.
*
* @param {{ conversationsTableName: string, participantsTableName: string }} tables
*/
async function acceptConversation(docClient, tables, conversation, accepterId, now) {
await docClient.send(
new TransactWriteCommand({
TransactItems: [
{
Update: {
TableName: tables.conversationsTableName,
Key: { id: conversation.id },
UpdateExpression: 'SET #status = :accepted, acceptedAt = :now',
ConditionExpression: '#status IN (:pending, :declined) AND requesterId <> :accepterId',
ExpressionAttributeNames: { '#status': 'status' },
ExpressionAttributeValues: {
':accepted': 'accepted',
':now': now,
':pending': 'pending',
':declined': 'declined',
':accepterId': accepterId
}
}
},
{
Update: {
TableName: tables.participantsTableName,
Key: { userId: accepterId, conversationId: conversation.id },
UpdateExpression: 'SET #status = :accepted, lastMessageAt = :now REMOVE requestedAt',
ConditionExpression: 'attribute_exists(userId)',
ExpressionAttributeNames: { '#status': 'status' },
ExpressionAttributeValues: { ':accepted': 'accepted', ':now': now }
}
},
{
Update: {
TableName: tables.participantsTableName,
Key: { userId: conversation.requesterId, conversationId: conversation.id },
UpdateExpression: 'SET #status = :accepted',
ConditionExpression: 'attribute_exists(userId)',
ExpressionAttributeNames: { '#status': 'status' },
ExpressionAttributeValues: { ':accepted': 'accepted' }
}
}
]
})
)
}
/**
* Counts one message request against `userId`'s daily quota
* (MAX_DAILY_MESSAGE_REQUESTS per UTC day, kept on their UsersTable row as
* `dmRequestDay`/`dmRequestCount`). Returns false, counting nothing, when the
* quota is used up.
*/
async function consumeRequestQuota(docClient, usersTableName, userId, now) {
const day = now.slice(0, 10)
// Two rounds: a concurrent request can start the day between our
// "same day" and "new day" attempts, making the second one fail too.
for (let round = 0; round < 2; round++) {
try {
await docClient.send(
new UpdateCommand({
TableName: usersTableName,
Key: { id: userId },
UpdateExpression: 'SET dmRequestCount = dmRequestCount + :one',
ConditionExpression: 'dmRequestDay = :day AND dmRequestCount < :max',
ExpressionAttributeValues: { ':one': 1, ':day': day, ':max': MAX_DAILY_MESSAGE_REQUESTS }
})
)
return true
} catch (error) {
if (error.name !== 'ConditionalCheckFailedException') throw error
}
try {
await docClient.send(
new UpdateCommand({
TableName: usersTableName,
Key: { id: userId },
UpdateExpression: 'SET dmRequestDay = :day, dmRequestCount = :one',
ConditionExpression:
'attribute_exists(id) AND (attribute_not_exists(dmRequestDay) OR dmRequestDay <> :day)',
ExpressionAttributeValues: { ':one': 1, ':day': day }
})
)
return true
} catch (error) {
if (error.name !== 'ConditionalCheckFailedException') throw error
}
}
return false
}
/** Every page of a Query's items, keys only. */
async function queryAllKeys(docClient, params) {
const keys = []
let exclusiveStartKey
do {
const page = await docClient.send(
new QueryCommand({ ...params, ExclusiveStartKey: exclusiveStartKey })
)
keys.push(
...(page.Items || []).map((row) => ({ blockerId: row.blockerId, blockedId: row.blockedId }))
)
exclusiveStartKey = page.LastEvaluatedKey
} while (exclusiveStartKey)
return keys
}
/**
* Deletes every block involving a user whose account is being deleted, in
* both directions: the blocks they placed, and other users' blocks of them
* (via `blockedIndex`).
*/
async function deleteAllBlocksForUser(docClient, blocksTableName, userId) {
const [placed, received] = await Promise.all([
queryAllKeys(docClient, {
TableName: blocksTableName,
KeyConditionExpression: 'blockerId = :userId',
ExpressionAttributeValues: { ':userId': userId }
}),
queryAllKeys(docClient, {
TableName: blocksTableName,
IndexName: 'blockedIndex',
KeyConditionExpression: 'blockedId = :userId',
ExpressionAttributeValues: { ':userId': userId }
})
])
await batchDelete(docClient, blocksTableName, [...placed, ...received])
}
module.exports = {
DM_POLICIES,
DEFAULT_DM_POLICY,
buildParticipantsKey,
getDmPolicy,
conversationStatus,
getBlockState,
sharesFlow,
isConnected,
evaluateNewConversation,
canStartConversation,
findConversation,
describeSendState,
acceptConversation,
consumeRequestQuota,
deleteAllBlocksForUser
}
|