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
use log::{log_enabled, error, info, Level};
use mongodb::bson::{doc, Document};
use pgnparse::parser::*;
use mongodb::{Client};
use mongodb::options::{UpdateOptions};
use futures::stream::StreamExt;

use crate::models::pgnwithdigest::*;
use crate::models::bookmove::*;
use crate::utils::env::*;
use crate::mongo::operations::*;
use crate::models::conv::{get_variant};

/// mongo book
pub struct MongoBook {
	/// mongodb uri
	mongodb_uri: String,
	/// client
	client: Option<Client>,
	/// max book depth in plies
	book_depth: usize,
	/// book db
	book_db: String
}

impl MongoBook {
	/// create new mongo book
	pub fn new() -> MongoBook {
		MongoBook {
			mongodb_uri: env_string_or("MONGODB_URI", "mongodb://localhost:27017"),
			client: None,
			book_depth: env_usize_or("BOOK_DEPTH", 40),
			book_db: env_string_or("BOOK_DB", "rustbook"),
		}
	}

	/// set book depth and return self
	pub fn book_depth(mut self, book_depth: usize) -> MongoBook {
		self.book_depth = book_depth;

		self
	}

	/// connect
	pub async fn connect(&mut self) {
		match connect(&self.mongodb_uri).await {
			Ok(client) => self.client = Some(client),
			_ => self.client = None
		}		
	}

	/// drop coll
	pub async fn drop_coll<T>(&mut self, coll: T)
	where T: core::fmt::Display {
		let coll = format!("{}", coll);

		if let Some(client) = &self.client {
			if log_enabled!(Level::Info) {
				info!("dropping {}", coll);
			}

			match client.database(&self.book_db).collection(&coll).drop(None).await {
				Ok(_) => {
					if log_enabled!(Level::Info) {
						info!("{} dropped ok", coll);
					}
				},
				Err(err) => {
					if log_enabled!(Level::Error) {
						error!("dropping {} failed {:?}", coll, err);
					}
				}
			}
		}
	}

	/// upsert one
	pub async fn upsert_one<T>(&mut self, coll: T, filter: Document, doc: Document)
	where T: core::fmt::Display {
		let coll = format!("{}", coll);

		if let Some(client) = &self.client {
			let result = client.database(&self.book_db).collection(&coll)
				.update_one(filter, doc!{"$set": doc}, UpdateOptions::builder().upsert(true).build()).await;

			match result {
				Ok(_) => {
					if log_enabled!(Level::Info) {
						info!("upserted in {} ok", coll);
					}
				},
				Err(err) => {
					if log_enabled!(Level::Error) {
						error!("upsert in {} failed {:?}", coll, err);
					}
				}
			}
		}
	}

	/// get moves for variant and epd
	pub async fn get_moves<T, V>(&mut self, variant: V, epd: T) -> std::collections::HashMap::<String, i32>
	where T: core::fmt::Display, V: core::fmt::Display {
		let variant = format!("{}", variant);
		let epd = format!("{}", epd);

		let mut moves = std::collections::HashMap::<String, i32>::new();

		if let Some(client) = &self.client {
			let result = client.database(&self.book_db).collection("moves")
				.find(doc!{
					"variant": variant.to_owned(),
					"epd": epd.to_owned(),					
				}, None).await;

			match result {
				Ok(cursor) => {
					let mut cursor = cursor;

					if log_enabled!(Level::Info) {
						info!("got cursor for epd {}", &epd);
					}

					while let Some(doc) = cursor.next().await {
						match doc {
							Ok(doc) => {
								let result_wrt = doc.get_i32("result_wrt").unwrap();
								let uci = doc.get("uci").unwrap().to_string();

								*moves.entry(uci).or_insert(0) += result_wrt;
							},
							Err(err) => {
								if log_enabled!(Level::Error) {
									info!("cursor next failed {:?}", err);
								}
							}
						}
					}
				},
				Err(err) => {
					if log_enabled!(Level::Error) {
						error!("getting cursor for {} failed {:?}", &epd, err);
					}
				}
			}
		}

		moves
	}

	/// add pgn to book
	pub async fn add_pgn_to_book<T>(&mut self, all_pgn: T)
	where T: core::fmt::Display {
		let all_pgn = format!("{}", all_pgn);

		if let Some(client) = &self.client {
			if log_enabled!(Level::Info) {
				info!("adding pgn of size {} to book", all_pgn.len());
			}

			let db = client.database(&self.book_db);
			let pgns = db.collection("pgns");

			let mut items:Vec<&str> = all_pgn.split("\r\n\r\n\r\n").collect();	
			let _ = items.pop();

			if log_enabled!(Level::Info) {
				info!("number of games {}", items.len());
			}
			
			for pgn_str in items {
				let old_pgn_str = pgn_str.to_owned();
				
				let mut pgn_with_digest:PgnWithDigest = pgn_str.into();
				
				if log_enabled!(Level::Info) {
					info!("processing pgn with sha {}", pgn_with_digest.sha256_base64);
				}
				
				let result = pgns.find_one(doc!{"_id": pgn_with_digest.sha256_base64.to_owned()}, None).await;

				let mut process_from = 0;

				let mut processed_depth = 0;

				if let Ok(Some(doc)) = result {
					let pgn_with_digest_stored:PgnWithDigest = doc.into();

					processed_depth = pgn_with_digest_stored.processed_depth as usize;

					if log_enabled!(Level::Info) {
						info!("pgn already in db {} processed depth {}",
							pgn_with_digest_stored.sha256_base64, processed_depth)
					}

					process_from = processed_depth;
				}

				let mut moves = parse_pgn_to_rust_struct(old_pgn_str);

				let num = moves.moves.len();
				
				if ( num <= processed_depth ) || ( processed_depth >= self.book_depth ) {
					if log_enabled!(Level::Info) {
						info!("pgn has no moves beyond processed depth, skipping")
					}
				}else{
					let mut process_to = self.book_depth;

					if num < process_to {
						process_to = num;
					}

					if log_enabled!(Level::Info) {
						let result = match moves.get_header("Result").as_str() {
							"1-0" => 2,
							"0-1" => 0,
							_ => 1
						};

						info!("pgn of orig variant {} and variant key {} has unprocessed moves from {} to {}\n{} {} - {} {} {}",
							moves.get_header("Variant"),
							get_variant(moves.get_header("Variant")),
							process_from,
							process_to,
							moves.get_header("White"),
							moves.get_header("WhiteElo"),
							moves.get_header("Black"),
							moves.get_header("BlackElo"),
							moves.get_header("Result"),
						);

						for i in process_from..process_to {
							let m = &moves.moves[i];

							let mut result_wrt = result;

							let parts:Vec<&str> = m.epd_before.split(" ").collect();

							if parts[1] == "b" {
								result_wrt = 2 - result_wrt;
							}

							if log_enabled!(Level::Info) {
								let sha = pgn_with_digest.sha256_base64.to_owned();
								let epd = m.epd_before.to_owned();
								let san = m.san.to_owned();
								let uci = m.uci.to_owned();

								let book_move = BookMove{
									variant: get_variant(moves.get_header("Variant")),
									sha: sha,
									epd: epd,
									san: san,
									uci: uci,
									result_wrt: result_wrt,
								};

								info!("adding move {}", book_move);

								let doc:Document = book_move.into();

								let result = db.collection("moves").insert_one(doc, None).await;
				
								match result {
									Ok(_) => {
										if log_enabled!(Level::Info) {
											info!("move inserted ok")
										}
									},
									Err(err) => {
										if log_enabled!(Level::Error) {
											error!("inserting move failed {:?}", err)
										}
									}
								}
							}
						}

						pgn_with_digest.processed_depth = process_to as i32;

						let sha = pgn_with_digest.sha256_base64.to_owned();

						let doc:Document = pgn_with_digest.into();
							
						if log_enabled!(Level::Info) {								
							info!("moves processed ok, updating {:?}", &doc);
						}
						
						let filter = doc!{"_id": sha};
						self.upsert_one("pgns", filter, doc).await;
					}
				}
			}
		}
	}
}

/// display for MongoBook
impl std::fmt::Display for MongoBook {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!("MongoBook\n-> uri = {}\n-> book depth = {}",
        	self.mongodb_uri, self.book_depth
        ))
    }
}