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
// SPDX-License-Identifier: MIT OR Apache-2.0
use crate;
use AtomicWaker;
use Any;
use Infallible;
use Future;
use Pin;
use Arc;
use AtomicBool;
use ;
use Mutex;
/// Represents the state of an observed task.
///
/// This enum is returned by [`Observer::observe`] to indicate the current status
/// of a task being observed. Once a task completes with [`Observation::Ready`],
/// subsequent observations will return [`Observation::Done`].
///
/// # Examples
///
/// ```
/// use some_executor::observer::Observation;
///
/// // An observation can be constructed from a value
/// let obs: Observation<i32> = Observation::from(42);
/// assert_eq!(obs, Observation::Ready(42));
///
/// // Observations can be converted to Option
/// let ready: Observation<String> = Observation::Ready("hello".to_string());
/// let opt: Option<String> = ready.into();
/// assert_eq!(opt, Some("hello".to_string()));
///
/// let pending: Observation<String> = Observation::Pending;
/// let opt: Option<String> = pending.into();
/// assert_eq!(opt, None);
/// ```
/// Represents the final state of an observed task.
///
/// This enum is returned when awaiting an [`Observer`] as a [`Future`].
/// Unlike [`Observation`], this only includes terminal states - either
/// the task completed successfully or was cancelled.
///
/// # Examples
///
/// ```
/// # use some_executor::observer::FinishedObservation;
/// # async fn example() {
/// # let observer: some_executor::observer::TypedObserver<String, std::convert::Infallible> = todo!();
/// // When awaiting an observer, you get a FinishedObservation
/// match observer.await {
/// FinishedObservation::Ready(value) => {
/// println!("Task completed with: {}", value);
/// }
/// FinishedObservation::Cancelled => {
/// println!("Task was cancelled");
/// }
/// }
/// # }
/// ```
/// Provides observation and control over spawned tasks.
///
/// An `Observer` allows you to:
/// - Check the current state of a task without blocking using [`observe`](Self::observe)
/// - Wait for task completion by awaiting the observer (it implements [`Future`])
/// - Cancel a task by dropping the observer
/// - Detach from a task to let it run independently using [`detach`](Self::detach)
///
/// # Cancellation
///
/// Dropping an observer requests cancellation of the associated task. Cancellation in
/// some_executor is optimistic and operates at three levels:
///
/// 1. **Lightweight cancellation**: some_executor guarantees that polls occurring logically
/// after cancellation will not be run. This is free and universal.
/// 2. **In-flight cancellation**: If the task is currently being polled, cancellation depends
/// on how the task itself reacts to cancellation through the `IS_CANCELLED` task local.
/// Task support for this is sporadic and not guaranteed.
/// 3. **Executor cancellation**: The executor may support cancellation by dropping the future
/// and not running it again. This is not guaranteed and depends on the executor implementation.
///
/// To allow a task to continue running without the observer, use [`detach`](Self::detach).
///
/// # Examples
///
/// ```
/// # use some_executor::observer::{Observer, TypedObserver};
/// # use some_executor::observer::{Observation, FinishedObservation};
/// # async fn example() {
/// # let observer: TypedObserver<String, std::convert::Infallible> = todo!();
/// // Check task state without blocking
/// match observer.observe() {
/// Observation::Pending => println!("Task still running"),
/// Observation::Ready(value) => println!("Task completed: {}", value),
/// Observation::Done => println!("Value already taken"),
/// Observation::Cancelled => println!("Task was cancelled"),
/// }
///
/// // Or wait for completion
/// # let observer: TypedObserver<String, std::convert::Infallible> = todo!();
/// match observer.await {
/// FinishedObservation::Ready(value) => println!("Got: {}", value),
/// FinishedObservation::Cancelled => println!("Cancelled"),
/// }
///
/// // Detach to let task run independently
/// # let observer: TypedObserver<String, std::convert::Infallible> = todo!();
/// observer.detach(); // Task continues running
/// # }
/// ```
/// A concrete implementation of [`Observer`] for tasks that return a specific type.
///
/// `TypedObserver` is the primary way to observe tasks spawned on executors. It provides
/// both synchronous observation through [`observe`](Self::observe) and asynchronous
/// completion through its [`Future`] implementation.
///
/// The `ENotifier` type parameter allows executors to receive notifications about
/// observer lifecycle events (like cancellation requests). Most users can use
/// [`std::convert::Infallible`] for this parameter if executor notifications aren't needed.
///
/// # Examples
///
/// ```
/// # use some_executor::observer::TypedObserver;
/// # use std::convert::Infallible;
/// # async fn example() {
/// # let observer: TypedObserver<i32, Infallible> = todo!();
/// // Spawn a task and get an observer
/// // let observer = executor.spawn(task);
///
/// // Check status without blocking
/// use some_executor::observer::Observation;
/// if let Observation::Ready(value) = observer.observe() {
/// println!("Task completed with: {}", value);
/// }
///
/// // Or wait for completion
/// # let observer: TypedObserver<i32, Infallible> = todo!();
/// let result = observer.await;
/// println!("Final result: {:?}", result);
/// # }
/// ```
///
/// # Cancellation
///
/// Dropping a `TypedObserver` will request cancellation of the associated task:
///
/// ```no_run
/// # // not runnable becuase of todo!()
/// # use some_executor::observer::TypedObserver;
/// # use std::convert::Infallible;
/// # let observer: TypedObserver<(), Infallible> = todo!();
/// // This will cancel the task
/// drop(observer);
///
/// // To avoid cancellation, detach the observer
/// # let observer: TypedObserver<(), Infallible> = todo!();
/// observer.detach(); // Task continues running
/// ```
/**
The sender side of an observer. This side is held by the executor, and is used to send values to the observer.
*/
pub
/// Provides inline notifications when an observed task completes.
///
/// Unlike [`Observer`] which requires polling or awaiting, `ObserverNotified` allows
/// you to receive immediate notification when a task completes. The notifier's
/// [`notify`](Self::notify) method is called inline by the executor when the task
/// finishes.
///
/// # Cancellation Behavior
///
/// When a task is cancelled, the notifier is dropped without calling [`notify`](Self::notify).
/// This allows you to detect cancellation by implementing [`Drop`] for your notifier type.
///
/// # Design Note
///
/// This trait requires [`Unpin`] to allow the notifier to be moved during task execution.
/// This design choice enables notifiers to maintain mutable state without requiring
/// interior mutability patterns.
///
/// # Examples
///
/// ```
/// use some_executor::observer::ObserverNotified;
/// use std::sync::mpsc;
///
/// // A simple notifier that sends results through a channel
/// struct ChannelNotifier<T> {
/// sender: mpsc::Sender<T>,
/// }
///
/// impl<T: Clone + 'static> ObserverNotified<T> for ChannelNotifier<T> {
/// fn notify(&mut self, value: &T) {
/// let _ = self.sender.send(value.clone());
/// }
/// }
///
/// // A notifier that logs completion
/// struct LogNotifier {
/// task_name: String,
/// }
///
/// impl<T: std::fmt::Debug + ?Sized> ObserverNotified<T> for LogNotifier {
/// fn notify(&mut self, value: &T) {
/// println!("Task '{}' completed with: {:?}", self.task_name, value);
/// }
/// }
///
/// impl Drop for LogNotifier {
/// fn drop(&mut self) {
/// println!("Task '{}' was cancelled or notifier dropped", self.task_name);
/// }
/// }
/// ```
/// Allows executors to receive notifications about observer lifecycle events.
///
/// This trait enables executors to be notified when observers request task cancellation.
/// While implementing cancellation support is optional, it can improve efficiency by
/// allowing executors to stop polling cancelled tasks.
///
/// # Using Without Notifications
///
/// If your executor doesn't need notifications, use [`std::convert::Infallible`] as
/// the type parameter and pass `None` where executor notifiers are expected:
///
/// ```
/// use std::convert::Infallible;
/// use some_executor::observer::{Observer, ObserverNotified, TypedObserver};
/// use some_executor::{BoxedSendObserver, BoxedSendObserverFuture, DynExecutor, ObjSafeTask, SomeExecutor};
/// use some_executor::task::Task;
///
///
/// // Define an executor that doesn't use notifications
/// #[derive(Debug)]
/// struct MyExecutor;
///
/// impl SomeExecutor for MyExecutor {
/// type ExecutorNotifier = Infallible;
///
/// fn spawn<F: Future + Send + 'static, Notifier: ObserverNotified<F::Output> + Send>(&mut self, task: Task<F, Notifier>) -> impl Observer<Value=F::Output> + Send where Self: Sized, F::Output: Send + Unpin {
/// todo!() as TypedObserver::<F::Output, Infallible>
/// }
///
/// fn spawn_async<'s, F: Future + Send + 'static, Notifier: ObserverNotified<F::Output> + Send>(&'s mut self, task: Task<F, Notifier>) -> impl Future<Output=impl Observer<Value=F::Output>> + Send + 's where Self: Sized, F::Output: Send + Unpin {
/// async { todo!() as TypedObserver::<F::Output, Infallible>}
/// }
///
/// fn spawn_objsafe(&mut self, task: ObjSafeTask) -> BoxedSendObserver {
/// todo!()
/// }
///
/// fn spawn_objsafe_async<'s>(&'s mut self, task: ObjSafeTask) -> BoxedSendObserverFuture<'s> {
/// Box::new(async { todo!() })
/// }
///
/// fn clone_box(&self) -> Box<DynExecutor> {
/// todo!()
/// }
///
/// fn executor_notifier(&mut self) -> Option<Self::ExecutorNotifier> {
/// None
/// }
///
/// // Implement the required methods...
/// // (implementation details omitted for brevity)
/// }
/// ```
///
/// # Examples
///
/// ```
/// use some_executor::observer::ExecutorNotified;
///
/// // A simple notifier that tracks cancellation requests
/// struct CancellationTracker {
/// task_id: u64,
/// cancelled: bool,
/// }
///
/// impl ExecutorNotified for CancellationTracker {
/// fn request_cancel(&mut self) {
/// self.cancelled = true;
/// println!("Task {} cancellation requested", self.task_id);
/// // Executor can now stop polling this task
/// }
/// }
/// ```
//support unboxing
//I guess a few ways?
pub
/**
Allow a `Box<dyn ExecutorNotified>` to be used as an ExecutorNotified directly.
The implementation proceeds by dyanmic dispatch.
*/
/*
I don't really get why we need both of these... but we do!
*/
/*
boilerplates
Observer - avoid copy/clone, Eq, Hash, default (channel), from/into, asref/asmut, deref, etc.
Observation - we want clone, Eq, Hash.
default is not obvious to me – could be pending but idk
we could support from based on the value
*/