perf(bulk-api-tester): optimize draft saving, share link creation, and combining with parallel multipart streaming and instant hard links

This commit is contained in:
2026-10-28 16:24:28 +05:30
parent ce75adb467
commit 2fd2c5e582
4 changed files with 643 additions and 239 deletions
+236 -47
View File
@@ -11,6 +11,7 @@ import (
"regexp"
"sort"
"strings"
"sync"
"time"
"github.com/go-chi/chi/v5"
@@ -101,6 +102,20 @@ func copyFile(src, dst string) error {
return err
}
func linkOrCopyFile(src, dst string) error {
if err := os.MkdirAll(filepath.Dir(dst), 0755); err != nil {
return err
}
// Try hard link first for instant zero-copy linking
if err := os.Link(src, dst); err == nil {
return nil
}
// Fallback to copy if cross-filesystem or link fails
return copyFile(src, dst)
}
func resolveDiskPathFromURL(rawURL string) string {
if rawURL == "" {
return ""
@@ -131,7 +146,7 @@ func listComparisonDraftsHandler(w http.ResponseWriter, r *http.Request) {
return
}
var drafts []ComparisonDraft
drafts := []ComparisonDraft{}
for _, entry := range entries {
if !entry.IsDir() {
continue
@@ -179,6 +194,12 @@ func saveComparisonDraftHandler(w http.ResponseWriter, r *http.Request) {
// Set 500MB limit on request body
r.Body = http.MaxBytesReader(w, r.Body, 500*1024*1024)
// High-speed direct binary streaming via multipart
if strings.HasPrefix(r.Header.Get("Content-Type"), "multipart/form-data") {
handleMultipartDraft(w, r)
return
}
var req SaveDraftRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
slog.Error("failed to decode save draft request", "error", err)
@@ -227,22 +248,7 @@ func saveComparisonDraftHandler(w http.ResponseWriter, r *http.Request) {
SourceDraftID: draftID,
}
isSuccess := false
switch v := it.Status.(type) {
case float64:
if int(v) >= 200 && int(v) < 300 {
isSuccess = true
}
case int:
if v >= 200 && v < 300 {
isSuccess = true
}
case string:
if strings.HasPrefix(v, "2") {
isSuccess = true
}
}
if isSuccess {
if isSuccessStatus(it.Status) {
successCount++
} else {
errorCount++
@@ -320,6 +326,186 @@ func saveComparisonDraftHandler(w http.ResponseWriter, r *http.Request) {
})
}
func handleMultipartDraft(w http.ResponseWriter, r *http.Request) {
mr, err := r.MultipartReader()
if err != nil {
slog.Error("failed to create multipart reader for draft", "error", err)
writeJSON(w, http.StatusBadRequest, map[string]any{"success": false, "error": "Invalid multipart payload"})
return
}
draftID := fmt.Sprintf("draft_%x_%s", time.Now().Unix(), randomHexString(4))
draftDir := filepath.Join("data", "bulk-api-tester", "drafts", draftID)
imagesDir := filepath.Join(draftDir, "images")
if err := os.MkdirAll(imagesDir, 0755); err != nil {
slog.Error("failed to create draft directory", "dir", draftDir, "error", err)
writeJSON(w, http.StatusInternalServerError, map[string]any{"success": false, "error": "Failed to create storage directory"})
return
}
var metaReq SaveDraftRequest
filesMap := make(map[string]string) // formName -> savedFilename
for {
part, err := mr.NextPart()
if err == io.EOF {
break
}
if err != nil {
slog.Warn("error reading draft multipart part", "error", err)
break
}
formName := part.FormName()
if formName == "meta" {
metaBytes, _ := io.ReadAll(part)
json.Unmarshal(metaBytes, &metaReq)
part.Close()
continue
}
if strings.HasPrefix(formName, "before_") || strings.HasPrefix(formName, "after_") {
fileName := part.FileName()
ext := strings.ToLower(filepath.Ext(fileName))
if ext == "" {
ext = ".png"
}
saveName := fmt.Sprintf("%s%s", formName, ext)
filePath := filepath.Join(imagesDir, saveName)
outFile, err := os.Create(filePath)
if err == nil {
io.Copy(outFile, part)
outFile.Close()
filesMap[formName] = saveName
} else {
slog.Warn("failed to write draft multipart image", "path", filePath, "error", err)
}
part.Close()
continue
}
part.Close()
}
if metaReq.ID != "" && validIDRegex.MatchString(metaReq.ID) {
if metaReq.ID != draftID {
targetDir := filepath.Join("data", "bulk-api-tester", "drafts", metaReq.ID)
if err := os.Rename(draftDir, targetDir); err == nil {
draftID = metaReq.ID
draftDir = targetDir
imagesDir = filepath.Join(draftDir, "images")
}
}
}
var items []DraftItem
var totalLatency int64
successCount := 0
errorCount := 0
for i, it := range metaReq.Items {
itemIndex := it.Index
if itemIndex <= 0 {
itemIndex = i + 1
}
dItem := DraftItem{
Index: itemIndex,
Status: it.Status,
Latency: it.Latency,
InputFilename: it.InputFilename,
OutputFilename: it.OutputFilename,
ContentType: it.ContentType,
TextContent: it.TextContent,
SourceDraftID: draftID,
}
if isSuccessStatus(it.Status) {
successCount++
} else {
errorCount++
}
totalLatency += it.Latency
beforeKey := fmt.Sprintf("before_%d", itemIndex)
if saveName, ok := filesMap[beforeKey]; ok {
dItem.BeforeImage = fmt.Sprintf("/api/comparison-drafts/%s/images/%s", draftID, saveName)
dItem.HasBefore = true
} else if it.BeforeData != "" {
beforeBytes, ext, err := decodeImageData(it.BeforeData)
if err == nil && len(beforeBytes) > 0 {
filename := fmt.Sprintf("before_%d.%s", itemIndex, ext)
filePath := filepath.Join(imagesDir, filename)
if err := os.WriteFile(filePath, beforeBytes, 0644); err == nil {
dItem.BeforeImage = fmt.Sprintf("/api/comparison-drafts/%s/images/%s", draftID, filename)
dItem.HasBefore = true
}
}
}
afterKey := fmt.Sprintf("after_%d", itemIndex)
if saveName, ok := filesMap[afterKey]; ok {
dItem.AfterImage = fmt.Sprintf("/api/comparison-drafts/%s/images/%s", draftID, saveName)
dItem.HasAfter = true
} else if it.AfterData != "" {
afterBytes, ext, err := decodeImageData(it.AfterData)
if err == nil && len(afterBytes) > 0 {
filename := fmt.Sprintf("after_%d.%s", itemIndex, ext)
filePath := filepath.Join(imagesDir, filename)
if err := os.WriteFile(filePath, afterBytes, 0644); err == nil {
dItem.AfterImage = fmt.Sprintf("/api/comparison-drafts/%s/images/%s", draftID, filename)
dItem.HasAfter = true
}
}
}
items = append(items, dItem)
}
title := strings.TrimSpace(metaReq.Title)
if title == "" {
title = fmt.Sprintf("Draft Run (%d results) - %s", len(items), time.Now().Format("Jan 02, 15:04"))
}
var avgLatency int64
if len(items) > 0 {
avgLatency = totalLatency / int64(len(items))
}
nowStr := time.Now().UTC().Format(time.RFC3339)
draftData := ComparisonDraft{
ID: draftID,
Title: title,
Notes: metaReq.Notes,
Endpoint: metaReq.Endpoint,
SpaceName: metaReq.SpaceName,
CreatedAt: nowStr,
UpdatedAt: nowStr,
Total: len(items),
SuccessCount: successCount,
ErrorCount: errorCount,
AvgLatency: avgLatency,
Items: items,
}
metaPath := filepath.Join(draftDir, "meta.json")
if err := atomicWriteJSON(metaPath, draftData); err != nil {
slog.Error("failed to save draft metadata", "path", metaPath, "error", err)
writeJSON(w, http.StatusInternalServerError, map[string]any{"success": false, "error": "Failed to save draft metadata"})
return
}
slog.Info("saved comparison draft via fast multipart", "draft_id", draftID, "items_count", len(items))
writeJSON(w, http.StatusOK, map[string]any{
"success": true,
"draftId": draftID,
"draft": draftData,
})
}
func deleteComparisonDraftHandler(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
if id == "" || !validIDRegex.MatchString(id) {
@@ -408,7 +594,13 @@ func combineDraftsHandler(w http.ResponseWriter, r *http.Request) {
return
}
var items []ComparisonItem
type fileTask struct {
src string
dst string
}
var linkTasks []fileTask
items := make([]ComparisonItem, len(req.Items))
var totalLatency int64
successCount := 0
errorCount := 0
@@ -426,22 +618,7 @@ func combineDraftsHandler(w http.ResponseWriter, r *http.Request) {
TextContent: it.TextContent,
}
isSuccess := false
switch v := it.Status.(type) {
case float64:
if int(v) >= 200 && int(v) < 300 {
isSuccess = true
}
case int:
if v >= 200 && v < 300 {
isSuccess = true
}
case string:
if strings.HasPrefix(v, "2") {
isSuccess = true
}
}
if isSuccess {
if isSuccessStatus(it.Status) {
successCount++
} else {
errorCount++
@@ -468,12 +645,9 @@ func combineDraftsHandler(w http.ResponseWriter, r *http.Request) {
}
filename := fmt.Sprintf("before_%d%s", newIndex, ext)
dst := filepath.Join(imagesDir, filename)
if err := copyFile(srcDiskPath, dst); err == nil {
cItem.BeforeImage = fmt.Sprintf("/api/comparison/%s/images/%s", shareID, filename)
cItem.HasBefore = true
} else {
slog.Warn("failed to copy before image", "src", srcDiskPath, "dst", dst, "error", err)
}
linkTasks = append(linkTasks, fileTask{src: srcDiskPath, dst: dst})
cItem.BeforeImage = fmt.Sprintf("/api/comparison/%s/images/%s", shareID, filename)
cItem.HasBefore = true
}
}
@@ -497,16 +671,31 @@ func combineDraftsHandler(w http.ResponseWriter, r *http.Request) {
}
filename := fmt.Sprintf("after_%d%s", newIndex, ext)
dst := filepath.Join(imagesDir, filename)
if err := copyFile(srcDiskPath, dst); err == nil {
cItem.AfterImage = fmt.Sprintf("/api/comparison/%s/images/%s", shareID, filename)
cItem.HasAfter = true
} else {
slog.Warn("failed to copy after image", "src", srcDiskPath, "dst", dst, "error", err)
}
linkTasks = append(linkTasks, fileTask{src: srcDiskPath, dst: dst})
cItem.AfterImage = fmt.Sprintf("/api/comparison/%s/images/%s", shareID, filename)
cItem.HasAfter = true
}
}
items = append(items, cItem)
items[i] = cItem
}
// Concurrently hard-link or copy files with worker pool
if len(linkTasks) > 0 {
var wg sync.WaitGroup
sem := make(chan struct{}, 16)
for _, task := range linkTasks {
wg.Add(1)
go func(t fileTask) {
defer wg.Done()
sem <- struct{}{}
defer func() { <-sem }()
if err := linkOrCopyFile(t.src, t.dst); err != nil {
slog.Warn("failed to link/copy draft image", "src", t.src, "dst", t.dst, "error", err)
}
}(task)
}
wg.Wait()
}
heading := strings.TrimSpace(req.Heading)
+166
View File
@@ -6,6 +6,7 @@ import (
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"os"
@@ -19,6 +20,18 @@ import (
var validIDRegex = regexp.MustCompile(`^[a-zA-Z0-9_\-]+$`)
func isSuccessStatus(status any) bool {
switch v := status.(type) {
case float64:
return int(v) >= 200 && int(v) < 300
case int:
return v >= 200 && v < 300
case string:
return strings.HasPrefix(v, "2")
}
return false
}
type ComparisonItem struct {
Index int `json:"index"`
Status any `json:"status"`
@@ -124,6 +137,12 @@ func createComparisonShareHandler(w http.ResponseWriter, r *http.Request) {
// Set 500MB limit on request body for batches of images
r.Body = http.MaxBytesReader(w, r.Body, 500*1024*1024)
// High-speed direct binary streaming via multipart
if strings.HasPrefix(r.Header.Get("Content-Type"), "multipart/form-data") {
handleMultipartShare(w, r)
return
}
var req ShareRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
slog.Error("failed to decode share request", "error", err)
@@ -363,3 +382,150 @@ func comparePageHandler(w http.ResponseWriter, r *http.Request) {
w.Write(htmlBytes)
}
func handleMultipartShare(w http.ResponseWriter, r *http.Request) {
mr, err := r.MultipartReader()
if err != nil {
slog.Error("failed to create multipart reader", "error", err)
writeJSON(w, http.StatusBadRequest, map[string]any{"success": false, "error": "Invalid multipart payload"})
return
}
shareID := fmt.Sprintf("cmp_%x_%s", time.Now().Unix(), randomHexString(4))
compDir := filepath.Join("data", "bulk-api-tester", "comparisons", shareID)
imagesDir := filepath.Join(compDir, "images")
if err := os.MkdirAll(imagesDir, 0755); err != nil {
slog.Error("failed to create comparison directory", "dir", compDir, "error", err)
writeJSON(w, http.StatusInternalServerError, map[string]any{"success": false, "error": "Failed to create storage directory"})
return
}
var metaReq ShareRequest
filesMap := make(map[string]string) // formName -> savedFilename
for {
part, err := mr.NextPart()
if err == io.EOF {
break
}
if err != nil {
slog.Warn("error reading multipart part", "error", err)
break
}
formName := part.FormName()
if formName == "meta" {
metaBytes, _ := io.ReadAll(part)
json.Unmarshal(metaBytes, &metaReq)
part.Close()
continue
}
if strings.HasPrefix(formName, "before_") || strings.HasPrefix(formName, "after_") {
fileName := part.FileName()
ext := strings.ToLower(filepath.Ext(fileName))
if ext == "" {
ext = ".png"
}
saveName := fmt.Sprintf("%s%s", formName, ext)
filePath := filepath.Join(imagesDir, saveName)
outFile, err := os.Create(filePath)
if err == nil {
io.Copy(outFile, part)
outFile.Close()
filesMap[formName] = saveName
} else {
slog.Warn("failed to write multipart image", "path", filePath, "error", err)
}
part.Close()
continue
}
part.Close()
}
var items []ComparisonItem
var totalLatency int64
successCount := 0
errorCount := 0
for i, it := range metaReq.Items {
itemIndex := it.Index
if itemIndex <= 0 {
itemIndex = i + 1
}
cItem := ComparisonItem{
Index: itemIndex,
Status: it.Status,
Latency: it.Latency,
InputFilename: it.InputFilename,
OutputFilename: it.OutputFilename,
ContentType: it.ContentType,
TextContent: it.TextContent,
}
if isSuccessStatus(it.Status) {
successCount++
} else {
errorCount++
}
totalLatency += it.Latency
beforeKey := fmt.Sprintf("before_%d", itemIndex)
if saveName, ok := filesMap[beforeKey]; ok {
cItem.BeforeImage = fmt.Sprintf("/api/comparison/%s/images/%s", shareID, saveName)
cItem.HasBefore = true
}
afterKey := fmt.Sprintf("after_%d", itemIndex)
if saveName, ok := filesMap[afterKey]; ok {
cItem.AfterImage = fmt.Sprintf("/api/comparison/%s/images/%s", shareID, saveName)
cItem.HasAfter = true
}
items = append(items, cItem)
}
title := strings.TrimSpace(metaReq.Title)
if title == "" {
title = fmt.Sprintf("Batch Comparison (%d results)", len(items))
}
var avgLatency int64
if len(items) > 0 {
avgLatency = totalLatency / int64(len(items))
}
shareData := ComparisonShare{
ID: shareID,
Title: title,
Endpoint: metaReq.Endpoint,
SpaceName: metaReq.SpaceName,
CreatedAt: time.Now().UTC().Format(time.RFC3339),
Total: len(items),
SuccessCount: successCount,
ErrorCount: errorCount,
AvgLatency: avgLatency,
Items: items,
}
metaPath := filepath.Join(compDir, "meta.json")
if err := atomicWriteJSON(metaPath, shareData); err != nil {
slog.Error("failed to save comparison meta", "path", metaPath, "error", err)
writeJSON(w, http.StatusInternalServerError, map[string]any{"success": false, "error": "Failed to save comparison meta"})
return
}
slog.Info("created shareable comparison via fast multipart", "share_id", shareID, "items_count", len(items))
writeJSON(w, http.StatusOK, map[string]any{
"success": true,
"shareId": shareID,
"url": "/tool/bulk-api-tester/compare/" + shareID,
"directUrl": "/compare/" + shareID,
"total": len(items),
})
}
File diff suppressed because one or more lines are too long
+240 -191
View File
@@ -3022,6 +3022,37 @@ const App = {
}
},
// ── High-Speed Blob Resolution Helper ────────────────────────────────────
async _getBlobFromUrlOrBinary(url, binaryData, contentType = 'image/png') {
if (url) {
try {
const res = await fetch(url);
if (res.ok) return await res.blob();
} catch (_) {}
}
if (binaryData) {
try {
let b64 = binaryData;
let mime = contentType || 'image/png';
if (b64.startsWith('data:')) {
const idx = b64.indexOf(';base64,');
if (idx !== -1) {
mime = b64.substring(5, idx);
b64 = b64.substring(idx + 8);
}
}
const binStr = atob(b64);
const len = binStr.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binStr.charCodeAt(i);
}
return new Blob([bytes], { type: mime });
} catch (_) {}
}
return null;
},
// ── Shareable Visual Comparison Studio ─────────────────────────────────────
async createShareableComparison() {
const results = this.state.bulk.results;
@@ -3039,88 +3070,84 @@ const App = {
<i class="fa-solid fa-spinner fa-spin"></i>
</div>
<h3 style="font-family:var(--font-display); font-size:16px; margin:0 0 6px 0; color:var(--text-1);">Packaging Comparison Snapshot</h3>
<p id="share-progress-text" style="font-size:12px; color:var(--text-3); margin:0 0 16px 0;">Processing result assets (0/${results.length})...</p>
<p id="share-progress-text" style="font-size:12px; color:var(--text-3); margin:0 0 16px 0;">Uploading streaming assets (${results.length} items)...</p>
<div class="progress-track" style="margin-bottom:0; height:6px;">
<div id="share-progress-fill" class="progress-fill" style="width:0%; background:linear-gradient(90deg, #7257ff, #38bdf8);"></div>
<div id="share-progress-fill" class="progress-fill" style="width:75%; background:linear-gradient(90deg, #7257ff, #38bdf8);"></div>
</div>
</div>
`;
document.body.appendChild(progressModal);
const updateProgress = (done, total) => {
const pText = document.getElementById('share-progress-text');
const pFill = document.getElementById('share-progress-fill');
if (pText) pText.textContent = `Processing result assets (${done}/${total})...`;
if (pFill) pFill.style.width = `${Math.round((done / total) * 100)}%`;
};
const blobToBase64 = (blob) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(blob);
});
};
try {
const items = [];
for (let i = 0; i < results.length; i++) {
const r = results[i];
updateProgress(i + 1, results.length);
let beforeData = '';
let afterData = '';
// 1. Resolve Before Image
// High-speed parallel blob resolution (zero base64 encoding overhead)
const resolvedItems = await Promise.all(results.map(async (r, i) => {
const itemIndex = r.index || (i + 1);
const beforeObj = this.resolveOriginalImageForResult(r);
if (beforeObj && beforeObj.url) {
try {
const bBlob = await fetch(beforeObj.url).then(res => res.blob());
beforeData = await blobToBase64(bBlob);
} catch(e) {
console.warn("Failed to encode before image", e);
}
}
// 2. Resolve After Image
if (r.blobUrl) {
try {
const aBlob = await fetch(r.blobUrl).then(res => res.blob());
afterData = await blobToBase64(aBlob);
} catch(e) {
console.warn("Failed to encode after image", e);
}
} else if (r.binaryData) {
afterData = r.binaryData.startsWith('data:') ? r.binaryData : `data:${r.contentType || 'image/png'};base64,${r.binaryData}`;
}
const [beforeBlob, afterBlob] = await Promise.all([
beforeObj && beforeObj.url ? this._getBlobFromUrlOrBinary(beforeObj.url, null) : Promise.resolve(null),
this._getBlobFromUrlOrBinary(r.blobUrl, r.binaryData, r.contentType || 'image/png')
]);
items.push({
index: r.index || (i + 1),
return {
index: itemIndex,
status: r.status,
latency: r.latency || 0,
inputFilename: (beforeObj && beforeObj.name) || r.inputFilename || `input_${i+1}`,
inputFilename: (beforeObj && beforeObj.name) || r.inputFilename || `input_${itemIndex}`,
outputFilename: this.getFinalFilename(r),
contentType: r.contentType || 'image/png',
beforeData: beforeData,
afterData: afterData,
textContent: r.fullContent || (typeof r.data === 'string' ? r.data : '')
textContent: r.fullContent || (typeof r.data === 'string' ? r.data : ''),
beforeBlob,
afterBlob
};
}));
const fd = new FormData();
const metaItems = [];
const getExt = (blob, fallbackType) => {
const type = (blob && blob.type) || fallbackType || '';
if (type.includes('jpeg') || type.includes('jpg')) return '.jpg';
if (type.includes('webp')) return '.webp';
if (type.includes('gif')) return '.gif';
if (type.includes('svg')) return '.svg';
if (type.includes('avif')) return '.avif';
return '.png';
};
for (const it of resolvedItems) {
if (it.beforeBlob) {
const ext = getExt(it.beforeBlob, 'image/png');
fd.append(`before_${it.index}`, it.beforeBlob, `before_${it.index}${ext}`);
}
if (it.afterBlob) {
const ext = getExt(it.afterBlob, it.contentType);
fd.append(`after_${it.index}`, it.afterBlob, `after_${it.index}${ext}`);
}
metaItems.push({
index: it.index,
status: it.status,
latency: it.latency,
inputFilename: it.inputFilename,
outputFilename: it.outputFilename,
contentType: it.contentType,
textContent: it.textContent
});
}
const activeSpace = this.state.spaces.find(s => s.id === this.state.activeSpaceId);
const payload = {
fd.append('meta', JSON.stringify({
title: `Batch Comparison (${results.length} results)`,
endpoint: this.state.url || '',
spaceName: activeSpace ? activeSpace.name : 'Default Space',
items: items
};
items: metaItems
}));
const basePath = window.location.pathname.includes('/tool/bulk-api-tester') ? '/tool/bulk-api-tester' : '';
const res = await fetch(`${basePath}/api/share-comparison`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
body: fd
});
progressModal.remove();
@@ -3147,7 +3174,6 @@ const App = {
copied = true;
}
} catch(_) {
// Fallback for environments without direct clipboard focus
try {
const ta = document.createElement('textarea');
ta.value = shareUrl;
@@ -3373,66 +3399,77 @@ const App = {
submitBtn.innerHTML = `<i class="fa-solid fa-spinner fa-spin"></i> Saving...`;
}
const blobToBase64 = (blob) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(blob);
});
};
try {
const items = [];
for (let i = 0; i < results.length; i++) {
const r = results[i];
let beforeData = '';
let afterData = '';
// High-speed parallel blob resolution (zero base64 encoding overhead)
const resolvedItems = await Promise.all(results.map(async (r, i) => {
const itemIndex = r.index || (i + 1);
const beforeObj = this.resolveOriginalImageForResult(r);
if (beforeObj && beforeObj.url) {
try {
const bBlob = await fetch(beforeObj.url).then(res => res.blob());
beforeData = await blobToBase64(bBlob);
} catch(_) {}
}
if (r.blobUrl) {
try {
const aBlob = await fetch(r.blobUrl).then(res => res.blob());
afterData = await blobToBase64(aBlob);
} catch(_) {}
} else if (r.binaryData) {
afterData = r.binaryData.startsWith('data:') ? r.binaryData : `data:${r.contentType || 'image/png'};base64,${r.binaryData}`;
}
const [beforeBlob, afterBlob] = await Promise.all([
beforeObj && beforeObj.url ? this._getBlobFromUrlOrBinary(beforeObj.url, null) : Promise.resolve(null),
this._getBlobFromUrlOrBinary(r.blobUrl, r.binaryData, r.contentType || 'image/png')
]);
items.push({
index: r.index || (i + 1),
return {
index: itemIndex,
status: r.status,
latency: r.latency || 0,
inputFilename: (beforeObj && beforeObj.name) || r.inputFilename || `input_${i+1}`,
inputFilename: (beforeObj && beforeObj.name) || r.inputFilename || `input_${itemIndex}`,
outputFilename: this.getFinalFilename(r),
contentType: r.contentType || 'image/png',
beforeData: beforeData,
afterData: afterData,
textContent: r.fullContent || (typeof r.data === 'string' ? r.data : '')
textContent: r.fullContent || (typeof r.data === 'string' ? r.data : ''),
beforeBlob,
afterBlob
};
}));
const fd = new FormData();
const metaItems = [];
const getExt = (blob, fallbackType) => {
const type = (blob && blob.type) || fallbackType || '';
if (type.includes('jpeg') || type.includes('jpg')) return '.jpg';
if (type.includes('webp')) return '.webp';
if (type.includes('gif')) return '.gif';
if (type.includes('svg')) return '.svg';
if (type.includes('avif')) return '.avif';
return '.png';
};
for (const it of resolvedItems) {
if (it.beforeBlob) {
const ext = getExt(it.beforeBlob, 'image/png');
fd.append(`before_${it.index}`, it.beforeBlob, `before_${it.index}${ext}`);
}
if (it.afterBlob) {
const ext = getExt(it.afterBlob, it.contentType);
fd.append(`after_${it.index}`, it.afterBlob, `after_${it.index}${ext}`);
}
metaItems.push({
index: it.index,
status: it.status,
latency: it.latency,
inputFilename: it.inputFilename,
outputFilename: it.outputFilename,
contentType: it.contentType,
textContent: it.textContent
});
}
const activeSpace = this.state.spaces.find(s => s.id === this.state.activeSpaceId);
const payload = {
fd.append('meta', JSON.stringify({
title: title || `Comparison Draft (${results.length} items)`,
notes: notes,
endpoint: this.state.url || '',
spaceName: activeSpace ? activeSpace.name : 'Workspace',
items: items
};
items: metaItems
}));
const basePath = window.location.pathname.includes('/tool/bulk-api-tester') ? '/tool/bulk-api-tester' : '';
const res = await fetch(`${basePath}/api/comparison-drafts`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
body: fd
});
if (!res.ok) {
@@ -3440,6 +3477,9 @@ const App = {
throw new Error(err.error || `HTTP ${res.status}`);
}
// Invalidate cache so drafts manager immediately loads latest
this._draftsCache = null;
document.querySelector('.save-draft-modal-overlay')?.remove();
this.toast(`Comparison draft saved!`, 'success');
this.updateDraftsBadge();
@@ -3520,10 +3560,102 @@ const App = {
modal.onclick = () => modal.remove();
this._selectedDraftItemKeys = new Set();
this._draftsCache = [];
if (this._draftsCache && this._draftsCache.length > 0) {
this._renderDraftsList(this._draftsCache);
}
await this.loadDraftsIntoManager();
},
_renderDraftsList(drafts) {
const container = document.getElementById('drafts-list-container');
if (!container) return;
if (!drafts || drafts.length === 0) {
container.innerHTML = `
<div style="padding:50px 20px; text-align:center; display:flex; flex-direction:column; align-items:center; gap:12px;">
<i class="fa-solid fa-folder-open" style="font-size:42px; color:var(--text-3); opacity:0.6;"></i>
<h4 style="font-family:var(--font-display); font-size:15px; color:var(--text-2); margin:0;">No Comparison Drafts Saved</h4>
<p style="font-size:12px; color:var(--text-3); max-width:400px; margin:0; line-height:1.5;">
When you execute single or batch API tests, click <b>"Save Draft"</b> to store the results here. Later, you can select and merge multiple drafts into a single shareable comparison link under one custom heading.
</p>
${this.state.bulk.results.length > 0 ? `
<button class="btn btn-primary btn-sm" style="margin-top:6px;" onclick="App.openSaveDraftModal()">
<i class="fa-solid fa-floppy-disk"></i> Save Current Results as First Draft
</button>
` : ''}
</div>
`;
return;
}
container.innerHTML = drafts.map(draft => {
const dateStr = new Date(draft.createdAt).toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
return `
<div class="draft-card" id="draft-card-${draft.id}">
<div class="draft-card-head">
<div class="draft-title-wrap">
<input type="checkbox" class="draft-checkbox" id="draft-cb-${draft.id}" onchange="App.onDraftCardCheckboxChange('${draft.id}', this.checked)" />
<div>
<div class="draft-title-text">${this.escapeHTML(draft.title)}</div>
<div style="display:flex; align-items:center; gap:8px; font-size:11px; color:var(--text-3); margin-top:3px; font-family:var(--font-mono);">
<span><i class="fa-regular fa-clock"></i> ${dateStr}</span>
${draft.spaceName ? `<span>· ${this.escapeHTML(draft.spaceName)}</span>` : ''}
${draft.endpoint ? `<span title="${this.escapeHTML(draft.endpoint)}">· ${this.escapeHTML(draft.endpoint.substring(0, 36))}...</span>` : ''}
</div>
</div>
</div>
<div style="display:flex; align-items:center; gap:8px;">
<span class="stat-capsule">${draft.total} Items</span>
${draft.avgLatency > 0 ? `<span class="stat-capsule"><i class="fa-solid fa-gauge-high"></i> ${draft.avgLatency}ms</span>` : ''}
<span class="stat-capsule ${draft.errorCount === 0 ? 'success' : 'error'}">${draft.successCount} OK</span>
<button class="btn btn-ghost btn-xs" onclick="App.shareSingleDraft('${draft.id}')" title="Generate shareable comparison link for this draft">
<i class="fa-solid fa-share-nodes"></i> Share
</button>
<button class="btn btn-ghost btn-xs" style="color:var(--danger);" onclick="App.deleteDraft('${draft.id}')" title="Delete draft">
<i class="fa-solid fa-trash"></i>
</button>
</div>
</div>
${draft.notes ? `
<div style="font-size:11.5px; color:var(--text-2); background:rgba(0,0,0,0.22); padding:6px 10px; border-radius:var(--r-sm); border:1px solid var(--border-1);">
<i class="fa-solid fa-note-sticky" style="color:var(--accent); margin-right:4px;"></i> ${this.escapeHTML(draft.notes)}
</div>
` : ''}
<!-- Items Strip -->
<div class="draft-items-strip">
${(draft.items || []).map(it => {
const key = `${draft.id}:${it.index}`;
const isChecked = this._selectedDraftItemKeys && this._selectedDraftItemKeys.has(key);
const afterUrl = it.afterImage ? (window.location.pathname.includes('/tool/bulk-api-tester') ? '/tool/bulk-api-tester' + it.afterImage : it.afterImage) : '';
return `
<div class="draft-item-card ${isChecked ? 'selected' : ''}" id="item-card-${draft.id}-${it.index}" onclick="App.toggleDraftItemDirectly('${draft.id}', ${it.index})">
<div class="draft-item-thumb">
<input type="checkbox" class="draft-item-checkbox" id="item-cb-${draft.id}-${it.index}"
${isChecked ? 'checked' : ''}
onclick="event.stopPropagation(); App.onDraftItemCbChange('${draft.id}', ${it.index}, this.checked)" />
${afterUrl ? `<img src="${afterUrl}" loading="lazy" decoding="async" />` : `<i class="fa-solid fa-file-code" style="color:var(--text-3); font-size:20px;"></i>`}
</div>
<div style="font-size:10.5px; font-weight:600; color:var(--text-1); overflow:hidden; text-overflow:ellipsis; white-space:nowrap;" title="${this.escapeHTML(it.outputFilename || it.inputFilename || '')}">
${this.escapeHTML(it.outputFilename || it.inputFilename || `#${it.index}`)}
</div>
<div style="display:flex; justify-content:space-between; align-items:center; font-size:10px; color:var(--text-3); font-family:var(--font-mono);">
<span>#${it.index}</span>
<span style="color:${String(it.status).startsWith('2') ? 'var(--success)' : 'var(--danger)'}; font-weight:700;">${it.status}</span>
<span>${it.latency}ms</span>
</div>
</div>
`;
}).join('')}
</div>
</div>
`;
}).join('');
this.updateDraftCounters();
},
async loadDraftsIntoManager() {
const container = document.getElementById('drafts-list-container');
if (!container) return;
@@ -3534,99 +3666,16 @@ const App = {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const drafts = await res.json();
this._draftsCache = drafts || [];
if (this._draftsCache.length === 0) {
container.innerHTML = `
<div style="padding:50px 20px; text-align:center; display:flex; flex-direction:column; align-items:center; gap:12px;">
<i class="fa-solid fa-folder-open" style="font-size:42px; color:var(--text-3); opacity:0.6;"></i>
<h4 style="font-family:var(--font-display); font-size:15px; color:var(--text-2); margin:0;">No Comparison Drafts Saved</h4>
<p style="font-size:12px; color:var(--text-3); max-width:400px; margin:0; line-height:1.5;">
When you execute single or batch API tests, click <b>"Save Draft"</b> to store the results here. Later, you can select and merge multiple drafts into a single shareable comparison link under one custom heading.
</p>
${this.state.bulk.results.length > 0 ? `
<button class="btn btn-primary btn-sm" style="margin-top:6px;" onclick="App.openSaveDraftModal()">
<i class="fa-solid fa-floppy-disk"></i> Save Current Results as First Draft
</button>
` : ''}
</div>
`;
return;
}
container.innerHTML = this._draftsCache.map(draft => {
const dateStr = new Date(draft.createdAt).toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
return `
<div class="draft-card" id="draft-card-${draft.id}">
<div class="draft-card-head">
<div class="draft-title-wrap">
<input type="checkbox" class="draft-checkbox" id="draft-cb-${draft.id}" onchange="App.onDraftCardCheckboxChange('${draft.id}', this.checked)" />
<div>
<div class="draft-title-text">${this.escapeHTML(draft.title)}</div>
<div style="display:flex; align-items:center; gap:8px; font-size:11px; color:var(--text-3); margin-top:3px; font-family:var(--font-mono);">
<span><i class="fa-regular fa-clock"></i> ${dateStr}</span>
${draft.spaceName ? `<span>· ${this.escapeHTML(draft.spaceName)}</span>` : ''}
${draft.endpoint ? `<span title="${this.escapeHTML(draft.endpoint)}">· ${this.escapeHTML(draft.endpoint.substring(0, 36))}...</span>` : ''}
</div>
</div>
</div>
<div style="display:flex; align-items:center; gap:8px;">
<span class="stat-capsule">${draft.total} Items</span>
${draft.avgLatency > 0 ? `<span class="stat-capsule"><i class="fa-solid fa-gauge-high"></i> ${draft.avgLatency}ms</span>` : ''}
<span class="stat-capsule ${draft.errorCount === 0 ? 'success' : 'error'}">${draft.successCount} OK</span>
<button class="btn btn-ghost btn-xs" onclick="App.shareSingleDraft('${draft.id}')" title="Generate shareable comparison link for this draft">
<i class="fa-solid fa-share-nodes"></i> Share
</button>
<button class="btn btn-ghost btn-xs" style="color:var(--danger);" onclick="App.deleteDraft('${draft.id}')" title="Delete draft">
<i class="fa-solid fa-trash"></i>
</button>
</div>
</div>
${draft.notes ? `
<div style="font-size:11.5px; color:var(--text-2); background:rgba(0,0,0,0.22); padding:6px 10px; border-radius:var(--r-sm); border:1px solid var(--border-1);">
<i class="fa-solid fa-note-sticky" style="color:var(--accent); margin-right:4px;"></i> ${this.escapeHTML(draft.notes)}
</div>
` : ''}
<!-- Items Strip -->
<div class="draft-items-strip">
${(draft.items || []).map(it => {
const key = `${draft.id}:${it.index}`;
const isChecked = this._selectedDraftItemKeys.has(key);
const afterUrl = it.afterImage ? (window.location.pathname.includes('/tool/bulk-api-tester') ? '/tool/bulk-api-tester' + it.afterImage : it.afterImage) : '';
return `
<div class="draft-item-card ${isChecked ? 'selected' : ''}" id="item-card-${draft.id}-${it.index}" onclick="App.toggleDraftItemDirectly('${draft.id}', ${it.index})">
<div class="draft-item-thumb">
<input type="checkbox" class="draft-item-checkbox" id="item-cb-${draft.id}-${it.index}"
${isChecked ? 'checked' : ''}
onclick="event.stopPropagation(); App.onDraftItemCbChange('${draft.id}', ${it.index}, this.checked)" />
${afterUrl ? `<img src="${afterUrl}" loading="lazy" />` : `<i class="fa-solid fa-file-code" style="color:var(--text-3); font-size:20px;"></i>`}
</div>
<div style="font-size:10.5px; font-weight:600; color:var(--text-1); overflow:hidden; text-overflow:ellipsis; white-space:nowrap;" title="${this.escapeHTML(it.outputFilename || it.inputFilename || '')}">
${this.escapeHTML(it.outputFilename || it.inputFilename || `#${it.index}`)}
</div>
<div style="display:flex; justify-content:space-between; align-items:center; font-size:10px; color:var(--text-3); font-family:var(--font-mono);">
<span>#${it.index}</span>
<span style="color:${String(it.status).startsWith('2') ? 'var(--success)' : 'var(--danger)'}; font-weight:700;">${it.status}</span>
<span>${it.latency}ms</span>
</div>
</div>
`;
}).join('')}
</div>
</div>
`;
}).join('');
this.updateDraftCounters();
this._renderDraftsList(this._draftsCache);
} catch(e) {
container.innerHTML = `
<div style="padding:40px; text-align:center; color:var(--danger);">
<i class="fa-solid fa-triangle-exclamation" style="font-size:28px; margin-bottom:8px;"></i>
<div>Failed to load drafts: ${this.escapeHTML(e.message)}</div>
</div>
`;
if (!this._draftsCache || this._draftsCache.length === 0) {
container.innerHTML = `
<div style="padding:40px; text-align:center; color:var(--danger);">
<i class="fa-solid fa-triangle-exclamation" style="font-size:28px; margin-bottom:8px;"></i>
<div>Failed to load drafts: ${this.escapeHTML(e.message)}</div>
</div>
`;
}
}
},