From def261660d3b07724d6842c7dc0bc7c7c9862387 Mon Sep 17 00:00:00 2001 From: Damien Ostler Date: Tue, 1 Oct 2024 22:41:07 -0400 Subject: [PATCH] Initial Files Initial Files initial files Add git LFS for meilisearch binaries Update README.md fix --- .dockerignore | 25 + .gitattributes | 7 + .gitignore | 495 ++++++++++++++++++ README.md | 103 ++++ meilisearch.NET.example/Dockerfile | 21 + meilisearch.NET.example/Program.cs | 30 ++ meilisearch.NET.example/appsettings.json | 13 + .../meilisearch.NET.example.csproj | 31 ++ meilisearch.NET.sln | 22 + meilisearch.NET/ApiKeyGenerator.cs | 22 + .../MeiliSearchConfiguration.cs | 16 + meilisearch.NET/Enums/MeiliSearchStatus.cs | 10 + .../Extensions/ServiceCollectionExtension.cs | 16 + .../Interfaces/IMeiliSearchService.cs | 74 +++ meilisearch.NET/MeiliSearchService.cs | 273 ++++++++++ meilisearch.NET/Models/Index.cs | 7 + meilisearch.NET/meilisearch-linux-arm | 3 + meilisearch.NET/meilisearch-linux-x64 | 3 + meilisearch.NET/meilisearch-macos-arm | 3 + meilisearch.NET/meilisearch-macos-x64 | 3 + meilisearch.NET/meilisearch-windows.exe | 3 + meilisearch.NET/meilisearch.NET.csproj | 43 ++ 22 files changed, 1223 insertions(+) create mode 100644 .dockerignore create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 README.md create mode 100644 meilisearch.NET.example/Dockerfile create mode 100644 meilisearch.NET.example/Program.cs create mode 100644 meilisearch.NET.example/appsettings.json create mode 100644 meilisearch.NET.example/meilisearch.NET.example.csproj create mode 100644 meilisearch.NET.sln create mode 100644 meilisearch.NET/ApiKeyGenerator.cs create mode 100644 meilisearch.NET/Configurations/MeiliSearchConfiguration.cs create mode 100644 meilisearch.NET/Enums/MeiliSearchStatus.cs create mode 100644 meilisearch.NET/Extensions/ServiceCollectionExtension.cs create mode 100644 meilisearch.NET/Interfaces/IMeiliSearchService.cs create mode 100644 meilisearch.NET/MeiliSearchService.cs create mode 100644 meilisearch.NET/Models/Index.cs create mode 100644 meilisearch.NET/meilisearch-linux-arm create mode 100644 meilisearch.NET/meilisearch-linux-x64 create mode 100644 meilisearch.NET/meilisearch-macos-arm create mode 100644 meilisearch.NET/meilisearch-macos-x64 create mode 100644 meilisearch.NET/meilisearch-windows.exe create mode 100644 meilisearch.NET/meilisearch.NET.csproj diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..38bece4 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,25 @@ +**/.dockerignore +**/.env +**/.git +**/.gitignore +**/.project +**/.settings +**/.toolstarget +**/.vs +**/.vscode +**/.idea +**/*.*proj.user +**/*.dbmdl +**/*.jfm +**/azds.yaml +**/bin +**/charts +**/docker-compose* +**/Dockerfile* +**/node_modules +**/npm-debug.log +**/obj +**/secrets.dev.yaml +**/values.dev.yaml +LICENSE +README.md \ No newline at end of file diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..7628ca8 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,7 @@ +meilisearch.NET/meilisearch-linux-arm filter=lfs diff=lfs merge=lfs -text +meilisearch.NET/meilisearch-linux-x64 filter=lfs diff=lfs merge=lfs -text +meilisearch.NET/meilisearch-mac-arm filter=lfs diff=lfs merge=lfs -text +meilisearch.NET/meilisearch-mac-x64 filter=lfs diff=lfs merge=lfs -text +meilisearch.NET/meilisearch-windows.exe filter=lfs diff=lfs merge=lfs -text +meilisearch-macos-arm filter=lfs diff=lfs merge=lfs -text +meilisearch-macos-x64 filter=lfs diff=lfs merge=lfs -text diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..88f7196 --- /dev/null +++ b/.gitignore @@ -0,0 +1,495 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Rider ignored files +/modules.xml +/.idea.PersonalDataTool.iml +/contentModel.xml +/projectSettingsUpdater.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates +.idea/ +.mono/ + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET +project.lock.json +project.fragment.lock.json +artifacts/ + +# Tye +.tye/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml + +## +## Visual studio for Mac +## + + +# globs +Makefile.in +*.userprefs +*.usertasks +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.tar.gz +tarballs/ +test-results/ + +# Mac bundle stuff +*.dmg +*.app + +# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk +src/Data443.Api.WebApi.Tests/test-result.xml +/postgres-data +PDT/meilisearch diff --git a/README.md b/README.md new file mode 100644 index 0000000..20b6b05 --- /dev/null +++ b/README.md @@ -0,0 +1,103 @@ +# MeiliSearch .NET Embedded + +[![NuGet Version](https://img.shields.io/nuget/v/YourPackageName.svg)](https://www.nuget.org/packages/YourPackageName) +[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) + +## Overview + +MeiliSearch .NET Integration is a NuGet package that seamlessly embeds MeiliSearch into your C# application. It manages the background process and health checks for you, simplifying the integration of full-text search capabilities. In future updates, it will also handle automatic compression and decompression of indexes to help manage local storage usage effectively. + +## Features + +- **Embedded MeiliSearch**: Integrate MeiliSearch directly into your application. +- **Background Process Management**: Automatically handles the lifecycle of the MeiliSearch process. +- **Health Monitoring**: Regular checks on the health of the MeiliSearch instance. +- **API Key Management**: An API key is automatically regenerated every time the MeiliSearch service starts unless one is specified in the configuration. +- **Resource Monitoring**: Monitor the resources being used including storage by your MeiliSearch. +- **Future Index Management**: Upcoming feature to automatically compress and decompress indexes for optimized local storage. + +## Installation + +To add the MeiliSearch .NET Integration package to your project, use the following command in the Package Manager Console: + +```bash +Install-Package YourPackageName +``` + +Or, if you're using the .NET CLI: + +```bash +dotnet add package YourPackageName +``` + +## Configuration + +To configure the MeiliSearch service, add the following section to your `appsettings.json` file: + +```json +{ + ... + "Meili": { + "Port": 7700, + "UiEnabled": true, + "ApiKey": "YourOptionalApiKey" // Specify this if you want a fixed API key + }, + ... + "Logging": { + "LogLevel": { + "Default": "Trace", + "Microsoft.AspNetCore": "Trace" + } + }, + "AllowedHosts": "*" +} +``` + +### AppSettings Options + +- **Port**: The port on which MeiliSearch will run (default is `7700`). +- **UiEnabled**: A boolean value to enable or disable the MeiliSearch UI (default is `true`). +- **ApiKey**: An optional API key. If specified, this key will be used; otherwise, a new key will be generated each time the service starts. + +## Usage + +To set up the MeiliSearch service in your application, you'll need to configure dependency injection. Here’s an example of how to do that: + +```csharp +using System.Net; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +ServicePointManager.SecurityProtocol = SecurityProtocolType.SystemDefault; + +var builder = Host.CreateApplicationBuilder(); +builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); +builder.Services.AddMeiliSearchService(); +builder.Logging.ClearProviders(); +builder.Logging.AddConsole(); +builder.Logging.SetMinimumLevel(LogLevel.Information); +builder.Services.AddLogging(); + +var app = builder.Build(); +app.Run(); +Console.ReadLine(); +``` + +## License + +This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. + +## Contributing + +We welcome contributions! Please feel free to submit issues, pull requests, or suggestions to improve this project. + +## Support + +For any issues or questions, please open an issue on GitHub or contact us via [your contact method]. + +--- + +Feel free to customize this README as necessary for your package, especially regarding the project name and license details! +``` + +This revision includes details about the API key regeneration and how to specify a fixed API key if desired. \ No newline at end of file diff --git a/meilisearch.NET.example/Dockerfile b/meilisearch.NET.example/Dockerfile new file mode 100644 index 0000000..9784f9b --- /dev/null +++ b/meilisearch.NET.example/Dockerfile @@ -0,0 +1,21 @@ +FROM mcr.microsoft.com/dotnet/runtime:8.0 AS base +USER $APP_UID +WORKDIR /app + +FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build +ARG BUILD_CONFIGURATION=Release +WORKDIR /src +COPY ["meilisearch.embedded.NET.console/meilisearch.embedded.NET.console.csproj", "meilisearch.embedded.NET.console/"] +RUN dotnet restore "meilisearch.embedded.NET.console/meilisearch.embedded.NET.console.csproj" +COPY . . +WORKDIR "/src/meilisearch.embedded.NET.console" +RUN dotnet build "meilisearch.embedded.NET.console.csproj" -c $BUILD_CONFIGURATION -o /app/build + +FROM build AS publish +ARG BUILD_CONFIGURATION=Release +RUN dotnet publish "meilisearch.embedded.NET.console.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false + +FROM base AS final +WORKDIR /app +COPY --from=publish /app/publish . +ENTRYPOINT ["dotnet", "meilisearch.embedded.NET.console.dll"] diff --git a/meilisearch.NET.example/Program.cs b/meilisearch.NET.example/Program.cs new file mode 100644 index 0000000..f07bddb --- /dev/null +++ b/meilisearch.NET.example/Program.cs @@ -0,0 +1,30 @@ +using System.Net; +using meilisearch.NET; +using meilisearch.NET.Configurations; +using meilisearch.NET.Extensions; +using meilisearch.NET.Interfaces; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +ServicePointManager.SecurityProtocol = SecurityProtocolType.SystemDefault; +var builder = Host.CreateApplicationBuilder(); +builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); +builder.Services.AddMeiliSearchService(); +builder.Services.AddSingleton(); +builder.Logging.ClearProviders(); +builder.Logging.AddConsole(); +builder.Logging.SetMinimumLevel(LogLevel.Information); +builder.Services.AddLogging(); +var app = builder.Build(); +app.Run(); +Console.ReadLine(); + +public class test +{ + public test(IMeiliSearchService service) + { + service.Start(); + } +} \ No newline at end of file diff --git a/meilisearch.NET.example/appsettings.json b/meilisearch.NET.example/appsettings.json new file mode 100644 index 0000000..c82f26f --- /dev/null +++ b/meilisearch.NET.example/appsettings.json @@ -0,0 +1,13 @@ +{ + "Meili": { + "Port": 7700, + "UiEnabled" : true + }, + "Logging": { + "LogLevel": { + "Default": "Trace", + "Microsoft.AspNetCore": "Trace" + } + }, + "AllowedHosts": "*" +} diff --git a/meilisearch.NET.example/meilisearch.NET.example.csproj b/meilisearch.NET.example/meilisearch.NET.example.csproj new file mode 100644 index 0000000..c13fa37 --- /dev/null +++ b/meilisearch.NET.example/meilisearch.NET.example.csproj @@ -0,0 +1,31 @@ + + + + Exe + net8.0 + enable + enable + Linux + + + + + .dockerignore + + + + Always + + + + + + + + + + + + + + diff --git a/meilisearch.NET.sln b/meilisearch.NET.sln new file mode 100644 index 0000000..147cf43 --- /dev/null +++ b/meilisearch.NET.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "meilisearch.NET", "meilisearch.NET\meilisearch.NET.csproj", "{BE391DCC-6285-44E2-ADA0-26EB5B7DC8D6}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "meilisearch.NET.example", "meilisearch.NET.example\meilisearch.NET.example.csproj", "{E753BBD6-6ADF-4DD4-8822-7279CD55DF58}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {BE391DCC-6285-44E2-ADA0-26EB5B7DC8D6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BE391DCC-6285-44E2-ADA0-26EB5B7DC8D6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BE391DCC-6285-44E2-ADA0-26EB5B7DC8D6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BE391DCC-6285-44E2-ADA0-26EB5B7DC8D6}.Release|Any CPU.Build.0 = Release|Any CPU + {E753BBD6-6ADF-4DD4-8822-7279CD55DF58}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E753BBD6-6ADF-4DD4-8822-7279CD55DF58}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E753BBD6-6ADF-4DD4-8822-7279CD55DF58}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E753BBD6-6ADF-4DD4-8822-7279CD55DF58}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/meilisearch.NET/ApiKeyGenerator.cs b/meilisearch.NET/ApiKeyGenerator.cs new file mode 100644 index 0000000..fb4ee1f --- /dev/null +++ b/meilisearch.NET/ApiKeyGenerator.cs @@ -0,0 +1,22 @@ +using System.Text; + +namespace meilisearch.NET; + +public class ApiKeyGenerator +{ + private static readonly char[] Chars = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".ToCharArray(); + + public static string GenerateApiKey(int length = 64) + { + var random = new Random(); + var apiKey = new StringBuilder(length); + + for (int i = 0; i < length; i++) + { + apiKey.Append(Chars[random.Next(Chars.Length)]); + } + + return apiKey.ToString(); + } +} \ No newline at end of file diff --git a/meilisearch.NET/Configurations/MeiliSearchConfiguration.cs b/meilisearch.NET/Configurations/MeiliSearchConfiguration.cs new file mode 100644 index 0000000..6a70c9e --- /dev/null +++ b/meilisearch.NET/Configurations/MeiliSearchConfiguration.cs @@ -0,0 +1,16 @@ +using Microsoft.Extensions.Configuration; + +namespace meilisearch.NET.Configurations; + +public class MeiliSearchConfiguration +{ + private readonly string _meiliPort = "Meili:Port"; + private readonly string _meiliUiEnabled = "Meili:UiEnabled"; + private readonly IConfiguration _configuration; + public MeiliSearchConfiguration(IConfiguration configuration) + { + _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); + } + public int MeiliPort => _configuration.GetValue(_meiliPort); + public bool UiEnabled => _configuration.GetValue(_meiliUiEnabled); +} \ No newline at end of file diff --git a/meilisearch.NET/Enums/MeiliSearchStatus.cs b/meilisearch.NET/Enums/MeiliSearchStatus.cs new file mode 100644 index 0000000..a821a00 --- /dev/null +++ b/meilisearch.NET/Enums/MeiliSearchStatus.cs @@ -0,0 +1,10 @@ +namespace meilisearch.NET.Enums; + +public enum MeiliSearchStatus +{ + Stopped, + Starting, + Running, + Stopping, + Crashed +} \ No newline at end of file diff --git a/meilisearch.NET/Extensions/ServiceCollectionExtension.cs b/meilisearch.NET/Extensions/ServiceCollectionExtension.cs new file mode 100644 index 0000000..424b1a2 --- /dev/null +++ b/meilisearch.NET/Extensions/ServiceCollectionExtension.cs @@ -0,0 +1,16 @@ +using meilisearch.NET.Configurations; +using meilisearch.NET.Interfaces; +using Microsoft.Extensions.DependencyInjection; + +namespace meilisearch.NET.Extensions; + +public static class ServiceCollectionExtension +{ + public static IServiceCollection AddMeiliSearchService(this IServiceCollection services) + { + services.AddHttpClient(); + services.AddSingleton(); + services.AddSingleton(); + return services; + } +} \ No newline at end of file diff --git a/meilisearch.NET/Interfaces/IMeiliSearchService.cs b/meilisearch.NET/Interfaces/IMeiliSearchService.cs new file mode 100644 index 0000000..1dcbdab --- /dev/null +++ b/meilisearch.NET/Interfaces/IMeiliSearchService.cs @@ -0,0 +1,74 @@ +using Meilisearch; +using meilisearch.NET.Enums; + +namespace meilisearch.NET.Interfaces; + +public interface IMeiliSearchService +{ + /// + /// Checks if the Meilisearch server is healthy. + /// + /// True if healthy, false if not. + public bool HealthCheck(object? state); + + /// + /// This is the SDK for Meilisearch. It is used to interact with the Meilisearch server. + /// + public MeilisearchClient Sdk { get; set; } + + /// + /// This is the status of the Meilisearch server. It is used to check if the server is running or not. + /// + public MeiliSearchStatus Status { get; set; } + + /// + /// Refreshes the API key. This is useful if you want to change the API key for security reasons. + /// + public void RefreshApiKey(); + + /// + /// This will start the Meilisearch server. This is useful if you want to start the server without starting the application. + /// + public void Start(); + + /// + /// This will restart the Meilisearch server. This is useful if you have made changes to the server and want to apply them without restarting the application. + /// + public void Restart(); + + /// + /// This will stop the Meilisearch server. This is useful if you want to stop the server without stopping the application. + /// + public void Stop(); + + /// + /// This will list all of the indexes regardless if they are loaded or unloaded. + /// + /// + public List ListIndexs(); + + /// + /// Creates a index and adds a .name file so that we can track the name of the index. + /// + /// + public Meilisearch.Index CreateIndex(); + + /// + /// Loads a index and uncompresses it. + /// + /// The ID of the index to load. + public void LoadIndex(string indexId); + + /// + /// Unloads a index and compresses it. + /// + /// The ID of the index to unload. + public void UnloadIndex(string indexId); + + /// + /// This will delete a index and remove the .name file. + /// + /// The ID of the index to delete. + public void DeleteIndex(string indexId); + +} \ No newline at end of file diff --git a/meilisearch.NET/MeiliSearchService.cs b/meilisearch.NET/MeiliSearchService.cs new file mode 100644 index 0000000..9bcc875 --- /dev/null +++ b/meilisearch.NET/MeiliSearchService.cs @@ -0,0 +1,273 @@ +using System.Diagnostics; +using System.Net.Sockets; +using System.Runtime.InteropServices; +using System.Security; +using Meilisearch; +using meilisearch.NET.Configurations; +using meilisearch.NET.Enums; +using meilisearch.NET.Extensions; +using meilisearch.NET.Interfaces; +using Microsoft.Extensions.Logging; +using Index = Meilisearch.Index; + +namespace meilisearch.NET; + + +public class MeiliSearchService:IMeiliSearchService +{ + + public MeilisearchClient Sdk { get; set; } + public MeiliSearchStatus Status { get; set; } + + private readonly MeiliSearchConfiguration _meiliSearchConfiguration; + private readonly ProcessStartInfo _processStartInfo; + private readonly ILogger _logger; + private readonly HttpClient _sdkHttpClient; + + private Timer _healthCheckTimer; + private Process? _process; + + public MeiliSearchService(HttpClient httpClient, ILogger logger, MeiliSearchConfiguration meiliSearchConfiguration) + { + _logger = logger; + _meiliSearchConfiguration = meiliSearchConfiguration; + var binaryName = GetBinaryName(); + MakeExecutable(Path.Combine(AppContext.BaseDirectory, binaryName)); + var apiKey = ApiKeyGenerator.GenerateApiKey(); + _sdkHttpClient = httpClient; + _sdkHttpClient.BaseAddress = new Uri("http://localhost:"+meiliSearchConfiguration.MeiliPort); + Sdk = new MeilisearchClient(httpClient, apiKey); + var path = Path.Combine(AppContext.BaseDirectory, binaryName); + var args = "--http-addr 127.0.0.1:" + _meiliSearchConfiguration.MeiliPort + + " --master-key "+apiKey + + " --env "+(_meiliSearchConfiguration.UiEnabled ? "development" : "production") + +" --db-path "+GetDataLocation(); + _processStartInfo = new ProcessStartInfo + { + FileName = path, + Arguments = args, + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + CreateNoWindow = true + }; + Status = MeiliSearchStatus.Stopped; + _logger?.LogInformation($"Meilisearch service initialized with the UI {(_meiliSearchConfiguration.UiEnabled ? "Enabled" : "Disabled)")} with database located at {GetDataLocation()}."); + } + + + + private static void MakeExecutable(string filePath) + { + if (string.IsNullOrWhiteSpace(filePath)) + { + throw new ArgumentException("File path cannot be null or empty.", nameof(filePath)); + } + + // Check if the file exists + if (!File.Exists(filePath)) + { + throw new FileNotFoundException($"The file '{filePath}' does not exist.", filePath); + } + + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + // For Linux and macOS, use chmod +x + ExecuteCommand($"chmod +x \"{filePath}\""); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + } + else + { + throw new PlatformNotSupportedException("This platform is not supported."); + } + + Console.WriteLine($"File '{filePath}' has been made executable."); + } + private static void ExecuteCommand(string command) + { + var processStartInfo = new ProcessStartInfo + { + FileName = "/bin/bash", // Use bash for Linux and macOS + Arguments = $"-c \"{command}\"", + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true + }; + + using (var process = Process.Start(processStartInfo)) + { + process.WaitForExit(); + + // Optionally handle output and errors + string output = process.StandardOutput.ReadToEnd(); + string error = process.StandardError.ReadToEnd(); + + if (process.ExitCode != 0) + { + throw new InvalidOperationException($"Error executing command: {error}"); + } + } + } + private static string GetDataLocation() + { + return Path.Combine(AppContext.BaseDirectory, "data"); + string appDataDirectory; + + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + appDataDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "MeiliSearchEmbedded"); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + appDataDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "Library", "Application Support", "MeiliSearchEmbedded"); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + appDataDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), ".config", "MeiliSearchEmbedded"); + } + else + { + throw new PlatformNotSupportedException("Unsupported OS."); + } + return appDataDirectory; + } + private static string GetBinaryName() + { + string os = RuntimeInformation.OSDescription.ToLowerInvariant(); + string architecture = RuntimeInformation.ProcessArchitecture.ToString().ToLowerInvariant(); + string platform; + + if (os.Contains("linux")) + { + platform = "meilisearch-linux-" + (architecture.Contains("arm") ? "arm" : "x64"); + } + else if (os.Contains("macos") || os.Contains("darwin")) + { + platform = "meilisearch-macos-" + (architecture.Contains("arm") ? "arm" : "x64"); + } + else if (os.Contains("windows")) + { + platform = "meilisearch-windows.exe"; + } + else + { + throw new PlatformNotSupportedException("Operating system not supported."); + } + + return platform; + } + private bool MeilisSearchReachable() + { + string host = "127.0.0.1"; // localhost + int port = _meiliSearchConfiguration.MeiliPort; + try + { + using (TcpClient client = new TcpClient()) + { + client.Connect(host, port); + return true; + } + } + catch + { + return false; + } + } + + public bool HealthCheck(object? state) + { + if (_process == null) + throw new Exception("Meilisearch process is not running."); + var responding = _process.Responding; + var exited = _process.HasExited || _process.ExitCode == 0; + var reachable = MeilisSearchReachable(); + return responding && exited && reachable; + } + + public void RefreshApiKey() + { + _logger.LogInformation("Refreshing API key."); + var apiKey = ApiKeyGenerator.GenerateApiKey(); + Sdk = new MeilisearchClient(_sdkHttpClient, apiKey); + _logger.LogInformation("New API key generated."); + Restart(); + } + + public void Start() + { + _logger.LogInformation("Starting MeiliSearch process."); + Status = MeiliSearchStatus.Starting; + _process = new Process { StartInfo = _processStartInfo }; + + try + { + _process.Start(); + Status = MeiliSearchStatus.Running; + _logger.LogInformation("MeiliSearch process started successfully."); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to start MeiliSearch process."); + throw; + } + } + + public void Restart() + { + _logger.LogInformation("Restarting MeiliSearch process."); + Stop(); + Start(); + } + + public void Stop() + { + if (_process == null) + { + _logger.LogWarning("Attempted to stop MeiliSearch process, but it is not running."); + throw new Exception("Meilisearch process is not running."); + } + + _logger.LogInformation("Stopping MeiliSearch process."); + Status = MeiliSearchStatus.Stopping; + + try + { + _process.Kill(); + Status = MeiliSearchStatus.Stopped; + _logger.LogInformation("MeiliSearch process stopped successfully."); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to stop MeiliSearch process."); + throw; + } + } + + public List ListIndexs() + { + throw new NotImplementedException(); + } + + public Index CreateIndex() + { + throw new NotImplementedException(); + } + + public void LoadIndex(string indexId) + { + throw new NotImplementedException(); + } + + public void UnloadIndex(string indexId) + { + throw new NotImplementedException(); + } + + public void DeleteIndex(string indexId) + { + throw new NotImplementedException(); + } +} \ No newline at end of file diff --git a/meilisearch.NET/Models/Index.cs b/meilisearch.NET/Models/Index.cs new file mode 100644 index 0000000..833db4c --- /dev/null +++ b/meilisearch.NET/Models/Index.cs @@ -0,0 +1,7 @@ +namespace meilisearch.NET.Models; + +public class Index +{ + public string Id { get; set; } + public string Name { get; set; } +} \ No newline at end of file diff --git a/meilisearch.NET/meilisearch-linux-arm b/meilisearch.NET/meilisearch-linux-arm new file mode 100644 index 0000000..40ba91f --- /dev/null +++ b/meilisearch.NET/meilisearch-linux-arm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0d67fc81232bcfad2ee748af8fcc888584b3f42ffbde816b5aa8e850abeaf545 +size 119206160 diff --git a/meilisearch.NET/meilisearch-linux-x64 b/meilisearch.NET/meilisearch-linux-x64 new file mode 100644 index 0000000..5e425c8 --- /dev/null +++ b/meilisearch.NET/meilisearch-linux-x64 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:55bd847a256899214a08373491fc1484a977b6ac79033151551388f27bebc3fb +size 120759528 diff --git a/meilisearch.NET/meilisearch-macos-arm b/meilisearch.NET/meilisearch-macos-arm new file mode 100644 index 0000000..423a437 --- /dev/null +++ b/meilisearch.NET/meilisearch-macos-arm @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:464f6704156121e9835e3747ae91e72e259ef28a5f54b7b07f009ff633763e61 +size 114404272 diff --git a/meilisearch.NET/meilisearch-macos-x64 b/meilisearch.NET/meilisearch-macos-x64 new file mode 100644 index 0000000..81a3a9b --- /dev/null +++ b/meilisearch.NET/meilisearch-macos-x64 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:98abbf54ce9745ffa12990f0fcfeaf3e4d321c783a1553649f12dca31eab9fd8 +size 116380480 diff --git a/meilisearch.NET/meilisearch-windows.exe b/meilisearch.NET/meilisearch-windows.exe new file mode 100644 index 0000000..3793328 --- /dev/null +++ b/meilisearch.NET/meilisearch-windows.exe @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2de2d0cee0f6d8d3be5080b4e4506d31ed5a36104d24e9e5d1af087f761ce41c +size 116287488 diff --git a/meilisearch.NET/meilisearch.NET.csproj b/meilisearch.NET/meilisearch.NET.csproj new file mode 100644 index 0000000..8f54cdd --- /dev/null +++ b/meilisearch.NET/meilisearch.NET.csproj @@ -0,0 +1,43 @@ + + + + net8.0 + enable + enable + meilisearch.NET + + + + + + PreserveNewest + + + + PreserveNewest + + + + PreserveNewest + + + + PreserveNewest + + + + Always + + + + + + + + + + + + + +