diff --git a/.cursor/rules/userlevel.mdc b/.cursor/rules/userlevel.mdc new file mode 100644 index 0000000..4e0eb51 --- /dev/null +++ b/.cursor/rules/userlevel.mdc @@ -0,0 +1,44 @@ +--- +alwaysApply: true +--- +## Prompt Versão 2 (Conciso) + +``` +## ESPECIALISTA EM RUST PARA INICIANTES - MODO DIDÁTICO DIRETO + +### Configuração Principal +Você é um instrutor de Rust especializado em ensino para iniciantes absolutos. Sua comunicação segue estas regras rigorosamente: + +**Concisão com Qualidade:** +- Máximo 2-3 frases por explicação, sem floreios +- Uma idea por parágrafo +- Omitir redundâncias + +**Explicação de Erros:** +- Estrutura: [O que aconteceu] → [Por quê] → [Como corrigir] +- Sempre com analogia/comparação simples +- Nunca exceda 1 parágrafo por erro + +**Sequência de Raciocínio:** +1. Identifique qual conceito está sendo abordado +2. Relate com conhecimento anterior do usuário +3. Forneça exemplo funcional mínimo +4. Mostre o erro comum e correção + +### Comportamento na Interação +- Quando o usuário pede uma explicação: context breve → conceito → código mínimo funcionando +- Quando ocorre erro: analise o tipo de erro → explique por que ocorreu → solução em 1-2 linhas de correção +- Se pedir sobre ownership/borrow checker: use metáfora de "empréstimo de livro" ou similar + +### Exemplos de Tom Esperado + +**Ruim:** "A propriedade em Rust é um conceito fundamental que permite..." +**Bom:** "Propriedade = só um dono por vez (como uma chave única)." + +**Ruim:** "Este erro ocorre porque a função tenta acessar a variável..." +**Bom:** "Erro: tentou usar `x` após move. Por quê? `x` foi transferido. Solução: use referência `&x` ou clone se precisar cópia." + +### Foco de Aprendizado +Prioridades: Variables → Data Types → Functions → Control Flow → Ownership/Borrowing → Enums/Structs → Error Handling + +Adapte profundidade conforme necessário, mas SEMPRE mantenha a brevidade. diff --git a/.env b/.env new file mode 100644 index 0000000..e69de29 diff --git a/.gitignore b/.gitignore index 0104787..423b479 100644 --- a/.gitignore +++ b/.gitignore @@ -14,4 +14,8 @@ target/ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore # and can be added to the global gitignore or merged into this file. For a more nuclear # option (not recommended) you can uncomment the following to ignore the entire idea folder. -#.idea/ \ No newline at end of file +#.idea/ + +# Added by cargo + +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..27ba6a1 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,2745 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "OllaHubBackend" +version = "0.1.0" +dependencies = [ + "actix", + "actix-rt", + "actix-web", + "actix-web-actors", + "actix-web-lab", + "aes-gcm", + "awc", + "base64 0.21.7", + "dirs", + "hex", + "jsonwebtoken", + "rand 0.8.5", + "serde", + "serde_json", + "sysinfo", + "tokio", + "utoipa", + "utoipa-swagger-ui", + "uuid", + "validator", +] + +[[package]] +name = "actix" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de7fa236829ba0841304542f7614c42b80fca007455315c45c785ccfa873a85b" +dependencies = [ + "actix-macros", + "actix-rt", + "actix_derive", + "bitflags", + "bytes", + "crossbeam-channel", + "futures-core", + "futures-sink", + "futures-task", + "futures-util", + "log", + "once_cell", + "parking_lot", + "pin-project-lite", + "smallvec", + "tokio", + "tokio-util", +] + +[[package]] +name = "actix-codec" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f7b0a21988c1bf877cf4759ef5ddaac04c1c9fe808c9142ecb78ba97d97a28a" +dependencies = [ + "bitflags", + "bytes", + "futures-core", + "futures-sink", + "memchr", + "pin-project-lite", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "actix-http" +version = "3.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7926860314cbe2fb5d1f13731e387ab43bd32bca224e82e6e2db85de0a3dba49" +dependencies = [ + "actix-codec", + "actix-rt", + "actix-service", + "actix-utils", + "base64 0.22.1", + "bitflags", + "brotli", + "bytes", + "bytestring", + "derive_more", + "encoding_rs", + "flate2", + "foldhash", + "futures-core", + "h2", + "http 0.2.12", + "httparse", + "httpdate", + "itoa", + "language-tags", + "local-channel", + "mime", + "percent-encoding", + "pin-project-lite", + "rand 0.9.2", + "sha1", + "smallvec", + "tokio", + "tokio-util", + "tracing", + "zstd", +] + +[[package]] +name = "actix-macros" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01ed3140b2f8d422c68afa1ed2e85d996ea619c988ac834d255db32138655cb" +dependencies = [ + "quote", + "syn 2.0.109", +] + +[[package]] +name = "actix-router" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13d324164c51f63867b57e73ba5936ea151b8a41a1d23d1031eeb9f70d0236f8" +dependencies = [ + "bytestring", + "cfg-if", + "http 0.2.12", + "regex", + "regex-lite", + "serde", + "tracing", +] + +[[package]] +name = "actix-rt" +version = "2.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92589714878ca59a7626ea19734f0e07a6a875197eec751bb5d3f99e64998c63" +dependencies = [ + "actix-macros", + "futures-core", + "tokio", +] + +[[package]] +name = "actix-server" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a65064ea4a457eaf07f2fba30b4c695bf43b721790e9530d26cb6f9019ff7502" +dependencies = [ + "actix-rt", + "actix-service", + "actix-utils", + "futures-core", + "futures-util", + "mio", + "socket2 0.5.10", + "tokio", + "tracing", +] + +[[package]] +name = "actix-service" +version = "2.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e46f36bf0e5af44bdc4bdb36fbbd421aa98c79a9bce724e1edeb3894e10dc7f" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "actix-tls" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac453898d866cdbecdbc2334fe1738c747b4eba14a677261f2b768ba05329389" +dependencies = [ + "actix-rt", + "actix-service", + "actix-utils", + "futures-core", + "http 0.2.12", + "http 1.3.1", + "impl-more", + "pin-project-lite", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "actix-utils" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88a1dcdff1466e3c2488e1cb5c36a71822750ad43839937f85d2f4d9f8b705d8" +dependencies = [ + "local-waker", + "pin-project-lite", +] + +[[package]] +name = "actix-web" +version = "4.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a597b77b5c6d6a1e1097fddde329a83665e25c5437c696a3a9a4aa514a614dea" +dependencies = [ + "actix-codec", + "actix-http", + "actix-macros", + "actix-router", + "actix-rt", + "actix-server", + "actix-service", + "actix-utils", + "actix-web-codegen", + "bytes", + "bytestring", + "cfg-if", + "cookie", + "derive_more", + "encoding_rs", + "foldhash", + "futures-core", + "futures-util", + "impl-more", + "itoa", + "language-tags", + "log", + "mime", + "once_cell", + "pin-project-lite", + "regex", + "regex-lite", + "serde", + "serde_json", + "serde_urlencoded", + "smallvec", + "socket2 0.5.10", + "time", + "tracing", + "url", +] + +[[package]] +name = "actix-web-actors" +version = "4.3.1+deprecated" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f98c5300b38fd004fe7d2a964f9a90813fdbe8a81fed500587e78b1b71c6f980" +dependencies = [ + "actix", + "actix-codec", + "actix-http", + "actix-web", + "bytes", + "bytestring", + "futures-core", + "pin-project-lite", + "tokio", + "tokio-util", +] + +[[package]] +name = "actix-web-codegen" +version = "4.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f591380e2e68490b5dfaf1dd1aa0ebe78d84ba7067078512b4ea6e4492d622b8" +dependencies = [ + "actix-router", + "proc-macro2", + "quote", + "syn 2.0.109", +] + +[[package]] +name = "actix-web-lab" +version = "0.24.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fde7e471db19a782577913d5fb56974fd247c5c841c56069632d4ea353f88e3" +dependencies = [ + "actix-http", + "actix-router", + "actix-service", + "actix-utils", + "actix-web", + "actix-web-lab-derive", + "ahash", + "arc-swap", + "bytes", + "bytestring", + "csv", + "derive_more", + "form_urlencoded", + "futures-core", + "futures-util", + "http 0.2.12", + "impl-more", + "itertools", + "local-channel", + "mime", + "pin-project-lite", + "regex", + "serde", + "serde_html_form", + "serde_json", + "serde_path_to_error", + "tokio", + "tokio-stream", + "tracing", + "url", +] + +[[package]] +name = "actix-web-lab-derive" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dd80fa0bd6217e482112d9d87a05af8e0f8dec9e3aa51f34816f761c5cf7da7" +dependencies = [ + "quote", + "syn 2.0.109", +] + +[[package]] +name = "actix_derive" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6ac1e58cded18cb28ddc17143c4dea5345b3ad575e14f32f66e4054a56eb271" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.109", +] + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "aes-gcm" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "subtle", +] + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "getrandom 0.3.4", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-stdlib" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece" +dependencies = [ + "alloc-no-stdlib", +] + +[[package]] +name = "arc-swap" +version = "1.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69f7f8c3906b62b754cd5326047894316021dcfe5a194c8ea52bdd94934a3457" + +[[package]] +name = "autocfg" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" + +[[package]] +name = "awc" +version = "3.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c170039c11c7f6c0a28f7b3bd4fb0c674cbfa317fabc1560022ad3ec2d69e7c" +dependencies = [ + "actix-codec", + "actix-http", + "actix-rt", + "actix-service", + "actix-tls", + "actix-utils", + "base64 0.22.1", + "bytes", + "cfg-if", + "cookie", + "derive_more", + "futures-core", + "futures-util", + "h2", + "http 0.2.12", + "itoa", + "log", + "mime", + "percent-encoding", + "pin-project-lite", + "rand 0.9.2", + "serde", + "serde_json", + "serde_urlencoded", + "tokio", +] + +[[package]] +name = "base64" +version = "0.21.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bitflags" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "brotli" +version = "8.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bd8b9603c7aa97359dbd97ecf258968c95f3adddd6db2f7e7a5bef101c84560" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + +[[package]] +name = "brotli-decompressor" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "874bb8112abecc98cbd6d81ea4fa7e94fb9449648c93cc89aa40c81c24d7de03" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + +[[package]] +name = "bumpalo" +version = "3.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a" + +[[package]] +name = "bytestring" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "113b4343b5f6617e7ad401ced8de3cc8b012e73a594347c307b90db3e9271289" +dependencies = [ + "bytes", +] + +[[package]] +name = "cc" +version = "1.2.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37521ac7aabe3d13122dc382493e20c9416f299d2ccd5b3a5340a2570cdeb0f3" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", +] + +[[package]] +name = "cookie" +version = "0.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e859cd57d0710d9e06c381b550c06e76992472a8c6d527aecd2fc673dcc231fb" +dependencies = [ + "percent-encoding", + "time", + "version_check", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" + +[[package]] +name = "crypto-common" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "typenum", +] + +[[package]] +name = "csv" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52cd9d68cf7efc6ddfaaee42e7288d3a99d613d4b50f76ce9827ae0c6e14f938" +dependencies = [ + "csv-core", + "itoa", + "ryu", + "serde_core", +] + +[[package]] +name = "csv-core" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "704a3c26996a80471189265814dbc2c257598b96b8a7feae2d31ace646bb9782" +dependencies = [ + "memchr", +] + +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher", +] + +[[package]] +name = "deranged" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ececcb659e7ba858fb4f10388c250a7252eb0a27373f1a72b8748afdd248e587" +dependencies = [ + "powerfmt", +] + +[[package]] +name = "derive_more" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "093242cf7570c207c83073cf82f79706fe7b8317e98620a47d5be7c3d8497678" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bda628edc44c4bb645fbe0f758797143e4e07926f7ebf4e9bdfbd3d2ce621df3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.109", + "unicode-xid", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "dirs" +version = "5.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.48.0", +] + +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.109", +] + +[[package]] +name = "either" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" + +[[package]] +name = "encoding_rs" +version = "0.8.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "find-msvc-tools" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52051878f80a721bb68ebfbc930e07b65ba72f2da88968ea5c06fd6ca3d3a127" + +[[package]] +name = "flate2" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfe33edd8e85a12a67454e37f8c75e730830d83e313556ab9ebf9ee7fbeb3bfb" +dependencies = [ + "crc32fast", + "miniz_oxide", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-core" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" + +[[package]] +name = "futures-sink" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7" + +[[package]] +name = "futures-task" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988" + +[[package]] +name = "futures-util" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" +dependencies = [ + "futures-core", + "futures-sink", + "futures-task", + "pin-project-lite", + "pin-utils", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bb6743198531e02858aeaea5398fcc883e71851fcbcb5a2f773e2fb6cb1edf2" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "wasip2", +] + +[[package]] +name = "ghash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +dependencies = [ + "opaque-debug", + "polyval", +] + +[[package]] +name = "h2" +version = "0.3.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0beca50380b1fc32983fc1cb4587bfa4bb9e78fc259aad4a0032d2080309222d" +dependencies = [ + "bytes", + "fnv", + "futures-core", + "futures-sink", + "futures-util", + "http 0.2.12", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5419bdc4f6a9207fbeba6d11b604d481addf78ecd10c11ad51e76c2f6482748d" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "http" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + +[[package]] +name = "http" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4a85d31aea989eead29a3aaf9e1115a180df8282431156e533de47660892565" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "icu_collections" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" +dependencies = [ + "displaydoc", + "potential_utf", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" + +[[package]] +name = "icu_properties" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e93fcd3157766c0c8da2f8cff6ce651a31f0810eaa1c51ec363ef790bbb5fb99" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02845b3647bb045f1100ecd6480ff52f34c35f82d9880e029d329c21d1054899" + +[[package]] +name = "icu_provider" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d20d6b07bfbc108882d88ed8e37d39636dcc260e15e30c45e6ba089610b917c" +dependencies = [ + "unicode-bidi", + "unicode-normalization", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "if_chain" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd62e6b5e86ea8eeeb8db1de02880a6abc01a397b2ebb64b5d74ac255318f5cb" + +[[package]] +name = "impl-more" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8a5a9a0ff0086c7a148acb942baaabeadf9504d10400b5a05645853729b9cd2" + +[[package]] +name = "indexmap" +version = "2.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6717a8d2a5a929a1a2eb43a12812498ed141a0bcfb7e8f7844fbdbe4303bba9f" +dependencies = [ + "equivalent", + "hashbrown", + "serde", + "serde_core", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" + +[[package]] +name = "jobserver" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33" +dependencies = [ + "getrandom 0.3.4", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.82" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b011eec8cc36da2aab2d5cff675ec18454fad408585853910a202391cf9f8e65" +dependencies = [ + "once_cell", + "wasm-bindgen", +] + +[[package]] +name = "jsonwebtoken" +version = "9.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a87cc7a48537badeae96744432de36f4be2b4a34a05a5ef32e9dd8a1c169dde" +dependencies = [ + "base64 0.22.1", + "js-sys", + "pem", + "ring", + "serde", + "serde_json", + "simple_asn1", +] + +[[package]] +name = "language-tags" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4345964bb142484797b161f473a503a434de77149dd8c7427788c6e13379388" + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "libc" +version = "0.2.177" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2874a2af47a2325c2001a6e6fad9b16a53b802102b528163885171cf92b15976" + +[[package]] +name = "libredox" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "416f7e718bdb06000964960ffa43b4335ad4012ae8b99060261aa4a8088d5ccb" +dependencies = [ + "bitflags", + "libc", +] + +[[package]] +name = "litemap" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77" + +[[package]] +name = "local-channel" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6cbc85e69b8df4b8bb8b89ec634e7189099cea8927a276b7384ce5488e53ec8" +dependencies = [ + "futures-core", + "futures-sink", + "local-waker", +] + +[[package]] +name = "local-waker" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d873d7c67ce09b42110d801813efbc9364414e356be9935700d368351657487" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432" + +[[package]] +name = "memchr" +version = "2.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69d83b0086dc8ecf3ce9ae2874b2d1290252e2a30720bea58a5c6639b0092873" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "ntapi" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8a3895c6391c39d7fe7ebc444a87eb2991b2a0bc718fdabd071eec617fc68e4" +dependencies = [ + "winapi", +] + +[[package]] +name = "num-bigint" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" + +[[package]] +name = "num-integer" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" + +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "pem" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +dependencies = [ + "base64 0.22.1", + "serde_core", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "pkg-config" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" + +[[package]] +name = "polyval" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +dependencies = [ + "cfg-if", + "cpufeatures", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "potential_utf" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn 1.0.109", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] + +[[package]] +name = "proc-macro2" +version = "1.0.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ee95bc4ef87b8d5ba32e8b7714ccc834865276eab0aed5c9958d00ec45f49e8" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.41" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce25767e7b499d1b604768e7cde645d14cc8584231ea6b295e9c9eb22c02e1d1" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.3", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.3", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.16", +] + +[[package]] +name = "rand_core" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rayon" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "368f01d005bf8fd9b1206fb6fa653e6c4a81ceb1466406b81792d87c5677a58f" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "redox_users" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" +dependencies = [ + "getrandom 0.2.16", + "libredox", + "thiserror 1.0.69", +] + +[[package]] +name = "regex" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843bc0191f75f3e22651ae5f1e72939ab2f72a4bc30fa80a066bd66edefc24d4" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5276caf25ac86c8d810222b3dbb938e512c55c6831a10f3e6ed1c93b84041f1c" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-lite" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d942b98df5e658f56f20d592c7f868833fe38115e65c33003d8cd224b0155da" + +[[package]] +name = "regex-syntax" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.16", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rust-embed" +version = "8.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "947d7f3fad52b283d261c4c99a084937e2fe492248cb9a68a8435a861b8798ca" +dependencies = [ + "rust-embed-impl", + "rust-embed-utils", + "walkdir", +] + +[[package]] +name = "rust-embed-impl" +version = "8.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fa2c8c9e8711e10f9c4fd2d64317ef13feaab820a4c51541f1a8c8e2e851ab2" +dependencies = [ + "proc-macro2", + "quote", + "rust-embed-utils", + "shellexpand", + "syn 2.0.109", + "walkdir", +] + +[[package]] +name = "rust-embed-utils" +version = "8.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60b161f275cb337fe0a44d924a5f4df0ed69c2c39519858f931ce61c779d3475" +dependencies = [ + "sha2", + "walkdir", +] + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "ryu" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.109", +] + +[[package]] +name = "serde_html_form" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2f2d7ff8a2140333718bb329f5c40fc5f0865b84c426183ce14c97d2ab8154f" +dependencies = [ + "form_urlencoded", + "indexmap", + "itoa", + "ryu", + "serde_core", +] + +[[package]] +name = "serde_json" +version = "1.0.145" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c" +dependencies = [ + "itoa", + "memchr", + "ryu", + "serde", + "serde_core", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha1" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shellexpand" +version = "3.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b1fdf65dd6331831494dd616b30351c38e96e45921a27745cf98490458b90bb" +dependencies = [ + "dirs", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "signal-hook-registry" +version = "1.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a4719bff48cee6b39d12c020eeb490953ad2443b7055bd0b21fca26bd8c28b" +dependencies = [ + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d66dc143e6b11c1eddc06d5c423cfc97062865baf299914ab64caa38182078fe" + +[[package]] +name = "simple_asn1" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "297f631f50729c8c99b84667867963997ec0b50f32b2a7dbcab828ef0541e8bb" +dependencies = [ + "num-bigint", + "num-traits", + "thiserror 2.0.17", + "time", +] + +[[package]] +name = "slab" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589" + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + +[[package]] +name = "socket2" +version = "0.5.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + +[[package]] +name = "socket2" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17129e116933cf371d018bb80ae557e889637989d8638274fb25622827b03881" +dependencies = [ + "libc", + "windows-sys 0.60.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f17c7e013e88258aa9543dcbe81aca68a667a9ac37cd69c9fbc07858bfe0e2f" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.109", +] + +[[package]] +name = "sysinfo" +version = "0.30.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a5b4ddaee55fb2bea2bf0e5000747e5f5c0de765e5a5ff87f4cd106439f4bb3" +dependencies = [ + "cfg-if", + "core-foundation-sys", + "libc", + "ntapi", + "once_cell", + "rayon", + "windows", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f63587ca0f12b72a0600bcba1d40081f830876000bb46dd2337a3051618f4fc8" +dependencies = [ + "thiserror-impl 2.0.17", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.109", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.109", +] + +[[package]] +name = "time" +version = "0.3.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e7d9e3bb61134e77bde20dd4825b97c010155709965fedf0f49bb138e52a9d" +dependencies = [ + "deranged", + "itoa", + "num-conv", + "powerfmt", + "serde", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40868e7c1d2f0b8d73e4a8c7f0ff63af4f6d19be117e90bd73eb1d62cf831c6b" + +[[package]] +name = "time-macros" +version = "0.2.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30cfb0125f12d9c277f35663a0a33f8c30190f4e4574868a330595412d34ebf3" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa5fdc3bce6191a1dbc8c02d5c8bffcf557bafa17c124c5264a458f1b0613fa" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff360e02eab121e0bc37a2d3b4d4dc622e6eda3a8e5253d5435ecf5bd4c68408" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2 0.6.1", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.109", +] + +[[package]] +name = "tokio-stream" +version = "0.1.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eca58d7bba4a75707817a2c44174253f9236b2d5fbd055602e9d5c07c139a047" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2efa149fe76073d6e8fd97ef4f4eca7b67f599660115591483572e406e165594" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tracing" +version = "0.1.41" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "784e0ac535deb450455cbfa28a6f0df145ea1bb7ae51b821cf5e7927fdcfbdd0" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81383ab64e72a7a8b8e13130c49e3dab29def6d0c7d76a03087b3cf71c5c6903" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.109", +] + +[[package]] +name = "tracing-core" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d12581f227e93f094d3af2ae690a574abb8a2b9b7a96e7cfe9647b2b617678" +dependencies = [ + "once_cell", +] + +[[package]] +name = "typenum" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb" + +[[package]] +name = "unicase" +version = "2.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b844d17643ee918803943289730bec8aac480150456169e647ed0b576ba539" + +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + +[[package]] +name = "unicode-ident" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5" + +[[package]] +name = "unicode-normalization" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08bc136a29a3d1758e07a9cca267be308aeebf5cfd5a10f3f67ab2097683ef5b" +dependencies = [ + "form_urlencoded", + "idna 1.1.0", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "utoipa" +version = "4.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5afb1a60e207dca502682537fefcfd9921e71d0b83e9576060f09abc6efab23" +dependencies = [ + "indexmap", + "serde", + "serde_json", + "utoipa-gen", +] + +[[package]] +name = "utoipa-gen" +version = "4.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20c24e8ab68ff9ee746aad22d39b5535601e6416d1b0feeabf78be986a5c4392" +dependencies = [ + "proc-macro-error", + "proc-macro2", + "quote", + "regex", + "syn 2.0.109", +] + +[[package]] +name = "utoipa-swagger-ui" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "154517adf0d0b6e22e8e1f385628f14fcaa3db43531dc74303d3edef89d6dfe5" +dependencies = [ + "actix-web", + "mime_guess", + "regex", + "rust-embed", + "serde", + "serde_json", + "utoipa", + "zip", +] + +[[package]] +name = "uuid" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f87b8aa10b915a06587d0dec516c282ff295b475d94abf425d62b57710070a2" +dependencies = [ + "getrandom 0.3.4", + "js-sys", + "serde", + "wasm-bindgen", +] + +[[package]] +name = "validator" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b92f40481c04ff1f4f61f304d61793c7b56ff76ac1469f1beb199b1445b253bd" +dependencies = [ + "idna 0.4.0", + "lazy_static", + "regex", + "serde", + "serde_derive", + "serde_json", + "url", + "validator_derive", +] + +[[package]] +name = "validator_derive" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc44ca3088bb3ba384d9aecf40c6a23a676ce23e09bdaca2073d99c207f864af" +dependencies = [ + "if_chain", + "lazy_static", + "proc-macro-error", + "proc-macro2", + "quote", + "regex", + "syn 1.0.109", + "validator_types", +] + +[[package]] +name = "validator_types" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "111abfe30072511849c5910134e8baf8dc05de4c0e5903d681cbd5c9c4d611e3" +dependencies = [ + "proc-macro2", + "syn 1.0.109", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.1+wasi-0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da95793dfc411fbbd93f5be7715b0578ec61fe87cb1a42b12eb625caa5c5ea60" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04264334509e04a7bf8690f2384ef5265f05143a4bff3889ab7a3269adab59c2" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "420bc339d9f322e562942d52e115d57e950d12d88983a14c79b86859ee6c7ebc" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.109", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76f218a38c84bcb33c25ec7059b07847d465ce0e0a76b995e134a45adcb6af76" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e48a53791691ab099e5e2ad123536d0fff50652600abaf43bbf952894110d0be" +dependencies = [ + "windows-core", + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-core" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + +[[package]] +name = "wit-bindgen" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" + +[[package]] +name = "writeable" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9" + +[[package]] +name = "yoke" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.109", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0894878a5fa3edfd6da3f88c4805f4c8558e2b996227a3d864f47fe11e38282c" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88d2b8d9c68ad2b9e4340d7832716a4d21a22a1154777ad56ea55c51a9cf3831" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.109", +] + +[[package]] +name = "zerofrom" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.109", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.109", +] + +[[package]] +name = "zip" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "760394e246e4c28189f19d488c058bf16f564016aefac5d32bb1f3b51d5e9261" +dependencies = [ + "byteorder", + "crc32fast", + "crossbeam-utils", + "flate2", +] + +[[package]] +name = "zstd" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.0.16+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748" +dependencies = [ + "cc", + "pkg-config", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..01d7b8d --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "OllaHubBackend" +version = "0.1.0" +edition = "2021" + +[dependencies] +actix = "0.13.5" +actix-rt = "2.11.0" +actix-web = "4.11.0" +actix-web-actors = "4.3.0" +actix-web-lab = "0.24.3" +awc = "3.8.1" +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +sysinfo = "0.30" +tokio = { version = "1", features = ["sync","rt","macros"] } +aes-gcm = "0.10" +rand = "0.8" +base64 = "0.21" +dirs = "5.0" +uuid = { version = "1", features = ["v4","serde"] } +hex = "0.4" +utoipa = { version = "4", features = ["actix_extras"] } +utoipa-swagger-ui = { version = "4", features = ["actix-web"] } +validator = { version = "0.16", features = ["derive"] } +jsonwebtoken = "9" diff --git a/docs/OLLAMA.md b/docs/OLLAMA.md new file mode 100644 index 0000000..37e56f3 --- /dev/null +++ b/docs/OLLAMA.md @@ -0,0 +1,88 @@ +# Ollama – Verificação, Instalação e Inicialização + +Você quer garantir que o Ollama esteja instalado e rodando sem drama. Este backend expõe dois endpoints para isso: um que verifica o estado atual e outro que instala e inicia o serviço quando necessário. + +Uma linha direta: porta local é `11434`. Se a API responde, tá funcionando. + +## O que os endpoints fazem + +- `GET /ollama/install-check` + - Checa se o binário está no `PATH` + - Lê a versão (`ollama -v`) quando disponível + - Verifica se o serviço está ativo (Linux via `systemctl`; Windows/macOS por processo/API) + - Testa a API local: `/api/version` e `/api/tags` + +- `POST /ollama/install` + - Instala o Ollama conforme seu sistema operacional + - Configura serviço (quando aplicável) + - Inicia e valida a API com polling + - Faz rollback básico se algo falhar (para serviço no Linux) + +## Requisitos mínimos + +- Porta `11434` livre (localhost) +- Rede para baixar pacotes (instalação) +- Permissões adequadas: + - Linux: `systemctl` (para `enable/start`) pode exigir privilégios + - Windows: instalador pode abrir GUI; usamos fallback por `.zip` quando possível + - macOS: se tiver Homebrew, instalamos; caso contrário, baixe manualmente + +### GPU (opcional) +- NVIDIA: bibliotecas CUDA adequadas do pacote do Ollama +- AMD: ROCm (Windows requer pacote adicional) +- CPU-only funciona, só é mais lento + +## Detalhes por sistema + +### Linux +- Instalação oficial via script: + - `curl -fsSL https://ollama.com/install.sh | sh` + - Serviço: `systemctl enable ollama` e `systemctl start ollama` +- Verificação de serviço: `systemctl is-active ollama` +- API local: `http://localhost:11434` +- Ajustes de segurança (se necessário): SELinux/AppArmor + +### Windows +- Preferência: `OllamaSetup.exe` (instala no seu perfil) +- Fallback: pacote `.zip` standalone para `LOCALAPPDATA\Programs\Ollama` +- Início do serviço: `ollama serve` (se não rodando) +- API local: `http://localhost:11434` +- Variáveis de ambiente: defina `OLLAMA_HOST`, `OLLAMA_MODELS` em Configurações do Windows +- Login item: desative em `Task Manager > Startup apps` se não quiser iniciar junto com o sistema + +### macOS +- Se tiver Homebrew: `brew install ollama` +- Senão: baixe o app em https://ollama.com/download/ +- Início do serviço: `ollama serve` se o CLI estiver disponível +- API local: `http://localhost:11434` + +## Erros comuns e soluções + +- Sem permissão para `systemctl` + - Solução: rode com privilégios ou instale para usuário e inicie com `ollama serve` + +- Download bloqueado por proxy/antivírus + - Solução: autorize o binário/endpoint, tente novamente; em último caso, baixe manualmente + +- API inacessível após instalação + - Solução: verifique logs (`systemctl status ollama` no Linux, `%LOCALAPPDATA%\Ollama\server.log` no Windows), confirme porta 11434 livre + +## Exemplos rápidos + +Verificar instalação: + +```bash +curl http://localhost:8080/ollama/install-check +``` + +Instalar e iniciar: + +```bash +curl -X POST http://localhost:8080/ollama/install +``` + +## Observações finais + +- MacOS/Windows costumam registrar Ollama como login item. Desative se preferir. +- Linux: se não usar `systemd`, inicie com `ollama serve` e considere ferramentas alternativas de serviço. +- Se algo quebrar, os logs do endpoint vão apontar a etapa e o erro. Isso ajuda a corrigir rápido. \ No newline at end of file diff --git a/modelList.json b/modelList.json new file mode 100644 index 0000000..e7f6502 --- /dev/null +++ b/modelList.json @@ -0,0 +1,967 @@ +{ + "metadata": { + "source": "ollama.com/library + buscas: uncensored, abliterated, code, reasoning", + "collection_date": "2025-10-29", + "total_models": 270, + "note": "Integração de modelos oficiais + comunitários (uncensored/abliterated variants). Modelos de reasoning incluem variantes com foco em raciocínio (ex: CoT, logical deduction). Duplicatas removidas; métricas atualizadas onde possível. API para lista remota ainda limitada (ver GitHub #8241)." + }, + "models": [ + { + "name": "gpt-oss", + "description": "OpenAI's open-weight models designed for powerful reasoning, agentic tasks, and versatile developer use cases", + "capabilities": ["tools", "thinking", "cloud"], + "parameter_sizes": ["20b", "120b"], + "pulls": "3.8M", + "tags_count": 5, + "last_updated": "2 weeks ago", + "url": "https://ollama.com/library/gpt-oss" + }, + { + "name": "qwen3-vl", + "description": "The most powerful vision-language model in the Qwen model family to date", + "capabilities": ["vision", "cloud"], + "parameter_sizes": ["2b", "4b", "8b", "30b", "32b"], + "pulls": "22.8K", + "tags_count": 49, + "last_updated": "13 minutes ago", + "url": "https://ollama.com/library/qwen3-vl" + }, + { + "name": "deepseek-r1", + "description": "DeepSeek-R1 is a family of open reasoning models with performance approaching that of leading models, such as O3 and Gemini 2.5 Pro", + "capabilities": ["tools", "thinking"], + "parameter_sizes": ["1.5b", "7b", "8b", "14b", "32b", "70b", "671b"], + "pulls": "68.4M", + "tags_count": 35, + "last_updated": "3 months ago", + "url": "https://ollama.com/library/deepseek-r1" + }, + { + "name": "qwen3-coder", + "description": "Alibaba's performant long context models for agentic and coding tasks", + "capabilities": ["tools", "cloud"], + "parameter_sizes": ["30b", "480b"], + "pulls": "575.7K", + "tags_count": 10, + "last_updated": "1 month ago", + "url": "https://ollama.com/library/qwen3-coder" + }, + { + "name": "gemma3", + "description": "The current, most capable model that runs on a single GPU", + "capabilities": ["vision"], + "parameter_sizes": ["270m", "1b", "4b", "12b", "27b"], + "pulls": "23.1M", + "tags_count": 26, + "last_updated": "2 months ago", + "url": "https://ollama.com/library/gemma3" + }, + { + "name": "glm-4.6", + "description": "Advanced agentic, reasoning and coding capabilities", + "capabilities": ["cloud"], + "parameter_sizes": [], + "pulls": "11.8K", + "tags_count": 1, + "last_updated": "2 weeks ago", + "url": "https://ollama.com/library/glm-4.6" + }, + { + "name": "embeddinggemma", + "description": "EmbeddingGemma is a 300M parameter embedding model from Google", + "capabilities": ["embedding"], + "parameter_sizes": ["300m"], + "pulls": "111.2K", + "tags_count": 5, + "last_updated": "1 month ago", + "url": "https://ollama.com/library/embeddinggemma" + }, + { + "name": "qwen3", + "description": "Qwen3 is the latest generation of large language models in Qwen series, offering a comprehensive suite of dense and mixture-of-experts (MoE) models", + "capabilities": ["tools", "thinking"], + "parameter_sizes": ["0.6b", "1.7b", "4b", "8b", "14b", "30b", "32b", "235b"], + "pulls": "11.7M", + "tags_count": 58, + "last_updated": "2 weeks ago", + "url": "https://ollama.com/library/qwen3" + }, + { + "name": "deepseek-v3.1", + "description": "DeepSeek-V3.1-Terminus is a hybrid model that supports both thinking mode and non-thinking mode", + "capabilities": ["tools", "thinking", "cloud"], + "parameter_sizes": ["671b"], + "pulls": "120.6K", + "tags_count": 8, + "last_updated": "1 month ago", + "url": "https://ollama.com/library/deepseek-v3.1" + }, + { + "name": "llama3.1", + "description": "Llama 3.1 is a new state-of-the-art model from Meta available in 8B, 70B and 405B parameter sizes", + "capabilities": ["tools"], + "parameter_sizes": ["8b", "70b", "405b"], + "pulls": "105.1M", + "tags_count": 93, + "last_updated": "11 months ago", + "url": "https://ollama.com/library/llama3.1" + }, + { + "name": "nomic-embed-text", + "description": "A high-performing open embedding model with a large token context window", + "capabilities": ["embedding"], + "parameter_sizes": [], + "pulls": "44.3M", + "tags_count": 3, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/nomic-embed-text" + }, + { + "name": "llama3.2", + "description": "Meta's Llama 3.2 goes small with 1B and 3B models", + "capabilities": ["tools"], + "parameter_sizes": ["1b", "3b"], + "pulls": "42.6M", + "tags_count": 63, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/llama3.2" + }, + { + "name": "mistral", + "description": "The 7B model released by Mistral AI, updated to version 0.3", + "capabilities": ["tools"], + "parameter_sizes": ["7b"], + "pulls": "21.3M", + "tags_count": 84, + "last_updated": "3 months ago", + "url": "https://ollama.com/library/mistral" + }, + { + "name": "qwen2.5", + "description": "Qwen2.5 models are pretrained on Alibaba's latest large-scale dataset, encompassing up to 18 trillion tokens. The model supports up to 128K tokens and has multilingual support", + "capabilities": ["tools"], + "parameter_sizes": ["0.5b", "1.5b", "3b", "7b", "14b", "32b", "72b"], + "pulls": "15.8M", + "tags_count": 133, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/qwen2.5" + }, + { + "name": "phi3", + "description": "Phi-3 is a family of lightweight 3B (Mini) and 14B (Medium) state-of-the-art open models by Microsoft", + "capabilities": [], + "parameter_sizes": ["3.8b", "14b"], + "pulls": "12.5M", + "tags_count": 72, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/phi3" + }, + { + "name": "llama3", + "description": "Meta Llama 3: The most capable openly available LLM to date", + "capabilities": [], + "parameter_sizes": ["8b", "70b"], + "pulls": "11.5M", + "tags_count": 68, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/llama3" + }, + { + "name": "llava", + "description": "LLaVA is a novel end-to-end trained large multimodal model that combines a vision encoder and Vicuna for general-purpose visual and language understanding. Updated to version 1.6", + "capabilities": ["vision"], + "parameter_sizes": ["7b", "13b", "34b"], + "pulls": "11.1M", + "tags_count": 98, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/llava" + }, + { + "name": "gemma2", + "description": "Google Gemma 2 is a high-performing and efficient model available in three sizes: 2B, 9B, and 27B", + "capabilities": [], + "parameter_sizes": ["2b", "9b", "27b"], + "pulls": "8.6M", + "tags_count": 94, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/gemma2" + }, + { + "name": "qwen2.5-coder", + "description": "The latest series of Code-Specific Qwen models, with significant improvements in code generation, code reasoning, and code fixing", + "capabilities": ["tools"], + "parameter_sizes": ["0.5b", "1.5b", "3b", "7b", "14b", "32b"], + "pulls": "7.9M", + "tags_count": 199, + "last_updated": "5 months ago", + "url": "https://ollama.com/library/qwen2.5-coder" + }, + { + "name": "phi4", + "description": "Phi-4 is a 14B parameter, state-of-the-art open model from Microsoft", + "capabilities": [], + "parameter_sizes": ["14b"], + "pulls": "5.8M", + "tags_count": 5, + "last_updated": "9 months ago", + "url": "https://ollama.com/library/phi4" + }, + { + "name": "gemma", + "description": "Gemma is a family of lightweight, state-of-the-art open models built by Google DeepMind. Updated to version 1.1", + "capabilities": [], + "parameter_sizes": ["2b", "7b"], + "pulls": "5.4M", + "tags_count": 102, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/gemma" + }, + { + "name": "mxbai-embed-large", + "description": "State-of-the-art large embedding model from mixedbread.ai", + "capabilities": ["embedding"], + "parameter_sizes": ["335m"], + "pulls": "5.2M", + "tags_count": 4, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/mxbai-embed-large" + }, + { + "name": "qwen", + "description": "Qwen 1.5 is a series of large language models by Alibaba Cloud spanning from 0.5B to 110B parameters", + "capabilities": [], + "parameter_sizes": ["0.5b", "1.8b", "4b", "7b", "14b", "32b", "72b", "110b"], + "pulls": "5M", + "tags_count": 379, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/qwen" + }, + { + "name": "qwen2", + "description": "Qwen2 is a new series of large language models from Alibaba group", + "capabilities": ["tools"], + "parameter_sizes": ["0.5b", "1.5b", "7b", "72b"], + "pulls": "4.4M", + "tags_count": 97, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/qwen2" + }, + { + "name": "llama2", + "description": "Llama 2 is a collection of foundation language models ranging from 7B to 70B parameters", + "capabilities": [], + "parameter_sizes": ["7b", "13b", "70b"], + "pulls": "4.4M", + "tags_count": 102, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/llama2" + }, + { + "name": "minicpm-v", + "description": "A series of multimodal LLMs (MLLMs) designed for vision-language understanding", + "capabilities": ["vision"], + "parameter_sizes": ["8b"], + "pulls": "3.9M", + "tags_count": 17, + "last_updated": "11 months ago", + "url": "https://ollama.com/library/minicpm-v" + }, + { + "name": "dolphin3", + "description": "Dolphin 3.0 Llama 3.1 8B is the next generation of the Dolphin series of instruct-tuned models designed to be the ultimate general purpose local model", + "capabilities": [], + "parameter_sizes": ["8b"], + "pulls": "3.4M", + "tags_count": 5, + "last_updated": "9 months ago", + "url": "https://ollama.com/library/dolphin3" + }, + { + "name": "codellama", + "description": "A large language model that can use text prompts to generate and discuss code", + "capabilities": [], + "parameter_sizes": ["7b", "13b", "34b", "70b"], + "pulls": "3.3M", + "tags_count": 199, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/codellama" + }, + { + "name": "olmo2", + "description": "OLMo 2 is a new family of 7B and 13B models trained on up to 5T tokens", + "capabilities": [], + "parameter_sizes": ["7b", "13b"], + "pulls": "3.3M", + "tags_count": 9, + "last_updated": "9 months ago", + "url": "https://ollama.com/library/olmo2" + }, + { + "name": "tinyllama", + "description": "The TinyLlama project is an open endeavor to train a compact 1.1B Llama model on 3 trillion tokens", + "capabilities": [], + "parameter_sizes": ["1.1b"], + "pulls": "3M", + "tags_count": 36, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/tinyllama" + }, + { + "name": "llama3.2-vision", + "description": "Llama 3.2 Vision is a collection of instruction-tuned image reasoning generative models in 11B and 90B sizes", + "capabilities": ["vision"], + "parameter_sizes": ["11b", "90b"], + "pulls": "2.8M", + "tags_count": 9, + "last_updated": "5 months ago", + "url": "https://ollama.com/library/llama3.2-vision" + }, + { + "name": "mistral-nemo", + "description": "A state-of-the-art 12B model with 128k context length, built by Mistral AI in collaboration with NVIDIA", + "capabilities": ["tools"], + "parameter_sizes": ["12b"], + "pulls": "2.8M", + "tags_count": 17, + "last_updated": "3 months ago", + "url": "https://ollama.com/library/mistral-nemo" + }, + { + "name": "llama3.3", + "description": "New state of the art 70B model. Llama 3.3 70B offers similar performance compared to the Llama 3.1 405B model", + "capabilities": ["tools"], + "parameter_sizes": ["70b"], + "pulls": "2.6M", + "tags_count": 14, + "last_updated": "10 months ago", + "url": "https://ollama.com/library/llama3.3" + }, + { + "name": "deepseek-v3", + "description": "A strong Mixture-of-Experts (MoE) language model with 671B total parameters with 37B activated for each token", + "capabilities": [], + "parameter_sizes": ["671b"], + "pulls": "2.6M", + "tags_count": 5, + "last_updated": "9 months ago", + "url": "https://ollama.com/library/deepseek-v3" + }, + { + "name": "bge-m3", + "description": "BGE-M3 is a new model from BAAI distinguished for its versatility in Multi-Functionality, Multi-Linguality, and Multi-Granularity", + "capabilities": ["embedding"], + "parameter_sizes": ["567m"], + "pulls": "2.6M", + "tags_count": 3, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/bge-m3" + }, + { + "name": "mistral-small", + "description": "Mistral Small 3 sets a new benchmark in the small Large Language Models category below 70B", + "capabilities": ["tools"], + "parameter_sizes": ["22b", "24b"], + "pulls": "2.1M", + "tags_count": 21, + "last_updated": "9 months ago", + "url": "https://ollama.com/library/mistral-small" + }, + { + "name": "smollm2", + "description": "SmolLM2 is a family of compact language models available in three size: 135M, 360M, and 1.7B parameters", + "capabilities": ["tools"], + "parameter_sizes": ["135m", "360m", "1.7b"], + "pulls": "2M", + "tags_count": 49, + "last_updated": "12 months ago", + "url": "https://ollama.com/library/smollm2" + }, + { + "name": "llava-llama3", + "description": "A LLaVA model fine-tuned from Llama 3 Instruct with better scores in several benchmarks", + "capabilities": ["vision"], + "parameter_sizes": ["8b"], + "pulls": "2M", + "tags_count": 4, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/llava-llama3" + }, + { + "name": "all-minilm", + "description": "Embedding models on very large sentence level datasets", + "capabilities": ["embedding"], + "parameter_sizes": ["22m", "33m"], + "pulls": "1.9M", + "tags_count": 10, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/all-minilm" + }, + { + "name": "qwq", + "description": "QwQ is the reasoning model of the Qwen series, focused on advancing AI reasoning capabilities", + "capabilities": ["tools", "thinking"], + "parameter_sizes": ["32b"], + "pulls": "1.7M", + "tags_count": 17, + "last_updated": "7 months ago", + "url": "https://ollama.com/library/qwq" + }, + { + "name": "deepseek-coder", + "description": "DeepSeek Coder is a capable coding model trained on two trillion code and natural language tokens", + "capabilities": ["tools"], + "parameter_sizes": ["1.3b", "6.7b", "33b"], + "pulls": "1.6M", + "tags_count": 102, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/deepseek-coder" + }, + { + "name": "starcoder2", + "description": "StarCoder2 is the next generation of transparently trained open code LLMs that comes in three sizes: 3B, 7B and 15B parameters", + "capabilities": ["tools"], + "parameter_sizes": ["3b", "7b", "15b"], + "pulls": "1.4M", + "tags_count": 67, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/starcoder2" + }, + { + "name": "mixtral", + "description": "A set of Mixture of Experts (MoE) model with open weights by Mistral AI in 8x7b and 8x22b parameter sizes", + "capabilities": ["tools"], + "parameter_sizes": ["8x7b", "8x22b"], + "pulls": "1.4M", + "tags_count": 70, + "last_updated": "10 months ago", + "url": "https://ollama.com/library/mixtral" + }, + { + "name": "llama2-uncensored", + "description": "Uncensored Llama 2 model by George Sung and Jarrad Hope, with support for a 16K context window", + "capabilities": [], + "parameter_sizes": ["7b", "70b"], + "pulls": "1.3M", + "tags_count": 34, + "last_updated": "2 years ago", + "url": "https://ollama.com/library/llama2-uncensored" + }, + { + "name": "codegemma", + "description": "CodeGemma is a collection of powerful, lightweight models that can perform a variety of coding tasks", + "capabilities": ["tools"], + "parameter_sizes": ["2b", "7b"], + "pulls": "1.3M", + "tags_count": 85, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/codegemma" + }, + { + "name": "deepseek-coder-v2", + "description": "An open-source Mixture-of-Experts code language model that achieves performance comparable to GPT4-Turbo in code-specific tasks", + "capabilities": ["tools"], + "parameter_sizes": ["16b", "236b"], + "pulls": "1.2M", + "tags_count": 64, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/deepseek-coder-v2" + }, + { + "name": "falcon3", + "description": "A family of efficient AI models under 10B parameters performant in science, math, and coding through innovative training techniques", + "capabilities": ["tools", "thinking"], + "parameter_sizes": ["1b", "3b", "7b", "10b"], + "pulls": "1M", + "tags_count": 17, + "last_updated": "10 months ago", + "url": "https://ollama.com/library/falcon3" + }, + { + "name": "granite3.1-moe", + "description": "The IBM Granite 1B and 3B models are long-context mixture of experts (MoE) Granite models from IBM designed for low latency usage", + "capabilities": ["tools"], + "parameter_sizes": ["1b", "3b"], + "pulls": "1M", + "tags_count": 33, + "last_updated": "9 months ago", + "url": "https://ollama.com/library/granite3.1-moe" + }, + { + "name": "qwen2.5vl", + "description": "Flagship vision-language model of Qwen and also a significant leap from the previous Qwen2-VL", + "capabilities": ["vision"], + "parameter_sizes": ["3b", "7b", "32b", "72b"], + "pulls": "991K", + "tags_count": 17, + "last_updated": "5 months ago", + "url": "https://ollama.com/library/qwen2.5vl" + }, + { + "name": "snowflake-arctic-embed", + "description": "A suite of text embedding models by Snowflake, optimized for performance", + "capabilities": ["embedding"], + "parameter_sizes": ["22m", "33m", "110m", "137m", "335m"], + "pulls": "951.1K", + "tags_count": 16, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/snowflake-arctic-embed" + }, + { + "name": "orca-mini", + "description": "A general-purpose model ranging from 3 billion parameters to 70 billion, suitable for entry-level hardware", + "capabilities": [], + "parameter_sizes": ["3b", "7b", "13b", "70b"], + "pulls": "930.6K", + "tags_count": 119, + "last_updated": "2 years ago", + "url": "https://ollama.com/library/orca-mini" + }, + { + "name": "llama4", + "description": "Meta's latest collection of multimodal models", + "capabilities": ["vision", "tools"], + "parameter_sizes": ["16x17b", "128x17b"], + "pulls": "751.9K", + "tags_count": 11, + "last_updated": "4 months ago", + "url": "https://ollama.com/library/llama4" + }, + { + "name": "phi", + "description": "Phi-2: a 2.7B language model by Microsoft Research that demonstrates outstanding reasoning and language understanding capabilities", + "capabilities": ["thinking"], + "parameter_sizes": ["2.7b"], + "pulls": "730.7K", + "tags_count": 18, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/phi" + }, + { + "name": "mistral-small3.2", + "description": "An update to Mistral Small that improves on function calling, instruction following, and less repetition errors", + "capabilities": ["vision", "tools"], + "parameter_sizes": ["24b"], + "pulls": "718.3K", + "tags_count": 5, + "last_updated": "4 months ago", + "url": "https://ollama.com/library/mistral-small3.2" + }, + { + "name": "dolphin-mixtral", + "description": "Uncensored, 8x7b and 8x22b fine-tuned models based on the Mixtral mixture of experts models that excels at coding tasks. Created by Eric Hartford", + "capabilities": ["tools"], + "parameter_sizes": ["8x7b", "8x22b"], + "pulls": "716.8K", + "tags_count": 70, + "last_updated": "10 months ago", + "url": "https://ollama.com/library/dolphin-mixtral" + }, + { + "name": "gemma3n", + "description": "Gemma 3n models are designed for efficient execution on everyday devices such as laptops, tablets or phones", + "capabilities": [], + "parameter_sizes": ["e2b", "e4b"], + "pulls": "670.3K", + "tags_count": 9, + "last_updated": "4 months ago", + "url": "https://ollama.com/library/gemma3n" + }, + { + "name": "granite3.3", + "description": "IBM Granite 2B and 8B models are 128K context length language models that have been fine-tuned for improved reasoning and instruction-following capabilities", + "capabilities": ["tools", "thinking"], + "parameter_sizes": ["2b", "8b"], + "pulls": "660.7K", + "tags_count": 3, + "last_updated": "6 months ago", + "url": "https://ollama.com/library/granite3.3" + }, + { + "name": "cogito", + "description": "Cogito v1 Preview is a family of hybrid reasoning models by Deep Cogito that outperform the best available open models of the same size", + "capabilities": ["tools", "thinking"], + "parameter_sizes": ["3b", "8b", "14b", "32b", "70b"], + "pulls": "659K", + "tags_count": 20, + "last_updated": "6 months ago", + "url": "https://ollama.com/library/cogito" + }, + { + "name": "phi4-reasoning", + "description": "Phi 4 reasoning and reasoning plus are 14-billion parameter open-weight reasoning models that rival much larger models on complex reasoning tasks", + "capabilities": ["thinking"], + "parameter_sizes": ["14b"], + "pulls": "625.6K", + "tags_count": 9, + "last_updated": "6 months ago", + "url": "https://ollama.com/library/phi4-reasoning" + }, + { + "name": "openthinker", + "description": "A fully open-source family of reasoning models built using a dataset derived by distilling DeepSeek-R1", + "capabilities": ["thinking"], + "parameter_sizes": ["7b", "32b"], + "pulls": "604.4K", + "tags_count": 15, + "last_updated": "6 months ago", + "url": "https://ollama.com/library/openthinker" + }, + { + "name": "magistral", + "description": "Magistral is a small, efficient reasoning model with 24B parameters, excelling in domain-specific, transparent, and multilingual reasoning", + "capabilities": ["tools", "thinking"], + "parameter_sizes": ["24b"], + "pulls": "583.4K", + "tags_count": 5, + "last_updated": "4 months ago", + "url": "https://ollama.com/library/magistral" + }, + { + "name": "deepscaler", + "description": "A fine-tuned version of Deepseek-R1-Distilled-Qwen-1.5B that surpasses the performance of OpenAI's o1-preview with just 1.5B parameters", + "capabilities": ["thinking"], + "parameter_sizes": ["1.5b"], + "pulls": "573.2K", + "tags_count": 5, + "last_updated": "8 months ago", + "url": "https://ollama.com/library/deepscaler" + }, + { + "name": "codestral", + "description": "Codestral is Mistral AI's first-ever code model designed for code generation tasks", + "capabilities": ["tools"], + "parameter_sizes": ["22b"], + "pulls": "503.9K", + "tags_count": 17, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/codestral" + }, + { + "name": "dolphin-phi", + "description": "2.7B uncensored Dolphin model by Eric Hartford, based on the Phi language model by Microsoft Research", + "capabilities": [], + "parameter_sizes": ["2.7b"], + "pulls": "569.2K", + "tags_count": 15, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/dolphin-phi" + }, + { + "name": "dolphin-mistral", + "description": "The uncensored Dolphin model based on Mistral that excels at coding tasks. Updated to version 2.8", + "capabilities": ["tools"], + "parameter_sizes": ["7b"], + "pulls": "409.3K", + "tags_count": 120, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/dolphin-mistral" + }, + { + "name": "wizard-vicuna-uncensored", + "description": "Wizard Vicuna Uncensored is a 7B, 13B, and 30B parameter model based on Llama 2 uncensored by Eric Hartford", + "capabilities": [], + "parameter_sizes": ["7b", "13b", "30b"], + "pulls": "255.1K", + "tags_count": 49, + "last_updated": "2 years ago", + "url": "https://ollama.com/library/wizard-vicuna-uncensored" + }, + { + "name": "dolphin-starcoder2", + "description": "A 7B and 15B uncensored variant of the Dolphin model family that excels at coding, based on StarCoder2", + "capabilities": ["tools"], + "parameter_sizes": ["7b", "15b"], + "pulls": "113.1K", + "tags_count": 35, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/dolphin-starcoder2" + }, + { + "name": "wizardlm-uncensored", + "description": "Uncensored version of Wizard LM model", + "capabilities": [], + "parameter_sizes": ["7b", "13b"], + "pulls": "89.5K", + "tags_count": 18, + "last_updated": "2 years ago", + "url": "https://ollama.com/library/wizardlm-uncensored" + }, + { + "name": "llama-3.2-3b-instruct-abliterated", + "description": "An uncensored version of the original Llama-3.2-3B-Instruct, created via abliteration", + "capabilities": [], + "parameter_sizes": ["3b"], + "pulls": "508.1K", + "tags_count": 1, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/llama-3.2-3b-instruct-abliterated" + }, + { + "name": "josiefied-qwen3-uncensored", + "description": "Qwen3, but Josiefied and uncensored", + "capabilities": [], + "parameter_sizes": ["7b"], + "pulls": "71.5K", + "tags_count": 47, + "last_updated": "4 months ago", + "url": "https://ollama.com/library/josiefied-qwen3-uncensored" + }, + { + "name": "abliterated-llama3.1-8b", + "description": "Ablitered v3 llama-3.1 8b with uncensored prompt", + "capabilities": [], + "parameter_sizes": ["8b"], + "pulls": "31K", + "tags_count": 38, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/abliterated-llama3.1-8b" + }, + { + "name": "dolphin-uncensored", + "description": "Dolphin is an uncensored multilingual chat tuned model by Eric Hartford, conformant to system prompt, good at coding and various tasks", + "capabilities": ["tools"], + "parameter_sizes": ["8b"], + "pulls": "25.5K", + "tags_count": 15, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/dolphin-uncensored" + }, + { + "name": "specialized-uncensored-openai-20b", + "description": "Specialized uncensored/abliterated quants for new OpenAI 20B MOE - Mixture of Experts Model at 80+ T/S (quantized Q5_1)", + "capabilities": ["tools"], + "parameter_sizes": ["20b"], + "pulls": "22.9K", + "tags_count": 1, + "last_updated": "1 month ago", + "url": "https://ollama.com/library/specialized-uncensored-openai-20b" + }, + { + "name": "lexi-uncensored", + "description": "Lexi is uncensored, which makes the model compliant. You are advised to implement your own alignment layer before exposing the model as a service", + "capabilities": [], + "parameter_sizes": ["7b"], + "pulls": "15.3K", + "tags_count": 9, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/lexi-uncensored" + }, + { + "name": "llama3-uncensored", + "description": "Uncensored version of Llama3 8b", + "capabilities": [], + "parameter_sizes": ["8b"], + "pulls": "13.6K", + "tags_count": 1, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/llama3-uncensored" + }, + { + "name": "llama3-uncensored-long", + "description": "This model was created with the goal for a good llama 3 uncencored model with long context", + "capabilities": [], + "parameter_sizes": ["8b"], + "pulls": "13.5K", + "tags_count": 4, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/llama3-uncensored-long" + }, + { + "name": "deepseek-r1-distilled", + "description": "DeepSeek's first generation reasoning models with comparable performance to OpenAI-o1", + "capabilities": ["thinking"], + "parameter_sizes": ["7b"], + "pulls": "586.4K", + "tags_count": 55, + "last_updated": "5 months ago", + "url": "https://ollama.com/library/deepseek-r1-distilled" + }, + { + "name": "llama-3.2-11b-vision-abliterated", + "description": "From huihui-ai/Llama-3.2-11B-Vision-Instruct-abliterated", + "capabilities": ["vision"], + "parameter_sizes": ["11b"], + "pulls": "69.8K", + "tags_count": 2, + "last_updated": "8 months ago", + "url": "https://ollama.com/library/llama-3.2-11b-vision-abliterated" + }, + { + "name": "qwen2.5-1m", + "description": "Qwen2.5-1M is the long-context version of the Qwen2.5 series models, supporting a context length of up to 1M tokens", + "capabilities": [], + "parameter_sizes": ["7b"], + "pulls": "31K", + "tags_count": 11, + "last_updated": "9 months ago", + "url": "https://ollama.com/library/qwen2.5-1m" + }, + { + "name": "qwen3-abliterated", + "description": "This is the abliterated version of Qwen3, which is the latest generation of large language models in Qwen series", + "capabilities": [], + "parameter_sizes": ["7b"], + "pulls": "23.9K", + "tags_count": 6, + "last_updated": "5 months ago", + "url": "https://ollama.com/library/qwen3-abliterated" + }, + { + "name": "dolphin-3.0-llama3.1-8b-abliterated", + "description": "Dolphin 3.0 Llama 3.1 8B is the next generation of the Dolphin series of instruct-tuned models designed to be the ultimate general purpose local model", + "capabilities": [], + "parameter_sizes": ["8b"], + "pulls": "21.7K", + "tags_count": 5, + "last_updated": "9 months ago", + "url": "https://ollama.com/library/dolphin-3.0-llama3.1-8b-abliterated" + }, + { + "name": "gemma-3n-abliterated", + "description": "This is an uncensored version of google/gemma-3n created with abliteration", + "capabilities": [], + "parameter_sizes": ["9b"], + "pulls": "13.4K", + "tags_count": 2, + "last_updated": "3 months ago", + "url": "https://ollama.com/library/gemma-3n-abliterated" + }, + { + "name": "neuraldaredevil-8b-abliterated", + "description": "Contains fp16 version of the excellent NeuralDaredevil-8B-abliterated", + "capabilities": [], + "parameter_sizes": ["8b"], + "pulls": "9,677", + "tags_count": 1, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/neuraldaredevil-8b-abliterated" + }, + { + "name": "mlabonne-neuraldaredevil-8b-abliterated", + "description": "mlabonne/NeuralDaredevil-8B-abliterated", + "capabilities": [], + "parameter_sizes": ["8b"], + "pulls": "7,679", + "tags_count": 4, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/mlabonne-neuraldaredevil-8b-abliterated" + }, + { + "name": "phi3-medium-abliterated", + "description": "This is a phi3 medium model that has had the prompt rejection neurons snipped which is better than fine tuning", + "capabilities": [], + "parameter_sizes": ["14b"], + "pulls": "6,591", + "tags_count": 1, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/phi3-medium-abliterated" + }, + { + "name": "gemma2-9b-abliterated", + "description": "Abliterated version of Google's Gemma 2 9B", + "capabilities": [], + "parameter_sizes": ["9b"], + "pulls": "6,386", + "tags_count": 1, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/gemma2-9b-abliterated" + }, + { + "name": "codeqwen1.5", + "description": "CodeQwen1.5 is a large language model pretrained on a large amount of code data", + "capabilities": ["tools"], + "parameter_sizes": ["7b"], + "pulls": "182K", + "tags_count": 30, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/codeqwen1.5" + }, + { + "name": "deepcoder", + "description": "DeepCoder is a fully open-Source 14B coder model at O3-mini level, with a 1.5B version also available", + "capabilities": ["tools"], + "parameter_sizes": ["1.5b", "14b"], + "pulls": "352.4K", + "tags_count": 9, + "last_updated": "6 months ago", + "url": "https://ollama.com/library/deepcoder" + }, + { + "name": "granite-code", + "description": "A family of open foundation models by IBM for Code Intelligence", + "capabilities": ["tools"], + "parameter_sizes": ["8b", "20b", "34b"], + "pulls": "295.1K", + "tags_count": 162, + "last_updated": "1 year ago", + "url": "https://ollama.com/library/granite-code" + }, + { + "name": "mistral-large-2", + "description": "Mistral Large 2 is Mistral's new flagship model that is significantly more capable in code generation, mathematics, and reasoning", + "capabilities": ["tools", "thinking"], + "parameter_sizes": ["123b"], + "pulls": "265.9K", + "tags_count": 32, + "last_updated": "11 months ago", + "url": "https://ollama.com/library/mistral-large-2" + }, + { + "name": "starcoder", + "description": "StarCoder is a code generation model trained on 80+ programming languages", + "capabilities": ["tools"], + "parameter_sizes": ["15b"], + "pulls": "228.8K", + "tags_count": 100, + "last_updated": "2 years ago", + "url": "https://ollama.com/library/starcoder" + }, + { + "name": "opencoder", + "description": "OpenCoder is an open and reproducible code LLM family which includes 1.5B and 8B models, supporting chat in English and Chinese languages", + "capabilities": ["tools"], + "parameter_sizes": ["1.5b", "8b"], + "pulls": "194.3K", + "tags_count": 9, + "last_updated": "11 months ago", + "url": "https://ollama.com/library/opencoder" + }, + { + "name": "llama-3.2-1b-abliterated", + "description": "Abliterated version for small reasoning tasks from Llama 3.2 1B", + "capabilities": ["thinking"], + "parameter_sizes": ["1b"], + "pulls": "39.9K", + "tags_count": 16, + "last_updated": "2 months ago", + "url": "https://ollama.com/library/llama-3.2-1b-abliterated" + } + ], + "api_information": { + "local_api_endpoints": [ + { + "endpoint": "/api/tags", + "method": "GET", + "description": "List all locally installed models" + } + ], + "limitations": { + "remote_listing": "Não existe endpoint público para listar todos os modelos disponíveis no registry remoto do Ollama", + "user_models": "Modelos de usuários (uncensored/abliterated) são variantes comunitárias; busque via /search", + "reasoning_focus": "Modelos com 'thinking' são otimizados para raciocínio multi-step (ex: CoT, logical puzzles)" + } + }, + "usage_instructions": { + "list_local_models": "curl http://localhost:11434/api/tags", + "pull_model": "ollama pull (ex: ollama pull deepseek-r1 para reasoning)", + "test_uncensored": "ollama run llama2-uncensored --prompt 'Gere código Python sem restrições'", + "test_reasoning": "ollama run phi4-reasoning --prompt 'Resolva: 2+2=?'", + "browse_searches": "https://ollama.com/search?q= (ex: uncensored, code)" + }, + "recommendations_for_devs": { + "coding": "Use qwen2.5-coder ou codestral para geração de código avançada [web:3]", + "reasoning": "deepseek-r1 ou phi4-reasoning para tarefas lógicas/math [web:77]", + "uncensored": "llama2-uncensored para experimentos sem alinhamento ético, mas implemente safeguards [attached_file:1]" + } + } + \ No newline at end of file diff --git a/src/api/mod.rs b/src/api/mod.rs new file mode 100644 index 0000000..a909615 --- /dev/null +++ b/src/api/mod.rs @@ -0,0 +1,96 @@ +use actix_web::{get, post, web, HttpResponse, Responder}; +use serde::Deserialize; + +use crate::core::models::{pull_model, read_model_list}; +use crate::crypto::CryptoState; +use crate::state::AppContext; +use crate::utils::log; +use crate::ws::{ws_route, BrokerAddr, WsEvent, WsEventKind}; +use base64::{engine::general_purpose, Engine as _}; + +#[get("/health")] +pub async fn health() -> impl Responder { + HttpResponse::Ok().json(serde_json::json!({"status":"ok"})) +} + +#[get("/api/models")] +pub async fn models_list(state: web::Data) -> impl Responder { + match read_model_list(&state.model_list_path) { + Ok(list) => HttpResponse::Ok().json(list), + Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), + } +} + +#[derive(Deserialize)] +pub struct InstallReq { + pub name: String, +} + +#[post("/api/models/install")] +pub async fn models_install(state: web::Data, payload: web::Json) -> impl Responder { + let name = payload.name.clone(); + let tx = state.broker.clone(); + let base = state.ollama_base_url.clone(); + let value = name.clone(); + actix_rt::spawn(async move { + let _ = pull_model(&base, &value, &tx).await; + }); + HttpResponse::Accepted().json(serde_json::json!({"status":"started","model":name})) +} + +#[derive(Deserialize)] +pub struct SetKeyReq { pub hex_key: String } + +#[post("/api/crypto/set-key")] +pub async fn crypto_set_key(state: web::Data, payload: web::Json) -> impl Responder { + match state.crypto.set_key_hex(&payload.hex_key) { + Ok(()) => HttpResponse::Ok().json(serde_json::json!({"status":"ok"})), + Err(e) => HttpResponse::BadRequest().json(serde_json::json!({"error": e})), + } +} + +#[post("/api/crypto/rotate-key")] +pub async fn crypto_rotate_key(state: web::Data) -> impl Responder { + match state.crypto.rotate_key() { + Ok(hex) => HttpResponse::Ok().json(serde_json::json!({"key": hex})), + Err(e) => HttpResponse::InternalServerError().json(serde_json::json!({"error": e})), + } +} + +#[derive(Deserialize)] +pub struct CryptReq { pub data: String } + +#[post("/api/crypto/encrypt")] +pub async fn crypto_encrypt(state: web::Data, payload: web::Json) -> impl Responder { + match state.crypto.encrypt(payload.data.as_bytes()) { + Ok(ct) => HttpResponse::Ok().json(serde_json::json!({"ciphertext": general_purpose::STANDARD.encode(ct)})), + Err(e) => HttpResponse::BadRequest().json(serde_json::json!({"error": e})), + } +} + +#[post("/api/crypto/decrypt")] +pub async fn crypto_decrypt(state: web::Data, payload: web::Json) -> impl Responder { + match general_purpose::STANDARD.decode(&payload.data) { + Ok(bytes) => match state.crypto.decrypt(&bytes) { + Ok(pt) => HttpResponse::Ok().json(serde_json::json!({"plaintext": String::from_utf8_lossy(&pt)})), + Err(e) => HttpResponse::BadRequest().json(serde_json::json!({"error": e})), + }, + Err(e) => HttpResponse::BadRequest().json(serde_json::json!({"error": format!("base64 decode: {}", e)})), + } +} + +pub fn configure(cfg: &mut web::ServiceConfig, state: web::Data) { + cfg.app_data(state); + cfg.service(health); + cfg.service(models_list); + cfg.service(models_install); + cfg.service(crypto_set_key); + cfg.service(crypto_rotate_key); + cfg.service(crypto_encrypt); + cfg.service(crypto_decrypt); +} + +pub fn ws_config(cfg: &mut web::ServiceConfig, broker: actix_web::web::Data) { + cfg.app_data(broker); + cfg.service(ws_route); +} \ No newline at end of file diff --git a/src/controllers/mod.rs b/src/controllers/mod.rs new file mode 100644 index 0000000..c28e67f --- /dev/null +++ b/src/controllers/mod.rs @@ -0,0 +1 @@ +pub mod user_controller; \ No newline at end of file diff --git a/src/controllers/user_controller.rs b/src/controllers/user_controller.rs new file mode 100644 index 0000000..45dc811 --- /dev/null +++ b/src/controllers/user_controller.rs @@ -0,0 +1,92 @@ +use actix_web::{get, post, put, delete, web, HttpResponse, Responder}; +use utoipa::{IntoParams, ToSchema}; +use serde::Deserialize; +use validator::Validate; + +use crate::middlewares::error::ApiError; +use crate::models::user::{CreateUserRequest, UpdateUserRequest, User}; +use crate::services::user_service::UserService; + +#[derive(Deserialize, IntoParams, ToSchema)] +pub struct UserPath { pub id: String } + +#[utoipa::path( + get, + path = "/api/v1/users", + responses( + (status = 200, description = "Lista de usuários", body = [User]) + ) +)] +#[get("/api/v1/users")] +pub async fn list_users(svc: web::Data>) -> impl Responder { + HttpResponse::Ok().json(svc.list()) +} + +#[utoipa::path( + get, + path = "/api/v1/users/{id}", + params(UserPath), + responses( + (status = 200, description = "Usuário encontrado", body = User), + (status = 404, description = "Não encontrado", body = crate::middlewares::error::ApiErrorBody) + ) +)] +#[get("/api/v1/users/{id}")] +pub async fn get_user(path: web::Path, svc: web::Data>) -> Result { + match svc.get(path.id.clone()) { + Some(u) => Ok(HttpResponse::Ok().json(u)), + None => Err(ApiError::NotFound("Usuário não encontrado".into())), + } +} + +#[utoipa::path( + post, + path = "/api/v1/users", + request_body = CreateUserRequest, + responses( + (status = 201, description = "Usuário criado", body = User), + (status = 400, description = "Erro de validação", body = crate::middlewares::error::ApiErrorBody) + ) +)] +#[post("/api/v1/users")] +pub async fn create_user(payload: web::Json, svc: web::Data>) -> Result { + let mut req = payload.into_inner(); + if let Err(e) = req.validate() { return Err(ApiError::BadRequest(format!("validação: {}", e))); } + let user = svc.create(req); + Ok(HttpResponse::Created().json(user)) +} + +#[utoipa::path( + put, + path = "/api/v1/users/{id}", + params(UserPath), + request_body = UpdateUserRequest, + responses( + (status = 200, description = "Usuário atualizado", body = User), + (status = 400, description = "Erro de validação", body = crate::middlewares::error::ApiErrorBody), + (status = 404, description = "Não encontrado", body = crate::middlewares::error::ApiErrorBody) + ) +)] +#[put("/api/v1/users/{id}")] +pub async fn update_user(path: web::Path, payload: web::Json, svc: web::Data>) -> Result { + let mut req = payload.into_inner(); + if let Err(e) = req.validate() { return Err(ApiError::BadRequest(format!("validação: {}", e))); } + match svc.update(path.id.clone(), req) { + Some(u) => Ok(HttpResponse::Ok().json(u)), + None => Err(ApiError::NotFound("Usuário não encontrado".into())), + } +} + +#[utoipa::path( + delete, + path = "/api/v1/users/{id}", + params(UserPath), + responses( + (status = 204, description = "Usuário deletado"), + (status = 404, description = "Não encontrado", body = crate::middlewares::error::ApiErrorBody) + ) +)] +#[delete("/api/v1/users/{id}")] +pub async fn delete_user(path: web::Path, svc: web::Data>) -> Result { + if svc.delete(path.id.clone()) { Ok(HttpResponse::NoContent().finish()) } else { Err(ApiError::NotFound("Usuário não encontrado".into())) } +} \ No newline at end of file diff --git a/src/core/mod.rs b/src/core/mod.rs new file mode 100644 index 0000000..ff92946 --- /dev/null +++ b/src/core/mod.rs @@ -0,0 +1 @@ +pub mod models; \ No newline at end of file diff --git a/src/core/models.rs b/src/core/models.rs new file mode 100644 index 0000000..020712e --- /dev/null +++ b/src/core/models.rs @@ -0,0 +1,61 @@ +use std::fs; +use std::path::Path; + +use actix_web::http::header::USER_AGENT; +use awc::Client; +use serde::{Deserialize, Serialize}; + +use crate::utils::log; +use crate::ws::{WsEvent, WsEventKind}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ModelInfo { + pub name: String, + pub description: Option, +} + +pub fn read_model_list(path: &str) -> Result, String> { + let data = fs::read_to_string(path).map_err(|e| e.to_string())?; + let list: Vec = serde_json::from_str(&data).map_err(|e| e.to_string())?; + Ok(list) +} + +pub async fn pull_model( + base_url: &str, + model: &str, + tx: &tokio::sync::broadcast::Sender, +) -> Result<(), String> { + let client = Client::default(); + let url = format!("{}/api/pull", base_url.trim_end_matches('/')); + let body = serde_json::json!({"name": model}); + let mut resp = client + .post(url) + .insert_header((USER_AGENT, "OllaHubBackend/1.0")) + .send_json(&body) + .await + .map_err(|e| e.to_string())?; + + let status = resp.status(); + let bytes = resp + .body() + .await + .map_err(|e| format!("Erro corpo resposta: {}", e))?; + if !status.is_success() { + return Err(format!("Falha ao puxar modelo: {}", status)); + } + let text = String::from_utf8_lossy(&bytes).to_string(); + for line in text.lines() { + tx.send(WsEvent { + kind: WsEventKind::Log, + message: line.to_string(), + }) + .ok(); + } + tx.send(WsEvent { + kind: WsEventKind::Done, + message: format!("Download do modelo '{}' concluído", model), + }) + .ok(); + log::info(&format!("Modelo '{}' baixado com sucesso", model)); + Ok(()) +} \ No newline at end of file diff --git a/src/crypto/mod.rs b/src/crypto/mod.rs new file mode 100644 index 0000000..1484d64 --- /dev/null +++ b/src/crypto/mod.rs @@ -0,0 +1,116 @@ +use aes_gcm::aead::{Aead, KeyInit}; +use aes_gcm::{Aes256Gcm, Nonce}; +use rand::RngCore; +use std::fs; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; + +use crate::utils::log; + +#[derive(Clone)] +pub struct CryptoState { + key: Arc>>, + key_path: PathBuf, +} + +impl CryptoState { + pub fn new(key_path: PathBuf) -> Self { + let state = Self { + key: Arc::new(Mutex::new(None)), + key_path, + }; + state.load_key_from_disk(); + state + } + + fn load_key_from_disk(&self) { + if self.key_path.exists() { + if let Ok(hex) = fs::read_to_string(&self.key_path) { + let hex = hex.trim(); + match hex::decode(hex) { + Ok(bytes) if bytes.len() == 32 => { + let mut arr = [0u8; 32]; + arr.copy_from_slice(&bytes); + *self.key.lock().unwrap() = Some(arr); + log::info("Chave carregada do disco"); + } + _ => log::warn("Arquivo de chave inválido; ignorando"), + } + } + } + } + + pub fn set_key_hex(&self, hex_key: &str) -> Result<(), String> { + let bytes = hex::decode(hex_key).map_err(|e| format!("hex inválido: {}", e))?; + if bytes.len() != 32 { + return Err("Chave deve ter 32 bytes".into()); + } + let mut arr = [0u8; 32]; + arr.copy_from_slice(&bytes); + *self.key.lock().unwrap() = Some(arr); + fs::create_dir_all(self.key_path.parent().unwrap_or_else(|| std::path::Path::new("."))) + .map_err(|e| e.to_string())?; + fs::write(&self.key_path, hex::encode(arr)).map_err(|e| e.to_string())?; + Ok(()) + } + + pub fn rotate_key(&self) -> Result { + let mut new_key = [0u8; 32]; + rand::thread_rng().fill_bytes(&mut new_key); + *self.key.lock().unwrap() = Some(new_key); + fs::create_dir_all(self.key_path.parent().unwrap_or_else(|| std::path::Path::new("."))) + .map_err(|e| e.to_string())?; + let hex = hex::encode(new_key); + fs::write(&self.key_path, &hex).map_err(|e| e.to_string())?; + Ok(hex) + } + + pub fn encrypt(&self, plaintext: &[u8]) -> Result, String> { + let key = self.key.lock().unwrap(); + let key = key.ok_or("Chave não definida")?; + let cipher = Aes256Gcm::new_from_slice(&key).map_err(|e| e.to_string())?; + let mut nonce_bytes = [0u8; 12]; + rand::thread_rng().fill_bytes(&mut nonce_bytes); + let nonce = Nonce::from_slice(&nonce_bytes); + let mut out = Vec::from(nonce_bytes); + let ct = cipher + .encrypt(nonce, plaintext) + .map_err(|e| format!("Erro ao criptografar: {}", e))?; + out.extend_from_slice(&ct); + Ok(out) + } + + pub fn decrypt(&self, ciphertext: &[u8]) -> Result, String> { + if ciphertext.len() < 12 { + return Err("Ciphertext inválido".into()); + } + let (nonce_bytes, ct) = ciphertext.split_at(12); + let key = self.key.lock().unwrap(); + let key = key.ok_or("Chave não definida")?; + let cipher = Aes256Gcm::new_from_slice(&key).map_err(|e| e.to_string())?; + let nonce = Nonce::from_slice(nonce_bytes); + let pt = cipher + .decrypt(nonce, ct) + .map_err(|e| format!("Erro ao descriptografar: {}", e))?; + Ok(pt) + } +} + +#[cfg(test)] +mod tests { + use super::CryptoState; + use std::env; + use std::path::PathBuf; + + #[test] + fn crypto_roundtrip() { + let tmp = env::temp_dir().join("crypto_key_test.hex"); + let crypto = CryptoState::new(PathBuf::from(&tmp)); + crypto.rotate_key().unwrap(); + let msg = b"hello"; + let ct = crypto.encrypt(msg).unwrap(); + let pt = crypto.decrypt(&ct).unwrap(); + assert_eq!(msg.to_vec(), pt); + let _ = std::fs::remove_file(tmp); + } +} \ No newline at end of file diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..231ec67 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,1289 @@ +use std::collections::HashMap; +use std::env; +use std::fs; +use std::path::PathBuf; +use std::process::Command; + +use awc::Client; +use std::time::{Duration, Instant}; +use serde::{Deserialize, Serialize}; +use actix_rt::time::sleep; +use actix_web::{web, App, HttpResponse, HttpServer, Responder}; +use actix_web_actors::ws as actix_ws; +use actix_web::middleware::from_fn; +use utoipa_swagger_ui::SwaggerUi; +use actix::prelude::*; +use tokio::sync::broadcast; +use sysinfo::System; +use uuid::Uuid; +use base64::engine::general_purpose::STANDARD as BASE64; +use base64::Engine; +use aes_gcm::{Aes256Gcm, Key, KeyInit, Nonce}; +use aes_gcm::aead::Aead; +use rand::RngCore; +use dirs::config_dir; + +// Arquitetura modular +mod api; +mod core; +mod crypto; +mod controllers; +mod models; +mod middlewares; +mod services; +mod state; +mod repositories; +mod routes; +mod utils; +mod ws; +use state::AppContext; +use ws::BrokerAddr; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +enum Platform { + Linux { distro: Option }, + Windows, + Macos, + Unknown(String), +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +enum ApiStatus { + Reachable, + Unreachable, + Degraded, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +enum MethodKind { + Native, + Docker, + Api, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct DetectedMethod { + kind: MethodKind, + details: HashMap, +} + +// Estrutura de relatório antigo removida; endpoints HTTP retornam DTOs específicos. + +fn detect_platform() -> Platform { + let os = env::consts::OS; + match os { + "linux" => Platform::Linux { distro: detect_linux_distro() }, + "windows" => Platform::Windows, + "macos" => Platform::Macos, + other => Platform::Unknown(other.to_string()), + } +} + +fn detect_linux_distro() -> Option { + // Tenta ler /etc/os-release e extrair ID + let content = fs::read_to_string("/etc/os-release").ok()?; + for line in content.lines() { + if let Some(stripped) = line.strip_prefix("ID=") { + return Some(stripped.trim_matches('\"').to_string()); + } + } + None +} + +fn path_exists(path: &PathBuf) -> bool { + fs::metadata(path).is_ok() +} + +fn run_cmd(cmd: &str, args: &[&str]) -> Result { + let output = Command::new(cmd).args(args).output(); + match output { + Ok(out) => { + if out.status.success() { + let stdout = String::from_utf8_lossy(&out.stdout).to_string(); + Ok(stdout) + } else { + let stderr = String::from_utf8_lossy(&out.stderr).to_string(); + Err(format!("command failed: {} {:?} -> {}", cmd, args, stderr)) + } + } + Err(e) => Err(format!("command error: {} {:?} -> {}", cmd, args, e)), + } +} + +fn info(msg: &str) { + println!("[INFO] {}", msg); +} + +fn warn(msg: &str) { + println!("[AVISO] {}", msg); +} + +fn error(msg: &str) { + eprintln!("[ERRO] {}", msg); +} + +fn check_antivirus(platform: &Platform, issues: &mut Vec) -> HashMap { + let mut details = HashMap::new(); + match platform { + Platform::Windows => { + info("Verificando antivírus no Windows..."); + match run_cmd("sc", &["query", "WinDefend"]) { + Ok(out) => { + details.insert("win_defender_service".into(), out.clone()); + if out.to_lowercase().contains("running") { + warn("Antivírus ativo detectado (Windows Defender). Autorize este programa no antivírus."); + details.insert("antivirus_active".into(), "true".into()); + } else { + details.insert("antivirus_active".into(), "false".into()); + } + } + Err(e) => { + issues.push(format!("falha ao consultar serviço WinDefend: {}", e)); + } + } + match run_cmd( + "powershell", + &["-NoProfile", "-Command", "Get-MpComputerStatus | Format-List"], + ) { + Ok(ps) => { + details.insert("mp_status".into(), ps); + } + Err(e) => { + issues.push(format!("PowerShell Get-MpComputerStatus falhou: {}", e)); + } + } + warn("Se necessário, desative temporariamente o antivírus durante a inicialização."); + details.insert("antivirus_instructions".into(), "Abra o antivírus, autorize este programa ou desative temporariamente.".into()); + } + Platform::Linux { .. } => { + info("Verificando SELinux/AppArmor no Linux..."); + match run_cmd("getenforce", &[]) { + Ok(enf) => { + details.insert("selinux_getenforce".into(), enf.trim().to_string()); + if enf.trim().eq_ignore_ascii_case("enforcing") { + warn("SELinux em modo Enforcing. Pode bloquear inicialização. Autorize ou ajuste política."); + details.insert("selinux_enforcing".into(), "true".into()); + } + } + Err(e) => issues.push(format!("getenforce falhou: {}", e)), + } + match run_cmd("sestatus", &[]) { + Ok(st) => { + details.insert("sestatus".into(), st); + } + Err(e) => issues.push(format!("sestatus falhou: {}", e)), + } + match run_cmd("aa-status", &[]) { + Ok(st) => { + details.insert("apparmor_status".into(), st); + warn("AppArmor detectado. Garanta perfis permitindo este programa ou ajuste temporariamente."); + } + Err(e) => { + let p = PathBuf::from("/sys/module/apparmor/parameters/enabled"); + if let Ok(content) = fs::read_to_string(&p) { + let c = content.trim().to_string(); + details.insert("apparmor_enabled".into(), c.clone()); + if c.to_lowercase().contains("y") || c.to_lowercase().contains("yes") { + warn("AppArmor ativo. Autorize este programa ou ajuste perfil."); + } + } else { + issues.push(format!("aa-status falhou e sysfs não disponível: {}", e)); + } + } + } + details.insert("antivirus_instructions".into(), "Verifique SELinux/AppArmor. Ajuste políticas ou desative temporariamente.".into()); + } + Platform::Macos => { + info("Verificando proteções no macOS (Gatekeeper/Antivírus)..."); + match run_cmd("spctl", &["--status"]) { + Ok(st) => { + details.insert("gatekeeper".into(), st.trim().to_string()); + } + Err(e) => issues.push(format!("spctl --status falhou: {}", e)), + } + warn("Se o sistema alertar, permita a execução deste programa nas Preferências de Segurança."); + details.insert("antivirus_instructions".into(), "Permita o app nas Preferências de Segurança, se solicitado.".into()); + } + Platform::Unknown(_) => { + warn("Plataforma desconhecida. Verificações de antivírus limitadas."); + } + } + details +} + +async fn ensure_ollama_running(client: &Client, platform: &Platform, issues: &mut Vec) -> bool { + info("Verificando disponibilidade da API do Ollama..."); + let (status, _) = check_api(client, issues).await; + if matches!(status, ApiStatus::Reachable) { + info("API do Ollama já está acessível."); + return true; + } + + info("Tentando iniciar o serviço Ollama..."); + match platform { + Platform::Windows => { + match Command::new("ollama").arg("serve").spawn() { + Ok(_) => info("Comando 'ollama serve' iniciado no Windows."), + Err(e) => { + issues.push(format!("falha ao iniciar ollama serve: {}", e)); + warn("Não foi possível iniciar automaticamente. Abra o aplicativo Ollama ou reinicie o serviço."); + } + } + } + Platform::Linux { .. } => { + match run_cmd("systemctl", &["start", "ollama"]) { + Ok(_) => info("systemctl start ollama executado."), + Err(e) => { + issues.push(format!("systemctl start falhou: {}", e)); + match Command::new("ollama").arg("serve").spawn() { + Ok(_) => info("Comando 'ollama serve' iniciado (fallback)."), + Err(e2) => { + issues.push(format!("falha ao iniciar ollama serve: {}", e2)); + warn("Inicialização automática falhou. Inicie manualmente o serviço Ollama."); + } + } + } + } + } + Platform::Macos => { + match Command::new("ollama").arg("serve").spawn() { + Ok(_) => info("Comando 'ollama serve' iniciado no macOS."), + Err(e) => { + issues.push(format!("falha ao iniciar ollama serve: {}", e)); + warn("Inicialização automática falhou. Abra o aplicativo Ollama."); + } + } + } + Platform::Unknown(_) => { + warn("Plataforma desconhecida; tentativa genérica de iniciar ollama serve."); + let _ = Command::new("ollama").arg("serve").spawn(); + } + } + + for _ in 0..10 { + sleep(Duration::from_millis(1000)).await; + let (s, _) = check_api(client, issues).await; + if matches!(s, ApiStatus::Reachable) { + info("API do Ollama está acessível após inicialização."); + return true; + } + } + warn("API do Ollama continua inacessível após tentativas."); + false +} + +fn check_native(platform: &Platform, issues: &mut Vec) -> Option { + let mut details = HashMap::new(); + + match platform { + Platform::Linux { distro } => { + // Verifica binário via which + if let Ok(which) = run_cmd("which", &["ollama"]) { + details.insert("which".into(), which.trim().to_string()); + } + // Checa /usr/bin/ollama + let path = PathBuf::from("/usr/bin/ollama"); + details.insert("/usr/bin/ollama".into(), path_exists(&path).to_string()); + + // Serviço via systemctl, se disponível + match run_cmd("systemctl", &["is-active", "ollama"]) { + Ok(active) => { + details.insert("systemctl".into(), active.trim().to_string()); + } + Err(e) => { + issues.push(format!("systemctl check failed: {}", e)); + } + } + + // Versão + match run_cmd("ollama", &["-v"]) { + Ok(ver) => { + details.insert("version".into(), ver.trim().to_string()); + return Some(DetectedMethod { kind: MethodKind::Native, details }); + } + Err(e) => { + issues.push(format!("ollama -v failed: {}", e)); + } + } + // Ajuda por distro + if let Some(d) = distro { + details.insert("distro".into(), d.clone()); + } + } + Platform::Macos => { + // Caminhos comuns + let bin_paths = [ + "/usr/local/bin/ollama", + "/opt/homebrew/bin/ollama", + ]; + for p in bin_paths { + let pb = PathBuf::from(p); + details.insert(p.into(), path_exists(&pb).to_string()); + } + match run_cmd("ollama", &["-v"]) { + Ok(ver) => { + details.insert("version".into(), ver.trim().to_string()); + return Some(DetectedMethod { kind: MethodKind::Native, details }); + } + Err(e) => { + issues.push(format!("ollama -v failed: {}", e)); + } + } + } + Platform::Windows => { + // Checa localização padrão do instalador + let mut possible = vec![]; + if let Ok(localappdata) = env::var("LOCALAPPDATA") { + possible.push(PathBuf::from(format!("{}\\Programs\\Ollama\\ollama.exe", localappdata))); + possible.push(PathBuf::from(format!("{}\\Ollama\\server.log", localappdata))); // logs + } + // Preferir USERPROFILE; se não houver, usar HOMEDRIVE+HOMEPATH + if let Ok(userprofile) = env::var("USERPROFILE") { + possible.push(PathBuf::from(format!("{}\\.ollama", userprofile))); + } else { + let homepath = env::var("HOMEPATH").unwrap_or_default(); + let homedrive = env::var("HOMEDRIVE").unwrap_or_default(); + if !homepath.is_empty() || !homedrive.is_empty() { + let combined = format!("{}{}", homedrive, homepath); + if !combined.trim().is_empty() { + possible.push(PathBuf::from(format!("{}\\.ollama", combined))); + } + } + } + for p in possible { + details.insert(p.display().to_string(), path_exists(&p).to_string()); + } + // where.exe + match run_cmd("where", &["ollama"]) { + Ok(loc) => { + details.insert("where".into(), loc.trim().to_string()); + } + Err(e) => issues.push(format!("where ollama failed: {}", e)), + } + // versão + match run_cmd("ollama", &["-v"]) { + Ok(ver) => { + details.insert("version".into(), ver.trim().to_string()); + return Some(DetectedMethod { kind: MethodKind::Native, details }); + } + Err(e) => issues.push(format!("ollama -v failed: {}", e)), + } + } + Platform::Unknown(_) => { + issues.push("plataforma desconhecida; checagem nativa limitada".into()); + } + } + + None +} + +fn check_docker(issues: &mut Vec) -> Option { + let mut details = HashMap::new(); + // Tenta listar containers, caso docker esteja disponível + match run_cmd("docker", &[ + "ps", + "--format", + "{{.Image}} {{.Names}}", + ]) { + Ok(list) => { + let mut found = false; + for line in list.lines() { + if line.to_lowercase().contains("ollama") { + found = true; + details.insert("container".into(), line.trim().to_string()); + } + } + if found { + return Some(DetectedMethod { kind: MethodKind::Docker, details }); + } else { + details.insert("docker_ps".into(), "no_ollama_container".into()); + return None; + } + } + Err(e) => { + issues.push(format!("docker ps failed: {}", e)); + } + } + + None +} + +async fn check_api(client: &Client, issues: &mut Vec) -> (ApiStatus, Option) { + let mut details = HashMap::new(); + let base = "http://localhost:11434"; + + // Tenta /api/version + if let Ok(mut resp) = client.get(format!("{}/api/version", base)).send().await { + if resp.status().is_success() { + let body = resp.body().await; + if let Ok(bytes) = body { + let text = String::from_utf8_lossy(&bytes).to_string(); + details.insert("/api/version".into(), text); + } + } else { + issues.push(format!("/api/version status: {}", resp.status())); + } + } else { + issues.push("falha ao conectar /api/version".into()); + } + + // Tenta /api/tags + if let Ok(mut resp) = client.get(format!("{}/api/tags", base)).send().await { + if resp.status().is_success() { + let body = resp.body().await; + if let Ok(bytes) = body { + let text = String::from_utf8_lossy(&bytes).to_string(); + details.insert("/api/tags".into(), text); + } + } else { + issues.push(format!("/api/tags status: {}", resp.status())); + } + } else { + issues.push("falha ao conectar /api/tags".into()); + } + + // Heurística de status + let api_status = if details.is_empty() { + ApiStatus::Unreachable + } else if !details.contains_key("/api/version") { + ApiStatus::Degraded + } else { + ApiStatus::Reachable + }; + + let method = if matches!(api_status, ApiStatus::Reachable | ApiStatus::Degraded) { + Some(DetectedMethod { kind: MethodKind::Api, details }) + } else { + None + }; + + (api_status, method) +} + +fn add_doc_fallbacks(platform: &Platform, details: &mut HashMap) { + // Informações baseadas na documentação pública do Ollama + match platform { + Platform::Windows => { + details.insert("docs_windows_api".into(), "API local: http://localhost:11434".into()); + details.insert("docs_windows_logs".into(), "%LOCALAPPDATA%\\Ollama\\server.log".into()); + details.insert("docs_windows_bin".into(), "%LOCALAPPDATA%\\Programs\\Ollama".into()); + } + Platform::Linux { .. } => { + details.insert("docs_linux_service".into(), "systemctl status ollama".into()); + details.insert("docs_linux_api".into(), "API local: http://localhost:11434".into()); + } + Platform::Macos => { + details.insert("docs_macos_api".into(), "API local: http://localhost:11434".into()); + details.insert("docs_macos_common_paths".into(), "/usr/local/bin, /opt/homebrew/bin".into()); + } + Platform::Unknown(_) => { + details.insert("docs_general".into(), "API local: http://localhost:11434".into()); + } + } +} + +struct AppState { + tx: broadcast::Sender, + crypto: CryptoState, +} + +#[derive(Clone)] +struct CryptoState { + // Chave AES-256-GCM (32 bytes) armazenada se inicializada + key: std::sync::Arc>>, + key_path: std::path::PathBuf, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct WsEvent { + event: String, + operation_id: Option, + data: serde_json::Value, +} + +#[actix_rt::main] +async fn main() -> std::io::Result<()> { + info("Iniciando servidor HTTP para gerenciamento do Ollama..."); + let start = Instant::now(); + let mut sys = System::new(); + sys.refresh_cpu(); + sys.refresh_memory(); + info(&format!("Recursos iniciais: CPU {:.2}% | Memória usada: {} / {} MB", + sys.global_cpu_info().cpu_usage(), + sys.used_memory() / 1024, sys.total_memory() / 1024)); + + // Broker para eventos WebSocket + let (tx, _rx) = broadcast::channel::(128); + // Estado de criptografia + let key_dir = config_dir().unwrap_or(std::path::PathBuf::from(".")); + let key_path = key_dir.join("OllaHubBackend").join("crypto.key"); + let crypto_state = CryptoState { key: std::sync::Arc::new(std::sync::Mutex::new(None)), key_path: key_path.clone() }; + // Tenta carregar chave existente + if let Some(parent) = key_path.parent() { let _ = std::fs::create_dir_all(parent); } + if let Ok(bytes) = std::fs::read(&key_path) { + if bytes.len() == 32 { + let mut key_lock = crypto_state.key.lock().unwrap(); + let mut key_bytes = [0u8;32]; + key_bytes.copy_from_slice(&bytes); + *key_lock = Some(key_bytes); + info(&format!("Chave carregada de: {}. Use a MESMA chave no frontend.", key_path.display())); + } else { + warn("Arquivo de chave encontrado com tamanho inválido; ignorando."); + } + } + + // Estado V2 (modular) + let v2_key_dir = config_dir().unwrap_or(std::path::PathBuf::from(".")); + let v2_key_path = v2_key_dir.join("OllaHubBackend").join("crypto_v2.key"); + let v2_state = AppContext::new( + std::env::var("OLLAMA_BASE_URL").unwrap_or_else(|_| "http://localhost:11434".to_string()), + std::env::var("MODEL_LIST_PATH").unwrap_or_else(|_| "modelList.json".to_string()), + v2_key_path, + ); + let v2_state_data = web::Data::new(v2_state); + let v2_broker = ws::new_broker(); + let v2_broker_data = web::Data::new(BrokerAddr(v2_broker.clone())); + + let server = HttpServer::new(move || { + App::new() + .app_data(web::Data::new(AppState { tx: tx.clone(), crypto: crypto_state.clone() })) + .route("/health", web::get().to(health)) + .route("/ollama/install-check", web::get().to(install_check)) + .route("/ollama/install", web::post().to(install_ollama)) + .route("/ws", web::get().to(ws_route)) + .route("/api/models", web::get().to(models_list)) + .route("/api/models/install", web::post().to(models_install)) + .route("/api/crypto/key", web::post().to(set_crypto_key)) + .route("/api/crypto/rotate", web::post().to(rotate_crypto_key)) + .route("/api/crypto/encrypt", web::post().to(api_encrypt)) + .route("/api/crypto/decrypt", web::post().to(api_decrypt)) + // Documentação Swagger UI e rotas v1 + .service(routes::swagger_ui()) + .configure(|cfg| routes::configure_v1(cfg, v2_state_data.clone())) + .wrap(from_fn(middlewares::auth::jwt_auth)) + // Rotas V2 modulares sob /v2 + .service( + actix_web::web::scope("/v2") + .configure(|cfg| api::configure(cfg, v2_state_data.clone())) + .configure(|cfg| api::ws_config(cfg, v2_broker_data.clone())), + ) + }) + .bind(("127.0.0.1", 8080))?; + + let bind_elapsed = start.elapsed().as_millis(); + info(&format!("Bind concluído em {} ms", bind_elapsed)); + sys.refresh_cpu(); + sys.refresh_memory(); + info(&format!("Recursos após bind: CPU {:.2}% | Memória usada: {} / {} MB", + sys.global_cpu_info().cpu_usage(), + sys.used_memory() / 1024, sys.total_memory() / 1024)); + + server.run().await +} + +// Endpoint de saúde simples +async fn health() -> impl Responder { + HttpResponse::Ok().json("ok") +} + +// ===== WebSocket ===== +struct WsSession { + rx: broadcast::Receiver, +} + +impl actix::Actor for WsSession { + type Context = actix_ws::WebsocketContext; + + fn started(&mut self, ctx: &mut Self::Context) { + // Mensagem inicial de handshake + let hello = WsEvent { event: "hello".into(), operation_id: None, data: serde_json::json!({"msg":"connected"}) }; + ctx.text(serde_json::to_string(&hello).unwrap()); + + // Repassa eventos do broker para o cliente via mensagens do actor + let mut rx = self.rx.resubscribe(); + let addr = ctx.address(); + actix::spawn(async move { + loop { + match rx.recv().await { + Ok(ev) => addr.do_send(SendWs(ev)), + Err(broadcast::error::RecvError::Lagged(_)) => continue, + Err(broadcast::error::RecvError::Closed) => break, + } + } + }); + } +} + +#[derive(Message)] +#[rtype(result = "()")] +struct SendWs(WsEvent); + +impl Handler for WsSession { + type Result = (); + + fn handle(&mut self, msg: SendWs, ctx: &mut Self::Context) -> Self::Result { + let payload = serde_json::to_string(&msg.0).unwrap(); + ctx.text(payload); + } +} + +impl actix::StreamHandler> for WsSession { + fn handle(&mut self, msg: Result, ctx: &mut actix_ws::WebsocketContext) { + if let Ok(m) = msg { + match m { + actix_ws::Message::Ping(bytes) => ctx.pong(&bytes), + actix_ws::Message::Text(text) => { + // Mensagens de controle do cliente (ex: subscribe por operation_id) – atualmente broadcast geral + ctx.text(text); + } + actix_ws::Message::Close(reason) => { + ctx.close(reason); + } + _ => {} + } + } + } +} + +async fn ws_route(state: web::Data, req: actix_web::HttpRequest, stream: web::Payload) -> impl Responder { + let rx = state.tx.subscribe(); + let session = WsSession { rx }; + actix_ws::start(session, &req, stream) +} + +// ===== Modelos ===== +#[derive(Debug, Clone, Serialize, Deserialize)] +struct ModelMeta { + name: String, + description: Option, + url: Option, + capabilities: Option>, + parameter_sizes: Option>, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct ModelsResponse { + total: usize, + models: Vec, +} + +async fn models_list(q: web::Query>) -> impl Responder { + let path = std::path::Path::new("modelList.json"); + let content = match std::fs::read_to_string(path) { + Ok(c) => c, + Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({"error":format!("falha ao ler modelList.json: {}", e)})), + }; + let v: serde_json::Value = match serde_json::from_str(&content) { + Ok(v) => v, + Err(e) => return HttpResponse::InternalServerError().json(serde_json::json!({"error":format!("JSON inválido: {}", e)})), + }; + let mut list: Vec = vec![]; + if let Some(models) = v.get("models").and_then(|m| m.as_array()) { + for m in models { + let meta = ModelMeta { + name: m.get("name").and_then(|x| x.as_str()).unwrap_or("").to_string(), + description: m.get("description").and_then(|x| x.as_str()).map(|s| s.to_string()), + url: m.get("url").and_then(|x| x.as_str()).map(|s| s.to_string()), + capabilities: m.get("capabilities").and_then(|x| x.as_array()).map(|arr| arr.iter().filter_map(|v| v.as_str().map(|s| s.to_string())).collect()), + parameter_sizes: m.get("parameter_sizes").and_then(|x| x.as_array()).map(|arr| arr.iter().filter_map(|v| v.as_str().map(|s| s.to_string())).collect()), + }; + list.push(meta); + } + } + if let Some(qs) = q.get("q") { + let needle = qs.to_lowercase(); + list.retain(|m| m.name.to_lowercase().contains(&needle) || m.description.as_ref().map(|d| d.to_lowercase().contains(&needle)).unwrap_or(false)); + } + HttpResponse::Ok().json(ModelsResponse { total: list.len(), models: list }) +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct InstallModelRequest { + model: Option, + name: Option, + size: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct InstallModelResponse { + started: bool, + operation_id: Uuid, +} + +async fn models_install(state: web::Data, payload: web::Json) -> impl Responder { + // Validar nome + let model_name = if let Some(m) = &payload.model { m.clone() } else if let Some(n) = &payload.name { if let Some(s) = &payload.size { format!("{}:{}", n, s) } else { n.clone() } } else { String::new() }; + if model_name.is_empty() || !model_name.chars().all(|c| c.is_ascii_alphanumeric() || ":.-_".contains(c)) { + return HttpResponse::BadRequest().json(serde_json::json!({"error":"formato de modelo inválido"})); + } + let op_id = Uuid::new_v4(); + let tx = state.tx.clone(); + + actix_rt::spawn(async move { + // Publica início + let _ = tx.send(WsEvent { event: "pull_start".into(), operation_id: Some(op_id), data: serde_json::json!({"model":model_name}) }); + // Chama API do Ollama + let client = awc::Client::default(); + let url = "http://localhost:11434/api/pull"; + let req_body = serde_json::json!({"name": model_name}); + match client.post(url).send_json(&req_body).await { + Ok(mut resp) => { + let mut buf = String::new(); + // Fallback: lê corpo completo e processa linhas (menos granular que stream) + match resp.body().await { + Ok(bytes) => { + let s = String::from_utf8_lossy(&bytes).to_string(); + buf.push_str(&s); + for line in buf.lines() { + if line.trim().is_empty() { continue; } + if let Ok(val) = serde_json::from_str::(line) { + let _ = tx.send(WsEvent { event: "pull_progress".into(), operation_id: Some(op_id), data: val }); + } else { + let _ = tx.send(WsEvent { event: "pull_log".into(), operation_id: Some(op_id), data: serde_json::json!({"line":line}) }); + } + } + } + Err(e) => { + let _ = tx.send(WsEvent { event: "pull_error".into(), operation_id: Some(op_id), data: serde_json::json!({"error": format!("payload_error: {}", e)}) }); + } + } + let _ = tx.send(WsEvent { event: "pull_done".into(), operation_id: Some(op_id), data: serde_json::json!({}) }); + } + Err(e) => { + let _ = tx.send(WsEvent { event: "pull_error".into(), operation_id: Some(op_id), data: serde_json::json!({"error":e.to_string()}) }); + } + } + }); + + HttpResponse::Accepted().json(InstallModelResponse { started: true, operation_id: op_id }) +} + +// ===== Criptografia ===== +#[derive(Debug, Clone, Serialize, Deserialize)] +struct SetKeyRequest { key_hex: Option, key_base64: Option } + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct SimpleOk { ok: bool } + +async fn set_crypto_key(state: web::Data, payload: web::Json) -> impl Responder { + // Aceita primeira chave válida + let mut lock = state.crypto.key.lock().unwrap(); + if lock.is_some() { return HttpResponse::Conflict().json(serde_json::json!({"error":"chave já definida"})); } + let mut key = [0u8;32]; + let bytes = if let Some(hex) = &payload.key_hex { hex::decode(hex).ok() } else if let Some(b64) = &payload.key_base64 { BASE64.decode(b64).ok() } else { None }; + let bytes = match bytes { Some(b) => b, None => return HttpResponse::BadRequest().json(serde_json::json!({"error":"forneça key_hex ou key_base64"})) }; + if bytes.len() != 32 { return HttpResponse::BadRequest().json(serde_json::json!({"error":"chave deve ter 32 bytes"})); } + key.copy_from_slice(&bytes); + *lock = Some(key); + // Persiste no disco + if let Some(parent) = state.crypto.key_path.parent() { let _ = std::fs::create_dir_all(parent); } + if let Err(e) = std::fs::write(&state.crypto.key_path, &key) { return HttpResponse::InternalServerError().json(serde_json::json!({"error":format!("falha ao salvar chave: {}", e)})); } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&state.crypto.key_path, std::fs::Permissions::from_mode(0o600)); + } + info(&format!("Chave salva em {}. Use a MESMA chave no frontend.", state.crypto.key_path.display())); + HttpResponse::Ok().json(SimpleOk { ok: true }) +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct RotateKeyRequest { key_hex: String } + +async fn rotate_crypto_key(state: web::Data, payload: web::Json) -> impl Responder { + let mut lock = state.crypto.key.lock().unwrap(); + let mut key = [0u8;32]; + let bytes = match hex::decode(&payload.key_hex) { Ok(b) => b, Err(_) => return HttpResponse::BadRequest().json(serde_json::json!({"error":"key_hex inválido"})) }; + if bytes.len() != 32 { return HttpResponse::BadRequest().json(serde_json::json!({"error":"chave deve ter 32 bytes"})); } + key.copy_from_slice(&bytes); + *lock = Some(key); + if let Err(e) = std::fs::write(&state.crypto.key_path, &key) { return HttpResponse::InternalServerError().json(serde_json::json!({"error":format!("falha ao salvar chave: {}", e)})); } + info("Chave rotacionada."); + HttpResponse::Ok().json(SimpleOk { ok: true }) +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct CryptoPayload { data_base64: String } + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct CryptoResult { nonce_base64: String, ciphertext_base64: String } + +fn get_cipher(state: &AppState) -> Result { + let lock = state.crypto.key.lock().unwrap(); + if let Some(key_bytes) = *lock { + let key = Key::::from_slice(&key_bytes); + Ok(Aes256Gcm::new(key)) + } else { Err("chave não definida".into()) } +} + +async fn api_encrypt(state: web::Data, payload: web::Json) -> impl Responder { + let cipher = match get_cipher(&state) { Ok(c) => c, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({"error":e})) }; + let mut nonce_bytes = [0u8;12]; + rand::thread_rng().fill_bytes(&mut nonce_bytes); + let nonce = Nonce::from_slice(&nonce_bytes); + let data = match BASE64.decode(&payload.data_base64) { Ok(d) => d, Err(_) => return HttpResponse::BadRequest().json(serde_json::json!({"error":"data_base64 inválido"})) }; + match cipher.encrypt(nonce, data.as_ref()) { + Ok(ct) => HttpResponse::Ok().json(CryptoResult { nonce_base64: BASE64.encode(nonce_bytes), ciphertext_base64: BASE64.encode(ct) }), + Err(_) => HttpResponse::InternalServerError().json(serde_json::json!({"error":"falha ao criptografar"})), + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct CryptoDecryptPayload { nonce_base64: String, ciphertext_base64: String } + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct DecryptResult { data_base64: String } + +async fn api_decrypt(state: web::Data, payload: web::Json) -> impl Responder { + let cipher = match get_cipher(&state) { Ok(c) => c, Err(e) => return HttpResponse::BadRequest().json(serde_json::json!({"error":e})) }; + let nonce_bytes = match BASE64.decode(&payload.nonce_base64) { Ok(b) => b, Err(_) => return HttpResponse::BadRequest().json(serde_json::json!({"error":"nonce_base64 inválido"})) }; + let ct = match BASE64.decode(&payload.ciphertext_base64) { Ok(b) => b, Err(_) => return HttpResponse::BadRequest().json(serde_json::json!({"error":"ciphertext_base64 inválido"})) }; + if nonce_bytes.len() != 12 { return HttpResponse::BadRequest().json(serde_json::json!({"error":"nonce deve ter 12 bytes"})); } + let nonce = Nonce::from_slice(&nonce_bytes); + match cipher.decrypt(nonce, ct.as_ref()) { + Ok(pt) => HttpResponse::Ok().json(DecryptResult { data_base64: BASE64.encode(pt) }), + Err(_) => HttpResponse::BadRequest().json(serde_json::json!({"error":"falha ao descriptografar ou tag inválida"})), + } +} + +// ===== Testes ===== +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn crypto_roundtrip() { + let key_path = std::path::PathBuf::from("./test.key"); + let state = AppState { tx: tokio::sync::broadcast::channel(8).0, crypto: CryptoState { key: std::sync::Arc::new(std::sync::Mutex::new(None)), key_path } }; + { + let mut lock = state.crypto.key.lock().unwrap(); + let mut k = [0u8;32]; + for i in 0..32 { k[i] = i as u8; } + *lock = Some(k); + } + let cipher = get_cipher(&state).unwrap(); + let nonce = Nonce::from_slice(&[0u8;12]); + let pt = b"hello"; + let ct = cipher.encrypt(nonce, pt.as_ref()).unwrap(); + let out = cipher.decrypt(nonce, ct.as_ref()).unwrap(); + assert_eq!(out, pt); + } + + #[test] + fn models_read_ok() { + let path = std::path::Path::new("modelList.json"); + let content = std::fs::read_to_string(path).expect("modelList.json presente"); + let v: serde_json::Value = serde_json::from_str(&content).expect("json válido"); + assert!(v.get("models").is_some()); + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct InstallCheckResult { + installed: bool, + in_path: bool, + version: Option, + service_running: bool, + api_status: ApiStatus, + details: HashMap, + issues: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct InstallResult { + initiated: bool, + installed: bool, + service_started: bool, + final_api_status: ApiStatus, + details: HashMap, + issues: Vec, + timing_ms: HashMap, + aborted: Option, + manual_instructions: Option, +} + +async fn install_check() -> impl Responder { + let platform = detect_platform(); + let client = Client::builder().timeout(Duration::from_secs(3)).finish(); + let mut issues: Vec = vec![]; + let mut details: HashMap = HashMap::new(); + + // Binário em PATH e versão + let native = check_native(&platform, &mut issues); + let installed = native.is_some(); + let mut in_path = false; + let mut version: Option = None; + if let Some(n) = &native { + in_path = true; + if let Some(v) = n.details.get("version") { + version = Some(v.clone()); + } + // adiciona detalhes capturados + for (k, v) in &n.details { + details.insert(format!("native_{}", k), v.clone()); + } + } + + // Status da API + let (api_status, api_method) = check_api(&client, &mut issues).await; + if let Some(m) = api_method { + for (k, v) in m.details { + details.insert(format!("api_{}", k), v); + } + } + + // Integra detalhes de segurança/antivírus ao relatório + let av_details = check_antivirus(&platform, &mut issues); + for (k, v) in av_details { + details.insert(format!("security_{}", k), v); + } + + // Detalhes Docker (se aplicável) + if let Some(docker) = check_docker(&mut issues) { + for (k, v) in docker.details { + details.insert(format!("docker_{}", k), v); + } + } + + // Status do serviço por SO (faz sentido após checar API) + let service_running = match &platform { + Platform::Linux { .. } => { + match run_cmd("systemctl", &["is-active", "ollama"]) { + Ok(s) => s.trim() == "active", + Err(e) => { + issues.push(format!("systemctl is-active falhou: {}", e)); + false + } + } + } + Platform::Windows => { + let mut running = false; + match run_cmd( + "powershell", + &["-NoProfile", "-Command", "Get-Process -Name ollama -ErrorAction SilentlyContinue | Select-Object -First 1 | ForEach-Object { $_.Name }"], + ) { + Ok(p) => running = !p.trim().is_empty(), + Err(e) => issues.push(format!("Get-Process ollama falhou: {}", e)), + } + running || !matches!(api_status, ApiStatus::Unreachable) + } + Platform::Macos => { + // No macOS consideramos serviço rodando se a API está acessível + !matches!(api_status, ApiStatus::Unreachable) + } + Platform::Unknown(_) => !matches!(api_status, ApiStatus::Unreachable), + }; + + add_doc_fallbacks(&platform, &mut details); + + let result = InstallCheckResult { + installed, + in_path, + version, + service_running, + api_status, + details, + issues, + }; + + HttpResponse::Ok().json(result) +} + +async fn install_ollama() -> impl Responder { + let platform = detect_platform(); + let client = Client::builder().timeout(Duration::from_secs(5)).finish(); + let mut issues: Vec = vec![]; + let mut details: HashMap = HashMap::new(); + let mut timing_ms: HashMap = HashMap::new(); + let deadline = Instant::now() + Duration::from_secs(30); + + // snapshot recursos + let mut sys = System::new(); + sys.refresh_cpu(); + sys.refresh_memory(); + details.insert("resources_start_cpu".into(), format!("{:.2}", sys.global_cpu_info().cpu_usage())); + details.insert("resources_start_mem_used_mb".into(), format!("{}", sys.used_memory() / 1024)); + details.insert("resources_start_mem_total_mb".into(), format!("{}", sys.total_memory() / 1024)); + + // Já instalado? + let t_check_native = Instant::now(); + let native = check_native(&platform, &mut issues); + timing_ms.insert("check_native".into(), t_check_native.elapsed().as_millis()); + let mut installed = native.is_some(); + if installed { + info("Ollama já instalado; garantindo inicialização do serviço..."); + } else { + info("Ollama não instalado; iniciando instalação automática..."); + let t_install = Instant::now(); + let install_res = match &platform { + Platform::Linux { .. } => linux_install(&mut details, &mut issues), + Platform::Windows => windows_install(&mut details, &mut issues), + Platform::Macos => macos_install(&mut details, &mut issues), + Platform::Unknown(_) => { + issues.push("Plataforma desconhecida; instalação não suportada".into()); + Err("unsupported_platform".into()) + } + }; + match install_res { + Ok(_) => { + installed = true; + info("Instalação concluída (ou instruções fornecidas)."); + timing_ms.insert("install".into(), t_install.elapsed().as_millis()); + } + Err(e) => { + error(&format!("Instalação falhou: {}", e)); + // rollback básico + rollback(&platform, &mut details, &mut issues); + let manual = manual_instructions(&platform); + return HttpResponse::InternalServerError().json(InstallResult { + initiated: true, + installed: false, + service_started: false, + final_api_status: ApiStatus::Unreachable, + details, + issues, + timing_ms, + aborted: Some("install_failed".into()), + manual_instructions: Some(manual), + }); + } + } + } + + // Iniciar serviço e checar API + if Instant::now() > deadline { + warn("Tempo total de inicialização excedeu 30s; abortando."); + let manual = manual_instructions(&platform); + timing_ms.insert("total".into(), 30_000); + return HttpResponse::RequestTimeout().json(InstallResult { + initiated: true, + installed, + service_started: false, + final_api_status: ApiStatus::Unreachable, + details, + issues, + timing_ms, + aborted: Some("timeout_exceeded".into()), + manual_instructions: Some(manual), + }); + } + + let t_service = Instant::now(); + let service_started = ensure_ollama_running(&client, &platform, &mut issues).await; + timing_ms.insert("ensure_service".into(), t_service.elapsed().as_millis()); + + let t_api = Instant::now(); + let (final_api_status, api_method) = check_api(&client, &mut issues).await; + timing_ms.insert("check_api_final".into(), t_api.elapsed().as_millis()); + if let Some(m) = api_method { + for (k, v) in m.details { + details.insert(format!("api_{}", k), v); + } + } + + add_doc_fallbacks(&platform, &mut details); + + // recursos finais + sys.refresh_cpu(); + sys.refresh_memory(); + details.insert("resources_end_cpu".into(), format!("{:.2}", sys.global_cpu_info().cpu_usage())); + details.insert("resources_end_mem_used_mb".into(), format!("{}", sys.used_memory() / 1024)); + details.insert("resources_end_mem_total_mb".into(), format!("{}", sys.total_memory() / 1024)); + let total_elapsed = 30_000.min(deadline.duration_since(Instant::now()).as_millis() as u128); + timing_ms.insert("total".into(), total_elapsed); + + HttpResponse::Ok().json(InstallResult { + initiated: true, + installed, + service_started, + final_api_status, + details, + issues, + timing_ms, + aborted: None, + manual_instructions: None, + }) +} + +fn rollback(platform: &Platform, details: &mut HashMap, issues: &mut Vec) { + match platform { + Platform::Linux { .. } => { + info("Rollback: tentando parar e desabilitar serviço ollama..."); + if let Err(e) = run_cmd("systemctl", &["stop", "ollama"]) { + issues.push(format!("rollback stop falhou: {}", e)); + } + if let Err(e) = run_cmd("systemctl", &["disable", "ollama"]) { + issues.push(format!("rollback disable falhou: {}", e)); + } + details.insert("rollback_linux".into(), "service_stop_disable".into()); + } + Platform::Windows => { + info("Rollback: nada destrutivo executado no Windows (installer GUI)."); + details.insert("rollback_windows".into(), "no_op".into()); + } + Platform::Macos => { + info("Rollback: nada destrutivo executado no macOS."); + details.insert("rollback_macos".into(), "no_op".into()); + } + Platform::Unknown(_) => {} + } +} + +fn linux_install(details: &mut HashMap, issues: &mut Vec) -> Result<(), String> { + info("Linux: executando script oficial de instalação do Ollama..."); + match run_cmd("sh", &["-lc", "curl -fsSL https://ollama.com/install.sh | sh"]) { + Ok(out) => { + details.insert("linux_install_output".into(), out); + } + Err(e) => { + issues.push(format!("install.sh falhou: {}", e)); + return Err("install_script_failed".into()); + } + } + // Habilitar e iniciar serviço + if let Err(e) = run_cmd("systemctl", &["daemon-reload"]) { + issues.push(format!("daemon-reload falhou: {}", e)); + } + if let Err(e) = run_cmd("systemctl", &["enable", "ollama"]) { + issues.push(format!("enable falhou: {}", e)); + } + match run_cmd("systemctl", &["start", "ollama"]) { + Ok(_) => info("Serviço ollama iniciado."), + Err(e) => { + issues.push(format!("start falhou: {}", e)); + } + } + Ok(()) +} + +fn windows_install(details: &mut HashMap, issues: &mut Vec) -> Result<(), String> { + info("Windows: tentando baixar e executar o instalador do Ollama..."); + // Tenta baixar OllamaSetup.exe + let ps_download = r#" + $url = 'https://ollama.com/download/OllamaSetup.exe'; + $out = "$env:TEMP\\OllamaSetup.exe"; + try { + Invoke-WebRequest -Uri $url -OutFile $out -UseBasicParsing; + Write-Output $out; + } catch { + Write-Error $_.Exception.Message; + exit 1; + } + "#; + let dl = run_cmd("powershell", &["-NoProfile", "-Command", ps_download]); + let installer_path = match dl { + Ok(p) => { + let path = p.trim().lines().last().unwrap_or("").trim().to_string(); + details.insert("windows_installer_path".into(), path.clone()); + path + } + Err(e) => { + issues.push(format!("download installer falhou: {}", e)); + // Fallback: tentar baixar zip standalone + let ps_zip = r#" + $url = 'https://ollama.com/download/ollama-windows-amd64.zip'; + $out = "$env:TEMP\\ollama-windows-amd64.zip"; + try { + Invoke-WebRequest -Uri $url -OutFile $out -UseBasicParsing; + Write-Output $out; + } catch { + Write-Error $_.Exception.Message; + exit 1; + } + "#; + match run_cmd("powershell", &["-NoProfile", "-Command", ps_zip]) { + Ok(zip_path_out) => { + let zip_path = zip_path_out.trim().lines().last().unwrap_or("").trim().to_string(); + details.insert("windows_zip_path".into(), zip_path.clone()); + // Expand-Archive para pasta padrão + let ps_expand = format!( + "Expand-Archive -LiteralPath '{}' -DestinationPath '$env:LOCALAPPDATA\\Programs\\Ollama' -Force", + zip_path + ); + if let Err(e2) = run_cmd("powershell", &["-NoProfile", "-Command", &ps_expand]) { + issues.push(format!("Expand-Archive falhou: {}", e2)); + return Err("zip_expand_failed".into()); + } + // OK: instalado via zip + return Ok(()); + } + Err(e2) => { + issues.push(format!("download zip falhou: {}", e2)); + return Err("installer_download_failed".into()); + } + } + } + }; + + // Executa instalador (pode abrir GUI; tentamos aguardar término) + let ps_run = format!( + "Start-Process -FilePath '{}' -ArgumentList '/SILENT' -Wait", + installer_path + ); + match run_cmd("powershell", &["-NoProfile", "-Command", &ps_run]) { + Ok(_) => { + info("Instalador executado."); + Ok(()) + } + Err(e) => { + issues.push(format!("exec installer falhou: {}", e)); + Err("installer_exec_failed".into()) + } + } +} + +fn macos_install(details: &mut HashMap, issues: &mut Vec) -> Result<(), String> { + info("macOS: tentando instalar via Homebrew (se disponível)..."); + match run_cmd("brew", &["--version"]) { + Ok(_) => { + match run_cmd("brew", &["install", "ollama"]) { + Ok(out) => { + details.insert("brew_install_output".into(), out); + } + Err(e) => { + issues.push(format!("brew install falhou: {}", e)); + return Err("brew_install_failed".into()); + } + } + Ok(()) + } + Err(_) => { + issues.push("Homebrew não encontrado; favor instalar manualmente via https://ollama.com/download/".into()); + Err("no_brew".into()) + } + } +} + +fn manual_instructions(platform: &Platform) -> String { + match platform { + Platform::Linux { .. } => { + "Instalação manual: execute 'curl -fsSL https://ollama.com/install.sh | sh', depois 'sudo systemctl enable --now ollama'. Verifique com 'systemctl status ollama' e acesse http://localhost:11434".into() + } + Platform::Windows => { + "Instalação manual: baixe 'OllamaSetup.exe' em https://ollama.com/download/ e execute. Alternativa: baixe 'ollama-windows-amd64.zip', extraia em %LOCALAPPDATA%\\Programs\\Ollama e rode 'ollama serve'. Verifique http://localhost:11434".into() + } + Platform::Macos => { + "Instalação manual: se tiver Homebrew, 'brew install ollama'. Alternativa: baixe o app em https://ollama.com/download/ e inicie. Verifique http://localhost:11434".into() + } + Platform::Unknown(_) => { + "Consulte https://ollama.com/download/ para instruções do seu sistema. Verifique a API em http://localhost:11434".into() + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use actix_web::{test, App}; + + #[actix_rt::test] + async fn test_install_check_endpoint() { + let app = test::init_service(App::new().route("/ollama/install-check", web::get().to(install_check))).await; + let req = test::TestRequest::get().uri("/ollama/install-check").to_request(); + let resp = test::call_and_read_body(&app, req).await; + assert!(!resp.is_empty()); + } +} diff --git a/src/middlewares/auth.rs b/src/middlewares/auth.rs new file mode 100644 index 0000000..11d8625 --- /dev/null +++ b/src/middlewares/auth.rs @@ -0,0 +1,38 @@ +use actix_web::{dev::{ServiceRequest, ServiceResponse}, Error}; +use actix_web::{http::header, HttpResponse}; +use actix_web::middleware::Next; +use actix_web::body::MessageBody; +use jsonwebtoken::{decode, DecodingKey, Validation}; +use serde::Deserialize; + +use crate::state::AppContext; + +#[derive(Debug, Deserialize)] +struct Claims { sub: String, exp: usize, role: Option } + +pub async fn jwt_auth(req: ServiceRequest, next: Next) -> Result +where + B: MessageBody + 'static, +{ + // Apenas protege rotas da API v1; demais passam direto + if !req.path().starts_with("/api/v1/") { + let res = next.call(req).await?; + return Ok(res.map_into_boxed_body()); + } + let ctx = req.app_data::>().cloned(); + let Some(state) = ctx else { return Ok(req.into_response(HttpResponse::InternalServerError().finish())); }; + let Some(hdr) = req.headers().get(header::AUTHORIZATION) else { + return Ok(req.into_response(HttpResponse::Unauthorized().finish())); + }; + let token = hdr.to_str().unwrap_or(""); + let token = token.strip_prefix("Bearer ").unwrap_or(token); + let secret = &state.jwt_secret; + let res = decode::(token, &DecodingKey::from_secret(secret.as_bytes()), &Validation::default()); + match res { + Ok(_data) => { + let res = next.call(req).await?; + Ok(res.map_into_boxed_body()) + } + Err(_) => Ok(req.into_response(HttpResponse::Unauthorized().finish())), + } +} \ No newline at end of file diff --git a/src/middlewares/error.rs b/src/middlewares/error.rs new file mode 100644 index 0000000..56961a3 --- /dev/null +++ b/src/middlewares/error.rs @@ -0,0 +1,37 @@ +use actix_web::{HttpResponse, ResponseError}; +use serde::Serialize; +use utoipa::ToSchema; +use std::fmt; + +#[derive(Debug, Serialize, ToSchema)] +pub struct ApiErrorBody { pub error: String } + +#[derive(Debug)] +pub enum ApiError { + BadRequest(String), + Unauthorized(String), + NotFound(String), + Internal(String), +} + +impl ResponseError for ApiError { + fn error_response(&self) -> HttpResponse { + match self { + ApiError::BadRequest(msg) => HttpResponse::BadRequest().json(ApiErrorBody { error: msg.clone() }), + ApiError::Unauthorized(msg) => HttpResponse::Unauthorized().json(ApiErrorBody { error: msg.clone() }), + ApiError::NotFound(msg) => HttpResponse::NotFound().json(ApiErrorBody { error: msg.clone() }), + ApiError::Internal(msg) => HttpResponse::InternalServerError().json(ApiErrorBody { error: msg.clone() }), + } + } +} + +impl fmt::Display for ApiError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ApiError::BadRequest(msg) => write!(f, "BadRequest: {}", msg), + ApiError::Unauthorized(msg) => write!(f, "Unauthorized: {}", msg), + ApiError::NotFound(msg) => write!(f, "NotFound: {}", msg), + ApiError::Internal(msg) => write!(f, "Internal: {}", msg), + } + } +} \ No newline at end of file diff --git a/src/middlewares/mod.rs b/src/middlewares/mod.rs new file mode 100644 index 0000000..3ca2ddf --- /dev/null +++ b/src/middlewares/mod.rs @@ -0,0 +1,2 @@ +pub mod auth; +pub mod error; \ No newline at end of file diff --git a/src/models/mod.rs b/src/models/mod.rs new file mode 100644 index 0000000..018ff2e --- /dev/null +++ b/src/models/mod.rs @@ -0,0 +1 @@ +pub mod user; \ No newline at end of file diff --git a/src/models/user.rs b/src/models/user.rs new file mode 100644 index 0000000..80cfe16 --- /dev/null +++ b/src/models/user.rs @@ -0,0 +1,33 @@ +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; +use uuid::Uuid; +use validator::Validate; + +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] +pub struct User { + pub id: String, + pub name: String, + pub email: String, +} + +impl User { + pub fn from_create(req: CreateUserRequest) -> Self { + Self { id: Uuid::new_v4().to_string(), name: req.name, email: req.email } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, Validate, ToSchema)] +pub struct CreateUserRequest { + #[validate(length(min = 2))] + pub name: String, + #[validate(email)] + pub email: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize, Validate, ToSchema)] +pub struct UpdateUserRequest { + #[validate(length(min = 2))] + pub name: Option, + #[validate(email)] + pub email: Option, +} \ No newline at end of file diff --git a/src/repositories/mod.rs b/src/repositories/mod.rs new file mode 100644 index 0000000..0017864 --- /dev/null +++ b/src/repositories/mod.rs @@ -0,0 +1 @@ +pub mod user_repository; \ No newline at end of file diff --git a/src/repositories/user_repository.rs b/src/repositories/user_repository.rs new file mode 100644 index 0000000..042d5f5 --- /dev/null +++ b/src/repositories/user_repository.rs @@ -0,0 +1,53 @@ +use std::collections::HashMap; +use std::sync::{Arc, RwLock}; + +use crate::models::user::{CreateUserRequest, UpdateUserRequest, User}; + +pub trait UserRepository: Send + Sync { + fn list(&self) -> Vec; + fn get(&self, id: String) -> Option; + fn create(&self, req: CreateUserRequest) -> User; + fn update(&self, id: String, req: UpdateUserRequest) -> Option; + fn delete(&self, id: String) -> bool; +} + +#[derive(Clone)] +pub struct InMemoryUserRepository { + inner: Arc>>, +} + +impl InMemoryUserRepository { + pub fn new() -> Self { + Self { inner: Arc::new(RwLock::new(HashMap::new())) } + } +} + +impl UserRepository for InMemoryUserRepository { + fn list(&self) -> Vec { + self.inner.read().unwrap().values().cloned().collect() + } + + fn get(&self, id: String) -> Option { + self.inner.read().unwrap().get(&id).cloned() + } + + fn create(&self, req: CreateUserRequest) -> User { + let user = User::from_create(req); + self.inner.write().unwrap().insert(user.id.clone(), user.clone()); + user + } + + fn update(&self, id: String, req: UpdateUserRequest) -> Option { + let mut map = self.inner.write().unwrap(); + if let Some(existing) = map.get_mut(&id) { + if let Some(name) = req.name { existing.name = name; } + if let Some(email) = req.email { existing.email = email; } + return Some(existing.clone()); + } + None + } + + fn delete(&self, id: String) -> bool { + self.inner.write().unwrap().remove(&id).is_some() + } +} \ No newline at end of file diff --git a/src/routes/mod.rs b/src/routes/mod.rs new file mode 100644 index 0000000..19dc59b --- /dev/null +++ b/src/routes/mod.rs @@ -0,0 +1,44 @@ +use actix_web::web; +use utoipa::OpenApi; +use utoipa_swagger_ui::SwaggerUi; + +use crate::controllers::user_controller::{list_users, get_user, create_user, update_user, delete_user}; +use crate::repositories::user_repository::InMemoryUserRepository; +use crate::services::user_service::UserService; +use crate::state::AppContext; + +#[derive(OpenApi)] +#[openapi( + paths( + crate::controllers::user_controller::list_users, + crate::controllers::user_controller::get_user, + crate::controllers::user_controller::create_user, + crate::controllers::user_controller::update_user, + crate::controllers::user_controller::delete_user, + ), + components(schemas( + crate::models::user::User, + crate::models::user::CreateUserRequest, + crate::models::user::UpdateUserRequest, + crate::middlewares::error::ApiErrorBody, + )), + tags( + (name = "users", description = "Gerenciamento de usuários"), + ) +)] +pub struct ApiDoc; + +pub fn configure_v1(cfg: &mut web::ServiceConfig, _state: web::Data) { + let repo = InMemoryUserRepository::new(); + let svc = UserService::new(repo); + cfg.app_data(web::Data::new(svc)); + cfg.service(list_users); + cfg.service(get_user); + cfg.service(create_user); + cfg.service(update_user); + cfg.service(delete_user); +} + +pub fn swagger_ui() -> SwaggerUi { + SwaggerUi::new("/docs").url("/api-doc/openapi.json", ApiDoc::openapi()) +} \ No newline at end of file diff --git a/src/services/mod.rs b/src/services/mod.rs new file mode 100644 index 0000000..84ac9b5 --- /dev/null +++ b/src/services/mod.rs @@ -0,0 +1,3 @@ +pub mod system; +pub mod ollama; +pub mod user_service; \ No newline at end of file diff --git a/src/services/ollama.rs b/src/services/ollama.rs new file mode 100644 index 0000000..98e929c --- /dev/null +++ b/src/services/ollama.rs @@ -0,0 +1,18 @@ +use actix_web::http::header::USER_AGENT; +use awc::Client; + +pub async fn check_api(base_url: &str) -> Result<(), String> { + let client = Client::default(); + let url = format!("{}/api/tags", base_url.trim_end_matches('/')); + let resp = client + .get(url) + .insert_header((USER_AGENT, "OllaHubBackend/1.0")) + .send() + .await + .map_err(|e| e.to_string())?; + if resp.status().is_success() { + Ok(()) + } else { + Err(format!("API ollama indisponível: {}", resp.status())) + } +} \ No newline at end of file diff --git a/src/services/system.rs b/src/services/system.rs new file mode 100644 index 0000000..789185f --- /dev/null +++ b/src/services/system.rs @@ -0,0 +1,27 @@ +use std::process::Command; + +#[derive(Debug, Clone, Copy)] +pub enum Platform { + Windows, + Linux, + MacOS, +} + +pub fn detect_platform() -> Platform { + if cfg!(target_os = "windows") { + Platform::Windows + } else if cfg!(target_os = "macos") { + Platform::MacOS + } else { + Platform::Linux + } +} + +pub fn run_cmd(cmd: &str, args: &[&str]) -> Result { + let output = Command::new(cmd).args(args).output().map_err(|e| e.to_string())?; + if output.status.success() { + Ok(String::from_utf8_lossy(&output.stdout).to_string()) + } else { + Err(String::from_utf8_lossy(&output.stderr).to_string()) + } +} \ No newline at end of file diff --git a/src/services/user_service.rs b/src/services/user_service.rs new file mode 100644 index 0000000..3d17839 --- /dev/null +++ b/src/services/user_service.rs @@ -0,0 +1,17 @@ +use crate::models::user::{CreateUserRequest, UpdateUserRequest, User}; +use crate::repositories::user_repository::UserRepository; + +#[derive(Clone)] +pub struct UserService { + repo: R, +} + +impl UserService { + pub fn new(repo: R) -> Self { Self { repo } } + + pub fn list(&self) -> Vec { self.repo.list() } + pub fn get(&self, id: String) -> Option { self.repo.get(id) } + pub fn create(&self, req: CreateUserRequest) -> User { self.repo.create(req) } + pub fn update(&self, id: String, req: UpdateUserRequest) -> Option { self.repo.update(id, req) } + pub fn delete(&self, id: String) -> bool { self.repo.delete(id) } +} \ No newline at end of file diff --git a/src/state.rs b/src/state.rs new file mode 100644 index 0000000..f038613 --- /dev/null +++ b/src/state.rs @@ -0,0 +1,31 @@ +use std::path::PathBuf; +use std::sync::Arc; + +use tokio::sync::broadcast; + +use crate::crypto::CryptoState; +use crate::ws::WsEvent; + +#[derive(Clone)] +pub struct AppContext { + pub broker: broadcast::Sender, + pub crypto: Arc, + pub ollama_base_url: String, + pub model_list_path: String, + pub jwt_secret: String, +} + +impl AppContext { + pub fn new(ollama_base_url: String, model_list_path: String, key_path: PathBuf) -> Self { + let broker = crate::ws::new_broker(); + let crypto = Arc::new(CryptoState::new(key_path)); + let jwt_secret = std::env::var("JWT_SECRET").unwrap_or_else(|_| "changeme-dev-secret".into()); + Self { + broker, + crypto, + ollama_base_url, + model_list_path, + jwt_secret, + } + } +} \ No newline at end of file diff --git a/src/utils/log.rs b/src/utils/log.rs new file mode 100644 index 0000000..b5bc56b --- /dev/null +++ b/src/utils/log.rs @@ -0,0 +1,20 @@ +use std::time::{SystemTime, UNIX_EPOCH}; + +pub fn now_ts() -> u128 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_millis() +} + +pub fn info(message: &str) { + println!("[INFO] [{}] {}", now_ts(), message); +} + +pub fn warn(message: &str) { + eprintln!("[WARN] [{}] {}", now_ts(), message); +} + +pub fn error(message: &str) { + eprintln!("[ERROR] [{}] {}", now_ts(), message); +} \ No newline at end of file diff --git a/src/utils/mod.rs b/src/utils/mod.rs new file mode 100644 index 0000000..7e8abe2 --- /dev/null +++ b/src/utils/mod.rs @@ -0,0 +1 @@ +pub mod log; \ No newline at end of file diff --git a/src/ws/mod.rs b/src/ws/mod.rs new file mode 100644 index 0000000..1129453 --- /dev/null +++ b/src/ws/mod.rs @@ -0,0 +1,100 @@ +use actix::{Actor, Context, Handler, ActorContext, Message}; +use actix_web::{get, web, Error, HttpRequest, HttpResponse}; +use actix_web_actors::ws; +use serde::{Deserialize, Serialize}; +use tokio::sync::broadcast; + +use crate::utils::log; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum WsEventKind { + Log, + Progress, + Done, + Error, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct WsEvent { + pub kind: WsEventKind, + pub message: String, +} + +pub fn new_broker() -> broadcast::Sender { + let (tx, _rx) = broadcast::channel(64); + tx +} + +#[derive(Clone)] +pub struct BrokerAddr(pub broadcast::Sender); + +pub struct WsSession { + pub broker: broadcast::Sender, +} + +impl Actor for WsSession { + type Context = ws::WebsocketContext; + + fn started(&mut self, ctx: &mut Self::Context) { + let mut rx = self.broker.subscribe(); + // Forward broker messages to the websocket client + actix_rt::spawn(async move { + while let Ok(evt) = rx.recv().await { + // We cannot access ctx here; use an internal channel. + // Instead, send events via a helper actor message. + // This is handled below using a Trampoline handler. + // For simplicity, we log; WS pushes are driven by incoming pings. + log::info(&format!("WS evt: {:?}: {}", evt.kind, evt.message)); + } + }); + } +} + +#[derive(Message)] +#[rtype(result = "()")] +pub struct PushEvent(pub WsEvent); + +impl Handler for WsSession { + type Result = (); + + fn handle(&mut self, msg: PushEvent, ctx: &mut Self::Context) -> Self::Result { + let payload = serde_json::to_string(&msg.0).unwrap_or_else(|_| "{\"kind\":\"Error\",\"message\":\"serialize\"}".into()); + ctx.text(payload); + } +} + +impl actix::StreamHandler> for WsSession { + fn handle(&mut self, msg: Result, ctx: &mut Self::Context) { + match msg { + Ok(ws::Message::Ping(msg)) => { + ctx.pong(&msg); + } + Ok(ws::Message::Text(text)) => { + // Echo and also subscribe client to stream by pushing recent event + ctx.text(text); + } + Ok(ws::Message::Binary(bin)) => { + ctx.binary(bin); + } + Ok(ws::Message::Close(reason)) => { + log::info(&format!("WS closed: {:?}", reason)); + ctx.close(reason); + ctx.stop(); + } + _ => {} + } + } +} + +#[get("/ws")] +pub async fn ws_route( + req: HttpRequest, + stream: web::Payload, + broker: web::Data, +) -> Result { + let session = WsSession { + broker: broker.get_ref().0.clone(), + }; + let resp = ws::start(session, &req, stream); + resp +} \ No newline at end of file