pub enum EventType {
    Exec,
    ExecDone,
    Read,
    Write,
    Miss,
}

Variants§

§

Exec

§

ExecDone

§

Read

§

Write

§

Miss

Implementations§

Examples found in repository?
src/lib.rs (line 16)
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
const EXEC_CODE: i8 = EventType::Exec.get_code();
const EXEC_DONE_CODE: i8 = EventType::ExecDone.get_code();

#[derive(Debug, Clone)]
pub struct Historian {
    pool: Arc<RwLock<SqlitePool>>,
    dir_path: PathBuf,
}

async fn raw_record_event(pool: &Pool<Sqlite>, event: DBEvent<'_>) -> Result<i64, DBError> {
    let res = sqlx::query!(
        "
        INSERT INTO events
        (script_id, type, cmd, args, content, time, main_event_id, dir, envs, humble)
        VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        RETURNING id
        ",
        event.script_id,
        event.ty,
        event.cmd,
        event.args,
        event.content,
        event.time,
        event.main_event_id,
        event.dir,
        event.envs,
        event.humble
    )
    .fetch_one(pool)
    .await?;
    Ok(res.id)
}

#[derive(Clone, Copy)]
struct DBEvent<'a> {
    script_id: i64,
    ty: i8,
    cmd: &'a str,
    time: NaiveDateTime,
    args: Option<&'a str>,
    dir: Option<&'a str>,
    envs: Option<&'a str>,
    content: Option<&'a str>,
    humble: bool,
    main_event_id: i64,
}
impl<'a> DBEvent<'a> {
    fn new(script_id: i64, time: NaiveDateTime, ty: i8, cmd: &'a str, humble: bool) -> Self {
        DBEvent {
            script_id,
            time,
            ty,
            cmd,
            humble,
            main_event_id: ZERO,
            envs: None,
            content: None,
            args: None,
            dir: None,
        }
    }
    fn args(mut self, value: &'a str) -> Self {
        self.args = Some(value);
        self
    }
    fn dir(mut self, value: &'a str) -> Self {
        self.dir = Some(value);
        self
    }
    fn content(mut self, value: &'a str) -> Self {
        self.content = Some(value);
        self
    }
    fn envs(mut self, value: &'a str) -> Self {
        self.envs = Some(value);
        self
    }
    fn humble(mut self) -> Self {
        self.humble = true;
        self
    }
    fn main_event_id(mut self, value: i64) -> Self {
        self.main_event_id = value;
        self
    }
}

macro_rules! last_arg {
    ($select:literal, $offset:expr, $limit:expr, $group_by:literal, $where:literal $(+ $more_where:literal)* , $($var:expr),*) => {{
        sqlx::query!(
            "
            WITH args AS (
                SELECT " + $select + ", max(time) as time FROM events
                WHERE type = ? AND NOT ignored "
                +
                $where
                $(+ $more_where)*
                +
                " GROUP BY args, script_id " + $group_by + " ORDER BY time DESC LIMIT ? OFFSET ?
            ) SELECT "
                + $select
                + " FROM args
            ",
            EXEC_CODE,
            $($var, )*
            $limit,
            $offset,
        )
    }};
}
macro_rules! do_last_arg {
    ($select:literal, $maybe_envs:literal, $ids:expr, $limit:expr, $offset:expr, $no_humble:expr, $dir:expr, $historian:expr) => {{
        let ids = join_id_str($ids);
        log::info!("查詢歷史 {}", ids);
        let limit = $limit as i64;
        let offset = $offset as i64;
        let no_dir = $dir.is_none();
        let dir = $dir.map(|p| p.to_string_lossy());
        let dir = dir.as_deref().unwrap_or(EMPTY_STR);
        // FIXME: 一旦可以綁定陣列就換掉這個醜死人的 instr
        last_arg!(
            $select,
            offset,
            limit,
            $maybe_envs,
            "
            AND instr(?, '[' || script_id || ']') > 0 AND (? OR dir = ?)
            AND (NOT ? OR NOT humble)
            ",
            ids,
            no_dir,
            dir,
            $no_humble
        )
        .fetch_all(&*$historian.pool.read().unwrap())
        .await
    }};
}

macro_rules! ignore_or_humble_arg {
    ($ignore_or_humble:literal, $pool:expr, $cond:literal $(+ $more_cond:literal)*, $($var:expr),+) => {
        sqlx::query!(
            "
            UPDATE events SET " + $ignore_or_humble + " = true
            WHERE type = ? AND main_event_id IN (
                SELECT id FROM events WHERE type = ? AND NOT ignored AND "
                + $cond $(+ $more_cond)*
                + "
            )
            ",
            EXEC_DONE_CODE,
            EXEC_CODE,
            $($var),*
        )
        .execute(&*$pool)
        .await?;

        sqlx::query!(
            "
            UPDATE events SET " + $ignore_or_humble + " = true
            WHERE type = ? AND NOT ignored AND
            "
                + $cond $(+ $more_cond)*,
            EXEC_CODE,
            $($var),*
        )
        .execute(&*$pool)
        .await?;
    };
}

#[derive(Debug)]
pub struct LastTimeRecord {
    pub script_id: i64,
    pub exec_time: Option<NaiveDateTime>,
    pub exec_done_time: Option<NaiveDateTime>,
    pub humble_time: Option<NaiveDateTime>,
}

impl Historian {
    pub async fn close(self) {
        log::info!("close the historian database");
        if let Ok(pool) = self.pool.read() {
            pool.close().await;
        }
    }
    async fn raw_record(&self, event: DBEvent<'_>) -> Result<i64, DBError> {
        let pool = &mut *self.pool.write().unwrap();
        let res = raw_record_event(pool, event).await;
        if res.is_err() {
            pool.close().await;
            log::warn!("資料庫錯誤 {:?},再試最後一次!", res);
            *pool = db::get_pool(&self.dir_path).await?;
            return raw_record_event(pool, event).await;
        }

        res
    }
    pub async fn new(dir_path: PathBuf) -> Result<Self, DBError> {
        db::get_pool(&dir_path).await.map(|pool| Historian {
            pool: Arc::new(RwLock::new(pool)),
            dir_path,
        })
    }
    pub async fn do_migrate(dir_path: &Path) -> Result<(), MigrateError> {
        migration::do_migrate(db::get_file(dir_path)).await?;
        Ok(())
    }

    pub async fn remove(&self, script_id: i64) -> Result<(), DBError> {
        let pool = self.pool.read().unwrap();
        sqlx::query!("DELETE FROM events WHERE script_id = ?", script_id,)
            .execute(&*pool)
            .await?;
        Ok(())
    }

    pub async fn record(&self, event: &Event<'_>) -> Result<i64, DBError> {
        log::debug!("記錄事件 {:?}", event);
        let ty = event.data.get_type().get_code();
        let cmd = std::env::args().collect::<Vec<_>>().join(" ");
        let mut db_event = DBEvent::new(event.script_id, event.time, ty, &cmd, event.humble);
        let id = match &event.data {
            EventData::Write | EventData::Read | EventData::Miss => {
                self.raw_record(db_event).await?
            }
            EventData::Exec {
                content,
                args,
                envs,
                dir,
            } => {
                let mut content = Some(*content);
                let last_event = sqlx::query!(
                    "
                    SELECT content FROM events
                    WHERE type = ? AND script_id = ? AND NOT content IS NULL
                    ORDER BY time DESC LIMIT 1
                    ",
                    ty,
                    event.script_id
                )
                .fetch_optional(&*self.pool.read().unwrap())
                .await?;
                if let Some(last_event) = last_event {
                    if last_event.content.as_deref() == content {
                        log::debug!("上次執行內容相同,不重複記錄");
                        content = None;
                    }
                }
                db_event.content = content;
                let dir = dir.map(|p| p.to_string_lossy()).unwrap_or_default();
                self.raw_record(db_event.envs(envs).dir(dir.as_ref()).args(args))
                    .await?
            }
            EventData::ExecDone {
                code,
                main_event_id,
            } => {
                let main_event = sqlx::query!(
                    "SELECT ignored, humble FROM events WHERE type = ? AND id = ?",
                    EXEC_CODE,
                    main_event_id
                )
                .fetch_optional(&*self.pool.read().unwrap())
                .await?;
                let main_event = match main_event {
                    Some(e) => e,
                    None => {
                        log::warn!("找不到主要事件,可能被 tidy 掉了");
                        return Ok(ZERO);
                    }
                };
                if main_event.ignored {
                    return Ok(ZERO);
                } else if main_event.humble {
                    log::debug!("謙卑地執行完畢了");
                    db_event = db_event.humble();
                }

                let code = code.to_string();
                let id = self
                    .raw_record(db_event.content(&code).main_event_id(*main_event_id))
                    .await?;

                if db_event.humble {
                    // XXX: 用很怪異的方式告訴外面的人不要記錄最新時間,醜死
                    ZERO
                } else {
                    id
                }
            }
        };
        Ok(id)
    }

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more
Compare self to key and return true if they are equal.

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Should always be Self
The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.