-
Notifications
You must be signed in to change notification settings - Fork 535
/
lambda.ts
2022 lines (1804 loc) · 59.4 KB
/
lambda.ts
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
/*!
* Copyright (c) Microsoft Corporation and contributors. All rights reserved.
* Licensed under the MIT License.
*/
import {
ISequencedDocumentAugmentedMessage,
IBranchOrigin,
IClientJoin,
IDocumentSystemMessage,
ISequencedDocumentMessage,
ISequencedDocumentSystemMessage,
ITrace,
MessageType,
NackErrorType,
ScopeType,
ISignalMessage,
ISummaryAck,
ISummaryContent,
IDocumentMessage,
} from "@fluidframework/protocol-definitions";
import {
canSummarize,
defaultHash,
getNextHash,
isNetworkError,
} from "@fluidframework/server-services-client";
import {
ControlMessageType,
extractBoxcar,
IClientSequenceNumber,
IContext,
IControlMessage,
IDeliState,
IDisableNackMessagesControlMessageContents,
IMessage,
INackMessage,
ITicketedSignalMessage,
IPartitionLambda,
IProducer,
IRawOperationMessage,
ISequencedOperationMessage,
IServiceConfiguration,
NackMessagesType,
NackOperationType,
RawOperationType,
SequencedOperationType,
IQueuedMessage,
INackMessagesControlMessageContents,
IUpdateDSNControlMessageContents,
LambdaCloseType,
SignalOperationType,
ITicketedMessage,
IExtendClientControlMessageContents,
ISequencedSignalClient,
IClientManager,
ICheckpointService,
} from "@fluidframework/server-services-core";
import {
CommonProperties,
getLumberBaseProperties,
Lumber,
LumberEventName,
Lumberjack,
} from "@fluidframework/server-services-telemetry";
import { DocumentContext } from "@fluidframework/server-lambdas-driver";
import { TypedEventEmitter } from "@fluidframework/common-utils";
import { IEvent } from "../events";
import {
logCommonSessionEndMetrics,
createSessionMetric,
createRoomJoinMessage,
createRoomLeaveMessage,
CheckpointReason,
DocumentCheckpointManager,
IServerMetadata,
} from "../utils";
import { CheckpointContext } from "./checkpointContext";
import { ClientSequenceNumberManager } from "./clientSeqManager";
import { IDeliCheckpointManager, ICheckpointParams } from "./checkpointManager";
enum IncomingMessageOrder {
Duplicate,
Gap,
ConsecutiveOrSystem,
}
enum SendType {
Immediate,
Later,
Never,
}
enum InstructionType {
ClearCache,
NoOp,
}
enum TicketType {
Sequenced,
Nack,
Signal,
}
type TicketedMessageOutput =
| ISequencedDocumentMessageOutput
| INackMessageOutput
| ISignalMessageOutput;
interface IBaseTicketedMessage<T> {
ticketType: TicketType;
message: T;
instruction?: InstructionType;
}
interface ISequencedDocumentMessageOutput extends IBaseTicketedMessage<ISequencedDocumentMessage> {
ticketType: TicketType.Sequenced;
send: SendType;
type: string;
timestamp: number;
msn: number;
}
interface INackMessageOutput extends IBaseTicketedMessage<INackMessage> {
ticketType: TicketType.Nack;
}
interface ISignalMessageOutput extends IBaseTicketedMessage<ITicketedSignalMessage> {
ticketType: TicketType.Signal;
}
/**
* Used for controlling op event logic
*/
interface IOpEvent {
idleTimer?: any;
maxTimer?: any;
sequencedMessagesSinceLastOpEvent: number;
}
/**
* @internal
*/
export enum OpEventType {
/**
* There have been no sequenced ops for X milliseconds since the last message.
*/
Idle,
/**
* More than X amount of ops have been ticketed since the emit.
*/
MaxOps,
/**
* There was no previous emit for the last X milliseconds.
*/
MaxTime,
/**
* Indicates the durable sequence number was updated.
*/
UpdatedDurableSequenceNumber,
}
/**
* @internal
*/
export interface IDeliLambdaEvents extends IEvent {
/**
* Emitted when certain op event heuristics are triggered.
*/
(
event: "opEvent",
listener: (
type: OpEventType,
sequenceNumber: number,
sequencedMessagesSinceLastOpEvent: number,
) => void,
);
/**
* Emitted when the lambda is updating the durable sequence number.
* This usually occurs via a control message after a summary was created.
*/
(event: "updatedDurableSequenceNumber", listener: (durableSequenceNumber: number) => void);
/**
* Emitted when the lambda is updating a nack message
*/
(
event: "updatedNackMessages",
listener: (
type: NackMessagesType,
contents: INackMessagesControlMessageContents | undefined,
) => void,
);
/**
* Emitted when the lambda receives a summarize message.
*/
(
event: "summarizeMessage",
listener: (summarizeMessage: ISequencedDocumentAugmentedMessage) => void,
);
/**
* Emitted when the lambda receives a custom control message.
*/
(event: "controlMessage", listener: (controlMessage: IControlMessage) => void);
/**
* Emitted when the lambda is closing.
*/
(event: "close", listener: (type: LambdaCloseType) => void);
/**
* NoClient message received
*/
(event: "noClient", listener: () => void);
}
/**
* Check if the string is a service message type, which includes
* MessageType.ClientJoin, MessageType.ClientLeave, MessageType.Control,
* MessageType.NoClient, MessageType.SummaryAck, and MessageType.SummaryNack
*
* @param type - the type to check
* @returns true if it is a system message type
*/
const isServiceMessageType = (type: string): boolean =>
type === MessageType.ClientJoin ||
type === MessageType.ClientLeave ||
type === MessageType.Control ||
type === MessageType.NoClient ||
type === MessageType.SummaryAck ||
type === MessageType.SummaryNack;
/**
* @internal
*/
export class DeliLambda extends TypedEventEmitter<IDeliLambdaEvents> implements IPartitionLambda {
private sequenceNumber: number;
private signalClientConnectionNumber: number;
private durableSequenceNumber: number;
private logOffset: number;
// Client sequence number mapping
private readonly clientSeqManager = new ClientSequenceNumberManager();
private minimumSequenceNumber = 0;
private readonly checkpointContext: CheckpointContext;
private lastSendP = Promise.resolve();
private lastNoClientP = Promise.resolve();
private lastSentMSN = 0;
private lastHash: string;
private lastInstruction: InstructionType | undefined = InstructionType.NoOp;
private lastMessageType: string | undefined;
private activityIdleTimer: any;
private readClientIdleTimer: any;
private noopEvent: any;
/**
* Used for controlling op event logic
*/
private readonly opEvent: IOpEvent = { sequencedMessagesSinceLastOpEvent: 0 };
/**
* Used for controlling checkpoint logic
*/
private readonly documentCheckpointManager = new DocumentCheckpointManager();
private globalCheckpointOnly: boolean;
private readonly localCheckpointEnabled: boolean;
private recievedNoClientOp: boolean = false;
private closed: boolean = false;
// mapping of enabled nack message types. messages will be nacked based on the provided info
private readonly nackMessages: Map<NackMessagesType, INackMessagesControlMessageContents>;
// Session level properties
private serviceSummaryGenerated: boolean = false;
constructor(
private readonly context: IContext,
private readonly tenantId: string,
private readonly documentId: string,
readonly lastCheckpoint: IDeliState,
checkpointManager: IDeliCheckpointManager,
private readonly clientManager: IClientManager | undefined,
private readonly deltasProducer: IProducer,
private readonly signalsProducer: IProducer | undefined,
private readonly rawDeltasProducer: IProducer,
private readonly serviceConfiguration: IServiceConfiguration,
private sessionMetric: Lumber<LumberEventName.SessionResult> | undefined,
private readonly checkpointService: ICheckpointService | undefined,
private readonly sequencedSignalClients: Map<string, ISequencedSignalClient> = new Map(),
) {
super();
// Instantiate existing clients
if (lastCheckpoint.clients) {
for (const client of lastCheckpoint.clients) {
if (client.clientId) {
this.clientSeqManager.upsertClient(
client.clientId,
client.clientSequenceNumber,
client.referenceSequenceNumber,
client.lastUpdate,
client.canEvict,
client.scopes,
client.nack,
client.serverMetadata,
);
}
}
}
// Initialize counting context
this.sequenceNumber = lastCheckpoint.sequenceNumber;
this.signalClientConnectionNumber = lastCheckpoint.signalClientConnectionNumber ?? 0;
this.lastHash = lastCheckpoint.expHash1 ?? defaultHash;
this.durableSequenceNumber = lastCheckpoint.durableSequenceNumber;
this.lastSentMSN = lastCheckpoint.lastSentMSN ?? 0;
this.logOffset = lastCheckpoint.logOffset;
if (lastCheckpoint.nackMessages) {
if (Array.isArray(lastCheckpoint.nackMessages)) {
this.nackMessages = new Map(lastCheckpoint.nackMessages);
} else {
// backwards compat. nackMessages is a INackMessagesControlMessageContents
this.nackMessages = new Map();
// extra check for very old nack messages
const identifier = lastCheckpoint.nackMessages.identifier;
if (identifier !== undefined) {
this.nackMessages.set(identifier, lastCheckpoint.nackMessages);
}
}
} else {
this.nackMessages = new Map();
}
const msn = this.clientSeqManager.getMinimumSequenceNumber();
this.documentCheckpointManager.setNoActiveClients(msn === -1);
this.minimumSequenceNumber = this.documentCheckpointManager.getNoActiveClients()
? this.sequenceNumber
: msn;
if (this.serviceConfiguration.deli.summaryNackMessages.checkOnStartup) {
this.checkNackMessagesState();
}
this.checkpointContext = new CheckpointContext(
this.tenantId,
this.documentId,
checkpointManager,
context,
this.checkpointService,
);
this.localCheckpointEnabled = this.checkpointService?.getLocalCheckpointEnabled() ?? false;
this.globalCheckpointOnly = this.localCheckpointEnabled ? false : true;
// start the activity idle timer when created
this.setActivityIdleTimer();
this.setReadClientIdleTimer();
if (this.serviceConfiguration.deli.opEvent.enable) {
this.updateOpMaxTimeTimer();
/**
* Deli's opEvent system is supposed to tell us when it's time to post ops for the session.
* It sends an "opEvent" event based heuristics like idle / max time / max ops.
* There's an edge case though. Suppose the following:
* 1. Server A created a deli for the session, consumes 100 kafka messages, and sequences 100 ops.
* 2. Within 5 seconds of sequencing those ops,
* Server A's deli saves a checkpoint (it remembers it sequenced those 100 ops)
* 3. Within a second of that checkpoint, the Kafka partition is rebalanced.
* 4. Server B now creates a deli for that session and it consumes those same 100 kafka messages.
* 4a. Server B's deli instance is smart enough to detect that those 100 kafka messages were already
* processed (due to the checkpoint created in #2) so it ignores them (the first if statement in handler).
*
* The above flow is a problem because the opEvent logic is not going to trigger since
* no messages were sequenced by this deli.
*
* Deli should be smart and check if it hasn't yet sent an opEvent for messages that
* were not durably stored.
*/
if (this.sequenceNumber > this.durableSequenceNumber) {
/**
* This makes it so the next time deli checks for a "maxTime" opEvent,
* it will fire the event since sequencedMessagesSinceLastOpEvent \> 0.
*/
this.opEvent.sequencedMessagesSinceLastOpEvent =
this.sequenceNumber - this.durableSequenceNumber;
}
}
if (this.serviceConfiguration.deli.checkForIdleClientsOnStartup) {
/**
* Instruct deli to check for idle clients on startup. Why do we want to do this?
*
* Suppose the following:
* 1. Deli starts up and there is 1 write client and it
* consumes 1 message it has already previouly consumed.
* 2. Deli is closed due to a rebalance 2 minutes later.
* 3. Suppose that deli keeps rebalancing every 2 minutes indefinitely.
*
* Deli is configured to checkpoint 1 message behind the head while there is a client in the session.
* This will cause the kafka partition to never get a new checkpoint because it's in this bad loop.
* Never checkpointing could eventually lead to messages expiring from Kafka (data loss/corruption).
*
* We can recover from this loop if we check for idle clients on startup and insert a leave message
* for that 1 write client (who is now definitely expired). It would end up making deli checkpoint properly.
*/
this.checkIdleWriteClients(Date.now());
}
}
/**
* {@inheritDoc IPartitionLambda.handler}
*/
public handler(rawMessage: IQueuedMessage): undefined {
// In cases where we are reprocessing messages we have already checkpointed exit early
if (this.logOffset !== undefined && rawMessage.offset <= this.logOffset) {
const reprocessOpsMetric = Lumberjack.newLumberMetric(LumberEventName.ReprocessOps);
reprocessOpsMetric.setProperties({
...getLumberBaseProperties(this.documentId, this.tenantId),
[CommonProperties.isEphemeralContainer]:
this.sessionMetric?.properties.get(CommonProperties.isEphemeralContainer) ??
false,
kafkaMessageOffset: rawMessage.offset,
databaseLastOffset: this.logOffset,
});
this.documentCheckpointManager.updateCheckpointMessages(rawMessage);
try {
const currentMessage =
this.documentCheckpointManager.getCheckpointInfo()
.currentKafkaCheckpointMessage;
if (
currentMessage &&
this.serviceConfiguration.deli.kafkaCheckpointOnReprocessingOp
) {
this.context.checkpoint(
currentMessage,
this.serviceConfiguration.deli.restartOnCheckpointFailure,
);
}
reprocessOpsMetric.setProperty(
"kafkaCheckpointOnReprocessingOp",
this.serviceConfiguration.deli.kafkaCheckpointOnReprocessingOp,
);
reprocessOpsMetric.success(`Successfully reprocessed repeating ops.`);
} catch (error) {
reprocessOpsMetric.error(`Error while reprocessing ops.`, error);
}
return undefined;
} else if (this.logOffset === undefined) {
Lumberjack.error(
`No value for logOffset`,
getLumberBaseProperties(this.documentId, this.tenantId),
);
}
this.logOffset = rawMessage.offset;
let sequencedMessageCount = 0;
// array of messages that should be produced to the deltas topic after processing
const produceToDeltas: ITicketedMessage[] = [];
const boxcar = extractBoxcar(rawMessage);
for (const message of boxcar.contents) {
// Ticket current message.
const ticketedMessage = this.ticket(
message,
this.serviceConfiguration.enableTraces ? this.createTrace("start") : undefined,
);
// Return early if message is invalid
if (!ticketedMessage) {
continue;
}
this.lastInstruction = ticketedMessage.instruction;
switch (ticketedMessage.ticketType) {
case TicketType.Sequenced: {
this.lastMessageType = ticketedMessage.type;
if (ticketedMessage.type !== MessageType.ClientLeave) {
// Check for idle write clients.
this.checkIdleWriteClients(ticketedMessage.timestamp);
}
// Check for document inactivity.
if (
!(
ticketedMessage.type === MessageType.NoClient ||
ticketedMessage.type === MessageType.Control
) &&
this.documentCheckpointManager.getNoActiveClients() &&
!this.serviceConfiguration.deli.disableNoClientMessage
) {
this.lastNoClientP = this.sendToRawDeltas(
this.createOpMessage(MessageType.NoClient),
).catch((error) => {
const errorMsg = "Could not send no client message";
this.context.log?.error(`${errorMsg}: ${JSON.stringify(error)}`, {
messageMetaData: {
documentId: this.documentId,
tenantId: this.tenantId,
},
});
Lumberjack.error(
errorMsg,
getLumberBaseProperties(this.documentId, this.tenantId),
error,
);
this.context.error(error, {
restart: true,
tenantId: this.tenantId,
documentId: this.documentId,
});
});
}
// Return early if sending is not required.
if (ticketedMessage.send === SendType.Never) {
continue;
}
// Return early but start a timer to create consolidated message.
this.clearNoopConsolidationTimer();
if (ticketedMessage.send === SendType.Later) {
this.setNoopConsolidationTimer();
continue;
}
const sequencedMessage = ticketedMessage.message;
if (this.serviceConfiguration.deli.enableOpHashing) {
this.lastHash = getNextHash(sequencedMessage, this.lastHash);
sequencedMessage.expHash1 = this.lastHash;
}
if (sequencedMessage.type === MessageType.Summarize) {
// note: this is being emitted before it's produced to the deltas topic
// that lets event handlers alter the message if necessary
this.emit(
"summarizeMessage",
sequencedMessage as ISequencedDocumentAugmentedMessage,
);
}
const outgoingMessage: ISequencedOperationMessage = {
type: SequencedOperationType,
tenantId: this.tenantId,
documentId: this.documentId,
operation: sequencedMessage,
};
if (this.serviceConfiguration.deli.maintainBatches) {
produceToDeltas.push(outgoingMessage);
} else {
this.produceMessage(this.deltasProducer, outgoingMessage);
}
sequencedMessageCount++;
// Update the msn last sent
this.lastSentMSN = ticketedMessage.msn;
// create a signal for a write client if all the following are true:
// 1. a signal producer is provided
// 2. the sequenced op is a join or leave message
// 3. enableWriteClientSignals is on or alfred told us to create a signal
// #3 allows alfred to be in charge of enabling this functionality
if (
this.signalsProducer &&
(sequencedMessage.type === MessageType.ClientJoin ||
sequencedMessage.type === MessageType.ClientLeave) &&
(this.serviceConfiguration.deli.enableWriteClientSignals ||
(sequencedMessage.serverMetadata &&
typeof sequencedMessage.serverMetadata === "object" &&
(sequencedMessage.serverMetadata as IServerMetadata).createSignal))
) {
const dataContent = this.extractDataContent(
message as IRawOperationMessage,
);
const signalMessage = this.createSignalMessage(
message as IRawOperationMessage,
sequencedMessage.sequenceNumber - 1,
dataContent,
);
if (sequencedMessage.type === MessageType.ClientJoin) {
this.addSequencedSignalClient(
dataContent as IClientJoin,
signalMessage,
);
} else {
this.sequencedSignalClients.delete(dataContent);
}
this.produceMessage(this.signalsProducer, signalMessage.message);
}
break;
}
case TicketType.Nack: {
if (this.serviceConfiguration.deli.maintainBatches) {
produceToDeltas.push(ticketedMessage.message);
} else {
this.produceMessage(this.deltasProducer, ticketedMessage.message);
}
break;
}
case TicketType.Signal: {
if (this.signalsProducer) {
this.produceMessage(this.signalsProducer, ticketedMessage.message);
}
break;
}
default: {
// ignore unknown types
break;
}
}
}
if (produceToDeltas.length > 0) {
// processing this boxcar resulted in one or more ticketed messages (sequenced ops or nacks)
// produce them in a single boxcar to the deltas topic
this.produceMessages(this.deltasProducer, produceToDeltas, rawMessage);
}
this.documentCheckpointManager.incrementRawMessageCounter();
this.documentCheckpointManager.updateCheckpointMessages(rawMessage);
if (this.lastMessageType === MessageType.ClientJoin) {
this.recievedNoClientOp = false;
if (this.localCheckpointEnabled) {
this.globalCheckpointOnly = false;
}
} else if (this.lastMessageType === MessageType.NoClient) {
this.recievedNoClientOp = true;
if (this.localCheckpointEnabled) {
this.globalCheckpointOnly = true;
}
// No clients in the session, since Deli get NoClient message it sends itself, emit no client event
this.emit("noClient");
}
const checkpointReason = this.getCheckpointReason(this.lastMessageType);
if (checkpointReason === undefined) {
this.documentCheckpointManager.updateCheckpointIdleTimer(
this.serviceConfiguration.deli.checkpointHeuristics.idleTime,
this.idleTimeCheckpoint,
);
} else {
// checkpoint the current up to date state
this.checkpoint(checkpointReason, this.globalCheckpointOnly);
}
// Start a timer to check inactivity on the document. To trigger idle client leave message,
// we send a noop back to alfred. The noop should trigger a client leave message if there are any.
this.clearActivityIdleTimer();
this.setActivityIdleTimer();
if (sequencedMessageCount > 0) {
// Check if Deli is over the max ops since last summary nack limit
// Note: we are explicitly checking this after processing the entire boxcar in order to not break batches
if (
this.serviceConfiguration.deli.summaryNackMessages.enable &&
!this.nackMessages.has(NackMessagesType.SummaryMaxOps)
) {
const opsSinceLastSummary = this.sequenceNumber - this.durableSequenceNumber;
if (
opsSinceLastSummary > this.serviceConfiguration.deli.summaryNackMessages.maxOps
) {
// this op brings us over the limit
// start nacking non-system ops and ops that are submitted by non-summarizers
this.updateNackMessages(NackMessagesType.SummaryMaxOps, {
identifier: NackMessagesType.SummaryMaxOps,
content: this.serviceConfiguration.deli.summaryNackMessages.nackContent,
allowSystemMessages: true,
allowedScopes: [ScopeType.SummaryWrite],
});
}
}
// Update the op event idle & max ops counter if ops were just sequenced
if (this.serviceConfiguration.deli.opEvent.enable) {
this.updateOpIdleTimer();
const maxOps = this.serviceConfiguration.deli.opEvent.maxOps;
if (maxOps !== undefined) {
this.opEvent.sequencedMessagesSinceLastOpEvent += sequencedMessageCount;
if (this.opEvent.sequencedMessagesSinceLastOpEvent > maxOps) {
this.emitOpEvent(OpEventType.MaxOps);
}
}
}
}
}
public close(closeType: LambdaCloseType): void {
this.closed = true;
this.checkpointContext.close();
this.clearActivityIdleTimer();
this.clearReadClientIdleTimer();
this.clearNoopConsolidationTimer();
this.documentCheckpointManager.clearCheckpointIdleTimer();
this.clearOpIdleTimer();
this.clearOpMaxTimeTimer();
this.emit("close", closeType);
this.removeAllListeners();
if (this.serviceConfiguration.enableLumberjack) {
this.logSessionEndMetrics(closeType);
if (!this.recievedNoClientOp && closeType === LambdaCloseType.ActivityTimeout) {
Lumberjack.info(
`Closing due to ActivityTimeout before NoClient op`,
getLumberBaseProperties(this.documentId, this.tenantId),
);
}
}
}
private produceMessage(producer: IProducer, message: ITicketedMessage): void {
this.lastSendP = producer
.send([message], message.tenantId, message.documentId)
.catch((error) => {
if (this.closed) {
return;
}
const errorMsg = "Could not send message to producer";
this.context.log?.error(`${errorMsg}: ${JSON.stringify(error)}`, {
messageMetaData: {
documentId: this.documentId,
tenantId: this.tenantId,
},
});
Lumberjack.error(
errorMsg,
getLumberBaseProperties(this.documentId, this.tenantId),
error,
);
this.context.error(error, {
restart: true,
tenantId: this.tenantId,
documentId: this.documentId,
});
});
}
private produceMessages(
producer: IProducer,
messages: ITicketedMessage[],
rawMessage: IQueuedMessage,
): void {
this.lastSendP = producer.send(messages, this.tenantId, this.documentId).catch((error) => {
if (this.closed) {
return;
}
const errorMsg = `Could not send ${messages.length} messages to producer. offset: ${rawMessage.offset}`;
this.context.log?.error(`${errorMsg}: ${JSON.stringify(error)}`, {
messageMetaData: {
documentId: this.documentId,
tenantId: this.tenantId,
},
});
Lumberjack.error(
errorMsg,
getLumberBaseProperties(this.documentId, this.tenantId),
error,
);
let restart = true;
let markAsCorrupt = false;
if (isNetworkError(error) && error.code === 413) {
// kafka message size too large
restart = false;
markAsCorrupt = true;
}
this.context.error(error, {
restart,
markAsCorrupt: markAsCorrupt ? rawMessage : undefined,
tenantId: this.tenantId,
documentId: this.documentId,
});
});
}
private logSessionEndMetrics(closeType: LambdaCloseType): void {
if (this.sessionMetric?.isCompleted()) {
Lumberjack.info(
"Session metric already completed. Creating a new one.",
getLumberBaseProperties(this.documentId, this.tenantId),
);
const isEphemeralContainer: boolean =
this.sessionMetric?.properties.get(CommonProperties.isEphemeralContainer) ?? false;
this.sessionMetric = createSessionMetric(
this.tenantId,
this.documentId,
LumberEventName.SessionResult,
this.serviceConfiguration,
isEphemeralContainer,
);
}
this.sessionMetric?.setProperties({
[CommonProperties.serviceSummarySuccess]: this.serviceSummaryGenerated,
});
logCommonSessionEndMetrics(
this.context as DocumentContext,
closeType,
this.sessionMetric,
this.sequenceNumber,
this.durableSequenceNumber,
[...this.nackMessages.keys()],
);
}
private ticket(
rawMessage: IMessage,
trace: ITrace | undefined,
): TicketedMessageOutput | undefined {
// Exit out early for unknown messages
if (rawMessage.type !== RawOperationType) {
return undefined;
}
// Update and retrieve the minimum sequence number
const message = rawMessage as IRawOperationMessage;
const dataContent = this.extractDataContent(message);
// Check if we should nack this message
if (this.nackMessages.size > 0 && this.serviceConfiguration.deli.enableNackMessages) {
for (const nackMessageControlMessageContents of this.nackMessages.values()) {
let shouldNack = true;
if (
nackMessageControlMessageContents.allowSystemMessages &&
(isServiceMessageType(message.operation.type) || !message.clientId)
) {
// this is a system message. don't nack it
shouldNack = false;
} else if (nackMessageControlMessageContents.allowedScopes) {
const clientId = message.clientId;
if (clientId) {
const client = this.clientSeqManager.get(clientId);
if (client) {
for (const scope of nackMessageControlMessageContents.allowedScopes) {
if (client.scopes.includes(scope)) {
// this client has an allowed scope. don't nack it
shouldNack = false;
break;
}
}
}
}
}
if (shouldNack) {
return this.createNackMessage(
message,
nackMessageControlMessageContents.content.code,
nackMessageControlMessageContents.content.type,
nackMessageControlMessageContents.content.message,
nackMessageControlMessageContents.content.retryAfter,
);
}
}
}
// Check incoming message order. Nack if there is any gap so that the client can resend.
const messageOrder = this.checkOrder(message);
if (messageOrder === IncomingMessageOrder.Duplicate) {
return;
} else if (messageOrder === IncomingMessageOrder.Gap) {
return this.createNackMessage(
message,
400,
NackErrorType.BadRequestError,
`Gap detected in incoming op`,
);
}
if (this.isInvalidMessage(message)) {
return this.createNackMessage(
message,
400,
NackErrorType.BadRequestError,
`Op not allowed`,
);
}
// Handle client join/leave messages.
if (message.clientId) {
// Nack inexistent client.
const client = this.clientSeqManager.get(message.clientId);
if (!client || client.nack) {
return this.createNackMessage(
message,
400,
NackErrorType.BadRequestError,
`Nonexistent client`,
);
}
// Verify that the message is within the current window.
// -1 check just for directly sent ops (e.g., using REST API).
if (
message.clientId &&
message.operation.referenceSequenceNumber !== -1 &&
message.operation.referenceSequenceNumber < this.minimumSequenceNumber
) {
this.clientSeqManager.upsertClient(
message.clientId,
message.operation.clientSequenceNumber,
this.minimumSequenceNumber,
message.timestamp,
true,
[],
true,
);
return this.createNackMessage(
message,
400,
NackErrorType.BadRequestError,
`Refseq ${message.operation.referenceSequenceNumber} < ${this.minimumSequenceNumber}`,
);
}
// Nack if an unauthorized client tries to summarize.
if (message.operation.type === MessageType.Summarize && !canSummarize(client.scopes)) {
return this.createNackMessage(
message,
403,
NackErrorType.InvalidScopeError,
`Client ${message.clientId} does not have summary permission`,
);
}
} else {
if (message.operation.type === MessageType.ClientLeave) {
if (!this.clientSeqManager.removeClient(dataContent)) {
// not a write client. check if it was a read client
const readClient = this.sequencedSignalClients.get(dataContent);
if (readClient) {
this.sequencedSignalClients.delete(dataContent);
return this.createSignalMessage(message, this.sequenceNumber, dataContent);
}
// Return if the client has already been removed due to a prior leave message.
return;
}
if (
this.serviceConfiguration.deli.enableLeaveOpNoClientServerMetadata &&
this.clientSeqManager.count() === 0
) {
// add server metadata to indicate the last client left
message.operation.serverMetadata ??= {};
(message.operation.serverMetadata as IServerMetadata).noClient = true;
}
} else if (message.operation.type === MessageType.ClientJoin) {
const clientJoinMessage = dataContent as IClientJoin;
if (clientJoinMessage.detail.mode === "read") {
if (this.sequencedSignalClients.has(clientJoinMessage.clientId)) {
// Return if the client has already been added due to a prior join message.
return;
}
// create the signal message