Mathchast CMS / Build Series / 10

D30 → Payload Pipeline

Полный интеграционный pipeline фабрики контента D30: package contract, validation, media, taxonomy, terms, idempotent upsert, draft-only permissions, review, publish и post-publish jobs.

D30Integration AdapterIdempotencyDraft OnlyReviewPublish Jobs

1. Ключевой принцип

D30
 ↓
Integration Adapter
 ↓
Payload REST / Local API
 ↓
Draft
 ↓
Review
 ↓
Publish
 ↓
Jobs
 ├── Meilisearch
 ├── Gorse
 ├── cache invalidation
 └── analytics/system events
D30 не пишет напрямую в PostgreSQL и не публикует контент.

2. D30 package contract

type D30ArticlePackage = {
  runId: string
  externalId: string
  pipelineVersion: string

  article: {
    title: string
    slug?: string
    excerpt?: string
    category: CategoryRef
    topics?: TopicRef[]
    terms?: TermCandidate[]
    source?: SourceRef
    heroImage?: MediaInput
    contentBlocks: D30Block[]
    d30Score?: number
    evidenceStatus?: string
    refreshAfter?: string
  }

  metadata?: {
    sourceUrl?: string
    sourceHash?: string
    inputHash?: string
    generatedAt?: string
  }
}

3. Обязательные поля

4. Validation stages

1. Envelope validation
2. Auth / service role validation
3. Schema validation
4. externalId validation
5. Taxonomy resolution
6. Terms resolution
7. Media resolution
8. Blocks validation
9. Quality fields validation
10. Idempotent upsert

5. Envelope validation

6. Auth

Только service account service_d30 или Integration Adapter с эквивалентными ограниченными правами.

7. externalId idempotency

existing = find Article by externalId

IF existing:
  update existing DRAFT
  action = update
ELSE:
  create new DRAFT
  action = create

never create duplicate for same externalId

8. inputHash optimization

if existing.importHash == incoming.inputHash:
  action = skip
  reason = identical_input

Это опциональная оптимизация. Она не заменяет проверку по externalId.

9. Category resolution

D30 category ref
↓
match by stable id/slug
↓
found → use relationship
↓
not found → fail item OR controlled mapping table
Не создавать новые top-level categories автоматически из D30 без отдельной политики.

10. Topic resolution

11. Term resolution

D30 term
 ↓
canonical/alias search
 ↓
existing term → relation
 ↓
no match → Term draft candidate
 ↓
article may reference only approved/existing term
or store pending candidate metadata separately

12. Media pipeline

MediaInput
 ↓
validate URL/file/type/size
 ↓
download or receive
 ↓
checksum
 ↓
dedupe
 ↓
upload through Payload Media
 ↓
relationship id

13. Media safety

14. Structured block mapping

D30 blockPayload block
rich_textRichTextBlock
imageImageBlock
galleryGalleryBlock
tableTableBlock
warningWarningBlock
quoteQuoteBlock
productProductBlock
adAdBlock
related_articlesRelatedArticlesBlock
term_referenceTermReferenceBlock

15. Unknown D30 block

Unknown block → item validation FAIL или explicit quarantine. Не сохранять raw HTML/unknown JSON silently.

16. Slug policy

17. Quality fields

FieldD30 может установитьPublish gate
d30ScoreYESinformational/threshold policy
evidenceStatusYESможет требовать review
qualityGateне финальный PASSфинальный PASS только review process
D30 не должен сам себе выдавать окончательное разрешение на публикацию.

18. ImportRuns lifecycle

queued
→ running
→ success | partial | failed | cancelled

19. ImportItems lifecycle

pending
→ success
   action=create|update|skip
OR
→ fail
   errorCode + errorMessage

20. Error taxonomy

AUTH_DENIED
SCHEMA_INVALID
EXTERNAL_ID_INVALID
CATEGORY_NOT_FOUND
TOPIC_INVALID
TERM_CONFLICT
MEDIA_DOWNLOAD_FAILED
MEDIA_TYPE_INVALID
BLOCK_UNKNOWN
BLOCK_INVALID
SLUG_CONFLICT
PAYLOAD_WRITE_FAILED
TIMEOUT
INTERNAL_ERROR

21. Retry policy

22. Dead-letter / quarantine

Repeated fail
 ↓
mark ImportItem failed
 ↓
store diagnostics
 ↓
manual review / reprocess command

Не нужен отдельный Kafka DLQ на MVP.

23. Transaction boundary

Критические CMS changes для одного article package должны быть максимально атомарны, но внешние сервисы Meili/Gorse не входят в DB transaction.

DB/CMS commit draft
      ↓
success
      ↓
enqueue downstream jobs

24. Review workflow

D30 draft
 ↓
editor/reviewer
 ↓
check:
- title/slug
- category/topics
- terms
- blocks
- evidence
- media
- safety
 ↓
qualityGate = pass
 ↓
publish by authorized role

25. Publish conditions

26. Post-publish jobs

Publish
 ├── searchIndexArticle
 ├── syncRecommendation
 ├── cache invalidation
 ├── sitemap freshness/invalidation
 └── ArticleEvent(published)

27. D30 refresh workflow

refreshAfter reached
 ↓
refreshArticle job
 ↓
create D30 request/task
 ↓
new package with same externalId
 ↓
update DRAFT
 ↓
review
 ↓
publish new version

28. Published article protection

Incoming D30 update must not overwrite live published content directly. It updates a draft/new version for review.

29. Version traceability

30. API response contract

{
  "runId": "...",
  "externalId": "...",
  "status": "success",
  "action": "create|update|skip",
  "articleId": "...",
  "draft": true,
  "warnings": []
}

31. Failure response

{
  "runId": "...",
  "externalId": "...",
  "status": "fail",
  "errorCode": "BLOCK_INVALID",
  "message": "...",
  "retryable": false
}

32. Batch ingestion

batch package
 ↓
ImportRun
 ↓
N items
 ↓
bounded concurrency
 ↓
per-item result
 ↓
aggregate run status

33. Scale gates

100
→ PASS
1,000
→ PASS
10,000
→ PASS
100,000
Никакого production 100k import до прохождения предыдущих стадий.

34. Observability

35. Security

36. Acceptance tests

#ТестPASS
D01New externalIddraft created
D02Same externalId retryno duplicate
D03Same inputHashskip optional
D04Unknown categorycontrolled fail
D05Unknown termdraft candidate/manual path
D06Unknown blockfail/quarantine
D07Invalid media typerejected
D08D30 publish attemptDENY
D09D30 delete attemptDENY
D10Update published articledraft version only
D11Transient failure retryidempotent
D12Post-publishjobs enqueued

37. Load tests

38. Что нельзя делать

  • Не писать D30 напрямую в PostgreSQL.
  • Не разрешать D30 publish/delete.
  • Не создавать новые categories автоматически.
  • Не принимать unknown blocks молча.
  • Не делать внешние Meili/Gorse calls внутри DB transaction.
  • Не импортировать 100k без staged tests.
  • Не использовать admin token для D30.
  • Не затирать live published version без review.

39. ТЗ ИИ-кодеру

  1. Создать D30 package schema.
  2. Создать Integration Adapter.
  3. Реализовать service auth.
  4. Реализовать validation stages.
  5. Реализовать category/topic/term resolution.
  6. Реализовать media ingestion/dedupe.
  7. Реализовать block mapping.
  8. Реализовать externalId idempotent upsert.
  9. Реализовать ImportRuns/ImportItems logging.
  10. Реализовать retry/quarantine.
  11. Реализовать refresh workflow.
  12. Прогнать acceptance/load tests.

40. Deliverables

1. D30ArticlePackage schema
2. Integration Adapter
3. auth middleware
4. validation pipeline
5. taxonomy resolver
6. term resolver
7. media resolver
8. block mapper
9. idempotent article upsert
10. ImportRun/ImportItem logging
11. retry policy
12. reprocess command
13. refresh workflow
14. acceptance test report
15. load test report
16. deviations.md
17. commit hash

41. Gate Build 10

PASS если:
FAIL → не переходить к Build 11.

42. Следующий документ

После PASS: build_11_docker_deploy.html — Docker/Compose, сервисы, networks, env, volumes, PostgreSQL, Payload/Next.js, Meilisearch, Gorse, healthchecks, backup и production deploy.