Skip to content
Merged
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
5 changes: 3 additions & 2 deletions casbin/enforcer_synced.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,8 @@ bool SyncedEnforcer ::IsAutoLoadingRunning() {

// StopAutoLoadPolicy causes the thread to exit
void SyncedEnforcer ::StopAutoLoadPolicy() {
ticker->stop();
if (ticker)
ticker->stop();
autoLoadRunning = false;
}

Expand Down Expand Up @@ -590,4 +591,4 @@ bool SyncedEnforcer::SyncedEnforceWithMatcher(const std::string& matcher, const

} // namespace casbin

#endif // ENFORCER_SYNCED_CPP
#endif // ENFORCER_SYNCED_CPP
32 changes: 20 additions & 12 deletions casbin/util/ticker.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,29 +33,37 @@ Ticker::~Ticker() {
}

void Ticker::start() {
std::lock_guard<std::mutex> lifecycle(_lifecycleMutex);
if (_running) return;
if (_worker.joinable())
_worker.join();
_running = true;
_futures1.push_back(std::async(std::launch::async, &Ticker::timer_loop, this));
_worker = std::thread(&Ticker::timer_loop, this);
}

void Ticker::stop() {
_running = false;
std::lock_guard<std::mutex> lock(_tickIntervalMutex);
for (auto&& f : _futures1) {
f.wait();
}
for (auto&& f : _futures2) {
f.wait();
std::lock_guard<std::mutex> lifecycle(_lifecycleMutex);
{
std::lock_guard<std::mutex> lock(_tickIntervalMutex);
_running = false;
}
_wake.notify_all();
if (_worker.joinable() && _worker.get_id() != std::this_thread::get_id())
_worker.join();
}

void Ticker::timer_loop() {
std::unique_lock<std::mutex> lock(_tickIntervalMutex);
while (_running) {
{
std::lock_guard<std::mutex> lock(_tickIntervalMutex);
_futures2.push_back(std::async(std::launch::async, _onTick));
std::this_thread::sleep_for(_tickInterval);
lock.unlock();
try {
_onTick();
} catch (...) {
// The previous async callbacks also kept exceptions in their
// futures. Keep a callback failure from terminating the scheduler.
}
lock.lock();
_wake.wait_for(lock, _tickInterval, [this] { return !_running.load(); });
}
}

Expand Down
9 changes: 7 additions & 2 deletions include/casbin/util/ticker.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,13 @@
#define TICKER_H

#include <chrono>
#include <atomic>
#include <condition_variable>
#include <functional>
#include <future>
#include <mutex>
#include <thread>
#include <vector>

namespace casbin {

Expand All @@ -43,9 +47,10 @@ class Ticker {
on_tick_t _onTick;
tick_interval_t _tickInterval;
std::atomic_bool _running;
std::mutex _lifecycleMutex;
std::mutex _tickIntervalMutex;
future_vec _futures1;
future_vec _futures2;
std::condition_variable _wake;
std::thread _worker;
};

}; // namespace casbin
Expand Down
1 change: 1 addition & 0 deletions tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ if(CASBIN_BUILD_TEST)

set(CASBIN_TEST_SOURCE
built_in_functions_test.cpp
ticker_test.cpp
config_test.cpp
enforcer_test.cpp
enforcer_cached_test.cpp
Expand Down
88 changes: 88 additions & 0 deletions tests/ticker_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

#include <gtest/gtest.h>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <future>
#include <mutex>
#include <thread>

#include "casbin/enforcer_synced.h"
#include "casbin/util/ticker.h"

namespace {

TEST(ReleaseTicker, SlowCallbacksDoNotOverlapAndCanRestart) {
std::atomic<int> active{0};
std::atomic<int> calls{0};
std::atomic<bool> overlap{false};
std::mutex progressMutex;
std::condition_variable progress;
casbin::Ticker ticker([&] {
if (active.fetch_add(1) != 0)
overlap = true;
{
std::lock_guard<std::mutex> lock(progressMutex);
++calls;
}
progress.notify_one();
std::this_thread::sleep_for(std::chrono::milliseconds(20));
--active;
}, std::chrono::milliseconds(1));
const auto waitForCalls = [&](int minimum) {
std::unique_lock<std::mutex> lock(progressMutex);
return progress.wait_for(lock, std::chrono::seconds(5), [&] { return calls.load() >= minimum; });
};
ticker.start();
// Wait for observable callback progress, including on busy CI runners.
EXPECT_TRUE(waitForCalls(3));
ticker.stop();
EXPECT_FALSE(overlap);
EXPECT_EQ(active.load(), 0);
EXPECT_GE(calls.load(), 1);
const auto before = calls.load();
ticker.start();
EXPECT_TRUE(waitForCalls(before + 1));
ticker.stop();
ticker.stop();
EXPECT_GT(calls.load(), before);
EXPECT_FALSE(overlap);
}

TEST(ReleaseTicker, StopInterruptsLongWait) {
std::promise<void> entered;
casbin::Ticker ticker([&] { entered.set_value(); }, std::chrono::seconds(10));
ticker.start();
auto ready = entered.get_future().wait_for(std::chrono::seconds(2));
EXPECT_EQ(ready, std::future_status::ready);
const auto before = std::chrono::steady_clock::now();
ticker.stop();
EXPECT_LT(std::chrono::steady_clock::now() - before, std::chrono::seconds(2));
}

TEST(ReleaseTicker, AutoLoadStopIsSafeBeforeStart) {
casbin::SyncedEnforcer enforcer;
enforcer.StopAutoLoadPolicy();
enforcer.StopAutoLoadPolicy();
EXPECT_FALSE(enforcer.IsAutoLoadingRunning());
}

} // namespace
Loading