fix(packs): serialize same-pack upload/delete; clipboard fallback on http dashboard

- per (domain, type) lock held from the Nextcloud PUT/DELETE through the packs.json write,
  so two concurrent replaces can't leave the file and its SHA1 out of sync
- navigator.clipboard is missing on http://<LAN-IP>; fall back to execCommand('copy')
  and tell the user to copy by hand if that fails too

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-23 15:55:11 +09:00
parent 03ab32f8ab
commit 4669418af1
2 changed files with 64 additions and 30 deletions

View File

@@ -40,7 +40,18 @@ PACK_TYPES = {
"modpack": {"label": "모드팩", "mcmeta": False},
}
_lock = threading.Lock()
_lock = threading.Lock() # packs.json 읽기-수정-쓰기 보호
_pack_locks: dict[tuple[str, str], threading.Lock] = {}
def _pack_lock(name: str, kind: str) -> threading.Lock:
"""같은 도메인·종류의 업로드/삭제를 Nextcloud 작업부터 메타 저장까지 한 줄로 세운다.
두 탭에서 동시에 교체하면 PUT 순서와 packs.json 저장 순서가 엇갈려 파일과 SHA1 이
어긋날 수 있어서다. uvicorn 워커가 1개(Dockerfile CMD 기본값)라 프로세스 내 락으로 충분하다.
"""
with _lock:
return _pack_locks.setdefault((name, kind), threading.Lock())
def _load_packs() -> dict:
@@ -149,27 +160,27 @@ def upload_pack(domain: str, kind: str, file: UploadFile) -> dict:
detail="zip 최상위에 pack.mcmeta 가 없습니다. 폴더째 압축하지 말고 폴더 안의 내용물을 압축해 주세요.",
)
with _client(timeout=None) as client:
_ensure_dir(client, name)
tmp.seek(0)
r = client.put(
_dav_url(name, f"{kind}.zip"),
content=iter(lambda: tmp.read(1024 * 1024), b""),
headers={"Content-Length": str(size)},
)
if r.status_code not in (201, 204):
raise HTTPException(status_code=502, detail=f"Nextcloud 업로드 실패: {r.status_code}")
meta = {
"sha1": sha1.hexdigest(),
"size": size,
"original_name": file.filename or f"{kind}.zip",
"uploaded_at": time.time(),
}
with _lock:
packs = _load_packs()
packs.setdefault(name, {})[kind] = meta
_save_packs(packs)
meta = {
"sha1": sha1.hexdigest(),
"size": size,
"original_name": file.filename or f"{kind}.zip",
}
with _pack_lock(name, kind):
with _client(timeout=None) as client:
_ensure_dir(client, name)
tmp.seek(0)
r = client.put(
_dav_url(name, f"{kind}.zip"),
content=iter(lambda: tmp.read(1024 * 1024), b""),
headers={"Content-Length": str(size)},
)
if r.status_code not in (201, 204):
raise HTTPException(status_code=502, detail=f"Nextcloud 업로드 실패: {r.status_code}")
meta["uploaded_at"] = time.time()
with _lock:
packs = _load_packs()
packs.setdefault(name, {})[kind] = meta
_save_packs(packs)
return {"domain": name, "kind": kind, "pack": {**meta, "url": _pack_url(kind, name)}}
@@ -178,18 +189,19 @@ def delete_pack(domain: str, kind: str) -> Response:
_require_storage()
_check_kind(kind)
name = domain.strip().lower()
with _lock:
packs = _load_packs()
if kind not in packs.get(name, {}):
with _pack_lock(name, kind):
if kind not in _load_packs().get(name, {}):
raise HTTPException(status_code=404, detail="pack not found")
with _client() as client:
r = client.delete(_dav_url(name, f"{kind}.zip"))
if r.status_code not in (204, 404):
raise HTTPException(status_code=502, detail=f"Nextcloud 삭제 실패: {r.status_code}")
packs[name].pop(kind)
if not packs[name]:
packs.pop(name)
_save_packs(packs)
with _lock:
packs = _load_packs()
packs[name].pop(kind, None)
if not packs[name]:
packs.pop(name)
_save_packs(packs)
return Response(status_code=204)

View File

@@ -26,6 +26,25 @@ function propsSnippet(pack) {
].join('\n')
}
// 대시보드는 http://<내부IP> 라 보안 컨텍스트가 아니어서 navigator.clipboard 가 없다.
// 그럴 땐 임시 textarea + execCommand('copy') 로 복사한다.
async function copyToClipboard(text) {
if (navigator.clipboard && window.isSecureContext) {
try { await navigator.clipboard.writeText(text); return true } catch { /* 아래로 */ }
}
const ta = document.createElement('textarea')
ta.value = text
ta.setAttribute('readonly', '')
ta.style.position = 'fixed'
ta.style.opacity = '0'
document.body.appendChild(ta)
ta.select()
let ok = false
try { ok = document.execCommand('copy') } catch { ok = false }
document.body.removeChild(ta)
return ok
}
// fetch 는 업로드 진행률을 못 주므로 XHR 사용
function uploadPack(domain, kind, file, onProgress) {
return new Promise((resolve, reject) => {
@@ -89,7 +108,10 @@ export default function Packs() {
}
async function copy(key, text) {
await navigator.clipboard.writeText(text)
if (!(await copyToClipboard(text))) {
setError('복사하지 못했습니다. 위 칸의 내용을 직접 선택해서 복사해 주세요.')
return
}
setCopied(key)
setTimeout(() => setCopied(null), 1500)
}