vyuh 0.2.11

Vyuh web framework for Axum and SQLx with handler-first APIs
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
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
use serde::{Deserialize, Serialize};
use std::{any::TypeId, borrow::Cow, collections::HashMap, sync::Arc, time::Duration};

use crate::{
    Error, Site,
    callables::{self, Callable},
};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskConf {
    pub poll_interval_ms: u32,
    pub capacity: usize,
    pub concurrency: usize,
    pub batch_size: usize,
    pub lease_duration_ms: u32,
}

impl Default for TaskConf {
    fn default() -> Self {
        Self {
            poll_interval_ms: 15000,
            capacity: 1000,
            concurrency: 10,
            batch_size: 250,
            lease_duration_ms: 300000,
        }
    }
}

#[derive(Clone)]
pub struct TaskContext {
    site: Site,
    payload: callables::DataBox,
    record: Arc<TaskRecord>,
}

impl callables::IntoDataBox for TaskContext {
    fn into_data_box(self) -> callables::DataBox {
        self.payload
    }
}

impl callables::HasSite for TaskContext {
    fn site(&self) -> &Site {
        &self.site
    }
}

type TaskHandler = Callable<TaskContext, Error>;

#[derive(Debug, thiserror::Error)]
pub enum TaskError {
    #[error("Type mismatch: expected {0}, got {1}")]
    TypeMismatch(String, String),

    #[error("Task '{0}' not found")]
    TaskNotFound(String),

    #[error("Task JSON error: {0}")]
    JsonError(#[from] serde_json::Error),

    #[error("Task execution error: {0}")]
    TaskExecutionError(String),

    #[error("Task already exists: {0}")]
    AlreadyExists(String),

    #[error("Identity already exists")]
    IdentityError,

    #[error(transparent)]
    CallError(#[from] crate::callables::CallError),

    #[error("Database error: {0}")]
    DatabaseError(#[from] sqlx::Error),

    #[error("Unknown task error: {0}")]
    Other(#[from] Box<dyn std::error::Error + Send + Sync>),
}

#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema, sqlx::Type,
)]
#[repr(i16)]
#[serde(rename_all = "lowercase")]
pub enum TaskStatus {
    Pending = 0,
    Running = 1,
    Suspended = 2,
    Succeeded = 3,
    Failed = 4,
}

impl TaskStatus {
    pub const fn as_i16(self) -> i16 {
        self as i16
    }

    pub fn as_str(self) -> &'static str {
        match self {
            TaskStatus::Pending => "pending",
            TaskStatus::Running => "running",
            TaskStatus::Suspended => "suspended",
            TaskStatus::Succeeded => "succeeded",
            TaskStatus::Failed => "failed",
        }
    }
}

#[derive(Debug, Default, Clone)]
pub struct TaskHandlerConf {
    pub name: String,
}

impl TaskHandlerConf {
    pub fn new(name: impl Into<String>) -> Self {
        Self { name: name.into() }
    }
}

#[derive(Debug, Default, Clone)]
pub struct TaskOptions {
    pub initial_delay: Option<Duration>,
    pub retry_delay: Option<Duration>,
    pub lease_duration: Option<Duration>,
    pub identity: Option<String>,
    pub max_attempts: Option<i32>,
    pub state: Option<String>,
    pub priority: i32,
}

#[derive(Debug, Clone)]
pub struct TaskListFilter {
    pub status: Option<TaskStatus>,
    pub name: Option<String>,
    pub priority_min: Option<i32>,
    pub identity: Option<String>,
    pub created_from: Option<chrono::DateTime<chrono::Utc>>,
    pub created_to: Option<chrono::DateTime<chrono::Utc>>,
    pub q: Option<String>,
    pub limit: usize,
    pub offset: usize,
}

impl Default for TaskListFilter {
    fn default() -> Self {
        Self {
            status: None,
            name: None,
            priority_min: None,
            identity: None,
            created_from: None,
            created_to: None,
            q: None,
            limit: 50,
            offset: 0,
        }
    }
}

#[derive(Debug, Clone)]
pub struct TaskListPage {
    pub records: Vec<TaskRecord>,
    pub next_cursor: Option<String>,
}

#[derive(Debug, Clone, sqlx::FromRow)]
pub struct TaskRecord {
    pub id: uuid::Uuid,
    pub name: String,
    pub input: String,
    pub state: Option<String>,
    pub resume_input: Option<String>,
    pub output: Option<String>,
    pub result: Option<String>,
    pub status: TaskStatus,
    pub attempts: i32,
    pub priority: i32,
    pub max_attempts: Option<i32>,
    pub retry_delay_ms: Option<i64>,
    pub lease_duration_ms: Option<i64>,
    pub last_error: Option<String>,
    pub identity: Option<String>,
    pub locked_by: Option<String>,
    pub leased_until: Option<chrono::DateTime<chrono::Utc>>,
    pub ready_at: Option<chrono::DateTime<chrono::Utc>>,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub updated_at: chrono::DateTime<chrono::Utc>,
    pub completed_at: Option<chrono::DateTime<chrono::Utc>>,
}

impl TaskRecord {
    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn input<T>(&self) -> Result<T, TaskError>
    where
        T: serde::de::DeserializeOwned,
    {
        serde_json::from_str(&self.input).map_err(TaskError::from)
    }

    pub fn state<T>(&self) -> Result<Option<T>, TaskError>
    where
        T: serde::de::DeserializeOwned,
    {
        self.state
            .as_deref()
            .map(serde_json::from_str)
            .transpose()
            .map_err(TaskError::from)
    }

    pub fn resume_input<T>(&self) -> Result<Option<T>, TaskError>
    where
        T: serde::de::DeserializeOwned,
    {
        self.resume_input
            .as_deref()
            .map(serde_json::from_str)
            .transpose()
            .map_err(TaskError::from)
    }
}

pub(crate) fn sort_claimed_tasks(tasks: &mut [TaskRecord]) {
    tasks.sort_by_key(|task| {
        (
            std::cmp::Reverse(task.priority),
            task.ready_at.unwrap_or(task.created_at),
            task.created_at,
        )
    });
}

#[derive(Debug, Clone)]
#[doc(hidden)]
pub enum TaskOutcome {
    Complete {
        result: String,
    },
    Suspend {
        state: String,
        output: Option<String>,
    },
    Sleep {
        state: String,
        delay: Duration,
    },
    Retry {
        delay: Option<Duration>,
        error: String,
    },
    Fail {
        error: String,
    },
}

impl TaskOutcome {
    pub fn complete<T: Serialize>(result: &T) -> Result<Self, TaskError> {
        Ok(Self::Complete {
            result: serde_json::to_string(result)?,
        })
    }

    pub fn suspend<S: Serialize, O: Serialize>(
        state: &S,
        output: Option<&O>,
    ) -> Result<Self, TaskError> {
        Ok(Self::Suspend {
            state: serde_json::to_string(state)?,
            output: output.map(serde_json::to_string).transpose()?,
        })
    }

    pub fn sleep<S: Serialize>(state: &S, delay: Duration) -> Result<Self, TaskError> {
        Ok(Self::Sleep {
            state: serde_json::to_string(state)?,
            delay,
        })
    }

    pub fn retry(delay: Option<Duration>, error: impl Into<String>) -> Self {
        Self::Retry {
            delay,
            error: error.into(),
        }
    }

    pub fn fail(error: impl Into<String>) -> Self {
        Self::Fail {
            error: error.into(),
        }
    }

    pub(crate) fn retry_error(delay: Option<Duration>, error: &Error) -> Self {
        Self::retry(delay, error.display_compact())
    }

    pub(crate) fn fail_error(error: &Error) -> Self {
        Self::fail(error.display_compact())
    }
}

impl<E> callables::IntoOutput<E> for TaskOutcome {
    fn into_output(self) -> Result<callables::DataBox, E> {
        Ok(callables::DataBox::new(self))
    }
}

impl callables::IntoReturnPart for TaskOutcome {
    fn into_return_part() -> callables::ReturnPart {
        callables::ReturnPart::Empty
    }
}

#[doc(hidden)]
pub trait IntoTaskOutcomePart {
    fn into_task_outcome(data: callables::DataBox) -> TaskOutcome;
}

impl IntoTaskOutcomePart for () {
    fn into_task_outcome(data: callables::DataBox) -> TaskOutcome {
        if data.downcast_ref::<()>().is_some() {
            TaskOutcome::Complete {
                result: "null".to_string(),
            }
        } else {
            unexpected_output()
        }
    }
}

impl IntoTaskOutcomePart for TaskOutcome {
    fn into_task_outcome(data: callables::DataBox) -> TaskOutcome {
        match data.downcast_ref::<TaskOutcome>() {
            Some(output) => output.clone(),
            None => unexpected_output(),
        }
    }
}

impl<T: callables::DataValue> IntoTaskOutcomePart for crate::Data<T> {
    fn into_task_outcome(data: callables::DataBox) -> TaskOutcome {
        match data.downcast_ref::<T>() {
            Some(value) => match TaskOutcome::complete(value) {
                Ok(outcome) => outcome,
                Err(err) => TaskOutcome::fail(format!("Task output serialization error: {err}")),
            },
            None => unexpected_output(),
        }
    }
}

impl<T, E> IntoTaskOutcomePart for Result<T, E>
where
    T: IntoTaskOutcomePart,
{
    fn into_task_outcome(data: callables::DataBox) -> TaskOutcome {
        T::into_task_outcome(data)
    }
}

fn unexpected_output() -> TaskOutcome {
    TaskOutcome::fail("Task handler returned an unexpected output type")
}

/// Opaque return type for task handlers.
///
/// Create via static constructors: `TaskState::complete`, `TaskState::suspend`,
/// `TaskState::sleep`, `TaskState::retry`, `TaskState::fail`.
/// The type parameter `O` is the output payload type.
pub struct TaskState<O = ()> {
    inner: TaskOutcome,
    _phantom: std::marker::PhantomData<fn() -> O>,
}

impl<O: Serialize> TaskState<O> {
    pub fn complete(output: O) -> Result<Self, TaskError> {
        Ok(Self {
            inner: TaskOutcome::Complete {
                result: serde_json::to_string(&output)?,
            },
            _phantom: std::marker::PhantomData,
        })
    }

    pub fn suspend<S: Serialize>(output: O, state: S) -> Result<Self, TaskError> {
        Ok(Self {
            inner: TaskOutcome::Suspend {
                state: serde_json::to_string(&state)?,
                output: Some(serde_json::to_string(&output)?),
            },
            _phantom: std::marker::PhantomData,
        })
    }

    pub fn sleep<S: Serialize>(state: S, delay: Duration) -> Result<Self, TaskError> {
        Ok(Self {
            inner: TaskOutcome::Sleep {
                state: serde_json::to_string(&state)?,
                delay,
            },
            _phantom: std::marker::PhantomData,
        })
    }

    pub fn retry(delay: Option<Duration>, error: impl Into<String>) -> Self {
        Self {
            inner: TaskOutcome::Retry {
                delay,
                error: error.into(),
            },
            _phantom: std::marker::PhantomData,
        }
    }

    pub fn fail(error: impl Into<String>) -> Self {
        Self {
            inner: TaskOutcome::Fail {
                error: error.into(),
            },
            _phantom: std::marker::PhantomData,
        }
    }
}

impl<O, E: From<TaskError>> callables::IntoOutput<E> for TaskState<O> {
    fn into_output(self) -> Result<callables::DataBox, E> {
        Ok(callables::DataBox::new(self.inner))
    }
}

impl<O> callables::IntoReturnPart for TaskState<O> {
    fn into_return_part() -> callables::ReturnPart {
        callables::ReturnPart::Empty
    }
}

impl<O> IntoTaskOutcomePart for TaskState<O> {
    fn into_task_outcome(data: callables::DataBox) -> TaskOutcome {
        TaskOutcome::into_task_outcome(data)
    }
}

impl<O> TaskState<O> {
    /// Unwrap into the underlying [`TaskOutcome`] for use by store implementors and tests.
    pub fn into_outcome(self) -> TaskOutcome {
        self.inner
    }
}

/// Optional DI parameter for task handlers that need suspend/resume.
///
/// Inject via handler signature: `suspension: Suspension<O>`.
/// Use `suspension.get()` to retrieve the resume value if the task was resumed.
pub struct Suspension<T> {
    resume_input: Option<T>,
}

impl<T: serde::de::DeserializeOwned + Send> callables::FromContextParts<TaskContext>
    for Suspension<T>
{
    fn from_context_parts(ctx: &TaskContext) -> Result<Self, callables::CallError> {
        let resume_input = ctx
            .record
            .resume_input
            .as_deref()
            .map(serde_json::from_str::<T>)
            .transpose()
            .map_err(|_| callables::CallError::DeserializeFailed)?;
        Ok(Self { resume_input })
    }
}

impl<T> callables::IntoArgPart for Suspension<T> {
    fn into_arg_part() -> callables::ArgPart {
        callables::ArgPart::Ignore
    }
}

impl<T: Clone> Suspension<T> {
    /// Returns the resume payload if this task execution was triggered by a resume.
    /// Returns `None` on the first (non-resumed) execution.
    pub fn get(&self) -> Option<T> {
        self.resume_input.clone()
    }
}

pub struct TaskMeta {
    pub about: Cow<'static, str>,
    pub type_name: Cow<'static, str>,
    pub schema_fn: fn(&mut schemars::SchemaGenerator) -> schemars::Schema,
}

#[derive(Clone)]
pub struct TaskService {
    pub name: String,
    pub type_id: TypeId,
    pub type_name: String,
    pub coerce: fn(&str) -> Result<(), TaskError>,
    output: fn(callables::DataBox) -> TaskOutcome,
    handler: TaskHandler,
}

impl TaskService {
    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn validate_data(&self, data: &str) -> Result<(), TaskError> {
        (self.coerce)(data)
    }

    pub fn validate_object<T: 'static>(&self, _obj: &T) -> Result<(), TaskError> {
        if self.type_id != TypeId::of::<T>() {
            return Err(TaskError::TypeMismatch(
                self.type_name.clone(),
                std::any::type_name::<T>().to_string(),
            ));
        }
        Ok(())
    }

    pub async fn execute(&self, site: Site, record: Arc<TaskRecord>) -> TaskOutcome {
        let payload = match self.handler.deserialize_input(&record.input) {
            Ok(value) => value,
            Err(e) => return TaskOutcome::fail(format!("Task input error: {}", e)),
        };

        let ctx = TaskContext {
            site,
            payload,
            record,
        };

        let data = match self.handler.call(ctx).await {
            Ok(data) => data,
            Err(e) => return TaskOutcome::fail_error(&e),
        };

        (self.output)(data)
    }

    pub fn new<T, H, Args>(name: &str, handler: H) -> Self
    where
        T: callables::DataValue,
        H: callables::Specable<Args> + Send + Sync + 'static,
        H::Output: callables::IntoOutput<Error>
            + callables::IntoReturnPart
            + IntoTaskOutcomePart
            + Send
            + 'static,
        Args: callables::FromContext<TaskContext>
            + callables::IntoArgSpecs
            + callables::HasData<T>
            + Send
            + 'static,
    {
        let callable: callables::Callable<TaskContext, Error> = Callable::new(handler);
        let coerce = |data: &str| -> Result<(), TaskError> {
            let _: T = serde_json::from_str(data)?;
            Ok(())
        };
        TaskService {
            name: name.to_string(),
            type_id: TypeId::of::<T>(),
            type_name: std::any::type_name::<T>().to_string(),
            coerce,
            output: H::Output::into_task_outcome,
            handler: callable,
        }
    }
}

#[derive(Clone)]
pub struct TaskRegistry {
    pub(crate) config: TaskConf,
    pub(crate) tasks: HashMap<String, TaskService>,
    pub(crate) typed_map: HashMap<TypeId, String>,
}

impl TaskRegistry {
    pub fn new() -> Self {
        Self {
            config: TaskConf::default(),
            tasks: HashMap::new(),
            typed_map: HashMap::new(),
        }
    }

    pub fn with_config(self, config: TaskConf) -> Self {
        Self {
            config,
            tasks: self.tasks,
            typed_map: self.typed_map,
        }
    }

    pub fn iter_services(&self) -> impl Iterator<Item = &TaskService> {
        self.tasks.values()
    }

    pub fn is_empty(&self) -> bool {
        self.tasks.is_empty()
    }

    pub fn register(&mut self, service: TaskService) -> Result<(), TaskError> {
        let name = service.name().to_string();
        if self.tasks.contains_key(&name) || self.typed_map.contains_key(&service.type_id) {
            return Err(TaskError::AlreadyExists(name));
        }
        self.typed_map.insert(service.type_id, name.clone());
        self.tasks.insert(name, service);
        Ok(())
    }

    pub fn merge(&mut self, other: TaskRegistry) -> Result<(), TaskError> {
        for (name, task) in other.tasks {
            if self.tasks.contains_key(&name) {
                return Err(TaskError::AlreadyExists(name));
            }
            if self.typed_map.contains_key(&task.type_id) {
                return Err(TaskError::AlreadyExists(name));
            }
            self.typed_map.insert(task.type_id, name.clone());
            self.tasks.insert(name, task);
        }
        Ok(())
    }

    pub(crate) fn dispatcher<S: crate::tasks::store::AbstractTaskStore + Send + Sync + 'static>(
        self: Arc<Self>,
        store: Arc<S>,
    ) -> TaskDispatcher<S> {
        TaskDispatcher {
            store,
            registry: self.clone(),
            notifier: Arc::new(tokio::sync::Notify::new()),
        }
    }

    pub async fn execute(&self, site: Site, record: Arc<TaskRecord>) -> TaskOutcome {
        let task = match self.tasks.get(record.name()) {
            Some(task) => task,
            None => return TaskOutcome::fail(format!("Task '{}' not found", record.name())),
        };
        task.execute(site, record).await
    }
}

#[derive(Clone)]
pub struct TaskDispatcher<S: crate::tasks::store::AbstractTaskStore + Send + Sync + 'static> {
    pub(crate) store: Arc<S>,
    pub(crate) notifier: Arc<tokio::sync::Notify>,
    pub(crate) registry: Arc<TaskRegistry>,
}

#[derive(Clone)]
pub struct TaskClient<S: crate::tasks::store::AbstractTaskStore + Send + Sync + 'static> {
    dispatcher: TaskDispatcher<S>,
}

impl<S: crate::tasks::store::AbstractTaskStore + Send + Sync + 'static> TaskClient<S> {
    pub(crate) fn new(dispatcher: TaskDispatcher<S>) -> Self {
        Self { dispatcher }
    }

    pub async fn submit<T: Serialize + 'static>(&self, input: T) -> Result<uuid::Uuid, TaskError> {
        self.dispatcher.submit(input).await
    }

    pub async fn submit_with<T: Serialize + 'static>(
        &self,
        input: T,
        conf: TaskOptions,
    ) -> Result<uuid::Uuid, TaskError> {
        self.dispatcher.submit_with(input, conf).await
    }

    pub async fn resume<T: Serialize>(&self, id: uuid::Uuid, input: T) -> Result<u64, TaskError> {
        self.dispatcher.resume(id, input).await
    }

    pub async fn list(&self, filter: TaskListFilter) -> Result<TaskListPage, TaskError> {
        self.dispatcher.list(filter).await
    }

    pub async fn get(&self, id: uuid::Uuid) -> Result<Option<TaskRecord>, TaskError> {
        self.dispatcher.get(id).await
    }
}

impl<S: crate::tasks::store::AbstractTaskStore + Send + Sync + 'static> TaskDispatcher<S> {
    pub fn has_tasks(&self) -> bool {
        !self.registry.is_empty()
    }

    pub fn store(&self) -> Arc<S> {
        self.store.clone()
    }

    pub async fn submit<T: 'static + Serialize>(&self, input: T) -> Result<uuid::Uuid, TaskError> {
        let name = self
            .registry
            .typed_map
            .get(&TypeId::of::<T>())
            .ok_or_else(|| TaskError::TaskNotFound("Unknown task type".to_string()))?
            .clone();
        self.submit_registered::<T>(&name, input, TaskOptions::default())
            .await
    }

    pub async fn submit_with<T: 'static + Serialize>(
        &self,
        input: T,
        conf: TaskOptions,
    ) -> Result<uuid::Uuid, TaskError> {
        let name = self
            .registry
            .typed_map
            .get(&TypeId::of::<T>())
            .ok_or_else(|| TaskError::TaskNotFound("Unknown task type".to_string()))?
            .clone();
        self.submit_registered::<T>(&name, input, conf).await
    }

    async fn submit_registered<T: 'static + Serialize>(
        &self,
        name: &str,
        input: T,
        conf: TaskOptions,
    ) -> Result<uuid::Uuid, TaskError> {
        if let Some(s) = self.registry.tasks.get(name) {
            s.validate_object(&input)?;
        } else {
            return Err(TaskError::TaskNotFound(name.to_string()));
        }
        let data = serde_json::to_string(&input)?;
        self.submit_serialized(name, data, conf).await
    }

    async fn submit_serialized(
        &self,
        name: &str,
        input: String,
        conf: TaskOptions,
    ) -> Result<uuid::Uuid, TaskError> {
        let now = chrono::Utc::now();
        let ready_at = Some(match conf.initial_delay {
            Some(delay) => now + chrono::Duration::from_std(delay).unwrap_or_default(),
            None => now,
        });
        let retry_delay_ms = conf
            .retry_delay
            .map(|delay| delay.as_millis().min(i64::MAX as u128) as i64);
        let lease_duration_ms = conf
            .lease_duration
            .map(|duration| duration.as_millis().min(i64::MAX as u128) as i64);
        let record = TaskRecord {
            id: uuid::Uuid::now_v7(),
            name: name.to_string(),
            input,
            state: conf.state,
            resume_input: None,
            output: None,
            result: None,
            status: TaskStatus::Pending,
            attempts: 0,
            priority: conf.priority,
            max_attempts: conf.max_attempts,
            retry_delay_ms,
            lease_duration_ms,
            last_error: None,
            identity: conf.identity,
            locked_by: None,
            leased_until: None,
            ready_at,
            created_at: now,
            updated_at: now,
            completed_at: None,
        };
        let task_id = record.id;
        self.store.store_task(record).await?;
        self.notifier.notify_one();
        Ok(task_id)
    }

    pub async fn resume<T: Serialize>(&self, id: uuid::Uuid, input: T) -> Result<u64, TaskError> {
        let input = serde_json::to_string(&input)?;
        let count = self.store.resume(id, input).await?;
        if count > 0 {
            self.notifier.notify_waiters();
        }
        Ok(count)
    }

    pub async fn list(&self, filter: TaskListFilter) -> Result<TaskListPage, TaskError> {
        self.store.list_tasks(filter).await
    }

    pub async fn get(&self, id: uuid::Uuid) -> Result<Option<TaskRecord>, TaskError> {
        self.store.get_task(id).await
    }
}

impl std::fmt::Debug for TaskRegistry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TaskRegistry")
            .field("tasks", &self.tasks.keys().collect::<Vec<_>>())
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use schemars::JsonSchema;
    use serde::{Deserialize, Serialize};

    use super::*;
    use crate::{
        Data, SiteError,
        tasks::{MemoryTaskStore, store::AbstractTaskStore},
    };

    #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
    struct DirectJob {
        id: i64,
    }

    #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
    struct ReportOutput {
        value: String,
    }

    async fn direct_job(input: Data<DirectJob>) -> Result<TaskState<String>, crate::Error> {
        Ok(TaskState::complete(format!("direct:{}", input.id))?)
    }

    async fn unit_job(_input: Data<DirectJob>) {}

    async fn result_unit_job(_input: Data<DirectJob>) -> Result<(), crate::Error> {
        Ok(())
    }

    async fn data_job(input: Data<DirectJob>) -> Data<ReportOutput> {
        Data::new(ReportOutput {
            value: format!("data:{}", input.id),
        })
    }

    async fn result_data_job(input: Data<DirectJob>) -> Result<Data<ReportOutput>, crate::Error> {
        Ok(Data::new(ReportOutput {
            value: format!("result:{}", input.id),
        }))
    }

    async fn result_data_error(
        _input: Data<DirectJob>,
    ) -> Result<Data<ReportOutput>, crate::Error> {
        Err(crate::Error::invalid("data failed"))
    }

    fn record<T: Serialize>(name: &str, input: &T) -> Result<Arc<TaskRecord>, TaskError> {
        let now = chrono::Utc::now();
        Ok(Arc::new(TaskRecord {
            id: uuid::Uuid::now_v7(),
            name: name.to_string(),
            input: serde_json::to_string(input)?,
            state: None,
            resume_input: None,
            output: None,
            result: None,
            status: TaskStatus::Running,
            attempts: 0,
            priority: 0,
            max_attempts: None,
            retry_delay_ms: None,
            lease_duration_ms: None,
            last_error: None,
            identity: None,
            locked_by: Some("runner-a".to_string()),
            leased_until: None,
            ready_at: Some(now),
            created_at: now,
            updated_at: now,
            completed_at: None,
        }))
    }

    async fn test_site() -> Result<Site, SiteError> {
        Site::build(
            crate::SiteConf::default().log_init(false),
            crate::bundles::bundle([]),
        )
        .await
    }

    fn complete_result(outcome: TaskOutcome) -> Option<String> {
        match outcome {
            TaskOutcome::Complete { result } => Some(result),
            _ => None,
        }
    }

    fn failed_error(outcome: TaskOutcome) -> Option<String> {
        match outcome {
            TaskOutcome::Fail { error } => Some(error),
            _ => None,
        }
    }

    #[tokio::test]
    async fn direct_registration_supports_typed_submit() -> Result<(), TaskError> {
        let mut registry = TaskRegistry::new();
        registry.register(TaskService::new("direct_job", direct_job))?;

        let store = Arc::new(MemoryTaskStore::new(10));
        let dispatcher = Arc::new(registry).dispatcher(store.clone());
        let client = TaskClient::new(dispatcher);

        let task_id = client.submit(DirectJob { id: 42 }).await?;
        let claimed = store.claim_tasks("runner-a").await?;

        assert_eq!(claimed.len(), 1);
        assert_eq!(claimed[0].id, task_id);
        assert_eq!(claimed[0].name, "direct_job");
        assert_eq!(claimed[0].input::<DirectJob>()?.id, 42);

        store
            .commit_outcome(task_id, "runner-a", TaskOutcome::complete(&"done")?)
            .await?;
        Ok(())
    }

    #[tokio::test]
    async fn task_unit_output_completes_with_null() -> Result<(), Box<dyn std::error::Error>> {
        let service = TaskService::new("unit_job", unit_job);
        let outcome = service
            .execute(
                test_site().await?,
                record("unit_job", &DirectJob { id: 7 })?,
            )
            .await;

        assert_eq!(complete_result(outcome).as_deref(), Some("null"));
        Ok(())
    }

    #[tokio::test]
    async fn task_result_unit_output_completes_with_null() -> Result<(), Box<dyn std::error::Error>>
    {
        let service = TaskService::new("result_unit_job", result_unit_job);
        let outcome = service
            .execute(
                test_site().await?,
                record("result_unit_job", &DirectJob { id: 7 })?,
            )
            .await;

        assert_eq!(complete_result(outcome).as_deref(), Some("null"));
        Ok(())
    }

    #[tokio::test]
    async fn task_state_output_still_controls_outcome() -> Result<(), Box<dyn std::error::Error>> {
        let service = TaskService::new("direct_job", direct_job);
        let outcome = service
            .execute(
                test_site().await?,
                record("direct_job", &DirectJob { id: 7 })?,
            )
            .await;

        assert_eq!(complete_result(outcome).as_deref(), Some("\"direct:7\""));
        Ok(())
    }

    #[tokio::test]
    async fn task_data_output_completes_with_payload() -> Result<(), Box<dyn std::error::Error>> {
        let service = TaskService::new("data_job", data_job);
        let outcome = service
            .execute(
                test_site().await?,
                record("data_job", &DirectJob { id: 7 })?,
            )
            .await;

        assert_eq!(
            complete_result(outcome).as_deref(),
            Some("{\"value\":\"data:7\"}")
        );
        Ok(())
    }

    #[tokio::test]
    async fn task_result_data_output_completes_with_payload()
    -> Result<(), Box<dyn std::error::Error>> {
        let service = TaskService::new("result_data_job", result_data_job);
        let outcome = service
            .execute(
                test_site().await?,
                record("result_data_job", &DirectJob { id: 7 })?,
            )
            .await;

        assert_eq!(
            complete_result(outcome).as_deref(),
            Some("{\"value\":\"result:7\"}")
        );
        Ok(())
    }

    #[tokio::test]
    async fn task_result_data_error_fails_task() -> Result<(), Box<dyn std::error::Error>> {
        let service = TaskService::new("result_data_error", result_data_error);
        let outcome = service
            .execute(
                test_site().await?,
                record("result_data_error", &DirectJob { id: 7 })?,
            )
            .await;

        assert!(failed_error(outcome).is_some_and(|error| error.contains("data failed")));
        Ok(())
    }
}