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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! THE BATCHING SEAM: where N asks of one table become one statement.
//!
//! ```text
//! { a: reel(id: 1) { … } b: reel(id: 2) { … } c: reel(id: 3) { … } }
//! │ │ │
//! └───────────────────────┴──────────────────────┘
//! BatchDoor<i64, ReelSqliteRow> ← ctx.data_opt, per request
//! │
//! one batch, one `rows(…)`, one statement
//! ```
//!
//! `ingraph/tests/wire_batching.rs` counted what a document costs with nothing installed: three
//! aliased singles are THREE statements, taken through [`SqlSource::pool`](super::SqlSource::pool)
//! rather than inferred from the emission. `ingraph/tests/wire_batched.rs` counts the same document
//! with a door from this module installed, and gets ONE.
//!
//! # The seam is INGRAPH's, and the engine is somebody else's
//!
//! The user's standing multi-backend law, restated at the ruling that opened this round: *不能用
//! async_graphql, 我已经说过很多遍了, 我们会支持多后端, 不要强制绑定某一个后端*. So the loader seam
//! itself is this framework's own — [`AsyncBatchLoad`] is the sentence *these keys, in one ask*, and
//! [`BatchError`] is the currency it fails in — and async-graphql's `DataLoader` is ONE BINDING of
//! it, reached through [`AsLoader`] under a feature of its own. Never the seam itself.
//!
//! What that buys is not hypothetical. The coalescing engine here is a window, a dedup, a fan-out
//! and an injected spawner; nothing about those is GraphQL, and a second wire backend — or a
//! caller with no wire at all — spends the same [`AsyncBatchLoad`] implementation without meeting
//! async-graphql's vocabulary anywhere.
//!
//! # The ERROR is Clone because a batch failure FANS OUT
//!
//! One statement answers many askers, so one refusal reaches many of them, so the currency has to
//! be duplicable. The engine's own errors are not: `SqlQueryError` wraps `sqlx::Error`, which is
//! not [`Clone`] and should not be made so. [`BatchError`] carries the refusal behind an [`Arc`]
//! and the WORD beside it, so cloning is a refcount and the sentence a client reads is the one the
//! store actually said.
//!
//! The word travels rather than being re-derived at the wire, and that is what keeps the two lanes
//! indistinguishable to a client: [`refused`](super::refused) takes anything that is
//! [`ToErrorCode`] + [`Display`](core::fmt::Display), [`BatchError`] is both, and so a store
//! refusal crossing through a batch reaches a client under `STORE_REFUSED` exactly as the per-row
//! lane's does.
//!
//! # The DOOR is erased, and `ctx.data` is why
//!
//! `Context::data::<T>` is a `TypeId` lookup, so an emitted resolver has to NAME a concrete type.
//! It cannot name the application's: a `DataLoader<AsLoader<…>>` closes over the cache factory, and
//! an application that plugs its own coalescing engine has no async-graphql type at all. So the
//! name the emission writes is [`BatchDoor<K, V>`](BatchDoor) — this crate's own, parameterised by
//! the two things the emission already knows, the record's id type and its row — and the openness
//! lives inside it, as [`SqlDoor`](super::SqlDoor)'s does.
//!
//! [`Batched`] is that inside: the ERASED capability a door carries, *one key, answered*. It is
//! deliberately the one-key verb rather than the batch verb, because the batching is the
//! provider's: a door hands one resolver's key to whatever is behind it, and what is behind it
//! decides who that key waits for.
//!
//! # The INSTALL contract, and what is deliberately NOT emitted
//!
//! ```ignore
//! let schema = SqlDoor::pooled(pool.clone())
//! .install(Schema::build(ReelsQuery::default(), EmptyMutation, EmptySubscription))
//! .finish();
//!
//! // per request, for each record a document may batch:
//! let loader = BatchDoor::batched(SqlRows::<ReelSqliteRow, Sqlite>::new(door), tokio::spawn);
//! schema.execute(Request::new(query).data(loader)).await
//! ```
//!
//! The SPAWNER is the application's, exactly as the pool is. Picking a runtime is not a framework's
//! act — this crate enables no `runtime-*` feature of sqlx for the same reason — and a
//! `DataLoader`'s flush future has to be handed to one. So this is a seam plus an install contract
//! and not an emission: nothing generated names `tokio::spawn`, and a build that installs nothing
//! answers exactly what it answered before.
//!
//! Which is the other half of the ruling: *走B吧, 不装loader 就慢一些呗* — the loader is OPTIONAL.
//! The emitted resolver reads `ctx.data_opt`, and an absent door is the per-row lane, slower and
//! correct. Presence is enablement; there is no configuration and nothing to break.
//!
//! # Per REQUEST, not per schema
//!
//! A door installed on the `SchemaBuilder` lives as long as the process, and a coalescing engine
//! that outlives a request is a CACHE — with an invalidation problem that exists only because it
//! outlived the request. [`BatchDoor::install`] is offered for the shape where that is what an
//! application wants; the idiom above, `Request::data(door)`, is the one this module recommends,
//! and `DataLoader::new`'s own `NoCache` is what makes coalescing rather than caching the win.
//!
//! # The FIVE BOUNDS an id owes, and where they are demanded
//!
//! *id有这些属性应该是必须的* — `Hash + Eq + Clone + Send + Sync`, mandatory. They are demanded at
//! the DECLARATION rather than here, through [`ids_are_keys`](crate::ids_are_keys), so a record
//! whose id could never be a batch key is refused where it is written and not at whichever
//! application first tries to install a door over it. This module's own bounds are the same five,
//! restated where the engine spends them.
use Arc;
use ;
pub use SqlRows;
pub use AsLoader;
/// What a batched answer arrives as — the one-key future a [`BatchDoor`] hands back.
///
/// BOXED, because the door is erased and an erased method cannot return an opaque future. `+ Send`
/// is written at the definition rather than left to inference, for the reason every future in this
/// crate that crosses a resolver states it: async-graphql demands `Send` of a resolver's future,
/// and an `async fn`'s is not `Send`-provable from outside (rustc #100013). Proving it here means
/// the emitted resolver's own future is provably `Send` whatever is behind the door.
///
/// The lifetime is the DOOR's: the future borrows the engine it joins a batch on, and a resolver
/// awaits it inside the request that found the door.
pub type BatchAnswer<'a, V> =
Pin;
/// THE NEUTRAL CURRENCY a batch fails in — a refusal, the word it is recognised by, and [`Clone`].
///
/// # Why the type exists at all, rather than the engine's own error travelling
///
/// Two facts meet here. A batch failure FANS OUT — one statement answers many askers, so one
/// refusal reaches many of them and the value has to be duplicable — and the engine's refusals are
/// not `Clone`: `SqlQueryError` holds an `sqlx::Error`, which holds a driver's. Making those
/// `Clone` to serve a coalescing engine would be the tail wagging the dog. So the fan-out's
/// requirement is paid HERE, once, by an [`Arc`], and no engine error changes shape for it.
///
/// The second fact is neutrality: this is the currency of a seam that must name no wire backend, so
/// it is neither `async_graphql::Error` nor anything convertible only into one. The BINDING
/// converts at its boundary, exactly as every other wire surface in this crate does.
///
/// # The word travels WITH the refusal
///
/// A batch's refusal has to reach a client under the same word the per-row lane's would, or the two
/// lanes are distinguishable and a client's error handling depends on whether an application
/// happened to install a door. So an [`ErrorCode`] is carried rather than re-derived at the
/// crossing, and this type is itself [`ToErrorCode`] + [`Display`](core::fmt::Display) — which is
/// exactly [`refused`](super::refused)'s bound, so the batched lane crosses through the same one
/// place a coded refusal is ever attached.
/// The carried refusal is the SOURCE rather than this value's own sentence, which is what a chain
/// walker expects to find: [`Display`](core::fmt::Display) above already renders the refusal, so a
/// reader that prints both sees one sentence twice — and the alternative, a wrapper sentence of
/// this type's own, would put a layer's name in front of every batched refusal a client reads.
/// THE NEUTRAL SEAM: these keys, in one ask.
///
/// # The shape, and what each part of it is for
///
/// `keys` is a SLICE because the whole point is that the ask is one. The answer is the found
/// `(key, value)` PAIRS — absent keys omitted rather than reported, since a batch of `k` keys over
/// a table where `k - 1` rows live is a perfectly ordinary answer and not a failure — and the whole
/// batch fails as one [`Err`], because one statement either ran or did not.
///
/// PAIRS rather than a map, and that is the neutrality showing: a map would fix a hasher and a
/// collection on a seam whose implementors have neither in common. The binding collects into
/// whatever its engine wants.
///
/// # `+ Send` at the DEFINITION
///
/// The engine SPAWNS this future — that is what an injected spawner is for — so it must be
/// provably `Send` from outside, which an `async fn`'s return is not (rustc #100013). Written out,
/// as every future in this crate that crosses a runtime boundary is.
///
/// # The five bounds are the KEY's, and they are stated at the implementor's position
///
/// Nothing here bounds `K`. A seam is a sentence about what an implementation does, and *hash this
/// and compare it* is the coalescing ENGINE's need rather than a batch read's: an implementation
/// that answers `k` keys by rendering one `IN (…)` needs neither. The bounds are demanded where
/// they are spent — at [`AsLoader`], which is the engine's own door — and mandated at every
/// declaration by [`ids_are_keys`](crate::ids_are_keys), which is the ruling's *强制*.
/// THE ERASED CAPABILITY a [`BatchDoor`] carries: one key, answered.
///
/// # The one-key verb, and why it is not the batch verb
///
/// A resolver holds one key. What it wants is not *run a batch* but *answer this, and if there are
/// siblings, wait for them* — and who those siblings are, how long to wait and whether to spawn is
/// the provider's business entirely. So the erased surface is the narrow one: the door asks for a
/// key and the thing behind it decides what batch that key joins.
///
/// # It is OBJECT-SAFE on purpose, which is what makes [`BatchDoor`] nameable
///
/// [`AsyncBatchLoad`] returns an opaque future and is therefore not a trait object. That is the right
/// shape for the seam an implementor writes — no allocation on the batch path — and the wrong one
/// for the type an emitted resolver has to spell, since `ctx.data` is a lookup on a concrete type
/// and the concrete type behind a door is the application's choice. This trait is the boundary
/// between those two facts, and the boxed [`BatchAnswer`] is what it costs: one allocation per
/// resolver, against a statement saved per sibling.
///
/// An application with its own coalescing engine implements THIS and installs it. It is the door's
/// openness, exactly as [`SqlSource`](super::SqlSource) is the read door's.
/// THE BATCH DOOR — the type an emitted resolver looks for, and the one an application installs.
///
/// One per `(id type, row type)` pair, which is one per record per database, which is exactly the
/// granularity a batch has: the rows of one table, addressed by one column. `SqlDoor<Sqlite>` and
/// `SqlDoor<Postgres>` are two types for the same reason and the keying does the same work here —
/// no registry, no name, and no way for a record to be answered out of another record's batch.
///
/// # Cloneable and cheap
///
/// The provider is behind an [`Arc`], so installing a door on a request costs a refcount. That
/// matters more here than at the read door: this one is minted PER REQUEST in the recommended
/// idiom, and a per-request mint that allocated an engine would have traded the N+1 for a different
/// cost.
/// Written out rather than derived, for the reason every parameterised type in this crate writes
/// its own: a derive would bound `K: Clone` and `V: Clone`, which neither needs to be — what is
/// cloned is the handle inside.
/// Written out because a trait object carries no [`Debug`](core::fmt::Debug). What a reader wants
/// from this line is WHICH door it is, which the two type names answer — and they are the two
/// halves of *which record, in which database*.