190 lines
13 KiB
C++
190 lines
13 KiB
C++
#pragma once
|
|
#include "cube_gold_intent.h"
|
|
#include <cerrno>
|
|
#include <fcntl.h>
|
|
#include <sys/file.h>
|
|
#include <sys/stat.h>
|
|
#include <tuple>
|
|
#include <unistd.h>
|
|
|
|
namespace PortCube {
|
|
// Core-private, bounded append-only journal. ACK means DB has the immutable
|
|
// intent, NOT that currency is applied or the actor may thaw. Keep ACK history
|
|
// so a restarted writer cannot reuse a sequence. No automatic compaction yet.
|
|
struct GoldDelivery {
|
|
GoldIntent intent;
|
|
uint64_t session=0;
|
|
uint32_t cookie=0,handle=0,ground=0,vnum=0,map=0;
|
|
};
|
|
constexpr size_t GoldDeliveryBytes=GoldIntentBytes+28;
|
|
inline std::string EncodeGoldDelivery(const GoldDelivery& d) {
|
|
const auto body=EncodeGoldIntent(d.intent);
|
|
if(body.empty()||d.intent.source!=1||!d.session||!d.cookie||!d.handle||!d.ground||!d.vnum||!d.map)return {};
|
|
Writer w;w.data=body;w.n(d.session,8);w.n(d.cookie,4);w.n(d.handle,4);w.n(d.ground,4);w.n(d.vnum,4);w.n(d.map,4);return w.data;
|
|
}
|
|
inline bool DecodeGoldDelivery(const std::string& body,GoldDelivery& d) {
|
|
d={};if(body.size()!=GoldDeliveryBytes)return false;GoldDelivery out;
|
|
if(!DecodeGoldIntent(body.substr(0,GoldIntentBytes),out.intent))return false;
|
|
Reader r(body);r.at=GoldIntentBytes;out.session=r.n(8);out.cookie=uint32_t(r.n(4));out.handle=uint32_t(r.n(4));
|
|
out.ground=uint32_t(r.n(4));out.vnum=uint32_t(r.n(4));out.map=uint32_t(r.n(4));
|
|
if(!r.ok||r.at!=body.size()||EncodeGoldDelivery(out)!=body)return false;d=std::move(out);return true;
|
|
}
|
|
inline GoldSourceBinding GoldSourceFor(const GoldDelivery& d) {
|
|
GoldSourceBinding s;s.account=d.intent.account;s.player=d.intent.player;s.epoch=d.intent.epoch;s.owner=d.intent.owner;s.request=d.intent.request;
|
|
s.session=d.session;s.cookie=d.cookie;s.handle=d.handle;return s;
|
|
}
|
|
class GoldOutbox {
|
|
struct Record {GoldDelivery delivery;bool acknowledged=false;};
|
|
struct Closing {GoldSourceBinding binding;unsigned count=0;bool acknowledged=false;};
|
|
int fd=-1,lock=-1,directory=-1;bool healthy=false;size_t bytes=0;
|
|
std::string error;std::map<std::string,Record> records;
|
|
std::map<std::string,Closing> sources;
|
|
static uint32_t Hash(const std::string& body){uint32_t h=2166136261u;for(unsigned char c:body){h^=c;h*=16777619u;}return h;}
|
|
bool Fail(const char* reason){healthy=false;error=reason;return false;}
|
|
static bool PrivateFile(int f){struct stat s={};return fstat(f,&s)==0&&S_ISREG(s.st_mode)&&s.st_nlink==1&&s.st_uid==geteuid()&&!(s.st_mode&0022);}
|
|
static bool WriteAll(int f,const std::string& body) {
|
|
size_t at=0;while(at<body.size()){const auto n=write(f,body.data()+at,body.size()-at);if(n<0&&errno==EINTR)continue;if(n<=0)return false;at+=size_t(n);}return true;
|
|
}
|
|
static std::string ClosingBody(const Closing& c) {
|
|
const auto binding=EncodeGoldSourceBinding(c.binding);if(binding.empty()||c.count>GoldSourceLimit)return {};
|
|
Writer w;w.data=binding;w.n(c.count,4);w.data.resize(GoldDeliveryBytes,'\0');return w.data;
|
|
}
|
|
static bool DecodeClosing(const std::string& body,Closing& c) {
|
|
c={};if(body.size()!=GoldDeliveryBytes)return false;Closing out;
|
|
if(!DecodeGoldSourceBinding(body.substr(0,GoldSourceBindingBytes),out.binding))return false;
|
|
Reader r(body);r.at=GoldSourceBindingBytes;out.count=unsigned(r.n(4));if(!r.ok||ClosingBody(out)!=body)return false;c=std::move(out);return true;
|
|
}
|
|
bool SourceImage(const GoldSourceBinding& binding,bool requireAck,GoldSourceSeal& seal)const {
|
|
seal={};if(EncodeGoldSourceBinding(binding).empty())return false;static_cast<GoldSourceBinding&>(seal)=binding;
|
|
std::vector<std::pair<unsigned,std::string>> ordered;
|
|
for(const auto& entry:records)if(entry.second.delivery.intent.request==binding.request) {
|
|
const auto& r=entry.second;
|
|
if((requireAck&&!r.acknowledged)||EncodeGoldSourceBinding(GoldSourceFor(r.delivery))!=EncodeGoldSourceBinding(binding))return false;
|
|
ordered.emplace_back(r.delivery.intent.sequence,r.delivery.intent.event);
|
|
}
|
|
std::sort(ordered.begin(),ordered.end());for(const auto& e:ordered){if(e.first!=seal.events.size()+1)return false;seal.events.push_back(e.second);}
|
|
return !EncodeGoldManifest(seal.events).empty();
|
|
}
|
|
bool AppendBody(unsigned op,const std::string& body) {
|
|
Writer w;w.data="CGO1";w.n(op,1);w.data+=body;w.n(Hash(w.data),4);const auto& frame=w.data;
|
|
if(!healthy||frame.size()!=FrameBytes||bytes>MaxBytes-frame.size())return Fail("gold outbox unavailable/full; retain hold and journal");
|
|
if(!WriteAll(fd,frame)||fsync(fd)!=0)return Fail("gold outbox write/sync uncertain; quarantine source and retain journal");
|
|
bytes+=frame.size();return true;
|
|
}
|
|
bool Append(unsigned op,const GoldDelivery& d){return AppendBody(op,EncodeGoldDelivery(d));}
|
|
bool Admit(const GoldDelivery& d)const {
|
|
if(EncodeGoldDelivery(d).empty()||records.size()>=MaxRecords||sources.count(d.intent.request))return false;
|
|
unsigned sequence=1;
|
|
for(const auto& entry:records)if(entry.second.delivery.intent.request==d.intent.request) {
|
|
const auto& i=entry.second.delivery.intent;
|
|
if(i.account!=d.intent.account||i.player!=d.intent.player||i.epoch!=d.intent.epoch||i.owner!=d.intent.owner)return false;
|
|
if(EncodeGoldSourceBinding(GoldSourceFor(entry.second.delivery))!=EncodeGoldSourceBinding(GoldSourceFor(d)))return false;
|
|
++sequence;
|
|
}
|
|
return d.intent.sequence==sequence;
|
|
}
|
|
public:
|
|
static constexpr size_t MaxRecords=8192,MaxBytes=16*1024*1024,FrameBytes=4+1+GoldDeliveryBytes+4;
|
|
GoldOutbox()=default;GoldOutbox(const GoldOutbox&)=delete;GoldOutbox& operator=(const GoldOutbox&)=delete;
|
|
~GoldOutbox(){if(fd>=0)close(fd);if(lock>=0)close(lock);if(directory>=0)close(directory);}
|
|
bool Ready()const{return healthy;}
|
|
const std::string& Error()const{return error;}
|
|
bool Open(const std::string& path) {
|
|
if(fd>=0||lock>=0||directory>=0)return Fail("gold outbox already opened");
|
|
const auto slash=path.rfind('/');const std::string dir=slash==std::string::npos?".":slash==0?"/":path.substr(0,slash);
|
|
const std::string name=slash==std::string::npos?path:path.substr(slash+1);
|
|
if(name.empty()||name=="."||name=="..")return Fail("invalid gold outbox path");
|
|
if(mkdir(dir.c_str(),0700)!=0&&errno!=EEXIST)return Fail("cannot create gold outbox directory");
|
|
directory=open(dir.c_str(),O_RDONLY|O_DIRECTORY|O_NOFOLLOW);
|
|
if(directory<0)return Fail("cannot open gold outbox directory");
|
|
lock=openat(directory,(name+".lock").c_str(),O_RDWR|O_CREAT|O_NOFOLLOW,0600);
|
|
if(lock<0||!PrivateFile(lock)||flock(lock,LOCK_EX|LOCK_NB)!=0)return Fail("gold outbox already owned/unsafe lock");
|
|
fd=openat(directory,name.c_str(),O_RDWR|O_CREAT|O_APPEND|O_NOFOLLOW,0600);
|
|
if(fd<0||!PrivateFile(fd)||flock(fd,LOCK_EX|LOCK_NB)!=0)return Fail("unsafe/owned gold outbox file");
|
|
struct stat info={};if(fstat(fd,&info)!=0||info.st_size<0||uint64_t(info.st_size)>MaxBytes)return Fail("gold outbox size invalid");
|
|
bytes=size_t(info.st_size);
|
|
if(fsync(fd)!=0||fsync(lock)!=0||fsync(directory)!=0)return Fail("cannot persist gold outbox directory entries");
|
|
if(bytes%FrameBytes)return Fail("torn gold outbox; retain bytes for repair");
|
|
for(size_t at=0;at<bytes;at+=FrameBytes) {
|
|
std::string frame(FrameBytes,'\0');size_t got=0;
|
|
while(got<frame.size()){const auto n=pread(fd,&frame[got],frame.size()-got,off_t(at+got));if(n<0&&errno==EINTR)continue;if(n<=0)return Fail("cannot read gold outbox");got+=size_t(n);}
|
|
Reader checksum(frame);checksum.at=FrameBytes-4;
|
|
if(frame.substr(0,4)!="CGO1"||checksum.n(4)!=Hash(frame.substr(0,FrameBytes-4)))return Fail("corrupt gold outbox; retain bytes for repair");
|
|
const unsigned op=uint8_t(frame[4]);const auto body=frame.substr(5,GoldDeliveryBytes);
|
|
if(op==3||op==4) {
|
|
Closing c;GoldSourceSeal seal;
|
|
if(!DecodeClosing(body,c)||!SourceImage(c.binding,op==4,seal)||seal.events.size()!=c.count)return Fail("corrupt source close proof");
|
|
auto it=sources.find(c.binding.request);
|
|
if(op==3) {
|
|
if(it!=sources.end()||sources.size()>=MaxRecords)return Fail("duplicate/overfull source close");
|
|
sources.emplace(c.binding.request,c);
|
|
} else {
|
|
if(it==sources.end()||it->second.acknowledged||ClosingBody(it->second)!=body)return Fail("unknown/conflicting source close ACK");
|
|
it->second.acknowledged=true;
|
|
}
|
|
continue;
|
|
}
|
|
GoldDelivery d;if(!DecodeGoldDelivery(body,d))return Fail("corrupt gold delivery body");auto it=records.find(d.intent.event);
|
|
if(op==1) {
|
|
if(it!=records.end()||!Admit(d))return Fail("conflicting/out-of-order gold outbox claim");
|
|
records.emplace(d.intent.event,Record{d,false});
|
|
} else if(op==2) {
|
|
if(it==records.end()||it->second.acknowledged||EncodeGoldDelivery(it->second.delivery)!=EncodeGoldDelivery(d))return Fail("unknown/conflicting gold outbox ACK");
|
|
it->second.acknowledged=true;
|
|
} else return Fail("unknown gold outbox operation");
|
|
}
|
|
healthy=true;return true;
|
|
}
|
|
unsigned Next(const std::string& request)const {unsigned n=1;for(const auto& r:records)if(r.second.delivery.intent.request==request)++n;return n;}
|
|
uint64_t Total(const std::string& request)const {
|
|
uint64_t total=0;for(const auto& r:records)if(r.second.delivery.intent.request==request) {
|
|
if(total>uint64_t(PortEconomy::GoldLimit)-r.second.delivery.intent.amount)return uint64_t(PortEconomy::GoldLimit);
|
|
total+=r.second.delivery.intent.amount;
|
|
}return total;
|
|
}
|
|
const GoldDelivery* Find(const std::string& event)const {auto it=records.find(event);return it==records.end()?nullptr:&it->second.delivery;}
|
|
bool Claim(const GoldDelivery& d) {
|
|
if(!healthy||EncodeGoldDelivery(d).empty())return false;auto it=records.find(d.intent.event);
|
|
if(it!=records.end())return EncodeGoldDelivery(it->second.delivery)==EncodeGoldDelivery(d);
|
|
if(!Admit(d)){error="gold outbox capacity/sequence/identity refused before writing";return false;}
|
|
if(!Append(1,d))return false;records.emplace(d.intent.event,Record{d,false});return true;
|
|
}
|
|
bool Acknowledge(const GoldDelivery& d) {
|
|
auto it=records.find(d.intent.event);
|
|
if(!healthy||it==records.end()||EncodeGoldDelivery(it->second.delivery)!=EncodeGoldDelivery(d))return false;
|
|
if(it->second.acknowledged)return true;
|
|
if(!Append(2,d))return false;it->second.acknowledged=true;return true;
|
|
}
|
|
bool IsClosing(const std::string& request)const{return sources.count(request)!=0;}
|
|
bool CloseSource(const GoldSourceBinding& binding) {
|
|
if(!healthy)return false;GoldSourceSeal seal;if(!SourceImage(binding,false,seal))return false;
|
|
auto it=sources.find(binding.request);Closing c{binding,unsigned(seal.events.size()),false};
|
|
if(it!=sources.end())return ClosingBody(it->second)==ClosingBody(c);
|
|
if(sources.size()>=MaxRecords)return false;
|
|
// Stop new claims DURABLY before waiting for existing delivery ACKs.
|
|
if(!AppendBody(3,ClosingBody(c)))return false;sources.emplace(binding.request,std::move(c));return true;
|
|
}
|
|
bool AcknowledgeSource(const GoldSourceSeal& seal) {
|
|
if(!healthy)return false;auto it=sources.find(seal.request);GoldSourceSeal expected;
|
|
if(it==sources.end()||EncodeGoldSourceBinding(seal)!=EncodeGoldSourceBinding(it->second.binding)||!SourceImage(seal,true,expected)||
|
|
seal.events!=expected.events||seal.events.size()!=it->second.count)return false;
|
|
if(it->second.acknowledged)return true;
|
|
if(!AppendBody(4,ClosingBody(it->second)))return false;it->second.acknowledged=true;return true;
|
|
}
|
|
bool SourceAcknowledged(const GoldSourceBinding& binding)const {
|
|
auto it=sources.find(binding.request);return healthy&&it!=sources.end()&&it->second.acknowledged&&EncodeGoldSourceBinding(binding)==EncodeGoldSourceBinding(it->second.binding);
|
|
}
|
|
std::vector<GoldSourceSeal> PendingSources()const {
|
|
std::vector<GoldSourceSeal> out;if(!healthy)return out;
|
|
for(const auto& entry:sources)if(!entry.second.acknowledged) {
|
|
GoldSourceSeal seal;if(SourceImage(entry.second.binding,true,seal)&&seal.events.size()==entry.second.count)out.push_back(std::move(seal));
|
|
}return out;
|
|
}
|
|
std::vector<GoldDelivery> Pending()const {
|
|
std::vector<GoldDelivery> out;if(!healthy)return out;
|
|
for(const auto& r:records)if(!r.second.acknowledged)out.push_back(r.second.delivery);
|
|
std::sort(out.begin(),out.end(),[](const auto& a,const auto& b){return std::tie(a.intent.account,a.intent.player,a.intent.request,a.intent.sequence)<std::tie(b.intent.account,b.intent.player,b.intent.request,b.intent.sequence);});return out;
|
|
}
|
|
};
|
|
}
|