-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathindex.ts
232 lines (206 loc) · 8.64 KB
/
index.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
import { CloudEvent, CloudEventV03, CloudEventV1, CONSTANTS, Mode, Version } from "../..";
import { Message, Headers } from "..";
import { headersFor, sanitize, v03structuredParsers, v1binaryParsers, v1structuredParsers } from "./headers";
import { isStringOrObjectOrThrow, ValidationError } from "../../event/validation";
import { JSONParser, MappedParser, Parser, parserByContentType } from "../../parsers";
// implements Serializer
export function binary(event: CloudEvent): Message {
const contentType: Headers = { [CONSTANTS.HEADER_CONTENT_TYPE]: CONSTANTS.DEFAULT_CONTENT_TYPE };
const headers: Headers = { ...contentType, ...headersFor(event) };
let body = event.data;
if (typeof event.data === "object" && !(event.data instanceof Uint32Array)) {
// we'll stringify objects, but not binary data
body = JSON.stringify(event.data);
}
return {
headers,
body,
};
}
// implements Serializer
export function structured(event: CloudEvent): Message {
if (event.data_base64) {
// The event's data is binary - delete it
event = event.cloneWith({ data: undefined });
}
return {
headers: {
[CONSTANTS.HEADER_CONTENT_TYPE]: CONSTANTS.DEFAULT_CE_CONTENT_TYPE,
},
body: event.toString(),
};
}
// implements Detector
// TODO: this could probably be optimized
export function isEvent(message: Message): boolean {
try {
deserialize(message);
return true;
} catch (err) {
return false;
}
}
/**
* Converts a Message to a CloudEvent
*
* @param {Message} message the incoming message
* @return {CloudEvent} A new {CloudEvent} instance
*/
export function deserialize(message: Message): CloudEvent {
const cleanHeaders: Headers = sanitize(message.headers);
const mode: Mode = getMode(cleanHeaders);
let version = getVersion(mode, cleanHeaders, message.body);
if (version !== Version.V03 && version !== Version.V1) {
console.error(`Unknown spec version ${version}. Default to ${Version.V1}`);
version = Version.V1;
}
switch (mode) {
case Mode.BINARY:
return parseBinary(message, version);
case Mode.STRUCTURED:
return parseStructured(message, version);
default:
throw new ValidationError("Unknown Message mode");
}
}
/**
* Determines the HTTP transport mode (binary or structured) based
* on the incoming HTTP headers.
* @param {Headers} headers the incoming HTTP headers
* @returns {Mode} the transport mode
*/
function getMode(headers: Headers): Mode {
const contentType = headers[CONSTANTS.HEADER_CONTENT_TYPE];
if (contentType && contentType.startsWith(CONSTANTS.MIME_CE)) {
return Mode.STRUCTURED;
}
if (headers[CONSTANTS.CE_HEADERS.ID]) {
return Mode.BINARY;
}
throw new ValidationError("no cloud event detected");
}
/**
* Determines the version of an incoming CloudEvent based on the
* HTTP headers or HTTP body, depending on transport mode.
* @param {Mode} mode the HTTP transport mode
* @param {Headers} headers the incoming HTTP headers
* @param {Record<string, unknown>} body the HTTP request body
* @returns {Version} the CloudEvent specification version
*/
function getVersion(mode: Mode, headers: Headers, body: string | Record<string, string> | unknown) {
if (mode === Mode.BINARY) {
// Check the headers for the version
const versionHeader = headers[CONSTANTS.CE_HEADERS.SPEC_VERSION];
if (versionHeader) {
return versionHeader;
}
} else {
// structured mode - the version is in the body
return typeof body === "string" ? JSON.parse(body).specversion : (body as CloudEvent).specversion;
}
return Version.V1;
}
/**
* Parses an incoming HTTP Message, converting it to a {CloudEvent}
* instance if it conforms to the Cloud Event specification for this receiver.
*
* @param {Message} message the incoming HTTP Message
* @param {Version} version the spec version of the incoming event
* @returns {CloudEvent} an instance of CloudEvent representing the incoming request
* @throws {ValidationError} of the event does not conform to the spec
*/
function parseBinary(message: Message, version: Version): CloudEvent {
const headers = message.headers;
let body = message.body;
if (!headers) throw new ValidationError("headers is null or undefined");
if (body) {
isStringOrObjectOrThrow(body, new ValidationError("payload must be an object or a string"));
}
if (
headers[CONSTANTS.CE_HEADERS.SPEC_VERSION] &&
headers[CONSTANTS.CE_HEADERS.SPEC_VERSION] !== Version.V03 &&
headers[CONSTANTS.CE_HEADERS.SPEC_VERSION] !== Version.V1
) {
throw new ValidationError(`invalid spec version ${headers[CONSTANTS.CE_HEADERS.SPEC_VERSION]}`);
}
// Clone and low case all headers names
const sanitizedHeaders = sanitize(headers);
const eventObj: { [key: string]: unknown | string | Record<string, unknown> } = {};
const parserMap: Record<string, MappedParser> = version === Version.V1 ? v1binaryParsers : v1binaryParsers;
for (const header in parserMap) {
if (sanitizedHeaders[header]) {
const mappedParser: MappedParser = parserMap[header];
eventObj[mappedParser.name] = mappedParser.parser.parse(sanitizedHeaders[header]);
delete sanitizedHeaders[header];
}
}
// Every unprocessed header can be an extension
for (const header in sanitizedHeaders) {
if (header.startsWith(CONSTANTS.EXTENSIONS_PREFIX)) {
eventObj[header.substring(CONSTANTS.EXTENSIONS_PREFIX.length)] = headers[header];
}
}
const parser = parserByContentType[eventObj.datacontenttype as string];
if (parser && body) {
body = parser.parse(body as string);
}
// At this point, if the datacontenttype is application/json and the datacontentencoding is base64
// then the data has already been decoded as a string, then parsed as JSON. We don't need to have
// the datacontentencoding property set - in fact, it's incorrect to do so.
if (eventObj.datacontenttype === CONSTANTS.MIME_JSON && eventObj.datacontentencoding === CONSTANTS.ENCODING_BASE64) {
delete eventObj.datacontentencoding;
}
return new CloudEvent({ ...eventObj, data: body } as CloudEventV1 | CloudEventV03, false);
}
/**
* Creates a new CloudEvent instance based on the provided payload and headers.
*
* @param {Message} message the incoming Message
* @param {Version} version the spec version of this message (v1 or v03)
* @returns {CloudEvent} a new CloudEvent instance for the provided headers and payload
* @throws {ValidationError} if the payload and header combination do not conform to the spec
*/
function parseStructured(message: Message, version: Version): CloudEvent {
const payload = message.body;
const headers = message.headers;
if (!payload) throw new ValidationError("payload is null or undefined");
if (!headers) throw new ValidationError("headers is null or undefined");
isStringOrObjectOrThrow(payload, new ValidationError("payload must be an object or a string"));
if (
headers[CONSTANTS.CE_HEADERS.SPEC_VERSION] &&
headers[CONSTANTS.CE_HEADERS.SPEC_VERSION] != Version.V03 &&
headers[CONSTANTS.CE_HEADERS.SPEC_VERSION] != Version.V1
) {
throw new ValidationError(`invalid spec version ${headers[CONSTANTS.CE_HEADERS.SPEC_VERSION]}`);
}
// Clone and low case all headers names
const sanitizedHeaders = sanitize(headers);
const contentType = sanitizedHeaders[CONSTANTS.HEADER_CONTENT_TYPE];
const parser: Parser = contentType ? parserByContentType[contentType] : new JSONParser();
if (!parser) throw new ValidationError(`invalid content type ${sanitizedHeaders[CONSTANTS.HEADER_CONTENT_TYPE]}`);
const incoming = { ...(parser.parse(payload as string) as Record<string, unknown>) };
const eventObj: { [key: string]: unknown } = {};
const parserMap: Record<string, MappedParser> = version === Version.V1 ? v1structuredParsers : v03structuredParsers;
for (const key in parserMap) {
const property = incoming[key];
if (property) {
const parser: MappedParser = parserMap[key];
eventObj[parser.name] = parser.parser.parse(property as string);
}
delete incoming[key];
}
// extensions are what we have left after processing all other properties
for (const key in incoming) {
eventObj[key] = incoming[key];
}
// data_base64 is a property that only exists on V1 events. For V03 events,
// there will be a .datacontentencoding property, and the .data property
// itself will be encoded as base64
if (eventObj.data_base64 || eventObj.datacontentencoding === CONSTANTS.ENCODING_BASE64) {
const data = eventObj.data_base64 || eventObj.data;
eventObj.data = new Uint32Array(Buffer.from(data as string, "base64"));
delete eventObj.data_base64;
delete eventObj.datacontentencoding;
}
return new CloudEvent(eventObj as CloudEventV1 | CloudEventV03, false);
}