Compare commits
	
		
			29 Commits
		
	
	
		
			7df19a480f
			...
			status_cod
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
| 
						 | 
					f7a3ca8fd7 | ||
| 6790061e22 | |||
| 50606bb69e | |||
| 5850f19cab | |||
| 2c8546e30a | |||
| 4e619d0ebc | |||
| 647c4cd324 | |||
| 7fab961d76 | |||
| d3fff194f4 | |||
| 3497312fd4 | |||
| 0fd76b1734 | |||
| 9bfa8f9108 | |||
| bdb1094a30 | |||
| 9aa2d9ce22 | |||
| 4b557a923c | |||
| c08a20ac00 | |||
| 94912e9125 | |||
| a9465dda6e | |||
| add6f00ed6 | |||
| 4a433a1a77 | |||
| 03cbcd9ae0 | |||
| 6fc71c7a78 | |||
| 96a3ca092a | |||
| b750d88d48 | |||
| 808790a7c3 | |||
| 2de01b2a0e | |||
| be0fd5505b | |||
| a23429104c | |||
| 66581cc453 | 
							
								
								
									
										3
									
								
								.gitignore
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										3
									
								
								.gitignore
									
									
									
									
										vendored
									
									
								
							@@ -4,4 +4,5 @@
 | 
				
			|||||||
perf.data
 | 
					perf.data
 | 
				
			||||||
flamegraph.svg
 | 
					flamegraph.svg
 | 
				
			||||||
perf.data.old
 | 
					perf.data.old
 | 
				
			||||||
/docker/logs/*
 | 
					/docker/logs/*
 | 
				
			||||||
 | 
					/downloaded
 | 
				
			||||||
							
								
								
									
										19
									
								
								.vscode/launch.json
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										19
									
								
								.vscode/launch.json
									
									
									
									
										vendored
									
									
								
							@@ -7,18 +7,15 @@
 | 
				
			|||||||
        {
 | 
					        {
 | 
				
			||||||
            "type": "lldb",
 | 
					            "type": "lldb",
 | 
				
			||||||
            "request": "launch",
 | 
					            "request": "launch",
 | 
				
			||||||
            "name": "Debug executable 'surreal_spider'",
 | 
					            "name": "Debug executable 'internet_mapper'",
 | 
				
			||||||
            "env": {
 | 
					 | 
				
			||||||
                "RUST_LOG": "surreal_spider=trace,reqwest=info",
 | 
					 | 
				
			||||||
            },
 | 
					 | 
				
			||||||
            "cargo": {
 | 
					            "cargo": {
 | 
				
			||||||
                "args": [
 | 
					                "args": [
 | 
				
			||||||
                    "build",
 | 
					                    "build",
 | 
				
			||||||
                    "--bin=surreal_spider",
 | 
					                    "--bin=internet_mapper",
 | 
				
			||||||
                    "--package=surreal_spider"
 | 
					                    "--package=internet_mapper"
 | 
				
			||||||
                ],
 | 
					                ],
 | 
				
			||||||
                "filter": {
 | 
					                "filter": {
 | 
				
			||||||
                    "name": "surreal_spider",
 | 
					                    "name": "internet_mapper",
 | 
				
			||||||
                    "kind": "bin"
 | 
					                    "kind": "bin"
 | 
				
			||||||
                }
 | 
					                }
 | 
				
			||||||
            },
 | 
					            },
 | 
				
			||||||
@@ -28,16 +25,16 @@
 | 
				
			|||||||
        {
 | 
					        {
 | 
				
			||||||
            "type": "lldb",
 | 
					            "type": "lldb",
 | 
				
			||||||
            "request": "launch",
 | 
					            "request": "launch",
 | 
				
			||||||
            "name": "Debug unit tests in executable 'surreal_spider'",
 | 
					            "name": "Debug unit tests in executable 'internet_mapper'",
 | 
				
			||||||
            "cargo": {
 | 
					            "cargo": {
 | 
				
			||||||
                "args": [
 | 
					                "args": [
 | 
				
			||||||
                    "test",
 | 
					                    "test",
 | 
				
			||||||
                    "--no-run",
 | 
					                    "--no-run",
 | 
				
			||||||
                    "--bin=surreal_spider",
 | 
					                    "--bin=internet_mapper",
 | 
				
			||||||
                    "--package=surreal_spider"
 | 
					                    "--package=internet_mapper"
 | 
				
			||||||
                ],
 | 
					                ],
 | 
				
			||||||
                "filter": {
 | 
					                "filter": {
 | 
				
			||||||
                    "name": "surreal_spider",
 | 
					                    "name": "internet_mapper",
 | 
				
			||||||
                    "kind": "bin"
 | 
					                    "kind": "bin"
 | 
				
			||||||
                }
 | 
					                }
 | 
				
			||||||
            },
 | 
					            },
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										2
									
								
								.vscode/settings.json
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										2
									
								
								.vscode/settings.json
									
									
									
									
										vendored
									
									
								
							@@ -3,6 +3,6 @@
 | 
				
			|||||||
        "creds",
 | 
					        "creds",
 | 
				
			||||||
        "reqwest",
 | 
					        "reqwest",
 | 
				
			||||||
        "rustls",
 | 
					        "rustls",
 | 
				
			||||||
        "surql"
 | 
					        "surql",
 | 
				
			||||||
    ]
 | 
					    ]
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
							
								
								
									
										1
									
								
								Cargo.lock
									
									
									
										generated
									
									
									
								
							
							
						
						
									
										1
									
								
								Cargo.lock
									
									
									
										generated
									
									
									
								
							@@ -1966,6 +1966,7 @@ name = "internet_mapper"
 | 
				
			|||||||
version = "0.1.0"
 | 
					version = "0.1.0"
 | 
				
			||||||
dependencies = [
 | 
					dependencies = [
 | 
				
			||||||
 "base64 0.22.1",
 | 
					 "base64 0.22.1",
 | 
				
			||||||
 | 
					 "futures-util",
 | 
				
			||||||
 "html5ever 0.29.1",
 | 
					 "html5ever 0.29.1",
 | 
				
			||||||
 "metrics",
 | 
					 "metrics",
 | 
				
			||||||
 "metrics-exporter-prometheus",
 | 
					 "metrics-exporter-prometheus",
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -5,12 +5,13 @@ edition = "2021"
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
[dependencies]
 | 
					[dependencies]
 | 
				
			||||||
base64 = "0.22.1"
 | 
					base64 = "0.22.1"
 | 
				
			||||||
 | 
					futures-util = "0.3.31"
 | 
				
			||||||
html5ever = "0.29"
 | 
					html5ever = "0.29"
 | 
				
			||||||
metrics = "0.24.1"
 | 
					metrics = "0.24.1"
 | 
				
			||||||
metrics-exporter-prometheus = { version = "0.16.2", features=["http-listener"]}
 | 
					metrics-exporter-prometheus = { version = "0.16.2", features=["http-listener"]}
 | 
				
			||||||
# minio = "0.1.0"
 | 
					# minio = "0.1.0"
 | 
				
			||||||
minio = {git="https://github.com/minio/minio-rs.git", rev = "c28f576"}
 | 
					minio = {git="https://github.com/minio/minio-rs.git", rev = "c28f576"}
 | 
				
			||||||
reqwest = { version = "0.12", features = ["gzip", "default", "rustls-tls"] }
 | 
					reqwest = { version = "0.12", features = ["gzip", "default", "rustls-tls", "stream"] }
 | 
				
			||||||
serde = { version = "1.0", features = ["derive"] }
 | 
					serde = { version = "1.0", features = ["derive"] }
 | 
				
			||||||
surrealdb = "2.2"
 | 
					surrealdb = "2.2"
 | 
				
			||||||
tokio = { version="1.41.0", features = ["full"] }
 | 
					tokio = { version="1.41.0", features = ["full"] }
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										14
									
								
								Crawler.toml
									
									
									
									
									
								
							
							
						
						
									
										14
									
								
								Crawler.toml
									
									
									
									
									
								
							@@ -3,14 +3,10 @@ surreal_url = "localhost:8000"
 | 
				
			|||||||
surreal_username = "root"
 | 
					surreal_username = "root"
 | 
				
			||||||
surreal_password = "root"
 | 
					surreal_password = "root"
 | 
				
			||||||
surreal_ns = "test"
 | 
					surreal_ns = "test"
 | 
				
			||||||
surreal_db = "v1.17"
 | 
					surreal_db = "v1.21.1"
 | 
				
			||||||
 | 
					 | 
				
			||||||
# Minio config
 | 
					 | 
				
			||||||
s3_bucket = "v1.17"
 | 
					 | 
				
			||||||
s3_url = "http://localhost:9000"
 | 
					 | 
				
			||||||
s3_access_key = "Ok6s9uQEvKrqRoGZdacm"
 | 
					 | 
				
			||||||
s3_secret_key = "qubeSkP787c7QZu4TvtnuwPTGIAq6ETPupCxvv6K"
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
# Crawler config
 | 
					# Crawler config
 | 
				
			||||||
crawl_filter = "en.wikipedia.com" 
 | 
					crawl_filter = "https://ftpgeoinfo.msl.mt.gov/Data/Spatial/MSDI" 
 | 
				
			||||||
budget = 1000
 | 
					start_url = "https://ftpgeoinfo.msl.mt.gov/Data/Spatial/MSDI"
 | 
				
			||||||
 | 
					budget = 10000
 | 
				
			||||||
 | 
					batch_size = 50
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										36
									
								
								README.md
									
									
									
									
									
								
							
							
						
						
									
										36
									
								
								README.md
									
									
									
									
									
								
							@@ -2,13 +2,43 @@
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
Crawls sites saving all the found links to a surrealdb database. It then proceeds to take batches of 100 uncrawled links untill the crawl budget is reached. It saves the data of each site in a minio database.
 | 
					Crawls sites saving all the found links to a surrealdb database. It then proceeds to take batches of 100 uncrawled links untill the crawl budget is reached. It saves the data of each site in a minio database.
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					## How to use
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					1. Clone the repo and `cd` into it.
 | 
				
			||||||
 | 
					2. Build the repo with `cargo build -r`
 | 
				
			||||||
 | 
					3. Start the docker conatiners
 | 
				
			||||||
 | 
						1. cd into the docker folder `cd docker`
 | 
				
			||||||
 | 
						2. Bring up the docker containers `docker compose up -d`
 | 
				
			||||||
 | 
					4. From the project's root, edit the `Crawler.toml` file to your liking.
 | 
				
			||||||
 | 
					5. Run with `./target/release/internet_mapper`
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					You can view stats of the project at `http://<your-ip>:3000/dashboards`
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					```bash
 | 
				
			||||||
 | 
					# Untested script but probably works
 | 
				
			||||||
 | 
					git clone https://git.oliveratkinson.net/Oliver/internet_mapper.git
 | 
				
			||||||
 | 
					cd internet_mapper
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					cargo build -r
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					cd docker
 | 
				
			||||||
 | 
					docker compose up -d
 | 
				
			||||||
 | 
					cd ..
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					$EDITOR Crawler.toml
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					./target/release/internet_mapper
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					```
 | 
				
			||||||
 | 
					
 | 
				
			||||||
### TODO
 | 
					### TODO
 | 
				
			||||||
 | 
					
 | 
				
			||||||
- [ ] Domain filtering - prevent the crawler from going on alternate versions of wikipedia.
 | 
					- [x] Domain filtering - prevent the crawler from going on alternate versions of wikipedia.
 | 
				
			||||||
- [ ] Conditionally save content - based on filename or file contents
 | 
					- [ ] Conditionally save content - based on filename or file contents
 | 
				
			||||||
- [x] GUI / TUI ? - Graphana
 | 
					- [x] GUI / TUI ? - Graphana
 | 
				
			||||||
- [x] Better asynchronous getting of the sites. Currently it all happens serially.
 | 
					- [x] Better asynchronous getting of the sites. Currently it all happens serially.
 | 
				
			||||||
- [ ] Allow for storing asynchronously
 | 
					- [x] Allow for storing asynchronously - dropping the "links to" logic fixes this need
 | 
				
			||||||
 | 
					- [x] Control crawler via config file (no recompliation needed)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
3/17/25: Took >1hr to crawl 100 pages
 | 
					3/17/25: Took >1hr to crawl 100 pages
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -17,6 +47,8 @@ This ment we stored 1000 pages, 142,997 urls, and 1,425,798 links between the tw
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
3/20/25: Took 5min to crawl 1000 pages
 | 
					3/20/25: Took 5min to crawl 1000 pages
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					3/21/25: Took 3min to crawl 1000 pages
 | 
				
			||||||
 | 
					
 | 
				
			||||||
# About
 | 
					# About
 | 
				
			||||||
 | 
					
 | 
				
			||||||

 | 
					
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -14,22 +14,6 @@ services:
 | 
				
			|||||||
      - --pass
 | 
					      - --pass
 | 
				
			||||||
      - root
 | 
					      - root
 | 
				
			||||||
      - rocksdb:/mydata/database.db
 | 
					      - rocksdb:/mydata/database.db
 | 
				
			||||||
  minio:
 | 
					 | 
				
			||||||
    image: quay.io/minio/minio
 | 
					 | 
				
			||||||
    ports:
 | 
					 | 
				
			||||||
      - 9000:9000
 | 
					 | 
				
			||||||
      - 9001:9001
 | 
					 | 
				
			||||||
    environment:
 | 
					 | 
				
			||||||
      - MINIO_ROOT_USER=root
 | 
					 | 
				
			||||||
      - MINIO_ROOT_PASSWORD=an8charpassword
 | 
					 | 
				
			||||||
      - MINIO_PROMETHEUS_AUTH_TYPE=public
 | 
					 | 
				
			||||||
    volumes:
 | 
					 | 
				
			||||||
      - minio_storage:/data
 | 
					 | 
				
			||||||
    command:
 | 
					 | 
				
			||||||
      - server
 | 
					 | 
				
			||||||
      - /data
 | 
					 | 
				
			||||||
      - --console-address
 | 
					 | 
				
			||||||
      - ":9001"
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
  alloy:
 | 
					  alloy:
 | 
				
			||||||
    image: grafana/alloy:latest
 | 
					    image: grafana/alloy:latest
 | 
				
			||||||
@@ -82,4 +66,3 @@ volumes:
 | 
				
			|||||||
  grafana_storage:
 | 
					  grafana_storage:
 | 
				
			||||||
  alloy_storage:
 | 
					  alloy_storage:
 | 
				
			||||||
  surrealdb_storage:
 | 
					  surrealdb_storage:
 | 
				
			||||||
  minio_storage:
 | 
					 | 
				
			||||||
 
 | 
				
			|||||||
@@ -7,14 +7,11 @@ scrape_configs:
 | 
				
			|||||||
    static_configs:
 | 
					    static_configs:
 | 
				
			||||||
    # change this your machine's ip, localhost won't work
 | 
					    # change this your machine's ip, localhost won't work
 | 
				
			||||||
    # because localhost refers to the docker container.
 | 
					    # because localhost refers to the docker container.
 | 
				
			||||||
      - targets: ['172.20.239.48:2500']
 | 
					      - targets: ['192.168.1.200:2500']
 | 
				
			||||||
 | 
					        #- targets: ['192.168.8.209:2500']
 | 
				
			||||||
  - job_name: loki
 | 
					  - job_name: loki
 | 
				
			||||||
    static_configs:
 | 
					    static_configs:
 | 
				
			||||||
      - targets: ['loki:3100']
 | 
					      - targets: ['loki:3100']
 | 
				
			||||||
  - job_name: prometheus
 | 
					  - job_name: prometheus
 | 
				
			||||||
    static_configs:
 | 
					    static_configs:
 | 
				
			||||||
      - targets: ['localhost:9090']
 | 
					      - targets: ['localhost:9090']
 | 
				
			||||||
  - job_name: minio
 | 
					 | 
				
			||||||
    metrics_path: /minio/v2/metrics/cluster
 | 
					 | 
				
			||||||
    static_configs:
 | 
					 | 
				
			||||||
      - targets: ['minio:9000']
 | 
					 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										126
									
								
								src/db.rs
									
									
									
									
									
								
							
							
						
						
									
										126
									
								
								src/db.rs
									
									
									
									
									
								
							@@ -1,57 +1,37 @@
 | 
				
			|||||||
use base64::{
 | 
					 | 
				
			||||||
    alphabet,
 | 
					 | 
				
			||||||
    engine::{self, general_purpose},
 | 
					 | 
				
			||||||
    Engine,
 | 
					 | 
				
			||||||
};
 | 
					 | 
				
			||||||
use metrics::counter;
 | 
					use metrics::counter;
 | 
				
			||||||
use serde::{ser::SerializeStruct, Deserialize, Serialize};
 | 
					use std::fmt::Debug;
 | 
				
			||||||
use std::{fmt::Debug, sync::LazyLock, time::Instant};
 | 
					use serde::{Deserialize, Serialize};
 | 
				
			||||||
use surrealdb::{
 | 
					use surrealdb::{
 | 
				
			||||||
    engine::remote::ws::{Client, Ws},
 | 
					    engine::remote::ws::{Client, Ws},
 | 
				
			||||||
    opt::auth::Root,
 | 
					    opt::auth::Root,
 | 
				
			||||||
    sql::Thing,
 | 
					    sql::Thing,
 | 
				
			||||||
    Response, Surreal,
 | 
					    Surreal,
 | 
				
			||||||
};
 | 
					};
 | 
				
			||||||
use tokio::sync::Mutex;
 | 
					use tracing::{error, instrument, trace};
 | 
				
			||||||
use tracing::{error, instrument, trace, warn};
 | 
					 | 
				
			||||||
use url::Url;
 | 
					use url::Url;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
use crate::Config;
 | 
					use crate::Config;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// static LOCK: LazyLock<Arc<Mutex<bool>>> = LazyLock::new(|| Arc::new(Mutex::new(true)));
 | 
					 | 
				
			||||||
static LOCK: LazyLock<Mutex<bool>> = LazyLock::new(|| Mutex::new(true));
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
const CUSTOM_ENGINE: engine::GeneralPurpose =
 | 
					 | 
				
			||||||
    engine::GeneralPurpose::new(&alphabet::URL_SAFE, general_purpose::NO_PAD);
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
const TIME_SPENT_ON_LOCK: &str = "surql_lock_waiting_ms";
 | 
					 | 
				
			||||||
const STORE: &str = "surql_store_calls";
 | 
					const STORE: &str = "surql_store_calls";
 | 
				
			||||||
const LINK: &str = "surql_link_calls";
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
#[derive(Deserialize, Clone)]
 | 
					#[derive(Serialize, Deserialize, Clone, Eq, PartialEq, Hash)]
 | 
				
			||||||
pub struct Website {
 | 
					pub struct Website {
 | 
				
			||||||
    /// The url that this data is found at
 | 
					    /// The url that this data is found at
 | 
				
			||||||
    pub site: Url,
 | 
					    pub site: Url,
 | 
				
			||||||
    /// Wether or not this link has been crawled yet
 | 
					    /// Wether or not this link has been crawled yet
 | 
				
			||||||
    pub crawled: bool,
 | 
					    pub crawled: bool,
 | 
				
			||||||
}
 | 
					    /// 200, 404, etc
 | 
				
			||||||
 | 
					    pub status_code: u16,
 | 
				
			||||||
impl Serialize for Website {
 | 
					 | 
				
			||||||
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
 | 
					 | 
				
			||||||
    where
 | 
					 | 
				
			||||||
        S: serde::Serializer {
 | 
					 | 
				
			||||||
            let mut state = serializer.serialize_struct("Website", 2)?;
 | 
					 | 
				
			||||||
            state.serialize_field("crawled", &self.crawled)?;
 | 
					 | 
				
			||||||
            // to_string() calls the correct naming of site
 | 
					 | 
				
			||||||
            state.serialize_field("site", &self.site.to_string())?;
 | 
					 | 
				
			||||||
            state.end()
 | 
					 | 
				
			||||||
    }
 | 
					 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
// manual impl to make tracing look nicer
 | 
					// manual impl to make tracing look nicer
 | 
				
			||||||
impl Debug for Website {
 | 
					impl Debug for Website {
 | 
				
			||||||
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 | 
					    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 | 
				
			||||||
        f.debug_struct("Website").field("site", &self.site).finish()
 | 
					        f.debug_struct("Website")
 | 
				
			||||||
 | 
					            .field("host", &self.site.host())
 | 
				
			||||||
 | 
					            .field("path", &self.site.path())
 | 
				
			||||||
 | 
					            .field("status_code", &self.status_code)
 | 
				
			||||||
 | 
					            .finish()
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -64,96 +44,25 @@ impl Website {
 | 
				
			|||||||
        };
 | 
					        };
 | 
				
			||||||
        Self {
 | 
					        Self {
 | 
				
			||||||
            crawled,
 | 
					            crawled,
 | 
				
			||||||
            site
 | 
					            site,
 | 
				
			||||||
        }
 | 
					            status_code: 0,
 | 
				
			||||||
    }
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    pub fn set_crawled(&mut self) {
 | 
					 | 
				
			||||||
        trace!("Set crawled to true");
 | 
					 | 
				
			||||||
        self.crawled = true
 | 
					 | 
				
			||||||
    }
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    pub fn get_url_as_string(site: &Url) -> String {
 | 
					 | 
				
			||||||
        let domain = match site.domain() {
 | 
					 | 
				
			||||||
            Some(s) => s.to_string(),
 | 
					 | 
				
			||||||
            None => {
 | 
					 | 
				
			||||||
                warn!("Failed to get domain of URL: {}, falling back to 'localhost'", site.to_string());
 | 
					 | 
				
			||||||
                "localhost".to_string()
 | 
					 | 
				
			||||||
            }
 | 
					 | 
				
			||||||
        };
 | 
					 | 
				
			||||||
        let path = site.path();
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        domain + path
 | 
					 | 
				
			||||||
    }
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    pub fn get_url_as_b64_path(site: &Url) -> String {
 | 
					 | 
				
			||||||
        let domain = site.domain().unwrap_or("DOMAIN").to_string();
 | 
					 | 
				
			||||||
        let path = &CUSTOM_ENGINE.encode(site.path());
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        domain + path
 | 
					 | 
				
			||||||
    }
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    #[instrument(skip_all)]
 | 
					 | 
				
			||||||
    pub async fn links_to(&self, other: Vec<Thing>, db: &Surreal<Client>) {
 | 
					 | 
				
			||||||
        let len = other.len();
 | 
					 | 
				
			||||||
        if len == 0 {
 | 
					 | 
				
			||||||
            return;
 | 
					 | 
				
			||||||
        }
 | 
					 | 
				
			||||||
        
 | 
					 | 
				
			||||||
        let from = &self.site;
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        // let to = other.site.to_string();
 | 
					 | 
				
			||||||
        trace!("Linking {} pages to {from}", other.len());
 | 
					 | 
				
			||||||
        counter!(LINK).increment(1);
 | 
					 | 
				
			||||||
        match db
 | 
					 | 
				
			||||||
            .query("COUNT(RELATE (SELECT id FROM website WHERE site = $in) -> links_to -> $out)")
 | 
					 | 
				
			||||||
            .bind(("in", from.clone()))
 | 
					 | 
				
			||||||
            .bind(("out", other))
 | 
					 | 
				
			||||||
            .await
 | 
					 | 
				
			||||||
        {
 | 
					 | 
				
			||||||
            Ok(mut e) => {
 | 
					 | 
				
			||||||
                // The relate could technically "fail" (not relate anything), this just means that
 | 
					 | 
				
			||||||
                // the query was ok.
 | 
					 | 
				
			||||||
                let _: Response = e;
 | 
					 | 
				
			||||||
                if let Ok(vec) = e.take(0) {
 | 
					 | 
				
			||||||
                    let _: Vec<usize> = vec;
 | 
					 | 
				
			||||||
                    if let Some(num) = vec.first() {
 | 
					 | 
				
			||||||
                        if *num == len {
 | 
					 | 
				
			||||||
                            trace!("Link for {from} OK - {num}/{len}");
 | 
					 | 
				
			||||||
                            return;
 | 
					 | 
				
			||||||
                        } else {
 | 
					 | 
				
			||||||
                            error!("Didn't link all the records. {num}/{len}. Surreal response: {:?}", e);
 | 
					 | 
				
			||||||
                            return;
 | 
					 | 
				
			||||||
                        }
 | 
					 | 
				
			||||||
                    }
 | 
					 | 
				
			||||||
                }
 | 
					 | 
				
			||||||
                error!("Linking request succeeded but couldn't verify the results.");
 | 
					 | 
				
			||||||
            }
 | 
					 | 
				
			||||||
            Err(e) => {
 | 
					 | 
				
			||||||
                error!("{}", e.to_string());
 | 
					 | 
				
			||||||
            }
 | 
					 | 
				
			||||||
        }
 | 
					        }
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    // Insert ever item in the vec into surreal, crawled state will be preserved as TRUE
 | 
					    // Insert ever item in the vec into surreal, crawled state will be preserved as TRUE
 | 
				
			||||||
    // if already in the database as such or incoming data is TRUE.
 | 
					    // if already in the database as such or incoming data is TRUE.
 | 
				
			||||||
 | 
					    #[instrument(skip(db))]
 | 
				
			||||||
    pub async fn store_all(all: Vec<Self>, db: &Surreal<Client>) -> Vec<Thing> {
 | 
					    pub async fn store_all(all: Vec<Self>, db: &Surreal<Client>) -> Vec<Thing> {
 | 
				
			||||||
        counter!(STORE).increment(1);
 | 
					        counter!(STORE).increment(1);
 | 
				
			||||||
        let mut things = Vec::with_capacity(all.len());
 | 
					        let mut things = Vec::with_capacity(all.len());
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        // TODO this only allows for one thread to be in the database at a time.
 | 
					        // FIXME failes *sometimes* because "Resource Busy"
 | 
				
			||||||
        // This is currently required since otherwise we get write errors.
 | 
					 | 
				
			||||||
        // If the default `crawled` is set to false, we might not need to write any more
 | 
					 | 
				
			||||||
        // than just the name. `accessed_at` is fun but not needed.
 | 
					 | 
				
			||||||
        let now = Instant::now();
 | 
					 | 
				
			||||||
        let lock = LOCK.lock().await;
 | 
					 | 
				
			||||||
        counter!(TIME_SPENT_ON_LOCK).increment(now.elapsed().as_millis() as u64);
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        match db
 | 
					        match db
 | 
				
			||||||
            .query(
 | 
					            .query(
 | 
				
			||||||
                "INSERT INTO website $array
 | 
					                "INSERT INTO website $array
 | 
				
			||||||
                    ON DUPLICATE KEY UPDATE
 | 
					                    ON DUPLICATE KEY UPDATE
 | 
				
			||||||
                        accessed_at = time::now(),
 | 
					                        accessed_at = time::now(),
 | 
				
			||||||
 | 
					                        status_code = $input.status_code,
 | 
				
			||||||
                        crawled = crawled OR $input.crawled
 | 
					                        crawled = crawled OR $input.crawled
 | 
				
			||||||
                    RETURN VALUE id;
 | 
					                    RETURN VALUE id;
 | 
				
			||||||
                 ",
 | 
					                 ",
 | 
				
			||||||
@@ -169,7 +78,6 @@ impl Website {
 | 
				
			|||||||
                error!("{:?}", err);
 | 
					                error!("{:?}", err);
 | 
				
			||||||
            }
 | 
					            }
 | 
				
			||||||
        }
 | 
					        }
 | 
				
			||||||
        drop(lock);
 | 
					 | 
				
			||||||
        things
 | 
					        things
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										66
									
								
								src/filesystem.rs
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										66
									
								
								src/filesystem.rs
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,66 @@
 | 
				
			|||||||
 | 
					use std::{io::ErrorKind, path::PathBuf};
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					use reqwest::header::HeaderValue;
 | 
				
			||||||
 | 
					use tokio::fs;
 | 
				
			||||||
 | 
					use tracing::{error, trace, warn};
 | 
				
			||||||
 | 
					use url::Url;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					pub fn as_path(url: &Url, content_type: &HeaderValue) -> PathBuf {
 | 
				
			||||||
 | 
					    // extract data from url to save it accurately
 | 
				
			||||||
 | 
					    let mut url_path = PathBuf::from("./downloaded/".to_string() + url.domain().unwrap_or("UnknownDomain") + url.path());
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    if let Ok(header) = content_type.to_str() {
 | 
				
			||||||
 | 
					        // text/html; charset=UTF-8; option=value
 | 
				
			||||||
 | 
					        let ttype = if let Some((t, _)) = header.split_once(';') {
 | 
				
			||||||
 | 
					            t
 | 
				
			||||||
 | 
					        } else {
 | 
				
			||||||
 | 
					            header
 | 
				
			||||||
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        if let Some((ttype, subtype)) = ttype.split_once('/') {
 | 
				
			||||||
 | 
					            trace!("Found Content-Type to be: {ttype}/{subtype} for {}", url.to_string());
 | 
				
			||||||
 | 
					            // If the Content-Type header is "*/html" (most likely "text/html") and the path's
 | 
				
			||||||
 | 
					            // extension is anything but html:
 | 
				
			||||||
 | 
					            if subtype=="html" && !url_path.extension().is_some_and(|f| f=="html" || f=="htm" ) {
 | 
				
			||||||
 | 
					                // time to slap a index.html to the end of that path there!
 | 
				
			||||||
 | 
					                url_path = url_path.join("index.html");
 | 
				
			||||||
 | 
					            }
 | 
				
			||||||
 | 
					        }
 | 
				
			||||||
 | 
					    } else {
 | 
				
			||||||
 | 
					        warn!("Header: {:?} couldn't be parsed into a string!", content_type);
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					    trace!("Final path for {} is: {:?}", url, url_path);
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    url_path
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					pub async fn init(filename: &PathBuf) -> Option<fs::File> {
 | 
				
			||||||
 | 
					    let file = async || tokio::fs::OpenOptions::new()
 | 
				
			||||||
 | 
					        .append(true)
 | 
				
			||||||
 | 
					        .create(true)
 | 
				
			||||||
 | 
					        .open(&filename).await;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    match file().await {
 | 
				
			||||||
 | 
					        Ok(ok) => Some(ok),
 | 
				
			||||||
 | 
					        Err(err) => {
 | 
				
			||||||
 | 
					            // the file/folder isn't found
 | 
				
			||||||
 | 
					            if err.kind() == ErrorKind::NotFound {
 | 
				
			||||||
 | 
					                if let Some(parent ) = &filename.parent() {
 | 
				
			||||||
 | 
					                    // create the folders
 | 
				
			||||||
 | 
					                    if let Err(err) = fs::create_dir_all(&parent).await {
 | 
				
			||||||
 | 
					                        error!("Dir creation: {err} {:?}", filename);
 | 
				
			||||||
 | 
					                        eprintln!("{}", err)
 | 
				
			||||||
 | 
					                    } else if let Ok(ok) = file().await {
 | 
				
			||||||
 | 
					                        return Some(ok);
 | 
				
			||||||
 | 
					                    }
 | 
				
			||||||
 | 
					                } else {
 | 
				
			||||||
 | 
					                    error!("Couldn't get file's parents: {:?}", &filename);
 | 
				
			||||||
 | 
					                }
 | 
				
			||||||
 | 
					            } else {
 | 
				
			||||||
 | 
					                error!("File open error: {err} {:?}", filename);
 | 
				
			||||||
 | 
					            }
 | 
				
			||||||
 | 
					            // we don't care about other errors, we can't/shouldn't fix them
 | 
				
			||||||
 | 
					            None
 | 
				
			||||||
 | 
					        }
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
							
								
								
									
										182
									
								
								src/main.rs
									
									
									
									
									
								
							
							
						
						
									
										182
									
								
								src/main.rs
									
									
									
									
									
								
							@@ -1,8 +1,13 @@
 | 
				
			|||||||
#![feature(ip_from)]
 | 
					#![feature(ip_from)]
 | 
				
			||||||
 | 
					#![warn(clippy::expect_used)]
 | 
				
			||||||
 | 
					#![deny(clippy::unwrap_used)]
 | 
				
			||||||
 | 
					
 | 
				
			||||||
extern crate html5ever;
 | 
					extern crate html5ever;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					use futures_util::StreamExt;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
use std::{
 | 
					use std::{
 | 
				
			||||||
 | 
					    collections::HashSet,
 | 
				
			||||||
    fs::File,
 | 
					    fs::File,
 | 
				
			||||||
    io::Read,
 | 
					    io::Read,
 | 
				
			||||||
    net::{IpAddr, Ipv4Addr},
 | 
					    net::{IpAddr, Ipv4Addr},
 | 
				
			||||||
@@ -11,16 +16,15 @@ use std::{
 | 
				
			|||||||
use db::{connect, Website};
 | 
					use db::{connect, Website};
 | 
				
			||||||
use metrics::{counter, gauge};
 | 
					use metrics::{counter, gauge};
 | 
				
			||||||
use metrics_exporter_prometheus::PrometheusBuilder;
 | 
					use metrics_exporter_prometheus::PrometheusBuilder;
 | 
				
			||||||
use s3::S3;
 | 
					 | 
				
			||||||
use serde::Deserialize;
 | 
					use serde::Deserialize;
 | 
				
			||||||
use surrealdb::{engine::remote::ws::Client, Surreal};
 | 
					use surrealdb::{engine::remote::ws::Client, Surreal};
 | 
				
			||||||
use tokio::task::JoinSet;
 | 
					use tokio::{io::{AsyncWriteExt, BufWriter}, task::JoinSet};
 | 
				
			||||||
use tracing::{debug, error, info, instrument, trace, trace_span};
 | 
					use tracing::{debug, debug_span, error, info, instrument, level_filters::LevelFilter, trace, trace_span, warn};
 | 
				
			||||||
use tracing_subscriber::{fmt, layer::SubscriberExt, EnvFilter, Layer, Registry};
 | 
					use tracing_subscriber::{fmt, layer::SubscriberExt, EnvFilter, Layer, Registry};
 | 
				
			||||||
 | 
					
 | 
				
			||||||
mod db;
 | 
					mod db;
 | 
				
			||||||
 | 
					mod filesystem;
 | 
				
			||||||
mod parser;
 | 
					mod parser;
 | 
				
			||||||
mod s3;
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
const GET_METRIC: &str = "total_gets";
 | 
					const GET_METRIC: &str = "total_gets";
 | 
				
			||||||
const GET_IN_FLIGHT: &str = "gets_in_flight";
 | 
					const GET_IN_FLIGHT: &str = "gets_in_flight";
 | 
				
			||||||
@@ -35,24 +39,25 @@ struct Config {
 | 
				
			|||||||
    surreal_username: String,
 | 
					    surreal_username: String,
 | 
				
			||||||
    surreal_password: String,
 | 
					    surreal_password: String,
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    s3_url: String,
 | 
					 | 
				
			||||||
    s3_bucket: String,
 | 
					 | 
				
			||||||
    s3_access_key: String,
 | 
					 | 
				
			||||||
    s3_secret_key: String,
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    crawl_filter: String,
 | 
					    crawl_filter: String,
 | 
				
			||||||
 | 
					    start_url: String,
 | 
				
			||||||
    budget: usize,
 | 
					    budget: usize,
 | 
				
			||||||
 | 
					    batch_size: usize,
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
#[tokio::main]
 | 
					#[tokio::main]
 | 
				
			||||||
async fn main() {
 | 
					async fn main() {
 | 
				
			||||||
 | 
					    println!("Logs and metrics are provided to the Grafana dashboard");
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    let writer = std::fs::OpenOptions::new()
 | 
					    let writer = std::fs::OpenOptions::new()
 | 
				
			||||||
        .append(true)
 | 
					        .append(true)
 | 
				
			||||||
        .create(true)
 | 
					        .create(true)
 | 
				
			||||||
        .open("./docker/logs/tracing.log")
 | 
					        .open("./docker/logs/tracing.log")
 | 
				
			||||||
        .expect("Couldn't make log file!");
 | 
					        .expect("Couldn't make log file!");
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    let filter = EnvFilter::from_default_env();
 | 
					    let filter = EnvFilter::builder()
 | 
				
			||||||
 | 
					        .with_default_directive(LevelFilter::DEBUG.into())
 | 
				
			||||||
 | 
					        .from_env_lossy();
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    let registry = Registry::default().with(
 | 
					    let registry = Registry::default().with(
 | 
				
			||||||
        fmt::layer()
 | 
					        fmt::layer()
 | 
				
			||||||
@@ -75,9 +80,8 @@ async fn main() {
 | 
				
			|||||||
        .install()
 | 
					        .install()
 | 
				
			||||||
        .expect("failed to install recorder/exporter");
 | 
					        .expect("failed to install recorder/exporter");
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    debug!("Starting...");
 | 
					    info!("Starting...");
 | 
				
			||||||
    // Would probably take these in as parameters from a cli
 | 
					
 | 
				
			||||||
    let starting_url = "https://en.wikipedia.org/";
 | 
					 | 
				
			||||||
    // When getting uncrawled pages, name must contain this variable. "" will effectively get ignored.
 | 
					    // When getting uncrawled pages, name must contain this variable. "" will effectively get ignored.
 | 
				
			||||||
    // let crawl_filter = "en.wikipedia.org/";
 | 
					    // let crawl_filter = "en.wikipedia.org/";
 | 
				
			||||||
    // let budget = 50;
 | 
					    // let budget = 50;
 | 
				
			||||||
@@ -88,13 +92,11 @@ async fn main() {
 | 
				
			|||||||
    let _ = file.read_to_string(&mut buf);
 | 
					    let _ = file.read_to_string(&mut buf);
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    let config: Config = toml::from_str(&buf).expect("Failed to parse Crawler.toml");
 | 
					    let config: Config = toml::from_str(&buf).expect("Failed to parse Crawler.toml");
 | 
				
			||||||
 | 
					    let starting_url = &config.start_url;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    let db = connect(&config)
 | 
					    let db = connect(&config)
 | 
				
			||||||
        .await
 | 
					        .await
 | 
				
			||||||
        .expect("Failed to connect to surreal, aborting.");
 | 
					        .expect("Failed to connect to surreal, aborting.");
 | 
				
			||||||
    let s3 = S3::connect(&config)
 | 
					 | 
				
			||||||
        .await
 | 
					 | 
				
			||||||
        .expect("Failed to connect to minio, aborting.\n\nThis probably means you need to login to the minio console and get a new access key!\n\n(Probably here) http://localhost:9001/access-keys/new-account\n\n");
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
    let reqwest = reqwest::Client::builder()
 | 
					    let reqwest = reqwest::Client::builder()
 | 
				
			||||||
        // .use_rustls_tls()
 | 
					        // .use_rustls_tls()
 | 
				
			||||||
@@ -108,38 +110,28 @@ async fn main() {
 | 
				
			|||||||
    let pre_loop_span = span.enter();
 | 
					    let pre_loop_span = span.enter();
 | 
				
			||||||
    // Download the site
 | 
					    // Download the site
 | 
				
			||||||
    let site = Website::new(starting_url, false);
 | 
					    let site = Website::new(starting_url, false);
 | 
				
			||||||
    process(site, db.clone(), reqwest.clone(), s3.clone()).await;
 | 
					    process(site, db.clone(), reqwest.clone()).await;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    drop(pre_loop_span);
 | 
					    drop(pre_loop_span);
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    let span = trace_span!("Loop");
 | 
					    let span = trace_span!("Loop");
 | 
				
			||||||
    let span = span.enter();
 | 
					    let span = span.enter();
 | 
				
			||||||
    while crawled < config.budget {
 | 
					    while crawled < config.budget {
 | 
				
			||||||
        let get_num = if config.budget - crawled < 100 {
 | 
					        let uncrawled =
 | 
				
			||||||
            config.budget - crawled
 | 
					            get_uncrawled_links(&db, config.budget - crawled, config.crawl_filter.clone(), &config).await;
 | 
				
			||||||
        } else {
 | 
					 | 
				
			||||||
            100
 | 
					 | 
				
			||||||
        };
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        let uncrawled = get_uncrawled_links(&db, get_num, config.crawl_filter.clone()).await;
 | 
					 | 
				
			||||||
        if uncrawled.is_empty() {
 | 
					        if uncrawled.is_empty() {
 | 
				
			||||||
            info!("Had more budget but finished crawling everything.");
 | 
					            info!("Had more budget but finished crawling everything.");
 | 
				
			||||||
            return;
 | 
					            return;
 | 
				
			||||||
        }
 | 
					        }
 | 
				
			||||||
        debug!("Crawling {} pages...", uncrawled.len());
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        let span = trace_span!("Crawling");
 | 
					 | 
				
			||||||
        let _ = span.enter();
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
        {
 | 
					        {
 | 
				
			||||||
            let mut futures = JoinSet::new();
 | 
					            let mut futures = JoinSet::new();
 | 
				
			||||||
            for site in uncrawled {
 | 
					            for site in uncrawled {
 | 
				
			||||||
                gauge!(BEING_PROCESSED).increment(1);
 | 
					                gauge!(BEING_PROCESSED).increment(1);
 | 
				
			||||||
                futures.spawn(process(site, db.clone(), reqwest.clone(), s3.clone()));
 | 
					                futures.spawn(process(site, db.clone(), reqwest.clone()));
 | 
				
			||||||
                // let percent = format!("{:.2}%", (crawled as f32 / budget as f32) * 100f32);
 | 
					                // let percent = format!("{:.2}%", (crawled as f32 / budget as f32) * 100f32);
 | 
				
			||||||
                // info!("Crawled {crawled} out of {budget} pages. ({percent})");
 | 
					                // info!("Crawled {crawled} out of {budget} pages. ({percent})");
 | 
				
			||||||
            }
 | 
					            }
 | 
				
			||||||
            debug!("Joining {} futures...", futures.len());
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
            let c = counter!(SITES_CRAWLED);
 | 
					            let c = counter!(SITES_CRAWLED);
 | 
				
			||||||
            // As futures complete runs code in while block
 | 
					            // As futures complete runs code in while block
 | 
				
			||||||
@@ -152,14 +144,23 @@ async fn main() {
 | 
				
			|||||||
    }
 | 
					    }
 | 
				
			||||||
    drop(span);
 | 
					    drop(span);
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    debug!("Done");
 | 
					    if let Ok(mut ok) = db
 | 
				
			||||||
 | 
					        .query("count(select id from website where crawled = true)")
 | 
				
			||||||
 | 
					        .await
 | 
				
			||||||
 | 
					    {
 | 
				
			||||||
 | 
					        let res = ok.take::<Option<usize>>(0);
 | 
				
			||||||
 | 
					        if let Ok(Some(n)) = res {
 | 
				
			||||||
 | 
					            info!("Total crawled pages now equals {n}");
 | 
				
			||||||
 | 
					        }
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    info!("Done");
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
#[instrument(skip(db, s3, reqwest))]
 | 
					#[instrument(skip(db, reqwest))]
 | 
				
			||||||
/// Downloads and crawls and stores a webpage.
 | 
					/// Downloads and crawls and stores a webpage.
 | 
				
			||||||
/// It is acceptable to clone `db`, `reqwest`, and `s3` because they all use `Arc`s internally. - Noted by Oliver
 | 
					/// It is acceptable to clone `db`, `reqwest`, and `s3` because they all use `Arc`s internally. - Noted by Oliver
 | 
				
			||||||
async fn process(mut site: Website, db: Surreal<Client>, reqwest: reqwest::Client, s3: S3) {
 | 
					async fn process(mut site: Website, db: Surreal<Client>, reqwest: reqwest::Client) {
 | 
				
			||||||
    
 | 
					 | 
				
			||||||
    // METRICS
 | 
					    // METRICS
 | 
				
			||||||
    trace!("Process: {}", &site.site);
 | 
					    trace!("Process: {}", &site.site);
 | 
				
			||||||
    // Build the request
 | 
					    // Build the request
 | 
				
			||||||
@@ -171,48 +172,110 @@ async fn process(mut site: Website, db: Surreal<Client>, reqwest: reqwest::Clien
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
    // Send the http request (get)
 | 
					    // Send the http request (get)
 | 
				
			||||||
    if let Ok(response) = request_builder.send().await {
 | 
					    if let Ok(response) = request_builder.send().await {
 | 
				
			||||||
 | 
					        let headers = response.headers();
 | 
				
			||||||
 | 
					        let code = response.status();
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        // METRICS
 | 
					        #[allow(non_snake_case)]
 | 
				
			||||||
        g.decrement(1);
 | 
					        let CT = headers.get("Content-Type");
 | 
				
			||||||
        counter!(GET_METRIC).increment(1);
 | 
					        let ct = headers.get("content-type");
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        // Get body from response
 | 
					        let ct = match (CT,ct) {
 | 
				
			||||||
        let data = response
 | 
					            (None, None) => {
 | 
				
			||||||
            .text()
 | 
					                warn!("Server did not respond with Content-Type header. Url: {} Headers: ({:?})", site.site.to_string(), headers);
 | 
				
			||||||
            .await
 | 
					                return
 | 
				
			||||||
            .expect("Failed to read http response's body!");
 | 
					            },
 | 
				
			||||||
        // Store document
 | 
					            (None, Some(a)) => a,
 | 
				
			||||||
        s3.store(&data, &site.site).await;
 | 
					            (Some(a), None) => a,
 | 
				
			||||||
 | 
					            (Some(a), Some(_)) => a,
 | 
				
			||||||
 | 
					        };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        // Parse document and get relationships
 | 
					        // create filepath (handles / -> /index.html)
 | 
				
			||||||
        let sites = parser::parse(&site, &data).await;
 | 
					        let path = filesystem::as_path(&site.site, ct);
 | 
				
			||||||
        
 | 
					 | 
				
			||||||
        // update self in db
 | 
					 | 
				
			||||||
        site.set_crawled();
 | 
					 | 
				
			||||||
        Website::store_all(vec![site], &db).await;
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
        // Store all the other sites so that we can link to them.
 | 
					        // make sure that the file is good to go
 | 
				
			||||||
        // let mut links_to = Vec::new();
 | 
					        if let Some(file) = filesystem::init(&path).await {
 | 
				
			||||||
        let _ = Website::store_all(sites, &db).await;
 | 
					            // Get body from response
 | 
				
			||||||
 | 
					            // stream the response onto the disk
 | 
				
			||||||
 | 
					            let mut stream = response.bytes_stream();
 | 
				
			||||||
 | 
					
 | 
				
			||||||
        // Make the database's links reflect the html links between sites
 | 
					            let should_parse = path.to_string_lossy().ends_with(".html");
 | 
				
			||||||
        // site.links_to(others, &db).await;
 | 
					            let mut writer = BufWriter::new(file);
 | 
				
			||||||
 | 
					            let mut buf: Vec<u8> = Vec::new();
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					            // Write file to disk
 | 
				
			||||||
 | 
					            info!("Writing at: {:?}", path);
 | 
				
			||||||
 | 
					            while let Some(data) = stream.next().await {
 | 
				
			||||||
 | 
					                match data {
 | 
				
			||||||
 | 
					                    Ok(data) => {
 | 
				
			||||||
 | 
					                        let _ = writer.write_all(&data).await;
 | 
				
			||||||
 | 
					                        // If we are going to parse this file later, we will save it
 | 
				
			||||||
 | 
					                        // into memory as well as the disk.
 | 
				
			||||||
 | 
					                        // We do this because the data here might be incomplete
 | 
				
			||||||
 | 
					                        if should_parse {
 | 
				
			||||||
 | 
					                            data.iter().for_each(|f| buf.push(*f));
 | 
				
			||||||
 | 
					                        }
 | 
				
			||||||
 | 
					                    },
 | 
				
			||||||
 | 
					                    Err(err) => {
 | 
				
			||||||
 | 
					                        eprintln!("{}", err)
 | 
				
			||||||
 | 
					                    },
 | 
				
			||||||
 | 
					                }
 | 
				
			||||||
 | 
					            }
 | 
				
			||||||
 | 
					            let _ = writer.flush();
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					            // (If needed) Parse the file
 | 
				
			||||||
 | 
					            if should_parse {
 | 
				
			||||||
 | 
					                let span = debug_span!("Should Parse");
 | 
				
			||||||
 | 
					                let enter = span.enter();
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					                // Parse document and get relationships
 | 
				
			||||||
 | 
					                let sites = parser::parse(&site, &buf).await;
 | 
				
			||||||
 | 
					                // De-duplicate this list
 | 
				
			||||||
 | 
					                let prev_len = sites.len();
 | 
				
			||||||
 | 
					                let set = sites.into_iter().fold(HashSet::new(), |mut set, item| {
 | 
				
			||||||
 | 
					                    set.insert(item);
 | 
				
			||||||
 | 
					                    set
 | 
				
			||||||
 | 
					                });
 | 
				
			||||||
 | 
					                let de_dupe_sites: Vec<Website> = set.into_iter().collect();
 | 
				
			||||||
 | 
					                let diff = prev_len - de_dupe_sites.len();
 | 
				
			||||||
 | 
					                trace!("Saved {diff} from being entered into the db by de-duping");
 | 
				
			||||||
 | 
					                // Store all the other sites so that we can link to them.
 | 
				
			||||||
 | 
					                let _ = Website::store_all(de_dupe_sites, &db).await;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					                drop(enter);
 | 
				
			||||||
 | 
					            }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					            // METRICS
 | 
				
			||||||
 | 
					            g.decrement(1);
 | 
				
			||||||
 | 
					            counter!(GET_METRIC).increment(1);
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					            // update self in db
 | 
				
			||||||
 | 
					            site.crawled = true;
 | 
				
			||||||
 | 
					            site.status_code = code.as_u16();
 | 
				
			||||||
 | 
					            Website::store_all(vec![site.clone()], &db).await;
 | 
				
			||||||
 | 
					        } else {
 | 
				
			||||||
 | 
					            error!("File failed to cooperate: {:?}", path);
 | 
				
			||||||
 | 
					        }
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					        trace!("Done processing: {}", &site.site);
 | 
				
			||||||
    } else {
 | 
					    } else {
 | 
				
			||||||
        error!("Failed to get: {}", &site.site);
 | 
					        error!("Failed to get: {}", &site.site);
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
/// Returns uncrawled links
 | 
					/// Returns uncrawled links
 | 
				
			||||||
#[instrument(skip(db))]
 | 
					#[instrument(skip(db, config))]
 | 
				
			||||||
async fn get_uncrawled_links(
 | 
					async fn get_uncrawled_links(
 | 
				
			||||||
    db: &Surreal<Client>,
 | 
					    db: &Surreal<Client>,
 | 
				
			||||||
    mut count: usize,
 | 
					    mut count: usize,
 | 
				
			||||||
    filter: String,
 | 
					    filter: String,
 | 
				
			||||||
 | 
					    config: &Config,
 | 
				
			||||||
) -> Vec<Website> {
 | 
					) -> Vec<Website> {
 | 
				
			||||||
    if count > 100 {
 | 
					    if count > config.batch_size {
 | 
				
			||||||
        count = 100
 | 
					        count = config.batch_size;
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
    debug!("Getting uncrawled links");
 | 
					
 | 
				
			||||||
 | 
					    debug!("Getting {} uncrawled links", count);
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    let mut response = db
 | 
					    let mut response = db
 | 
				
			||||||
        .query("SELECT * FROM website WHERE crawled = false AND site ~ type::string($format) LIMIT $count;")
 | 
					        .query("SELECT * FROM website WHERE crawled = false AND site ~ type::string($format) LIMIT $count;")
 | 
				
			||||||
@@ -224,4 +287,3 @@ async fn get_uncrawled_links(
 | 
				
			|||||||
        .take(0)
 | 
					        .take(0)
 | 
				
			||||||
        .expect("Returned websites couldn't be parsed")
 | 
					        .expect("Returned websites couldn't be parsed")
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										123
									
								
								src/parser.rs
									
									
									
									
									
								
							
							
						
						
									
										123
									
								
								src/parser.rs
									
									
									
									
									
								
							@@ -1,22 +1,24 @@
 | 
				
			|||||||
use std::default::Default;
 | 
					use std::default::Default;
 | 
				
			||||||
use std::str::FromStr;
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
use html5ever::tokenizer::{BufferQueue, TokenizerResult};
 | 
					use html5ever::tokenizer::{BufferQueue, TokenizerResult};
 | 
				
			||||||
use html5ever::tokenizer::{StartTag, TagToken};
 | 
					use html5ever::tokenizer::{StartTag, TagToken};
 | 
				
			||||||
use html5ever::tokenizer::{Token, TokenSink, TokenSinkResult, Tokenizer, TokenizerOpts};
 | 
					use html5ever::tokenizer::{Token, TokenSink, TokenSinkResult, Tokenizer, TokenizerOpts};
 | 
				
			||||||
use html5ever::{local_name, tendril::*};
 | 
					use html5ever::{local_name, tendril::*};
 | 
				
			||||||
use tracing::instrument;
 | 
					use tracing::{debug, error, instrument, trace, warn};
 | 
				
			||||||
 | 
					use url::Url;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
use crate::db::Website;
 | 
					use crate::db::Website;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
impl TokenSink for Website {
 | 
					impl TokenSink for Website {
 | 
				
			||||||
    type Handle = Vec<Website>;
 | 
					    type Handle = Vec<Website>;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    #[instrument(skip(token, _line_number))]
 | 
				
			||||||
    fn process_token(&self, token: Token, _line_number: u64) -> TokenSinkResult<Self::Handle> {
 | 
					    fn process_token(&self, token: Token, _line_number: u64) -> TokenSinkResult<Self::Handle> {
 | 
				
			||||||
        match token {
 | 
					        match token {
 | 
				
			||||||
            TagToken(tag) => {
 | 
					            TagToken(tag) => {
 | 
				
			||||||
                if tag.kind == StartTag {
 | 
					                if tag.kind == StartTag {
 | 
				
			||||||
                    match tag.name {
 | 
					                    match tag.name {
 | 
				
			||||||
 | 
					                        // this should be all the html elements that have links
 | 
				
			||||||
                        local_name!("a")
 | 
					                        local_name!("a")
 | 
				
			||||||
                        | local_name!("audio")
 | 
					                        | local_name!("audio")
 | 
				
			||||||
                        | local_name!("area")
 | 
					                        | local_name!("area")
 | 
				
			||||||
@@ -31,23 +33,18 @@ impl TokenSink for Website {
 | 
				
			|||||||
                                let attr_name = attr.name.local.to_string();
 | 
					                                let attr_name = attr.name.local.to_string();
 | 
				
			||||||
                                if attr_name == "src" || attr_name == "href" || attr_name == "data"
 | 
					                                if attr_name == "src" || attr_name == "href" || attr_name == "data"
 | 
				
			||||||
                                {
 | 
					                                {
 | 
				
			||||||
                                    // Get clone of the current site object
 | 
					                                    trace!("Found `{}` in html `{}` tag", &attr.value, tag.name);
 | 
				
			||||||
                                    let mut web = self.clone();
 | 
					                                    let url = try_get_url(&self.site, &attr.value);
 | 
				
			||||||
 | 
					
 | 
				
			||||||
                                    // Set url
 | 
					                                    if let Some(mut parsed) = url {
 | 
				
			||||||
                                    let mut url = web.site;
 | 
					                                        parsed.set_query(None);
 | 
				
			||||||
                                    url.set_fragment(None); // removes #xyz
 | 
					                                        parsed.set_fragment(None);
 | 
				
			||||||
                                    let joined = url
 | 
					                                        trace!("Final cleaned URL: `{}`", parsed.to_string());
 | 
				
			||||||
                                        .join(&attr.value)
 | 
					                                        let web = Website::new(&parsed.to_string(), false);
 | 
				
			||||||
                                        .expect("Failed to join url during parsing!");
 | 
					                                        links.push(web);
 | 
				
			||||||
                                    web.site = joined;
 | 
					                                    }
 | 
				
			||||||
 | 
					 | 
				
			||||||
                                    web.crawled = false;
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
                                    links.push(web);
 | 
					 | 
				
			||||||
                                }
 | 
					                                }
 | 
				
			||||||
                            }
 | 
					                            }
 | 
				
			||||||
 | 
					 | 
				
			||||||
                            return TokenSinkResult::Script(links);
 | 
					                            return TokenSinkResult::Script(links);
 | 
				
			||||||
                        }
 | 
					                        }
 | 
				
			||||||
                        local_name!("button") | local_name!("meta") | local_name!("iframe") => {
 | 
					                        local_name!("button") | local_name!("meta") | local_name!("iframe") => {
 | 
				
			||||||
@@ -65,30 +62,90 @@ impl TokenSink for Website {
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
#[instrument(skip_all)]
 | 
					#[instrument(skip_all)]
 | 
				
			||||||
/// Parses the passed site and returns all the sites it links to.
 | 
					/// Parses the passed site and returns all the sites it links to.
 | 
				
			||||||
pub async fn parse(site: &Website, data: &str) -> Vec<Website> {
 | 
					pub async fn parse(site: &Website, data: &[u8]) -> Vec<Website> {
 | 
				
			||||||
 | 
					    debug!("Parsing {}", site.site.to_string());
 | 
				
			||||||
    // prep work
 | 
					    // prep work
 | 
				
			||||||
    let mut other_sites: Vec<Website> = Vec::new();
 | 
					    let mut other_sites: Vec<Website> = Vec::new();
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    // change data into something that can be tokenized
 | 
					    // change data into something that can be tokenized
 | 
				
			||||||
    let chunk = Tendril::from_str(data).expect("Failed to parse string into Tendril!");
 | 
					    let s: Result<Tendril<fmt::UTF8>, ()> = Tendril::try_from_byte_slice(data);
 | 
				
			||||||
    // create buffer of tokens and push our input into it
 | 
					    if let Ok(chunk) = s {
 | 
				
			||||||
    let token_buffer = BufferQueue::default();
 | 
					        // create buffer of tokens and push our input into it
 | 
				
			||||||
    token_buffer.push_back(
 | 
					        let token_buffer = BufferQueue::default();
 | 
				
			||||||
        chunk
 | 
					        token_buffer.push_back(
 | 
				
			||||||
            .try_reinterpret::<fmt::UTF8>()
 | 
					            chunk
 | 
				
			||||||
            .expect("Failed to reinterprt chunk!"),
 | 
					                .try_reinterpret::<fmt::UTF8>()
 | 
				
			||||||
    );
 | 
					                .expect("Failed to reinterpret chunk!"),
 | 
				
			||||||
    // create the tokenizer
 | 
					        );
 | 
				
			||||||
    let tokenizer = Tokenizer::new(site.clone(), TokenizerOpts::default());
 | 
					        // create the tokenizer
 | 
				
			||||||
 | 
					        let tokenizer = Tokenizer::new(site.clone(), TokenizerOpts::default());
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    // go thru buffer
 | 
					        // go thru buffer
 | 
				
			||||||
    while let TokenizerResult::Script(mut sites) = tokenizer.feed(&token_buffer) {
 | 
					        while let TokenizerResult::Script(mut sites) = tokenizer.feed(&token_buffer) {
 | 
				
			||||||
        other_sites.append(&mut sites);
 | 
					            other_sites.append(&mut sites);
 | 
				
			||||||
        // other_sites.push(sites);
 | 
					            // other_sites.push(sites);
 | 
				
			||||||
 | 
					        }
 | 
				
			||||||
 | 
					        assert!(token_buffer.is_empty());
 | 
				
			||||||
 | 
					        tokenizer.end();
 | 
				
			||||||
 | 
					    } else {
 | 
				
			||||||
 | 
					        warn!("Tendril failed to parse on: {}", site.site.to_string());
 | 
				
			||||||
    }
 | 
					    }
 | 
				
			||||||
    assert!(token_buffer.is_empty());
 | 
					 | 
				
			||||||
    tokenizer.end();
 | 
					 | 
				
			||||||
 | 
					
 | 
				
			||||||
    other_sites
 | 
					    other_sites
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					#[instrument]
 | 
				
			||||||
 | 
					fn try_get_url(parent: &Url, link: &str) -> Option<Url> {
 | 
				
			||||||
 | 
					    match Url::parse(link) {
 | 
				
			||||||
 | 
					        Ok(ok) => Some(ok),
 | 
				
			||||||
 | 
					        Err(e) => {
 | 
				
			||||||
 | 
					            if link.starts_with('#') {
 | 
				
			||||||
 | 
					                trace!("Rejecting # url");
 | 
				
			||||||
 | 
					                None
 | 
				
			||||||
 | 
					            } else if link.starts_with("//") {
 | 
				
			||||||
 | 
					                // if a url starts with "//" is assumed that it will adopt
 | 
				
			||||||
 | 
					                // the same scheme as it's parent
 | 
				
			||||||
 | 
					                // https://stackoverflow.com/questions/9646407/two-forward-slashes-in-a-url-src-href-attribute
 | 
				
			||||||
 | 
					                let scheme = parent.scheme();
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					                match Url::parse(&format!("{scheme}://{}", link)) {
 | 
				
			||||||
 | 
					                    Ok(url) => Some(url),
 | 
				
			||||||
 | 
					                    Err(err) => {
 | 
				
			||||||
 | 
					                        error!("Failed parsing relative scheme url: {}", err);
 | 
				
			||||||
 | 
					                        None
 | 
				
			||||||
 | 
					                    }
 | 
				
			||||||
 | 
					                }
 | 
				
			||||||
 | 
					            } else {
 | 
				
			||||||
 | 
					                // # This is some sort of realative url, gonna try patching it up into an absolute
 | 
				
			||||||
 | 
					                // url
 | 
				
			||||||
 | 
					                match e {
 | 
				
			||||||
 | 
					                    url::ParseError::RelativeUrlWithoutBase => {
 | 
				
			||||||
 | 
					                        // Is: scheme://host:port
 | 
				
			||||||
 | 
					                        let mut origin = parent.origin().ascii_serialization();
 | 
				
			||||||
 | 
					                        if !origin.ends_with('/') && !link.starts_with('/') {
 | 
				
			||||||
 | 
					                            origin += "/";
 | 
				
			||||||
 | 
					                        }
 | 
				
			||||||
 | 
					                        let url = origin.clone() + link;
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					                        if let Ok(url) = Url::parse(&url) {
 | 
				
			||||||
 | 
					                            trace!("Built `{url}` from `{origin} + `{}`", link.to_string());
 | 
				
			||||||
 | 
					                            Some(url)
 | 
				
			||||||
 | 
					                        } else {
 | 
				
			||||||
 | 
					                            error!(
 | 
				
			||||||
 | 
					                                "Failed to reconstruct a url from relative url: `{}` on site: `{}`. Failed url was: {}",
 | 
				
			||||||
 | 
					                                link,
 | 
				
			||||||
 | 
					                                parent.to_string(),
 | 
				
			||||||
 | 
					                                url
 | 
				
			||||||
 | 
					                            );
 | 
				
			||||||
 | 
					                            None
 | 
				
			||||||
 | 
					                        }
 | 
				
			||||||
 | 
					                    }
 | 
				
			||||||
 | 
					                    _ => {
 | 
				
			||||||
 | 
					                        error!("MISC error: {:?} {:?}", e, link);
 | 
				
			||||||
 | 
					                        None
 | 
				
			||||||
 | 
					                    }
 | 
				
			||||||
 | 
					                }
 | 
				
			||||||
 | 
					            }
 | 
				
			||||||
 | 
					        }
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
 
 | 
				
			|||||||
							
								
								
									
										100
									
								
								src/s3.rs
									
									
									
									
									
								
							
							
						
						
									
										100
									
								
								src/s3.rs
									
									
									
									
									
								
							@@ -1,100 +0,0 @@
 | 
				
			|||||||
use metrics::counter;
 | 
					 | 
				
			||||||
use minio::s3::{
 | 
					 | 
				
			||||||
    args::{BucketExistsArgs, MakeBucketArgs},
 | 
					 | 
				
			||||||
    client::ClientBuilder,
 | 
					 | 
				
			||||||
    creds::StaticProvider,
 | 
					 | 
				
			||||||
    error::Error,
 | 
					 | 
				
			||||||
    http::BaseUrl,
 | 
					 | 
				
			||||||
    Client,
 | 
					 | 
				
			||||||
};
 | 
					 | 
				
			||||||
use tracing::{instrument, trace, warn};
 | 
					 | 
				
			||||||
use url::Url;
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
use crate::{db::Website, Config};
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
const S3_ROUND_TRIP_METRIC: &str = "s3_trips";
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
#[derive(Clone)]
 | 
					 | 
				
			||||||
pub struct S3 {
 | 
					 | 
				
			||||||
    bucket_name: String,
 | 
					 | 
				
			||||||
    client: Client,
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
impl S3 {
 | 
					 | 
				
			||||||
    #[instrument(skip_all, name = "S3")]
 | 
					 | 
				
			||||||
    pub async fn connect(config: &Config) -> Result<Self, Error> {
 | 
					 | 
				
			||||||
        let base_url = config
 | 
					 | 
				
			||||||
            .s3_url
 | 
					 | 
				
			||||||
            .parse::<BaseUrl>()
 | 
					 | 
				
			||||||
            .expect("Failed to parse url into BaseUrl");
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        let static_provider =
 | 
					 | 
				
			||||||
            StaticProvider::new(&config.s3_access_key, &config.s3_secret_key, None);
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        let client = ClientBuilder::new(base_url)
 | 
					 | 
				
			||||||
            .provider(Some(Box::new(static_provider)))
 | 
					 | 
				
			||||||
            .build()?;
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        trace!("Checking bucket...");
 | 
					 | 
				
			||||||
        let exists = client
 | 
					 | 
				
			||||||
            .bucket_exists(
 | 
					 | 
				
			||||||
                &BucketExistsArgs::new(&config.s3_bucket)
 | 
					 | 
				
			||||||
                    .expect("Failed to check if bucket exists"),
 | 
					 | 
				
			||||||
            )
 | 
					 | 
				
			||||||
            .await?;
 | 
					 | 
				
			||||||
        counter!(S3_ROUND_TRIP_METRIC).increment(1);
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        if !exists {
 | 
					 | 
				
			||||||
            trace!("Creating bucket...");
 | 
					 | 
				
			||||||
            client
 | 
					 | 
				
			||||||
                .make_bucket(
 | 
					 | 
				
			||||||
                    &MakeBucketArgs::new(&config.s3_bucket).expect("Failed to create bucket!"),
 | 
					 | 
				
			||||||
                )
 | 
					 | 
				
			||||||
                .await?;
 | 
					 | 
				
			||||||
        }
 | 
					 | 
				
			||||||
        counter!(S3_ROUND_TRIP_METRIC).increment(1);
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        trace!("Connection successful");
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        Ok(Self {
 | 
					 | 
				
			||||||
            bucket_name: config.s3_bucket.to_owned(),
 | 
					 | 
				
			||||||
            client,
 | 
					 | 
				
			||||||
        })
 | 
					 | 
				
			||||||
    }
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
    #[instrument(name = "s3_store", skip_all)]
 | 
					 | 
				
			||||||
    pub async fn store(&self, data: &str, url: &Url) {
 | 
					 | 
				
			||||||
        let counter = counter!(S3_ROUND_TRIP_METRIC);
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        let filename = Website::get_url_as_string(url);
 | 
					 | 
				
			||||||
        trace!("Storing {} as {filename}", url.to_string());
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
        counter.increment(1);
 | 
					 | 
				
			||||||
        match &self
 | 
					 | 
				
			||||||
            .client
 | 
					 | 
				
			||||||
            .put_object_content(&self.bucket_name, &filename, data.to_owned())
 | 
					 | 
				
			||||||
            .send()
 | 
					 | 
				
			||||||
            .await
 | 
					 | 
				
			||||||
        {
 | 
					 | 
				
			||||||
            Ok(_) => {}
 | 
					 | 
				
			||||||
            Err(err) => match err {
 | 
					 | 
				
			||||||
                Error::InvalidObjectName(_) => {
 | 
					 | 
				
			||||||
                    // This code will really only run if the url has non-english chars
 | 
					 | 
				
			||||||
                    warn!("Tried storing invalid object name, retrying with Base64 encoding. Last try.");
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
                    let filename: String = Website::get_url_as_b64_path(url);
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
                    counter.increment(1);
 | 
					 | 
				
			||||||
                    let _ = &self
 | 
					 | 
				
			||||||
                        .client
 | 
					 | 
				
			||||||
                        .put_object_content(&self.bucket_name, &filename, data.to_owned())
 | 
					 | 
				
			||||||
                        .send()
 | 
					 | 
				
			||||||
                        .await
 | 
					 | 
				
			||||||
                        .unwrap();
 | 
					 | 
				
			||||||
                }
 | 
					 | 
				
			||||||
                _ => {}
 | 
					 | 
				
			||||||
            },
 | 
					 | 
				
			||||||
        };
 | 
					 | 
				
			||||||
    }
 | 
					 | 
				
			||||||
}
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
		Reference in New Issue
	
	Block a user