( recipientName: string, message: Omit<TeammateMessage, 'read'>, teamName?: string, )
| 356 | * @param teamName - Optional team name |
| 357 | */ |
| 358 | export async function writeToMailbox( |
| 359 | recipientName: string, |
| 360 | message: Omit<TeammateMessage, 'read'>, |
| 361 | teamName?: string, |
| 362 | ): Promise<void> { |
| 363 | await ensureInboxDir(teamName) |
| 364 | |
| 365 | const inboxPath = getInboxPath(recipientName, teamName) |
| 366 | const lockFilePath = `${inboxPath}.lock` |
| 367 | |
| 368 | logForDebugging( |
| 369 | `[TeammateMailbox] writeToMailbox: recipient=${recipientName}, from=${message.from}, path=${inboxPath}`, |
| 370 | ) |
| 371 | |
| 372 | // Ensure the inbox file exists before locking (proper-lockfile requires the file to exist) |
| 373 | try { |
| 374 | await writeFile(inboxPath, '[]', { encoding: 'utf-8', flag: 'wx' }) |
| 375 | logForDebugging(`[TeammateMailbox] writeToMailbox: created new inbox file`) |
| 376 | } catch (error) { |
| 377 | const code = getErrnoCode(error) |
| 378 | if (code !== 'EEXIST') { |
| 379 | logForDebugging( |
| 380 | `[TeammateMailbox] writeToMailbox: failed to create inbox file: ${error}`, |
| 381 | ) |
| 382 | logError(error) |
| 383 | throw error |
| 384 | } |
| 385 | } |
| 386 | |
| 387 | let release: (() => Promise<void>) | undefined |
| 388 | try { |
| 389 | release = await lockfile.lock(inboxPath, { |
| 390 | lockfilePath: lockFilePath, |
| 391 | ...LOCK_OPTIONS, |
| 392 | }) |
| 393 | |
| 394 | // Re-read messages after acquiring lock to get the latest state |
| 395 | const messages = await readMailboxForMutation(recipientName, teamName) |
| 396 | |
| 397 | const newMessage = toMailboxMessage({ |
| 398 | ...message, |
| 399 | read: false, |
| 400 | }) |
| 401 | |
| 402 | messages.push(newMessage) |
| 403 | |
| 404 | await writeCompactedMailbox(inboxPath, messages, 'writeToMailbox') |
| 405 | logForDebugging( |
| 406 | `[TeammateMailbox] Wrote message to ${recipientName}'s inbox from ${message.from}`, |
| 407 | ) |
| 408 | } catch (error) { |
| 409 | logForDebugging(`Failed to write to inbox for ${recipientName}: ${error}`) |
| 410 | logError(error) |
| 411 | throw error |
| 412 | } finally { |
| 413 | if (release) { |
| 414 | await release() |
| 415 | } |
no test coverage detected