Merge remote-tracking branch 'origin/main' into feature/social-post
# Conflicts: # docs/DECISIONS.md # docs/DEVLOG.md # solution/backend/requirements.txt # solution/backend/scheduler/__init__.py # solution/backend/worker/handlers.py # solution/site/src/pages/HomePage.tsx # solution/site/src/sections/index.ts
This commit is contained in:
commit
58d6249102
502 files changed
+127276
-5267
No files matched your search
@@ -89,7 +89,9 @@ class FaqCRUD(IFaqCRUD):
|
||||
.where(
|
||||
place_faqs.place_id == place_id,
|
||||
place_faqs.deleted == False, # noqa: E712
|
||||
place_faqs.generated_by == SourceType.LLM.value,
|
||||
# 목표 수를 채운 공통 질문(TEMPLATE)도 자동 산출물이다 — 재생성마다 다시 고른다.
|
||||
# 안 내리면 fact 가 새로 생겨 LLM 이 답한 주제에 옛 문의 안내가 겹쳐 남는다.
|
||||
place_faqs.generated_by.in_((SourceType.LLM.value, SourceType.TEMPLATE.value)),
|
||||
# 이미 내려간 것(EXPIRED)과 사장님이 반려한 것(REJECTED)은 그대로 둔다 —
|
||||
# 반려는 판단의 기록이라 재생성이 지울 이유가 없다.
|
||||
place_faqs.status.not_in((FactStatus.EXPIRED.value, FactStatus.REJECTED.value)),
|
||||
|
||||
@@ -83,7 +83,7 @@ class JobQueue:
|
||||
FOR UPDATE SKIP LOCKED
|
||||
LIMIT 1
|
||||
)
|
||||
RETURNING job_id, job_type, payload, attempts, max_attempts
|
||||
RETURNING job_id, job_type, payload, attempts, max_attempts, worker_id
|
||||
""")
|
||||
|
||||
async def run(s):
|
||||
@@ -140,6 +140,25 @@ class JobQueue:
|
||||
|
||||
return await self._tx(run)
|
||||
|
||||
async def fail_permanent(self, job_id: str, worker_id: str, error: str) -> bool:
|
||||
"""재시도 없이 바로 DEAD. 시도 횟수가 남아 있어도 보내지 않는다.
|
||||
|
||||
★ 다시 해도 같은 결과인 실패에 쓴다(common/job_errors.PermanentJobError).
|
||||
백오프 재큐는 '일시적 장애' 라는 판단인데, 사업장이 지워졌거나 업종이 없는 잡은
|
||||
그 판단이 틀렸다 — 큐만 붙들고 DEAD 알림을 세 배로 늘린다."""
|
||||
sql = text("""
|
||||
UPDATE jobs SET status = 4, last_error = :err,
|
||||
lease_until = NULL, worker_id = NULL, updated_at = now()
|
||||
WHERE job_id = CAST(:id AS uuid) AND status = 2 AND worker_id = :wid
|
||||
RETURNING job_id
|
||||
""")
|
||||
|
||||
async def run(s):
|
||||
row = (await s.execute(sql, {"id": job_id, "wid": worker_id, "err": error[:2000]})).first()
|
||||
return row is not None
|
||||
|
||||
return await self._tx(run)
|
||||
|
||||
# ---- lease 갱신(heartbeat) / 회수(reaper) ----
|
||||
async def renew_lease(self, job_id: str, worker_id: str, lease_sec: int = 120) -> bool:
|
||||
sql = text("""
|
||||
@@ -176,11 +195,41 @@ class JobQueue:
|
||||
return await self._tx(run)
|
||||
|
||||
# ---- 단건 조회 (상태 폴링) ----
|
||||
async def set_progress(self, job: dict, progress: dict) -> bool:
|
||||
# 회수된 옛 워커가 새 시도의 진행 상태를 덮지 못하게 한다.
|
||||
sql = text("""
|
||||
UPDATE jobs SET progress = CAST(:progress AS jsonb), updated_at = now()
|
||||
WHERE job_id = CAST(:id AS uuid) AND status = 2
|
||||
AND worker_id = :wid AND attempts = :attempt
|
||||
AND lease_until > now()
|
||||
RETURNING job_id
|
||||
""")
|
||||
|
||||
async def run(s):
|
||||
row = (await s.execute(sql, {
|
||||
"id": job["job_id"], "wid": job["worker_id"], "attempt": job["attempts"],
|
||||
"progress": json.dumps(progress),
|
||||
})).first()
|
||||
return row is not None
|
||||
|
||||
return await self._tx(run)
|
||||
|
||||
async def find_latest(self, dedupe_key: str) -> dict | None:
|
||||
"""복구는 완료·실패 이력도 찾는다. 활성 중복 방지와 다른 조회다."""
|
||||
async def run(s):
|
||||
row = (await s.execute(text("""
|
||||
SELECT job_id, status FROM jobs WHERE dedupe_key = :dk
|
||||
ORDER BY created_at DESC, job_id DESC LIMIT 1
|
||||
"""), {"dk": dedupe_key})).mappings().first()
|
||||
return {**row, "job_id": str(row["job_id"])} if row else None
|
||||
|
||||
return await DB_SESSION_MNG.execute_lambda(self.DB, DBWRType.DB_READ.value, run)
|
||||
|
||||
async def get(self, job_id: str) -> dict | None:
|
||||
"""잡 단건 조회(읽기). 없으면 None. status 는 정수(JobStatus 값)."""
|
||||
sql = text("""
|
||||
SELECT job_id, job_type, status, priority, attempts, max_attempts,
|
||||
payload, result, last_error, run_after, run_started_at, created_at, updated_at
|
||||
payload, result, progress, last_error, run_after, run_started_at, created_at, updated_at
|
||||
FROM jobs WHERE job_id = CAST(:id AS uuid)
|
||||
""")
|
||||
|
||||
@@ -190,7 +239,7 @@ class JobQueue:
|
||||
return None
|
||||
d = dict(row)
|
||||
d["job_id"] = str(d["job_id"])
|
||||
for key in ("payload", "result"):
|
||||
for key in ("payload", "result", "progress"):
|
||||
if isinstance(d.get(key), str):
|
||||
d[key] = json.loads(d[key])
|
||||
return d
|
||||
|
||||
@@ -31,6 +31,7 @@ class PlaceContentCRUD:
|
||||
select(
|
||||
area_contents.local_content_id,
|
||||
area_contents.content_type,
|
||||
area_contents.source,
|
||||
area_contents.external_id,
|
||||
area_contents.title,
|
||||
area_contents.body,
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
"""발행 DB를 작업 원장으로 사용해 알림 적재 실패/재시작에도 대상을 다시 찾는다."""
|
||||
from sqlalchemy import select, or_, text
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
|
||||
from common.database.model.models import sites, places, site_versions, site_search_status as Status
|
||||
from common.enums import SiteStatus
|
||||
|
||||
|
||||
def published_conditions():
|
||||
return (
|
||||
sites.deleted.is_(False), places.deleted.is_(False),
|
||||
sites.status == SiteStatus.PUBLISHED.value,
|
||||
sites.published_at.is_not(None), sites.current_version_id.is_not(None),
|
||||
)
|
||||
|
||||
|
||||
async def lock_batch(session) -> bool:
|
||||
# 여러 API 프로세스가 같은 크론을 등록해도 외부 호출은 한 곳만 수행한다.
|
||||
return bool(await session.scalar(text("SELECT pg_try_advisory_xact_lock(734920151)")))
|
||||
|
||||
|
||||
async def new_publications(session, property_url: str):
|
||||
result = await session.execute(
|
||||
select(sites, places, site_versions)
|
||||
.join(places, places.place_id == sites.place_id)
|
||||
.join(site_versions, site_versions.site_version_id == sites.current_version_id)
|
||||
.outerjoin(Status, Status.site_id == sites.site_id)
|
||||
.where(*published_conditions(), site_versions.deleted.is_(False), or_(
|
||||
Status.site_id.is_(None), Status.site_version_id != sites.current_version_id,
|
||||
Status.property_url != property_url, Status.published_at != sites.published_at,
|
||||
))
|
||||
.order_by(sites.published_at).limit(100)
|
||||
)
|
||||
return result.all()
|
||||
|
||||
|
||||
async def register(session, values: dict):
|
||||
reset = dict(values, sitemap_submitted_at=None, inspected_at=None, first_indexed_at=None,
|
||||
inspection=None, error_code=None, failures=0, alerted_at=None,
|
||||
next_check_at=text("now()"), updated_at=text("now()"), deleted=False)
|
||||
await session.execute(insert(Status).values(**values).on_conflict_do_update(
|
||||
index_elements=[Status.site_id], set_=reset,
|
||||
))
|
||||
|
||||
|
||||
async def due_sites(session, property_url: str):
|
||||
result = await session.execute(
|
||||
select(Status).join(sites, sites.site_id == Status.site_id)
|
||||
.join(places, places.place_id == sites.place_id)
|
||||
.where(*published_conditions(), Status.deleted.is_(False),
|
||||
Status.site_version_id == sites.current_version_id,
|
||||
Status.published_at == sites.published_at, Status.property_url == property_url,
|
||||
Status.next_check_at <= text("now()"))
|
||||
.order_by(Status.next_check_at).limit(5)
|
||||
.with_for_update(of=Status)
|
||||
)
|
||||
return result.scalars().all()
|
||||
@@ -5,12 +5,34 @@ from sqlalchemy import and_, func, select, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import places, site_publish_logs, site_versions, sites
|
||||
from common.enums import BuildStatus, ErrorType, SiteStatus
|
||||
from common.database.model.models import place_photos, places, site_publish_logs, site_versions, sites
|
||||
from common.enums import BuildStatus, ErrorType, MediaStatus, SiteStatus
|
||||
from common.logger import LOG
|
||||
from common.utils.gtime import GTime
|
||||
|
||||
|
||||
def _primary_photo_subquery():
|
||||
"""place_photos 에서 대표 사진 한 장의 url 만 고르는 상관 서브쿼리(사업장당 1행).
|
||||
|
||||
site_payload.primary_media 와 같은 규칙 — 객실·메뉴 사진(unit_id 있음)이 아닌 첫 장,
|
||||
sort_order 순. `.correlate(places)` 라서 바깥 쿼리가 `places` 를 셀렉트에 들고 있어야 한다.
|
||||
sites.thumbnail_url 이 비어 있을 때(Azure 썸네일 저장소 미설정 등) 서비스 계층이 이걸로
|
||||
대신 채운다 — 여기서는 후보만 얹고, 언제 쓸지는 서비스 계층 몫이다."""
|
||||
return (
|
||||
select(place_photos.url)
|
||||
.where(
|
||||
place_photos.place_id == places.place_id,
|
||||
place_photos.deleted == False, # noqa: E712
|
||||
place_photos.status == MediaStatus.APPROVED.value,
|
||||
place_photos.unit_id.is_(None),
|
||||
)
|
||||
.order_by(place_photos.sort_order.asc(), place_photos.created_at.asc())
|
||||
.limit(1)
|
||||
.correlate(places)
|
||||
.scalar_subquery()
|
||||
)
|
||||
|
||||
|
||||
# 사이트/버전/발행로그 CRUD. 항상 place_id 또는 site_id 로 스코프한다.
|
||||
class ISiteCRUD(ABC):
|
||||
@abstractmethod
|
||||
@@ -23,6 +45,7 @@ class ISiteCRUD(ABC):
|
||||
|
||||
@abstractmethod
|
||||
async def list_owner_sites(self, cdb: AsyncSession, owner_user_id, skip, limit) -> Tuple[ErrorType, list, int]:
|
||||
"""(ErrorType, [(place, site, built_at, primary_photo_url)], 총건수)."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
@@ -45,6 +68,10 @@ class ISiteCRUD(ABC):
|
||||
async def get_version(self, cdb: AsyncSession, site_id, site_version_id) -> Tuple[ErrorType, site_versions]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_version_by_number(self, cdb: AsyncSession, site_id, version: int) -> Tuple[ErrorType, site_versions]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def finish_version(self, cdb: AsyncSession, site_version_id, data: dict) -> Tuple[ErrorType, int]:
|
||||
pass
|
||||
@@ -63,6 +90,7 @@ class ISiteCRUD(ABC):
|
||||
|
||||
@abstractmethod
|
||||
async def list_published(self, cdb: AsyncSession, limit: int) -> Tuple[ErrorType, list]:
|
||||
"""(ErrorType, [(site, place, primary_photo_url)])."""
|
||||
pass
|
||||
|
||||
|
||||
@@ -94,10 +122,16 @@ class SiteCRUD(ISiteCRUD):
|
||||
return ErrorType.DB_RUN_FAILED, None
|
||||
|
||||
async def list_owner_sites(self, cdb: AsyncSession, owner_user_id, skip: int, limit: int) -> Tuple[ErrorType, list, int]:
|
||||
"""사장님의 사업장 + 사이트 + 마지막 빌드 시각. (ErrorType, [(place, site, built_at)], 총건수).
|
||||
"""사장님의 사업장 + 사이트 + 마지막 빌드 시각 + 빌더 대표 사진.
|
||||
(ErrorType, [(place, site, built_at, primary_photo_url)], 총건수).
|
||||
|
||||
따로 읽으면 줄마다 사이트를 다시 물어 N+1 이다. LEFT JOIN 이라 사이트가 없는 사업장
|
||||
(위저드만 걸어온 것)도 내려간다 — 빠지면 만들다 만 것을 찾을 길이 없다."""
|
||||
(위저드만 걸어온 것)도 내려간다 — 빠지면 만들다 만 것을 찾을 길이 없다.
|
||||
|
||||
★ primary_photo_url 은 site_payload.primary_media 와 같은 규칙(사진 중 객실·메뉴가 아닌
|
||||
첫 장, sort_order 순)으로 고른 place_photos.url 이다 — sites.thumbnail_url 이 비어 있을 때
|
||||
(Azure 썸네일 저장소 미설정 등으로 재호스팅에 실패한 경우) 서비스 계층이 이걸로 대신 채운다.
|
||||
여기서는 후보만 얹고, "발행한 적 있는 줄에만 쓴다"는 판단은 서비스 계층 몫이다."""
|
||||
try:
|
||||
where = and_(places.deleted == False, places.owner_user_id == owner_user_id) # noqa: E712
|
||||
|
||||
@@ -107,7 +141,7 @@ class SiteCRUD(ISiteCRUD):
|
||||
total = int(cnt_rows[0] or 0) if cnt_rows else 0
|
||||
|
||||
query = (
|
||||
select(places, sites, site_versions.built_at)
|
||||
select(places, sites, site_versions.built_at, _primary_photo_subquery())
|
||||
.outerjoin(sites, and_(sites.place_id == places.place_id, sites.deleted == False)) # noqa: E712
|
||||
.outerjoin(site_versions, site_versions.site_version_id == sites.current_version_id)
|
||||
.where(where)
|
||||
@@ -189,6 +223,31 @@ class SiteCRUD(ISiteCRUD):
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, None
|
||||
|
||||
async def get_version_by_number(self, cdb: AsyncSession, site_id, version: int) -> Tuple[ErrorType, site_versions]:
|
||||
"""롤백 대상 조회 — site_versions.version(사람이 보는 번호) 로 찾는다.
|
||||
|
||||
★ site_version_id(uuid) 가 아니다. 화면·API 는 버전 번호로 고르는 게 자연스럽고,
|
||||
그 번호가 곧 out/versions/<slug>/<version>/ 디렉토리 이름이다(prerender.ts)."""
|
||||
try:
|
||||
query = (
|
||||
select(site_versions)
|
||||
.where(
|
||||
site_versions.site_id == site_id,
|
||||
site_versions.version == version,
|
||||
site_versions.deleted == False, # noqa: E712
|
||||
)
|
||||
.limit(1)
|
||||
)
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type, None
|
||||
if len(rows) != 1:
|
||||
return ErrorType.DB_INVALID_KEY, None
|
||||
return ErrorType.SUCCESS, rows[0]
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, None
|
||||
|
||||
async def finish_version(self, cdb: AsyncSession, site_version_id, data: dict) -> Tuple[ErrorType, int]:
|
||||
"""빌드 결과를 버전에 기록한다(BUILT 또는 FAILED)."""
|
||||
try:
|
||||
@@ -236,14 +295,18 @@ class SiteCRUD(ISiteCRUD):
|
||||
return ErrorType.DB_RUN_FAILED, []
|
||||
|
||||
async def list_published(self, cdb: AsyncSession, limit: int = 12) -> Tuple[ErrorType, list]:
|
||||
"""발행된 사이트 + 그 사업장을 최신순으로. 랜딩 쇼케이스가 읽는 목록이다.
|
||||
"""발행된 사이트 + 그 사업장 + 빌더 대표 사진을 최신순으로. 랜딩 쇼케이스가 읽는 목록이다.
|
||||
(ErrorType, [(site, place, primary_photo_url)]).
|
||||
|
||||
★ 회사 스코프가 없는 **유일한** 사이트 조회다(비로그인 API 가 쓴다). 그래서 행을 통째로
|
||||
돌려주고, 무엇이 밖으로 나갈지는 services/showcase_service 한 곳에서만 고른다 —
|
||||
여기서 열을 골라 두면 나중에 필드를 늘릴 때 공개 여부를 판단할 자리가 사라진다."""
|
||||
여기서 열을 골라 두면 나중에 필드를 늘릴 때 공개 여부를 판단할 자리가 사라진다.
|
||||
|
||||
★ primary_photo_url 은 list_owner_sites 와 같은 서브쿼리(_primary_photo_subquery) —
|
||||
sites.thumbnail_url 이 비어 있을 때 showcase_service 가 이걸로 대신 채운다."""
|
||||
try:
|
||||
query = (
|
||||
select(sites, places)
|
||||
select(sites, places, _primary_photo_subquery())
|
||||
.join(places, places.place_id == sites.place_id)
|
||||
.where(
|
||||
sites.status == SiteStatus.PUBLISHED.value,
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import json
|
||||
from sqlalchemy import text
|
||||
from common.enums import JobType
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import place_social_posts as Post
|
||||
|
||||
@@ -41,7 +42,7 @@ async def decide(s, post_id, sha, approve, via):
|
||||
)
|
||||
).first()
|
||||
if row and approve and row.account_id:
|
||||
await enqueue(s, post_id, 9)
|
||||
await enqueue(s, post_id, JobType.SOCIAL_POST.value)
|
||||
return bool(row)
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user