Initial Files

Initial Files

initial files

Add git LFS for meilisearch binaries

Update README.md

fix
This commit is contained in:
Damien Ostler 2024-10-01 22:41:07 -04:00
commit def261660d
22 changed files with 1223 additions and 0 deletions

25
.dockerignore Normal file
View File

@ -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

7
.gitattributes vendored Normal file
View File

@ -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

495
.gitignore vendored Normal file
View File

@ -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

103
README.md Normal file
View File

@ -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. Heres 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.

View File

@ -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"]

View File

@ -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<test>();
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();
}
}

View File

@ -0,0 +1,13 @@
{
"Meili": {
"Port": 7700,
"UiEnabled" : true
},
"Logging": {
"LogLevel": {
"Default": "Trace",
"Microsoft.AspNetCore": "Trace"
}
},
"AllowedHosts": "*"
}

View File

@ -0,0 +1,31 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>
<ItemGroup>
<Content Include="..\.dockerignore">
<Link>.dockerignore</Link>
</Content>
<None Remove="appsettings.json" />
<Content Include="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\meilisearch.NET\meilisearch.NET.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />
</ItemGroup>
</Project>

22
meilisearch.NET.sln Normal file
View File

@ -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

View File

@ -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();
}
}

View File

@ -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<int>(_meiliPort);
public bool UiEnabled => _configuration.GetValue<bool>(_meiliUiEnabled);
}

View File

@ -0,0 +1,10 @@
namespace meilisearch.NET.Enums;
public enum MeiliSearchStatus
{
Stopped,
Starting,
Running,
Stopping,
Crashed
}

View File

@ -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<MeiliSearchService>();
services.AddSingleton<MeiliSearchConfiguration>();
services.AddSingleton<IMeiliSearchService, MeiliSearchService>();
return services;
}
}

View File

@ -0,0 +1,74 @@
using Meilisearch;
using meilisearch.NET.Enums;
namespace meilisearch.NET.Interfaces;
public interface IMeiliSearchService
{
/// <summary>
/// Checks if the Meilisearch server is healthy.
/// </summary>
/// <returns>True if healthy, false if not.</returns>
public bool HealthCheck(object? state);
/// <summary>
/// This is the SDK for Meilisearch. It is used to interact with the Meilisearch server.
/// </summary>
public MeilisearchClient Sdk { get; set; }
/// <summary>
/// This is the status of the Meilisearch server. It is used to check if the server is running or not.
/// </summary>
public MeiliSearchStatus Status { get; set; }
/// <summary>
/// Refreshes the API key. This is useful if you want to change the API key for security reasons.
/// </summary>
public void RefreshApiKey();
/// <summary>
/// This will start the Meilisearch server. This is useful if you want to start the server without starting the application.
/// </summary>
public void Start();
/// <summary>
/// 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.
/// </summary>
public void Restart();
/// <summary>
/// This will stop the Meilisearch server. This is useful if you want to stop the server without stopping the application.
/// </summary>
public void Stop();
/// <summary>
/// This will list all of the indexes regardless if they are loaded or unloaded.
/// </summary>
/// <returns></returns>
public List<string> ListIndexs();
/// <summary>
/// Creates a index and adds a .name file so that we can track the name of the index.
/// </summary>
/// <returns></returns>
public Meilisearch.Index CreateIndex();
/// <summary>
/// Loads a index and uncompresses it.
/// </summary>
/// <param name="indexId">The ID of the index to load.</param>
public void LoadIndex(string indexId);
/// <summary>
/// Unloads a index and compresses it.
/// </summary>
/// <param name="indexId">The ID of the index to unload.</param>
public void UnloadIndex(string indexId);
/// <summary>
/// This will delete a index and remove the .name file.
/// </summary>
/// <param name="indexId">The ID of the index to delete.</param>
public void DeleteIndex(string indexId);
}

View File

@ -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<MeiliSearchService> _logger;
private readonly HttpClient _sdkHttpClient;
private Timer _healthCheckTimer;
private Process? _process;
public MeiliSearchService(HttpClient httpClient, ILogger<MeiliSearchService> 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<string> 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();
}
}

View File

@ -0,0 +1,7 @@
namespace meilisearch.NET.Models;
public class Index
{
public string Id { get; set; }
public string Name { get; set; }
}

BIN
meilisearch.NET/meilisearch-linux-arm (Stored with Git LFS) Normal file

Binary file not shown.

BIN
meilisearch.NET/meilisearch-linux-x64 (Stored with Git LFS) Normal file

Binary file not shown.

BIN
meilisearch.NET/meilisearch-macos-arm (Stored with Git LFS) Normal file

Binary file not shown.

BIN
meilisearch.NET/meilisearch-macos-x64 (Stored with Git LFS) Normal file

Binary file not shown.

BIN
meilisearch.NET/meilisearch-windows.exe (Stored with Git LFS) Normal file

Binary file not shown.

View File

@ -0,0 +1,43 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>meilisearch.NET</RootNamespace>
</PropertyGroup>
<ItemGroup>
<None Remove="meilisearch-linux-arm" />
<Content Include="meilisearch-linux-arm">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<None Remove="meilisearch-linux-x64" />
<Content Include="meilisearch-linux-x64">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<None Remove="meilisearch-macos-arm" />
<Content Include="meilisearch-macos-arm">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<None Remove="meilisearch-macos-x64" />
<Content Include="meilisearch-macos-x64">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<None Remove="meilisearch-windows.exe" />
<Content Include="meilisearch-windows.exe">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference Include="MeiliSearch" Version="0.15.3" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.2" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.1" />
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<PackageReference Include="System.Text.Json" Version="8.0.4" />
</ItemGroup>
</Project>