thread-flow 0.1.0

Thread dataflow integration for data processing pipelines, using CocoIndex.
Documentation
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
// SPDX-FileCopyrightText: 2025 Knitli Inc. <knitli@knit.li>
// SPDX-License-Identifier: AGPL-3.0-or-later

//! D1 Target Factory - Cloudflare D1 distributed SQLite database target
//!
//! Implements ReCoco TargetFactoryBase for exporting code analysis results to
//! Cloudflare D1 edge databases with content-addressed caching.

use async_trait::async_trait;
use recoco::base::schema::{BasicValueType, FieldSchema, ValueType};
use recoco::base::value::{BasicValue, FieldValues, KeyValue, Value};
use recoco::ops::factory_bases::TargetFactoryBase;
use recoco::ops::interface::{
    ExportTargetDeleteEntry, ExportTargetMutationWithContext, ExportTargetUpsertEntry,
    FlowInstanceContext, SetupStateCompatibility,
};
use recoco::ops::sdk::{
    TypedExportDataCollectionBuildOutput, TypedExportDataCollectionSpec,
    TypedResourceSetupChangeItem,
};
use recoco::setup::{ChangeDescription, CombinedState, ResourceSetupChange, SetupChangeType};
use recoco::utils::prelude::Error as RecocoError;
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
use std::hash::Hash;
use std::sync::Arc;

#[cfg(feature = "caching")]
use crate::cache::{CacheConfig, QueryCache};

/// D1 Target Factory for Cloudflare D1 databases
#[derive(Debug, Clone)]
pub struct D1TargetFactory;

/// D1 connection specification
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct D1Spec {
    /// Cloudflare account ID
    pub account_id: String,
    /// D1 database ID
    pub database_id: String,
    /// API token for authentication
    pub api_token: String,
    /// Optional table name override
    pub table_name: Option<String>,
}

/// D1 table identifier (SetupKey)
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct D1TableId {
    pub database_id: String,
    pub table_name: String,
}

/// D1 table schema state
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct D1SetupState {
    pub table_id: D1TableId,
    pub key_columns: Vec<ColumnSchema>,
    pub value_columns: Vec<ColumnSchema>,
    pub indexes: Vec<IndexSchema>,
}

/// Column schema definition
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ColumnSchema {
    pub name: String,
    pub sql_type: String,
    pub nullable: bool,
    pub primary_key: bool,
}

/// Index schema definition
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct IndexSchema {
    pub name: String,
    pub columns: Vec<String>,
    pub unique: bool,
}

/// D1 schema migration instructions (SetupChange)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct D1SetupChange {
    pub table_id: D1TableId,
    pub create_table_sql: Option<String>,
    pub create_indexes_sql: Vec<String>,
    pub alter_table_sql: Vec<String>,
}

impl ResourceSetupChange for D1SetupChange {
    fn describe_changes(&self) -> Vec<ChangeDescription> {
        let mut changes = vec![];
        if let Some(sql) = &self.create_table_sql {
            changes.push(ChangeDescription::Action(format!("CREATE TABLE: {}", sql)));
        }
        for sql in &self.alter_table_sql {
            changes.push(ChangeDescription::Action(format!("ALTER TABLE: {}", sql)));
        }
        for sql in &self.create_indexes_sql {
            changes.push(ChangeDescription::Action(format!("CREATE INDEX: {}", sql)));
        }
        changes
    }

    fn change_type(&self) -> SetupChangeType {
        if self.create_table_sql.is_some() {
            SetupChangeType::Create
        } else if !self.alter_table_sql.is_empty() || !self.create_indexes_sql.is_empty() {
            SetupChangeType::Update
        } else {
            SetupChangeType::Invalid
        }
    }
}

/// D1 export context (runtime state)
pub struct D1ExportContext {
    pub database_id: String,
    pub table_name: String,
    pub account_id: String,
    pub api_token: String,
    /// Shared HTTP client with connection pooling
    pub http_client: Arc<reqwest::Client>,
    pub key_fields_schema: Vec<FieldSchema>,
    pub value_fields_schema: Vec<FieldSchema>,
    pub metrics: crate::monitoring::performance::PerformanceMetrics,
    #[cfg(feature = "caching")]
    pub query_cache: QueryCache<String, serde_json::Value>,
}

impl D1ExportContext {
    /// Create a new D1 export context with a shared HTTP client
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        database_id: String,
        table_name: String,
        account_id: String,
        api_token: String,
        http_client: Arc<reqwest::Client>,
        key_fields_schema: Vec<FieldSchema>,
        value_fields_schema: Vec<FieldSchema>,
        metrics: crate::monitoring::performance::PerformanceMetrics,
    ) -> Result<Self, RecocoError> {
        #[cfg(feature = "caching")]
        let query_cache = QueryCache::new(CacheConfig {
            max_capacity: 10_000, // 10k query results
            ttl_seconds: 300,     // 5 minutes
        });

        Ok(Self {
            database_id,
            table_name,
            account_id,
            api_token,
            http_client,
            key_fields_schema,
            value_fields_schema,
            metrics,
            #[cfg(feature = "caching")]
            query_cache,
        })
    }

    /// Create a new D1 export context with a default HTTP client (for tests and examples)
    pub fn new_with_default_client(
        database_id: String,
        table_name: String,
        account_id: String,
        api_token: String,
        key_fields_schema: Vec<FieldSchema>,
        value_fields_schema: Vec<FieldSchema>,
        metrics: crate::monitoring::performance::PerformanceMetrics,
    ) -> Result<Self, RecocoError> {
        use std::time::Duration;

        let http_client = Arc::new(
            reqwest::Client::builder()
                .pool_max_idle_per_host(10)
                .pool_idle_timeout(Some(Duration::from_secs(90)))
                .tcp_keepalive(Some(Duration::from_secs(60)))
                .http2_keep_alive_interval(Some(Duration::from_secs(30)))
                .timeout(Duration::from_secs(30))
                .build()
                .map_err(|e| {
                    RecocoError::internal_msg(format!("Failed to create HTTP client: {}", e))
                })?,
        );

        Self::new(
            database_id,
            table_name,
            account_id,
            api_token,
            http_client,
            key_fields_schema,
            value_fields_schema,
            metrics,
        )
    }

    pub fn api_url(&self) -> String {
        format!(
            "https://api.cloudflare.com/client/v4/accounts/{}/d1/database/{}/query",
            self.account_id, self.database_id
        )
    }

    async fn execute_sql(
        &self,
        sql: &str,
        params: Vec<serde_json::Value>,
    ) -> Result<(), RecocoError> {
        use std::time::Instant;

        // Generate cache key from SQL + params
        #[cfg(feature = "caching")]
        let cache_key = format!("{}{:?}", sql, params);

        // Check cache first (only for caching feature)
        #[cfg(feature = "caching")]
        {
            if let Some(_cached_result) = self.query_cache.get(&cache_key).await {
                // Cache hit - no need to query D1
                self.metrics.record_cache_hit();
                return Ok(());
            }
            self.metrics.record_cache_miss();
        }

        let start = Instant::now();

        let request_body = serde_json::json!({
            "sql": sql,
            "params": params
        });

        let response = self
            .http_client
            .post(self.api_url())
            .header("Authorization", format!("Bearer {}", self.api_token))
            .header("Content-Type", "application/json")
            .json(&request_body)
            .send()
            .await
            .map_err(|e| {
                self.metrics.record_query(start.elapsed(), false);
                RecocoError::internal_msg(format!("D1 API request failed: {}", e))
            })?;

        if !response.status().is_success() {
            let status = response.status();
            let error_text = response
                .text()
                .await
                .unwrap_or_else(|_| "Unknown error".to_string());
            self.metrics.record_query(start.elapsed(), false);
            return Err(RecocoError::internal_msg(format!(
                "D1 API error ({}): {}",
                status, error_text
            )));
        }

        let result: serde_json::Value = response.json().await.map_err(|e| {
            self.metrics.record_query(start.elapsed(), false);
            RecocoError::internal_msg(format!("Failed to parse D1 response: {}", e))
        })?;

        if !result["success"].as_bool().unwrap_or(false) {
            let errors = result["errors"].to_string();
            self.metrics.record_query(start.elapsed(), false);
            return Err(RecocoError::internal_msg(format!(
                "D1 execution failed: {}",
                errors
            )));
        }

        self.metrics.record_query(start.elapsed(), true);

        // Cache the successful result
        #[cfg(feature = "caching")]
        {
            self.query_cache.insert(cache_key, result.clone()).await;
        }

        Ok(())
    }

    async fn execute_batch(
        &self,
        statements: Vec<(String, Vec<serde_json::Value>)>,
    ) -> Result<(), RecocoError> {
        for (sql, params) in statements {
            self.execute_sql(&sql, params).await?;
        }
        Ok(())
    }

    pub fn build_upsert_stmt(
        &self,
        key: &KeyValue,
        values: &FieldValues,
    ) -> Result<(String, Vec<serde_json::Value>), RecocoError> {
        let mut columns = vec![];
        let mut placeholders = vec![];
        let mut params = vec![];
        let mut update_clauses = vec![];

        // Extract key parts - KeyValue is a wrapper around Box<[KeyPart]>
        for (idx, _key_field) in self.key_fields_schema.iter().enumerate() {
            if let Some(key_part) = key.0.get(idx) {
                columns.push(self.key_fields_schema[idx].name.clone());
                placeholders.push("?".to_string());
                params.push(key_part_to_json(key_part)?);
            }
        }

        // Add value fields
        for (idx, value) in values.fields.iter().enumerate() {
            if let Some(value_field) = self.value_fields_schema.get(idx) {
                columns.push(value_field.name.clone());
                placeholders.push("?".to_string());
                params.push(value_to_json(value)?);
                update_clauses.push(format!(
                    "{} = excluded.{}",
                    value_field.name, value_field.name
                ));
            }
        }

        let sql = format!(
            "INSERT INTO {} ({}) VALUES ({}) ON CONFLICT DO UPDATE SET {}",
            self.table_name,
            columns.join(", "),
            placeholders.join(", "),
            update_clauses.join(", ")
        );

        Ok((sql, params))
    }

    pub fn build_delete_stmt(
        &self,
        key: &KeyValue,
    ) -> Result<(String, Vec<serde_json::Value>), RecocoError> {
        let mut where_clauses = vec![];
        let mut params = vec![];

        for (idx, _key_field) in self.key_fields_schema.iter().enumerate() {
            if let Some(key_part) = key.0.get(idx) {
                where_clauses.push(format!("{} = ?", self.key_fields_schema[idx].name));
                params.push(key_part_to_json(key_part)?);
            }
        }

        let sql = format!(
            "DELETE FROM {} WHERE {}",
            self.table_name,
            where_clauses.join(" AND ")
        );

        Ok((sql, params))
    }

    pub async fn upsert(&self, upserts: &[ExportTargetUpsertEntry]) -> Result<(), RecocoError> {
        let statements = upserts
            .iter()
            .map(|entry| self.build_upsert_stmt(&entry.key, &entry.value))
            .collect::<Result<Vec<_>, _>>()?;

        let result = self.execute_batch(statements).await;

        // Invalidate cache on successful mutation
        #[cfg(feature = "caching")]
        if result.is_ok() {
            self.query_cache.clear().await;
        }

        result
    }

    pub async fn delete(&self, deletes: &[ExportTargetDeleteEntry]) -> Result<(), RecocoError> {
        let statements = deletes
            .iter()
            .map(|entry| self.build_delete_stmt(&entry.key))
            .collect::<Result<Vec<_>, _>>()?;

        let result = self.execute_batch(statements).await;

        // Invalidate cache on successful mutation
        #[cfg(feature = "caching")]
        if result.is_ok() {
            self.query_cache.clear().await;
        }

        result
    }

    /// Get cache statistics for monitoring
    #[cfg(feature = "caching")]
    pub async fn cache_stats(&self) -> crate::cache::CacheStats {
        self.query_cache.stats().await
    }

    /// Manually clear the query cache
    #[cfg(feature = "caching")]
    pub async fn clear_cache(&self) {
        self.query_cache.clear().await;
    }
}

/// Convert KeyPart to JSON
/// Made public for testing purposes
pub fn key_part_to_json(
    key_part: &recoco::base::value::KeyPart,
) -> Result<serde_json::Value, RecocoError> {
    use recoco::base::value::KeyPart;

    Ok(match key_part {
        KeyPart::Bytes(b) => {
            use base64::Engine;
            serde_json::Value::String(base64::engine::general_purpose::STANDARD.encode(b))
        }
        KeyPart::Str(s) => serde_json::Value::String(s.to_string()),
        KeyPart::Bool(b) => serde_json::Value::Bool(*b),
        KeyPart::Int64(i) => serde_json::Value::Number((*i).into()),
        KeyPart::Range(range) => serde_json::json!([range.start, range.end]),
        KeyPart::Uuid(uuid) => serde_json::Value::String(uuid.to_string()),
        KeyPart::Date(date) => serde_json::Value::String(date.to_string()),
        KeyPart::Struct(parts) => {
            let json_parts: Result<Vec<_>, _> = parts.iter().map(key_part_to_json).collect();
            serde_json::Value::Array(json_parts?)
        }
    })
}

/// Convert ReCoco Value to JSON for D1 API
/// Made public for testing purposes
pub fn value_to_json(value: &Value) -> Result<serde_json::Value, RecocoError> {
    Ok(match value {
        Value::Null => serde_json::Value::Null,
        Value::Basic(basic) => basic_value_to_json(basic)?,
        Value::Struct(field_values) => {
            let fields: Result<Vec<_>, _> = field_values.fields.iter().map(value_to_json).collect();
            serde_json::Value::Array(fields?)
        }
        Value::UTable(items) | Value::LTable(items) => {
            let json_items: Result<Vec<_>, _> = items
                .iter()
                .map(|scope_val| {
                    // ScopeValue(FieldValues)
                    let fields: Result<Vec<_>, _> =
                        scope_val.0.fields.iter().map(value_to_json).collect();
                    fields.map(serde_json::Value::Array)
                })
                .collect();
            serde_json::Value::Array(json_items?)
        }
        Value::KTable(map) => {
            let mut json_map = serde_json::Map::new();
            for (key, scope_val) in map {
                let key_str = format!("{:?}", key); // Simple key representation
                let fields: Result<Vec<_>, _> =
                    scope_val.0.fields.iter().map(value_to_json).collect();
                json_map.insert(key_str, serde_json::Value::Array(fields?));
            }
            serde_json::Value::Object(json_map)
        }
    })
}

/// Convert BasicValue to JSON
/// Made public for testing purposes
pub fn basic_value_to_json(value: &BasicValue) -> Result<serde_json::Value, RecocoError> {
    Ok(match value {
        BasicValue::Bool(b) => serde_json::Value::Bool(*b),
        BasicValue::Int64(i) => serde_json::Value::Number((*i).into()),
        BasicValue::Float32(f) => serde_json::Number::from_f64(*f as f64)
            .map(serde_json::Value::Number)
            .unwrap_or(serde_json::Value::Null),
        BasicValue::Float64(f) => serde_json::Number::from_f64(*f)
            .map(serde_json::Value::Number)
            .unwrap_or(serde_json::Value::Null),
        BasicValue::Str(s) => serde_json::Value::String(s.to_string()),
        BasicValue::Bytes(b) => {
            use base64::Engine;
            serde_json::Value::String(base64::engine::general_purpose::STANDARD.encode(b))
        }
        BasicValue::Json(j) => (**j).clone(),
        BasicValue::Vector(vec) => {
            let json_vec: Result<Vec<_>, _> = vec.iter().map(basic_value_to_json).collect();
            serde_json::Value::Array(json_vec?)
        }
        // Handle other BasicValue variants
        _ => serde_json::Value::String(format!("{:?}", value)),
    })
}

impl D1SetupState {
    pub fn new(
        table_id: &D1TableId,
        key_fields: &[FieldSchema],
        value_fields: &[FieldSchema],
    ) -> Result<Self, RecocoError> {
        let mut key_columns = vec![];
        let mut value_columns = vec![];
        let indexes = vec![];

        for field in key_fields {
            key_columns.push(ColumnSchema {
                name: field.name.clone(),
                // spellchecker:off
                sql_type: value_type_to_sql(&field.value_type.typ),
                // spellchecker:on
                nullable: field.value_type.nullable,
                primary_key: true,
            });
        }

        for field in value_fields {
            value_columns.push(ColumnSchema {
                name: field.name.clone(),
                // spellchecker:off
                sql_type: value_type_to_sql(&field.value_type.typ),
                // spellchecker:on
                nullable: field.value_type.nullable,
                primary_key: false,
            });
        }

        Ok(Self {
            table_id: table_id.clone(),
            key_columns,
            value_columns,
            indexes,
        })
    }

    pub fn create_table_sql(&self) -> String {
        let mut columns = vec![];

        for col in self.key_columns.iter().chain(self.value_columns.iter()) {
            let mut col_def = format!("{} {}", col.name, col.sql_type);
            if !col.nullable {
                col_def.push_str(" NOT NULL");
            }
            columns.push(col_def);
        }

        if !self.key_columns.is_empty() {
            let pk_cols: Vec<_> = self.key_columns.iter().map(|c| &c.name).collect();
            columns.push(format!(
                "PRIMARY KEY ({})",
                pk_cols
                    .iter()
                    .map(|s| s.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            ));
        }

        format!(
            "CREATE TABLE IF NOT EXISTS {} ({})",
            self.table_id.table_name,
            columns.join(", ")
        )
    }

    pub fn create_indexes_sql(&self) -> Vec<String> {
        self.indexes
            .iter()
            .map(|idx| {
                let unique = if idx.unique { "UNIQUE " } else { "" };
                format!(
                    "CREATE {}INDEX IF NOT EXISTS {} ON {} ({})",
                    unique,
                    idx.name,
                    self.table_id.table_name,
                    idx.columns.join(", ")
                )
            })
            .collect()
    }
}

/// Map ValueType to SQL type
/// Made public for testing purposes
pub fn value_type_to_sql(value_type: &ValueType) -> String {
    match value_type {
        ValueType::Basic(BasicValueType::Bool) => "INTEGER".to_string(),
        ValueType::Basic(BasicValueType::Int64) => "INTEGER".to_string(),
        ValueType::Basic(BasicValueType::Float32 | BasicValueType::Float64) => "REAL".to_string(),
        ValueType::Basic(BasicValueType::Str) => "TEXT".to_string(),
        ValueType::Basic(BasicValueType::Bytes) => "BLOB".to_string(),
        ValueType::Basic(BasicValueType::Json) => "TEXT".to_string(),
        _ => "TEXT".to_string(), // Default for complex types
    }
}

#[async_trait]
impl TargetFactoryBase for D1TargetFactory {
    type Spec = D1Spec;
    type DeclarationSpec = ();
    type SetupKey = D1TableId;
    type SetupState = D1SetupState;
    type SetupChange = D1SetupChange;
    type ExportContext = D1ExportContext;

    fn name(&self) -> &str {
        "d1"
    }

    async fn build(
        self: Arc<Self>,
        data_collections: Vec<TypedExportDataCollectionSpec<Self>>,
        _declarations: Vec<Self::DeclarationSpec>,
        context: Arc<FlowInstanceContext>,
    ) -> Result<
        (
            Vec<TypedExportDataCollectionBuildOutput<Self>>,
            Vec<(Self::SetupKey, Self::SetupState)>,
        ),
        RecocoError,
    > {
        use std::time::Duration;

        // Create shared HTTP client with connection pooling for all D1 contexts
        // This ensures efficient connection reuse across all D1 table operations
        let http_client = Arc::new(
            reqwest::Client::builder()
                // Connection pool configuration for Cloudflare D1 API
                .pool_max_idle_per_host(10) // Max idle connections per host
                .pool_idle_timeout(Some(Duration::from_secs(90))) // Keep connections warm
                .tcp_keepalive(Some(Duration::from_secs(60))) // Prevent firewall timeouts
                .http2_keep_alive_interval(Some(Duration::from_secs(30))) // HTTP/2 keep-alive pings
                .timeout(Duration::from_secs(30)) // Per-request timeout
                .build()
                .map_err(|e| {
                    RecocoError::internal_msg(format!("Failed to create HTTP client: {}", e))
                })?,
        );

        let mut build_outputs = vec![];
        let mut setup_states = vec![];

        for collection_spec in data_collections {
            let spec = collection_spec.spec.clone();

            let table_name = spec.table_name.clone().unwrap_or_else(|| {
                format!("{}_{}", context.flow_instance_name, collection_spec.name)
            });

            let table_id = D1TableId {
                database_id: spec.database_id.clone(),
                table_name: table_name.clone(),
            };

            let setup_state = D1SetupState::new(
                &table_id,
                &collection_spec.key_fields_schema,
                &collection_spec.value_fields_schema,
            )?;

            let database_id = spec.database_id.clone();
            let account_id = spec.account_id.clone();
            let api_token = spec.api_token.clone();
            let key_schema = collection_spec.key_fields_schema.to_vec();
            let value_schema = collection_spec.value_fields_schema.clone();
            let client = Arc::clone(&http_client);

            let export_context = Box::pin(async move {
                let metrics = crate::monitoring::performance::PerformanceMetrics::new();
                D1ExportContext::new(
                    database_id,
                    table_name,
                    account_id,
                    api_token,
                    client,
                    key_schema,
                    value_schema,
                    metrics,
                )
                .map(Arc::new)
            });

            build_outputs.push(TypedExportDataCollectionBuildOutput {
                setup_key: table_id.clone(),
                desired_setup_state: setup_state.clone(),
                export_context,
            });

            setup_states.push((table_id, setup_state));
        }

        Ok((build_outputs, setup_states))
    }

    async fn diff_setup_states(
        &self,
        _key: Self::SetupKey,
        desired_state: Option<Self::SetupState>,
        existing_states: CombinedState<Self::SetupState>,
        _flow_instance_ctx: Arc<FlowInstanceContext>,
    ) -> Result<Self::SetupChange, RecocoError> {
        let desired = desired_state
            .ok_or_else(|| RecocoError::client("No desired state provided for D1 table"))?;

        let mut change = D1SetupChange {
            table_id: desired.table_id.clone(),
            create_table_sql: None,
            create_indexes_sql: vec![],
            alter_table_sql: vec![],
        };

        if existing_states.staging.is_empty() {
            change.create_table_sql = Some(desired.create_table_sql());
            change.create_indexes_sql = desired.create_indexes_sql();
            return Ok(change);
        }

        if !existing_states.staging.is_empty() {
            change.create_indexes_sql = desired.create_indexes_sql();
        }

        Ok(change)
    }

    fn check_state_compatibility(
        &self,
        desired_state: &Self::SetupState,
        existing_state: &Self::SetupState,
    ) -> Result<SetupStateCompatibility, RecocoError> {
        if desired_state.key_columns != existing_state.key_columns
            || desired_state.value_columns != existing_state.value_columns
        {
            return Ok(SetupStateCompatibility::PartialCompatible);
        }

        if desired_state.indexes != existing_state.indexes {
            return Ok(SetupStateCompatibility::PartialCompatible);
        }

        Ok(SetupStateCompatibility::Compatible)
    }

    fn describe_resource(&self, key: &Self::SetupKey) -> Result<String, RecocoError> {
        Ok(format!("D1 table: {}.{}", key.database_id, key.table_name))
    }

    async fn apply_mutation(
        &self,
        mutations: Vec<ExportTargetMutationWithContext<'async_trait, Self::ExportContext>>,
    ) -> Result<(), RecocoError> {
        let mut mutations_by_db: thread_utilities::RapidMap<
            String,
            Vec<&ExportTargetMutationWithContext<'_, Self::ExportContext>>,
        > = thread_utilities::get_map();

        for mutation in &mutations {
            mutations_by_db
                .entry(mutation.export_context.database_id.clone())
                .or_default()
                .push(mutation);
        }

        for (_db_id, db_mutations) in mutations_by_db {
            for mutation in &db_mutations {
                if !mutation.mutation.upserts.is_empty() {
                    mutation
                        .export_context
                        .upsert(&mutation.mutation.upserts)
                        .await?;
                }
            }

            for mutation in &db_mutations {
                if !mutation.mutation.deletes.is_empty() {
                    mutation
                        .export_context
                        .delete(&mutation.mutation.deletes)
                        .await?;
                }
            }
        }

        Ok(())
    }

    async fn apply_setup_changes(
        &self,
        changes: Vec<TypedResourceSetupChangeItem<'async_trait, Self>>,
        _context: Arc<FlowInstanceContext>,
    ) -> Result<(), RecocoError> {
        // Note: For D1, we need account_id and api_token which are not in the SetupKey
        // This is a limitation - setup changes need to be applied manually or through
        // the same export context used for mutations
        // For now, we'll skip implementation as it requires additional context
        // that's not available in this method signature

        // TODO: Store API credentials in a way that's accessible during setup_changes
        // OR require that setup_changes are only called after build() which creates
        // the export_context

        for change_item in changes {
            eprintln!(
                "D1 setup changes for {}.{}: {} operations",
                change_item.setup_change.table_id.database_id,
                change_item.setup_change.table_id.table_name,
                change_item.setup_change.create_table_sql.is_some() as usize
                    + change_item.setup_change.alter_table_sql.len()
                    + change_item.setup_change.create_indexes_sql.len()
            );
        }

        Ok(())
    }
}