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
use std::{
    sync::{Arc, RwLock},
    collections::LinkedList
};
use futures::future::{AbortRegistration};
use cyfs_base::*;
use crate::{
    types::*, 
    ndn::{*, channel::{DownloadSession, DownloadSessionState}}, 
    stack::{Stack}, 
};

enum WaitSession {
    None(StateWaiter), 
    Some(DownloadSession)
}

struct ContextImpl {
    referer: String, 
    create_at: Timestamp, 
    source: DownloadSource<DeviceDesc>, 
    session: RwLock<WaitSession>
}

#[derive(Clone)]
pub struct SingleSourceContext(Arc<ContextImpl>);

impl SingleSourceContext {
    pub fn ptr_eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.0, &other.0)
    }

    pub fn source(&self) -> &DownloadSource<DeviceDesc> {
        &self.0.source
    }

    pub fn from_desc(referer: String, remote: DeviceDesc) -> Self {
        Self(Arc::new(ContextImpl {
            create_at: bucky_time_now(), 
            referer, 
            source: DownloadSource {
                target: remote, 
                codec_desc: ChunkCodecDesc::Stream(None, None, None), 
            }, 
            session: RwLock::new(WaitSession::None(StateWaiter::new()))
        }))
    }

    pub async fn from_id(stack: &Stack, referer: String, remote: DeviceId) -> BuckyResult<Self> {
        let device = stack.device_cache().get(&remote).await
                .ok_or_else(|| BuckyError::new(BuckyErrorCode::NotFound, "device desc not found"))?;
        Ok(Self(Arc::new(ContextImpl {
            create_at: bucky_time_now(), 
            referer, 
            source: DownloadSource {
                target: device.desc().clone(), 
                codec_desc: ChunkCodecDesc::Stream(None, None, None), 
            },
            session: RwLock::new(WaitSession::None(StateWaiter::new()))
        })))
    }

    pub async fn wait_session(&self, abort: impl futures::Future<Output = BuckyError>) -> BuckyResult<DownloadSession> {
        enum NextStep {
            Wait(AbortRegistration), 
            Some(DownloadSession)
        }

        let next = {
            let mut session = self.0.session.write().unwrap();
            match &mut *session {
                WaitSession::None(waiter) => NextStep::Wait(waiter.new_waiter()), 
                WaitSession::Some(session) => NextStep::Some(session.clone())
            }
        };

        match next {
            NextStep::Some(session) => Ok(session),
            NextStep::Wait(waiter) => StateWaiter::abort_wait(abort, waiter, || {
                let session = self.0.session.read().unwrap();
                match & *session {
                    WaitSession::Some(session) => session.clone(),
                    _ => unreachable!()
                }
            }).await
        }
      
    }
}

#[async_trait::async_trait]
impl DownloadContext for SingleSourceContext {
    fn clone_as_context(&self) -> Box<dyn DownloadContext> {
        Box::new(self.clone())
    }

    fn is_mergable(&self) -> bool {
        false
    }

    fn referer(&self) -> &str {
        self.0.referer.as_str()
    }

    async fn update_at(&self) -> Timestamp {
        self.0.create_at
    }

    async fn sources_of(&self, filter: &DownloadSourceFilter, _limit: usize) -> (LinkedList<DownloadSource<DeviceDesc>>, Timestamp) {
        let mut result = LinkedList::new();
        if filter.check(self.source()) {
            result.push_back(DownloadSource {
                target: self.source().target.clone(), 
                codec_desc: self.source().codec_desc.clone(), 
            });
        } 
        (result, self.0.create_at)
    }

    fn on_new_session(&self, _task: &dyn LeafDownloadTask, new_session: &DownloadSession, _update_at: Timestamp) {
        let waiter = {
            let mut session = self.0.session.write().unwrap();
            match &mut *session {
                WaitSession::None(waiter) => {
                    let waiter = waiter.transfer();
                    *session = WaitSession::Some(new_session.clone());
                    waiter
                } 
                WaitSession::Some(_) => unreachable!()
            }
        };
       
        waiter.wake();
    }

    fn on_drain(
        &self, 
        task: &dyn LeafDownloadTask, 
        _update_at: Timestamp) {
        let session = {
            let session = self.0.session.read().unwrap();
            match &*session {
                WaitSession::Some(session) => Some(session.clone()), 
                _ => None
            }
        };
        
        if let Some(session) = session {
            if let DownloadSessionState::Canceled(err) = session.state() {
                let _ = task.cancel_by_error(err);
            }
        }
    }
}