-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbidService.ts
More file actions
1574 lines (1426 loc) · 45.2 KB
/
bidService.ts
File metadata and controls
1574 lines (1426 loc) · 45.2 KB
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Bid placement workflow with locking, ledger holds, and Redis caching.
import { randomUUID } from "node:crypto";
import { ObjectId, type ClientSession, type WithId } from "mongodb";
import type { ServiceDependencies } from "../../shared/service.js";
import { runMongoTransaction } from "../../shared/storage/mongoTransaction.js";
import { acquireRedisLock, releaseRedisLock, type RedisLock } from "../../shared/storage/redisLock.js";
import type { RedisClient } from "../../shared/storage/redis.js";
import { computeExpiresAt, resolveRetentionMs } from "../../shared/storage/retention.js";
import {
mongoCollections,
type AuctionDocument,
type AuctionRoundConfig,
type AuctionRoundStateDocument,
type AuctionWatchlistDocument,
type BidDocument,
type NotificationQueueDocument
} from "../../shared/storage/mongoSchemas.js";
import {
createLedgerRepository,
LedgerError,
type LedgerErrorCode,
type LedgerBalance,
type HoldOperationInput
} from "../ledger/ledgerStore.js";
import {
buildAuctionSnapshotKey,
buildAuctionUserRateLimitKey,
buildBidIdempotencyKey,
buildIpRateLimitKey,
buildRankingKey,
buildRoundStateKey,
buildTopKey,
buildUserRateLimitKey
} from "./auctionKeys.js";
import {
buildAuctionSnapshotFields,
buildRoundStateFields,
primeAuctionSnapshotCache,
primeRoundStateCache,
roundStateTtlSeconds,
snapshotTtlSeconds,
type AuctionSnapshotCache,
type RoundStateCache
} from "./auctionCache.js";
import { ensureAuctionRoundProgress } from "./auctionProgress.js";
import { createAuctionRepository } from "./auctionStore.js";
import { buildRankingMember } from "./bidRanking.js";
import { FastBidError, FastBidProcessor, type FastBidPlacement } from "./fastBidProcessor.js";
import { createRoundFinalizationService } from "./roundFinalizationService.js";
import { applyAntiSnipingExtension } from "./roundStateMachine.js";
import { publishRealtimeEvent, toRealtimeSnapshot } from "../../shared/realtime/events.js";
import { writeBalanceCache } from "../../shared/ledgerBalanceCache.js";
const bidLockTtlMs = 8000;
const topSetTtlSeconds = 10;
const bidIdempotencyTtlSeconds = 600;
const idempotencyWaitMs = 750;
const idempotencyPollMs = 50;
const bidLockWaitMs = 1500;
const bidLockPollMs = 25;
const localRateLimitMaxEntries = 10000;
const localBidLockMaxEntries = 5000;
const persistLastBidAt = readEnvBoolean("BID_PERSIST_LAST_BID_AT", true);
const persistSnapshot = readEnvBoolean("BID_PERSIST_SNAPSHOT", true);
const rateLimitScript = `
local time = redis.call("TIME")
local nowMs = (tonumber(time[1]) * 1000) + math.floor(tonumber(time[2]) / 1000)
local function consume(key, capacity, refillRate)
if not capacity or not refillRate or capacity <= 0 or refillRate <= 0 then
return 0
end
local bucket = redis.call("HMGET", key, "tokens", "ts")
local tokens = tonumber(bucket[1])
local lastMs = tonumber(bucket[2])
if not tokens then
tokens = capacity
end
if not lastMs then
lastMs = nowMs
end
if tokens > capacity then
tokens = capacity
end
if tokens < capacity then
local deltaMs = nowMs - lastMs
if deltaMs > 0 then
local refill = (deltaMs / 1000) * refillRate
tokens = math.min(capacity, tokens + refill)
end
end
local allowed = tokens >= 1
if allowed then
tokens = tokens - 1
end
redis.call("HSET", key, "tokens", tokens, "ts", nowMs)
local ttlSeconds = math.ceil((capacity / refillRate) * 2)
if ttlSeconds < 1 then
ttlSeconds = 1
end
redis.call("EXPIRE", key, ttlSeconds)
return allowed and 1 or 0
end
local userAllowed = consume(KEYS[1], tonumber(ARGV[1]), tonumber(ARGV[2]))
if userAllowed ~= 1 then
return 0
end
local auctionAllowed = consume(KEYS[2], tonumber(ARGV[3]), tonumber(ARGV[4]))
if auctionAllowed ~= 1 then
return 0
end
local ipAllowed = consume(KEYS[3], tonumber(ARGV[5]), tonumber(ARGV[6]))
if ipAllowed ~= 1 then
return 0
end
return 1
`;
const bidCacheUpdateScript = `
local rankingKey = KEYS[1]
local roundStateKey = KEYS[2]
local snapshotKey = KEYS[3]
local topKey = KEYS[4]
local idempotencyKey = KEYS[5]
local updateRanking = ARGV[1] == "1"
local bidAmount = ARGV[2]
local rankingMember = ARGV[3]
local previousMember = ARGV[4]
local roundStateTtl = tonumber(ARGV[5])
local snapshotTtl = tonumber(ARGV[6])
local idempotencyTtl = tonumber(ARGV[7])
local topSetTtl = tonumber(ARGV[8])
local topCount = tonumber(ARGV[9])
local index = 10
local roundFieldCount = tonumber(ARGV[index]) or 0
index = index + 1
local roundArgs = {}
for i = 1, roundFieldCount * 2 do
roundArgs[i] = ARGV[index]
index = index + 1
end
local snapshotFieldCount = tonumber(ARGV[index]) or 0
index = index + 1
local snapshotArgs = {}
for i = 1, snapshotFieldCount * 2 do
snapshotArgs[i] = ARGV[index]
index = index + 1
end
local idempotencyValue = ARGV[index]
if updateRanking then
redis.call("ZADD", rankingKey, bidAmount, rankingMember)
if previousMember and previousMember ~= "" then
redis.call("ZREM", rankingKey, previousMember)
end
end
if roundFieldCount > 0 then
redis.call("HSET", roundStateKey, unpack(roundArgs))
if roundStateTtl and roundStateTtl > 0 then
redis.call("EXPIRE", roundStateKey, roundStateTtl)
end
end
if snapshotFieldCount > 0 then
redis.call("HSET", snapshotKey, unpack(snapshotArgs))
if snapshotTtl and snapshotTtl > 0 then
redis.call("EXPIRE", snapshotKey, snapshotTtl)
end
end
if idempotencyTtl and idempotencyTtl > 0 then
redis.call("SET", idempotencyKey, idempotencyValue, "EX", idempotencyTtl)
else
redis.call("SET", idempotencyKey, idempotencyValue)
end
redis.call("DEL", topKey)
if topCount and topCount > 0 then
local topMembers = redis.call("ZREVRANGE", rankingKey, 0, topCount - 1)
local bidIds = {}
for i = 1, #topMembers do
local member = topMembers[i]
local sep = string.find(member, ":")
if sep then
local bidId = string.sub(member, sep + 1)
if bidId and bidId ~= "" then
table.insert(bidIds, bidId)
end
end
end
if #bidIds > 0 then
redis.call("SADD", topKey, unpack(bidIds))
if topSetTtl and topSetTtl > 0 then
redis.call("EXPIRE", topKey, topSetTtl)
end
end
end
return 1
`;
export type BidErrorCode =
| "invalid_request"
| "auction_not_found"
| "auction_not_live"
| "round_not_found"
| "round_not_live"
| "bid_too_low"
| "round_locked"
| "rate_limited"
| "idempotency_conflict";
export class BidError extends Error {
readonly code: BidErrorCode;
readonly status: number;
constructor(code: BidErrorCode, message: string, status: number) {
super(message);
this.code = code;
this.status = status;
}
}
export interface BidPlacementInput {
auctionId: ObjectId;
userId: string;
amount: number;
maxAmount?: number;
idempotencyKey: string;
audit?: BidDocument["audit"];
metadata?: Record<string, unknown>;
ip: string;
origin?: "manual" | "proxy" | "auto";
}
export interface BidPlacementResult {
bid: WithId<BidDocument>;
balance: LedgerBalance;
roundState: RoundStateView;
extended: boolean;
idempotent: boolean;
}
type BidTransactionResult = BidPlacementResult & {
auction: WithId<AuctionDocument>;
roundConfig: AuctionRoundConfig;
previousBid?: WithId<BidDocument> | null;
updateRanking: boolean;
};
type RoundStateView = {
status: AuctionRoundStateDocument["status"];
roundIndex: number;
scheduledStartAt: Date;
scheduledEndAt: Date;
effectiveEndAt: Date;
extensionCount: number;
lastBidAt?: Date | null;
startedAt?: Date | null;
closedAt?: Date | null;
};
type TopBidSnapshot = Pick<
WithId<BidDocument>,
"_id" | "userId" | "amount" | "maxAmount" | "createdAt"
>;
type ProxyCandidate = TopBidSnapshot & { maxValue: number };
type LocalRateLimitState = {
tokens: number;
lastMs: number;
expiresAt: number;
};
type LocalLockState = {
key: string;
token: string;
expiresAt: number;
};
type BidLock = { type: "redis"; lock: RedisLock } | { type: "local"; lock: LocalLockState };
export function createBidService(deps: ServiceDependencies) {
const auctionRepository = createAuctionRepository(deps.mongo);
const ledger = createLedgerRepository(deps.mongo, {
retentionDays: deps.config.dataRetention.ledgerDays,
redis: deps.redis,
logger: deps.logger
});
const bids = deps.mongo.db.collection<BidDocument>(mongoCollections.bids);
const watchlist = deps.mongo.db.collection<AuctionWatchlistDocument>(
mongoCollections.auctionWatchlist
);
const notificationQueue = deps.mongo.db.collection<NotificationQueueDocument>(
mongoCollections.notificationQueue
);
const roundStates = deps.mongo.db.collection<AuctionRoundStateDocument>(
mongoCollections.auctionRoundStates
);
const finalizationService = createRoundFinalizationService(deps);
const bidRetentionMs = resolveRetentionMs(deps.config.dataRetention.bidsDays);
const bidRetentionSeconds = toSeconds(bidRetentionMs);
const notificationRetentionMs = resolveRetentionMs(deps.config.dataRetention.notificationsDays);
const fastBidProcessor = new FastBidProcessor(deps.redis, {
balanceTtlSeconds: 3600,
activeTtlSeconds: bidRetentionSeconds,
bidRecordTtlSeconds: bidRetentionSeconds,
idempotencyTtlSeconds: 86400,
topSetTtlSeconds
});
const localRateLimits = new Map<string, LocalRateLimitState>();
const localBidLocks = new Map<string, LocalLockState>();
let rateLimitFallbackLogged = false;
let lockFallbackLogged = false;
const finalizationThrottle = new Map<string, number>();
const finalizationThrottleMs = 5000;
const warnRateLimitFallback = (error: unknown) => {
if (rateLimitFallbackLogged) {
return;
}
rateLimitFallbackLogged = true;
deps.logger.warn({ err: error }, "Redis rate limits unavailable; using local fallback");
};
const warnLockFallback = (error: unknown) => {
if (lockFallbackLogged) {
return;
}
lockFallbackLogged = true;
deps.logger.warn({ err: error }, "Redis lock unavailable; using local fallback");
};
const allowFastPath = deps.config.bids.mode !== "safe";
const shouldUseFastPath = (input: BidPlacementInput): boolean => {
if (!allowFastPath) {
return false;
}
if (deps.config.bids.proxyAutoRaise) {
return false;
}
if (input.maxAmount !== undefined) {
return false;
}
if (input.origin === "auto") {
return false;
}
return true;
};
const primeBalanceCache = async (userId: string, currency: string): Promise<void> => {
const balance = await ledger.getBalance(userId, currency);
await writeBalanceCache(deps.redis, {
...balance,
updatedAt: new Date()
});
};
const publishFastBidEvents = async (placement: FastBidPlacement): Promise<void> => {
const snapshot = placement.snapshot;
await Promise.all([
publishRealtimeEvent(deps.redis, {
type: "auction.snapshot.updated",
auctionId: snapshot.auctionId,
snapshot: toRealtimeSnapshot({ ...snapshot, serverTime: new Date() })
}),
publishRealtimeEvent(deps.redis, {
type: "auction.bids.updated",
auctionId: snapshot.auctionId
}),
publishRealtimeEvent(deps.redis, {
type: "bids.active.updated",
userIds: [placement.bid.userId]
}),
publishRealtimeEvent(deps.redis, {
type: "balance.updated",
userIds: [placement.bid.userId],
currency: placement.balance.currency
})
]);
};
const rethrowFastBidError = (error: FastBidError): never => {
if (error.kind === "ledger") {
throw new LedgerError(error.code as LedgerErrorCode, error.message, error.status);
}
throw new BidError(error.code as BidErrorCode, error.message, error.status);
};
const kickFinalizationIfNeeded = async (auctionId: ObjectId): Promise<void> => {
const auctionIdText = auctionId.toHexString();
const nowMs = Date.now();
const nextAllowed = finalizationThrottle.get(auctionIdText) ?? 0;
if (nowMs < nextAllowed) {
return;
}
finalizationThrottle.set(auctionIdText, nowMs + finalizationThrottleMs);
try {
const pending = await roundStates
.find({ auctionId, status: "closed", settlementCompletedAt: { $exists: false } })
.sort({ closedAt: 1, effectiveEndAt: 1 })
.limit(1)
.toArray();
const target = pending[0];
if (!target) {
return;
}
await finalizationService.finalizeRound(auctionId, target.roundIndex);
} catch (error) {
deps.logger.warn(
{ err: error, auctionId: auctionIdText },
"Failed to kick round finalization"
);
}
};
async function placeBid(input: BidPlacementInput): Promise<BidPlacementResult> {
if (input.origin !== "auto") {
await enforceRateLimits(
deps.redis,
deps.config.rateLimits,
input,
localRateLimits,
warnRateLimitFallback
);
}
void kickFinalizationIfNeeded(input.auctionId);
if (shouldUseFastPath(input)) {
let fastOutcome = await fastBidProcessor.placeBid(input);
if (fastOutcome.status === "fallback" && fastOutcome.reason === "balance_missing") {
try {
const auction = await auctionRepository.getAuctionById(input.auctionId);
if (auction) {
await primeBalanceCache(input.userId, auction.currency);
fastOutcome = await fastBidProcessor.placeBid(input);
}
} catch (error) {
deps.logger.warn({ err: error }, "Failed to prime balance cache for fast bid");
}
}
if (fastOutcome.status === "success") {
try {
await publishFastBidEvents(fastOutcome.value);
} catch (error) {
deps.logger.warn({ err: error }, "Failed to publish fast bid updates");
}
return {
bid: fastOutcome.value.bid,
balance: fastOutcome.value.balance,
roundState: fastOutcome.value.roundState,
extended: fastOutcome.value.extended,
idempotent: fastOutcome.value.idempotent
};
}
if (fastOutcome.status === "error") {
rethrowFastBidError(fastOutcome.error);
}
}
try {
await ensureAuctionRoundProgress(deps, auctionRepository, input.auctionId);
} catch (error) {
deps.logger.warn(
{ err: error, auctionId: input.auctionId.toHexString() },
"Failed to catch up auction rounds before bid"
);
}
let previousTop: TopBidSnapshot | null = null;
try {
previousTop = await loadTopBid(input.auctionId);
} catch (error) {
deps.logger.warn({ err: error }, "Failed to load previous top bid");
}
const existing = await resolveIdempotentBid(input);
if (existing) {
return toPlacementResult(existing);
}
const lockKey = buildBidLockKey(input.auctionId.toHexString(), input.userId);
const lock = await acquireBidLock(
deps.redis,
localBidLocks,
lockKey,
bidLockTtlMs,
bidLockWaitMs,
warnLockFallback
);
if (!lock) {
const waited = await waitForIdempotentBid(input, idempotencyWaitMs);
if (waited) {
return toPlacementResult(waited);
}
throw new BidError("round_locked", "Round is processing another bid.", 409);
}
try {
const result = await runMongoTransaction(deps.mongo, async (session) => {
const auction = await auctionRepository.getAuctionById(input.auctionId, session);
if (!auction) {
throw new BidError("auction_not_found", "Auction not found.", 404);
}
const roundState = await auctionRepository.getLiveRoundState(input.auctionId, session);
if (!roundState) {
throw new BidError("round_not_live", "No live round available.", 409);
}
const roundConfig = findRoundConfig(auction.rounds, roundState.roundIndex);
const existingBid = await bids.findOne(
{ idempotencyKey: input.idempotencyKey },
{ session }
);
if (existingBid) {
if (!matchesIdempotentBid(existingBid, input)) {
throw new BidError(
"idempotency_conflict",
"Idempotency key does not match bid payload.",
409
);
}
const resolvedRoundIndex = existingBid.roundIndex ?? roundState.roundIndex;
const resolvedRoundState =
existingBid.roundIndex !== undefined
? await auctionRepository.getRoundState(
input.auctionId,
existingBid.roundIndex,
session
)
: roundState;
if (!resolvedRoundState) {
throw new BidError("round_not_found", "Round state not found.", 404);
}
const resolvedRoundConfig = findRoundConfig(auction.rounds, resolvedRoundIndex);
const balance = await ledger.getBalanceInSession(
input.userId,
auction.currency,
session
);
return {
bid: existingBid,
balance,
roundState: resolvedRoundState,
extended: false,
idempotent: true,
auction,
roundConfig: resolvedRoundConfig,
updateRanking: existingBid.active
};
}
const now = new Date();
assertAuctionLive(auction, now);
assertRoundLive(roundState, now);
const previousBid = await bids.findOne(
{
auctionId: input.auctionId,
userId: input.userId,
active: true
},
{
session,
sort: { createdAt: -1, _id: -1 }
}
);
const minBid = normalizeNonNegative(auction.minBid);
const minIncrement = normalizeNonNegative(auction.minIncrement);
const currentTop = await loadTopBidInSession(input.auctionId, session);
const minRequired = resolveMinimumBidAmount(
minBid,
minIncrement,
currentTop?.amount ?? 0
);
if (input.amount < minRequired) {
throw new BidError("bid_too_low", "Bid must meet the minimum increment.", 409);
}
const origin = input.origin ?? (input.maxAmount !== undefined ? "proxy" : "manual");
const resolvedMaxAmount = resolveMaxAmount(input);
if (previousBid && input.amount <= previousBid.amount) {
throw new BidError("bid_too_low", "Bid must exceed the current amount.", 409);
}
if (resolvedMaxAmount < input.amount) {
throw new BidError("invalid_request", "Max amount must be >= bid amount.", 409);
}
const previousEscrow = previousBid?.maxAmount ?? previousBid?.amount ?? 0;
if (resolvedMaxAmount < previousEscrow) {
throw new BidError("bid_too_low", "Max amount cannot decrease.", 409);
}
const delta = resolvedMaxAmount - previousEscrow;
const bidId = new ObjectId();
if (previousBid) {
const inactiveUpdate: Record<string, unknown> = { active: false, inactiveAt: now };
const expiresAt = computeExpiresAt(now, bidRetentionMs);
if (expiresAt) {
inactiveUpdate.expiresAt = expiresAt;
}
await bids.updateOne(
{ _id: previousBid._id, active: true },
{ $set: inactiveUpdate },
{ session }
);
}
const bidDoc: WithId<BidDocument> = {
_id: bidId,
auctionId: input.auctionId,
userId: input.userId,
amount: input.amount,
createdAt: now,
idempotencyKey: input.idempotencyKey,
active: true,
roundIndex: roundState.roundIndex
};
if (input.audit) {
bidDoc.audit = input.audit;
}
if (input.maxAmount !== undefined) {
bidDoc.maxAmount = resolvedMaxAmount;
}
if (origin) {
bidDoc.origin = origin;
}
await bids.insertOne(bidDoc, { session });
const watchNow = now;
await watchlist.updateOne(
{ userId: input.userId, auctionId: input.auctionId },
{
$setOnInsert: { userId: input.userId, auctionId: input.auctionId, createdAt: watchNow },
$set: { updatedAt: watchNow, notifyOutbid: true }
},
{ upsert: true, session }
);
let balance: LedgerBalance;
if (delta > 0) {
const holdInput: HoldOperationInput = {
userId: input.userId,
amount: delta,
currency: auction.currency,
holdId: buildHoldId(bidId),
idempotencyKey: buildHoldIdempotencyKey(input.idempotencyKey),
metadata: buildHoldMetadata(
input.metadata,
auction._id.toHexString(),
roundState.roundIndex,
bidId.toHexString(),
input.amount,
resolvedMaxAmount,
origin
),
audit: input.audit
};
const holdResult = await ledger.createHoldInSession(holdInput, session);
balance = holdResult.balance;
} else {
balance = await ledger.getBalanceInSession(input.userId, auction.currency, session);
}
const antiSnipingPreview = applyAntiSnipingExtension(roundState, roundConfig, now);
let resolvedState = { ...roundState, ...antiSnipingPreview.state };
let extended = antiSnipingPreview.extended;
if (persistLastBidAt || antiSnipingPreview.extended) {
const persisted = await auctionRepository.applyBidAntiSniping(
auction,
roundState.roundIndex,
now,
session
);
resolvedState = persisted.state;
extended = persisted.extended;
}
const lastBidAt = resolvedState.lastBidAt ?? now;
const bidIsLatest =
!resolvedState.lastBidAt || resolvedState.lastBidAt.getTime() === now.getTime();
if (persistSnapshot || extended) {
await auctionRepository.updateAuctionSnapshot(
auction._id,
{
currentRoundIndex: resolvedState.roundIndex,
roundStatus: resolvedState.status,
roundEffectiveEndAt: resolvedState.effectiveEndAt,
roundLastBidAt: lastBidAt,
lastBidAmount: bidIsLatest ? bidDoc.amount : null
},
now,
session
);
}
return {
bid: bidDoc,
balance,
roundState: resolvedState,
extended,
idempotent: false,
auction,
roundConfig,
previousBid,
updateRanking: true
};
});
const { snapshot } = await updateRedisCaches(deps.redis, result, deps.logger);
try {
await Promise.all([
publishRealtimeEvent(deps.redis, {
type: "auction.snapshot.updated",
auctionId: snapshot.auctionId,
snapshot: toRealtimeSnapshot({ ...snapshot, serverTime: new Date() })
}),
publishRealtimeEvent(deps.redis, {
type: "auction.bids.updated",
auctionId: snapshot.auctionId
}),
publishRealtimeEvent(deps.redis, {
type: "bids.active.updated",
userIds: [result.bid.userId]
}),
publishRealtimeEvent(deps.redis, {
type: "balance.updated",
userIds: [result.bid.userId],
currency: result.auction.currency
})
]);
} catch (error) {
deps.logger.warn({ err: error }, "Failed to publish realtime bid updates");
}
let autoRaised = false;
if (deps.config.bids.proxyAutoRaise && input.origin !== "auto") {
autoRaised = await maybeApplyAutoRaise(result, input);
}
if (!autoRaised) {
try {
const currentTop = await loadTopBid(result.auction._id);
await maybeQueueOutbidNotification(previousTop, currentTop, result);
} catch (error) {
deps.logger.warn({ err: error }, "Failed to process outbid notifications");
}
}
return toPlacementResult(result);
} finally {
await releaseBidLock(deps.redis, localBidLocks, lock);
}
}
async function resolveIdempotentBid(
input: BidPlacementInput
): Promise<BidTransactionResult | null> {
const existingBid = await bids.findOne({ idempotencyKey: input.idempotencyKey });
if (!existingBid) {
return null;
}
if (!matchesIdempotentBid(existingBid, input)) {
throw new BidError(
"idempotency_conflict",
"Idempotency key does not match bid payload.",
409
);
}
const auction = await auctionRepository.getAuctionById(input.auctionId);
if (!auction) {
throw new BidError("auction_not_found", "Auction not found.", 404);
}
const roundState =
existingBid.roundIndex !== undefined
? await auctionRepository.getRoundState(input.auctionId, existingBid.roundIndex)
: await auctionRepository.getLiveRoundState(input.auctionId);
if (!roundState) {
throw new BidError("round_not_live", "No live round available.", 409);
}
const roundConfig = findRoundConfig(auction.rounds, roundState.roundIndex);
const balance = await ledger.getBalance(input.userId, auction.currency);
return {
bid: existingBid,
balance,
roundState,
extended: false,
idempotent: true,
auction,
roundConfig,
updateRanking: existingBid.active
};
}
async function waitForIdempotentBid(
input: BidPlacementInput,
timeoutMs: number
): Promise<BidTransactionResult | null> {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
const resolved = await resolveIdempotentBid(input);
if (resolved) {
return resolved;
}
await delay(idempotencyPollMs);
}
return null;
}
async function maybeApplyAutoRaise(
result: BidTransactionResult,
input: BidPlacementInput
): Promise<boolean> {
const candidates = await loadTopProxyCandidates(result.auction._id);
const target = resolveAutoRaiseTarget(
candidates,
normalizeNonNegative(result.auction.minIncrement),
input.userId
);
if (!target) {
return false;
}
try {
await placeBid({
auctionId: result.auction._id,
userId: target.userId,
amount: target.amount,
maxAmount: target.maxAmount,
idempotencyKey: buildAutoBidIdempotencyKey(
result.auction._id.toHexString(),
target.userId,
result.bid._id.toHexString()
),
audit: { source: "auto", actorId: "system" },
metadata: { autoFromBidId: result.bid._id.toHexString() },
ip: `auto:${target.userId}`,
origin: "auto"
});
return true;
} catch (error) {
deps.logger.warn({ err: error }, "Auto-raise bid failed");
return false;
}
}
async function maybeQueueOutbidNotification(
previousTop: TopBidSnapshot | null,
currentTop: TopBidSnapshot | null,
result: BidTransactionResult
): Promise<void> {
if (!previousTop || !currentTop) {
return;
}
if (previousTop.userId === currentTop.userId) {
return;
}
const watching = await watchlist.findOne({
userId: previousTop.userId,
auctionId: result.auction._id,
notifyOutbid: { $ne: false }
});
if (!watching) {
return;
}
const now = new Date();
const auctionId = result.auction._id.toHexString();
const roundIndex = result.roundState.roundIndex;
const minIncrement = normalizeNonNegative(result.auction.minIncrement);
const rebidAmount = normalizeBidAmount(
currentTop.amount + Math.max(0, minIncrement)
);
const payload: Record<string, unknown> = {
auctionId,
roundIndex,
auctionTitle: result.auction.title,
currency: result.auction.currency,
previousAmount: previousTop.amount,
currentAmount: currentTop.amount,
rebidAmount,
currentLeader: currentTop.userId,
bidId: currentTop._id.toHexString()
};
const replayUrl = buildReplayUrl(deps.config.web.publicUrl, auctionId, roundIndex);
if (replayUrl) {
payload.replayUrl = replayUrl;
}
const idempotencyKey = buildOutbidIdempotencyKey(
auctionId,
roundIndex,
previousTop.userId,
currentTop._id.toHexString()
);
const expiresAt = computeExpiresAt(now, notificationRetentionMs);
const update: Record<string, unknown> = {
type: "outbid_alert",
userId: previousTop.userId,
auctionId: result.auction._id,
roundIndex,
status: "pending",
payload,
idempotencyKey,
attempts: 0,
nextAttemptAt: now,
createdAt: now,
updatedAt: now
};
if (expiresAt) {
update.expiresAt = expiresAt;
}
await notificationQueue.updateOne(
{ idempotencyKey },
{ $setOnInsert: update },
{ upsert: true }
);
}
async function loadTopBidInSession(
auctionId: ObjectId,
session: ClientSession
): Promise<TopBidSnapshot | null> {
return bids
.find({ auctionId, active: true }, { session })
.sort({ amount: -1, createdAt: 1, _id: 1 })
.project<TopBidSnapshot>({
_id: 1,
userId: 1,
amount: 1,
maxAmount: 1,
createdAt: 1
})
.limit(1)
.next();
}
async function loadTopBid(auctionId: ObjectId): Promise<TopBidSnapshot | null> {
return bids
.find({ auctionId, active: true })
.sort({ amount: -1, createdAt: 1, _id: 1 })
.project<TopBidSnapshot>({
_id: 1,
userId: 1,
amount: 1,
maxAmount: 1,
createdAt: 1
})
.limit(1)
.next();
}
async function loadTopProxyCandidates(
auctionId: ObjectId
): Promise<ProxyCandidate[]> {
const results = await bids
.aggregate<ProxyCandidate>([
{ $match: { auctionId, active: true } },
{
$addFields: {
maxValue: { $ifNull: ["$maxAmount", "$amount"] }
}
},