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
use {
    super::Config,
    anchor_lang::{prelude::*, AnchorDeserialize},
    std::{collections::VecDeque, convert::TryFrom},
};

pub const SEED_POOL: &[u8] = b"pool";

/**
 * Pool
 */

#[account]
#[derive(Debug)]
pub struct Pool {
    pub workers: VecDeque<Pubkey>,
}

impl Pool {
    pub fn pubkey() -> Pubkey {
        Pubkey::find_program_address(&[SEED_POOL], &crate::ID).0
    }
}

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

/**
 * PoolAccount
 */

pub trait PoolAccount {
    fn new(&mut self) -> Result<()>;

    fn rotate(&mut self, config: &Account<Config>, worker: Pubkey) -> Result<()>;
}

impl PoolAccount for Account<'_, Pool> {
    fn new(&mut self) -> Result<()> {
        self.workers = VecDeque::new();
        Ok(())
    }

    fn rotate(&mut self, config: &Account<Config>, worker: Pubkey) -> Result<()> {
        // Pop a worker out of the pool
        self.workers.pop_front();

        // Push provided worker into the pool
        self.workers.push_back(worker);

        // Drain pool to the configured size limit
        while self.workers.len() > config.pool_size {
            self.workers.pop_front();
        }

        Ok(())
    }
}