Skip to content

Commit 9abe64b

Browse files
authored
refactor(metactl): extract Lua runtime setup to dedicated module (#18439)
Move Lua gRPC client functionality from main.rs to a new lua_support module in databend-common-meta-control. This improves code organization by separating Lua runtime concerns from the main binary logic. Changes: - Create src/meta/control/src/lua_support.rs with LuaGrpcClient and setup functions - Update main.rs to use lua_support::setup_lua_environment() - Add mlua and meta-kvapi dependencies to control library - Remove duplicate Lua implementation code from main.rs This refactoring makes the Lua functionality more maintainable and reusable across the codebase while preserving all existing behavior.
1 parent e9a8870 commit 9abe64b

File tree

5 files changed

+119
-82
lines changed

5 files changed

+119
-82
lines changed

โ€ŽCargo.lock

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

โ€Žsrc/meta/binaries/metactl/main.rs

Lines changed: 4 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ use std::collections::BTreeMap;
1818
use std::io::Read;
1919
use std::io::{self};
2020
use std::sync::Arc;
21-
use std::time::Duration;
2221

2322
use clap::CommandFactory;
2423
use clap::Parser;
@@ -44,6 +43,7 @@ use databend_common_meta_control::args::WatchArgs;
4443
use databend_common_meta_control::export_from_disk;
4544
use databend_common_meta_control::export_from_grpc;
4645
use databend_common_meta_control::import;
46+
use databend_common_meta_control::lua_support;
4747
use databend_common_meta_kvapi::kvapi::KVApi;
4848
use databend_common_meta_types::protobuf::WatchRequest;
4949
use databend_common_meta_types::UpsertKV;
@@ -54,10 +54,6 @@ use databend_meta::version::METASRV_COMMIT_VERSION;
5454
use display_more::DisplayOptionExt;
5555
use futures::stream::TryStreamExt;
5656
use mlua::Lua;
57-
use mlua::LuaSerdeExt;
58-
use mlua::UserData;
59-
use mlua::UserDataMethods;
60-
use mlua::Value;
6157
use serde::Deserialize;
6258

6359
#[derive(Debug, Deserialize, Parser)]
@@ -237,33 +233,8 @@ impl App {
237233
async fn run_lua(&self, args: &LuaArgs) -> anyhow::Result<()> {
238234
let lua = Lua::new();
239235

240-
// Register new_grpc_client function
241-
let new_grpc_client = lua
242-
.create_function(|_lua, address: String| {
243-
let client = MetaGrpcClient::try_create(
244-
vec![address],
245-
"root",
246-
"xxx",
247-
Some(Duration::from_secs(2)),
248-
Some(Duration::from_secs(1)),
249-
None,
250-
)
251-
.map_err(|e| {
252-
mlua::Error::external(format!("Failed to create gRPC client: {}", e))
253-
})?;
254-
255-
Ok(LuaGrpcClient::new(client))
256-
})
257-
.map_err(|e| anyhow::anyhow!("Failed to create new_grpc_client function: {}", e))?;
258-
259-
lua.globals()
260-
.set("new_grpc_client", new_grpc_client)
261-
.map_err(|e| anyhow::anyhow!("Failed to register new_grpc_client: {}", e))?;
262-
263-
// Export NULL constant to Lua environment
264-
lua.globals()
265-
.set("NULL", Value::NULL)
266-
.map_err(|e| anyhow::anyhow!("Failed to register NULL constant: {}", e))?;
236+
// Setup Lua environment with gRPC client support
237+
lua_support::setup_lua_environment(&lua)?;
267238

268239
let script = match &args.file {
269240
Some(path) => std::fs::read_to_string(path)?,
@@ -281,56 +252,7 @@ impl App {
281252
}
282253

283254
fn new_grpc_client(&self, addresses: Vec<String>) -> Result<Arc<ClientHandle>, CreationError> {
284-
eprintln!(
285-
"Using gRPC API address: {}",
286-
serde_json::to_string(&addresses).unwrap()
287-
);
288-
MetaGrpcClient::try_create(
289-
addresses,
290-
"root",
291-
"xxx",
292-
Some(Duration::from_secs(2)),
293-
Some(Duration::from_secs(1)),
294-
None,
295-
)
296-
}
297-
}
298-
299-
struct LuaGrpcClient {
300-
client: Arc<ClientHandle>,
301-
}
302-
303-
impl LuaGrpcClient {
304-
fn new(client: Arc<ClientHandle>) -> Self {
305-
Self { client }
306-
}
307-
}
308-
309-
impl UserData for LuaGrpcClient {
310-
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
311-
methods.add_async_method("get", |lua, this, key: String| async move {
312-
match this.client.get_kv(&key).await {
313-
Ok(result) => match lua.to_value(&result) {
314-
Ok(lua_value) => Ok((Some(lua_value), None::<String>)),
315-
Err(e) => Ok((None::<Value>, Some(format!("Lua conversion error: {}", e)))),
316-
},
317-
Err(e) => Ok((None::<Value>, Some(format!("gRPC error: {}", e)))),
318-
}
319-
});
320-
321-
methods.add_async_method(
322-
"upsert",
323-
|lua, this, (key, value): (String, String)| async move {
324-
let upsert = UpsertKV::update(key, value.as_bytes());
325-
match this.client.request(upsert).await {
326-
Ok(result) => match lua.to_value(&result) {
327-
Ok(lua_value) => Ok((Some(lua_value), None::<String>)),
328-
Err(e) => Ok((None::<Value>, Some(format!("Lua conversion error: {}", e)))),
329-
},
330-
Err(e) => Ok((None::<Value>, Some(format!("gRPC error: {}", e)))),
331-
}
332-
},
333-
);
255+
lua_support::new_grpc_client(addresses)
334256
}
335257
}
336258

โ€Žsrc/meta/control/Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ edition = { workspace = true }
1111

1212
[dependencies]
1313
databend-common-meta-client = { workspace = true }
14+
databend-common-meta-kvapi = { workspace = true }
1415
databend-common-meta-raft-store = { workspace = true }
1516
databend-common-meta-sled-store = { workspace = true }
1617
databend-common-meta-types = { workspace = true }
@@ -20,6 +21,7 @@ databend-meta = { workspace = true }
2021
anyhow = { workspace = true }
2122
clap = { workspace = true }
2223
futures = { workspace = true }
24+
mlua = { workspace = true }
2325
raft-log = { workspace = true }
2426
reqwest = { workspace = true }
2527
serde = { workspace = true }

โ€Žsrc/meta/control/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,5 +20,6 @@ pub mod export_from_disk;
2020
pub mod export_from_grpc;
2121
pub mod import;
2222
mod import_v004;
23+
pub mod lua_support;
2324
pub(crate) mod reading;
2425
mod upgrade;
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
// Copyright 2021 Datafuse Labs
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
use std::sync::Arc;
16+
use std::time::Duration;
17+
18+
use databend_common_meta_client::errors::CreationError;
19+
use databend_common_meta_client::ClientHandle;
20+
use databend_common_meta_client::MetaGrpcClient;
21+
use databend_common_meta_kvapi::kvapi::KVApi;
22+
use databend_common_meta_types::UpsertKV;
23+
use mlua::Lua;
24+
use mlua::LuaSerdeExt;
25+
use mlua::UserData;
26+
use mlua::UserDataMethods;
27+
use mlua::Value;
28+
29+
pub struct LuaGrpcClient {
30+
client: Arc<ClientHandle>,
31+
}
32+
33+
impl LuaGrpcClient {
34+
pub fn new(client: Arc<ClientHandle>) -> Self {
35+
Self { client }
36+
}
37+
}
38+
39+
impl UserData for LuaGrpcClient {
40+
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
41+
methods.add_async_method("get", |lua, this, key: String| async move {
42+
match this.client.get_kv(&key).await {
43+
Ok(result) => match lua.to_value(&result) {
44+
Ok(lua_value) => Ok((Some(lua_value), None::<String>)),
45+
Err(e) => Ok((None::<Value>, Some(format!("Lua conversion error: {}", e)))),
46+
},
47+
Err(e) => Ok((None::<Value>, Some(format!("gRPC error: {}", e)))),
48+
}
49+
});
50+
51+
methods.add_async_method(
52+
"upsert",
53+
|lua, this, (key, value): (String, String)| async move {
54+
let upsert = UpsertKV::update(key, value.as_bytes());
55+
match this.client.request(upsert).await {
56+
Ok(result) => match lua.to_value(&result) {
57+
Ok(lua_value) => Ok((Some(lua_value), None::<String>)),
58+
Err(e) => Ok((None::<Value>, Some(format!("Lua conversion error: {}", e)))),
59+
},
60+
Err(e) => Ok((None::<Value>, Some(format!("gRPC error: {}", e)))),
61+
}
62+
},
63+
);
64+
}
65+
}
66+
67+
pub fn setup_lua_environment(lua: &Lua) -> anyhow::Result<()> {
68+
// Register new_grpc_client function
69+
let new_grpc_client = lua
70+
.create_function(|_lua, address: String| {
71+
let client = MetaGrpcClient::try_create(
72+
vec![address],
73+
"root",
74+
"xxx",
75+
Some(Duration::from_secs(2)),
76+
Some(Duration::from_secs(1)),
77+
None,
78+
)
79+
.map_err(|e| mlua::Error::external(format!("Failed to create gRPC client: {}", e)))?;
80+
81+
Ok(LuaGrpcClient::new(client))
82+
})
83+
.map_err(|e| anyhow::anyhow!("Failed to create new_grpc_client function: {}", e))?;
84+
85+
lua.globals()
86+
.set("new_grpc_client", new_grpc_client)
87+
.map_err(|e| anyhow::anyhow!("Failed to register new_grpc_client: {}", e))?;
88+
89+
// Export NULL constant to Lua environment
90+
lua.globals()
91+
.set("NULL", Value::NULL)
92+
.map_err(|e| anyhow::anyhow!("Failed to register NULL constant: {}", e))?;
93+
94+
Ok(())
95+
}
96+
97+
pub fn new_grpc_client(addresses: Vec<String>) -> Result<Arc<ClientHandle>, CreationError> {
98+
eprintln!(
99+
"Using gRPC API address: {}",
100+
serde_json::to_string(&addresses).unwrap()
101+
);
102+
MetaGrpcClient::try_create(
103+
addresses,
104+
"root",
105+
"xxx",
106+
Some(Duration::from_secs(2)),
107+
Some(Duration::from_secs(1)),
108+
None,
109+
)
110+
}

0 commit comments

Comments
ย (0)