载入中...
搜索中...
未找到
GameEvent.cpp
浏览该文件的文档.
20eve::schema::FieldDefinition schemaField(std::string name, eve::schema::ValueType type, bool required = true) {
49 eventNode.objectSchema = std::make_shared<const eve::schema::SchemaDefinition>(std::move(event));
71 auto registration = eve::schema::SchemaRegistry::registerVersioned(eventStreamSchemaDefinition());
79 eve::DiagnosticDetails{{"schemaId", id}, {"schemaVersion", "1"}, {"validationCode", error.code}},
259 if (envelope.type.empty()) return failure(eve::DiagnosticCode::InvalidArgument, "event type must not be empty");
261 return failure(eve::DiagnosticCode::InvalidArgument, "event schemaId must be a valid logical ID");
265 if (!payloadDocument.valid()) return failure(eve::DiagnosticCode::ParseError, "payload must be valid JSON");
268 if (!revision_.incremented()) return failure(eve::DiagnosticCode::Failed, "event stream revision exhausted");
303const GameEvent* GameEventLog::find(uint64_t sequence) const { return find(EventSequence(sequence)); }
333int GameEventLog::querySequence(uint64_t firstSequence) { return querySequence(EventSequence(firstSequence)); }
350EventConsumer* GameEventLog::newConsumer(uint64_t firstSequence) { return newConsumer(EventSequence(firstSequence)); }
353 while (!events_.empty() && events_.front().sequence.value() < firstSequence.value()) events_.pop_front();
358void GameEventLog::clearBefore(uint64_t firstSequence) { clearBefore(EventSequence(firstSequence)); }
406 return invalid(eve::DiagnosticCode::ParseError, error.empty() ? "invalid event stream snapshot" : error);
431 if (!value.isObject() || !parseU64(value.get("sequence"), restoredSequence) || restoredSequence <= previous ||
432 !parseI64(value.get("tick"), restoredTick) || !value.get("flags").isNumber() || !value.get("payload")) {
450 return invalid(eve::DiagnosticCode::ParseError, "invalid eventId at index " + std::to_string(i));
454 if (std::find(restoredEventIds.begin(), restoredEventIds.end(), formattedId) != restoredEventIds.end())
465 snapshotVersion == 1 ? (causationText.empty() ? "none" : "legacy") : value.getString("causationKind");
467 snapshotVersion == 1 ? (correlationText.empty() ? "none" : "legacy") : value.getString("correlationKind");
470 return invalid(eve::DiagnosticCode::ParseError, "invalid causation kind at index " + std::to_string(i));
472 return invalid(eve::DiagnosticCode::ParseError, "invalid correlation kind at index " + std::to_string(i));
473 if ((causationKind == "none" && !causationText.empty()) || (causationKind != "none" && causationText.empty()) ||
482 return invalid(eve::DiagnosticCode::ParseError, "invalid causation ID at index " + std::to_string(i));
484 return invalid(eve::DiagnosticCode::ParseError, "invalid correlation ID at index " + std::to_string(i));
487 event.schemaId = eve::LogicalId::fromParts("game_event", event.type).value_or(eve::LogicalId());
491 return invalid(eve::DiagnosticCode::ParseError, "invalid schemaId at index " + std::to_string(i));
497 return invalid(eve::DiagnosticCode::ParseError, "invalid schemaVersion at index " + std::to_string(i));
523eve::Result<eve::SnapshotEnvelope> GameEventLog::snapshot(const eve::SnapshotHashProvider& hashProvider) const {
526 return eve::makeSnapshotEnvelope("game_event.stream", eventStreamSchema(), eve::SchemaVersion(1), instanceId_,
540 auto metadata = eve::validateSnapshotPayloadMetadata(migrated.value().payload, migrated.value().revision,
569eve::Result<std::string> GameEventLog::snapshotEnvelopeJson(const eve::SnapshotHashProvider& hashProvider) const {
593ModuleRegister GameEventModule_register("GameEvent", (ModuleManager::creator_t)(GameEventModule::create),
607 envelope.addFunc("getEventId", [](GameEvent* e) { return e ? e->eventId.format() : std::string{}; });
613 envelope.addFunc("getCausation", [](GameEvent* e) { return e ? e->causation.format() : std::string{}; });
617 envelope.addFunc("getCorrelation", [](GameEvent* e) { return e ? e->correlation.format() : std::string{}; });
621 envelope.addFunc("getSchemaId", [](GameEvent* e) { return e ? e->schemaId.format() : std::string{}; });
624 envelope.addFunc("getTick", [](GameEvent* e) { return e ? static_cast<int64_t>(e->tick.value()) : int64_t{0}; });
625 envelope.addFunc("getFlags", [](GameEvent* e) { return e ? static_cast<int64_t>(e->flags) : int64_t{0}; });
629 "EventConsumer", std::function<EventConsumer*()>([]() -> EventConsumer* { return nullptr; }), false);
642 "GameEventLog", std::function<GameEventLog*()>([]() -> GameEventLog* { return nullptr; }), false);
644 stream.addFunc("append", [vm](GameEventLog* s, const std::string& eventId, const std::string& type,
651 eve::Result<EventSequence>::failure(eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument,
655 if (tick < 0 || flags < 0 || static_cast<std::uint64_t>(flags) > std::numeric_limits<std::uint32_t>::max()) {
669 eve::Result<EventSequence>::failure(eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument,
680 envelope.causation = parsed ? CausationRef::fromEventId(*parsed) : CausationRef::fromLegacy(causation);
693 return eve::script::projectResult(vm, s->append(std::move(envelope)), [](EventSequence sequence) {
722 stream.addFunc("restore", [vm = table.getHandle()](GameEventLog* stream, const std::string& json) {
The single Squirrel projection for common Result, Status and Value.
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={}, DiagnosticDetails details={}, std::string source={})
Construct an error diagnostic with the standard error severity.
Definition Diagnostic.h:125
Human-readable, scoped identifier in the form namespace:name.
Definition Identity.h:411
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:48
static std::optional< LogicalId > parse(std::string_view text)
Parses a scoped logical name.
Definition Identity.cpp:36
bool isValid() const noexcept
Returns whether this value contains a valid namespace and name.
Definition Identity.h:433
static Module * find(const char *name)
Finds a live module instance by name, or nullptr. @ownership Borrowed; ModuleManager owns the returne...
Definition Module.cpp:175
static void insert(const char *name, Module *inst)
Stores a module instance under a name (used by Module_IMPL).
Definition Module.cpp:194
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:175
Result< void > add(LogicalId schema, SchemaVersion from, SchemaVersion to, Migration migration)
Register one schema-local migration edge.
Definition Snapshot.cpp:196
static Result< Value > fromJson(std::string_view json)
Parse one strict JSON value into an owning Value.
Definition Value.cpp:57
constexpr bool isNil() const noexcept
Returns whether this value is the all-zero nil ID.
Definition Identity.h:176
static std::optional< Id128 > parse(std::string_view text) noexcept
Parses canonical UUID text.
Definition Identity.h:151
static constexpr Id128 fromUuid(const Id128< OtherTag > &value) noexcept
Re-tags an existing UUID at an explicit domain boundary.
Definition Identity.h:136
constexpr std::optional< StrongUint64 > incremented() const noexcept
Returns the next value, or empty instead of unsigned wraparound.
Definition StrongUint64.h:30
constexpr std::uint64_t value() const noexcept
Returns the underlying value at an explicit protocol boundary.
Definition StrongUint64.h:26
static constexpr StrongUint64 zero() noexcept
Returns the zero value for this strong type.
Definition StrongUint64.h:24
constexpr bool isZero() const noexcept
Returns whether this value is zero.
Definition StrongUint64.h:28
static CausationRef fromEventId(EventId value)
Creates a causation reference to an event.
Definition GameEvent.h:105
static CausationRef fromLegacy(std::string value)
Creates a compatibility-only arbitrary string causation.
Definition GameEvent.h:125
static CausationRef fromCommandId(CommandId value)
Creates a causation reference to a command.
Definition GameEvent.h:115
static CorrelationId fromLegacy(std::string value)
Creates a compatibility-only arbitrary string correlation.
Definition GameEvent.h:66
static CorrelationId fromEventId(EventId value)
Creates a canonical correlation ID from an EventId.
Definition GameEvent.h:58
Independent sequence cursor used to consume an GameEventLog in batches.
Definition GameEvent.h:224
int read(int maxCount)
Reads at most maxCount events and advances past the returned batch.
Definition GameEvent.cpp:224
int batchCount() const
Returns the number of events in the most recent batch.
Definition GameEvent.cpp:237
Deterministic in-memory stream of topic-neutral event envelopes.
Definition GameEvent.h:261
const GameEvent * queryAt(int index) const
Returns one result from the latest query, or nullptr.
Definition GameEvent.cpp:335
int queryType(const std::string &type)
Queries all retained events of a type in sequence order.
Definition GameEvent.cpp:305
const GameEvent * at(int index) const
Returns a retained event by stream order, or nullptr.
Definition GameEvent.cpp:341
eve::Result< eve::SnapshotEnvelope > snapshot(const eve::SnapshotHashProvider &hashProvider) const
Captures the stream payload in the common snapshot envelope.
Definition GameEvent.cpp:523
void clearBefore(EventSequence firstSequence)
Removes retained events with sequence lower than firstSequence.
Definition GameEvent.cpp:352
eve::Result< std::string > snapshotEnvelopeJson(const eve::SnapshotHashProvider &hashProvider) const
Serializes the common event-stream snapshot envelope.
Definition GameEvent.cpp:569
eve::Result< EventSequence > append(GameEvent envelope)
Appends a typed-metadata envelope and assigns stream-local order.
Definition GameEvent.cpp:255
const GameEvent * find(EventSequence sequence) const
Returns an event by exact sequence, or nullptr. @ownership Borrowed from this stream; callers must no...
Definition GameEvent.cpp:296
EventConsumer * newConsumer(EventSequence firstSequence=EventSequence(1))
Creates an independently positioned consumer cursor.
Definition GameEvent.cpp:345
void clear()
Removes retained events while preserving the next sequence number.
Definition GameEvent.cpp:360
std::string snapshotJson() const
Exports stream state as deterministic compact JSON.
Definition GameEvent.cpp:374
int querySource(const std::string &source)
Queries all retained events from a source in sequence order.
Definition GameEvent.cpp:312
eve::Result< void > restoreSnapshotJson(std::string_view json, const eve::SnapshotHashProvider &hashProvider)
Parses and transactionally restores a common event-stream envelope.
Definition GameEvent.cpp:576
int querySubject(const std::string &subject)
Queries all retained events concerning a subject in sequence order.
Definition GameEvent.cpp:319
eve::Result< void > restoreSnapshot(const eve::SnapshotEnvelope &snapshot, const eve::SnapshotHashProvider &hashProvider)
Restores a verified or migrated stream envelope atomically.
Definition GameEvent.cpp:530
int querySequence(EventSequence firstSequence)
Queries retained events whose sequence is at least firstSequence.
Definition GameEvent.cpp:326
eve::Result< void > restore(std::string_view json)
Transactionally restores stream state from a snapshot.
Definition GameEvent.cpp:397
Script module factory for generic GameEventLog objects.
Definition GameEvent.h:409
static GameEventLog * newLog()
Allocates a module-owned event stream. @ownership Borrowed from the manager-owned GameEvent module; t...
Definition GameEvent.cpp:587
GameEventModule()=default
Constructs a GameEventModule.
static Document parse(const std::string &text, std::string *error=nullptr)
Parse.
Definition Json.cpp:581
static eve::Result< SchemaRegistrationStatus > registerVersioned(const SchemaDefinition &definition)
Registers a new exact (id, version) entry without replacing it.
Definition SchemaRegistry.cpp:864
static std::vector< ValidationError > validate(const std::string &schemaId, const std::string &json)
Validates JSON text against the highest registered schema version.
Definition SchemaRegistry.cpp:955
static const SchemaDefinition * resolve(const std::string &schemaId, int schemaVersion)
Resolves one exact (schemaId, schemaVersion) pair, or nullptr.
Definition SchemaRegistry.cpp:879
Definition Container.h:35
ModuleRegister GameEventModule_register("GameEvent",(ModuleManager::creator_t)(GameEventModule::create), GameEventModule::expose)
@ String
@ Object
@ Integer
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
Definition SquirrelBinding.cpp:470
std::vector< DiagnosticDetail > DiagnosticDetails
Owning collection of diagnostic details with stable insertion order.
Definition Diagnostic.h:88
@ InvalidArgument
@ Failed
@ ParseError
@ Conflict
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 Identity.h:469
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 Identity.h:466
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.
Definition EventSequence.h:13
std::function< Result< ContentId >(std::string_view canonicalInput)> SnapshotHashProvider
Injected content-digest implementation used by snapshots.
Definition Snapshot.h:36
Definition Container.h:602
Stable outer format shared by persistence and cross-process snapshots.
Definition Snapshot.h:46
EventSequence sequence
Sequence assigned by the owning stream; it is never global identity.
Definition GameEvent.h:187
EventId eventId
Stable event identity; nil is allowed only for legacy transient events.
Definition GameEvent.h:185
std::string payload
Canonical serialized payload at the stream persistence boundary.
Definition GameEvent.h:207
SchemaVersion schemaVersion
Version of the payload schema, not a stream or runtime generation.
Definition GameEvent.h:201
CausationRef causation
Direct causation reference, normally an event or command ID.
Definition GameEvent.h:195
Metadata and validation constraints for one object member.
Definition SchemaTypes.h:77
std::vector< FieldDefinition > fields
Definition SchemaTypes.h:99
bool additionalProperties
Definition SchemaTypes.h:98
Recursive node in the deliberately small Eve Schema language.
Definition SchemaTypes.h:47
std::shared_ptr< const SchemaDefinition > objectSchema
Inline object shape for an object node.
Definition SchemaTypes.h:57