载入中...
搜索中...
未找到
GameEvent.cpp
浏览该文件的文档.
2
3#include <utility>
4
6
7#include "common/Json.h"
9
10#include <simplesquirrel/simplesquirrel.hpp>
11
12#include <algorithm>
13#include <cmath>
14#include <iomanip>
15#include <limits>
16#include <sstream>
17#include <string_view>
18
19namespace eve::game_event {
20namespace {
21
22eve::schema::FieldDefinition schemaField(std::string name, eve::schema::ValueType type, bool required = true) {
24 result.name = std::move(name);
25 result.type = type;
26 result.required = required;
27 return result;
28}
29
30eve::schema::SchemaDefinition eventStreamSchemaDefinition() {
32 event.additionalProperties = false;
33 event.fields = {
34 schemaField("eventId", eve::schema::ValueType::String),
35 schemaField("sequence", eve::schema::ValueType::String),
36 schemaField("type", eve::schema::ValueType::String),
37 schemaField("source", eve::schema::ValueType::String),
38 schemaField("subject", eve::schema::ValueType::String),
39 schemaField("causationKind", eve::schema::ValueType::String),
40 schemaField("causation", eve::schema::ValueType::String),
41 schemaField("correlationKind", eve::schema::ValueType::String),
42 schemaField("correlation", eve::schema::ValueType::String),
43 schemaField("schemaId", eve::schema::ValueType::String),
44 schemaField("schemaVersion", eve::schema::ValueType::String),
45 schemaField("tick", eve::schema::ValueType::String),
46 schemaField("flags", eve::schema::ValueType::Integer),
47 schemaField("payload", eve::schema::ValueType::Any),
48 };
51 eventNode.objectSchema = std::make_shared<const eve::schema::SchemaDefinition>(std::move(event));
52 auto events = schemaField("events", eve::schema::ValueType::Array);
53 events.itemSchema = std::make_shared<const eve::schema::SchemaNode>(std::move(eventNode));
54
56 schema.id = "game_event:stream";
57 schema.version = 1;
58 schema.title = "Game Event Stream Snapshot";
59 schema.description = "Current persistent payload owned by GameEventLog.";
60 schema.additionalProperties = false;
61 schema.fields = {
62 schemaField("version", eve::schema::ValueType::Integer),
63 schemaField("revision", eve::schema::ValueType::String),
64 schemaField("nextSequence", eve::schema::ValueType::String),
65 std::move(events),
66 };
67 return schema;
68}
69
70eve::Result<void> validateCurrentEventStream(std::string_view json) {
71 constexpr auto id = "game_event:stream";
73 auto registration = eve::schema::SchemaRegistry::registerVersioned(eventStreamSchemaDefinition());
74 if (!registration.ok()) return eve::Result<void>::failure(registration.status());
75 }
76 const auto errors = eve::schema::SchemaRegistry::validate(id, 1, std::string(json));
77 if (errors.empty()) return eve::Result<void>::success();
78 const auto& error = errors.front();
81 eve::DiagnosticDetails{{"schemaId", id}, {"schemaVersion", "1"}, {"validationCode", error.code}},
82 "game_event.snapshot.schema"));
83}
84
85std::string quote(const std::string& value) {
86 return eve::json::quoteString(value, eve::json::StringEscapeStyle::Canonical);
87}
88
89bool parseU64(const eve::json::Value& value, uint64_t& out) {
90 if (!value.isString()) return false;
91 auto parsed = eve::json::scanUnsignedInteger(value.asString(), eve::json::UnsignedIntegerSyntax::LegacyStoull);
92 if (!parsed) return false;
93 out = parsed.value().value;
94 return parsed.value().consumed == parsed.value().size;
95}
96
97bool parseI64(const eve::json::Value& value, int64_t& out) {
98 if (!value.isString()) return false;
99 try {
100 const std::string text = value.asString();
101 size_t used = 0;
102 out = std::stoll(text, &used);
103 return used == text.size();
104 } catch (...) {
105 return false;
106 }
107}
108
109std::string canonicalJson(const eve::json::Value& value) {
110 if (value.isNull()) return "null";
111 if (value.isBool()) return value.asBool() ? "true" : "false";
112 if (value.isNumber()) return value.asString();
113 if (value.isString()) return quote(value.asString());
114 if (value.isArray()) {
115 std::string out = "[";
116 for (size_t i = 0; i < value.size(); ++i) {
117 if (i) out += ',';
118 out += canonicalJson(value.at(i));
119 }
120 return out + ']';
121 }
122 if (value.isObject()) {
123 auto keys = value.keys();
124 std::sort(keys.begin(), keys.end());
125 std::string out = "{";
126 for (size_t i = 0; i < keys.size(); ++i) {
127 if (i) out += ',';
128 out += quote(keys[i]) + ':' + canonicalJson(value.get(keys[i].c_str()));
129 }
130 return out + '}';
131 }
132 return {};
133}
134
135const char* correlationKindName(CorrelationId::Kind kind) {
136 switch (kind) {
137 case CorrelationId::Kind::None: return "none";
138 case CorrelationId::Kind::Id: return "id";
139 case CorrelationId::Kind::Legacy: return "legacy";
140 }
141 return "none";
142}
143
144const char* causationKindName(CausationRef::Kind kind) {
145 switch (kind) {
146 case CausationRef::Kind::None: return "none";
147 case CausationRef::Kind::Event: return "event";
148 case CausationRef::Kind::Command: return "command";
149 case CausationRef::Kind::Legacy: return "legacy";
150 }
151 return "none";
152}
153
154CorrelationId correlationFromSnapshot(const std::string& kind, const std::string& text) {
155 if (kind == "none") return {};
156 if (kind == "id") {
157 if (const auto parsed = EventId::parse(text)) return CorrelationId::fromEventId(*parsed);
158 return {};
159 }
161}
162
163CausationRef causationFromSnapshot(const std::string& kind, const std::string& text) {
164 if (kind == "none") return {};
165 if (kind == "event") {
166 if (const auto parsed = EventId::parse(text)) return CausationRef::fromEventId(*parsed);
167 return {};
168 }
169 if (kind == "command") {
170 if (const auto parsed = CommandId::parse(text)) return CausationRef::fromCommandId(*parsed);
171 return {};
172 }
174}
175
176eve::LogicalId eventStreamSchema() {
177 const auto schema = eve::LogicalId::parse("game_event:stream");
178 if (!schema) std::terminate();
179 return *schema;
180}
181
182const eve::SnapshotMigrationChain& eventStreamMigrations() {
183 static const eve::SnapshotMigrationChain chain = [] {
185 const auto registration =
186 result.add(eventStreamSchema(), eve::SchemaVersion(0), eve::SchemaVersion(1),
188 const auto* object = payload.getIf<eve::Value::Object>();
189 if (!object)
191 eve::DiagnosticCode::ParseError, "event stream payload must be an object"));
193 });
194 if (!registration.ok()) std::terminate();
195 return result;
196 }();
197 return chain;
198}
199
200} // namespace
201
202EventConsumer::EventConsumer(GameEventLog* stream, EventSequence sequence)
203 : stream_(stream), nextSequence_(sequence.value() == 0 ? EventSequence(1) : sequence) {}
204
205int EventConsumer::read(int maxCount) {
206 batch_.clear();
207 if (!stream_ || maxCount <= 0) return 0;
208 if (nextSequence_.value() < stream_->oldestSequence().value()) nextSequence_ = stream_->oldestSequence();
209 for (const auto& event : stream_->events_) {
210 if (event.sequence.value() < nextSequence_.value()) continue;
211 if (static_cast<int>(batch_.size()) >= maxCount) break;
212 batch_.push_back(&event);
213 nextSequence_ = EventSequence(event.sequence.value() + 1);
214 }
215 return static_cast<int>(batch_.size());
216}
217
218int EventConsumer::batchCount() const { return static_cast<int>(batch_.size()); }
219
220const GameEvent* EventConsumer::batchAt(int index) const {
221 return index >= 0 && static_cast<size_t>(index) < batch_.size() ? batch_[static_cast<size_t>(index)] : nullptr;
222}
223
224EventSequence EventConsumer::position() const { return nextSequence_; }
225
226void EventConsumer::seek(EventSequence sequence) {
227 nextSequence_ = sequence.value() == 0 ? EventSequence(1) : sequence;
228 batch_.clear();
229}
230
231void EventConsumer::seek(uint64_t sequence) { seek(EventSequence(sequence)); }
232
233GameEventLog::GameEventLog(eve::UuidEntropySource entropy, eve::UuidClock clock)
234 : eventIdGenerator_(std::in_place, std::move(entropy), std::move(clock)) {}
235
237 const auto failure = [](eve::DiagnosticCode code, std::string message) {
239 };
240 if (envelope.type.empty()) return failure(eve::DiagnosticCode::InvalidArgument, "event type must not be empty");
241 if (!envelope.schemaId.isValid())
242 return failure(eve::DiagnosticCode::InvalidArgument, "event schemaId must be a valid logical ID");
243 if (envelope.schemaVersion.isZero())
244 return failure(eve::DiagnosticCode::InvalidArgument, "event schemaVersion must be non-zero");
245 auto payloadDocument = eve::json::Document::parse(envelope.payload);
246 if (!payloadDocument.valid()) return failure(eve::DiagnosticCode::ParseError, "payload must be valid JSON");
247 const auto next = nextSequence_.incremented();
248 if (!next) return failure(eve::DiagnosticCode::Failed, "event sequence exhausted");
249 if (!revision_.incremented()) return failure(eve::DiagnosticCode::Failed, "event stream revision exhausted");
250
251 if (envelope.eventId.isNil()) {
252 if (eventIdGenerator_) {
253 const auto generated = eventIdGenerator_->generate();
254 if (!generated) return failure(eve::DiagnosticCode::Failed, "event ID generation failed");
255 envelope.eventId = EventId::fromUuid(*generated);
256 } else {
258 "eventId is required when no UUIDv7 generator is configured");
259 }
260 }
261 if (!envelope.eventId.isNil()) {
262 for (const auto& existing : events_) {
263 if (existing.eventId == envelope.eventId)
264 return failure(eve::DiagnosticCode::Conflict, "eventId already exists in this stream");
265 }
266 }
267
268 envelope.sequence = nextSequence_;
269 envelope.payload = canonicalJson(payloadDocument.root());
270 events_.push_back(std::move(envelope));
271 nextSequence_ = *next;
272 revision_ = *revision_.incremented();
273 if (events_.back().tick > snapshotTick_) snapshotTick_ = events_.back().tick;
274 return eve::Result<EventSequence>::success(events_.back().sequence);
275}
276
278 const auto it =
279 std::lower_bound(events_.begin(), events_.end(), sequence.value(),
280 [](const GameEvent& event, uint64_t value) { return event.sequence.value() < value; });
281 return it != events_.end() && it->sequence.value() == sequence.value() ? &*it : nullptr;
282}
283
285
286int GameEventLog::queryType(const std::string& type) {
287 query_.clear();
288 for (const auto& event : events_)
289 if (event.type == type) query_.push_back(&event);
290 return static_cast<int>(query_.size());
291}
292
293int GameEventLog::querySource(const std::string& source) {
294 query_.clear();
295 for (const auto& event : events_)
296 if (event.source == source) query_.push_back(&event);
297 return static_cast<int>(query_.size());
298}
299
300int GameEventLog::querySubject(const std::string& subject) {
301 query_.clear();
302 for (const auto& event : events_)
303 if (event.subject == subject) query_.push_back(&event);
304 return static_cast<int>(query_.size());
305}
306
308 query_.clear();
309 for (const auto& event : events_)
310 if (event.sequence.value() >= firstSequence.value()) query_.push_back(&event);
311 return static_cast<int>(query_.size());
312}
313
314int GameEventLog::querySequence(uint64_t firstSequence) { return querySequence(EventSequence(firstSequence)); }
315
317 return index >= 0 && static_cast<size_t>(index) < query_.size() ? query_[static_cast<size_t>(index)] : nullptr;
318}
319
320int GameEventLog::size() const { return static_cast<int>(events_.size()); }
321
323 return index >= 0 && static_cast<size_t>(index) < events_.size() ? &events_[static_cast<size_t>(index)] : nullptr;
324}
325
327 consumers_.push_back(std::unique_ptr<EventConsumer>(new EventConsumer(this, firstSequence)));
328 return consumers_.back().get();
329}
330
331EventConsumer* GameEventLog::newConsumer(uint64_t firstSequence) { return newConsumer(EventSequence(firstSequence)); }
332
334 while (!events_.empty() && events_.front().sequence.value() < firstSequence.value()) events_.pop_front();
335 query_.clear();
336 for (auto& consumer : consumers_) consumer->batch_.clear();
337}
338
339void GameEventLog::clearBefore(uint64_t firstSequence) { clearBefore(EventSequence(firstSequence)); }
340
342 events_.clear();
343 query_.clear();
344 for (auto& consumer : consumers_) consumer->batch_.clear();
345}
346
348 clear();
349 nextSequence_ = EventSequence(1);
350 revision_ = eve::Revision::zero();
351 snapshotTick_ = eve::SimulationTick::zero();
352 for (auto& consumer : consumers_) consumer->seek(1);
353}
354
355std::string GameEventLog::snapshotJson() const {
356 std::ostringstream out;
357 out << "{\"version\":2,\"revision\":" << quote(std::to_string(revision_.value()))
358 << ",\"nextSequence\":" << quote(std::to_string(nextSequence_.value())) << ",\"events\":[";
359 bool first = true;
360 for (const auto& event : events_) {
361 if (!first) out << ',';
362 first = false;
363 out << "{\"eventId\":" << quote(event.eventId.format())
364 << ",\"sequence\":" << quote(std::to_string(event.sequence.value())) << ",\"type\":" << quote(event.type)
365 << ",\"source\":" << quote(event.source) << ",\"subject\":" << quote(event.subject)
366 << ",\"causationKind\":" << quote(causationKindName(event.causation.kind()))
367 << ",\"causation\":" << quote(event.causation.format())
368 << ",\"correlationKind\":" << quote(correlationKindName(event.correlation.kind()))
369 << ",\"correlation\":" << quote(event.correlation.format())
370 << ",\"schemaId\":" << quote(event.schemaId.format())
371 << ",\"schemaVersion\":" << quote(std::to_string(event.schemaVersion.value()))
372 << ",\"tick\":" << quote(std::to_string(event.tick.value())) << ",\"flags\":" << event.flags
373 << ",\"payload\":" << event.payload << '}';
374 }
375 return out.str() + "]}";
376}
377
379 std::string error;
380 auto document = eve::json::Document::parse(std::string(json), &error);
381 const auto root = document.root();
382 const auto invalid = [&](eve::DiagnosticCode code, std::string message) {
384 };
385 const int snapshotVersion = root.getInt("version");
386 if (!document.valid() || !root.isObject() || (snapshotVersion != 1 && snapshotVersion != 2)) {
387 return invalid(eve::DiagnosticCode::ParseError, error.empty() ? "invalid event stream snapshot" : error);
388 }
389 if (snapshotVersion == 2) {
390 auto schemaValidation = validateCurrentEventStream(json);
391 if (!schemaValidation.ok()) return schemaValidation;
392 }
393 uint64_t restoredNext = 0;
394 if (!parseU64(root.get("nextSequence"), restoredNext) || restoredNext == 0) {
395 return invalid(eve::DiagnosticCode::ParseError, "invalid nextSequence");
396 }
397 uint64_t restoredRevision = restoredNext - 1;
398 if (!root.get("revision").isNull() && !parseU64(root.get("revision"), restoredRevision))
399 return invalid(eve::DiagnosticCode::ParseError, "invalid revision");
400 const auto values = root.get("events");
401 if (!values.isArray()) {
402 return invalid(eve::DiagnosticCode::ParseError, "events must be an array");
403 }
404 std::deque<GameEvent> restored;
405 uint64_t previous = 0;
406 std::vector<std::string> restoredEventIds;
407 for (size_t i = 0; i < values.size(); ++i) {
408 const auto value = values.at(i);
409 GameEvent event;
410 int64_t restoredTick = 0;
411 uint64_t restoredSequence = 0;
412 if (!value.isObject() || !parseU64(value.get("sequence"), restoredSequence) || restoredSequence <= previous ||
413 !parseI64(value.get("tick"), restoredTick) || !value.get("flags").isNumber() || !value.get("payload")) {
414 return invalid(eve::DiagnosticCode::ParseError, "invalid event at index " + std::to_string(i));
415 }
416 event.sequence = EventSequence(restoredSequence);
417 if (restoredTick < 0) {
418 return invalid(eve::DiagnosticCode::ParseError, "invalid tick at index " + std::to_string(i));
419 }
420 event.tick = SimulationTick(static_cast<uint64_t>(restoredTick));
421 event.type = value.getString("type");
422 if (event.type.empty()) {
423 return invalid(eve::DiagnosticCode::ParseError, "event type must not be empty");
424 }
425 const std::string eventIdText = value.getString("eventId");
426 if (eventIdText.empty()) {
427 event.eventId = EventId::nil();
428 } else {
429 const auto parsedId = EventId::parse(eventIdText);
430 if (!parsedId)
431 return invalid(eve::DiagnosticCode::ParseError, "invalid eventId at index " + std::to_string(i));
432 event.eventId = *parsedId;
433 if (!event.eventId.isNil()) {
434 const auto formattedId = event.eventId.format();
435 if (std::find(restoredEventIds.begin(), restoredEventIds.end(), formattedId) != restoredEventIds.end())
436 return invalid(eve::DiagnosticCode::Conflict,
437 "duplicate non-nil eventId at index " + std::to_string(i));
438 restoredEventIds.push_back(formattedId);
439 }
440 }
441 event.source = value.getString("source");
442 event.subject = value.getString("subject");
443 const std::string causationText = value.getString("causation");
444 const std::string correlationText = value.getString("correlation");
445 const std::string causationKind =
446 snapshotVersion == 1 ? (causationText.empty() ? "none" : "legacy") : value.getString("causationKind");
447 const std::string correlationKind =
448 snapshotVersion == 1 ? (correlationText.empty() ? "none" : "legacy") : value.getString("correlationKind");
449 if (causationKind != "none" && causationKind != "event" && causationKind != "command" &&
450 causationKind != "legacy")
451 return invalid(eve::DiagnosticCode::ParseError, "invalid causation kind at index " + std::to_string(i));
452 if (correlationKind != "none" && correlationKind != "id" && correlationKind != "legacy")
453 return invalid(eve::DiagnosticCode::ParseError, "invalid correlation kind at index " + std::to_string(i));
454 if ((causationKind == "none" && !causationText.empty()) || (causationKind != "none" && causationText.empty()) ||
455 (correlationKind == "none" && !correlationText.empty()) ||
456 (correlationKind != "none" && correlationText.empty()))
457 return invalid(eve::DiagnosticCode::ParseError,
458 "causal reference value/kind mismatch at index " + std::to_string(i));
459 event.causation = causationFromSnapshot(causationKind, causationText);
460 event.correlation = correlationFromSnapshot(correlationKind, correlationText);
461 if ((causationKind == "event" || causationKind == "command") &&
463 return invalid(eve::DiagnosticCode::ParseError, "invalid causation ID at index " + std::to_string(i));
464 if (correlationKind == "id" && event.correlation.kind() == CorrelationId::Kind::None)
465 return invalid(eve::DiagnosticCode::ParseError, "invalid correlation ID at index " + std::to_string(i));
466 const std::string schemaIdText = value.getString("schemaId");
467 if (schemaIdText.empty()) {
468 event.schemaId = eve::LogicalId::fromParts("game_event", event.type).value_or(eve::LogicalId());
469 } else {
470 const auto parsedSchema = eve::LogicalId::parse(schemaIdText);
471 if (!parsedSchema)
472 return invalid(eve::DiagnosticCode::ParseError, "invalid schemaId at index " + std::to_string(i));
473 event.schemaId = *parsedSchema;
474 }
475 uint64_t restoredSchemaVersion = snapshotVersion == 1 ? 1 : 0;
476 if (snapshotVersion == 2 &&
477 (!parseU64(value.get("schemaVersion"), restoredSchemaVersion) || restoredSchemaVersion == 0)) {
478 return invalid(eve::DiagnosticCode::ParseError, "invalid schemaVersion at index " + std::to_string(i));
479 }
480 event.schemaVersion = SchemaVersion(restoredSchemaVersion);
481 const double flags = value.getDouble("flags", -1.0);
482 if (flags < 0 || flags > std::numeric_limits<uint32_t>::max() || std::floor(flags) != flags) {
483 return invalid(eve::DiagnosticCode::ParseError, "invalid flags at index " + std::to_string(i));
484 }
485 event.flags = static_cast<uint32_t>(flags);
486 event.payload = canonicalJson(value.get("payload"));
487 previous = event.sequence.value();
488 restored.push_back(std::move(event));
489 }
490 if (!restored.empty() && restored.back().sequence.value() >= restoredNext) {
491 return invalid(eve::DiagnosticCode::ParseError, "nextSequence must exceed retained events");
492 }
493 events_ = std::move(restored);
494 nextSequence_ = EventSequence(restoredNext);
495 revision_ = eve::Revision(restoredRevision);
496 snapshotTick_ = eve::SimulationTick::zero();
497 for (const auto& event : events_)
498 if (event.tick > snapshotTick_) snapshotTick_ = event.tick;
499 query_.clear();
500 consumers_.clear();
502}
503
507 return eve::makeSnapshotEnvelope("game_event.stream", eventStreamSchema(), eve::SchemaVersion(1), instanceId_,
508 revision_, snapshotTick_, std::move(payload).takeValue(), hashProvider);
509}
510
512 const eve::SnapshotHashProvider& hashProvider) {
513 if (source.type != "game_event.stream" || source.schema != eventStreamSchema())
515 eve::DiagnosticCode::InvalidArgument, "snapshot does not belong to game_event::GameEventLog"));
516 if (!instanceId_.isNil() && source.instanceId != instanceId_)
518 eve::DiagnosticCode::Conflict, "snapshot instanceId does not match game_event::GameEventLog"));
519 auto migrated = eventStreamMigrations().migrate(source, eve::SchemaVersion(1), hashProvider);
520 if (!migrated.ok()) return eve::Result<void>::failure(migrated.status());
521 auto metadata = eve::validateSnapshotPayloadMetadata(migrated.value().payload, migrated.value().revision,
522 migrated.value().tick);
523 if (!metadata.ok()) return eve::Result<void>::failure(metadata.status());
524 auto payload = migrated.value().payload.toJson();
525 if (!payload.ok()) return eve::Result<void>::failure(payload.status());
526
527 GameEventLog candidate(instanceId_);
528 candidate.eventIdGenerator_ = eventIdGenerator_;
529 auto restored = candidate.restore(std::move(payload).takeValue());
530 if (!restored.ok()) return eve::Result<void>::failure(restored.status());
531 if (candidate.snapshotTick_ != migrated.value().tick)
533 eve::DiagnosticCode::Conflict, "event stream payload tick disagrees with snapshot envelope"));
534 candidate.instanceId_ = migrated.value().instanceId;
535 candidate.revision_ = migrated.value().revision;
536 candidate.snapshotTick_ = migrated.value().tick;
537 // The UUID generator is a runtime capability, not persisted state. Keep
538 // it across the atomic payload replacement and invalidate old cursors.
539 eventIdGenerator_ = std::move(candidate.eventIdGenerator_);
540 instanceId_ = candidate.instanceId_;
541 revision_ = candidate.revision_;
542 snapshotTick_ = candidate.snapshotTick_;
543 nextSequence_ = candidate.nextSequence_;
544 events_ = std::move(candidate.events_);
545 query_.clear();
546 consumers_.clear();
548}
549
551 auto value = snapshot(hashProvider);
552 if (!value.ok()) return eve::Result<std::string>::failure(value.status());
553 return std::move(value).andThen(
554 [](eve::SnapshotEnvelope&& envelope) { return eve::serializeSnapshotEnvelope(envelope); });
555}
556
558 const eve::SnapshotHashProvider& hashProvider) {
559 auto source = eve::parseSnapshotEnvelope(json, hashProvider);
560 if (!source.ok()) return eve::Result<void>::failure(source.status());
561 return restoreSnapshot(std::move(source).takeValue(), hashProvider);
562}
563
564EventSequence GameEventLog::oldestSequence() const {
565 return events_.empty() ? nextSequence_ : events_.front().sequence;
566}
567
569 auto* module = GameEventModule::create();
570 module->streams_.push_back(std::make_unique<GameEventLog>());
571 return module->streams_.back().get();
572}
573
575 GameEventModule::expose);
576GameEventModule* GameEventModule::create() {
577 auto* existing = ModuleManager::find(name);
578 if (existing) return static_cast<GameEventModule*>(existing);
579 auto* module = new GameEventModule();
581 return module;
582}
583const char* GameEventModule::name = "GameEvent";
584
585void GameEventModule::expose(ssq::Table& table) {
586 auto envelope = table.addClass<GameEvent>(
587 "GameEventRecord", std::function<GameEvent*()>([]() -> GameEvent* { return nullptr; }), false);
588 envelope.addFunc("getEventId", [](GameEvent* e) { return e ? e->eventId.format() : std::string{}; });
589 envelope.addFunc("getSequence",
590 [](GameEvent* e) { return e ? static_cast<int64_t>(e->sequence.value()) : int64_t{0}; });
591 envelope.addFunc("getType", [](GameEvent* e) { return e ? e->type : std::string{}; });
592 envelope.addFunc("getSource", [](GameEvent* e) { return e ? e->source : std::string{}; });
593 envelope.addFunc("getSubject", [](GameEvent* e) { return e ? e->subject : std::string{}; });
594 envelope.addFunc("getCausation", [](GameEvent* e) { return e ? e->causation.format() : std::string{}; });
595 envelope.addFunc("getCausationKind", [](GameEvent* e) {
596 return e ? std::string(causationKindName(e->causation.kind())) : std::string{};
597 });
598 envelope.addFunc("getCorrelation", [](GameEvent* e) { return e ? e->correlation.format() : std::string{}; });
599 envelope.addFunc("getCorrelationKind", [](GameEvent* e) {
600 return e ? std::string(correlationKindName(e->correlation.kind())) : std::string{};
601 });
602 envelope.addFunc("getSchemaId", [](GameEvent* e) { return e ? e->schemaId.format() : std::string{}; });
603 envelope.addFunc("getSchemaVersion",
604 [](GameEvent* e) { return e ? static_cast<int64_t>(e->schemaVersion.value()) : int64_t{0}; });
605 envelope.addFunc("getTick", [](GameEvent* e) { return e ? static_cast<int64_t>(e->tick.value()) : int64_t{0}; });
606 envelope.addFunc("getFlags", [](GameEvent* e) { return e ? static_cast<int64_t>(e->flags) : int64_t{0}; });
607 envelope.addFunc("getPayload", [](GameEvent* e) { return e ? e->payload : std::string{}; });
608
609 auto consumer = table.addClass<EventConsumer>(
610 "EventConsumer", std::function<EventConsumer*()>([]() -> EventConsumer* { return nullptr; }), false);
611 consumer.addFunc("read", &EventConsumer::read);
612 consumer.addFunc("batchCount", &EventConsumer::batchCount);
613 consumer.addFunc("batchAt", [](EventConsumer* c, int index) -> GameEvent* {
614 return c ? const_cast<GameEvent*>(c->batchAt(index)) : nullptr;
615 });
616 consumer.addFunc("position",
617 [](EventConsumer* c) { return c ? static_cast<int64_t>(c->position().value()) : int64_t{0}; });
618 consumer.addFunc("seek", [](EventConsumer* c, int64_t sequence) {
619 if (c) c->seek(sequence > 0 ? uint64_t(sequence) : 1);
620 });
621
622 auto stream = table.addClass<GameEventLog>(
623 "GameEventLog", std::function<GameEventLog*()>([]() -> GameEventLog* { return nullptr; }), false);
624 const HSQUIRRELVM vm = table.getHandle();
625 stream.addFunc("append", [vm](GameEventLog* s, const std::string& eventId, const std::string& type,
626 const std::string& source, const std::string& subject, const std::string& causation,
627 const std::string& correlation, int64_t tick, int64_t flags,
628 const std::string& payload) {
629 if (!s) {
631 vm,
633 "event stream must not be null", "stream")),
634 [](EventSequence) { return eve::Value::null(); });
635 }
636 if (tick < 0 || flags < 0 || static_cast<std::uint64_t>(flags) > std::numeric_limits<std::uint32_t>::max()) {
638 vm,
641 "event tick and flags must be non-negative and in range", "envelope")),
642 [](EventSequence) { return eve::Value::null(); });
643 }
644 GameEvent envelope;
645 if (!eventId.empty()) {
646 const auto parsed = EventId::parse(eventId);
647 if (!parsed) {
649 vm,
651 "eventId must be a UUID", "eventId")),
652 [](EventSequence) { return eve::Value::null(); });
653 }
654 envelope.eventId = *parsed;
655 }
656 envelope.type = type;
657 envelope.source = source;
658 envelope.subject = subject;
659 if (!causation.empty()) {
660 const auto parsed = EventId::parse(causation);
661 envelope.causation = parsed ? CausationRef::fromEventId(*parsed) : CausationRef::fromLegacy(causation);
662 }
663 if (!correlation.empty()) {
664 const auto parsed = EventId::parse(correlation);
665 envelope.correlation =
666 parsed ? CorrelationId::fromEventId(*parsed) : CorrelationId::fromLegacy(correlation);
667 }
668 const auto schema = eve::LogicalId::fromParts("game_event", type);
669 if (schema) envelope.schemaId = *schema;
670 envelope.schemaVersion = SchemaVersion(1);
671 envelope.tick = SimulationTick(static_cast<std::uint64_t>(tick));
672 envelope.flags = static_cast<std::uint32_t>(flags);
673 envelope.payload = payload;
674 return eve::script::projectResult(vm, s->append(std::move(envelope)), [](EventSequence sequence) {
675 return eve::Value::integer(static_cast<std::int64_t>(sequence.value()));
676 });
677 });
678 stream.addFunc("find", [](GameEventLog* s, int64_t sequence) -> GameEvent* {
679 return s && sequence > 0 ? const_cast<GameEvent*>(s->find(uint64_t(sequence))) : nullptr;
680 });
681 stream.addFunc("queryType", &GameEventLog::queryType);
682 stream.addFunc("querySource", &GameEventLog::querySource);
683 stream.addFunc("querySubject", &GameEventLog::querySubject);
684 stream.addFunc("querySequence", [](GameEventLog* s, int64_t sequence) {
685 return s ? s->querySequence(sequence > 0 ? uint64_t(sequence) : 1) : 0;
686 });
687 stream.addFunc("queryAt", [](GameEventLog* s, int index) -> GameEvent* {
688 return s ? const_cast<GameEvent*>(s->queryAt(index)) : nullptr;
689 });
690 stream.addFunc("size", &GameEventLog::size);
691 stream.addFunc("at", [](GameEventLog* s, int index) -> GameEvent* {
692 return s ? const_cast<GameEvent*>(s->at(index)) : nullptr;
693 });
694 stream.addFunc("newConsumer", [](GameEventLog* s, int64_t sequence) {
695 return s ? s->newConsumer(sequence > 0 ? uint64_t(sequence) : 1) : nullptr;
696 });
697 stream.addFunc("clearBefore", [](GameEventLog* s, int64_t sequence) {
698 if (s) s->clearBefore(sequence > 0 ? uint64_t(sequence) : 1);
699 });
700 stream.addFunc("clear", &GameEventLog::clear);
701 stream.addFunc("reset", &GameEventLog::reset);
702 stream.addFunc("snapshotJson", &GameEventLog::snapshotJson);
703 stream.addFunc("restore", [vm = table.getHandle()](GameEventLog* stream, const std::string& json) {
704 if (!stream)
707 "game event log must not be null")));
708 return eve::script::projectResult(vm, stream->restore(json));
709 });
710
711 auto cls = table.addClass(name, GameEventModule::create, false);
712 expose(cls);
713}
714
715void GameEventModule::expose(ssq::Class& cls) {
716 cls.addFunc("getName", &GameEventModule::getName);
717 cls.addFunc("newLog", [](GameEventModule*) { return GameEventModule::newLog(); });
718}
719
720} // namespace eve::game_event
Value::Object payload
int root
Definition AnimSmr.cpp:119
int subject
Definition AnimSmr.cpp:163
const std::string & s
struct SQVM * HSQUIRRELVM
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
std::string name
Definition ECS.cpp:154
std::string message
DiagnosticCode code
std::int32_t c
std::int32_t first
char quote
bool required
Poco::JSON::Object::Ptr result
uint64_t used
std::shared_ptr< const OceanSprayFrame > previous
std::unique_ptr< gpgpu::Sequence > sequence
Definition OnnxGpgpu.cpp:43
std::string error
Definition Package.cpp:174
std::vector< particles::ParticleRecordEvent > events
std::set< std::string > values
Object::Ptr value
std::string text
ScriptStructure out
std::string_view source
std::string kind
std::string string
The single Squirrel projection for common Result, Status and Value.
SimulationTick tick
uint32_t index
uint32_t flags
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Human-readable, scoped identifier in the form namespace:name.
Definition Identity.h:414
static std::optional< LogicalId > fromParts(std::string_view namespaceName, std::string_view name)
Builds a logical ID from separate namespace and name components.
Definition Identity.cpp:49
static std::optional< LogicalId > parse(std::string_view text)
Parses a scoped logical name.
Definition Identity.cpp:37
bool isValid() const noexcept
Returns whether this value contains a valid namespace and name.
Definition Identity.h:436
Module *(* creator_t)()
Definition Module.h:59
static Module * find(const char *name)
Finds a live module instance by name, or nullptr. @ownership Borrowed; ModuleManager owns the returne...
static void insert(const char *name, Module *inst)
Stores a module instance under a name (used by Module_IMPL).
virtual std::string getName() const =0
Returns the name.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
One directed payload migration step.
Definition Snapshot.h:145
Result< void > add(LogicalId schema, SchemaVersion from, SchemaVersion to, Migration migration)
Register one schema-local migration edge.
Definition Snapshot.cpp:196
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
static Value null()
Compatibility factory for a null value.
Definition Value.h:113
static Result< Value > fromJson(std::string_view json)
Parse one strict JSON value into an owning Value.
Definition Value.cpp:177
std::map< std::string, Value > Object
Definition Value.h:34
static constexpr Id128 nil() noexcept
Returns the all-zero nil value.
Definition Identity.h:141
constexpr bool isNil() const noexcept
Returns whether this value is the all-zero nil ID.
Definition Identity.h:175
static std::optional< Id128 > parse(std::string_view text) noexcept
Parses canonical UUID text.
Definition Identity.h:150
static constexpr Id128 fromUuid(const Id128< OtherTag > &value) noexcept
Re-tags an existing UUID at an explicit domain boundary.
Definition Identity.h:135
constexpr std::optional< StrongUint64 > incremented() const noexcept
Returns the next value, or empty instead of unsigned wraparound.
constexpr std::uint64_t value() const noexcept
Returns the underlying value at an explicit protocol boundary.
static constexpr StrongUint64 zero() noexcept
Returns the zero value for this strong type.
constexpr bool isZero() const noexcept
Returns whether this value is zero.
static CausationRef fromEventId(EventId value)
Creates a causation reference to an event.
Definition GameEvent.h:106
static CausationRef fromLegacy(std::string value)
Creates a compatibility-only arbitrary string causation.
Definition GameEvent.h:126
Kind kind() const noexcept
Returns the tagged causation kind.
Definition GameEvent.h:134
static CausationRef fromCommandId(CommandId value)
Creates a causation reference to a command.
Definition GameEvent.h:116
Kind kind() const noexcept
Returns the tagged correlation kind.
Definition GameEvent.h:75
static CorrelationId fromLegacy(std::string value)
Creates a compatibility-only arbitrary string correlation.
Definition GameEvent.h:67
static CorrelationId fromEventId(EventId value)
Creates a canonical correlation ID from an EventId.
Definition GameEvent.h:59
Independent sequence cursor used to consume an GameEventLog in batches.
Definition GameEvent.h:225
int read(int maxCount)
Reads at most maxCount events and advances past the returned batch.
int batchCount() const
Returns the number of events in the most recent batch.
Deterministic in-memory stream of topic-neutral event envelopes.
Definition GameEvent.h:262
const GameEvent * queryAt(int index) const
Returns one result from the latest query, or nullptr.
int queryType(const std::string &type)
Queries all retained events of a type in sequence order.
const GameEvent * at(int index) const
Returns a retained event by stream order, or nullptr.
eve::Result< eve::SnapshotEnvelope > snapshot(const eve::SnapshotHashProvider &hashProvider) const
Captures the stream payload in the common snapshot envelope.
void clearBefore(EventSequence firstSequence)
Removes retained events with sequence lower than firstSequence.
int size() const
Returns the number of retained events.
eve::Result< std::string > snapshotEnvelopeJson(const eve::SnapshotHashProvider &hashProvider) const
Serializes the common event-stream snapshot envelope.
eve::Result< EventSequence > append(GameEvent envelope)
Appends a typed-metadata envelope and assigns stream-local order.
const GameEvent * find(EventSequence sequence) const
Returns an event by exact sequence, or nullptr. @ownership Borrowed from this stream; callers must no...
EventConsumer * newConsumer(EventSequence firstSequence=EventSequence(1))
Creates an independently positioned consumer cursor.
void clear()
Removes retained events while preserving the next sequence number.
std::string snapshotJson() const
Exports stream state as deterministic compact JSON.
int querySource(const std::string &source)
Queries all retained events from a source in sequence order.
eve::Result< void > restoreSnapshotJson(std::string_view json, const eve::SnapshotHashProvider &hashProvider)
Parses and transactionally restores a common event-stream envelope.
int querySubject(const std::string &subject)
Queries all retained events concerning a subject in sequence order.
eve::Result< void > restoreSnapshot(const eve::SnapshotEnvelope &snapshot, const eve::SnapshotHashProvider &hashProvider)
Restores a verified or migrated stream envelope atomically.
int querySequence(EventSequence firstSequence)
Queries retained events whose sequence is at least firstSequence.
eve::Result< void > restore(std::string_view json)
Transactionally restores stream state from a snapshot.
void reset()
Removes all state and restarts sequence allocation at one.
Script module factory for generic GameEventLog objects.
Definition GameEvent.h:410
static GameEventLog * newLog()
Allocates a module-owned event stream. @ownership Borrowed from the manager-owned GameEvent module; t...
GameEventModule()=default
Constructs a GameEventModule.
static Document parse(const std::string &text, std::string *error=nullptr)
Parse.
Definition Json.cpp:623
EVENGINE_API_FOUNDATION public API.
Definition Json.h:39
static eve::Result< SchemaRegistrationStatus > registerVersioned(const SchemaDefinition &definition)
Registers a new exact (id, version) entry without replacing it.
static std::vector< ValidationError > validate(const std::string &schemaId, const std::string &json)
Validates JSON text against the highest registered schema version.
static const SchemaDefinition * resolve(const std::string &schemaId, int schemaVersion)
Resolves one exact (schemaId, schemaVersion) pair, or nullptr.
void keys(const Value &value, std::initializer_list< const char * > names)
eve::SimulationTick SimulationTick
Definition GameEvent.h:30
eve::EventSequence EventSequence
Definition GameEvent.h:29
eve::SchemaVersion SchemaVersion
Definition GameEvent.h:32
ModuleRegister GameEventModule_register("GameEvent",(ModuleManager::creator_t)(GameEventModule::create), GameEventModule::expose)
std::string quoteString(std::string_view value, StringEscapeStyle style)
Encode an owning JSON string using the canonical serializer's escaping implementation.
Definition Json.cpp:576
Result< UnsignedIntegerScan > scanUnsignedInteger(std::string_view text, UnsignedIntegerSyntax syntax)
Scan an unsigned integer prefix without mutating caller state.
Definition Json.cpp:583
std::unordered_map< std::string, SkillDefinition > & table()
Definition Skill.cpp:73
ValueType
JSON-compatible value kinds understood by a schema field.
Definition SchemaTypes.h:16
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
std::vector< DiagnosticDetail > DiagnosticDetails
Owning collection of diagnostic details with stable insertion order.
Definition Diagnostic.h:88
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
Result< void > validateSnapshotPayloadMetadata(const Value &payload, Revision revision, SimulationTick tick)
Validate optional payload copies of envelope revision and tick.
Definition Snapshot.cpp:80
std::function< std::chrono::system_clock::time_point()> UuidClock
Clock callback used by the injectable UUIDv7 generator.
Definition UuidV7.h:29
Result< SnapshotEnvelope > parseSnapshotEnvelope(std::string_view json, const SnapshotHashProvider &hashProvider)
Parse and verify an envelope from canonical or compatible JSON text.
Definition Snapshot.cpp:190
Result< std::string > serializeSnapshotEnvelope(const SnapshotEnvelope &snapshot)
Serialize an envelope as deterministic compact JSON.
Definition Snapshot.cpp:184
std::function< bool(std::span< std::uint8_t > bytes)> UuidEntropySource
Entropy callback used by UUIDv7 generation.
Definition UuidV7.h:26
Result< SnapshotEnvelope > makeSnapshotEnvelope(std::string type, LogicalId schema, SchemaVersion schemaVersion, PersistentId instanceId, Revision revision, SimulationTick tick, Value payload, const SnapshotHashProvider &hashProvider)
Construct and seal a snapshot envelope.
Definition Snapshot.cpp:103
detail::StrongUint64< detail::RevisionTag > Revision
Monotonic content/state revision used for optimistic-concurrency checks.
Definition Revision.h:13
detail::StrongUint64< detail::EventSequenceTag > EventSequence
Stream-local event ordering value; it is not a global event identity.
std::function< Result< ContentId >(std::string_view canonicalInput)> SnapshotHashProvider
Injected content-digest implementation used by snapshots.
Definition Snapshot.h:36
EVENGINE_API_FOUNDATION public API.
Definition Module.h:223
Stable outer format shared by persistence and cross-process snapshots.
Definition Snapshot.h:46
Envelope metadata shared by event domains.
Definition GameEvent.h:184
std::string type
Compatibility event name and diagnostic topic.
Definition GameEvent.h:190
EventSequence sequence
Sequence assigned by the owning stream; it is never global identity.
Definition GameEvent.h:188
EventId eventId
Stable event identity; nil is allowed only for legacy transient events.
Definition GameEvent.h:186
std::string payload
Canonical serialized payload at the stream persistence boundary.
Definition GameEvent.h:208
SchemaVersion schemaVersion
Version of the payload schema, not a stream or runtime generation.
Definition GameEvent.h:202
SchemaId schemaId
Logical schema identifier for the typed payload codec.
Definition GameEvent.h:200
CorrelationId correlation
Business workflow correlation reference.
Definition GameEvent.h:198
CausationRef causation
Direct causation reference, normally an event or command ID.
Definition GameEvent.h:196
Metadata and validation constraints for one object member.
Definition SchemaTypes.h:77
Versioned runtime schema for a JSON object.
Definition SchemaTypes.h:93
std::vector< FieldDefinition > fields
Definition SchemaTypes.h:99
Recursive node in the deliberately small Eve Schema language.
Definition SchemaTypes.h:47
ValueType type
The value kind accepted by this node.
Definition SchemaTypes.h:49
std::shared_ptr< const SchemaDefinition > objectSchema
Inline object shape for an object node.
Definition SchemaTypes.h:57