Uygulama açıkken Db Migration çalıştırma
This commit is contained in:
parent
6f3b20ffe2
commit
8186364642
9 changed files with 366 additions and 218 deletions
|
|
@ -3060,6 +3060,24 @@
|
||||||
"en": "Background Workers are being renewed.",
|
"en": "Background Workers are being renewed.",
|
||||||
"tr": "Arka Plan Çalışanları yenileniyor."
|
"tr": "Arka Plan Çalışanları yenileniyor."
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"resourceName": "Platform",
|
||||||
|
"key": "App.DbMigrate.StartMessage",
|
||||||
|
"en": "Database migration is starting.",
|
||||||
|
"tr": "Veritabanı geçişi başlatılıyor."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"resourceName": "Platform",
|
||||||
|
"key": "App.DbMigrate.EndMessage",
|
||||||
|
"en": "Database migration has completed.",
|
||||||
|
"tr": "Veritabanı geçişi tamamlandı."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"resourceName": "Platform",
|
||||||
|
"key": "App.DbMigrate.ErrorMessage",
|
||||||
|
"en": "An error occurred during database migration.",
|
||||||
|
"tr": "Veritabanı geçişi sırasında bir hata oluştu."
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"resourceName": "Platform",
|
"resourceName": "Platform",
|
||||||
"key": "App.ClearRedisCache.Message",
|
"key": "App.ClearRedisCache.Message",
|
||||||
|
|
@ -3240,6 +3258,12 @@
|
||||||
"en": "Clear Redis Cache",
|
"en": "Clear Redis Cache",
|
||||||
"tr": "Redis Önbelleğini Temizle"
|
"tr": "Redis Önbelleğini Temizle"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"resourceName": "Platform",
|
||||||
|
"key": "ListForms.ListForm.DbMigrate",
|
||||||
|
"en": "DB Migrate",
|
||||||
|
"tr": "DB Göçü"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"resourceName": "Platform",
|
"resourceName": "Platform",
|
||||||
"key": "ListForms.ListForm.SaveGridState",
|
"key": "ListForms.ListForm.SaveGridState",
|
||||||
|
|
|
||||||
|
|
@ -131,6 +131,14 @@ public class ListFormSeeder_Saas : IDataSeedContributor, ITransientDependency
|
||||||
DialogParameters = JsonSerializer.Serialize(new { name = "@Name", id = "@Id" }),
|
DialogParameters = JsonSerializer.Serialize(new { name = "@Name", id = "@Id" }),
|
||||||
IsVisible = true,
|
IsVisible = true,
|
||||||
},
|
},
|
||||||
|
new() {
|
||||||
|
ButtonPosition= UiCommandButtonPositionTypeEnum.Toolbar,
|
||||||
|
Hint = "ListForms.ListForm.DbMigrate",
|
||||||
|
Text = "ListForms.ListForm.DbMigrate",
|
||||||
|
AuthName = listFormName,
|
||||||
|
OnClick = "UiEvalService.ApiDbMigrate();",
|
||||||
|
IsVisible = true,
|
||||||
|
},
|
||||||
}),
|
}),
|
||||||
InsertServiceAddress = "list-form-dynamic-api/tenant-insert",
|
InsertServiceAddress = "list-form-dynamic-api/tenant-insert",
|
||||||
UpdateServiceAddress = "list-form-dynamic-api/tenant-update",
|
UpdateServiceAddress = "list-form-dynamic-api/tenant-update",
|
||||||
|
|
@ -143,7 +151,7 @@ public class ListFormSeeder_Saas : IDataSeedContributor, ITransientDependency
|
||||||
new() { FieldName = "Country", FieldDbType = DbType.String, Value = "Türkiye", CustomValueType = FieldCustomValueTypeEnum.Value },
|
new() { FieldName = "Country", FieldDbType = DbType.String, Value = "Türkiye", CustomValueType = FieldCustomValueTypeEnum.Value },
|
||||||
new() { FieldName = "MaxConcurrentUsers", FieldDbType = DbType.Int32, Value = "0", CustomValueType = FieldCustomValueTypeEnum.Value }
|
new() { FieldName = "MaxConcurrentUsers", FieldDbType = DbType.Int32, Value = "0", CustomValueType = FieldCustomValueTypeEnum.Value }
|
||||||
}),
|
}),
|
||||||
SubFormsJson =JsonSerializer.Serialize(new List<dynamic>() {
|
SubFormsJson = JsonSerializer.Serialize(new List<dynamic>() {
|
||||||
new {
|
new {
|
||||||
TabType = ListFormTabTypeEnum.List,
|
TabType = ListFormTabTypeEnum.List,
|
||||||
TabTitle = AppCodes.Branches,
|
TabTitle = AppCodes.Branches,
|
||||||
|
|
@ -4907,7 +4915,7 @@ public class ListFormSeeder_Saas : IDataSeedContributor, ITransientDependency
|
||||||
#endregion
|
#endregion
|
||||||
}
|
}
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region Route
|
#region Route
|
||||||
listFormName = AppCodes.Menus.Routes;
|
listFormName = AppCodes.Menus.Routes;
|
||||||
if (!await _listFormRepository.AnyAsync(a => a.ListFormCode == listFormName))
|
if (!await _listFormRepository.AnyAsync(a => a.ListFormCode == listFormName))
|
||||||
|
|
@ -5500,7 +5508,7 @@ public class ListFormSeeder_Saas : IDataSeedContributor, ITransientDependency
|
||||||
#endregion
|
#endregion
|
||||||
}
|
}
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region Custom Endpoint
|
#region Custom Endpoint
|
||||||
listFormName = AppCodes.DeveloperKits.CustomEndpoints;
|
listFormName = AppCodes.DeveloperKits.CustomEndpoints;
|
||||||
if (!await _listFormRepository.AnyAsync(a => a.ListFormCode == listFormName))
|
if (!await _listFormRepository.AnyAsync(a => a.ListFormCode == listFormName))
|
||||||
|
|
@ -5729,7 +5737,7 @@ public class ListFormSeeder_Saas : IDataSeedContributor, ITransientDependency
|
||||||
#endregion
|
#endregion
|
||||||
}
|
}
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region Products
|
#region Products
|
||||||
listFormName = AppCodes.Orders.Products;
|
listFormName = AppCodes.Orders.Products;
|
||||||
if (!await _listFormRepository.AnyAsync(a => a.ListFormCode == listFormName))
|
if (!await _listFormRepository.AnyAsync(a => a.ListFormCode == listFormName))
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,168 @@
|
||||||
|
using System;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.IO;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.AspNetCore.Authorization;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
|
|
||||||
|
namespace Sozsoft.Platform.Controllers;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// DB hazır olduğunda bile /setup sayfasından migration çalıştırmaya olanak tanır.
|
||||||
|
/// </summary>
|
||||||
|
[Route("api/setup")]
|
||||||
|
[Authorize(Roles = "admin")]
|
||||||
|
public class SetupController : ControllerBase
|
||||||
|
{
|
||||||
|
private readonly IConfiguration _configuration;
|
||||||
|
private readonly IHostEnvironment _env;
|
||||||
|
|
||||||
|
public SetupController(
|
||||||
|
IConfiguration configuration,
|
||||||
|
IHostEnvironment env)
|
||||||
|
{
|
||||||
|
_configuration = configuration;
|
||||||
|
_env = env;
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("status")]
|
||||||
|
[AllowAnonymous]
|
||||||
|
public IActionResult Status()
|
||||||
|
{
|
||||||
|
return Ok(new { dbExists = SetupAppRunner.DatabaseIsReady(_configuration) });
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("migrate")]
|
||||||
|
public async Task Migrate(CancellationToken ct)
|
||||||
|
{
|
||||||
|
Response.ContentType = "text/event-stream; charset=utf-8";
|
||||||
|
Response.Headers["Cache-Control"] = "no-cache, no-store";
|
||||||
|
Response.Headers["X-Accel-Buffering"] = "no";
|
||||||
|
await Response.Body.FlushAsync(ct);
|
||||||
|
|
||||||
|
async Task Send(string level, string message)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var payload = JsonSerializer.Serialize(new { level, message });
|
||||||
|
await Response.WriteAsync($"data: {payload}\n\n", ct);
|
||||||
|
await Response.Body.FlushAsync(ct);
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
}
|
||||||
|
|
||||||
|
var migratorPath = _configuration["Setup:MigratorPath"]
|
||||||
|
?? Path.GetFullPath(Path.Combine(_env.ContentRootPath, "..", "Sozsoft.Platform.DbMigrator"));
|
||||||
|
|
||||||
|
await Send("info", "Veritabanı migration ve seed başlatılıyor...");
|
||||||
|
await Send("info", $"Migrator yolu: {migratorPath}");
|
||||||
|
|
||||||
|
var extraArgs = _configuration["Setup:MigratorArgs"] ?? "--Seed=true";
|
||||||
|
|
||||||
|
string fileName;
|
||||||
|
string arguments;
|
||||||
|
string workingDirectory;
|
||||||
|
|
||||||
|
if (migratorPath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) && System.IO.File.Exists(migratorPath))
|
||||||
|
{
|
||||||
|
fileName = "dotnet";
|
||||||
|
arguments = $"\"{migratorPath}\" {extraArgs}";
|
||||||
|
workingDirectory = Path.GetDirectoryName(migratorPath)!;
|
||||||
|
}
|
||||||
|
else if (Directory.Exists(migratorPath))
|
||||||
|
{
|
||||||
|
var dllFiles = Directory.GetFiles(migratorPath, "*.DbMigrator.dll", SearchOption.TopDirectoryOnly);
|
||||||
|
if (dllFiles.Length == 0)
|
||||||
|
dllFiles = Directory.GetFiles(migratorPath, "*Migrator*.dll", SearchOption.TopDirectoryOnly);
|
||||||
|
|
||||||
|
if (dllFiles.Length > 0)
|
||||||
|
{
|
||||||
|
fileName = "dotnet";
|
||||||
|
arguments = $"\"{dllFiles[0]}\" {extraArgs}";
|
||||||
|
workingDirectory = migratorPath;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
fileName = "dotnet";
|
||||||
|
arguments = $"run --project \"{migratorPath}\" -- {extraArgs}";
|
||||||
|
workingDirectory = migratorPath;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
await Send("error", $"Migrator yolu bulunamadı veya geçersiz: {migratorPath}");
|
||||||
|
await Send("done", "Hata ile sonlandı.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await Send("info", $"Çalıştırılıyor: {fileName} {arguments}");
|
||||||
|
|
||||||
|
Process? process = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
process = new Process
|
||||||
|
{
|
||||||
|
StartInfo = new ProcessStartInfo
|
||||||
|
{
|
||||||
|
FileName = fileName,
|
||||||
|
Arguments = arguments,
|
||||||
|
RedirectStandardOutput = true,
|
||||||
|
RedirectStandardError = true,
|
||||||
|
UseShellExecute = false,
|
||||||
|
CreateNoWindow = true,
|
||||||
|
WorkingDirectory = workingDirectory,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
process.Start();
|
||||||
|
|
||||||
|
async Task ReadStream(StreamReader reader, string level)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
while (!reader.EndOfStream)
|
||||||
|
{
|
||||||
|
var line = await reader.ReadLineAsync(ct);
|
||||||
|
if (line != null) await Send(level, line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) { }
|
||||||
|
}
|
||||||
|
|
||||||
|
await Task.WhenAll(
|
||||||
|
ReadStream(process.StandardOutput, "info"),
|
||||||
|
ReadStream(process.StandardError, "warn"));
|
||||||
|
|
||||||
|
await process.WaitForExitAsync(ct);
|
||||||
|
|
||||||
|
if (process.ExitCode == 0)
|
||||||
|
{
|
||||||
|
await Send("success", "Migration ve seed başarıyla tamamlandı.");
|
||||||
|
await Send("done", "Tamamlandı.");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
await Send("error", $"Migration başarısız. Çıkış kodu: {process.ExitCode}");
|
||||||
|
await Send("done", "Hata ile sonlandı.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException)
|
||||||
|
{
|
||||||
|
await Send("warn", "Migration isteği iptal edildi.");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
await Send("error", $"Migration hatası: {ex.Message}");
|
||||||
|
await Send("done", "Hata ile sonlandı.");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
process?.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -130,7 +130,7 @@ internal static class SetupAppRunner
|
||||||
app.MapGet("/api/setup/status", (IConfiguration cfg) =>
|
app.MapGet("/api/setup/status", (IConfiguration cfg) =>
|
||||||
Results.Ok(new { dbExists = DatabaseIsReady(cfg) }));
|
Results.Ok(new { dbExists = DatabaseIsReady(cfg) }));
|
||||||
|
|
||||||
app.MapGet("/api/setup/migrate", async (IConfiguration cfg, IHostEnvironment env,
|
app.MapPost("/api/setup/migrate", async (IConfiguration cfg, IHostEnvironment env,
|
||||||
IHostApplicationLifetime lifetime, HttpContext ctx, CancellationToken ct) =>
|
IHostApplicationLifetime lifetime, HttpContext ctx, CancellationToken ct) =>
|
||||||
{
|
{
|
||||||
ctx.Response.ContentType = "text/event-stream; charset=utf-8";
|
ctx.Response.ContentType = "text/event-stream; charset=utf-8";
|
||||||
|
|
@ -149,13 +149,6 @@ internal static class SetupAppRunner
|
||||||
catch { }
|
catch { }
|
||||||
}
|
}
|
||||||
|
|
||||||
if (DatabaseIsReady(cfg))
|
|
||||||
{
|
|
||||||
await Send("warn", "Veritabanı zaten hazır. Migration atlanıyor.");
|
|
||||||
await Send("done", "Tamamlandı.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
var migratorPath = cfg["Setup:MigratorPath"]
|
var migratorPath = cfg["Setup:MigratorPath"]
|
||||||
?? Path.GetFullPath(Path.Combine(env.ContentRootPath, "..", "Sozsoft.Platform.DbMigrator"));
|
?? Path.GetFullPath(Path.Combine(env.ContentRootPath, "..", "Sozsoft.Platform.DbMigrator"));
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,16 +0,0 @@
|
||||||
using Microsoft.AspNetCore.Mvc;
|
|
||||||
using Volo.Abp.AspNetCore.Mvc;
|
|
||||||
|
|
||||||
namespace Sozsoft.Platform.Controllers;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Tam ABP uygulaması çalışırken setup durumunu döner.
|
|
||||||
/// SetupAppRunner'ın aynı endpoint'i DB hazır olmadığında dbExists=false döner.
|
|
||||||
/// </summary>
|
|
||||||
[ApiController]
|
|
||||||
[Route("api/setup")]
|
|
||||||
public class SetupController : AbpControllerBase
|
|
||||||
{
|
|
||||||
[HttpGet("status")]
|
|
||||||
public IActionResult Status() => Ok(new { dbExists = true });
|
|
||||||
}
|
|
||||||
|
|
@ -4,127 +4,59 @@ import { getLocalization } from '@/services/localization.service'
|
||||||
import { store } from '@/store'
|
import { store } from '@/store'
|
||||||
import { clearRedisCache } from './languageText.service'
|
import { clearRedisCache } from './languageText.service'
|
||||||
import { kickUser } from './identity.service'
|
import { kickUser } from './identity.service'
|
||||||
|
import { getSetupMigrate } from './setup.service'
|
||||||
|
|
||||||
export abstract class UiEvalService {
|
export abstract class UiEvalService {
|
||||||
static Init = () => {
|
static Init = () => {
|
||||||
//console.log('init')
|
//console.log('init')
|
||||||
}
|
}
|
||||||
|
|
||||||
static ApiGenerateBackgroundWorkers = () => {
|
private static translate = (
|
||||||
// Get store state directly instead of using hook
|
localizationKey: string,
|
||||||
const state = store.getState()
|
params?: Record<string, string | number>,
|
||||||
const { texts, config } = state.abpConfig
|
defaultResourceName?: string,
|
||||||
|
): string => {
|
||||||
// Create translate function similar to useLocalization hook
|
const { texts, config } = store.getState().abpConfig
|
||||||
const translate = (
|
if (!texts) return localizationKey
|
||||||
localizationKey: string,
|
return getLocalization(
|
||||||
params?: Record<string, string | number>,
|
texts,
|
||||||
defaultResourceName?: string,
|
defaultResourceName ?? config?.localization?.defaultResourceName,
|
||||||
): string => {
|
localizationKey,
|
||||||
if (!texts) {
|
params,
|
||||||
return localizationKey
|
)
|
||||||
}
|
}
|
||||||
return getLocalization(
|
|
||||||
texts,
|
|
||||||
defaultResourceName ?? config?.localization?.defaultResourceName,
|
|
||||||
localizationKey,
|
|
||||||
params,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const asyncCall = async () => {
|
|
||||||
await generateBackgroundWorkers()
|
|
||||||
}
|
|
||||||
|
|
||||||
asyncCall()
|
|
||||||
|
|
||||||
|
private static runWithToast = (asyncFn: () => Promise<void>, toastKey: string) => {
|
||||||
|
asyncFn()
|
||||||
toast.push(
|
toast.push(
|
||||||
<Notification type="success" duration={2000}>
|
<Notification type="success" duration={2000}>
|
||||||
{translate('::App.BackgroundWorkers.Message')}
|
{UiEvalService.translate(toastKey)}
|
||||||
</Notification>,
|
</Notification>,
|
||||||
{
|
{ placement: 'top-end' },
|
||||||
placement: 'top-end',
|
|
||||||
},
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static ApiGenerateBackgroundWorkers = () => {
|
||||||
|
UiEvalService.runWithToast(() => generateBackgroundWorkers(), '::App.BackgroundWorkers.Message')
|
||||||
|
}
|
||||||
|
|
||||||
static ApiClearRedisCache = () => {
|
static ApiClearRedisCache = () => {
|
||||||
// Get store state directly instead of using hook
|
UiEvalService.runWithToast(() => clearRedisCache(), '::App.ClearRedisCache.Message')
|
||||||
const state = store.getState()
|
|
||||||
const { texts, config } = state.abpConfig
|
|
||||||
|
|
||||||
// Create translate function similar to useLocalization hook
|
|
||||||
const translate = (
|
|
||||||
localizationKey: string,
|
|
||||||
params?: Record<string, string | number>,
|
|
||||||
defaultResourceName?: string,
|
|
||||||
): string => {
|
|
||||||
if (!texts) {
|
|
||||||
return localizationKey
|
|
||||||
}
|
|
||||||
return getLocalization(
|
|
||||||
texts,
|
|
||||||
defaultResourceName ?? config?.localization?.defaultResourceName,
|
|
||||||
localizationKey,
|
|
||||||
params,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const asyncCall = async () => {
|
|
||||||
await clearRedisCache()
|
|
||||||
}
|
|
||||||
|
|
||||||
asyncCall()
|
|
||||||
|
|
||||||
toast.push(
|
|
||||||
<Notification type="success" duration={2000}>
|
|
||||||
{translate('::App.ClearRedisCache.Message')}
|
|
||||||
</Notification>,
|
|
||||||
{
|
|
||||||
placement: 'top-end',
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
static ApiKickUser = (userId: string, gridRef?: any) => {
|
static ApiKickUser = (userId: string, gridRef?: any) => {
|
||||||
// Get store state directly instead of using hook
|
UiEvalService.runWithToast(async () => {
|
||||||
const state = store.getState()
|
|
||||||
const { texts, config } = state.abpConfig
|
|
||||||
|
|
||||||
// Create translate function similar to useLocalization hook
|
|
||||||
const translate = (
|
|
||||||
localizationKey: string,
|
|
||||||
params?: Record<string, string | number>,
|
|
||||||
defaultResourceName?: string,
|
|
||||||
): string => {
|
|
||||||
if (!texts) {
|
|
||||||
return localizationKey
|
|
||||||
}
|
|
||||||
return getLocalization(
|
|
||||||
texts,
|
|
||||||
defaultResourceName ?? config?.localization?.defaultResourceName,
|
|
||||||
localizationKey,
|
|
||||||
params,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const asyncCall = async () => {
|
|
||||||
await kickUser(userId)
|
await kickUser(userId)
|
||||||
if (gridRef?.current) {
|
if (gridRef?.current) {
|
||||||
gridRef.current.instance().refresh()
|
gridRef.current.instance().refresh()
|
||||||
}
|
}
|
||||||
}
|
}, '::App.KickUser.Message')
|
||||||
|
}
|
||||||
|
|
||||||
asyncCall()
|
static ApiDbMigrate = () => {
|
||||||
|
UiEvalService.runWithToast(async () => {
|
||||||
toast.push(
|
await getSetupMigrate()
|
||||||
<Notification type="success" duration={2000}>
|
}, '::App.DbMigrate.StartMessage')
|
||||||
{translate('::App.KickUser.Message')}
|
|
||||||
</Notification>,
|
|
||||||
{
|
|
||||||
placement: 'top-end',
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
import apiService from './api.service'
|
import apiService from './api.service'
|
||||||
|
import { applicationConfigurationUrl } from './abpConfig.service'
|
||||||
|
|
||||||
export interface SetupStatusDto {
|
export interface SetupStatusDto {
|
||||||
dbExists: boolean
|
dbExists: boolean
|
||||||
|
|
@ -11,11 +12,67 @@ export const getSetupStatus = () =>
|
||||||
url: '/api/setup/status',
|
url: '/api/setup/status',
|
||||||
})
|
})
|
||||||
|
|
||||||
/**
|
export const getSetupMigrate = () =>
|
||||||
* Returns the SSE URL for migration streaming.
|
apiService.fetchData({
|
||||||
* Usage: new EventSource(getMigrateUrl())
|
method: 'POST',
|
||||||
*/
|
url: '/api/setup/migrate',
|
||||||
|
})
|
||||||
|
|
||||||
export const getMigrateUrl = (): string => {
|
export const getMigrateUrl = (): string => {
|
||||||
const base = import.meta.env.VITE_API_URL ?? ''
|
const base = import.meta.env.VITE_API_URL ?? ''
|
||||||
return `${base}/api/setup/migrate`
|
return `${base}/api/setup/migrate`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sunucu yeniden başlayana kadar ABP config endpoint'ini poll eder.
|
||||||
|
* Arka arkaya 2 başarılı yanıt alındığında onReady çağrılır.
|
||||||
|
* @param onReady Sunucu hazır olduğunda çağrılacak callback
|
||||||
|
* @param onAttempt Her denemede kaçıncı deneme olduğunu bildiren opsiyonel callback
|
||||||
|
*/
|
||||||
|
export const pollUntilServerReady = (onReady: () => void, onAttempt?: (attempt: number) => void): (() => void) => {
|
||||||
|
const REQUIRED_SUCCESS = 2
|
||||||
|
let attempt = 0
|
||||||
|
let successCount = 0
|
||||||
|
let timerId: ReturnType<typeof setTimeout> | null = null
|
||||||
|
let cancelled = false
|
||||||
|
|
||||||
|
const tick = async () => {
|
||||||
|
if (cancelled) return
|
||||||
|
attempt++
|
||||||
|
onAttempt?.(attempt)
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(
|
||||||
|
`${import.meta.env.VITE_API_URL ?? ''}${applicationConfigurationUrl(false)}`,
|
||||||
|
{ method: 'GET', headers: { Accept: 'application/json' }, cache: 'no-store' },
|
||||||
|
)
|
||||||
|
if (res.status === 200) {
|
||||||
|
try {
|
||||||
|
const json = await res.json()
|
||||||
|
if (json && typeof json.currentUser === 'object') {
|
||||||
|
successCount++
|
||||||
|
if (successCount >= REQUIRED_SUCCESS) {
|
||||||
|
onReady()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
timerId = setTimeout(tick, 1000)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} catch { /* parse hatası */ }
|
||||||
|
}
|
||||||
|
successCount = 0
|
||||||
|
} catch {
|
||||||
|
successCount = 0
|
||||||
|
}
|
||||||
|
timerId = setTimeout(tick, 2000)
|
||||||
|
}
|
||||||
|
|
||||||
|
// İlk denemeden önce kısa bekleme (sunucunun kapanma süresi)
|
||||||
|
timerId = setTimeout(tick, 3000)
|
||||||
|
|
||||||
|
// İptal fonksiyonu döner
|
||||||
|
return () => {
|
||||||
|
cancelled = true
|
||||||
|
if (timerId) clearTimeout(timerId)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,6 @@
|
||||||
import { useEffect, useRef, useState } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
import { APP_NAME } from '@/constants/app.constant'
|
import { APP_NAME } from '@/constants/app.constant'
|
||||||
import { getMigrateUrl } from '@/services/setup.service'
|
import { getMigrateUrl, getSetupStatus, pollUntilServerReady } from '@/services/setup.service'
|
||||||
import { applicationConfigurationUrl, getAppConfig } from '@/services/abpConfig.service'
|
|
||||||
|
|
||||||
interface LogLine {
|
interface LogLine {
|
||||||
level: 'info' | 'warn' | 'error' | 'success' | 'restart' | 'done'
|
level: 'info' | 'warn' | 'error' | 'success' | 'restart' | 'done'
|
||||||
|
|
@ -24,7 +23,6 @@ const DatabaseSetup = () => {
|
||||||
const [status, setStatus] = useState<MigrationStatus>('idle')
|
const [status, setStatus] = useState<MigrationStatus>('idle')
|
||||||
const [pollCountdown, setPollCountdown] = useState(0)
|
const [pollCountdown, setPollCountdown] = useState(0)
|
||||||
const logEndRef = useRef<HTMLDivElement>(null)
|
const logEndRef = useRef<HTMLDivElement>(null)
|
||||||
const eventSourceRef = useRef<EventSource | null>(null)
|
|
||||||
const pollTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
const pollTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||||
|
|
||||||
// Auto-scroll to bottom when new logs arrive
|
// Auto-scroll to bottom when new logs arrive
|
||||||
|
|
@ -35,8 +33,9 @@ const DatabaseSetup = () => {
|
||||||
// Cleanup on component unmount
|
// Cleanup on component unmount
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
return () => {
|
return () => {
|
||||||
eventSourceRef.current?.close()
|
const ref = pollTimerRef.current as any
|
||||||
if (pollTimerRef.current) clearTimeout(pollTimerRef.current)
|
if (ref?.unref) ref.unref()
|
||||||
|
else if (pollTimerRef.current) clearTimeout(pollTimerRef.current as any)
|
||||||
}
|
}
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
|
|
@ -47,56 +46,14 @@ const DatabaseSetup = () => {
|
||||||
// ── Poll ABP config endpoint until server is ready ──────────────
|
// ── Poll ABP config endpoint until server is ready ──────────────
|
||||||
const pollUntilReady = () => {
|
const pollUntilReady = () => {
|
||||||
setStatus('restarting')
|
setStatus('restarting')
|
||||||
|
const cancel = pollUntilServerReady(
|
||||||
let attempt = 0
|
() => { window.location.href = '/' },
|
||||||
let successCount = 0
|
(attempt) => setPollCountdown(attempt),
|
||||||
const REQUIRED_SUCCESS = 2 // sunucunun kararlı olduğunu doğrulamak için arka arkaya 2 başarılı yanıt
|
)
|
||||||
|
pollTimerRef.current = { unref: cancel } as any
|
||||||
const tick = async () => {
|
|
||||||
attempt++
|
|
||||||
setPollCountdown(attempt)
|
|
||||||
try {
|
|
||||||
const res = await fetch(
|
|
||||||
`${import.meta.env.VITE_API_URL ?? ''}${applicationConfigurationUrl(false)}`,
|
|
||||||
{
|
|
||||||
method: 'GET',
|
|
||||||
headers: { Accept: 'application/json' },
|
|
||||||
cache: 'no-store',
|
|
||||||
},
|
|
||||||
)
|
|
||||||
if (res.status === 200) {
|
|
||||||
try {
|
|
||||||
const json = await res.json()
|
|
||||||
// ABP config yanıtının geçerli olduğunu doğrula (currentUser alanı her zaman bulunur)
|
|
||||||
if (json && typeof json.currentUser === 'object') {
|
|
||||||
successCount++
|
|
||||||
if (successCount >= REQUIRED_SUCCESS) {
|
|
||||||
// Sunucu tamamen hazır — yönlendir
|
|
||||||
window.location.href = '/'
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// Bir sonraki doğrulama denemesi
|
|
||||||
pollTimerRef.current = setTimeout(tick, 1000)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
// JSON parse hatası — sunucu henüz tam hazır değil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Başarısız — sıfırla ve tekrar dene
|
|
||||||
successCount = 0
|
|
||||||
} catch {
|
|
||||||
// Sunucu henüz yanıt vermiyor — bekleniyor, tekrar dene
|
|
||||||
successCount = 0
|
|
||||||
}
|
|
||||||
pollTimerRef.current = setTimeout(tick, 2000)
|
|
||||||
}
|
|
||||||
|
|
||||||
// İlk denemeden önce kısa bir bekleme (sunucunun kapanma süresi)
|
|
||||||
pollTimerRef.current = setTimeout(tick, 3000)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const startMigration = () => {
|
const startMigration = async () => {
|
||||||
if (status === 'running') return
|
if (status === 'running') return
|
||||||
|
|
||||||
setLogs([])
|
setLogs([])
|
||||||
|
|
@ -104,46 +61,71 @@ const DatabaseSetup = () => {
|
||||||
addLog('info', 'Starting migration...')
|
addLog('info', 'Starting migration...')
|
||||||
|
|
||||||
const url = getMigrateUrl()
|
const url = getMigrateUrl()
|
||||||
const es = new EventSource(url)
|
const abortController = new AbortController()
|
||||||
eventSourceRef.current = es
|
|
||||||
|
|
||||||
es.onmessage = (event) => {
|
const parseChunk = (chunk: string) => {
|
||||||
try {
|
// SSE format: "data: {...}\n\n"
|
||||||
const data = JSON.parse(event.data) as { level?: string; message?: string }
|
const lines = chunk.split('\n')
|
||||||
const level = (data.level ?? 'info') as LogLine['level']
|
for (const line of lines) {
|
||||||
const message = data.message ?? event.data
|
const trimmed = line.trim()
|
||||||
|
if (!trimmed.startsWith('data:')) continue
|
||||||
|
const raw = trimmed.slice(5).trim()
|
||||||
|
if (!raw) continue
|
||||||
|
try {
|
||||||
|
const data = JSON.parse(raw) as { level?: string; message?: string }
|
||||||
|
const level = (data.level ?? 'info') as LogLine['level']
|
||||||
|
const message = data.message ?? raw
|
||||||
|
|
||||||
if (level === 'done') {
|
if (level === 'done') {
|
||||||
es.close()
|
setStatus((prev) => {
|
||||||
eventSourceRef.current = null
|
if (prev === 'running') return 'error'
|
||||||
// If we received a "restart" event, switch to poll mode; otherwise keep success/error state
|
return prev
|
||||||
setStatus((prev) => {
|
})
|
||||||
if (prev === 'running') return 'error' // failed — no restart event received
|
return
|
||||||
return prev
|
}
|
||||||
})
|
|
||||||
return
|
addLog(level, message)
|
||||||
|
|
||||||
|
if (level === 'success') {
|
||||||
|
setStatus('success')
|
||||||
|
} else if (level === 'error') {
|
||||||
|
setStatus('error')
|
||||||
|
} else if (level === 'restart') {
|
||||||
|
pollUntilReady()
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
addLog('info', raw)
|
||||||
}
|
}
|
||||||
|
|
||||||
addLog(level, message)
|
|
||||||
|
|
||||||
if (level === 'success') {
|
|
||||||
setStatus('success')
|
|
||||||
} else if (level === 'error') {
|
|
||||||
setStatus('error')
|
|
||||||
} else if (level === 'restart') {
|
|
||||||
// Backend is stopping the minimal app — start polling
|
|
||||||
pollUntilReady()
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
addLog('info', event.data)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
es.onerror = () => {
|
try {
|
||||||
es.close()
|
const response = await fetch(url, {
|
||||||
eventSourceRef.current = null
|
method: 'POST',
|
||||||
setStatus((prev) => (prev === 'running' ? 'error' : prev))
|
headers: { Accept: 'text/event-stream' },
|
||||||
addLog('error', 'Server connection lost or migration could not be completed.')
|
signal: abortController.signal,
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok || !response.body) {
|
||||||
|
addLog('error', `Server responded with status ${response.status}`)
|
||||||
|
setStatus('error')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const reader = response.body.getReader()
|
||||||
|
const decoder = new TextDecoder()
|
||||||
|
|
||||||
|
// eslint-disable-next-line no-constant-condition
|
||||||
|
while (true) {
|
||||||
|
const { done, value } = await reader.read()
|
||||||
|
if (done) break
|
||||||
|
parseChunk(decoder.decode(value, { stream: true }))
|
||||||
|
}
|
||||||
|
} catch (err: any) {
|
||||||
|
if (err?.name !== 'AbortError') {
|
||||||
|
setStatus((prev) => (prev === 'running' ? 'error' : prev))
|
||||||
|
addLog('error', 'Server connection lost or migration could not be completed.')
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue