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
use crate::schema::*;
use rebuilderd_common::errors::*;
use rebuilderd_common::config::*;
use diesel::prelude::*;
use chrono::prelude::*;
use chrono::Duration;
use serde::{Serialize, Deserialize};
use rebuilderd_common::api::QueueItem;
use crate::models::Package;

#[derive(Identifiable, Queryable, AsChangeset, Serialize, PartialEq, Debug)]
#[table_name="queue"]
pub struct Queued {
    pub id: i32,
    pub package_id: i32,
    pub version: String,
    pub priority: i32,
    pub queued_at: NaiveDateTime,
    pub worker_id: Option<i32>,
    pub started_at: Option<NaiveDateTime>,
    pub last_ping: Option<NaiveDateTime>,
}

impl Queued {
    pub fn get_id(my_id: i32, connection: &SqliteConnection) -> Result<Queued> {
        use crate::schema::queue::dsl::*;
        let item = queue
            .filter(id.eq(my_id))
            .first::<Queued>(connection)?;
        Ok(item)
    }

    pub fn get(pkg: i32, my_version: &str, connection: &SqliteConnection) -> Result<Option<Queued>> {
        use crate::schema::queue::dsl::*;
        let job = queue
            .filter(package_id.eq(pkg))
            .filter(version.eq(my_version))
            .first::<Queued>(connection)
            .optional()?;
        Ok(job)
    }

    pub fn pop_next(my_worker_id: i32, connection: &SqliteConnection) -> Result<Option<QueueItem>> {
        use crate::schema::queue::dsl::*;
        let item = queue
            .filter(worker_id.is_null())
            .order_by((priority, queued_at, id))
            .first::<Queued>(connection)
            .optional()?;
        if let Some(mut item) = item {
            let now: DateTime<Utc> = Utc::now();

            item.worker_id = Some(my_worker_id);
            item.started_at = Some(now.naive_utc());
            item.last_ping = Some(now.naive_utc());
            item.update(connection)?;

            Ok(Some(item.into_api_item(connection)?))
        } else {
            Ok(None)
        }
    }

    pub fn ping_job(&mut self, connection: &SqliteConnection) -> Result<()> {
        let now: DateTime<Utc> = Utc::now();
        self.last_ping = Some(now.naive_utc());
        self.update(connection)
    }

    pub fn delete(&self, connection: &SqliteConnection) -> Result<()> {
        use crate::schema::queue::columns::*;
        diesel::delete(queue::table
            .filter(id.eq(self.id))
        ).execute(connection)?;
        Ok(())
    }

    pub fn list(limit: Option<i64>, connection: &SqliteConnection) -> Result<Vec<Queued>> {
        use crate::schema::queue::dsl::*;

        let query = Box::new(queue
            .order_by((priority, queued_at, id)));

        let results = if let Some(limit) = limit {
            query
                .limit(limit)
                .load::<Queued>(connection)?
        } else {
            query
                .load::<Queued>(connection)?
        };

        Ok(results)
    }

    pub fn update(&self, connection: &SqliteConnection) -> Result<()> {
        use crate::schema::queue::columns::*;
        diesel::update(queue::table.filter(id.eq(self.id)))
            .set(self)
            .execute(connection)?;
        Ok(())
    }

    pub fn queue_batch(pkgs: &[(i32, String)], priority: i32, connection: &SqliteConnection) -> Result<()> {
        let pkgs = pkgs.iter()
            .map(|(id, version)| NewQueued::new(*id, version.to_string(), priority))
            .collect::<Vec<_>>();

        diesel::insert_into(queue::table)
            .values(pkgs)
            // TODO: not supported by diesel yet
            // .on_conflict_do_nothing()
            .execute(connection)?;

        Ok(())
    }

    pub fn drop_for_pkgs(pkgs: &[i32], connection: &SqliteConnection) -> Result<()> {
        diesel::delete(queue::table.filter(queue::package_id.eq_any(pkgs)))
            .execute(connection)?;
        Ok(())
    }

    pub fn requeue(&self, connection: &SqliteConnection) -> Result<()> {
        diesel::update(queue::table)
            .filter(queue::id.eq(self.id))
            .set((
                queue::worker_id.eq(Option::<i32>::None),
                queue::started_at.eq(Option::<NaiveDateTime>::None),
                queue::last_ping.eq(Option::<NaiveDateTime>::None),
            ))
            .execute(connection)?;

        Ok(())
    }

    pub fn free_stale_jobs(connection: &SqliteConnection) -> Result<()> {
        let now = Utc::now().naive_utc();
        let deadline = now - Duration::seconds(PING_DEADLINE);

        diesel::update(queue::table.filter(queue::last_ping.lt(deadline)))
            .set((
                queue::worker_id.eq(Option::<i32>::None),
                queue::started_at.eq(Option::<NaiveDateTime>::None),
                queue::last_ping.eq(Option::<NaiveDateTime>::None),
            ))
            .execute(connection)?;

        Ok(())
    }

    pub fn into_api_item(self, connection: &SqliteConnection) -> Result<QueueItem> {
        let pkg = Package::get_id(self.package_id, connection)?;

        Ok(QueueItem {
            id: self.id,
            package: pkg.into_api_item()?,
            version: self.version,
            queued_at: self.queued_at,
            worker_id: self.worker_id,
            started_at: self.started_at,
            last_ping: self.last_ping,
        })
    }
}

#[derive(Insertable, Serialize, Deserialize, Debug)]
#[table_name="queue"]
pub struct NewQueued {
    pub package_id: i32,
    pub version: String,
    pub priority: i32,
    pub queued_at: NaiveDateTime,
}

impl NewQueued {
    pub fn new(package_id: i32, version: String, priority: i32) -> NewQueued {
        let now: DateTime<Utc> = Utc::now();
        NewQueued {
            package_id,
            version,
            priority,
            queued_at: now.naive_utc(),
        }
    }

    pub fn insert(&self, connection: &SqliteConnection) -> Result<()> {
        // TODO: on conflict do nothing after it landed in diesel sqlite
        if Queued::get(self.package_id, &self.version, connection)?.is_none() {
            diesel::insert_into(queue::table)
                .values(self)
                .execute(connection)?;
        }
        Ok(())
    }
}