-
Notifications
You must be signed in to change notification settings - Fork 535
/
lambdaFactory.ts
426 lines (396 loc) · 14.2 KB
/
lambdaFactory.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
/*!
* Copyright (c) Microsoft Corporation and contributors. All rights reserved.
* Licensed under the MIT License.
*/
import { EventEmitter } from "events";
import { inspect } from "util";
import { toUtf8 } from "@fluidframework/common-utils";
import {
ICheckpointService,
IClientManager,
IContext,
IClusterDrainingChecker,
IDeliState,
IDocument,
IDocumentRepository,
ILogger,
IPartitionLambda,
IPartitionLambdaConfig,
IPartitionLambdaFactory,
IProducer,
IServiceConfiguration,
ITenantManager,
LambdaCloseType,
MongoManager,
requestWithRetry,
} from "@fluidframework/server-services-core";
import { defaultHash, IGitManager } from "@fluidframework/server-services-client";
import {
Lumber,
LumberEventName,
Lumberjack,
getLumberBaseProperties,
} from "@fluidframework/server-services-telemetry";
import { NoOpLambda, createSessionMetric, isDocumentValid, isDocumentSessionValid } from "../utils";
import { DeliLambda } from "./lambda";
import { createDeliCheckpointManagerFromCollection } from "./checkpointManager";
const getDefaultCheckpoint = (): IDeliState => {
return {
clients: undefined,
durableSequenceNumber: 0,
expHash1: defaultHash,
logOffset: -1,
sequenceNumber: 0,
signalClientConnectionNumber: 0,
lastSentMSN: 0,
nackMessages: undefined,
checkpointTimestamp: Date.now(),
};
};
/**
* @internal
*/
export class DeliLambdaFactory
extends EventEmitter
implements IPartitionLambdaFactory<IPartitionLambdaConfig>
{
constructor(
private readonly operationsDbMongoManager: MongoManager,
private readonly documentRepository: IDocumentRepository,
private readonly checkpointService: ICheckpointService,
private readonly tenantManager: ITenantManager,
private readonly clientManager: IClientManager | undefined,
private readonly forwardProducer: IProducer,
private readonly signalProducer: IProducer | undefined,
private readonly reverseProducer: IProducer,
private readonly serviceConfiguration: IServiceConfiguration,
private readonly clusterDrainingChecker?: IClusterDrainingChecker | undefined,
) {
super();
}
public async create(
config: IPartitionLambdaConfig,
context: IContext,
updateActivityTime?: (activityTime?: number) => void,
): Promise<IPartitionLambda> {
const { documentId, tenantId } = config;
let sessionMetric: Lumber<LumberEventName.SessionResult> | undefined;
const messageMetaData = {
documentId,
tenantId,
};
let gitManager: IGitManager;
let document: IDocument | undefined;
try {
// Lookup the last sequence number stored
// TODO - is this storage specific to the orderer in place? Or can I generalize the output context?
document =
(await this.documentRepository.readOne({ documentId, tenantId })) ?? undefined;
// Check if the document was deleted prior.
if (document === undefined || !isDocumentValid(document)) {
// (Old, from tanviraumi:) Temporary guard against failure until we figure out what causing this to trigger.
// Document sessions can be joined (via Alfred) after a document is functionally deleted.
const errorMessage = `Received attempt to connect to a missing/deleted document.`;
context.log?.error(errorMessage, { messageMetaData });
Lumberjack.error(errorMessage, getLumberBaseProperties(documentId, tenantId));
return new NoOpLambda(context);
}
if (!isDocumentSessionValid(document, this.serviceConfiguration)) {
// Session for this document is either nonexistent or exists in a different location.
const errMsg = `Received attempt to connect to invalid session: ${JSON.stringify(
document.session,
)}`;
context.log?.error(errMsg, { messageMetaData });
Lumberjack.error(errMsg, getLumberBaseProperties(documentId, tenantId));
if (this.serviceConfiguration.enforceDiscoveryFlow) {
// This can/will prevent any users from creating a valid session in this location
// for the liftime of this NoOpLambda. This is not ideal; however, throwing an error
// to prevent lambda creation would mark the document as corrupted, which is worse.
return new NoOpLambda(context);
}
}
sessionMetric = createSessionMetric(
tenantId,
documentId,
LumberEventName.SessionResult,
this.serviceConfiguration,
document?.isEphemeralContainer,
);
gitManager = await this.tenantManager.getTenantGitManager(tenantId, documentId);
} catch (error) {
const errMsg = "Deli lambda creation failed";
context.log?.error(`${errMsg}. Exception: ${inspect(error)}`, { messageMetaData });
Lumberjack.error(errMsg, getLumberBaseProperties(documentId, tenantId), error);
this.logSessionFailureMetrics(sessionMetric, errMsg);
throw error;
}
let lastCheckpoint;
// Restore deli state if not present in the cache. Mongodb casts undefined as null so we are checking
// both to be safe. Empty sring denotes a cache that was cleared due to a service summary or the document
// was created within a different tenant.
if (document.deli === undefined || document.deli === null) {
const message = "New document. Setting empty deli checkpoint";
context.log?.info(message, { messageMetaData });
Lumberjack.info(message, getLumberBaseProperties(documentId, tenantId));
lastCheckpoint = getDefaultCheckpoint();
} else {
if (document.deli === "") {
const docExistsMessge = "Existing document. Fetching checkpoint from summary";
context.log?.info(docExistsMessge, { messageMetaData });
Lumberjack.info(docExistsMessge, getLumberBaseProperties(documentId, tenantId));
const lastCheckpointFromSummary = await this.loadStateFromSummary(
tenantId,
documentId,
gitManager,
context.log,
);
if (lastCheckpointFromSummary === undefined) {
const errMsg = "Could not load state from summary";
context.log?.error(errMsg, { messageMetaData });
Lumberjack.error(errMsg, getLumberBaseProperties(documentId, tenantId));
this.logSessionFailureMetrics(sessionMetric, errMsg);
lastCheckpoint = getDefaultCheckpoint();
} else {
lastCheckpoint = lastCheckpointFromSummary;
// Since the document was originated elsewhere or cache was cleared, logOffset info is irrelavant.
// Currently the lambda checkpoints only after updating the logOffset so setting this to lower
// is okay. Conceptually this is similar to default checkpoint where logOffset is -1. In this case,
// the sequence number is 'n' rather than '0'.
lastCheckpoint.logOffset = -1;
const message = `Deli checkpoint from summary: ${JSON.stringify(
lastCheckpoint,
)}`;
context.log?.info(message, { messageMetaData });
Lumberjack.info(message, getLumberBaseProperties(documentId, tenantId));
}
} else {
lastCheckpoint = await this.checkpointService.restoreFromCheckpoint(
documentId,
tenantId,
"deli",
document,
);
}
}
// Add checkpointTimestamp as UTC now if checkpoint doesn't have a timestamp yet.
if (
lastCheckpoint.checkpointTimestamp === undefined ||
lastCheckpoint.checkpointTimestamp === null
) {
lastCheckpoint.checkpointTimestamp = Date.now();
}
const checkpointManager = createDeliCheckpointManagerFromCollection(
tenantId,
documentId,
this.checkpointService,
);
const deliLambda = new DeliLambda(
context,
tenantId,
documentId,
lastCheckpoint,
checkpointManager,
this.clientManager,
// The producer as well it shouldn't take. Maybe it just gives an output stream?
this.forwardProducer,
this.signalProducer,
this.reverseProducer,
this.serviceConfiguration,
sessionMetric,
this.checkpointService,
);
deliLambda.on("close", (closeType) => {
const baseLumberjackProperties = getLumberBaseProperties(documentId, tenantId);
const handler = async (): Promise<void> => {
if (
closeType === LambdaCloseType.ActivityTimeout ||
closeType === LambdaCloseType.Error
) {
if (document?.isEphemeralContainer) {
if (this.serviceConfiguration.deli.enableEphemeralContainerSummaryCleanup) {
// Call to historian to delete summaries
await requestWithRetry(
async () => gitManager.deleteSummary(false),
"deliLambda_onClose" /* callName */,
baseLumberjackProperties /* telemetryProperties */,
(error) => true /* shouldRetry */,
3 /* maxRetries */,
);
}
// Delete the document metadata, soft or hard depending on the configuration
const deletionFilter = {
documentId,
tenantId,
};
if (
this.serviceConfiguration.deli.ephemeralContainerSoftDeleteTimeInMs >= 0
) {
const scheduledDeletionTimeStr = new Date(
Date.now() +
this.serviceConfiguration.deli
.ephemeralContainerSoftDeleteTimeInMs,
).toJSON();
await this.documentRepository.updateOne(
deletionFilter,
{ scheduledDeletionTime: scheduledDeletionTimeStr },
null,
);
Lumberjack.info(
`Successfully scheduled to clean up ephemeral container`,
{
...baseLumberjackProperties,
scheduledDeletionTime: scheduledDeletionTimeStr,
},
);
} else {
await this.documentRepository.deleteOne(deletionFilter);
Lumberjack.info(
`Successfully cleaned up ephemeral container`,
baseLumberjackProperties,
);
}
return;
}
const filter = { documentId, tenantId, session: { $exists: true } };
const keepSessionActive = this.checkpointService.getGlobalCheckpointFailed();
const data = {
"session.isSessionAlive": false,
"session.isSessionActive": keepSessionActive,
"lastAccessTime": Date.now(),
};
// Set skip session stickiness to be true if cluster is in draining
if (this.clusterDrainingChecker) {
try {
const isClusterDraining =
await this.clusterDrainingChecker.isClusterDraining();
if (isClusterDraining) {
Lumberjack.info(
"Cluster is in draining, set skip session stickiness to be true",
);
// Skip session stickiness if cluster is in draining
data["session.ignoreSessionStickiness"] = true;
}
} catch (error) {
Lumberjack.error(
"Failed to get cluster draining status",
baseLumberjackProperties,
error,
);
}
}
await this.documentRepository.updateOne(filter, data, undefined);
const message = `Marked session alive as false and active as ${keepSessionActive} for closeType:
${JSON.stringify(closeType)}`;
context.log?.info(message, { messageMetaData });
Lumberjack.info(message, baseLumberjackProperties);
}
};
handler().catch((error) => {
const message = `Failed to handle session alive and active with exception ${error}`;
context.log?.error(message, { messageMetaData });
Lumberjack.error(message, baseLumberjackProperties, error);
});
});
deliLambda.on("noClient", () => {
const baseLumberjackProperties = getLumberBaseProperties(documentId, tenantId);
const handler = async (): Promise<void> => {
// Set activity timer to reduce session grace period for ephemeral containers if cluster is in draining
if (document?.isEphemeralContainer && this.clusterDrainingChecker) {
const isClusterDraining = await this.clusterDrainingChecker.isClusterDraining();
if (isClusterDraining) {
Lumberjack.info(
"Cluster is under draining and NoClient event is received",
baseLumberjackProperties,
);
if (updateActivityTime) {
// Set session activity time to be 2 minutes later.
// It means this labmda will be closed in about 2 minutes
updateActivityTime(Date.now() + 2 * 60 * 1000);
}
}
}
};
handler().catch((error) => {
Lumberjack.error(
"Failed to handle NoClient event.",
baseLumberjackProperties,
error,
);
});
});
// Fire-and-forget sessionAlive and sessionActive update for session-boot performance.
// Worst case is that document is allowed to be deleted while active.
context.log?.info(`Deli Lambda is marking session as alive and active as true.`, {
messageMetaData,
});
this.documentRepository
.updateOne(
{ tenantId, documentId },
{
"session.isSessionAlive": true,
"session.isSessionActive": true,
},
)
.catch((error) => {
const errMsg = "Deli Lambda failed to mark session as active.";
context.log?.error(`${errMsg} Exception: ${inspect(error)}`, { messageMetaData });
Lumberjack.error(`${errMsg}`, getLumberBaseProperties(documentId, tenantId), error);
});
return deliLambda;
}
private logSessionFailureMetrics(
sessionMetric: Lumber<LumberEventName.SessionResult> | undefined,
errMsg: string,
): void {
sessionMetric?.error(errMsg);
}
public async dispose(): Promise<void> {
// Emit this event to close the broadcasterLambda and publisher
this.emit("dispose");
const mongoClosedP = this.operationsDbMongoManager.close();
const forwardProducerClosedP = this.forwardProducer.close();
const signalProducerClosedP = this.signalProducer?.close();
const reverseProducerClosedP = this.reverseProducer.close();
await Promise.all([
mongoClosedP,
forwardProducerClosedP,
signalProducerClosedP,
reverseProducerClosedP,
]);
}
// Fetches last durable deli state from summary. Returns undefined if not present.
private async loadStateFromSummary(
tenantId: string,
documentId: string,
gitManager: IGitManager,
logger: ILogger | undefined,
): Promise<IDeliState | undefined> {
const existingRef = await gitManager.getRef(encodeURIComponent(documentId));
if (existingRef) {
try {
const content = await gitManager.getContent(
existingRef.object.sha,
".serviceProtocol/deli",
);
const summaryCheckpoint = JSON.parse(
toUtf8(content.content, content.encoding),
) as IDeliState;
return summaryCheckpoint;
} catch (error) {
const messageMetaData = {
documentId,
tenantId,
};
const errorMessage = `Error fetching deli state from summary`;
logger?.error(errorMessage, { messageMetaData });
logger?.error(JSON.stringify(error), { messageMetaData });
Lumberjack.error(
errorMessage,
getLumberBaseProperties(documentId, tenantId),
error,
);
return undefined;
}
}
}
}