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
use {
anchor_lang::{prelude::*, AnchorDeserialize},
std::{collections::VecDeque, convert::TryFrom},
};
pub const SEED_POOL: &[u8] = b"pool";
const DEFAULT_POOL_SIZE: usize = 1;
#[account]
#[derive(Debug)]
pub struct Pool {
pub id: u64,
pub size: usize,
pub workers: VecDeque<Pubkey>,
}
impl Pool {
pub fn pubkey(id: u64) -> Pubkey {
Pubkey::find_program_address(&[SEED_POOL, id.to_be_bytes().as_ref()], &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())
}
}
#[derive(AnchorSerialize, AnchorDeserialize)]
pub struct PoolSettings {
pub size: usize,
}
pub trait PoolAccount {
fn pubkey(&self) -> Pubkey;
fn init(&mut self, id: u64) -> Result<()>;
fn rotate(&mut self, worker: Pubkey) -> Result<()>;
fn update(&mut self, settings: &PoolSettings) -> Result<()>;
}
impl PoolAccount for Account<'_, Pool> {
fn pubkey(&self) -> Pubkey {
Pool::pubkey(self.id)
}
fn init(&mut self, id: u64) -> Result<()> {
self.id = id;
self.size = DEFAULT_POOL_SIZE;
self.workers = VecDeque::new();
Ok(())
}
fn rotate(&mut self, worker: Pubkey) -> Result<()> {
self.workers.push_back(worker);
while self.workers.len() > self.size {
self.workers.pop_front();
}
Ok(())
}
fn update(&mut self, settings: &PoolSettings) -> Result<()> {
self.size = settings.size;
while self.workers.len() > self.size {
self.workers.pop_front();
}
Ok(())
}
}