Files
Aislo/B06_Section/B06_Section_Section_Store.ts
T
eomsangdonandClaude Opus 5 0e2309f5ce fix(B05): 지운 구조물 부활 차단 · 임시저장이 캐시 수정분을 저장하도록
사용자 확정 모델: 초기 계산값은 **원복용으로 그대로 두고**, 사용자가 제어한 수정
1세트가 최종본이다. 여러 세트는 두지 않는다. 두 곳이 이 모델을 어기고 있었다.

① 지운 구조물이 되살아난다 — B05는 그려질 때마다 종단 정본의 비정규 측점을 모아
   `/structures/migrate`를 부른다. 서버의 "멱등" 기준이 **지금 그 자리에 구조물이
   있는가**여서, 사용자가 지우면 자리가 비고 다음 진입에서 같은 구조물이 다시
   생성됐다(진행단계 오버레이로 오가면 매번). 옮긴 자리를 `structures.json`의
   `migrated_legacy`에 **이력으로** 남기고, 이력에 있으면 구조물이 없어도 다시 만들지
   않는다. 원천(비정규 측점)은 원복용으로 손대지 않는다. 이력은 일반 저장 경로에서도
   보존한다 — 사라지면 삭제분이 부활한다.

② 임시저장이 캐시 수정분을 버린다 — B05 [임시저장]이 `cross_patches`를 보내지 않고
   `invalidateSectionDetail`로 공유 캐시를 비웠다. B06에서 만져 캐시에 얹힌 구조물
   조정(4축·다단·연동·표시 반폭)이 영구저장소에 못 가고 사라졌다. 계획선·비정규 측점
   저장 **뒤에** 캐시 수정분을 `saveSections`로 남기고, 그 다음에 캐시를 비운다 —
   순서가 뒤바뀌면 재계산이 사용자 수정을 덮는다.

`saveCachedCrossPatches`·`crossPatchesFromCache`는 공유 캐시 모듈에 뒀다 — B05 페이지
파일이 이미 700줄을 넘겨 더 불리지 않기 위함이다(기존 부채).

tsc/ruff/prettier 통과, pytest 200 passed(기존 실패 1건 유지).
신규 검증: tmp/tests/test_b05_structures_migration_history.py 4건.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-24 19:56:40 +09:00

125 lines
5.6 KiB
TypeScript

/* =============================================================================
* B06_Section_Section_Store.ts
* 종횡단 상세(SectionDetailResponse)의 **프론트 공유 캐시** — B05·B06이 같은 객체를 본다.
*
* ── 왜 필요한가 (2026-08-03 사용자 확정) ─────────────────────────────
* B05(노선·계획선)와 B06(종횡단 설계)은 같은 영구저장소 데이터의 두 창이다. 페이지마다
* 따로 fetch해 제각각 들고 있으면, B06에서 지반유형·암 경계를 고친 뒤 B05로 넘어갔을 때
* 횡단 기준 유토곡선이 옛 값으로 그려진다(사용자가 실제로 겪은 문제). 여기서 한 번 받아
* **같은 객체 참조**를 두 페이지에 주면, B06이 측점 설계를 제자리 갱신하는 순간 B05가
* 다음 그리기에서 그대로 본다 — 별도 동기화 코드가 필요 없다.
*
* ── 수명 규칙 ─────────────────────────────────────────────────────
* 키는 `projectId:routeId`. SPA 모듈 싱글턴이라 페이지를 오가도 살아 있고, 새로고침이면
* 사라져 영구저장소에서 다시 받는다(영구저장소가 항상 정본). 서버가 파일을 통째로 다시
* 쓰는 조작(재생성·계획선 편집 저장·확정)은 그 응답/재조회로 `replace`·`invalidate`한다.
* ========================================================================== */
import type { CrossSectionPatch, SectionDetailResponse } from "./B06_Section_Api_Fetch";
import { fetchSectionDetail, saveSections } from "./B06_Section_Api_Fetch";
const cache = new Map<string, SectionDetailResponse>();
const pending = new Map<string, Promise<SectionDetailResponse>>();
function keyOf(projectId: string, routeId: number): string {
return `${projectId}:${routeId}`;
}
/**
* 상세를 가져온다 — 캐시가 있으면 **같은 객체**를 즉시 돌려주고, 없으면 한 번만 fetch한다
* (동시 호출은 같은 Promise를 공유). `force`면 캐시를 버리고 다시 받는다.
*/
export async function loadSectionDetail(
projectId: string,
routeId: number,
options?: { force?: boolean },
): Promise<SectionDetailResponse> {
const key = keyOf(projectId, routeId);
if (!options?.force) {
const cached = cache.get(key);
if (cached) return cached;
const inFlight = pending.get(key);
if (inFlight) return inFlight;
}
const request = fetchSectionDetail(projectId, routeId)
.then((detail) => {
cache.set(key, detail);
return detail;
})
.finally(() => {
pending.delete(key);
});
pending.set(key, request);
return request;
}
/** 서버가 새 상세를 통째로 돌려준 조작(재생성 등) 뒤 캐시를 그 값으로 바꾼다. */
export function replaceSectionDetail(
projectId: string,
routeId: number,
detail: SectionDetailResponse,
): void {
cache.set(keyOf(projectId, routeId), detail);
}
/**
* 캐시를 비운다. routeId를 생략하면 그 프로젝트 전부 —
* 서버 쪽 정본이 바뀌었는데 새 상세를 손에 못 쥔 조작(계획선 편집 저장 등) 뒤에 쓴다.
*/
export function invalidateSectionDetail(projectId: string, routeId?: number): void {
if (routeId !== undefined) {
cache.delete(keyOf(projectId, routeId));
return;
}
const prefix = `${projectId}:`;
for (const key of [...cache.keys()]) {
if (key.startsWith(prefix)) cache.delete(key);
}
}
/**
* 캐시에 얹힌 **사용자 수정분**을 저장 payload로 뽑는다(2026-08-24 사용자 확정 흐름).
*
* 초기 계산값은 원복용으로 서버에 그대로 있고, 사용자가 만진 값은 이 캐시 한 세트가
* 최종본이다. B05 [임시저장]도 이 세트를 함께 보내야 B06에서 만진 구조물 조정이
* 영구저장소에 남는다 — 안 보내면 캐시만 비워져 편집이 사라진다.
*
* 초기 계산값에는 없는 키(사용자가 만져야 생기는 키)만 싣는다.
*/
export function crossPatchesFromCache(detail: SectionDetailResponse): CrossSectionPatch[] {
const patches: CrossSectionPatch[] = [];
for (const section of detail.cross_sections) {
const design = section.design;
if (!design) continue;
const patch: CrossSectionPatch = { chainage_m: section.chainage_m };
let touched = false;
const put = <K extends keyof CrossSectionPatch>(key: K, value: CrossSectionPatch[K]): void => {
if (value === undefined || value === null) return;
patch[key] = value;
touched = true;
};
put("display_half_width_m", design.display_half_width_m);
put("inlet_structure", design.inlet_structure);
put("basin_adjust", design.basin_adjust);
put("revet_adjust", design.revet_adjust);
put("extra_wall_counts", design.extra_wall_counts);
put("revet_link_detached", design.revet_link_detached);
put("revet_follow_grade", design.revet_follow_grade);
if (touched) patches.push(patch);
}
return patches;
}
/**
* 캐시에 얹힌 사용자 수정분을 영구저장소에 남긴다(임시저장용). 캐시가 없거나 수정분이
* 없으면 아무것도 보내지 않는다. 저장 실패는 호출자가 처리한다.
*/
export async function saveCachedCrossPatches(projectId: string, routeId: number): Promise<number> {
const detail = cache.get(keyOf(projectId, routeId));
if (!detail) return 0;
const patches = crossPatchesFromCache(detail);
if (!patches.length) return 0;
await saveSections(projectId, routeId, undefined, patches);
return patches.length;
}