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
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
use std::{
    collections::HashMap,
    io::{self, Write},
    path::Path,
};
use versatile_data::{Activity, FieldData, IdxSized};

use crate::{Collection, CollectionRow, Condition};

use super::Database;

mod operation;
pub use operation::{Depends, Pend, Record, SessionOperation};

mod sequence_number;
use sequence_number::SequenceNumber;

use serde::Serialize;

mod relation;
pub use relation::SessionDepend;
use relation::SessionRelation;

pub mod search;
use search::SessionSearch;

#[derive(Serialize)]
pub struct SessionInfo {
    pub(super) name: String,
    pub(super) access_at: u64,
    pub(super) expire: i64,
}

#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Serialize)]
pub struct SessionCollectionRow {
    pub(crate) collection_id: i32,
    pub(crate) row: i64, //-の場合はセッションの行が入る
}
impl SessionCollectionRow {
    pub fn new(collection_id: i32, row: i64) -> Self {
        Self { collection_id, row }
    }
    pub fn collection_id(&self) -> i32 {
        self.collection_id
    }
    pub fn row(&self) -> i64 {
        self.row
    }
}
impl From<CollectionRow> for SessionCollectionRow {
    fn from(item: CollectionRow) -> Self {
        SessionCollectionRow {
            collection_id: item.collection_id(),
            row: item.row() as i64,
        }
    }
}
pub struct TemporaryDataEntity {
    pub(super) activity: Activity,
    pub(super) term_begin: u64,
    pub(super) term_end: u64,
    pub(super) fields: HashMap<String, Vec<u8>>,
}
impl TemporaryDataEntity {
    pub fn activity(&self) -> Activity {
        self.activity
    }
    pub fn term_begin(&self) -> u64 {
        self.term_begin
    }
    pub fn term_end(&self) -> u64 {
        self.term_end
    }
    pub fn fields(&self) -> &HashMap<String, Vec<u8>> {
        &self.fields
    }
}
pub type TemporaryData = HashMap<i32, HashMap<i64, TemporaryDataEntity>>;

pub struct SessionData {
    pub(super) sequence_number: SequenceNumber,
    pub(super) sequence: IdxSized<usize>,
    pub(super) collection_id: IdxSized<i32>,
    pub(super) row: IdxSized<i64>,
    pub(super) operation: IdxSized<SessionOperation>,
    pub(super) activity: IdxSized<u8>,
    pub(super) term_begin: IdxSized<u64>,
    pub(super) term_end: IdxSized<u64>,
    pub(super) fields: HashMap<String, FieldData>,
    pub(super) relation: SessionRelation,
}
pub struct Session {
    name: String,
    pub(super) session_data: Option<SessionData>,
    pub(super) temporary_data: TemporaryData,
}
impl Session {
    pub fn new(
        main_database: &Database,
        name: impl Into<String>,
        expire_interval_sec: Option<i64>,
    ) -> io::Result<Self> {
        let mut name: String = name.into();
        assert!(name != "");
        if name == "" {
            name = "untitiled".to_owned();
        }
        let session_dir = main_database.session_dir(&name);
        if !session_dir.exists() {
            std::fs::create_dir_all(&session_dir)?;
        }
        let session_data = Self::new_data(&session_dir, expire_interval_sec)?;
        let temporary_data = Self::init_temporary_data(&session_data)?;
        Ok(Self {
            name,
            session_data: Some(session_data),
            temporary_data,
        })
    }
    pub fn name(&mut self) -> &str {
        &self.name
    }
    fn init_temporary_data(session_data: &SessionData) -> io::Result<TemporaryData> {
        let mut temporary_data = HashMap::new();
        for session_row in 1..session_data.sequence.max_rows()? {
            let collection_id = session_data.collection_id.value(session_row).unwrap();
            if collection_id > 0 {
                let col = temporary_data
                    .entry(collection_id)
                    .or_insert(HashMap::new());
                let row = session_data.row.value(session_row).unwrap();

                let temporary_row: i64 = if row == 0 {
                    -(session_row as i64)
                } else {
                    row as i64
                };
                let mut fields = HashMap::new();
                for (key, val) in &session_data.fields {
                    if let Some(v) = val.get(session_row) {
                        fields.insert(key.to_string(), v.to_vec());
                    }
                }
                col.insert(
                    temporary_row,
                    TemporaryDataEntity {
                        activity: if session_data.activity.value(session_row).unwrap() == 1 {
                            Activity::Active
                        } else {
                            Activity::Inactive
                        },
                        term_begin: session_data.term_begin.value(session_row).unwrap(),
                        term_end: session_data.term_end.value(session_row).unwrap(),
                        fields,
                    },
                );
            }
        }
        Ok(temporary_data)
    }
    pub fn new_data(
        session_dir: &Path,
        expire_interval_sec: Option<i64>,
    ) -> io::Result<SessionData> {
        let mut access = session_dir.to_path_buf();
        access.push("expire");
        let mut file = std::fs::OpenOptions::new()
            .create(true)
            .write(true)
            .open(access)?;
        let expire = if let Some(expire) = expire_interval_sec {
            expire
        } else {
            -1
        };
        file.write(&expire.to_be_bytes())?;

        let mut fields = HashMap::new();
        let mut fields_dir = session_dir.to_path_buf();
        fields_dir.push("fields");
        if !fields_dir.exists() {
            std::fs::create_dir_all(&fields_dir.to_owned())?;
        }
        for p in fields_dir.read_dir()? {
            let p = p?;
            let path = p.path();
            if path.is_dir() {
                if let Some(fname) = p.file_name().to_str() {
                    let field = FieldData::new(path)?;
                    fields.insert(fname.to_owned(), field);
                }
            }
        }

        Ok(SessionData {
            sequence_number: SequenceNumber::new({
                let mut path = session_dir.to_path_buf();
                path.push("sequece_number.i");
                path
            })?,
            sequence: IdxSized::new({
                let mut path = session_dir.to_path_buf();
                path.push("sequence.i");
                path
            })?,
            collection_id: IdxSized::new({
                let mut path = session_dir.to_path_buf();
                path.push("collection_id.i");
                path
            })?,
            row: IdxSized::new({
                let mut path = session_dir.to_path_buf();
                path.push("row.i");
                path
            })?,
            operation: IdxSized::new({
                let mut path = session_dir.to_path_buf();
                path.push("operation.i");
                path
            })?,
            activity: IdxSized::new({
                let mut path = session_dir.to_path_buf();
                path.push("activity.i");
                path
            })?,
            term_begin: IdxSized::new({
                let mut path = session_dir.to_path_buf();
                path.push("term_begin.i");
                path
            })?,
            term_end: IdxSized::new({
                let mut path = session_dir.to_path_buf();
                path.push("term_end.i");
                path
            })?,
            fields,
            relation: SessionRelation::new(session_dir)?,
        })
    }

    pub fn begin_search(&self, collection_id: i32) -> SessionSearch {
        SessionSearch::new(self, collection_id)
    }
    pub fn search(&self, collection_id: i32, condtions: &Vec<Condition>) -> SessionSearch {
        let mut search = SessionSearch::new(self, collection_id);
        for c in condtions {
            search = search.search(c.clone());
        }
        search
    }

    pub fn field_bytes<'a>(
        &'a self,
        database: &'a Database,
        collection_id: i32,
        row: i64,
        key: &str,
    ) -> &[u8] {
        if let Some(tmp_col) = self.temporary_data.get(&collection_id) {
            if let Some(tmp_row) = tmp_col.get(&row) {
                if let Some(val) = tmp_row.fields.get(key) {
                    return val;
                }
            }
        }
        if row > 0 {
            if let Some(col) = database.collection(collection_id) {
                return col.field_bytes(row as u32, key);
            }
        }
        b""
    }

    pub fn collection_field_bytes<'a>(
        &'a self,
        collection: &'a Collection,
        row: i64,
        key: &str,
    ) -> &[u8] {
        if let Some(tmp_col) = self.temporary_data.get(&collection.id()) {
            if let Some(tmp_row) = tmp_col.get(&row) {
                if let Some(val) = tmp_row.fields.get(key) {
                    return val;
                }
            }
        }
        if row > 0 {
            return collection.field_bytes(row as u32, key);
        }
        b""
    }
    pub fn temporary_collection(
        &self,
        collection_id: i32,
    ) -> Option<&HashMap<i64, TemporaryDataEntity>> {
        self.temporary_data.get(&collection_id)
    }

    pub fn depends(&self, key: Option<&str>, pend_row: u32) -> Option<Vec<SessionDepend>> {
        let mut r = vec![];
        if let Some(ref session_data) = self.session_data {
            if let Some(key_name) = key {
                if let Some(key_id) = session_data
                    .relation
                    .key_names
                    .find_row(key_name.as_bytes())
                {
                    for relation_row in session_data
                        .relation
                        .rows
                        .session_row
                        .select_by_value(&pend_row)
                        .iter()
                    {
                        if let (Some(key), Some(depend)) = (
                            session_data.relation.rows.key.value(*relation_row),
                            session_data.relation.rows.depend.value(*relation_row),
                        ) {
                            if key == key_id {
                                r.push(SessionDepend::new(key_name, depend));
                            }
                        }
                    }
                    return Some(r);
                }
            } else {
                for relation_row in session_data
                    .relation
                    .rows
                    .session_row
                    .select_by_value(&pend_row)
                    .iter()
                {
                    if let (Some(key), Some(depend)) = (
                        session_data.relation.rows.key.value(*relation_row),
                        session_data.relation.rows.depend.value(*relation_row),
                    ) {
                        r.push(SessionDepend::new(
                            unsafe { session_data.relation.key_names.str(key) }.unwrap(),
                            depend,
                        ));
                    }
                }
                return Some(r);
            }
        }
        None
    }
}