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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
// Copyright 2025 The Drasi Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use Result;
use ;
use HashSet;
use crateDispatchMode;
use crate;
use crateRecoveryPolicy;
use SourceMiddlewareConfig;
/// Query language for continuous queries
///
/// Drasi supports two query languages for continuous query processing:
///
/// # Query Languages
///
/// - **Cypher**: Default graph query language with pattern matching
/// - **GQL**: GraphQL-style queries compiled to Cypher
///
/// # Default Behavior
///
/// If not specified, queries default to `QueryLanguage::Cypher`.
///
/// # Examples
///
/// ## Using Cypher (Default)
///
/// ```yaml
/// queries:
/// - id: active_orders
/// query: "MATCH (o:Order) WHERE o.status = 'active' RETURN o"
/// queryLanguage: Cypher # Optional, this is the default
/// sources: [orders_db]
/// ```
///
/// ## Using GQL
///
/// ```yaml
/// queries:
/// - id: user_data
/// query: |
/// {
/// users(status: "active") {
/// id
/// name
/// email
/// }
/// }
/// queryLanguage: GQL
/// sources: [users_db]
/// ```
///
/// # Important Limitations
///
/// **Unsupported Clauses**: ORDER BY, TOP, and LIMIT clauses are not supported in continuous
/// queries as they conflict with incremental result computation.
/// Source subscription configuration for queries
///
/// `SourceSubscriptionConfig` defines how a query subscribes to a specific source,
/// including any middleware pipeline to apply to changes from that source.
///
/// # Fields
///
/// - **source_id**: ID of the source to subscribe to
/// - **nodes**: Optional list of node labels to subscribe to from this source
/// - **relations**: Optional list of relation labels to subscribe to from this source
/// - **pipeline**: Optional list of middleware IDs to apply to changes from this source
///
/// # Examples
///
/// ## Simple Subscription (No Pipeline)
///
/// ```yaml
/// source_subscriptions:
/// - source_id: orders_db
/// pipeline: []
/// ```
///
/// ## Subscription with Middleware Pipeline
///
/// ```yaml
/// source_subscriptions:
/// - source_id: raw_events
/// pipeline: [decoder, mapper, validator]
/// ```
///
/// ## Subscription with Label Filtering
///
/// ```yaml
/// source_subscriptions:
/// - source_id: orders_db
/// nodes: [Order, Customer]
/// relations: [PLACED_BY]
/// pipeline: []
/// ```
/// Settings passed to a source when subscribing
///
/// `SourceSubscriptionSettings` contains all the information a source needs to
/// intelligently handle bootstrap and subscription for a query, including the
/// specific node and relation labels the query is interested in.
///
/// # Fields
///
/// - **source_id**: ID of the source
/// - **enable_bootstrap**: Whether to request initial data
/// - **query_id**: ID of the subscribing query
/// - **nodes**: Set of node labels the query is interested in from this source
/// - **relations**: Set of relation labels the query is interested in from this source
///
/// # Example
///
/// ```ignore
/// use drasi_lib::config::SourceSubscriptionSettings;
/// use std::collections::HashSet;
///
/// let settings = SourceSubscriptionSettings {
/// source_id: "orders_db".to_string(),
/// enable_bootstrap: true,
/// query_id: "my-query".to_string(),
/// nodes: ["Order", "Customer"].iter().map(|s| s.to_string()).collect(),
/// relations: ["PLACED_BY"].iter().map(|s| s.to_string()).collect(),
/// resume_from: None,
/// request_position_handle: false,
/// };
/// ```
/// Root configuration for drasi-lib
///
/// `DrasiLibConfig` is the top-level configuration structure for DrasiLib.
/// It defines server settings, queries, and storage backends.
///
/// # Plugin Architecture
///
/// **Important**: drasi-lib has ZERO awareness of which plugins exist. Sources and
/// reactions are passed as owned instances via `with_source()` and `with_reaction()`
/// on the builder. Only queries can be configured via the builder.
///
/// # Configuration Structure
///
/// A typical configuration has these sections:
///
/// 1. **id**: Unique server identifier (optional, defaults to UUID)
/// 2. **priority_queue_capacity**: Default capacity for event queues (optional)
/// 3. **dispatch_buffer_capacity**: Default capacity for dispatch buffers (optional)
/// 4. **storage_backends**: Storage backend definitions (optional)
/// 5. **queries**: Continuous queries to process data
///
/// # Capacity Settings
///
/// - **priority_queue_capacity**: Default capacity for timestamp-ordered event queues in
/// queries and reactions. Higher values support more out-of-order events but consume
/// more memory. Default: 10000
///
/// - **dispatch_buffer_capacity**: Default capacity for event dispatch channels between
/// components (sources → queries, queries → reactions). Higher values improve throughput
/// under load but consume more memory. Default: 1000
///
/// Individual components can override these defaults by setting their own capacity values.
///
/// # Thread Safety
///
/// This struct is `Clone` and can be safely shared across threads.
///
/// # Usage
///
/// Use `DrasiLib::builder()` to create instances:
///
/// ```no_run
/// use drasi_lib::{DrasiLib, Query};
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let core = DrasiLib::builder()
/// .with_id("my-server")
/// .with_query(
/// Query::cypher("my-query")
/// .query("MATCH (n) RETURN n")
/// .from_source("my-source")
/// .build()
/// )
/// .build()
/// .await?;
/// # Ok(())
/// # }
/// ```
///
/// # Validation
///
/// Call [`validate()`](DrasiLibConfig::validate) to check:
/// - Unique query IDs
/// - Valid storage backend references
///
/// Note: Source and reaction validation happens at runtime when instances are added.
/// Configuration for a continuous query
///
/// `QueryConfig` defines a continuous query that processes data changes from sources
/// and emits incremental result updates. Queries subscribe to one or more sources and
/// maintain materialized views that update automatically as data changes.
///
/// # Query Languages
///
/// Queries can be written in either:
/// - **Cypher**: Default graph pattern matching language
/// - **GQL**: GraphQL-style queries (compiled to Cypher)
///
/// **Important**: ORDER BY, TOP, and LIMIT clauses are not supported in continuous
/// queries as they conflict with incremental result computation.
///
/// # Bootstrap Processing
///
/// - **enableBootstrap**: Controls whether the query processes initial data (default: true)
/// - **bootstrapBufferSize**: Event buffer size during bootstrap phase (default: 10000)
///
/// During bootstrap, events are buffered to maintain ordering while initial data loads.
/// After bootstrap completes, queries switch to incremental processing mode.
///
/// # Synthetic Joins
///
/// Queries can define synthetic relationships between node types from different sources
/// via the `joins` field. This creates virtual edges based on property equality without
/// requiring physical relationships in the source data.
///
/// # Configuration Fields
///
/// - **id**: Unique identifier (referenced by reactions)
/// - **query**: Query string in specified language
/// - **queryLanguage**: Cypher or GQL (default: Cypher)
/// - **sources**: Source IDs to subscribe to
/// - **auto_start**: Start automatically (default: true)
/// - **joins**: Optional synthetic join definitions
/// - **enableBootstrap**: Process initial data (default: true)
/// - **bootstrapBufferSize**: Buffer size during bootstrap (default: 10000)
/// - **priority_queue_capacity**: Out-of-order event queue size (overrides global)
/// - **dispatch_buffer_capacity**: Output buffer size (overrides global)
/// - **dispatch_mode**: Broadcast or Channel routing
///
/// # Examples
///
/// ## Basic Cypher Query
///
/// ```yaml
/// queries:
/// - id: active_orders
/// query: "MATCH (o:Order) WHERE o.status = 'active' RETURN o"
/// queryLanguage: Cypher # Optional, this is default
/// sources: [orders_db]
/// auto_start: true
/// enableBootstrap: true
/// bootstrapBufferSize: 10000
/// ```
///
/// ## Query with Multiple Sources
///
/// ```yaml
/// queries:
/// - id: order_customer_join
/// query: |
/// MATCH (o:Order)-[:BELONGS_TO]->(c:Customer)
/// WHERE o.status = 'active'
/// RETURN o, c
/// sources: [orders_db, customers_db]
/// ```
///
/// ## Query with Synthetic Joins
///
/// ```yaml
/// queries:
/// - id: synthetic_join_query
/// query: |
/// MATCH (o:Order)-[:CUSTOMER]->(c:Customer)
/// RETURN o.id, c.name
/// sources: [orders_db, customers_db]
/// joins:
/// - id: CUSTOMER # Relationship type in query
/// keys:
/// - label: Order
/// property: customer_id
/// - label: Customer
/// property: id
/// ```
///
/// ## High-Throughput Query
///
/// ```yaml
/// queries:
/// - id: high_volume_processing
/// query: "MATCH (n:Event) WHERE n.timestamp > timestamp() - 60000 RETURN n"
/// sources: [event_stream]
/// priority_queue_capacity: 100000 # Large queue for many out-of-order events
/// dispatch_buffer_capacity: 10000 # Large output buffer
/// bootstrapBufferSize: 50000 # Large bootstrap buffer
/// ```
///
/// ## GQL Query
///
/// ```yaml
/// queries:
/// - id: gql_users
/// query: |
/// {
/// users(status: "active") {
/// id
/// name
/// email
/// }
/// }
/// queryLanguage: GQL
/// sources: [users_db]
/// ```
/// Synthetic join configuration for queries
///
/// `QueryJoinConfig` defines a virtual relationship between node types from different
/// sources. This allows queries to join data without requiring physical relationships
/// in the source systems.
///
/// # Join Semantics
///
/// Joins create synthetic edges by matching property values across nodes. The `id`
/// field specifies the relationship type used in the query's MATCH pattern, and `keys`
/// define which properties to match.
///
/// # Examples
///
/// ## Simple Join on Single Property
///
/// ```yaml
/// joins:
/// - id: CUSTOMER # Use in query: MATCH (o:Order)-[:CUSTOMER]->(c:Customer)
/// keys:
/// - label: Order
/// property: customer_id # Order.customer_id
/// - label: Customer
/// property: id # Customer.id
/// # Creates edge when Order.customer_id == Customer.id
/// ```
///
/// ## Multi-Source Join
///
/// ```yaml
/// joins:
/// - id: ASSIGNED_TO
/// keys:
/// - label: Task
/// property: assignee_id
/// - label: User
/// property: user_id
/// ```
/// Join key specification for synthetic joins
///
/// `QueryJoinKeyConfig` specifies one side of a join condition by identifying
/// a node label and the property to use for matching.
///
/// # Example
///
/// For joining orders to customers:
///
/// ```yaml
/// keys:
/// - label: Order
/// property: customer_id
/// - label: Customer
/// property: id
/// ```
///
/// This creates an edge when `Order.customer_id == Customer.id`.
// Conversion implementations for QueryJoin types