Skip to content
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
60 changes: 60 additions & 0 deletions doc/developer-guide/cripts/cripts-misc.en.rst
Original file line number Diff line number Diff line change
Expand Up @@ -414,3 +414,63 @@ Debug logging uses the same format string syntax as ``fmt::format()`` in ``libfm
debug tags in your ATS configuration to enable debug output for your Cripts.
The default debug tag for Cripts is the name of the Cript itself, either
the Cript source file, or the compiled plugin name.

Cache Groups
============

As a way to manage association between cache entries, Cripts provides an infrastructure
for cache groups. A cache group is a set of cache entries that are logically
associated with each other via custom identifiers.

Example implementation of the Cache Groups RFC

.. code-block:: cpp

do_create_instance()
{
// Create a cache-group for this site / remap rule(s). They can be shared.
instance.data[0] = cripts::Cache::Group::Manager::Factory("example_site");
}

do_delete_instance()
{
void *ptr = AsPointer(instance.data[0]);

if (ptr) {
delete static_cast<std::shared_ptr<cripts::Cache::Group> *>(ptr);
instance.data[0] = nullptr;
}
}

do_cache_lookup()
{
if (cached.response.lookupstatus != cripts::LookupStatus::MISS) {
void *ptr = AsPointer(instance.data[0]);

if (ptr) {
auto date = cached.response.AsDate("Date");
if (date != 0) {
auto cache_groups = cached.response["Cache-Groups"];
if (!cache_groups.empty()) {
borrow cg = *static_cast<std::shared_ptr<cripts::Cache::Group> *>(ptr);
if (cg->Lookup(cache_groups.split(','), date)) {
cached.response.lookupstatus = cripts::LookupStatus::HIT_STALE;
}
}
}
}
}
}

do_read_response()
{
void *ptr = AsPointer(instance.data[0]);

if (ptr) {
auto invalidation = client.request["Cache-Group-Invalidation"];
if (!invalidation.empty()) {
borrow cg = *static_cast<std::shared_ptr<cripts::Cache::Group> *>(ptr);
cg->Insert(invalidation.split(','));
}
}
}
106 changes: 106 additions & 0 deletions example/cripts/cache_groups.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/*
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

http://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.
*/

#define CRIPTS_CONVENIENCE_APIS 1

#include <cripts/CacheGroup.hpp>
#include <cripts/Preamble.hpp>

do_create_instance()
{
// Create a cache-group for this site / remap rule(s). They can be shared.
instance.data[0] = cripts::Cache::Group::Manager::Factory("example");
}

do_delete_instance()
{
void *ptr = AsPointer(instance.data[0]);

if (ptr) {
delete static_cast<std::shared_ptr<cripts::Cache::Group> *>(ptr);
instance.data[0] = nullptr;
}
}

do_cache_lookup()
{
if (cached.response.lookupstatus != cripts::LookupStatus::MISS) {
void *ptr = AsPointer(instance.data[0]);

if (ptr) {
auto date = cached.response.AsDate("Date");

if (date != 0) {
auto cache_groups = cached.response["Cache-Groups"];

CDebug("Looking up {}", cache_groups);
if (!cache_groups.empty()) {
borrow cg = *static_cast<std::shared_ptr<cripts::Cache::Group> *>(ptr);

if (cg->Lookup(cache_groups.split(','), date)) {
CDebug("Cache Group hit, forcing revalidation for request");
cached.response.lookupstatus = cripts::LookupStatus::HIT_STALE;
}
}
}
}
}
}

do_read_response()
{
void *ptr = AsPointer(instance.data[0]);

if (ptr) {
auto invalidation = client.request["Cache-Group-Invalidation"];

if (!invalidation.empty()) {
borrow cg = *static_cast<std::shared_ptr<cripts::Cache::Group> *>(ptr);

cg->Insert(invalidation.split(','));
}
}

// This is just for simulating origin responses that would include cache-groups.
#if 0
server.response["Cache-Groups"] = "\"foo\", \"bar\"";
#endif
}

// The RFC draft does not support / provide definitions for this. It is useful,
// but should be protected with appropriate ACLs / authentication.
#if 0
do_remap()
{
void *ptr = AsPointer(instance.data[0]);

if (ptr && urls.pristine.path == ".well-known/Cache-Groups") {
auto invalidation = client.request["Cache-Group-Invalidation"];

if (!invalidation.empty()) {
borrow cg = *static_cast<std::shared_ptr<cripts::Cache::Group> *>(ptr);

cg->Insert(invalidation.split(','));
CDebug("Forcing a cache miss for cache-groups: {}", invalidation);
StatusCode(202);
}
}
}
#endif

#include <cripts/Epilogue.hpp>
215 changes: 215 additions & 0 deletions include/cripts/CacheGroup.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
/*
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

http://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.
*/
#pragma once

#include <unordered_map>
#include <string>
#include <vector>
#include <chrono>
#include <mutex>
#include <shared_mutex>
#include <fstream>
#include <memory>
#include <cstdint>

#include "cripts/Context.hpp"
#include "cripts/Time.hpp"

// Implemented in the .cc file
int _cripts_cache_group_sync(TSCont cont, TSEvent event, void *edata);

namespace cripts::Cache
{

class Group
{
private:
using self_type = Group;

struct _Entry {
cripts::Time::Point timestamp; // Timestamp of when the entry was created
size_t length; // Length of the group ID
uint32_t prefix; // First 4 characters of the group ID
uint64_t hash; // Hash value of the group ID, needed when writing to disk
};

// Header structure for on-disk map files (after VERSION field)
struct _MapHeader {
time_t created_ts;
time_t last_write_ts;
time_t last_sync_ts;
size_t count;
};

using _MapType = std::unordered_map<uint64_t, _Entry>;

struct _MapSlot {
std::unique_ptr<_MapType> map;
std::string path;
cripts::Time::Point created;
cripts::Time::Point last_write;
cripts::Time::Point last_sync;
};

public:
static constexpr uint64_t VERSION = (static_cast<uint64_t>('C') << 56) | (static_cast<uint64_t>('G') << 48) |
(static_cast<uint64_t>('M') << 40) | (static_cast<uint64_t>('A') << 32) |
(static_cast<uint64_t>('P') << 24) | (static_cast<uint64_t>('S') << 16) |
(static_cast<uint64_t>('0') << 8) | 0x00; // Change this on version bump

static constexpr std::chrono::seconds DEFAULT_MAX_AGE{63072000}; // 2 Years, max cache lifetime in ATS as well

Group(const std::string &name, const std::string &base_dir, size_t max_entries = 1024, size_t num_maps = 3)
{
Initialize(name, base_dir, num_maps, max_entries, DEFAULT_MAX_AGE);
Comment on lines +77 to +79
Copy link

Copilot AI Dec 22, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Initialize method is called from the constructor with parameters in a different order (num_maps and max_entries are swapped). The constructor at line 78 passes max_entries as the third parameter and num_maps as the fourth, but Initialize expects num_maps third and max_entries fourth. This will cause the values to be assigned incorrectly, leading to unexpected behavior.

Copilot uses AI. Check for mistakes.
}

// Not used at the moment.
Group() = default;

~Group() { WriteToDisk(); }

Group(const self_type &) = delete;
self_type &operator=(const self_type &) = delete;

void Initialize(const std::string &name, const std::string &base_dir, size_t num_maps = 3, size_t max_entries = 1024,
std::chrono::seconds max_age = DEFAULT_MAX_AGE);

void
SetMaxEntries(size_t max_entries)
{
std::unique_lock lock(_mutex);
_max_entries = max_entries;
}

void
SetMaxAge(std::chrono::seconds max_age)
{
std::unique_lock lock(_mutex);
_max_age = max_age;
}

void Insert(cripts::string_view key);
void Insert(const std::vector<cripts::string_view> &keys);
bool Lookup(cripts::string_view key, cripts::Time::Point age) const;
bool Lookup(const std::vector<cripts::string_view> &keys, cripts::Time::Point age) const;

bool
Lookup(cripts::string_view key, time_t age) const
{
return Lookup(key, cripts::Time::Clock::from_time_t(age));
}

bool
Lookup(const std::vector<cripts::string_view> &keys, time_t age) const
{
return Lookup(keys, cripts::Time::Clock::from_time_t(age));
}

cripts::Time::Point
LastSync() const
{
std::shared_lock lock(_mutex);
return _last_sync;
}

void WriteToDisk();
void LoadFromDisk();

private:
mutable std::shared_mutex _mutex;
std::string _name = "CacheGroup";
size_t _num_maps = 3;
size_t _max_entries = 1024;
std::chrono::seconds _max_age = DEFAULT_MAX_AGE;
size_t _map_index = 0;
cripts::Time::Point _last_sync = cripts::Time::Point{};

std::vector<_MapSlot> _slots;
std::ofstream _txn_log;
std::string _log_path;
std::string _base_dir;

void appendLog(const _Entry &entry);
void clearLog();
void syncMap(size_t index);

public:
class Manager
{
friend int ::_cripts_cache_group_sync(TSCont cont, TSEvent event, void *edata);
using self_type = Manager;

public:
static void *Factory(const std::string &name, size_t max_entries = 1024, size_t num_maps = 3);

Manager(const self_type &) = delete;
self_type &operator=(const self_type &) = delete;

protected:
void _scheduleCont();

std::unordered_map<std::string, std::weak_ptr<Group>> _groups;
std::mutex _mutex;

private:
Manager()
{
_base_dir = TSRuntimeDirGet();

if (std::filesystem::exists(_base_dir)) {
_base_dir += "/cache_groups";
if (!std::filesystem::exists(_base_dir)) {
std::error_code ec;

std::filesystem::create_directories(_base_dir, ec);
if (ec) {
TSError("cripts::Cache::Group::Manager: Failed to create directory `%s': %s", _base_dir.c_str(), ec.message().c_str());
} else {
std::filesystem::permissions(_base_dir, std::filesystem::perms::group_write, std::filesystem::perm_options::add, ec);

if (ec) {
TSWarning("cripts::Cache::Group::Manager: Failed to set permissions on `%s': %s", _base_dir.c_str(),
ec.message().c_str());
}
}
}
}
_scheduleCont(); // Kick it off
}

~Manager()
{
if (_action) {
TSActionCancel(_action);
_action = nullptr;
}
if (_cont) {
TSContDestroy(_cont);
_cont = nullptr;
}
}

static self_type &_instance();

TSCont _cont = nullptr;
TSAction _action = nullptr;
std::string _base_dir;
};
};
} // namespace cripts::Cache
1 change: 1 addition & 0 deletions src/cripts/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ list(REMOVE_ITEM CPP_FILES ${TEST_CPP_FILES})

set(CRIPTS_PUBLIC_HEADERS
${PROJECT_SOURCE_DIR}/include/cripts/Bundle.hpp
${PROJECT_SOURCE_DIR}/include/cripts/CacheGroup.hpp
${PROJECT_SOURCE_DIR}/include/cripts/Certs.hpp
${PROJECT_SOURCE_DIR}/include/cripts/Configs.hpp
${PROJECT_SOURCE_DIR}/include/cripts/ConfigsBase.hpp
Expand Down
Loading