Remove command when user disconnected

This commit is contained in:
chalith
2023-10-31 18:31:06 +05:30
parent dc9e1b46e5
commit 835b702e7e
4 changed files with 31 additions and 15 deletions

View File

@@ -146,7 +146,14 @@ namespace hpsh
return (write(ctx.control_fds[1], HPSH_CTR_TERMINATE, 10) < 0) ? -1 : 0;
}
int execute(std::string_view id, std::string_view pubkey, std::string_view message)
void remove_user_commands(std::string_view user_pubkey)
{
std::scoped_lock lock(ctx.command_mutex);
ctx.commands.remove_if([&](const command_context &command)
{ return command.user_pubkey == user_pubkey; });
}
int execute(std::string_view id, std::string_view user_pubkey, std::string_view message)
{
if (ctx.is_shutting_down)
return -1;
@@ -203,9 +210,11 @@ namespace hpsh
return -1;
}
close(child_fds[0]);
{
std::scoped_lock lock(ctx.command_mutex);
ctx.commands.push_back(command_context{std::string(id), std::string(pubkey), {child_fds[0], child_fds[1]}, std::string(), false});
ctx.commands.push_back(command_context{std::string(id), std::string(user_pubkey), {child_fds[0], child_fds[1]}, std::string(), false});
}
return 0;
@@ -219,6 +228,8 @@ namespace hpsh
{
if (ctx.commands.size() > 0)
{
std::scoped_lock<std::mutex> lock(ctx.command_mutex);
auto itr = ctx.commands.begin();
while (itr != ctx.commands.end())
{
@@ -262,7 +273,7 @@ namespace hpsh
std::scoped_lock<std::mutex> lock(usr::ctx.users_mutex);
// Find the user session by user pubkey.
const auto user_itr = usr::ctx.users.find(itr->pubkey);
const auto user_itr = usr::ctx.users.find(itr->user_pubkey);
if (user_itr != usr::ctx.users.end()) // match found
{
const usr::connected_user &user = user_itr->second;
@@ -272,10 +283,10 @@ namespace hpsh
user.session.send(msg);
}
}
{
std::scoped_lock<std::mutex> lock(ctx.command_mutex);
itr = ctx.commands.erase(itr);
}
// Close the file descriptor and remove the command from context.
close(itr->child_fds[1]);
itr = ctx.commands.erase(itr);
}
else
{
@@ -283,10 +294,7 @@ namespace hpsh
}
}
}
else
{
util::sleep(1000);
}
util::sleep(1000);
}
}
}

View File

@@ -10,7 +10,7 @@ namespace hpsh
struct command_context
{
std::string id;
std::string pubkey;
std::string user_pubkey;
int child_fds[2];
std::string response;
bool read_completed = false;
@@ -37,7 +37,9 @@ namespace hpsh
int send_terminate_message();
int execute(std::string_view id, std::string_view pubkey, std::string_view message);
void remove_user_commands(std::string_view user_pubkey);
int execute(std::string_view id, std::string_view user_pubkey, std::string_view message);
void response_watcher();
}

View File

@@ -420,8 +420,14 @@ namespace usr
*/
int remove_user(const std::string &pubkey)
{
std::scoped_lock<std::mutex> lock(ctx.users_mutex);
ctx.users.erase(pubkey);
{
std::scoped_lock<std::mutex> lock(ctx.users_mutex);
ctx.users.erase(pubkey);
}
// Remove any hpsh commands sent by the user.
if (hpsh::ctx.is_initialized)
hpsh::remove_user_commands(pubkey);
return 0;
}

Binary file not shown.