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.",
|
||||
"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",
|
||||
"key": "App.ClearRedisCache.Message",
|
||||
|
|
@ -3240,6 +3258,12 @@
|
|||
"en": "Clear Redis Cache",
|
||||
"tr": "Redis Önbelleğini Temizle"
|
||||
},
|
||||
{
|
||||
"resourceName": "Platform",
|
||||
"key": "ListForms.ListForm.DbMigrate",
|
||||
"en": "DB Migrate",
|
||||
"tr": "DB Göçü"
|
||||
},
|
||||
{
|
||||
"resourceName": "Platform",
|
||||
"key": "ListForms.ListForm.SaveGridState",
|
||||
|
|
|
|||
|
|
@ -131,6 +131,14 @@ public class ListFormSeeder_Saas : IDataSeedContributor, ITransientDependency
|
|||
DialogParameters = JsonSerializer.Serialize(new { name = "@Name", id = "@Id" }),
|
||||
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",
|
||||
UpdateServiceAddress = "list-form-dynamic-api/tenant-update",
|
||||
|
|
|
|||
|
|
@ -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) =>
|
||||
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) =>
|
||||
{
|
||||
ctx.Response.ContentType = "text/event-stream; charset=utf-8";
|
||||
|
|
@ -149,13 +149,6 @@ internal static class SetupAppRunner
|
|||
catch { }
|
||||
}
|
||||
|
||||
if (DatabaseIsReady(cfg))
|
||||
{
|
||||
await Send("warn", "Veritabanı zaten hazır. Migration atlanıyor.");
|
||||
await Send("done", "Tamamlandı.");
|
||||
return;
|
||||
}
|
||||
|
||||
var migratorPath = cfg["Setup:MigratorPath"]
|
||||
?? 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,26 +4,20 @@ import { getLocalization } from '@/services/localization.service'
|
|||
import { store } from '@/store'
|
||||
import { clearRedisCache } from './languageText.service'
|
||||
import { kickUser } from './identity.service'
|
||||
import { getSetupMigrate } from './setup.service'
|
||||
|
||||
export abstract class UiEvalService {
|
||||
static Init = () => {
|
||||
//console.log('init')
|
||||
}
|
||||
|
||||
static ApiGenerateBackgroundWorkers = () => {
|
||||
// Get store state directly instead of using hook
|
||||
const state = store.getState()
|
||||
const { texts, config } = state.abpConfig
|
||||
|
||||
// Create translate function similar to useLocalization hook
|
||||
const translate = (
|
||||
private static translate = (
|
||||
localizationKey: string,
|
||||
params?: Record<string, string | number>,
|
||||
defaultResourceName?: string,
|
||||
): string => {
|
||||
if (!texts) {
|
||||
return localizationKey
|
||||
}
|
||||
const { texts, config } = store.getState().abpConfig
|
||||
if (!texts) return localizationKey
|
||||
return getLocalization(
|
||||
texts,
|
||||
defaultResourceName ?? config?.localization?.defaultResourceName,
|
||||
|
|
@ -32,99 +26,37 @@ export abstract class UiEvalService {
|
|||
)
|
||||
}
|
||||
|
||||
const asyncCall = async () => {
|
||||
await generateBackgroundWorkers()
|
||||
}
|
||||
|
||||
asyncCall()
|
||||
|
||||
private static runWithToast = (asyncFn: () => Promise<void>, toastKey: string) => {
|
||||
asyncFn()
|
||||
toast.push(
|
||||
<Notification type="success" duration={2000}>
|
||||
{translate('::App.BackgroundWorkers.Message')}
|
||||
{UiEvalService.translate(toastKey)}
|
||||
</Notification>,
|
||||
{
|
||||
placement: 'top-end',
|
||||
},
|
||||
{ placement: 'top-end' },
|
||||
)
|
||||
}
|
||||
|
||||
static ApiGenerateBackgroundWorkers = () => {
|
||||
UiEvalService.runWithToast(() => generateBackgroundWorkers(), '::App.BackgroundWorkers.Message')
|
||||
}
|
||||
|
||||
static ApiClearRedisCache = () => {
|
||||
// Get store state directly instead of using hook
|
||||
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',
|
||||
},
|
||||
)
|
||||
UiEvalService.runWithToast(() => clearRedisCache(), '::App.ClearRedisCache.Message')
|
||||
}
|
||||
|
||||
static ApiKickUser = (userId: string, gridRef?: any) => {
|
||||
// Get store state directly instead of using hook
|
||||
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 () => {
|
||||
UiEvalService.runWithToast(async () => {
|
||||
await kickUser(userId)
|
||||
if (gridRef?.current) {
|
||||
gridRef.current.instance().refresh()
|
||||
}
|
||||
}, '::App.KickUser.Message')
|
||||
}
|
||||
|
||||
asyncCall()
|
||||
|
||||
toast.push(
|
||||
<Notification type="success" duration={2000}>
|
||||
{translate('::App.KickUser.Message')}
|
||||
</Notification>,
|
||||
{
|
||||
placement: 'top-end',
|
||||
},
|
||||
)
|
||||
static ApiDbMigrate = () => {
|
||||
UiEvalService.runWithToast(async () => {
|
||||
await getSetupMigrate()
|
||||
}, '::App.DbMigrate.StartMessage')
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import apiService from './api.service'
|
||||
import { applicationConfigurationUrl } from './abpConfig.service'
|
||||
|
||||
export interface SetupStatusDto {
|
||||
dbExists: boolean
|
||||
|
|
@ -11,11 +12,67 @@ export const getSetupStatus = () =>
|
|||
url: '/api/setup/status',
|
||||
})
|
||||
|
||||
/**
|
||||
* Returns the SSE URL for migration streaming.
|
||||
* Usage: new EventSource(getMigrateUrl())
|
||||
*/
|
||||
export const getSetupMigrate = () =>
|
||||
apiService.fetchData({
|
||||
method: 'POST',
|
||||
url: '/api/setup/migrate',
|
||||
})
|
||||
|
||||
export const getMigrateUrl = (): string => {
|
||||
const base = import.meta.env.VITE_API_URL ?? ''
|
||||
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 { APP_NAME } from '@/constants/app.constant'
|
||||
import { getMigrateUrl } from '@/services/setup.service'
|
||||
import { applicationConfigurationUrl, getAppConfig } from '@/services/abpConfig.service'
|
||||
import { getMigrateUrl, getSetupStatus, pollUntilServerReady } from '@/services/setup.service'
|
||||
|
||||
interface LogLine {
|
||||
level: 'info' | 'warn' | 'error' | 'success' | 'restart' | 'done'
|
||||
|
|
@ -24,7 +23,6 @@ const DatabaseSetup = () => {
|
|||
const [status, setStatus] = useState<MigrationStatus>('idle')
|
||||
const [pollCountdown, setPollCountdown] = useState(0)
|
||||
const logEndRef = useRef<HTMLDivElement>(null)
|
||||
const eventSourceRef = useRef<EventSource | null>(null)
|
||||
const pollTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
|
||||
// Auto-scroll to bottom when new logs arrive
|
||||
|
|
@ -35,8 +33,9 @@ const DatabaseSetup = () => {
|
|||
// Cleanup on component unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
eventSourceRef.current?.close()
|
||||
if (pollTimerRef.current) clearTimeout(pollTimerRef.current)
|
||||
const ref = pollTimerRef.current as any
|
||||
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 ──────────────
|
||||
const pollUntilReady = () => {
|
||||
setStatus('restarting')
|
||||
|
||||
let attempt = 0
|
||||
let successCount = 0
|
||||
const REQUIRED_SUCCESS = 2 // sunucunun kararlı olduğunu doğrulamak için arka arkaya 2 başarılı yanıt
|
||||
|
||||
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',
|
||||
},
|
||||
const cancel = pollUntilServerReady(
|
||||
() => { window.location.href = '/' },
|
||||
(attempt) => setPollCountdown(attempt),
|
||||
)
|
||||
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)
|
||||
pollTimerRef.current = { unref: cancel } as any
|
||||
}
|
||||
|
||||
// İ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
|
||||
|
||||
setLogs([])
|
||||
|
|
@ -104,21 +61,24 @@ const DatabaseSetup = () => {
|
|||
addLog('info', 'Starting migration...')
|
||||
|
||||
const url = getMigrateUrl()
|
||||
const es = new EventSource(url)
|
||||
eventSourceRef.current = es
|
||||
const abortController = new AbortController()
|
||||
|
||||
es.onmessage = (event) => {
|
||||
const parseChunk = (chunk: string) => {
|
||||
// SSE format: "data: {...}\n\n"
|
||||
const lines = chunk.split('\n')
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim()
|
||||
if (!trimmed.startsWith('data:')) continue
|
||||
const raw = trimmed.slice(5).trim()
|
||||
if (!raw) continue
|
||||
try {
|
||||
const data = JSON.parse(event.data) as { level?: string; message?: string }
|
||||
const data = JSON.parse(raw) as { level?: string; message?: string }
|
||||
const level = (data.level ?? 'info') as LogLine['level']
|
||||
const message = data.message ?? event.data
|
||||
const message = data.message ?? raw
|
||||
|
||||
if (level === 'done') {
|
||||
es.close()
|
||||
eventSourceRef.current = null
|
||||
// If we received a "restart" event, switch to poll mode; otherwise keep success/error state
|
||||
setStatus((prev) => {
|
||||
if (prev === 'running') return 'error' // failed — no restart event received
|
||||
if (prev === 'running') return 'error'
|
||||
return prev
|
||||
})
|
||||
return
|
||||
|
|
@ -131,21 +91,43 @@ const DatabaseSetup = () => {
|
|||
} else if (level === 'error') {
|
||||
setStatus('error')
|
||||
} else if (level === 'restart') {
|
||||
// Backend is stopping the minimal app — start polling
|
||||
pollUntilReady()
|
||||
}
|
||||
} catch {
|
||||
addLog('info', event.data)
|
||||
addLog('info', raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
es.onerror = () => {
|
||||
es.close()
|
||||
eventSourceRef.current = null
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { Accept: 'text/event-stream' },
|
||||
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.')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-900 flex flex-col items-center justify-center p-6 text-white">
|
||||
|
|
|
|||
Loading…
Reference in a new issue