fix: index creation/deletion + added store of folder ID for index database to be able to compress it

This commit is contained in:
Damien 2025-02-25 01:29:01 -05:00
parent 81ffe6285f
commit 6e4e491675
3 changed files with 35 additions and 38 deletions

View File

@ -13,29 +13,19 @@ public class Program
{ {
public static async Task Main(string[] args) public static async Task Main(string[] args)
{ {
// Set security protocol to SystemDefault
ServicePointManager.SecurityProtocol = SecurityProtocolType.SystemDefault; ServicePointManager.SecurityProtocol = SecurityProtocolType.SystemDefault;
// Configure and build the host
IHost host = CreateHostBuilder(args).Build(); IHost host = CreateHostBuilder(args).Build();
//Resolve test dependency
var testService = host.Services.GetService<test>(); var testService = host.Services.GetService<test>();
// Run the host
await host.RunAsync(); await host.RunAsync();
} }
public static IHostBuilder CreateHostBuilder(string[] args) => public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args) Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, configuration) => .ConfigureAppConfiguration((hostingContext, configuration) =>
{ {
configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
configuration.AddEnvironmentVariables(); // Add environment variables as well (optional, but good practice) configuration.AddEnvironmentVariables();
configuration.AddCommandLine(args); // Support command line arguments configuration.AddCommandLine(args);
}) })
.ConfigureServices((hostContext, services) => .ConfigureServices((hostContext, services) =>
{ {
@ -52,7 +42,7 @@ public class Program
}) })
.UseConsoleLifetime(options => .UseConsoleLifetime(options =>
{ {
options.SuppressStatusMessages = true; // This is optional: you can suppress the "Application started" message options.SuppressStatusMessages = true;
}); });
} }
@ -62,10 +52,16 @@ public class test
public test(MeilisearchService service, ILogger<test> logger) public test(MeilisearchService service, ILogger<test> logger)
{ {
_logger = logger ?? throw new ArgumentNullException(nameof(logger)); _logger = logger ?? throw new ArgumentNullException(nameof(logger));
// You can perform actions with the Meilisearch service here // Wait until Meilisearch is running
while (!service.IsMeilisearchRunning())
{
_logger.LogInformation("Waiting for Meilisearch to start...");
Task.Delay(1000).Wait(); // Wait for 1 second before checking again
}
service.CreateIndex("test");
_logger.LogInformation("Test service initialized."); _logger.LogInformation("Test service initialized.");
} }
} }

View File

@ -36,6 +36,7 @@ public class MeilisearchService:IDisposable
"ext", "ext",
"size" "size"
}; };
private readonly string _indexBasePath = Path.Combine(AppContext.BaseDirectory, "db", "indexes" );
public MeilisearchService(HttpClient httpClient, ILogger<MeilisearchService> logger, MeiliSearchConfiguration meiliConfiguration) public MeilisearchService(HttpClient httpClient, ILogger<MeilisearchService> logger, MeiliSearchConfiguration meiliConfiguration)
{ {
@ -45,7 +46,8 @@ public class MeilisearchService:IDisposable
Client = new MeilisearchClient("http://localhost:"+meiliConfiguration.MeiliPort ); Client = new MeilisearchClient("http://localhost:"+meiliConfiguration.MeiliPort );
_documentCollection = new ObservableCollection<KeyValuePair<string,IDocument>>(); _documentCollection = new ObservableCollection<KeyValuePair<string,IDocument>>();
_documentCollection.CollectionChanged += CheckIfNeedDocumentSync; _documentCollection.CollectionChanged += CheckIfNeedDocumentSync;
StartMeilisearch(); StartMeilisearch().Wait();
EnsureRepositoryIndexExists().Wait();
} }
@ -96,15 +98,6 @@ public class MeilisearchService:IDisposable
} }
} }
private bool IsMeilisearchRunning()
{
var processName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? "meilisearch-windows"
: "meilisearch";
var processes = Process.GetProcessesByName(processName);
return processes.Any();
}
private async Task StartMeilisearch() private async Task StartMeilisearch()
{ {
var binaryName = GetMeilisearchBinaryName(); var binaryName = GetMeilisearchBinaryName();
@ -209,10 +202,15 @@ public class MeilisearchService:IDisposable
#endregion #endregion
#region Public #region Public
/// <summary> public bool IsMeilisearchRunning()
/// Creates a new index on the Meilisearch server if it does not already exist. {
/// </summary> var processName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
/// <param name="indexName">The name for the new index.</param> ? "meilisearch-windows"
: "meilisearch";
var processes = Process.GetProcessesByName(processName);
return processes.Any();
}
public void CreateIndex(string indexName) public void CreateIndex(string indexName)
{ {
var indexes = Client.GetAllIndexesAsync().Result; var indexes = Client.GetAllIndexesAsync().Result;
@ -221,6 +219,8 @@ public class MeilisearchService:IDisposable
_logger.LogWarning($"Index {indexName} already exists, skipping creation of index."); _logger.LogWarning($"Index {indexName} already exists, skipping creation of index.");
return; return;
} }
var foldersBefore = Directory.GetDirectories(_indexBasePath);
_logger.LogTrace($"Creating index '{indexName}'..."); _logger.LogTrace($"Creating index '{indexName}'...");
Client.CreateIndexAsync(indexName).Wait(); Client.CreateIndexAsync(indexName).Wait();
Task.Delay(5000).Wait(); Task.Delay(5000).Wait();
@ -228,24 +228,23 @@ public class MeilisearchService:IDisposable
var test = index.GetFilterableAttributesAsync().Result; var test = index.GetFilterableAttributesAsync().Result;
index.UpdateFilterableAttributesAsync(FIELDS).Wait(); index.UpdateFilterableAttributesAsync(FIELDS).Wait();
_logger.LogInformation($"{indexName} index created!"); _logger.LogInformation($"{indexName} index created!");
var foldersAfter = Directory.GetDirectories(_indexBasePath);
var folder = Path.GetFileName(foldersAfter.Except(foldersBefore).FirstOrDefault());
Client.GetIndexAsync("index_bindings").Result.AddDocumentsAsync(new List<Models.Index> Client.GetIndexAsync("index_bindings").Result.AddDocumentsAsync(new List<Models.Index>
{ {
new Models.Index() new()
{ {
Name = indexName Name = indexName,
CreatedAt = DateTime.UtcNow,
FolderId = folder
} }
}, "name").Wait(); }, "name").Wait();
} }
/// <summary>
/// Deletes a index for a repoistory.
/// </summary>
/// <param name="indexName">The name of the index.</param>
public void DeleteIndex(string indexName) public void DeleteIndex(string indexName)
{ {
var indexes = Client.GetAllIndexesAsync().Result; var indexes = Client.GetAllIndexesAsync().Result;
if (indexes.Results.Any(x => x.Uid != indexName)) if (indexes.Results.Any(x => x.Uid == indexName)==false)
{ {
_logger.LogWarning($"Index '{indexName}' does not exist, skipping deletion of index."); _logger.LogWarning($"Index '{indexName}' does not exist, skipping deletion of index.");
return; return;

View File

@ -3,4 +3,6 @@
public class Index public class Index
{ {
public string Name { get; set; } public string Name { get; set; }
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public string FolderId { get; set; }
} }