Skip to content
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

add send_batch method to kafka mod #324

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
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
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 5 additions & 3 deletions crates/mod-kafka/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ version = "0.1.0"
edition = "2021"

[dependencies]
anyhow = {workspace=true}
anyhow.workspace=true
config = {path="../config"}
duration-serde = {path="../duration-serde"}
futures.workspace=true
mlua = {workspace=true, features=["vendored", "lua54", "async", "send", "serialize"]}
rdkafka = {workspace=true}
serde = {workspace=true}
rdkafka.workspace=true
serde.workspace=true
tokio.workspace=true
62 changes: 62 additions & 0 deletions crates/mod-kafka/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use config::{any_err, get_or_create_sub_module};
use futures::stream::FuturesOrdered;
use futures::StreamExt;
use mlua::prelude::LuaUserData;
use mlua::{Lua, LuaSerdeExt, UserDataMethods, Value};
use rdkafka::message::{Header, OwnedHeaders};
Expand Down Expand Up @@ -94,6 +96,66 @@ impl LuaUserData for Producer {
Ok((partition, offset))
});

methods.add_async_method("send_batch", |lua, this, values: Vec<Value>| async move {
let mut tasks = FuturesOrdered::new();
let producer = this.get_producer()?;

for value in values {
let record: Record = lua.from_value(value)?;

let headers = if record.headers.is_empty() {
None
} else {
let mut headers = OwnedHeaders::new();
for (key, v) in &record.headers {
headers = headers.insert(Header {
key,
value: Some(v),
});
}
Some(headers)
};

let producer = producer.clone();

tasks.push_back(tokio::spawn(async move {
producer
.send(
FutureRecord {
topic: &record.topic,
partition: record.partition,
payload: record.payload.as_ref(),
key: record.key.as_ref(),
headers,
timestamp: None,
},
Timeout::After(record.timeout.unwrap_or(Duration::from_secs(60))),
)
.await
}));
}

let failed_indexes = lua.create_table()?;
let errors = lua.create_table()?;
let mut index = 1;

while let Some(result) = tasks.next().await {
match result {
Ok(Ok(_)) => {}
Ok(Err((error, _msg))) => {
failed_indexes.push(index)?;
errors.push(format!("{error:#}"))?;
}
Err(error) => {
failed_indexes.push(index)?;
errors.push(format!("{error:#}"))?;
}
}
index += 1;
}
Ok((failed_indexes, errors))
});

methods.add_method("close", |_lua, this, _: ()| {
this.producer.lock().unwrap().take();
Ok(())
Expand Down
2 changes: 1 addition & 1 deletion docs/reference/kumo.kafka/_index.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Module `kumo.amqp`
# Module `kumo.kafka`

This module provides Apache Kafka client functionality.

Expand Down
37 changes: 37 additions & 0 deletions docs/reference/kumo.kafka/build_producer.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,43 @@ producer:send {
}
```

### client:send_batch({PARAMS})

{{ since('dev') }}

Sends a batch of messages. `PARAMS` is a table of object style table with the
following keys:

* `topic` - required string; the name of the queue to which to send the message
* `payload` - required string; the message to send
* `timeout` - how long to wait for a response.

The result from send_batch is a tuple of tables: local failed_items, errors = producer:send_batch(...).

```lua
local producer = kumo.kafka.build_producer {
['bootstrap.servers'] = 'localhost:9092',
}

local failed_items, errors = producer:send_batch {{
topic = 'my.topic',
payload = 'payload 1',
timeout = '1 minute',
},
{
topic = 'my.other.topic',
payload = 'payload 2',
timeout = '1 minute',
}}
if #failed_items > 0 then
-- some items failed
for i, item_idx in ipairs(failed_items) do
local error = errors[i]
print(string.format("item idx %d failed: %s", item_idx, error))
end
end
```

### client:close()

{{since('2024.09.02-c5476b89')}}
Expand Down
Loading