forked from honeycombio/examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.js
More file actions
93 lines (85 loc) · 2.65 KB
/
Copy pathhandler.js
File metadata and controls
93 lines (85 loc) · 2.65 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
'use strict';
const AWS = require('aws-sdk'); // eslint-disable-line import/no-extraneous-dependencies
const beeline = require('honeycomb-beeline')({
writeKey: process.env.HONEYCOMB_API_KEY,
dataset: process.env.HONEYCOMB_DATASET,
serviceName: 'lambda'
});
const s3 = new AWS.S3();
// Some far-in-the-future timestamp to subtract against so that we always get
// chronological order of execution timestamp -> reverse lexicographical order.
const END_TIMESTAMP = 2000000000000;
// `persist` will persist a certain text payload to S3
module.exports.persist = (event, context, callback) => {
let body = event.body || "";
// This serverless handler happens to expect to be downstream of an existing
// trace, generated by a Honeycomb Beeline.
let ctx = beeline.unmarshalTraceContext(event.headers["x-honeycomb-trace"] || "") || {};
let span = beeline.startTrace({
name: 'persist',
content_length: body.length
}, ctx.traceId, ctx.parentSpanId);
// This is a dumb way to fake flakiness in this handler, but this enables us
// to use this serverless function to simulate failures.
if (body.length > 280) {
beeline.finishTrace(span);
callback(null, {
statusCode: 413,
body: JSON.stringify({ message: "body too large" }),
});
return;
}
const key = ""+(END_TIMESTAMP - new Date().getTime());
let subSpan = beeline.startSpan({
name: 's3.putObject',
content_length: body.length
});
s3.putObject({
Body: body,
Bucket: process.env.bucket,
Key: key
}).promise().then(() => {
if (subSpan) {
beeline.finishSpan(subSpan);
}
let tagSet = [];
if (body.indexOf("#") > -1) {
tagSet.push({ Key: "hashtag", Value: "true" });
}
if (body.indexOf("@") > -1) {
tagSet.push({ Key: "username", Value: "true" });
}
if (tagSet.length) {
subSpan = beeline.startSpan({
name: 's3.putObjectTagging',
num_tags: tagSet.length,
keys: tagSet.map(t => t.Key)
});
return s3.putObjectTagging({
// Issuing a second request, because this is a contrived example
Bucket: process.env.bucket,
Key: key,
Tagging: { TagSet: tagSet }
}).promise();
}
return Promise.resolve();
}).then(() => {
if (subSpan) {
beeline.finishSpan(subSpan);
}
beeline.finishTrace(span);
callback(null, {
statusCode: 200,
body: JSON.stringify({
message: `Stored ${body.length} bytes`
}),
});
})
.catch(err => {
if (subSpan) {
beeline.finishSpan(subSpan);
}
beeline.finishTrace(span);
callback(err, { statusCode: 500, body: { message: 'Error persisting' }})
});
};