|
| 1 | +/** |
| 2 | + * Module dependencies |
| 3 | + */ |
| 4 | +import mongoose from 'mongoose'; |
| 5 | + |
| 6 | +/** |
| 7 | + * @function BillingMeterOutbox |
| 8 | + * @description Lazily resolves the BillingMeterOutbox Mongoose model. |
| 9 | + * Deferred to keep unit tests importable before model registration. |
| 10 | + * @returns {import('mongoose').Model} The registered BillingMeterOutbox model. |
| 11 | + */ |
| 12 | +// biome-ignore lint/correctness/useQwikValidLexicalScope: false positive — Node.js repository, not Qwik |
| 13 | +const BillingMeterOutbox = () => mongoose.model('BillingMeterOutbox'); |
| 14 | + |
| 15 | +/** |
| 16 | + * @function create |
| 17 | + * @description Insert a pending outbox row for a deferred extras debit. |
| 18 | + * @param {Object} payload - Outbox row fields. |
| 19 | + * @param {string} payload.organizationId - Organization ObjectId. |
| 20 | + * @param {string} payload.idempotencyKey - Usage attribution idempotency key. |
| 21 | + * @param {number} payload.extrasUnits - Extras units to debit. |
| 22 | + * @param {Object} [options={}] - Optional write options. |
| 23 | + * @param {import('mongoose').ClientSession} [options.session] - Optional Mongo session. |
| 24 | + * @returns {Promise<Object>} Inserted outbox document. |
| 25 | + */ |
| 26 | +// biome-ignore lint/correctness/useQwikValidLexicalScope: false positive — Node.js repository, not Qwik |
| 27 | +const create = async ({ organizationId, idempotencyKey, extrasUnits }, options = {}) => { |
| 28 | + const docs = await BillingMeterOutbox().create( |
| 29 | + [{ |
| 30 | + organizationId, |
| 31 | + idempotencyKey, |
| 32 | + extrasUnits, |
| 33 | + status: 'pending', |
| 34 | + }], |
| 35 | + options.session ? { session: options.session } : undefined, |
| 36 | + ); |
| 37 | + return docs[0]; |
| 38 | +}; |
| 39 | + |
| 40 | +/** |
| 41 | + * @function findPendingDue |
| 42 | + * @description Return pending outbox rows whose last attempt is due for retry. |
| 43 | + * Rows with lastAttemptedAt=null are due immediately. |
| 44 | + * @param {number} [thresholdMs=300000] - Retry backoff threshold in milliseconds. |
| 45 | + * @param {number} [limit=100] - Maximum rows to return. |
| 46 | + * @returns {Promise<Object[]>} Pending due outbox rows. |
| 47 | + */ |
| 48 | +// biome-ignore lint/correctness/useQwikValidLexicalScope: false positive — Node.js repository, not Qwik |
| 49 | +const findPendingDue = (thresholdMs = 5 * 60 * 1000, limit = 100) => { |
| 50 | + const dueBefore = new Date(Date.now() - thresholdMs); |
| 51 | + return BillingMeterOutbox() |
| 52 | + .find({ |
| 53 | + status: 'pending', |
| 54 | + $or: [ |
| 55 | + { lastAttemptedAt: null }, |
| 56 | + { lastAttemptedAt: { $lt: dueBefore } }, |
| 57 | + ], |
| 58 | + }) |
| 59 | + .sort({ lastAttemptedAt: 1, createdAt: 1 }) |
| 60 | + .limit(limit) |
| 61 | + .lean(); |
| 62 | +}; |
| 63 | + |
| 64 | +/** |
| 65 | + * @function markCommitted |
| 66 | + * @description Mark an outbox row as committed after a successful extras debit. |
| 67 | + * The `status:'pending'` filter makes this idempotent: committed or |
| 68 | + * failed rows are immutable and concurrent calls are no-ops. |
| 69 | + * @param {string} id - Outbox row id. |
| 70 | + * @returns {Promise<Object>} Mongo update result. |
| 71 | + */ |
| 72 | +// biome-ignore lint/correctness/useQwikValidLexicalScope: false positive — Node.js repository, not Qwik |
| 73 | +const markCommitted = (id) => |
| 74 | + BillingMeterOutbox().updateOne( |
| 75 | + { _id: id, status: 'pending' }, |
| 76 | + { $set: { status: 'committed', lastError: null, lastAttemptedAt: new Date() } }, |
| 77 | + ); |
| 78 | + |
| 79 | +/** |
| 80 | + * @function markFailedAttempt |
| 81 | + * @description Record a failed debit attempt. The fifth failed attempt exhausts |
| 82 | + * the row and moves it to failed status atomically. The status |
| 83 | + * transition uses `{ status: 'pending' }` as a filter on the |
| 84 | + * exhaustion update so that concurrent cron runs cannot emit |
| 85 | + * duplicate exhausted events. |
| 86 | + * @param {string} id - Outbox row id. |
| 87 | + * @param {Error|string} error - Failure to record. |
| 88 | + * @returns {Promise<Object|null>} Updated outbox row after failure accounting. |
| 89 | + */ |
| 90 | +// biome-ignore lint/correctness/useQwikValidLexicalScope: false positive — Node.js repository, not Qwik |
| 91 | +const markFailedAttempt = async (id, error) => { |
| 92 | + const message = error?.message ?? String(error); |
| 93 | + const doc = await BillingMeterOutbox().findOneAndUpdate( |
| 94 | + { _id: id, status: 'pending' }, |
| 95 | + { |
| 96 | + $inc: { attempts: 1 }, |
| 97 | + $set: { |
| 98 | + lastError: message, |
| 99 | + lastAttemptedAt: new Date(), |
| 100 | + }, |
| 101 | + }, |
| 102 | + { returnDocument: 'after' }, |
| 103 | + ).lean(); |
| 104 | + |
| 105 | + if (!doc) return null; |
| 106 | + if (doc.attempts >= 5) { |
| 107 | + // Atomic exhaustion transition: filter on status:'pending' ensures only |
| 108 | + // the first concurrent caller wins the status flip and owns the event emit. |
| 109 | + return BillingMeterOutbox().findOneAndUpdate( |
| 110 | + { _id: id, status: 'pending' }, |
| 111 | + { $set: { status: 'failed' } }, |
| 112 | + { returnDocument: 'after' }, |
| 113 | + ).lean(); |
| 114 | + } |
| 115 | + return doc; |
| 116 | +}; |
| 117 | + |
| 118 | +export default { |
| 119 | + create, |
| 120 | + findPendingDue, |
| 121 | + markCommitted, |
| 122 | + markFailedAttempt, |
| 123 | +}; |
0 commit comments