duroxide-cdb 0.1.6

A CosmosDB-based provider implementation for Duroxide, a durable task orchestration framework
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
use crate::client::{CosmosDBClient, QueryParameter};
use crate::models::*;
use duroxide::providers::ProviderError;
use duroxide::TagFilter;

/// Query for visible, unlocked orchestrator queue items in specific dispatch slots.
pub async fn find_candidate_orch_item(
    client: &CosmosDBClient,
    now_ms: u64,
    my_slots: &[u8],
    min_version_packed: Option<i64>,
    max_version_packed: Option<i64>,
    excluded_instances: &[String],
) -> Result<Option<QueueItemDocument>, ProviderError> {
    // If no slots assigned, skip query entirely
    if my_slots.is_empty() {
        return Ok(None);
    }

    let mut sql = format!(
        "SELECT * FROM c \
         WHERE c.type = '{}' \
         AND c.visibleAt <= @now \
         AND (NOT IS_DEFINED(c.lockedUntil) OR c.lockedUntil = null OR c.lockedUntil <= @now)",
        DOC_TYPE_ORCH_QUEUE
    );

    // Only add dispatchSlot filter when NOT all 256 slots are assigned
    if my_slots.len() < 256 {
        let slot_list = my_slots
            .iter()
            .map(|s| s.to_string())
            .collect::<Vec<_>>()
            .join(",");
        sql.push_str(&format!(" AND c.dispatchSlot IN ({})", slot_list));
    }

    let mut params = vec![QueryParameter::new("@now", serde_json::json!(now_ms))];

    // Capability filter
    if let (Some(min_v), Some(max_v)) = (min_version_packed, max_version_packed) {
        sql.push_str(
            " AND (NOT IS_DEFINED(c.pinnedDuroxideVersionPacked) \
             OR c.pinnedDuroxideVersionPacked = null \
             OR (c.pinnedDuroxideVersionPacked >= @minVersion \
                 AND c.pinnedDuroxideVersionPacked <= @maxVersion))",
        );
        params.push(QueryParameter::new("@minVersion", serde_json::json!(min_v)));
        params.push(QueryParameter::new("@maxVersion", serde_json::json!(max_v)));
    }

    // Exclude instances we already failed to lock
    for (i, instance) in excluded_instances.iter().enumerate() {
        let param_name = format!("@excl{i}");
        sql.push_str(&format!(" AND c.instanceId != {param_name}"));
        params.push(QueryParameter::new(param_name, serde_json::json!(instance)));
    }

    // No ORDER BY — cross-partition queries don't support it via gateway.
    // Sort client-side and pick the earliest.
    let results = client.query(&sql, params, None).await?;

    let mut items: Vec<QueueItemDocument> = results
        .into_iter()
        .map(|doc| serde_json::from_value(doc))
        .collect::<Result<Vec<_>, _>>()
        .map_err(|e| {
            ProviderError::permanent(
                "find_candidate_orch_item",
                format!("Failed to deserialize queue item: {e}"),
            )
        })?;

    // Sort by enqueuedAt ascending, pick earliest
    items.sort_by_key(|i| i.enqueued_at);
    Ok(items.into_iter().next())
}

/// Query for visible, unlocked worker queue items in specific dispatch slots.
pub async fn find_candidate_work_item(
    client: &CosmosDBClient,
    now_ms: u64,
    my_slots: &[u8],
    session_owner_id: Option<&str>,
    excluded_items: &[String],
    tag_filter: &TagFilter,
) -> Result<Option<QueueItemDocument>, ProviderError> {
    // If no slots assigned, skip query entirely
    if my_slots.is_empty() {
        return Ok(None);
    }

    let mut sql = format!(
        "SELECT * FROM c \
         WHERE c.type = '{}' \
         AND c.visibleAt <= @now \
         AND (NOT IS_DEFINED(c.lockedUntil) OR c.lockedUntil = null OR c.lockedUntil <= @now)",
        DOC_TYPE_WORKER_QUEUE
    );

    // Only add dispatchSlot filter when NOT all 256 slots are assigned
    if my_slots.len() < 256 {
        let slot_list = my_slots
            .iter()
            .map(|s| s.to_string())
            .collect::<Vec<_>>()
            .join(",");
        sql.push_str(&format!(" AND c.dispatchSlot IN ({})", slot_list));
    }

    let mut params = vec![QueryParameter::new("@now", serde_json::json!(now_ms))];

    // If no session config, skip session items
    if session_owner_id.is_none() {
        sql.push_str(" AND (NOT IS_DEFINED(c.sessionId) OR c.sessionId = null)");
    }

    // Tag filter clause
    match tag_filter {
        TagFilter::DefaultOnly => {
            sql.push_str(" AND (NOT IS_DEFINED(c.tag) OR c.tag = null)");
        }
        TagFilter::Tags(set) => {
            let mut tags: Vec<String> = set.iter().cloned().collect();
            tags.sort();
            let tag_list: Vec<String> = tags
                .iter()
                .enumerate()
                .map(|(i, tag)| {
                    let param_name = format!("@tag{i}");
                    params.push(QueryParameter::new(param_name.clone(), serde_json::json!(tag)));
                    param_name
                })
                .collect();
            sql.push_str(&format!(" AND c.tag IN ({})", tag_list.join(",")));
        }
        TagFilter::DefaultAnd(set) => {
            let mut tags: Vec<String> = set.iter().cloned().collect();
            tags.sort();
            let tag_list: Vec<String> = tags
                .iter()
                .enumerate()
                .map(|(i, tag)| {
                    let param_name = format!("@tag{i}");
                    params.push(QueryParameter::new(param_name.clone(), serde_json::json!(tag)));
                    param_name
                })
                .collect();
            sql.push_str(&format!(
                " AND (NOT IS_DEFINED(c.tag) OR c.tag = null OR c.tag IN ({}))",
                tag_list.join(",")
            ));
        }
        TagFilter::Any => {
            // No additional filter — fetch everything
        }
        TagFilter::None => {
            // Should not reach here (caller returns early), but be safe
            sql.push_str(" AND false");
        }
    }

    // Exclude items we already failed to lock
    for (i, item_id) in excluded_items.iter().enumerate() {
        let param_name = format!("@excl{i}");
        sql.push_str(&format!(" AND c.id != {param_name}"));
        params.push(QueryParameter::new(param_name, serde_json::json!(item_id)));
    }

    // No ORDER BY — cross-partition queries don't support it via gateway.
    // Sort client-side and pick the earliest.
    let results = client.query(&sql, params, None).await?;

    let mut items: Vec<QueueItemDocument> = results
        .into_iter()
        .map(|doc| serde_json::from_value(doc))
        .collect::<Result<Vec<_>, _>>()
        .map_err(|e| {
            ProviderError::permanent(
                "find_candidate_work_item",
                format!("Failed to deserialize work item: {e}"),
            )
        })?;

    // Sort by enqueuedAt ascending, pick earliest
    items.sort_by_key(|i| i.enqueued_at);
    Ok(items.into_iter().next())
}

/// Collect all pending messages for an instance from the orchestrator queue.
pub async fn collect_orch_messages(
    client: &CosmosDBClient,
    instance_id: &str,
    now_ms: u64,
) -> Result<Vec<QueueItemDocument>, ProviderError> {
    let sql = format!(
        "SELECT * FROM c \
         WHERE c.instanceId = @instanceId \
         AND c.type = '{}' \
         AND c.visibleAt <= @now \
         AND (NOT IS_DEFINED(c.lockedUntil) OR c.lockedUntil = null OR c.lockedUntil <= @now) \
         ORDER BY c.enqueuedAt",
        DOC_TYPE_ORCH_QUEUE
    );

    let params = vec![
        QueryParameter::new("@instanceId", serde_json::json!(instance_id)),
        QueryParameter::new("@now", serde_json::json!(now_ms)),
    ];

    let results = client.query(&sql, params, Some(instance_id)).await?;

    results
        .into_iter()
        .map(|doc| {
            serde_json::from_value(doc).map_err(|e| {
                ProviderError::permanent(
                    "collect_orch_messages",
                    format!("Failed to deserialize queue item: {e}"),
                )
            })
        })
        .collect()
}

/// Fetch history for an instance/execution.
pub async fn fetch_history(
    client: &CosmosDBClient,
    instance_id: &str,
    execution_id: u64,
) -> Result<Vec<HistoryDocument>, ProviderError> {
    let sql = format!(
        "SELECT * FROM c \
         WHERE c.instanceId = @instanceId \
         AND c.type = '{}' \
         AND c.executionId = @executionId \
         ORDER BY c.eventId",
        DOC_TYPE_HISTORY
    );

    let params = vec![
        QueryParameter::new("@instanceId", serde_json::json!(instance_id)),
        QueryParameter::new("@executionId", serde_json::json!(execution_id)),
    ];

    let results = client.query(&sql, params, Some(instance_id)).await?;

    results
        .into_iter()
        .map(|doc| {
            serde_json::from_value(doc).map_err(|e| {
                ProviderError::permanent(
                    "fetch_history",
                    format!("Failed to deserialize history doc: {e}"),
                )
            })
        })
        .collect()
}

/// Query for all documents by type in a partition.
pub async fn query_by_type_in_partition(
    client: &CosmosDBClient,
    instance_id: &str,
    doc_type: &str,
) -> Result<Vec<serde_json::Value>, ProviderError> {
    let sql = "SELECT * FROM c WHERE c.instanceId = @instanceId AND c.type = @type";
    let params = vec![
        QueryParameter::new("@instanceId", serde_json::json!(instance_id)),
        QueryParameter::new("@type", serde_json::json!(doc_type)),
    ];
    client.query(sql, params, Some(instance_id)).await
}

/// Query instances across all partitions with optional status filter.
pub async fn query_instances(
    client: &CosmosDBClient,
    status_filter: Option<&str>,
) -> Result<Vec<InstanceDocument>, ProviderError> {
    let mut sql = format!("SELECT * FROM c WHERE c.type = '{}'", DOC_TYPE_INSTANCE);
    let mut params = vec![];

    if let Some(status) = status_filter {
        sql.push_str(" AND c.status = @status");
        params.push(QueryParameter::new("@status", serde_json::json!(status)));
    }

    let results = client.query(&sql, params, None).await?;

    results
        .into_iter()
        .map(|doc| {
            serde_json::from_value(doc).map_err(|e| {
                ProviderError::permanent(
                    "query_instances",
                    format!("Failed to deserialize instance: {e}"),
                )
            })
        })
        .collect()
}

/// Find orch_queue items locked by a specific lock token.
pub async fn find_items_by_lock_token(
    client: &CosmosDBClient,
    lock_token: &str,
    doc_type: &str,
) -> Result<Vec<QueueItemDocument>, ProviderError> {
    let sql = format!("SELECT * FROM c WHERE c.type = @type AND c.lockToken = @lockToken");
    let params = vec![
        QueryParameter::new("@type", serde_json::json!(doc_type)),
        QueryParameter::new("@lockToken", serde_json::json!(lock_token)),
    ];

    let results = client.query(&sql, params, None).await?;

    results
        .into_iter()
        .map(|doc| {
            serde_json::from_value(doc).map_err(|e| {
                ProviderError::permanent(
                    "find_items_by_lock_token",
                    format!("Failed to deserialize queue item: {e}"),
                )
            })
        })
        .collect()
}

/// Find instance by lock token.
pub async fn find_instance_by_lock_token(
    client: &CosmosDBClient,
    lock_token: &str,
) -> Result<Option<InstanceDocument>, ProviderError> {
    let sql = format!(
        "SELECT * FROM c WHERE c.type = '{}' AND c.lockToken = @lockToken",
        DOC_TYPE_INSTANCE
    );
    let params = vec![QueryParameter::new(
        "@lockToken",
        serde_json::json!(lock_token),
    )];

    let results = client.query(&sql, params, None).await?;

    if let Some(doc) = results.into_iter().next() {
        let inst: InstanceDocument = serde_json::from_value(doc).map_err(|e| {
            ProviderError::permanent(
                "find_instance_by_lock_token",
                format!("Failed to deserialize instance: {e}"),
            )
        })?;
        Ok(Some(inst))
    } else {
        Ok(None)
    }
}

/// Query pending outbox intents older than a threshold.
pub async fn query_pending_intents(
    client: &CosmosDBClient,
    age_threshold_ms: u64,
    now_ms: u64,
) -> Result<Vec<crate::models::OutboxIntentDocument>, ProviderError> {
    let cutoff = now_ms.saturating_sub(age_threshold_ms);
    let sql = format!(
        "SELECT * FROM c WHERE c.type = '{}' AND c.status = 'pending' AND c.createdAt <= @cutoff",
        DOC_TYPE_OUTBOX_INTENT
    );
    let params = vec![QueryParameter::new("@cutoff", serde_json::json!(cutoff))];

    let results = client.query(&sql, params, None).await?;

    results
        .into_iter()
        .map(|doc| {
            serde_json::from_value(doc).map_err(|e| {
                ProviderError::permanent(
                    "query_pending_intents",
                    format!("Failed to deserialize outbox intent: {e}"),
                )
            })
        })
        .collect()
}

/// Query all documents in a partition (for deletion).
pub async fn query_all_in_partition(
    client: &CosmosDBClient,
    instance_id: &str,
) -> Result<Vec<serde_json::Value>, ProviderError> {
    let sql = "SELECT c.id FROM c WHERE c.instanceId = @instanceId";
    let params = vec![QueryParameter::new(
        "@instanceId",
        serde_json::json!(instance_id),
    )];
    client.query(sql, params, Some(instance_id)).await
}

/// Count documents by type (cross-partition).
/// Uses client-side counting since cross-partition aggregates aren't supported via gateway.
pub async fn count_by_type(
    client: &CosmosDBClient,
    doc_type: &str,
    extra_filter: Option<&str>,
) -> Result<usize, ProviderError> {
    let mut sql = format!("SELECT c.id FROM c WHERE c.type = @type");
    if let Some(filter) = extra_filter {
        sql.push_str(&format!(" AND {filter}"));
    }
    let params = vec![QueryParameter::new("@type", serde_json::json!(doc_type))];
    let results = client.query(&sql, params, None).await?;
    Ok(results.len())
}