Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions src/message/kafka/headers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,18 @@ export function headersFor<T>(event: CloudEventV1<T>): Headers {
const headers: Headers = {};

Object.getOwnPropertyNames(event).forEach((property) => {
// Ignore the 'data' property
// it becomes the Kafka message's 'value' field
if (property != CONSTANTS.CE_ATTRIBUTES.DATA && property != CONSTANTS.STRUCTURED_ATTRS_1.DATA_BASE64) {
const value = event[property];
// Ignore undefined properties, 'data' (mapped to message value), and
// 'datacontenttype' (mapped directly to 'content-type' per Kafka binding 3.2.1).
if (
value !== undefined &&
property !== CONSTANTS.CE_ATTRIBUTES.DATA &&
property !== CONSTANTS.STRUCTURED_ATTRS_1.DATA_BASE64 &&
property !== CONSTANTS.CE_ATTRIBUTES.CONTENT_TYPE
) {
// all CloudEvent property names get prefixed with 'ce_'
// https://github.com/cloudevents/spec/blob/v1.0.1/kafka-protocol-binding.md#3231-property-names
headers[`ce_${property}`] = event[property] as string;
headers[`ce_${property}`] = value as string;
}
});

Expand Down
52 changes: 29 additions & 23 deletions src/message/kafka/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,9 @@ function toBinaryKafkaMessage<T>(event: CloudEventV1<T>): KafkaMessage<T | undef
// 3.2.1. Content Type
// For the binary mode, the header content-type property MUST be mapped directly
// to the CloudEvents datacontenttype attribute.
const headers: Headers = {
...{ [CONSTANTS.HEADER_CONTENT_TYPE]: event.datacontenttype },
...headersFor(event)
const headers: Headers = {
...(event.datacontenttype !== undefined ? { [CONSTANTS.HEADER_CONTENT_TYPE]: event.datacontenttype } : {}),
...headersFor(event),
};
return {
headers,
Expand Down Expand Up @@ -118,21 +118,21 @@ function deserializeKafkaMessage<T>(message: Message): CloudEvent<T> | CloudEven
throw new ValidationError("No CloudEvent detected");
}
const m = message as KafkaMessage<T>;
if (!m.value) {
throw new ValidationError("Value is null or undefined");
}
if (!m.headers) {
throw new ValidationError("Headers are null or undefined");
}
const cleanHeaders: Headers = sanitize(m.headers);
const mode: Mode = getMode(cleanHeaders);
if (mode !== Mode.BINARY && (m.value === null || m.value === undefined || m.value === "")) {
throw new ValidationError("Value is null or undefined");
}
switch (mode) {
case Mode.BINARY:
return parseBinary(m);
case Mode.STRUCTURED:
return parseStructured(m as unknown as KafkaMessage<string>);
return parseStructured(m as unknown as KafkaMessage<string>, cleanHeaders);
case Mode.BATCH:
return parseBatched(m as unknown as KafkaMessage<string>);
return parseBatched(m as unknown as KafkaMessage<string>, cleanHeaders);
default:
throw new ValidationError("Unknown Message mode");
}
Expand Down Expand Up @@ -177,18 +177,19 @@ function getMode(headers: Headers): Mode {
function parseBinary<T>(message: KafkaMessage<T>): CloudEvent<T> {
const eventObj: { [key: string ]: unknown } = {};
const headers = { ...message.headers };
const cleanHeaders = sanitize(message.headers);

eventObj.datacontenttype = headers[CONSTANTS.HEADER_CONTENT_TYPE];
eventObj.datacontenttype = cleanHeaders[CONSTANTS.HEADER_CONTENT_TYPE];

for (const key in KAFKA_CE_HEADERS) {
const h = KAFKA_CE_HEADERS[key];
if (!!headers[h]) {
if (headers[h]) {
eventObj[HEADER_MAP[h]] = headers[h];
if (h === KAFKA_CE_HEADERS.TIME) {
eventObj.time = new Date(eventObj.time as string).toISOString();
}
delete headers[h];
}
delete headers[h];
}

// Any remaining headers are extension attributes
Expand All @@ -202,22 +203,24 @@ function parseBinary<T>(message: KafkaMessage<T>): CloudEvent<T> {

return new CloudEvent<T>({
...eventObj,
data: extractBinaryData(message),
data: extractBinaryData(message, cleanHeaders),
partitionkey: message.key,
}, false);
}

/**
* Parses a structured kafka CE message and returns a CloudEvent
* @param {KafkaMessage<T>} message the message
* @param {Headers} cleanHeaders lowercased headers
* @returns {CloudEvent<T>} a KafkaEvent<T>
*/
function parseStructured<T>(message: KafkaMessage<string>): CloudEvent<T> {
function parseStructured<T>(message: KafkaMessage<string>, cleanHeaders = sanitize(message.headers)): CloudEvent<T> {
// Although the format of a structured encoded event could be something
// other than JSON, e.g. XML, we currently only support JSON
// encoded structured events.
if (!message.headers[CONSTANTS.HEADER_CONTENT_TYPE]?.startsWith(CONSTANTS.MIME_CE_JSON)) {
throw new ValidationError(`Unsupported event encoding ${message.headers[CONSTANTS.HEADER_CONTENT_TYPE]}`);
const contentType = cleanHeaders[CONSTANTS.HEADER_CONTENT_TYPE];
if (!contentType?.startsWith(CONSTANTS.MIME_CE_JSON)) {
throw new ValidationError(`Unsupported event encoding ${contentType}`);
}
const eventObj = JSON.parse(message.value);
// `time` is optional, so only normalize it when the event has one.
Expand All @@ -233,14 +236,16 @@ function parseStructured<T>(message: KafkaMessage<string>): CloudEvent<T> {
/**
* Parses a batch kafka CE message and returns a CloudEvent[]
* @param {KafkaMessage<T>} message the message
* @param {Headers} cleanHeaders lowercased headers
* @returns {CloudEvent<T>[]} an array of KafkaEvent<T>
*/
function parseBatched<T>(message: KafkaMessage<string>): CloudEvent<T>[] {
function parseBatched<T>(message: KafkaMessage<string>, cleanHeaders = sanitize(message.headers)): CloudEvent<T>[] {
// Although the format of batch encoded events could be something
// other than JSON, e.g. XML, we currently only support JSON
// encoded structured events.
if (!message.headers[CONSTANTS.HEADER_CONTENT_TYPE]?.startsWith(CONSTANTS.MIME_CE_BATCH)) {
throw new ValidationError(`Unsupported event encoding ${message.headers[CONSTANTS.HEADER_CONTENT_TYPE]}`);
const contentType = cleanHeaders[CONSTANTS.HEADER_CONTENT_TYPE];
if (!contentType?.startsWith(CONSTANTS.MIME_CE_BATCH)) {
throw new ValidationError(`Unsupported event encoding ${contentType}`);
}
const events = JSON.parse(message.value) as Record<string, unknown>[];
return events.map((e) => new CloudEvent({ ...e, partitionkey: message.key }, false));
Expand All @@ -249,18 +254,19 @@ function parseBatched<T>(message: KafkaMessage<string>): CloudEvent<T>[] {
/**
* Gets the data from a binary kafka ce message as T
* @param {KafkaMessage} message a KafkaMessage
* @param {Headers} cleanHeaders lowercased headers
* @returns {string | undefined} the data in the message
*/
function extractBinaryData<T>(message: KafkaMessage<T>): T {
function extractBinaryData<T>(message: KafkaMessage<T>, cleanHeaders = sanitize(message.headers)): T {
let data = message.value as T;
// If the event data is JSON, go ahead and parse it
const datacontenttype = message.headers[CONSTANTS.HEADER_CONTENT_TYPE] as string;
const datacontenttype = cleanHeaders[CONSTANTS.HEADER_CONTENT_TYPE] as string;
if (!!datacontenttype && datacontenttype.startsWith(CONSTANTS.MIME_JSON)) {
if (typeof message.value === "string") {
if (typeof message.value === "string" && message.value.length > 0) {
data = JSON.parse(message.value);
} else if (typeof message.value === "object" && Buffer.isBuffer(message.value)) {
} else if (typeof message.value === "object" && Buffer.isBuffer(message.value) && message.value.length > 0) {
data = JSON.parse(message.value.toString());
}
}
}
return data;
}
Expand Down
85 changes: 85 additions & 0 deletions test/integration/kafka_tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -329,4 +329,89 @@ describe("Kafka transport", () => {
expect(eventDeserialized.data).to.deep.equal(dataBinary);
expect(eventDeserialized.data_base64).to.equal(data_base64);
});

it("Omits undefined headers and duplicate ce_datacontenttype in binary messages", () => {
const msgWithoutOptionals = Kafka.binary(new CloudEvent({ source, type, id }));
for (const [header, val] of Object.entries(msgWithoutOptionals.headers)) {
expect(val, `header ${header} should not be undefined`).to.not.equal(undefined);
}
expect(msgWithoutOptionals.headers).to.not.have.property("ce_datacontenttype");

const msgWithContentType = Kafka.binary(fixture);
expect(msgWithContentType.headers[CONSTANTS.HEADER_CONTENT_TYPE]).to.equal(datacontenttype);
expect(msgWithContentType.headers).to.not.have.property("ce_datacontenttype");
});

it("Round-trips binary messages with no data or falsy data", () => {
for (const dataValue of [undefined, "", 0, false]) {
const original = new CloudEvent({
source,
type,
...(dataValue !== undefined ? { data: dataValue } : {}),
});
const message = Kafka.binary(original);
const decoded = Kafka.toEvent(message) as CloudEvent<unknown>;
expect(decoded.data).to.equal(dataValue);
}
});

it("Parses structured and binary messages with mixed-case Content-Type headers", () => {
const structuredMsg: KafkaMessage<string> = {
key,
body: undefined,
value: JSON.stringify({ id, source, type, specversion: V1, data }),
headers: { "Content-Type": CONSTANTS.DEFAULT_CE_CONTENT_TYPE },
};
const structuredEvent = Kafka.toEvent(structuredMsg) as CloudEvent<Idata>;
expect(structuredEvent.id).to.equal(id);
expect(structuredEvent.data).to.deep.equal(data);

const binaryMsg: KafkaMessage<string> = {
key,
body: undefined,
value: JSON.stringify(data),
headers: {
"Content-Type": "application/json",
[KAFKA_CE_HEADERS.ID]: id,
[KAFKA_CE_HEADERS.SOURCE]: source,
[KAFKA_CE_HEADERS.TYPE]: type,
},
};
const binaryEvent = Kafka.toEvent(binaryMsg) as CloudEvent<Idata>;
expect(binaryEvent.datacontenttype).to.equal("application/json");
expect(binaryEvent.data).to.deep.equal(data);
});

it("Skips empty ce_time header and empty application/json value in binary messages", () => {
const emptyTimeMsg: KafkaMessage<string> = {
key,
body: undefined,
value: "",
headers: {
[CONSTANTS.HEADER_CONTENT_TYPE]: "application/json",
[KAFKA_CE_HEADERS.ID]: id,
[KAFKA_CE_HEADERS.SOURCE]: source,
[KAFKA_CE_HEADERS.TYPE]: type,
[KAFKA_CE_HEADERS.TIME]: "",
},
};
const decoded = Kafka.toEvent(emptyTimeMsg) as CloudEvent<string>;
expect(decoded.id).to.equal(id);
expect(decoded.data).to.equal("");
expect(decoded.time).to.be.a("string").and.not.equal("");

const emptyBufMsg: KafkaMessage<Buffer> = {
key,
body: undefined,
value: Buffer.alloc(0),
headers: {
[CONSTANTS.HEADER_CONTENT_TYPE]: "application/json",
[KAFKA_CE_HEADERS.ID]: id,
[KAFKA_CE_HEADERS.SOURCE]: source,
[KAFKA_CE_HEADERS.TYPE]: type,
},
};
const decodedBuf = Kafka.toEvent(emptyBufMsg) as CloudEvent<Buffer>;
expect(decodedBuf.data).to.deep.equal(Buffer.alloc(0));
});
});