Repository navigation
Expand file tree
/
Copy pathruntime_mutation_tests.cpp
More file actions
327 lines (308 loc) · 15.3 KB
/
Copy pathruntime_mutation_tests.cpp
File metadata and controls
327 lines (308 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
#include "../../tests/support/runtime_mutation_fixture.hpp"
#include <teaql/provider_sqlite/provider.hpp>
#include <teaql/provider_sqlite/dialect.hpp>
#include <teaql/sql/executor.hpp>
#include <iostream>
using namespace teaql;
using namespace mutation_fixture;
using Access = detail::EntityDataServiceAccess;
static void check(bool value, const char* message) {
if (!value) {
throw std::runtime_error(message);
}
}
struct PreparationObserver final : EntityDataServiceBehavior, InternalIdGenerator, Checker {
State& state;
mutable std::uint64_t next = 100;
explicit PreparationObserver(State& state) : state(state) {}
RuntimeHookResult before_insert(Memory r, const UserContext&, InsertCommand&) const override {
state.note("hook");
return RuntimeHookResult::ok(r, {});
}
Result<std::uint64_t, RuntimeError> generate_id(Memory r, std::string_view) const override {
state.note("id");
return Result<std::uint64_t, RuntimeError>::ok(r, next++);
}
std::string_view entity() const override {
return "Order";
}
void check_and_fix(const UserContext&,
EntityValues&,
const ObjectLocation&,
CheckResults&) const override {
state.note("fix");
}
};
static void internal_preparation_before_intent() {
GlobalContext global;
auto user_context = global.make_user_context();
auto r = user_context->memory_resource();
auto& state = user_context->make<State>();
auto& metadata = user_context->make<InMemoryMetadataStore>();
EntityDescriptor descriptor(std::allocator_arg, Allocator(r), "Order");
descriptor.property("id", DataType::U64).id();
descriptor.property("version", DataType::I64).version();
descriptor.property("name", DataType::Text);
metadata.register_entity(std::move(descriptor));
user_context->set_metadata(*user_context, metadata);
auto& observer = user_context->make_resource<PreparationObserver>(state);
auto& behaviors = user_context->make<InMemoryEntityDataServiceBehaviorRegistry>();
behaviors.register_behavior("Order", *user_context, observer);
user_context->set_entity_data_service_behavior_registry(*user_context, behaviors);
user_context->set_internal_id_generator(*user_context, observer);
auto& checkers = user_context->make<InMemoryCheckerRegistry>();
checkers.register_checker(*user_context, observer);
user_context->set_checker_registry(*user_context, checkers);
auto& executor = user_context->make_resource<Executor>(state);
auto& service =
EntityDataService<Executor>::for_executor(*user_context, "Order", *user_context, executor);
auto& command = user_context->make<InsertCommand>("Order");
command.value("name", "input");
auto& result = Access::insert_internal(service, command).wait();
check(!result && result.error().to_string(r).starts_with("REQUEST_COMMENT_REQUIRED") &&
state.notes.size() == 3 && state.notes[0] == "hook" && state.notes[1] == "id" &&
state.notes[2] == "fix" && observer.next == 101 && state.requests.empty() &&
state.events.empty(),
"internal preparation follows source callback order before physical intent rejection");
check(!command.values.fields.contains(std::string_view("id")),
"preparation and its generated ID do not mutate the caller's command snapshot");
}
static void adapters_and_audit() {
GlobalContext global;
auto user = global.make_user_context();
auto r = user->memory_resource();
user->disable_sql_log();
auto& state = user->make<State>();
auto& executor = user->make_resource<Executor>(state);
auto& sink = user->make_resource<Sink>(state);
user->set_event_sink(*user, sink);
auto& cache = user->make_resource<Cache>(state);
user->insert_resource(*user, static_cast<AggregationCacheBackend&>(cache));
auto& service = EntityDataService<Executor>::for_executor(*user, "Order", *user, executor);
check(bool(Access::bind_mutation_intent(
service, "Inspect native mutation lifecycle PRIVATE-SIBLING PRIVATE-TOKEN")),
"private fixture binds explicit mutation and readback intent");
auto& bindings = user->make<SqlLogContext>();
bindings.parameter_policies = {SqlParameterLogPolicy::Masked,
SqlParameterLogPolicy::Credential};
auto& operands = user->make<Vector<Value>>();
operands.emplace_back("PRIVATE-SIBLING");
operands.emplace_back("PRIVATE-TOKEN");
auto& privacy = user->make<SqlIntentRedactions>(
SqlIntentRedactions::from_bindings(r, bindings, operands, ""));
check(bool(Access::bind_mutation_privacy(service, privacy)),
"bind invocation operands independently of changed fields");
auto& lineage = user->make<TraceChain>();
lineage.emplace_back(TraceKind::AuditReason, "Order", "PRIVATE-SIBLING PRIVATE-TOKEN", 7);
service.with_trace_context(lineage);
auto& cmd = user->make<UpdateCommand>("Order", std::uint64_t(7));
cmd.value("name", "new").expected_version(3);
cmd.old_values.emplace(r);
cmd.old_values->fields.emplace(String("name", r), Value(r, "old"));
cmd.old_values->fields.emplace(String("other", r), Value(r, "preserved"));
auto& result = Access::update_internal(service, cmd).wait();
check(result && result.value() == 1, "runtime update executes");
check(state.notes.size() == 3 && state.notes[0] == "provider" &&
state.notes[1] == "fixture::entity:Order" && state.notes[2] == "event",
"cache invalidation precedes event delivery");
check(state.events[0].old_values &&
state.events[0].new_values->at(String("other", r)).try_text() == "preserved",
"complete old snapshots retained and merged");
check(state.events[0].diagnostic_redactions() != nullptr &&
state.requests[0].diagnostic_redactions() != nullptr,
"entity mutation dispatch preserves provenance in requests and delivered raw events");
{
auto safe = state.events[0].build_safe_event(r, {}, {});
check(safe.entity_id == 7 && !safe.trace_chain.empty() &&
std::none_of(safe.trace_chain.begin(),
safe.trace_chain.end(),
[](const auto& node) {
return node.comment.find("PRIVATE-") != String::npos;
}),
"real mutation event projection hides operands absent from the change set");
}
auto& batch = user->make<BatchUpdateCommand>("Order");
batch.batch_ids.emplace_back(std::uint64_t(7));
batch.batch_expected_versions.emplace_back(4);
batch.batch_values.emplace_back();
batch.batch_values.back().fields.emplace(String("name", r), Value(r, "after"));
batch.batch_values.back().fields.emplace(String("unknown", r), Value(r, "event only"));
batch.update_fields.emplace_back("name");
auto& written = Access::execute_prepared_batch_update(service, batch).wait();
check(written && state.events.back().values.contains(std::string_view("unknown")),
"batch event retains full input beyond SQL projection");
check(std::get<UpdateCommand>(state.requests.back().data).values.fields.size() == 1,
"SQL batch update filters by update_fields");
auto& retained = global.make<RawAuditEvent>(state.events.back());
user.reset();
check(retained.values.contains(std::string_view("unknown")),
"Global audit copy survives actual User destruction");
}
static void conflict_failure_and_cancel() {
GlobalContext global;
auto user = global.make_user_context();
auto r = user->memory_resource();
auto& state = user->make<State>();
state.affected.push_back(0);
auto& executor = user->make_resource<Executor>(state);
auto& service = EntityDataService<Executor>::for_executor(*user, "Order", *user, executor);
check(bool(Access::bind_mutation_intent(service, "Inspect native mutation lifecycle")),
"private fixture binds explicit mutation and readback intent");
auto& cmd = user->make<UpdateCommand>("Order", std::uint64_t(7));
cmd.expected_version(1);
auto& result = Access::update_internal(service, cmd).wait();
check(!result &&
result.error().runtime_error().kind() == RuntimeError::Kind::OptimisticLockConflict,
"zero version-checked rows conflict");
check(state.events.empty(), "failed mutation emits no event");
state.pending = true;
auto& future = Access::update_internal(service, cmd);
check(!future.poll(), "mutation may suspend");
unsigned cancelled = 0;
state.external_cancel = &cancelled;
user.reset();
check(cancelled == 1, "close joins pending native mutation before arena reclamation");
}
static void sqlite_entry() {
GlobalContext global;
auto user = global.make_user_context();
auto r = user->memory_resource();
user->disable_sql_log();
auto& metadata = user->make<InMemoryMetadataStore>();
EntityDescriptor d(std::allocator_arg, Allocator(r), "Order");
d.table("orders");
d.property("id", DataType::U64).id();
d.property("version", DataType::I64).version();
d.property("name", DataType::Text);
metadata.register_entity(std::move(d));
user->set_metadata(*user, metadata);
auto& connection = user->make_resource<SqliteConnection>();
auto& transport = user->make<SqliteMutationExecutor>(connection);
auto& sql = user->make<CompiledQuery>();
sql.sql = "CREATE TABLE orders(id INTEGER PRIMARY KEY,version INTEGER,name TEXT)";
check(bool(transport.execute(r, sql)), "SQLite setup");
auto& dialect = user->make_resource<SqliteDialect>();
auto& state = user->make<SqlExecutorState>();
auto& executor = user->make<SqlDataServiceExecutor<MutationExecutorError>>(
dialect, transport, metadata, state);
using E = std::remove_reference_t<decltype(executor)>;
auto& service = EntityDataService<E>::for_executor(*user, "Order", *user, executor);
check(bool(Access::bind_mutation_intent(service, "Inspect native mutation lifecycle")),
"private fixture binds explicit mutation and readback intent");
auto& insert = user->make<InsertCommand>("Order");
insert.value("id", std::uint64_t(7)).value("name", "first");
auto& result = Access::insert_internal(service, insert).wait();
check(result && result.value() == 1, "prepared runtime insert uses real SQLite");
auto& update = user->make<UpdateCommand>("Order", std::uint64_t(7));
update.value("name", "second").expected_version(1);
auto& changed = Access::update_internal(service, update).wait();
check(changed && changed.value() == 1, "real SQLite guarded update through runtime adapter");
auto& conflict = Access::update_internal(service, update).wait();
check(!conflict, "second update with stale version conflicts");
}
struct ClosingHook final : EntityDataServiceBehavior {
UserContext& user;
explicit ClosingHook(UserContext& user) : user(user) {}
RuntimeHookResult before_insert(Memory r, const UserContext&, InsertCommand&) const override {
user.close();
return RuntimeHookResult::ok(r, {});
}
};
struct ClosingSink final : RawAuditEventSink {
UserContext& user;
explicit ClosingSink(UserContext& user) : user(user) {}
RuntimeHookResult on_event(Memory r, const UserContext&, const RawAuditEvent&) const override {
user.close();
return RuntimeHookResult::ok(r, {});
}
};
static void callback_expiry() {
GlobalContext global;
auto user = global.make_user_context();
auto r = user->memory_resource();
auto& state = user->make<State>();
auto& executor = user->make_resource<Executor>(state);
auto& service = EntityDataService<Executor>::for_executor(*user, "Order", *user, executor);
check(bool(Access::bind_mutation_intent(service, "Inspect native mutation lifecycle")),
"private fixture binds explicit mutation and readback intent");
auto registry = user->make_ref<InMemoryEntityDataServiceBehaviorRegistry>();
user->set_entity_data_service_behavior_registry(*user, user->get(registry));
user->destroy(registry);
auto& command = user->make<InsertCommand>("Order");
bool rejected = false;
try {
(void)service.prepare_insert_command(command);
} catch (const ReferenceError&) {
rejected = true;
}
check(rejected, "destroyed behavior registry is rejected before callbacks");
auto replacement = user->make_ref<InMemoryEntityDataServiceBehaviorRegistry>();
user->set_entity_data_service_behavior_registry(*user, user->get(replacement));
auto policy = user->make_resource_ref<RequestPolicy>();
user->set_request_policy(*user, user->get(policy));
user->destroy(policy);
rejected = false;
try {
(void)service.prepare_insert_command(command);
} catch (const ReferenceError&) {
rejected = true;
}
check(rejected, "destroyed request policy is rejected before virtual dispatch");
user->clear_request_policy();
auto sink = user->make_resource_ref<Sink>(state);
user->set_event_sink(*user, user->get(sink));
user->destroy(sink);
rejected = false;
RawAuditEvent event(std::allocator_arg, Allocator(r), RawAuditEventKind::Created, "Order");
try {
(void)user->send_event(event);
} catch (const ReferenceError&) {
rejected = true;
}
check(rejected, "destroyed raw sink is rejected before virtual dispatch");
}
int main(int argc, char** argv) {
if (argc == 2) {
std::set_terminate([] {
std::_Exit(0);
});
GlobalContext global;
auto user = global.make_user_context();
auto r = user->memory_resource();
if (std::string_view(argv[1]) == "reentrant-event") {
auto& sink = user->make_resource<ClosingSink>(*user);
user->set_event_sink(*user, sink);
RawAuditEvent event(
std::allocator_arg, Allocator(r), RawAuditEventKind::Created, "Order");
(void)user->send_event(event);
} else {
auto& registry = user->make<InMemoryEntityDataServiceBehaviorRegistry>();
auto& hook = user->make_resource<ClosingHook>(*user);
registry.register_behavior("Order", *user, hook);
user->set_entity_data_service_behavior_registry(*user, registry);
auto& state = user->make<State>();
auto& executor = user->make_resource<Executor>(state);
auto& service =
EntityDataService<Executor>::for_executor(*user, "Order", *user, executor);
check(bool(Access::bind_mutation_intent(service, "Inspect native mutation lifecycle")),
"private fixture binds explicit mutation and readback intent");
auto& command = user->make<InsertCommand>("Order");
(void)service.prepare_insert_command(command);
}
return 1;
}
auto* previous = std::pmr::set_default_resource(std::pmr::null_memory_resource());
try {
internal_preparation_before_intent();
adapters_and_audit();
conflict_failure_and_cancel();
sqlite_entry();
callback_expiry();
std::pmr::set_default_resource(previous);
std::cout << "Runtime mutation contracts passed\n";
} catch (const std::exception& e) {
std::pmr::set_default_resource(previous);
std::cerr << e.what() << '\n';
return 1;
}
}