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
use {
    super::InstructionData,
    crate::{errors::ClockworkError, response::TaskResponse},
    anchor_lang::{
        prelude::*,
        solana_program::{
            instruction::Instruction,
            program::{get_return_data, invoke_signed},
        },
        AnchorDeserialize,
    },
    chrono::{DateTime, NaiveDateTime, Utc},
    clockwork_cron::Schedule,
    std::{convert::TryFrom, str::FromStr},
};

pub const SEED_QUEUE: &[u8] = b"queue";

/**
 * Queue
 */

#[account]
#[derive(Debug)]
pub struct Queue {
    pub authority: Pubkey,
    pub balance: u64,
    pub name: String,
    pub process_at: Option<i64>,
    pub schedule: String,
    pub status: QueueStatus,
    pub task_count: u64,
}

impl Queue {
    pub fn pubkey(authority: Pubkey, name: String) -> Pubkey {
        Pubkey::find_program_address(
            &[SEED_QUEUE, authority.as_ref(), name.as_bytes()],
            &crate::ID,
        )
        .0
    }
}

impl TryFrom<Vec<u8>> for Queue {
    type Error = Error;
    fn try_from(data: Vec<u8>) -> std::result::Result<Self, Self::Error> {
        Queue::try_deserialize(&mut data.as_slice())
    }
}

/**
 * QueueAccount
 */

pub trait QueueAccount {
    fn process(&mut self) -> Result<()>;

    fn new(&mut self, authority: Pubkey, name: String, schedule: String) -> Result<()>;

    fn next_process_at(&self, ts: i64) -> Option<i64>;

    fn roll_forward(&mut self) -> Result<()>;

    fn sign(
        &self,
        account_infos: &[AccountInfo],
        bump: u8,
        ix: &InstructionData,
    ) -> Result<Option<TaskResponse>>;
}

impl QueueAccount for Account<'_, Queue> {
    fn process(&mut self) -> Result<()> {
        // Validate the queue is pending
        require!(
            self.status == QueueStatus::Pending,
            ClockworkError::InvalidQueueStatus,
        );

        if self.task_count > 0 {
            // If there are actions, change the queue status to 'executing'
            self.status = QueueStatus::Processing { task_id: 0 };
        } else {
            // Otherwise, just roll forward the process_at timestamp
            self.roll_forward()?;
        }

        Ok(())
    }

    fn new(&mut self, authority: Pubkey, name: String, schedule: String) -> Result<()> {
        // Initialize queue account
        self.authority = authority.key();
        self.balance = 0;
        self.name = name;
        self.schedule = schedule;
        self.status = QueueStatus::Pending;
        self.task_count = 0;

        // Set process_at (schedule must be set first)
        let ts = Clock::get().unwrap().unix_timestamp;
        self.process_at = self.next_process_at(ts);

        Ok(())
    }

    fn next_process_at(&self, ts: i64) -> Option<i64> {
        match Schedule::from_str(&self.schedule)
            .unwrap()
            .after(&DateTime::<Utc>::from_utc(
                NaiveDateTime::from_timestamp(ts, 0),
                Utc,
            ))
            .take(1)
            .next()
        {
            Some(datetime) => Some(datetime.timestamp()),
            None => None,
        }
    }

    fn roll_forward(&mut self) -> Result<()> {
        self.status = QueueStatus::Pending;
        match self.process_at {
            Some(process_at) => self.process_at = self.next_process_at(process_at),
            None => (),
        };
        Ok(())
    }

    fn sign(
        &self,
        account_infos: &[AccountInfo],
        bump: u8,
        ix: &InstructionData,
    ) -> Result<Option<TaskResponse>> {
        invoke_signed(
            &Instruction::from(ix),
            account_infos,
            &[&[
                SEED_QUEUE,
                self.authority.as_ref(),
                self.name.as_bytes(),
                &[bump],
            ]],
        )
        .map_err(|_err| ClockworkError::InnerIxFailed)?;

        match get_return_data() {
            None => Ok(None),
            Some((program_id, return_data)) => {
                if program_id != ix.program_id {
                    Err(ClockworkError::InvalidReturnData.into())
                } else {
                    Ok(Some(
                        TaskResponse::try_from_slice(return_data.as_slice())
                            .map_err(|_err| ClockworkError::InvalidTaskResponse)?,
                    ))
                }
            }
        }
    }
}

/**
 * QueueStatus
 */

#[derive(AnchorDeserialize, AnchorSerialize, Clone, Copy, Debug, PartialEq, Eq)]
pub enum QueueStatus {
    Paused,
    Pending,
    Processing { task_id: u64 },
}