-
Notifications
You must be signed in to change notification settings - Fork 24
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
KafkaProducer: Expose run()
method
#63
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
@@ -29,7 +29,7 @@ struct NoDelegate: NIOAsyncSequenceProducerDelegate { | |||||||||||||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
/// `AsyncSequence` implementation for handling messages acknowledged by the Kafka cluster (``KafkaAcknowledgedMessage``). | ||||||||||||||||||||||||||||||||||||||||||
public struct AcknowledgedMessagesAsyncSequence: AsyncSequence { | ||||||||||||||||||||||||||||||||||||||||||
public struct KafkaMessageAcknowledgements: AsyncSequence { | ||||||||||||||||||||||||||||||||||||||||||
public typealias Element = Result<KafkaAcknowledgedMessage, KafkaAcknowledgedMessageError> | ||||||||||||||||||||||||||||||||||||||||||
typealias WrappedSequence = NIOAsyncSequenceProducer<Element, NoBackPressure, NoDelegate> | ||||||||||||||||||||||||||||||||||||||||||
let wrappedSequence: WrappedSequence | ||||||||||||||||||||||||||||||||||||||||||
|
@@ -77,65 +77,104 @@ public actor KafkaProducer { | |||||||||||||||||||||||||||||||||||||||||
/// Dictionary containing all topic names with their respective `rd_kafka_topic_t` pointer. | ||||||||||||||||||||||||||||||||||||||||||
private var topicHandles: [String: OpaquePointer] | ||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
// We use implicitly unwrapped optionals here as these properties need to access self upon initialization | ||||||||||||||||||||||||||||||||||||||||||
/// Used for handling the connection to the Kafka cluster. | ||||||||||||||||||||||||||||||||||||||||||
private var client: KafkaClient! | ||||||||||||||||||||||||||||||||||||||||||
/// Task that polls the Kafka cluster for updates periodically. | ||||||||||||||||||||||||||||||||||||||||||
private var pollTask: Task<Void, Never>! | ||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
/// `AsyncSequence` that returns all ``KafkaProducerMessage`` objects that have been | ||||||||||||||||||||||||||||||||||||||||||
/// acknowledged by the Kafka cluster. | ||||||||||||||||||||||||||||||||||||||||||
public nonisolated let acknowledgements: AcknowledgedMessagesAsyncSequence | ||||||||||||||||||||||||||||||||||||||||||
nonisolated let acknowlegdementsSource: AcknowledgedMessagesAsyncSequence.WrappedSequence.Source | ||||||||||||||||||||||||||||||||||||||||||
private typealias Acknowledgement = Result<KafkaAcknowledgedMessage, KafkaAcknowledgedMessageError> | ||||||||||||||||||||||||||||||||||||||||||
private let client: KafkaClient | ||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
// Private initializer, use factory methods to create KafkaProducer | ||||||||||||||||||||||||||||||||||||||||||
/// Initialize a new ``KafkaProducer``. | ||||||||||||||||||||||||||||||||||||||||||
/// - Parameter config: The ``KafkaProducerConfig`` for configuring the ``KafkaProducer``. | ||||||||||||||||||||||||||||||||||||||||||
/// - Parameter topicConfig: The ``KafkaTopicConfig`` used for newly created topics. | ||||||||||||||||||||||||||||||||||||||||||
/// - Parameter logger: A logger. | ||||||||||||||||||||||||||||||||||||||||||
/// - Throws: A ``KafkaError`` if the received message is an error message or malformed. | ||||||||||||||||||||||||||||||||||||||||||
public init( | ||||||||||||||||||||||||||||||||||||||||||
config: KafkaProducerConfig = KafkaProducerConfig(), | ||||||||||||||||||||||||||||||||||||||||||
topicConfig: KafkaTopicConfig = KafkaTopicConfig(), | ||||||||||||||||||||||||||||||||||||||||||
/// - Throws: A ``KafkaError`` if initializing the producer failed. | ||||||||||||||||||||||||||||||||||||||||||
private init( | ||||||||||||||||||||||||||||||||||||||||||
client: KafkaClient, | ||||||||||||||||||||||||||||||||||||||||||
topicConfig: KafkaTopicConfig, | ||||||||||||||||||||||||||||||||||||||||||
logger: Logger | ||||||||||||||||||||||||||||||||||||||||||
) async throws { | ||||||||||||||||||||||||||||||||||||||||||
self.client = client | ||||||||||||||||||||||||||||||||||||||||||
self.topicConfig = topicConfig | ||||||||||||||||||||||||||||||||||||||||||
self.logger = logger | ||||||||||||||||||||||||||||||||||||||||||
self.topicHandles = [:] | ||||||||||||||||||||||||||||||||||||||||||
self.logger = logger | ||||||||||||||||||||||||||||||||||||||||||
self.state = .started | ||||||||||||||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
/// Initialize a new ``KafkaProducer`` that ignores incoming message acknowledgements. | ||||||||||||||||||||||||||||||||||||||||||
/// - Parameter config: The ``KafkaProducerConfig`` for configuring the ``KafkaProducer``. | ||||||||||||||||||||||||||||||||||||||||||
/// - Parameter topicConfig: The ``KafkaTopicConfig`` used for newly created topics. | ||||||||||||||||||||||||||||||||||||||||||
/// - Parameter logger: A logger. | ||||||||||||||||||||||||||||||||||||||||||
/// - Returns: The newly created ``KafkaProducer``. | ||||||||||||||||||||||||||||||||||||||||||
/// - Throws: A ``KafkaError`` if initializing the producer failed. | ||||||||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
Can we also create a radar to rename the config structs to spell out configuration. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||||||||||||||||||||||||||||||||||||||||||
public static func newProducer( | ||||||||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||||||||||||||||||||||||||||||||||
config: KafkaProducerConfig = KafkaProducerConfig(), | ||||||||||||||||||||||||||||||||||||||||||
topicConfig: KafkaTopicConfig = KafkaTopicConfig(), | ||||||||||||||||||||||||||||||||||||||||||
logger: Logger | ||||||||||||||||||||||||||||||||||||||||||
) async throws -> KafkaProducer { | ||||||||||||||||||||||||||||||||||||||||||
let client = try RDKafka.createClient( | ||||||||||||||||||||||||||||||||||||||||||
type: .producer, | ||||||||||||||||||||||||||||||||||||||||||
configDictionary: config.dictionary, | ||||||||||||||||||||||||||||||||||||||||||
// Having no callback will discard any incoming acknowlegement messages | ||||||||||||||||||||||||||||||||||||||||||
// Ref: rdkafka_broker.c:rd_kafka_dr_msgq | ||||||||||||||||||||||||||||||||||||||||||
callback: nil, | ||||||||||||||||||||||||||||||||||||||||||
logger: logger | ||||||||||||||||||||||||||||||||||||||||||
) | ||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
let producer = try await KafkaProducer( | ||||||||||||||||||||||||||||||||||||||||||
client: client, | ||||||||||||||||||||||||||||||||||||||||||
topicConfig: topicConfig, | ||||||||||||||||||||||||||||||||||||||||||
logger: logger | ||||||||||||||||||||||||||||||||||||||||||
) | ||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
return producer | ||||||||||||||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
/// Initialize a new ``KafkaProducer`` alongside a ``KafkaMessageAcknowledgements`` `AsyncSequence` that can be used | ||||||||||||||||||||||||||||||||||||||||||
/// to receive message acknowlegements. | ||||||||||||||||||||||||||||||||||||||||||
/// - Parameter config: The ``KafkaProducerConfig`` for configuring the ``KafkaProducer``. | ||||||||||||||||||||||||||||||||||||||||||
/// - Parameter topicConfig: The ``KafkaTopicConfig`` used for newly created topics. | ||||||||||||||||||||||||||||||||||||||||||
/// - Parameter logger: A logger. | ||||||||||||||||||||||||||||||||||||||||||
/// - Returns: A tuple containing the created ``KafkaProducer`` and the ``KafkaMessageAcknowledgements`` | ||||||||||||||||||||||||||||||||||||||||||
/// `AsyncSequence` used for receiving message acknowledgements. | ||||||||||||||||||||||||||||||||||||||||||
/// - Throws: A ``KafkaError`` if initializing the producer failed. | ||||||||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||||||||||||||||||||||||||||||||||
public static func newProducerWithAcknowledgements( | ||||||||||||||||||||||||||||||||||||||||||
config: KafkaProducerConfig = KafkaProducerConfig(), | ||||||||||||||||||||||||||||||||||||||||||
topicConfig: KafkaTopicConfig = KafkaTopicConfig(), | ||||||||||||||||||||||||||||||||||||||||||
logger: Logger | ||||||||||||||||||||||||||||||||||||||||||
) async throws -> (KafkaProducer, KafkaMessageAcknowledgements) { | ||||||||||||||||||||||||||||||||||||||||||
// (NIOAsyncSequenceProducer.makeSequence Documentation Excerpt) | ||||||||||||||||||||||||||||||||||||||||||
// This method returns a struct containing a NIOAsyncSequenceProducer.Source and a NIOAsyncSequenceProducer. | ||||||||||||||||||||||||||||||||||||||||||
// The source MUST be held by the caller and used to signal new elements or finish. | ||||||||||||||||||||||||||||||||||||||||||
// The sequence MUST be passed to the actual consumer and MUST NOT be held by the caller. | ||||||||||||||||||||||||||||||||||||||||||
// This is due to the fact that deiniting the sequence is used as part of a trigger to | ||||||||||||||||||||||||||||||||||||||||||
// terminate the underlying source. | ||||||||||||||||||||||||||||||||||||||||||
let acknowledgementsSourceAndSequence = NIOAsyncSequenceProducer.makeSequence( | ||||||||||||||||||||||||||||||||||||||||||
elementType: Acknowledgement.self, | ||||||||||||||||||||||||||||||||||||||||||
let sourceAndSequence = NIOAsyncSequenceProducer.makeSequence( | ||||||||||||||||||||||||||||||||||||||||||
elementType: Result<KafkaAcknowledgedMessage, KafkaAcknowledgedMessageError>.self, | ||||||||||||||||||||||||||||||||||||||||||
backPressureStrategy: NoBackPressure(), | ||||||||||||||||||||||||||||||||||||||||||
delegate: NoDelegate() | ||||||||||||||||||||||||||||||||||||||||||
) | ||||||||||||||||||||||||||||||||||||||||||
self.acknowlegdementsSource = acknowledgementsSourceAndSequence.source | ||||||||||||||||||||||||||||||||||||||||||
self.acknowledgements = AcknowledgedMessagesAsyncSequence( | ||||||||||||||||||||||||||||||||||||||||||
wrappedSequence: acknowledgementsSourceAndSequence.sequence | ||||||||||||||||||||||||||||||||||||||||||
) | ||||||||||||||||||||||||||||||||||||||||||
let source = sourceAndSequence.source | ||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
self.client = try RDKafka.createClient( | ||||||||||||||||||||||||||||||||||||||||||
let client = try RDKafka.createClient( | ||||||||||||||||||||||||||||||||||||||||||
type: .producer, | ||||||||||||||||||||||||||||||||||||||||||
configDictionary: config.dictionary, | ||||||||||||||||||||||||||||||||||||||||||
callback: self.deliveryReportCallback, | ||||||||||||||||||||||||||||||||||||||||||
logger: self.logger | ||||||||||||||||||||||||||||||||||||||||||
callback: { [logger, source] messageResult in | ||||||||||||||||||||||||||||||||||||||||||
guard let messageResult else { | ||||||||||||||||||||||||||||||||||||||||||
logger.error("Could not resolve acknowledged message") | ||||||||||||||||||||||||||||||||||||||||||
return | ||||||||||||||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
_ = source.yield(messageResult) // Ignore YieldResult | ||||||||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Let's add why we ignore this result i.e. due to no back pressure support. |
||||||||||||||||||||||||||||||||||||||||||
}, | ||||||||||||||||||||||||||||||||||||||||||
logger: logger | ||||||||||||||||||||||||||||||||||||||||||
) | ||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
// Poll Kafka every millisecond | ||||||||||||||||||||||||||||||||||||||||||
self.pollTask = Task { [client] in | ||||||||||||||||||||||||||||||||||||||||||
while !Task.isCancelled { | ||||||||||||||||||||||||||||||||||||||||||
client?.withKafkaHandlePointer { handle in | ||||||||||||||||||||||||||||||||||||||||||
rd_kafka_poll(handle, 0) | ||||||||||||||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||||||||||||||
try? await Task.sleep(nanoseconds: 1_000_000) | ||||||||||||||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||||||||||||||
let producer = try await KafkaProducer( | ||||||||||||||||||||||||||||||||||||||||||
client: client, | ||||||||||||||||||||||||||||||||||||||||||
topicConfig: topicConfig, | ||||||||||||||||||||||||||||||||||||||||||
logger: logger | ||||||||||||||||||||||||||||||||||||||||||
) | ||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
let acknowlegementsSequence = KafkaMessageAcknowledgements(wrappedSequence: sourceAndSequence.sequence) | ||||||||||||||||||||||||||||||||||||||||||
return (producer, acknowlegementsSequence) | ||||||||||||||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
/// Method to shutdown the ``KafkaProducer``. | ||||||||||||||||||||||||||||||||||||||||||
|
@@ -155,7 +194,7 @@ public actor KafkaProducer { | |||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
private func _shutDownGracefully(timeout: Int32) async { | ||||||||||||||||||||||||||||||||||||||||||
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in | ||||||||||||||||||||||||||||||||||||||||||
// Wait 10 seconds for outstanding messages to be sent and callbacks to be called | ||||||||||||||||||||||||||||||||||||||||||
// Wait `timeout` seconds for outstanding messages to be sent and callbacks to be called | ||||||||||||||||||||||||||||||||||||||||||
self.client.withKafkaHandlePointer { handle in | ||||||||||||||||||||||||||||||||||||||||||
rd_kafka_flush(handle, timeout) | ||||||||||||||||||||||||||||||||||||||||||
continuation.resume() | ||||||||||||||||||||||||||||||||||||||||||
|
@@ -165,11 +204,24 @@ public actor KafkaProducer { | |||||||||||||||||||||||||||||||||||||||||
for (_, topicHandle) in self.topicHandles { | ||||||||||||||||||||||||||||||||||||||||||
rd_kafka_topic_destroy(topicHandle) | ||||||||||||||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||||||||||||||
self.pollTask.cancel() | ||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
self.state = .shutDown | ||||||||||||||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
/// Start polling Kafka for acknowledged messages. | ||||||||||||||||||||||||||||||||||||||||||
/// | ||||||||||||||||||||||||||||||||||||||||||
/// - Parameter pollInterval: The desired time interval between two consecutive polls. | ||||||||||||||||||||||||||||||||||||||||||
/// - Returns: An awaitable task representing the execution of the poll loop. | ||||||||||||||||||||||||||||||||||||||||||
public func run(pollInterval: Duration = .milliseconds(100)) async throws { | ||||||||||||||||||||||||||||||||||||||||||
// TODO(felix): make pollInterval part of config -> easier to adapt to Service protocol (service-lifecycle) | ||||||||||||||||||||||||||||||||||||||||||
while self.state == .started { | ||||||||||||||||||||||||||||||||||||||||||
self.client.withKafkaHandlePointer { handle in | ||||||||||||||||||||||||||||||||||||||||||
rd_kafka_poll(handle, 0) | ||||||||||||||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can we make this a method on the |
||||||||||||||||||||||||||||||||||||||||||
try await Task.sleep(for: pollInterval) | ||||||||||||||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
/// Send messages to the Kafka cluster asynchronously, aka "fire and forget". | ||||||||||||||||||||||||||||||||||||||||||
/// This function is non-blocking. | ||||||||||||||||||||||||||||||||||||||||||
/// - Parameter message: The ``KafkaProducerMessage`` that is sent to the KafkaCluster. | ||||||||||||||||||||||||||||||||||||||||||
|
@@ -220,29 +272,6 @@ public actor KafkaProducer { | |||||||||||||||||||||||||||||||||||||||||
return self.messageIDCounter | ||||||||||||||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
// Closure that is executed when a message has been acknowledged by Kafka | ||||||||||||||||||||||||||||||||||||||||||
private lazy var deliveryReportCallback: (UnsafePointer<rd_kafka_message_t>?) -> Void = { [logger, acknowlegdementsSource] messagePointer in | ||||||||||||||||||||||||||||||||||||||||||
guard let messagePointer = messagePointer else { | ||||||||||||||||||||||||||||||||||||||||||
logger.error("Could not resolve acknowledged message") | ||||||||||||||||||||||||||||||||||||||||||
return | ||||||||||||||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
let messageID = UInt(bitPattern: messagePointer.pointee._private) | ||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
do { | ||||||||||||||||||||||||||||||||||||||||||
let message = try KafkaAcknowledgedMessage(messagePointer: messagePointer, id: messageID) | ||||||||||||||||||||||||||||||||||||||||||
_ = acknowlegdementsSource.yield(.success(message)) | ||||||||||||||||||||||||||||||||||||||||||
} catch { | ||||||||||||||||||||||||||||||||||||||||||
guard let error = error as? KafkaAcknowledgedMessageError else { | ||||||||||||||||||||||||||||||||||||||||||
fatalError("Caught error that is not of type \(KafkaAcknowledgedMessageError.self)") | ||||||||||||||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||||||||||||||
_ = acknowlegdementsSource.yield(.failure(error)) | ||||||||||||||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
// The messagePointer is automatically destroyed by librdkafka | ||||||||||||||||||||||||||||||||||||||||||
// For safety reasons, we only use it inside of this closure | ||||||||||||||||||||||||||||||||||||||||||
} | ||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||
/// Check `topicHandles` for a handle matching the topic name and create a new handle if needed. | ||||||||||||||||||||||||||||||||||||||||||
/// - Parameter topic: The name of the topic that is addressed. | ||||||||||||||||||||||||||||||||||||||||||
private func createTopicHandleIfNeeded(topic: String) throws -> OpaquePointer? { | ||||||||||||||||||||||||||||||||||||||||||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we create a ticket to try to internalise all of the properties here into our state where it makes sense
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
#64