Эх сурвалжийг харах

feat(data-platform): 交付 1.3.1–1.3.4 API 推送

支持 JSON 与 NDJSON、推送身份校验及持久回执查询。Web 2.4.432 / Server 1.0.621
YY968XX 4 өдөр өмнө
parent
commit
07b266479d
41 өөрчлөгдсөн 2126 нэмэгдсэн , 111 устгасан
  1. 1 1
      Web/package.json
  2. 2 0
      Web/src/views/aidop/data-platform/api/ingestDatasets.ts
  3. 25 2
      Web/src/views/aidop/data-platform/components/DatasetReleasePanel.vue
  4. 128 0
      Web/src/views/aidop/data-platform/components/IngestBatchStatus.vue
  5. 66 0
      Web/src/views/aidop/data-platform/components/IngestPushSample.vue
  6. 157 0
      doc/plan/系统集成/数据中台/API推送.openapi.yaml
  7. 127 0
      doc/plan/系统集成/数据中台/API推送接入指南.md
  8. 3 3
      server/Admin.NET.Web.Entry/Admin.NET.Web.Entry.csproj
  9. 80 26
      server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/IngestBatchPreparer.cs
  10. 8 0
      server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/IngestContracts.cs
  11. 12 4
      server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/PurchaseBatchProcessor.cs
  12. 1 0
      server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/PurchaseHandoffContracts.cs
  13. 5 1
      server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/PurchaseOrderSchemaRegistry.cs
  14. 3 1
      server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/PurchaseVersionConfiguration.cs
  15. 131 0
      server/Plugins/Admin.NET.Plugin.AiDOP.Tests/DataPlatform/MdpIngestAuthenticationTests.cs
  16. 20 0
      server/Plugins/Admin.NET.Plugin.AiDOP.Tests/DataPlatform/MdpIngestContractBindingTests.cs
  17. 17 0
      server/Plugins/Admin.NET.Plugin.AiDOP.Tests/DataPlatform/MdpPurchaseWorkerTests.cs
  18. 39 0
      server/Plugins/Admin.NET.Plugin.AiDOP.Tests/DataPlatform/MdpPushKitTests.cs
  19. 18 0
      server/Plugins/Admin.NET.Plugin.AiDOP.Tests/DataPlatform/MdpSchemaMigrationGateTests.cs
  20. 34 0
      server/Plugins/Admin.NET.Plugin.AiDOP.Tests/DataPlatform/MdpUnifiedIngressContractTests.cs
  21. 6 0
      server/Plugins/Admin.NET.Plugin.AiDOP/Admin.NET.Plugin.AiDOP.csproj
  22. 25 3
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpBatchFactory.cs
  23. 84 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpDatasetReleaseController.SchemaMigration.cs
  24. 10 3
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpDatasetReleaseController.cs
  25. 43 23
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestAdmissionStore.cs
  26. 100 31
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestAuthenticationHandler.cs
  27. 94 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestBatchStatusService.cs
  28. 14 2
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestContractBinder.cs
  29. 25 2
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestController.cs
  30. 177 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestDatasetController.ApiContract.cs
  31. 15 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestDatasetController.cs
  32. 141 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestExternalIdentities.cs
  33. 17 1
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestProtocol.cs
  34. 27 6
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestReceiveService.cs
  35. 4 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestServiceCollectionExtensions.cs
  36. 69 2
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpPurchaseHandoffService.Versioned.cs
  37. 146 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpPushKit.cs
  38. 63 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/PushKitClients/Push.cs
  39. 85 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/PushKitClients/Push.java
  40. 45 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/PushKitClients/push.mjs
  41. 59 0
      server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/PushKitClients/push.py

+ 1 - 1
Web/package.json

@@ -1,7 +1,7 @@
 {
 	"name": "admin.net",
 	"type": "module",
-	"version": "2.4.431",
+	"version": "2.4.432",
 	"packageManager": "pnpm@10.32.1",
 	"lastBuildTime": "2026.03.15",
 	"description": "Admin.NET 站在巨人肩膀上的 .NET 通用权限开发框架",

+ 2 - 0
Web/src/views/aidop/data-platform/api/ingestDatasets.ts

@@ -70,6 +70,8 @@ export interface Candidate {
 	trialJson?: string;
 	environmentKey: string;
 	flowId?: string;
+	schemaMigrationRequired?: boolean;
+	schemaMigrationReady?: boolean;
 }
 export interface VersionWorkspace {
 	timeline: { action: string; detail: string; actor: string; createdAt: string; releaseId?: string }[];

+ 25 - 2
Web/src/views/aidop/data-platform/components/DatasetReleasePanel.vue

@@ -1,6 +1,8 @@
 <script setup lang="ts">
 import { computed, onMounted, ref } from 'vue';
 import { ElMessage, ElMessageBox } from 'element-plus';
+import IngestBatchStatus from './IngestBatchStatus.vue';
+import IngestPushSample from './IngestPushSample.vue';
 import RelationalTrialPanel from './RelationalTrialPanel.vue';
 import { changeLifecycle, releaseAction, saveCandidate, versions, type Candidate, type IngestDataset, type VersionWorkspace } from '../api/ingestDatasets';
 
@@ -19,6 +21,7 @@ const trialSample = ref('');
 const expectedValid = ref(2);
 const expectedIsolated = ref(1);
 const expectedQuantity = ref(15.5);
+const migrationReference = ref('');
 const evidence = computed(() => (candidate.value?.trialJson ? JSON.parse(candidate.value.trialJson) : undefined));
 const labels: Record<string, string> = {
 	DRAFT: '草稿',
@@ -36,7 +39,7 @@ const labels: Record<string, string> = {
 	Cancelled: '已撤销',
 	Terminated: '已终止',
 };
-const actions: Record<string, string> = { DRAFT: '创建草稿', precheck: '预检通过', trial: '完成沙箱试跑', submit: '提交审批', publish: '启用版本', pause: '暂停', resume: '恢复', retire: '退役' };
+const actions: Record<string, string> = { DRAFT: '创建草稿', precheck: '预检通过', trial: '完成沙箱试跑', submit: '提交审批', publish: '启用版本', pause: '暂停', resume: '恢复', retire: '退役', 'schema-migration-ready': '登记迁移完成' };
 const mappingRows = computed(() => {
 	if (!candidate.value) return [];
 	const live = model.value?.history.find((row) => row.state === 'PUBLISHED' && row.version === props.dataset.activeSchemaVersion);
@@ -105,6 +108,14 @@ function transition(action: string) {
 		action === 'publish'
 	);
 }
+function recordMigration() {
+	const row = candidate.value;
+	if (!row || !migrationReference.value.trim()) return;
+	return run(async () => {
+		await releaseAction(props.dataset.id, props.factoryId, row.id, 'migration-ready', { evidenceReference: migrationReference.value.trim() });
+		migrationReference.value = '';
+	});
+}
 async function lifecycle(action: string) {
 	const result = await ElMessageBox.prompt('填写原因', '数据集' + (action === 'pause' ? '暂停' : action === 'resume' ? '恢复' : '退役'), { inputPattern: /\S/ });
 	await run(() => changeLifecycle(props.dataset, props.factoryId, action, result.value), true);
@@ -135,6 +146,7 @@ async function lifecycle(action: string) {
 			@row-click="
 				(c: Candidate) => {
 					selected = c.id;
+					migrationReference = '';
 					example(c);
 				}
 			"
@@ -166,6 +178,15 @@ async function lifecycle(action: string) {
 				</el-collapse-item>
 			</el-collapse>
 			<p v-if="candidate.flowId">审批实例 {{ candidate.flowId }} · {{ labels[candidate.approval || ''] }}</p>
+			<template v-if="candidate.schemaMigrationRequired">
+				<p v-if="candidate.schemaMigrationReady">调用方迁移已登记</p>
+				<p v-else-if="model?.lifecycle !== 'PAUSED'">字段映射有变更。请暂停接收,并按暂停后的修订新建候选。</p>
+				<p v-else>字段映射有变更。处理完在途批次后登记调用方迁移记录。</p>
+				<template v-if="!candidate.schemaMigrationReady && !obsolete && model?.lifecycle === 'PAUSED' && model.canPublish && candidate.approval === 'Approved'">
+					<el-input v-model="migrationReference" maxlength="250" aria-label="迁移完成凭据" placeholder="填写调用方迁移完成的工单或联测记录" />
+					<el-button :disabled="busy || !migrationReference.trim()" @click="recordMigration">登记迁移完成</el-button>
+				</template>
+			</template>
 			<el-button v-if="candidate.state === 'DRAFT'" :disabled="busy || obsolete" @click="transition('precheck')">预检</el-button>
 			<template v-if="['PREFLIGHT', 'RECONCILING'].includes(candidate.state) && model?.canTrial">
 				<el-input v-model="trialSample" type="textarea" :rows="5" aria-label="采购试跑样本" />
@@ -184,10 +205,12 @@ async function lifecycle(action: string) {
 				<p v-for="q in evidence.quarantines" :key="q.rawEventId">{{ q.field }} · {{ q.reason }} · {{ q.rawEventId }}</p>
 			</template>
 			<el-button v-if="candidate.state === 'RECONCILING' && model?.canTrial" :disabled="busy || obsolete || !evidence?.matched" @click="transition('submit')">提交审批</el-button>
-			<el-button v-if="candidate.state === 'REVIEW' && model?.canPublish" :disabled="busy || obsolete || candidate.approval !== 'Approved'" type="primary" @click="transition('publish')"
+			<el-button v-if="candidate.state === 'REVIEW' && model?.canPublish" :disabled="busy || obsolete || candidate.approval !== 'Approved' || (candidate.schemaMigrationRequired && !candidate.schemaMigrationReady)" type="primary" @click="transition('publish')"
 				>启用 {{ candidate.version }}</el-button
 			>
 		</section>
+		<IngestBatchStatus :key="factoryId + '/' + dataset.id" :dataset-id="dataset.id" :factory-id="factoryId" :has-schema="!!dataset.activeSchemaVersion" />
+		<IngestPushSample v-if="dataset.activeSchemaVersion" :key="'sample/' + factoryId + '/' + dataset.id" :dataset-id="dataset.id" :factory-id="factoryId" />
 		<RelationalTrialPanel v-if="model?.canTrial" :dataset-id="dataset.id" :factory-id="factoryId" :active="model.lifecycle === 'ACTIVE' && dataset.enabled" />
 		<el-collapse v-if="model?.timeline.length">
 			<el-collapse-item title="查看操作记录" name="history">

+ 128 - 0
Web/src/views/aidop/data-platform/components/IngestBatchStatus.vue

@@ -0,0 +1,128 @@
+<script setup lang="ts">
+import { shallowRef } from 'vue';
+import service from '/@/utils/request';
+import { downloadByData } from '/@/utils/download';
+
+const props = defineProps<{ datasetId: string; factoryId: string; hasSchema: boolean }>();
+interface BatchStatus {
+	receiveStatus: string;
+	batchId: string;
+	schemaVersion: string;
+	acceptedRecordCount: number;
+	workerStatus: string | null;
+	isolatedRecordCount: number;
+	receiverAcceptedRecordCount: number | null;
+	handoffStatus: string;
+	updatedAt: string;
+	errorCode: string | null;
+}
+
+const batchId = shallowRef('');
+const result = shallowRef<BatchStatus>();
+const busy = shallowRef(false);
+const failed = shallowRef(false);
+const downloading = shallowRef(false);
+const batchPattern = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
+const workerLabels: Record<string, string> = {
+	PENDING: '待处理',
+	PROCESSING: '处理中',
+	RETRY_PENDING: '待重试',
+	HANDOFF_READY: '待交接',
+	SUCCEEDED: '已完成',
+	PARTIAL: '部分完成',
+	QUARANTINED: '已隔离',
+	FAILED: '处理失败',
+};
+const receiveLabels: Record<string, string> = {
+	accepted: '已接收',
+	captured: '已留存,待解析',
+	rejected: '校验失败,原文已留存',
+	empty: '空页,原文已留存',
+};
+const handoffLabels: Record<string, string> = {
+	not_started: '未发起',
+	pending: '待处理',
+	awaiting_delivery: '待投递',
+	confirmed: '已确认',
+	failed: '交接失败',
+};
+
+async function downloadContract() {
+	const path = '/api/DataPlatform/ingest-datasets/' + props.datasetId + '/api-contract';
+	const { data } = await service.get<{ datasetKey: string; schemaVersion: string }>(path, { params: { factoryId: props.factoryId } });
+	downloadByData(JSON.stringify(data, null, 2), data.datasetKey + '.' + data.schemaVersion + '.api.json', 'application/json');
+}
+
+async function downloadKit() {
+	if (downloading.value) return;
+	downloading.value = true;
+	try {
+		const path = '/api/DataPlatform/ingest-datasets/' + props.datasetId + '/api-contract';
+		const { data, headers } = await service.get<Blob>(path, {
+			params: { factoryId: props.factoryId, kit: true },
+			responseType: 'blob',
+		});
+		const fileName = String(headers['content-disposition'] ?? '').match(/filename="?([a-zA-Z0-9._-]+)"?/i)?.[1];
+		downloadByData(data, fileName ?? 'api-push-kit.zip', 'application/zip');
+	} finally {
+		downloading.value = false;
+	}
+}
+
+function downloadDiagnostics() {
+	const status = result.value;
+	if (!status) return;
+	downloadByData(JSON.stringify(status, null, 2), status.batchId + '.diagnostics.json', 'application/json');
+}
+
+async function query() {
+	const selected = batchId.value.trim();
+	if (busy.value || !batchPattern.test(selected)) return;
+	busy.value = true;
+	failed.value = false;
+	result.value = undefined;
+	try {
+		const path = '/api/DataPlatform/ingest-datasets/' + props.datasetId + '/batches/' + selected;
+		const { data } = await service.get<BatchStatus>(path, { params: { factoryId: props.factoryId } });
+		result.value = data;
+	} catch {
+		failed.value = true;
+	} finally {
+		busy.value = false;
+	}
+}
+</script>
+
+<template>
+	<section>
+		<h3>API 接收批次</h3>
+		<el-button v-if="hasSchema" link type="primary" @click="downloadContract">下载 API 推送契约</el-button>
+		<el-button v-if="hasSchema" link type="primary" :loading="downloading" @click="downloadKit">下载 API 推送接入包</el-button>
+		<form class="batch-search" @submit.prevent="query">
+			<el-input v-model="batchId" aria-label="接收批次号" placeholder="输入推送或拉取的 Raw 批次号" :disabled="busy" />
+			<el-button native-type="submit" :disabled="!batchPattern.test(batchId.trim())" :loading="busy">查询批次</el-button>
+		</form>
+		<p v-if="failed" role="alert">查询失败,请核对批次号和当前数据集。</p>
+		<el-descriptions v-if="result" :column="2" border>
+			<el-descriptions-item label="Schema 版本">{{ result.schemaVersion }}</el-descriptions-item>
+			<el-descriptions-item label="接收状态">{{ receiveLabels[result.receiveStatus] ?? result.receiveStatus }}</el-descriptions-item>
+			<el-descriptions-item label="接收行数">{{ result.acceptedRecordCount }}</el-descriptions-item>
+			<el-descriptions-item label="处理状态">{{ workerLabels[result.workerStatus ?? ''] ?? '待确认' }}</el-descriptions-item>
+			<el-descriptions-item label="隔离行数">{{ result.isolatedRecordCount }}</el-descriptions-item>
+			<el-descriptions-item label="交接状态">{{ handoffLabels[result.handoffStatus] ?? '待确认' }}</el-descriptions-item>
+			<el-descriptions-item label="接收方确认行数">{{ result.receiverAcceptedRecordCount ?? '待确认' }}</el-descriptions-item>
+			<el-descriptions-item label="更新时间">{{ new Date(result.updatedAt).toLocaleString() }}</el-descriptions-item>
+			<el-descriptions-item v-if="result.errorCode" label="诊断码">{{ result.errorCode }}</el-descriptions-item>
+		</el-descriptions>
+		<el-button v-if="result" link type="primary" @click="downloadDiagnostics">下载批次排查记录</el-button>
+	</section>
+</template>
+
+<style scoped>
+.batch-search {
+	display: flex;
+	gap: 8px;
+	max-width: 520px;
+	margin-bottom: 12px;
+}
+</style>

+ 66 - 0
Web/src/views/aidop/data-platform/components/IngestPushSample.vue

@@ -0,0 +1,66 @@
+<script setup lang="ts">
+import { shallowRef } from 'vue';
+import service from '/@/utils/request';
+
+const props = defineProps<{ datasetId: string; factoryId: string }>();
+interface Validation {
+	schemaVersion: string;
+	received: number;
+	valid: number;
+	isolated: number;
+	issues: { position: string; field: string; reason: string }[];
+	traceId: string;
+}
+const mediaType = shallowRef('application/json');
+const sample = shallowRef('');
+const result = shallowRef<Validation>();
+const error = shallowRef('');
+const busy = shallowRef(false);
+
+async function validate() {
+	if (busy.value || !sample.value.trim()) return;
+	busy.value = true;
+	result.value = undefined;
+	error.value = '';
+	try {
+		const url = '/api/DataPlatform/ingest-datasets/' + props.datasetId + '/api-contract/validate';
+		const { data } = await service.post<Validation>(url, { mediaType: mediaType.value, sample: sample.value }, {
+			params: { factoryId: props.factoryId },
+		});
+		result.value = data;
+	} catch (failure) {
+		const code = (failure as { response?: { data?: { code?: string } } })?.response?.data?.code;
+		error.value = typeof code === 'string' ? code : '报文校验失败';
+	} finally {
+		busy.value = false;
+	}
+}
+</script>
+
+<template>
+	<el-collapse>
+		<el-collapse-item title="校验推送报文">
+			<el-form label-position="top" @submit.prevent="validate">
+				<el-form-item label="报文格式">
+					<el-radio-group v-model="mediaType" :disabled="busy">
+						<el-radio value="application/json">JSON</el-radio>
+						<el-radio value="application/x-ndjson">NDJSON</el-radio>
+					</el-radio-group>
+				</el-form-item>
+				<el-form-item label="推送报文样本">
+					<el-input v-model="sample" type="textarea" :rows="4" aria-label="推送报文样本" :disabled="busy" />
+				</el-form-item>
+				<el-button native-type="submit" :loading="busy" :disabled="!sample.trim()">校验报文</el-button>
+			</el-form>
+			<p v-if="error" role="alert">{{ error }}</p>
+			<section v-if="result" aria-label="报文校验结果">
+				<p>Schema {{ result.schemaVersion }} · 读取 {{ result.received }} 行 · 合格 {{ result.valid }} 行 · 需隔离 {{ result.isolated }} 行</p>
+				<el-table v-if="result.issues.length" :data="result.issues">
+					<el-table-column prop="position" label="位置" />
+					<el-table-column prop="field" label="字段" />
+					<el-table-column prop="reason" label="诊断码" />
+				</el-table>
+			</section>
+		</el-collapse-item>
+	</el-collapse>
+</template>

+ 157 - 0
doc/plan/系统集成/数据中台/API推送.openapi.yaml

@@ -0,0 +1,157 @@
+openapi: 3.1.0
+info:
+  title: Ai-DOP 数据中台 API 推送
+  version: 1.0.0
+paths:
+  /api/v1/ingest/{datasetKey}:
+    parameters:
+      - $ref: '#/components/parameters/Dataset'
+      - $ref: '#/components/parameters/Timestamp'
+      - $ref: '#/components/parameters/Nonce'
+      - $ref: '#/components/parameters/Factory'
+      - name: X-Schema-Version
+        in: header
+        schema: { type: string, maxLength: 64 }
+    post:
+      summary: 持久接收推送批次
+      security: [{hmac: [], signature: [], digest: []}, {oauthBearer: []}, {mtls: []}]
+      parameters:
+        - $ref: '#/components/parameters/SignatureVersion'
+        - name: Idempotency-Key
+          in: header
+          required: true
+          schema: { type: string, minLength: 1, maxLength: 128 }
+      requestBody:
+        required: true
+        content:
+          application/json:
+            schema:
+              type: object
+              required: [data]
+              properties:
+                factoryId: { type: string, pattern: '^[1-9][0-9]{0,18}$' }
+                data:
+                  type: object
+                  required: [list]
+                  properties:
+                    list:
+                      type: array
+                      minItems: 1
+                      maxItems: 100
+                      items: { type: object }
+          application/x-ndjson:
+            schema: { type: string }
+            description: 每行一个 JSON 对象,最多 100 行,原始报文最多 1 MiB。
+      responses:
+        '202':
+          description: 原文、行索引和接收待办已持久化
+          content:
+            application/json:
+              schema: { $ref: '#/components/schemas/Receipt' }
+        '400': { $ref: '#/components/responses/RequestError' }
+        '401': { $ref: '#/components/responses/RequestError' }
+        '403': { $ref: '#/components/responses/RequestError' }
+        '409': { $ref: '#/components/responses/RequestError' }
+        '413': { $ref: '#/components/responses/RequestError' }
+        '415': { $ref: '#/components/responses/RequestError' }
+        '422': { $ref: '#/components/responses/RequestError' }
+        '429': { $ref: '#/components/responses/RateLimited' }
+        '503': { $ref: '#/components/responses/RequestError' }
+  /api/v1/ingest/{datasetKey}/batches/{batchId}:
+    parameters:
+      - $ref: '#/components/parameters/Dataset'
+      - $ref: '#/components/parameters/Timestamp'
+      - $ref: '#/components/parameters/Nonce'
+      - $ref: '#/components/parameters/Factory'
+      - name: batchId
+        in: path
+        required: true
+        schema: { type: string, format: uuid }
+    get:
+      summary: 查询来源获准访问的批次
+      security: [{hmac: [], signature: [], digest: []}, {oauthBearer: []}, {mtls: []}]
+      parameters:
+        - $ref: '#/components/parameters/SignatureVersion'
+      responses:
+        '200':
+          description: 接收和异步处理状态
+          content:
+            application/json:
+              schema:
+                allOf:
+                  - $ref: '#/components/schemas/Receipt'
+                  - type: object
+                    properties:
+                      workerStatus: { type: [string, 'null'] }
+                      handoffStatus: { enum: [pending, awaiting_delivery, confirmed, failed] }
+                      isolatedRecordCount: { type: integer, minimum: 0 }
+                      receiverAcceptedRecordCount: { type: [integer, 'null'], minimum: 0 }
+                      updatedAt: { type: string, format: date-time }
+                      errorCode: { type: [string, 'null'] }
+        '401': { $ref: '#/components/responses/RequestError' }
+        '403': { $ref: '#/components/responses/RequestError' }
+        '404': { $ref: '#/components/responses/RequestError' }
+        '429': { $ref: '#/components/responses/RateLimited' }
+        '503': { $ref: '#/components/responses/RequestError' }
+components:
+  securitySchemes:
+    hmac: { type: apiKey, in: header, name: X-Access-Key }
+    signature: { type: apiKey, in: header, name: X-Signature }
+    digest: { type: apiKey, in: header, name: X-Content-SHA256 }
+    oauthBearer: { type: http, scheme: bearer, bearerFormat: JWT }
+    mtls: { type: mutualTLS }
+  parameters:
+    Dataset:
+      name: datasetKey
+      in: path
+      required: true
+      schema: { type: string, pattern: '^[a-z0-9][a-z0-9._-]{0,79}$' }
+    Timestamp:
+      name: X-Timestamp
+      in: header
+      required: true
+      schema: { type: string, pattern: '^[0-9]{1,20}$' }
+    Nonce:
+      name: X-Nonce
+      in: header
+      required: true
+      schema: { type: string, minLength: 1, maxLength: 128 }
+    Factory:
+      name: X-Factory-Id
+      in: header
+      description: 用于 NDJSON 和批次查询。多工厂授权必须指定。
+      schema: { type: string, pattern: '^[1-9][0-9]{0,18}$' }
+    SignatureVersion:
+      name: X-Signature-Version
+      in: header
+      schema: { enum: [mdp-ingress-hmac-sha256-v1, mdp-ingress-hmac-sha256-v2] }
+  schemas:
+    Receipt:
+      type: object
+      required: [batchId, receiveStatus, acceptedRecordCount, schemaVersion, receivedAt]
+      properties:
+        batchId: { type: string, format: uuid }
+        receiveStatus: { const: accepted }
+        acceptedRecordCount: { type: integer, minimum: 1 }
+        schemaVersion: { type: string }
+        receivedAt: { type: string, format: date-time }
+    Error:
+      type: object
+      required: [code, traceId]
+      properties:
+        code: { type: string }
+        traceId: { type: string }
+  responses:
+    RequestError:
+      description: 请求被拒绝或服务不可用
+      content:
+        application/json:
+          schema: { $ref: '#/components/schemas/Error' }
+    RateLimited:
+      description: 当前分钟来源或租户已到限额
+      headers:
+        Retry-After:
+          schema: { type: integer, minimum: 1, maximum: 60 }
+      content:
+        application/json:
+          schema: { $ref: '#/components/schemas/Error' }

+ 127 - 0
doc/plan/系统集成/数据中台/API推送接入指南.md

@@ -0,0 +1,127 @@
+# 数据中台 API 推送接入指南
+
+运维人员在「数据源管理 → 接收数据集 → 版本与审批」确认租户、工厂、来源、数据集编码和已启用的 Schema 版本,并完成来源授权。对接方取得环境地址和对应凭据后,先推送一批测试数据,再用回执中的批次号查询处理结果。
+
+通过「下载 API 推送契约」取得当前版本的 Schema、JSON 和 NDJSON 样例、限额、错误码和签名测试向量。用「校验推送报文」选择实际格式并粘贴样本,可核对合格行以及需要隔离的位置和原因。校验在内存中完成。正式推送后,运维人员可按批次号查询交接结果并下载排查记录,记录包含批次状态和计数。
+
+已启用版本的来源字段映射发生变化时,先暂停接收,再按暂停后的修订建候选。候选试跑对账和独立审批通过后,核对在途批次均已处理,请调用方适配新报文,并由发布人员在版本工作区登记对应工单或联测记录。系统在启用时复核暂停状态、在途及迁移记录,凭据锁定旧版本、候选版本和配置修订。历史批次仍按入库时的映射快照处理。
+
+## 调用接口
+
+| 操作 | 接口 | 成功响应 |
+| --- | --- | --- |
+| 提交 | `POST /api/v1/ingest/{datasetKey}` | 202。返回 `batchId`、`receiveStatus`、`acceptedRecordCount`、`schemaVersion`、`receivedAt`。 |
+| 查询 | `GET /api/v1/ingest/{datasetKey}/batches/{batchId}` | 200。补充 Worker 状态、隔离数、接收方确认数、交接状态、更新时间和诊断码。 |
+
+- JSON 用 `application/json`,采购首包的行放在 `data.list`。多工厂授权在 JSON 顶层提供 `factoryId`。
+- NDJSON 用 `application/x-ndjson`,每行一个对象,接受 LF、CRLF 和一个可选的末尾换行。空行、行内真实回车、非法 UTF-8 或 JSON 语法错误会拒收整批。多工厂授权使用 `X-Factory-Id`。
+- 批次最多 1 MiB,最多 100 行,JSON 深度最多 16。NDJSON 单行受同一批次字节上限限制。工厂和租户使用字符串 ID。批次内厂别与授权不一致会拒收。
+- POST 可以用 `X-Schema-Version` 指定当前启用的版本。可从版本工作区查看启用值。采购字段质量错误进入隔离,正常行仍可交接。采购基线的字段定义见 [采购来源 JSON Schema](../../../../server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/Schemas/po-source-v1.schema.json)。
+- 202 表示已持久接收。 `handoffStatus=confirmed` 表示接收方已确认,处理状态为 `PARTIAL` 时同时核对隔离数。有多工厂授权时查询也传 `X-Factory-Id`。运维人员可在数据集版本工作区用批次号查询。
+
+## 认证与重试
+
+所有请求带当前 Unix 秒 `X-Timestamp` 和随机的 `X-Nonce`。时间容差为 ±5 分钟。同一身份的 Nonce 具有 15 分钟防重放窗口。
+
+| 方式 | 请求要求 |
+| --- | --- |
+| HMAC | 发送 `X-Access-Key`、`X-Signature`、`X-Content-SHA256`。现有 JSON 仍可用 v1,NDJSON、GET 和显式 Schema 使用 v2。 |
+| OAuth2 | HTTPS 请求携带 `Authorization: Bearer <token>`,令牌须来自平台登记的发行者,提供已登记的应用身份及对应提交或查询 scope。 |
+| mTLS | TLS 握手提供已登记且可信的客户端证书。接入节点核查证书链、用途、有效期和吊销。 |
+| 幂等 | POST 必填 `Idempotency-Key`。7 天内用原字节和原幂等键重试可得到原回执。每次尝试使用新时间戳、Nonce,HMAC 调用重新签名。GET 使用空报文及空幂等键。 |
+| 限流 | 来源和租户限额均以服务端分钟窗口计算。响应 429 后按 `Retry-After` 等待并重试。 |
+
+签名原文使用 UTF-8。以下大写名称代表取值,`&` 是分隔符。摘要使用原字节的 SHA-256 小写十六进制。密钥用平台分发的 Base64 解码得到。签名值为 HMAC-SHA256 结果的 Base64。
+
+```text
+v1: METHOD&PATH&ACCESS_KEY&TIMESTAMP&NONCE&SHA256&IDEMPOTENCY_KEY
+v2: mdp-ingress-hmac-sha256-v2&METHOD&PATH&ACCESS_KEY&TIMESTAMP&NONCE&SHA256&IDEMPOTENCY_KEY&MEDIA_TYPE&FACTORY_HEADER&SCHEMA_HEADER
+```
+
+v2 发送 `X-Signature-Version: mdp-ingress-hmac-sha256-v2`。签名路径使用请求路径,方法大写。媒体类型使用小写且移除 charset 参数。未传工厂或版本时对应项为空。GET 的媒体类型项为空,空字节摘要为 `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855`。
+
+出现错误时,记录 HTTP 状态、`code` 和 `traceId`。常见情形包括 400 报文或厂别错误,401 认证或重放,403 来源或数据集授权不可用,404 批次不可访问,409 幂等冲突或历史键已到期,413 超出字节上限,415 格式不支持,422 Schema 版本、行数或深度校验失败,429 来源或租户限流。遇到 503 先查平台运行状态,恢复后按原幂等键和原文重试。
+
+
+## 采购订单行的版本与重送
+
+JSON 和 NDJSON 采购行沿用必填的 `sourceUpdatedAt`,请使用含时区的 ISO 8601 时间。对同一租户、工厂、来源、数据集和订单行,系统按该时间换算出的 UTC 时刻比较。较新版本更新原订单行,晚到的旧版本保留已生效数据,同一时刻同一业务内容复用原订单行。同一时刻不同业务内容进入隔离,批次查询可看到隔离行数。
+
+202 回执确认原文已收存。处理结果以批次查询为准,已收到的过期事件仍保留 Raw 供追溯。对同一事件签名重试时,原幂等键和原字节保持一致。推送合法的新业务版本时使用新的幂等键和较新的来源更新时间。
+
+新接收的采购 API 批次在 Raw 快照记录排序规则,Worker 使用采购二级包 `MDP-PO-001@1.2.0`。包的 `sourceChange` 包含 `generation=0`、UTC ticks 版本和 `deleted=false`。历史 `1.0.0` 快照仍按原契约处理,关系库增量 `1.1.0` 沿用源日志版本。API 时间排序与关系库位点分别管理,同一业务行切换写入来源使用既有受控交接流程。
+
+## OAuth2 和 mTLS 配置
+
+在部署配置的 `MdpUnifiedIngress:ExternalIdentity` 下登记已批准的应用或客户端证书。OAuth2 配置 `OAuth2` 节点下的 `MetadataAddress`、`Issuer`、`Audience`、`AppOnlyClaim`、`AppOnlyValue`、`WriteScope`、`ReadScope`。服务读取签名器的 HTTPS 元数据,验签后从 `client_id` 解析应用并从 `scope` 验权。mTLS 需要实际 TLS 端点启用客户端证书,部署节点使用受信任的证书链及可到达的证书吊销端点。
+
+分别在 `OAuth2:Clients` 或 `Mtls:Clients` 中登记 `Enabled`、`Identity`、`TenantId`、`UserId`、`GrantReference`。OAuth2 的 Identity 为应用 ID,mTLS 为证书 SHA-256 指纹大写十六进制。来源授权使用与既有来源授权相同的表和租户、工厂、数据集范围。授权记录的 `access_key_hash` 为 UTF-8 字符串 `mdp-external\0{method}\0{GrantReference}` 的 SHA-256 小写十六进制,两个 `\0` 是实际 NUL 字节,method 为 `oauth2` 或 `mtls`。创建或撤销该授权由平台运维按既有来源授权审批操作。应用或证书停用可禁用外部配置及授权记录。证书正常换代可沿用同一来源引用,延续该来源授权和防重放。
+
+[推送和批次查询的 OpenAPI 定义](./API推送.openapi.yaml)
+
+## 客户端签名示例
+
+从版本工作区下载数据集契约后,先把其中的 `signatureVector.canonical` 和 `signatureVector.exampleKeyBase64` 传给下面任一函数。结果应与 `signatureVector.signatureBase64` 一致。测试向量的凭据仅用于核对签名算法。
+
+Python
+
+```python
+import base64, hashlib, hmac
+
+def sign(canonical, key_base64):
+    key = base64.b64decode(key_base64)
+    digest = hmac.digest(key, canonical.encode("utf-8"), hashlib.sha256)
+    return base64.b64encode(digest).decode("ascii")
+```
+
+Node.js
+
+```javascript
+import { createHmac } from 'node:crypto';
+
+function sign(canonical, keyBase64) {
+    return createHmac('sha256', Buffer.from(keyBase64, 'base64'))
+        .update(canonical, 'utf8').digest('base64');
+}
+```
+
+C#
+
+```csharp
+using System;
+using System.Security.Cryptography;
+using System.Text;
+
+static string Sign(string canonical, string keyBase64) =>
+    Convert.ToBase64String(HMACSHA256.HashData(
+        Convert.FromBase64String(keyBase64), Encoding.UTF8.GetBytes(canonical)));
+```
+
+Java
+
+```java
+import java.nio.charset.StandardCharsets;
+import java.security.GeneralSecurityException;
+import java.util.Base64;
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+
+static String sign(String canonical, String keyBase64) throws GeneralSecurityException {
+    var signer = Mac.getInstance("HmacSHA256");
+    signer.init(new SecretKeySpec(Base64.getDecoder().decode(keyBase64), "HmacSHA256"));
+    return Base64.getEncoder().encodeToString(signer.doFinal(canonical.getBytes(StandardCharsets.UTF_8)));
+}
+```
+
+联调时使用下载资料的 `samples.ndjson` 或 `samples.json`。以下 cURL 示例所需环境变量由调用方填写。先按 v2 规则准备 `TIMESTAMP`、`NONCE`、`DIGEST` 和 `SIGNATURE`,再发送用于计算摘要的同一份文件。
+
+```bash
+curl --request POST "$INGRESS_BASE$DATASET_ENDPOINT" \
+  --header 'Content-Type: application/x-ndjson' \
+  --header 'X-Signature-Version: mdp-ingress-hmac-sha256-v2' \
+  --header "X-Access-Key: $ACCESS_KEY" --header "X-Signature: $SIGNATURE" \
+  --header "X-Content-SHA256: $DIGEST" --header "X-Timestamp: $TIMESTAMP" \
+  --header "X-Nonce: $NONCE" --header "Idempotency-Key: $IDEMPOTENCY_KEY" \
+  --header "X-Schema-Version: $SCHEMA_VERSION" --header "X-Factory-Id: $FACTORY_ID" \
+  --data-binary @sample.ndjson
+```

+ 3 - 3
server/Admin.NET.Web.Entry/Admin.NET.Web.Entry.csproj

@@ -11,9 +11,9 @@
     <GenerateSatelliteAssembliesForCore>true</GenerateSatelliteAssembliesForCore>
     <Copyright>Admin.NET</Copyright>
     <Description>Admin.NET 通用权限开发平台</Description>
-    <AssemblyVersion>1.0.620</AssemblyVersion>
-    <FileVersion>1.0.620</FileVersion>
-    <Version>1.0.620</Version>
+    <AssemblyVersion>1.0.621</AssemblyVersion>
+    <FileVersion>1.0.621</FileVersion>
+    <Version>1.0.621</Version>
   </PropertyGroup>
 
   <ItemGroup>

+ 80 - 26
server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/IngestBatchPreparer.cs

@@ -1,3 +1,4 @@
+using System.Security.Cryptography;
 using System.Text;
 using System.Text.Json;
 
@@ -12,30 +13,39 @@ public sealed class IngestBatchPreparer(ISchemaRegistry schemas)
         string sourceSchemaVersion,
         ReadOnlySpan<byte> payload,
         IngestLimits limits,
-        IngestSourceWindow? window = null)
+        IngestSourceWindow? window = null,
+        IngestPayloadFormat format = IngestPayloadFormat.Json)
     {
-        ArgumentOutOfRangeException.ThrowIfNegativeOrZero(limits.MaxBodyBytes);
-        ArgumentOutOfRangeException.ThrowIfNegativeOrZero(limits.MaxRecords);
-        ArgumentOutOfRangeException.ThrowIfNegativeOrZero(limits.MaxJsonDepth);
-        var contract = schemas.Find(identity.DatasetKey, sourceSchemaVersion)
-            ?? throw new IngestContractException(IngestContractError.UnknownSchema);
-        if (payload.Length > limits.MaxBodyBytes)
-            throw new IngestContractException(IngestContractError.BodyTooLarge);
-
+        var contract = ResolveContract(identity, sourceSchemaVersion, payload.Length, limits);
         var bytes = payload.ToArray();
         var batchId = Guid.NewGuid();
         var receivedAt = DateTimeOffset.UtcNow;
-        var events = IndexEvents(bytes, batchId, contract, limits);
+        var events = IndexEvents(bytes, batchId, contract, limits, format);
         var batch = new RawIngestBatch(batchId, identity, receivedAt, contract.Snapshot(), events.Count,
             bytes, PurchaseOrderSchemaRegistry.ComputeSha256(bytes), window);
         return new PreparedIngestBatch(batch, events);
     }
 
+    private IngestContract ResolveContract(IngestDatasetIdentity identity, string sourceSchemaVersion, int length, IngestLimits limits)
+    {
+        ArgumentOutOfRangeException.ThrowIfNegativeOrZero(limits.MaxBodyBytes);
+        ArgumentOutOfRangeException.ThrowIfNegativeOrZero(limits.MaxRecords);
+        ArgumentOutOfRangeException.ThrowIfNegativeOrZero(limits.MaxJsonDepth);
+        var contract = schemas.Find(identity.DatasetKey, sourceSchemaVersion)
+            ?? throw new IngestContractException(IngestContractError.UnknownSchema);
+        if (length > limits.MaxBodyBytes)
+            throw new IngestContractException(IngestContractError.BodyTooLarge);
+        return contract;
+    }
+
     private static IReadOnlyList<RawIngestEvent> IndexEvents(
-        byte[] bytes, Guid batchId, IngestContract contract, IngestLimits limits)
+        byte[] bytes, Guid batchId, IngestContract contract, IngestLimits limits, IngestPayloadFormat format)
     {
         try
         {
+            if (format == IngestPayloadFormat.Ndjson)
+                return IndexNdjson(bytes, batchId, contract, limits);
+
             ValidateJson(bytes, limits.MaxJsonDepth);
 
             var root = new Utf8JsonReader(bytes, new JsonReaderOptions { MaxDepth = limits.MaxJsonDepth });
@@ -45,7 +55,6 @@ public sealed class IngestBatchPreparer(ISchemaRegistry schemas)
             if (list.TokenType != JsonTokenType.StartArray)
                 throw new IngestContractException(IngestContractError.InvalidEnvelope);
 
-            var names = contract.FieldMapJson == null ? null : JsonSerializer.Deserialize<Dictionary<string,string>>(contract.FieldMapJson);
             var events = new List<RawIngestEvent>();
             while (list.Read() && list.TokenType != JsonTokenType.EndArray)
             {
@@ -57,7 +66,7 @@ public sealed class IngestBatchPreparer(ISchemaRegistry schemas)
                 var offset = checked((int)list.TokenStartIndex);
                 list.Skip();
                 var length = checked((int)list.BytesConsumed) - offset;
-                events.Add(CreateEvent(bytes.AsMemory(offset, length), batchId, events.Count, contract.ObjectCode, offset, limits.MaxJsonDepth, names));
+                events.Add(CreateEvent(bytes.AsMemory(offset, length), batchId, events.Count, contract, offset, limits.MaxJsonDepth, $"/data/list/{events.Count}"));
             }
 
             if (events.Count == 0)
@@ -75,6 +84,43 @@ public sealed class IngestBatchPreparer(ISchemaRegistry schemas)
         }
     }
 
+    private static IReadOnlyList<RawIngestEvent> IndexNdjson(
+        byte[] bytes, Guid batchId, IngestContract contract, IngestLimits limits)
+    {
+        var events = new List<RawIngestEvent>();
+        for (var start = 0; start < bytes.Length;)
+        {
+            var remaining = bytes.AsSpan(start);
+            var newline = remaining.IndexOf((byte)'\n');
+            var line = newline < 0 ? remaining : remaining[..newline];
+            var length = line.Length;
+            if (newline >= 0 && !line.IsEmpty && line[^1] == (byte)'\r')
+                line = line[..^1];
+            var contentLength = line.Length;
+            while (!line.IsEmpty && line[0] is (byte)' ' or (byte)'\t')
+                line = line[1..];
+            if (line.IsEmpty || line.Contains((byte)'\r'))
+                throw new IngestContractException(IngestContractError.InvalidEnvelope);
+            ValidateJson(line, limits.MaxJsonDepth);
+            var reader = new Utf8JsonReader(line, new JsonReaderOptions { MaxDepth = limits.MaxJsonDepth });
+            if (!reader.Read() || reader.TokenType != JsonTokenType.StartObject)
+                throw new IngestContractException(IngestContractError.InvalidEnvelope);
+            if (events.Count == limits.MaxRecords)
+                throw new IngestContractException(IngestContractError.TooManyRecords);
+
+            var offset = start + contentLength - line.Length;
+            reader.Skip();
+            events.Add(CreateEvent(bytes.AsMemory(offset, checked((int)reader.BytesConsumed)), batchId,
+                events.Count, contract, offset, limits.MaxJsonDepth, $"/lines/{events.Count + 1}"));
+            start += length + 1;
+        }
+
+        if (events.Count == 0)
+            throw new IngestContractException(IngestContractError.InvalidEnvelope);
+
+        return events.AsReadOnly();
+    }
+
     private static void ValidateJson(ReadOnlySpan<byte> bytes, int maxDepth)
     {
         StrictUtf8.GetCharCount(bytes);
@@ -128,25 +174,33 @@ public sealed class IngestBatchPreparer(ISchemaRegistry schemas)
     }
 
     private static RawIngestEvent CreateEvent(
-        ReadOnlyMemory<byte> payload, Guid batchId, int ordinal, string objectCode, int offset, int maxDepth, Dictionary<string,string>? names)
+        ReadOnlyMemory<byte> payload, Guid batchId, int ordinal, IngestContract contract, int offset, int maxDepth,
+        string sourcePosition)
     {
         using var document = JsonDocument.Parse(payload, new JsonDocumentOptions { MaxDepth = maxDepth });
         var row = document.RootElement;
-        var orderNumber = UniqueString(row, names?["PoNo"] ?? "PoNo");
-        var orderLine = UniqueString(row, names?["PoLine"] ?? "PoLine");
-        var sourceBusinessKey = IsKeyPart(orderNumber, 100) && IsKeyPart(orderLine, 50)
-            ? $"{orderNumber}#{orderLine}"
+        var keyParts = new List<string>();
+        foreach (var field in contract.KeyFields)
+        {
+            var value = UniqueString(row, field.Name);
+            if (!IsKeyPart(value, field.MaxLength))
+                break;
+            keyParts.Add(value!);
+        }
+        var businessKey = keyParts.Count > 0 && keyParts.Count == contract.KeyFields.Count
+            ? string.Join('#', keyParts)
             : null;
-
-        var sourceUpdatedAt = UniqueString(row, names?["sourceUpdatedAt"] ?? "sourceUpdatedAt");
-        var sourceTime = sourceUpdatedAt is { Length: >= 6 }
-            && (sourceUpdatedAt.EndsWith('Z') || sourceUpdatedAt[^6] is '+' or '-')
-            && row.GetProperty(names?["sourceUpdatedAt"] ?? "sourceUpdatedAt").TryGetDateTimeOffset(out _)
-            ? sourceUpdatedAt
+        var timeField = contract.SourceTimeField;
+        var timestamp = timeField is null ? null : UniqueString(row, timeField);
+        var sourceTime = timestamp is { Length: >= 6 }
+            && (timestamp.EndsWith('Z') || timestamp[^6] is '+' or '-')
+            && row.GetProperty(timeField!).TryGetDateTimeOffset(out _)
+            ? timestamp
             : null;
 
-        return new RawIngestEvent(Guid.NewGuid(), batchId, ordinal, objectCode, $"/data/list/{ordinal}", offset,
-            payload.Length, PurchaseOrderSchemaRegistry.ComputeSha256(payload.Span), sourceBusinessKey, sourceTime);
+        return new RawIngestEvent(Guid.NewGuid(), batchId, ordinal, contract.ObjectCode, sourcePosition, offset,
+            payload.Length, Convert.ToHexString(SHA256.HashData(payload.Span)).ToLowerInvariant(),
+            businessKey, sourceTime);
     }
 
     private static bool IsKeyPart(string? value, int maxLength) =>

+ 8 - 0
server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/IngestContracts.cs

@@ -6,6 +6,8 @@ namespace Admin.NET.Plugin.AiDOP.DataPlatform.Core;
 public sealed record IngestDatasetIdentity(
     long TenantId, long FactoryId, long SourceId, long DatasetId, string SourceCode, string DatasetKey);
 
+public enum IngestPayloadFormat { Json, Ndjson }
+
 public sealed record IngestLimits(int MaxBodyBytes, int MaxRecords, int MaxJsonDepth);
 
 public sealed record SchemaStamp(string Version, string Sha256);
@@ -36,13 +38,19 @@ public sealed record IngestContract(
 {
     [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
     public string? FieldMapJson { get; init; }
+    public IReadOnlyList<IngestKeyField> KeyFields { get; init; } = [];
+    public string? SourceTimeField { get; init; }
+
     public IngestVersionSnapshot Snapshot() => new(
         SourceSchema.Stamp, RawSchema.Stamp, HandoffSchema.Stamp, MappingVersion, RuleVersion, ConfigVersion) { FieldMapJson = FieldMapJson };
 }
 
+public sealed record IngestKeyField(string Name, int MaxLength);
+
 public sealed record IngestSourceWindow(DateTimeOffset? From, DateTimeOffset? To, string? Watermark)
 {
     public const string VerifiedRelationalSnapshot = "RELATIONAL-SNAPSHOT-V1";
+    public const string PurchaseApiTime = "PURCHASE-API-TIME-V1";
 
     [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
     public long? SourceGeneration { get; init; }

+ 12 - 4
server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/PurchaseBatchProcessor.cs

@@ -26,6 +26,7 @@ public static class PurchaseBatchProcessor
         var businessKeys = new HashSet<(string Key, long? Version)>();
         var events = new HashSet<Guid>();
         var verifiedRelational = batch.SourceWindow?.Watermark == IngestSourceWindow.VerifiedRelationalSnapshot;
+        var versionedApi = batch.SourceWindow?.Watermark == IngestSourceWindow.PurchaseApiTime;
         var generation = verifiedRelational ? batch.SourceWindow?.SourceGeneration : null;
         for (var ordinal = 0; ordinal < prepared.Events.Count; ordinal++)
         {
@@ -36,7 +37,7 @@ public static class PurchaseBatchProcessor
                 throw new InvalidDataException("RAW_EVENT_INTEGRITY_ERROR");
 
             var slice = batch.Payload.Slice(rawEvent.PayloadOffset, rawEvent.PayloadLength);
-            var (line, quarantine) = ConvertLine(rawEvent, slice, reverse, verifiedRelational, generation);
+            var (line, quarantine) = ConvertLine(rawEvent, slice, reverse, verifiedRelational, generation, versionedApi);
             if (quarantine is not null)
                 quarantines.Add(quarantine);
             else if (businessKeys.Add((line!.BusinessKey, line.SourceChange?.Version)))
@@ -47,14 +48,15 @@ public static class PurchaseBatchProcessor
 
         var package = new PurchaseHandoffPackage(batch.BatchId, leaseToken, identity.TenantId, identity.FactoryId,
             identity.SourceId, identity.DatasetId, identity.DatasetKey, identity.SourceCode,
-            generation.HasValue ? PurchaseHandoffPackage.RelationalChangeVersion : PurchaseHandoffPackage.Version,
+            versionedApi ? PurchaseHandoffPackage.ApiChangeVersion :
+                generation.HasValue ? PurchaseHandoffPackage.RelationalChangeVersion : PurchaseHandoffPackage.Version,
             batch.Versions.SourceSchema.Version, batch.Versions.MappingVersion, items);
         return new PurchaseBatchProcessingResult(package, quarantines);
     }
 
     public static (PurchaseHandoffLine? Line, PurchaseQuarantine? Quarantine) ConvertLine(
         RawIngestEvent rawEvent, ReadOnlyMemory<byte> rowPayload, IReadOnlyDictionary<string,string>? reverse = null,
-        bool verifiedRelational = false, long? sourceGeneration = null)
+        bool verifiedRelational = false, long? sourceGeneration = null, bool versionedApi = false)
     {
         if (rawEvent.RawEventId == Guid.Empty || rawEvent.ObjectCode != "PURCHASE_ORDER"
             || rowPayload.Length != rawEvent.PayloadLength
@@ -109,8 +111,14 @@ public static class PurchaseBatchProcessor
         if (rawEvent.SourceUpdatedAt is not { Length: >= 6 } updatedAt
             || !(updatedAt.EndsWith('Z') || updatedAt[^6] is '+' or '-')
             || !fields.TryGetValue("sourceUpdatedAt", out var sourceTime) || sourceTime.ValueKind != JsonValueKind.String
-            || sourceTime.GetString() != updatedAt || !sourceTime.TryGetDateTimeOffset(out _))
+            || sourceTime.GetString() != updatedAt || !sourceTime.TryGetDateTimeOffset(out var sourceInstant))
             return Reject("sourceUpdatedAt", "INVALID_SOURCE_TIME");
+        if (versionedApi)
+        {
+            if (sourceInstant.UtcTicks <= 0)
+                return Reject("sourceUpdatedAt", "INVALID_SOURCE_TIME");
+            change = new PurchaseSourceChange(0, sourceInstant.UtcTicks, false);
+        }
         if ($"{poNo}#{poLine}" != rawEvent.SourceBusinessKey)
             throw new InvalidDataException("RAW_BUSINESS_KEY_MISMATCH");
 

+ 1 - 0
server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/PurchaseHandoffContracts.cs

@@ -39,6 +39,7 @@ public sealed record PurchaseHandoffPackage(
 {
     public const string Version = "1.0.0";
     public const string RelationalChangeVersion = "1.1.0";
+    public const string ApiChangeVersion = "1.2.0";
     private static readonly JsonSerializerOptions DigestJson = new(JsonSerializerDefaults.Web);
 
     public string PackageCode => "MDP-PO-001";

+ 5 - 1
server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/PurchaseOrderSchemaRegistry.cs

@@ -13,7 +13,11 @@ public sealed class PurchaseOrderSchemaRegistry : ISchemaRegistry
         ReadSchema(SourceVersion, "po-source-v1.schema.json"),
         ReadSchema("raw-envelope-v1", "raw-envelope-v1.schema.json"),
         ReadSchema("MDP-PO-001@1.0.0", "mdp-po-001-v1.schema.json"),
-        "po-map-v1", "po-rule-v1", "po-config-v1");
+        "po-map-v1", "po-rule-v1", "po-config-v1")
+    {
+        KeyFields = [new("PoNo", 100), new("PoLine", 50)],
+        SourceTimeField = "sourceUpdatedAt"
+    };
 
     public IngestContract? Find(string datasetKey, string sourceSchemaVersion) =>
         datasetKey == DatasetKey && sourceSchemaVersion == SourceVersion ? PurchaseOrder : null;

+ 3 - 1
server/Plugins/Admin.NET.Plugin.AiDOP.DataPlatform.Core/PurchaseVersionConfiguration.cs

@@ -47,7 +47,9 @@ public sealed class PurchaseVersionConfiguration : ISchemaRegistry
             SourceSchema = Baseline.SourceSchema with { Stamp = new SchemaStamp(version, Baseline.SourceSchema.Stamp.Sha256) },
             MappingVersion = hash,
             ConfigVersion = version,
-            FieldMapJson = MappingJson
+            FieldMapJson = MappingJson,
+            KeyFields = [new(names["PoNo"], 100), new(names["PoLine"], 50)],
+            SourceTimeField = names["sourceUpdatedAt"]
         };
     }
 

+ 131 - 0
server/Plugins/Admin.NET.Plugin.AiDOP.Tests/DataPlatform/MdpIngestAuthenticationTests.cs

@@ -0,0 +1,131 @@
+using System.Net;
+using System.Security.Claims;
+using System.Security.Cryptography;
+using System.Security.Cryptography.X509Certificates;
+using System.Text.Json;
+using Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
+using Microsoft.Extensions.Configuration;
+using Microsoft.IdentityModel.JsonWebTokens;
+using Microsoft.IdentityModel.Tokens;
+using Xunit;
+
+namespace Admin.NET.Plugin.AiDOP.Tests.DataPlatform;
+
+public sealed class MdpIngestAuthenticationTests
+{
+    private const string Issuer = "https://issuer.example.test";
+    private const string Audience = "mdp-ingress";
+    private const string OAuth = "MdpUnifiedIngress:ExternalIdentity:OAuth2:";
+    private const string Mtls = "MdpUnifiedIngress:ExternalIdentity:Mtls:";
+
+    [Fact]
+    public async Task OAuth2_RequiresVerifiedIssuerAudienceSignatureApplicationAndScope()
+    {
+        using var issuerRsa = RSA.Create(2048);
+        using var otherRsa = RSA.Create(2048);
+        var key = new RsaSecurityKey(issuerRsa) { KeyId = "documented-key" };
+        var otherKey = new RsaSecurityKey(otherRsa) { KeyId = key.KeyId };
+        using var metadata = new HttpClient(new Metadata(issuerRsa.ExportParameters(false)));
+        var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
+        {
+            [OAuth + "MetadataAddress"] = Issuer + "/.well-known/openid-configuration",
+            [OAuth + "Issuer"] = Issuer,
+            [OAuth + "Audience"] = Audience,
+            [OAuth + "AppOnlyClaim"] = "token_kind",
+            [OAuth + "AppOnlyValue"] = "app",
+            [OAuth + "ReadScope"] = "batch.read",
+            [OAuth + "WriteScope"] = "batch.write",
+            [OAuth + "Clients:0:Enabled"] = "true",
+            [OAuth + "Clients:0:Identity"] = "factory-client",
+            [OAuth + "Clients:0:GrantReference"] = "factory-source",
+            [OAuth + "Clients:0:TenantId"] = "101",
+            [OAuth + "Clients:0:UserId"] = "102"
+        }).Build();
+        var service = new MdpIngestExternalIdentities(configuration, new ClientFactory(metadata));
+
+        var caller = await Resolve(Token());
+        Assert.NotNull(caller);
+        Assert.Equal(101, caller.TenantId);
+        Assert.Equal(102, caller.UserId);
+        var expectedHash = Convert.ToHexString(SHA256.HashData("mdp-external\0oauth2\0factory-source"u8)).ToLowerInvariant();
+        Assert.Equal(expectedHash, caller.AccessKeyHash);
+        Assert.Null(await Resolve(Token(), read: true));
+        Assert.NotNull(await Resolve(Token(scope: "batch.read"), read: true));
+        Assert.Null(await Resolve(Token(audience: "another-api")));
+        Assert.Null(await Resolve(Token(issuer: Issuer + "/other")));
+        Assert.Null(await Resolve(Token(app: "user")));
+        Assert.Null(await Resolve(Token(client: "other-client")));
+        Assert.Null(await Resolve(Token(signingKey: otherKey)));
+        Assert.Null(await Resolve(Token(expired: true)));
+        configuration[OAuth + "Clients:0:Enabled"] = "false";
+        Assert.Null(await Resolve(Token()));
+
+        Task<MdpIngestIdentity?> Resolve(string token, bool read = false) =>
+            service.ResolveBearerAsync("Bearer " + token, read, CancellationToken.None);
+
+        string Token(string issuer = Issuer, string audience = Audience, string app = "app", string client = "factory-client",
+            string scope = "batch.write", RsaSecurityKey? signingKey = null, bool expired = false)
+        {
+            var now = DateTime.UtcNow;
+            return new JsonWebTokenHandler().CreateToken(new SecurityTokenDescriptor
+            {
+                Issuer = issuer, Audience = audience,
+                IssuedAt = now.AddMinutes(-5), NotBefore = now.AddMinutes(-5), Expires = now.AddMinutes(expired ? -2 : 2),
+                Subject = new ClaimsIdentity([new Claim("token_kind", app), new Claim("client_id", client), new Claim("scope", scope)]),
+                SigningCredentials = new SigningCredentials(signingKey ?? key, SecurityAlgorithms.RsaSha256)
+            });
+        }
+    }
+
+    [Fact]
+    public void Mtls_RejectsAnExplicitlyMappedCertificateWithoutATrustedChain()
+    {
+        using var rsa = RSA.Create(2048);
+        var request = new CertificateRequest("CN=isolated-factory", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
+        request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new("1.3.6.1.5.5.7.3.2") }, true));
+        using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-1), DateTimeOffset.UtcNow.AddMinutes(1));
+        var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
+        {
+            [Mtls + "Clients:0:Enabled"] = "true",
+            [Mtls + "Clients:0:Identity"] = certificate.GetCertHashString(HashAlgorithmName.SHA256),
+            [Mtls + "Clients:0:GrantReference"] = "factory-source",
+            [Mtls + "Clients:0:TenantId"] = "101",
+            [Mtls + "Clients:0:UserId"] = "102"
+        }).Build();
+        using var http = new HttpClient();
+        var service = new MdpIngestExternalIdentities(configuration, new ClientFactory(http));
+        Assert.Null(service.ResolveCertificate(certificate));
+    }
+
+    private sealed class ClientFactory(HttpClient client) : IHttpClientFactory
+    {
+        public HttpClient CreateClient(string name) => client;
+    }
+
+    private sealed class Metadata(RSAParameters publicKey) : HttpMessageHandler
+    {
+        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
+        {
+            var document = request.RequestUri!.AbsolutePath switch
+            {
+                "/.well-known/openid-configuration" => JsonSerializer.Serialize(new
+                {
+                    issuer = Issuer, jwks_uri = Issuer + "/keys"
+                }),
+                "/keys" => JsonSerializer.Serialize(new
+                {
+                    keys = new[]
+                    {
+                        new
+                        {
+                            kty = "RSA", kid = "documented-key", use = "sig", alg = "RS256",
+                            n = Base64UrlEncoder.Encode(publicKey.Modulus), e = Base64UrlEncoder.Encode(publicKey.Exponent)
+                        }
+                    }
+                }),
+                _ => throw new InvalidOperationException()
+            };
+            return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(document) });
+        }
+    }
+}

+ 20 - 0
server/Plugins/Admin.NET.Plugin.AiDOP.Tests/DataPlatform/MdpIngestContractBindingTests.cs

@@ -79,6 +79,26 @@ public sealed class MdpIngestContractBindingTests
             Assert.Equal(15.5m,Assert.Single(package.Items).OrderQty);
             Assert.Equal("A#1",v2.Events[0].SourceBusinessKey);
             Assert.Equal("po-source-v2",package.SourceSchemaVersion);
+            const string second = "lab.vendor.purchase-orders";
+            Execute(connectionString, """
+                INSERT INTO mdp_ingest_dataset VALUES (106,101,102,'lab.vendor.purchase-orders','vendor-po-v1',1);
+                INSERT INTO mdp_ingest_dataset_source VALUES (106,101,102,103,1);
+                INSERT INTO mdp_ingest_dataset_version VALUES (106,101,102,'vendor-po-v1');
+                INSERT INTO mdp_ingest_contract_archive VALUES
+                    (101,102,106,'vendor-po-v1','{"PoNo":"VendorOrder","OrderQty":"Qty"}');
+                INSERT INTO mdp_ingest_published_source VALUES (101,102,106,'vendor-po-v1',103);
+                """);
+            var ndjson = """{"VendorOrder":"B","PoLine":"02","Qty":15.5,"ItemCode":"X","sourceUpdatedAt":"2026-11-20T00:00:00Z"}"""u8.ToArray();
+            var vendor = await binder.PrepareAsync(101, 102, 103, second, ndjson, Limits, format: IngestPayloadFormat.Ndjson,
+                schemaVersion: "vendor-po-v1");
+            Assert.Equal(second, vendor.Batch.Identity.DatasetKey);
+            Assert.Equal("B#02", Assert.Single(vendor.Events).SourceBusinessKey);
+            Assert.Equal(15.5m, Assert.Single(PurchaseBatchProcessor.Process(vendor, "").Package.Items).OrderQty);
+            var otherSchema = await Assert.ThrowsAsync<IngestContractException>(() =>
+                binder.PrepareAsync(101, 102, 103, second, ndjson, Limits, format: IngestPayloadFormat.Ndjson,
+                    schemaVersion: "po-source-v2"));
+            Assert.Equal(IngestContractError.UnknownSchema, otherSchema.Code);
+
             Execute(connectionString, "INSERT INTO mdp_ingest_lifecycle VALUES (104,'PAUSED')");
             await RejectAsync(101,102,103,IngestContractError.DatasetUnavailable);
             Assert.Single(PurchaseBatchProcessor.Process(v2,"").Package.Items);

+ 17 - 0
server/Plugins/Admin.NET.Plugin.AiDOP.Tests/DataPlatform/MdpPurchaseWorkerTests.cs

@@ -65,6 +65,23 @@ public sealed class MdpPurchaseWorkerTests
             Assert.Single(result.Quarantines));
     }
 
+    [Fact]
+    public void ApiSnapshot_PreservesTwoOrderedVersionsAndOldPackagesStayUnchanged()
+    {
+        var old = Prepare(Fixture());
+        var api = old with { Batch = old.Batch with { SourceWindow = new(null, null, "PURCHASE-API-TIME-V1") } };
+        Assert.Equal("1.0.0", PurchaseBatchProcessor.Process(old, "").Package.PackageVersion);
+        var result = PurchaseBatchProcessor.Process(api, "");
+        Assert.Equal("1.2.0", result.Package.PackageVersion);
+        Assert.Equal(2, result.Package.Items.Count);
+        Assert.All(result.Package.Items, line =>
+        {
+            Assert.NotNull(line.SourceChange);
+            Assert.Equal(0, line.SourceChange.Generation);
+            Assert.Equal(DateTimeOffset.Parse(line.SourceUpdatedAt).UtcTicks, line.SourceChange.Version);
+        });
+    }
+
     private static PreparedIngestBatch Prepare(string content) =>
         Preparer.Prepare(Identity, PurchaseOrderSchemaRegistry.SourceVersion, Encoding.UTF8.GetBytes(content), Limits);
 

+ 39 - 0
server/Plugins/Admin.NET.Plugin.AiDOP.Tests/DataPlatform/MdpPushKitTests.cs

@@ -0,0 +1,39 @@
+using System.IO.Compression;
+using System.Text.Json;
+using Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
+using Xunit;
+
+namespace Admin.NET.Plugin.AiDOP.Tests.DataPlatform;
+
+public sealed class MdpPushKitTests
+{
+    [Theory]
+    [InlineData("https://localhost:5443", true)]
+    [InlineData("http://localhost:5443", false)]
+    [InlineData("https://localhost:5443/other", false)]
+    public void KitUsesPublishedMappingAndOnlyExportsApprovedHttpsOrigin(string origin, bool approved)
+    {
+        using var data = JsonDocument.Parse("""
+            {"datasetKey":"lab.purchase.v1","schemaVersion":"po-test","schemaJson":"{}",
+             "rowSchema":{"type":"object","required":["VendorPoNo"]},
+             "endpoint":"/api/v1/ingest/lab.purchase.v1",
+             "batchStatusEndpoint":"/api/v1/ingest/lab.purchase.v1/batches/{batchId}",
+             "samples":{"json":"{}","ndjson":"{\"VendorPoNo\":\"PO-1\"}\n"},
+             "signatureVector":{"exampleKeyBase64":"example"}}
+            """);
+        using var zip = new ZipArchive(new MemoryStream(MdpPushKit.Build(data.RootElement, "801", origin)));
+        using var openapi = JsonDocument.Parse(Read("openapi.json"));
+        Assert.Equal(approved ? 1 : 0, openapi.RootElement.GetProperty("servers").GetArrayLength());
+        Assert.True(openapi.RootElement.GetProperty("paths").TryGetProperty("/api/v1/ingest/lab.purchase.v1", out _));
+        Assert.Contains("VendorPoNo", Read("row.schema.json"));
+        Assert.Equal("{\"VendorPoNo\":\"PO-1\"}\n", Read("sample.ndjson"));
+        Assert.DoesNotContain("SIGNING_KEY_BASE64=", Read("client.env"));
+        Assert.All(new[] { "push.py", "push.mjs", "Push.cs", "Push.java" }, name => Assert.Contains("Idempotency-Key", Read(name)));
+
+        string Read(string name)
+        {
+            using var reader = new StreamReader(zip.GetEntry(name)!.Open());
+            return reader.ReadToEnd();
+        }
+    }
+}

+ 18 - 0
server/Plugins/Admin.NET.Plugin.AiDOP.Tests/DataPlatform/MdpSchemaMigrationGateTests.cs

@@ -0,0 +1,18 @@
+using Xunit;
+
+namespace Admin.NET.Plugin.AiDOP.Tests.DataPlatform;
+
+public sealed class MdpSchemaMigrationGateTests
+{
+    [Fact]
+    public void PublicationRequiresMigrationBeforeChangingTheActiveContract()
+    {
+        var dir = new DirectoryInfo(AppContext.BaseDirectory);
+        while (dir != null && !Directory.Exists(Path.Combine(dir.FullName, "server"))) dir = dir.Parent;
+        var code = File.ReadAllText(Path.Combine(dir!.FullName, "server", "Plugins", "Admin.NET.Plugin.AiDOP",
+            "DataPlatform", "UnifiedIngress", "MdpDatasetReleaseController.cs"));
+        var publish = code.IndexOf("case \"publish\"", StringComparison.Ordinal);
+        var update = code.IndexOf("await Publish(dataset, row);", publish, StringComparison.Ordinal);
+        Assert.Contains("await EnsureSchemaMigrationReady(dataset, row);", code[publish..update]);
+    }
+}

+ 34 - 0
server/Plugins/Admin.NET.Plugin.AiDOP.Tests/DataPlatform/MdpUnifiedIngressContractTests.cs

@@ -56,6 +56,40 @@ public sealed class MdpUnifiedIngressContractTests
         Assert.Equal((byte)'{', prepared.Batch.Payload.Span[0]);
     }
 
+    [Fact]
+    public void Ndjson_PreservesOriginalBytesAndExactSlices()
+    {
+        var bytes = Encoding.UTF8.GetBytes("  {\"PoNo\":\"采购单\",\"PoLine\":\"01\"} \r\n{\"PoNo\":\"另一个\",\"PoLine\":\"02\"}\n");
+        var result = Preparer.Prepare(Identity, SourceVersion, bytes, Limits, format: IngestPayloadFormat.Ndjson);
+        Assert.Equal(bytes, result.Batch.Payload.ToArray());
+        Assert.Equal(new[] { "采购单#01", "另一个#02" }, result.Events.Select(row => row.SourceBusinessKey));
+        Assert.Equal(new[] { "/lines/1", "/lines/2" }, result.Events.Select(row => row.SourcePosition));
+        Assert.Equal(2, result.Events[0].PayloadOffset);
+        foreach (var row in result.Events)
+        {
+            var slice = result.Batch.Payload.Slice(row.PayloadOffset, row.PayloadLength);
+            Assert.Equal((byte)'}', slice.Span[^1]);
+            Assert.Equal(Convert.ToHexString(SHA256.HashData(slice.Span)).ToLowerInvariant(), row.PayloadSha256);
+        }
+    }
+
+    [Theory]
+    [InlineData("{}", null)]
+    [InlineData("{}\r\n{}\r\n", null)]
+    [InlineData("", IngestContractError.InvalidEnvelope)]
+    [InlineData("{}\n\n{}", IngestContractError.InvalidEnvelope)]
+    [InlineData("{}\n[]", IngestContractError.InvalidEnvelope)]
+    [InlineData("{} {}", IngestContractError.InvalidJson)]
+    public void Ndjson_ValidatesLineBoundaries(string body, IngestContractError? expected)
+    {
+        PreparedIngestBatch Read() => Preparer.Prepare(Identity, SourceVersion, Encoding.UTF8.GetBytes(body),
+            Limits, format: IngestPayloadFormat.Ndjson);
+        if (expected.HasValue)
+            Assert.Equal(expected.Value, Assert.Throws<IngestContractException>(() => Read()).Code);
+        else
+            Assert.NotEmpty(Read().Events);
+    }
+
     [Fact]
     public void RawContract_UsesOnePayloadAndOnlyIndexesForEvents()
     {

+ 6 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/Admin.NET.Plugin.AiDOP.csproj

@@ -30,5 +30,11 @@
     <Folder Include="WorkOrder\Dto\" />
   </ItemGroup>
 
+  <ItemGroup>
+    <Compile Remove="DataPlatform/UnifiedIngress/PushKitClients/Push.cs" />
+    <EmbeddedResource Include="DataPlatform/UnifiedIngress/PushKitClients/*"
+                      LogicalName="MdpPushKit.%(Filename)%(Extension)" />
+  </ItemGroup>
+
   <Import Project="../../build/DataPlatformBoundary.targets" />
 </Project>

+ 25 - 3
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpBatchFactory.cs

@@ -1,5 +1,6 @@
 using System.Globalization;
 using System.Text.Json;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
 
 namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
 
@@ -24,9 +25,7 @@ internal static class MdpBatchFactory
             {
                 foreach (var row in list.EnumerateArray())
                 {
-                    if (row.ValueKind != JsonValueKind.Object || !TryId(row, "factoryId", out var rowFactory)
-                        || rowFactory.HasValue && rowFactory != factory || !TryId(row, "tenantId", out var rowTenant)
-                        || rowTenant.HasValue && rowTenant != tenant) return false;
+                    if (!RowMatches(row, tenant, factory)) return false;
                 }
             }
             return factory > 0;
@@ -37,6 +36,29 @@ internal static class MdpBatchFactory
         }
     }
 
+    internal static bool TryResolve(long configuredFactory, bool fromBatch, long? requested, out long factory)
+    {
+        factory = requested ?? configuredFactory;
+        return factory > 0 && (fromBatch ? requested.HasValue : factory == configuredFactory);
+    }
+
+    internal static bool RowsMatch(PreparedIngestBatch prepared)
+    {
+        var identity = prepared.Batch.Identity;
+        foreach (var row in prepared.Events)
+        {
+            using var document = JsonDocument.Parse(prepared.Batch.Payload.Slice(row.PayloadOffset, row.PayloadLength));
+            if (!RowMatches(document.RootElement, identity.TenantId, identity.FactoryId))
+                return false;
+        }
+        return true;
+    }
+
+    private static bool RowMatches(JsonElement row, long tenant, long factory) =>
+        row.ValueKind == JsonValueKind.Object && TryId(row, "factoryId", out var rowFactory)
+        && (!rowFactory.HasValue || rowFactory == factory) && TryId(row, "tenantId", out var rowTenant)
+        && (!rowTenant.HasValue || rowTenant == tenant);
+
     private static bool TryId(JsonElement root, string field, out long? value)
     {
         value = null;

+ 84 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpDatasetReleaseController.SchemaMigration.cs

@@ -0,0 +1,84 @@
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
+using Admin.NET.Plugin.AiDOP.Entity.DataPlatform;
+using Admin.NET.Plugin.ApprovalFlow;
+
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
+
+public sealed record MdpSchemaMigrationConfirmation(string? EvidenceReference);
+
+public sealed partial class MdpIngestDatasetController
+{
+    private const string MigrationReadyAction = "schema-migration-ready";
+
+    [HttpPost("{id:long}/releases/{release:long}/migration-ready")]
+    [DisplayName("登记 Schema 迁移完成")]
+    public Task<IActionResult> RecordSchemaMigration(long id, long release, [FromQuery] long? factoryId,
+        MdpSchemaMigrationConfirmation input) => Locked(id, factoryId, async (dataset, scope) =>
+    {
+        if (!await Can(PublishPermission)) return Forbid();
+        var row = await db.Ado.SqlQuerySingleAsync<Release>(ReleaseSelect + " AND id=@release FOR UPDATE",
+            new { tenant = scope.TenantId, factory = scope.FactoryId, id, release });
+        Require(row != null && row.State == "REVIEW" && row.BaseRevision == dataset.Revision
+            && row.EnvironmentKey == TargetEnvironment, "请在当前配置修订提交候选版本审批");
+        var approved = await Approval(row!);
+        Require(approved?.Status == FlowInstanceStatusEnum.Approved && await HasFactoryApproval(approved.Id, scope),
+            "尚未取得人工审批通过记录");
+        Require(await RequiresSchemaMigration(dataset, row!), "该版本无需登记 Schema 迁移");
+        await CheckMigrationWindow(dataset);
+        var reference = input.EvidenceReference?.Trim();
+        Require(reference is { Length: > 0 and <= 250 } && !reference.Any(char.IsControl),
+            "填写调用方迁移完成的工单或联测记录");
+        await Log(id, release, MigrationReadyAction, MigrationStamp(dataset, row!) + reference);
+        return NoContent();
+    });
+
+    private async Task EnsureSchemaMigrationReady(MdpIngestDataset dataset, Release row)
+    {
+        if (!await RequiresSchemaMigration(dataset, row)) return;
+        await CheckMigrationWindow(dataset);
+        Require(await HasMigrationConfirmation(dataset, row), "破坏性 Schema 变更须先登记调用方迁移完成");
+    }
+
+    private async Task<bool> RequiresSchemaMigration(MdpIngestDataset dataset, Release row) =>
+        RequiresSchemaMigration(dataset, row, await ReadActiveMapping(dataset));
+
+    private static bool RequiresSchemaMigration(MdpIngestDataset dataset, Release row, string? mapping) =>
+        dataset.ActiveSchemaVersion is { Length: > 0 }
+        && !string.Equals(mapping, row.MappingJson, StringComparison.Ordinal);
+
+    private async Task<string?> ReadActiveMapping(MdpIngestDataset dataset)
+    {
+        if (dataset.ActiveSchemaVersion is not { Length: > 0 } version)
+            return null;
+        var archive = await db.Ado.SqlQuerySingleAsync<string>("""
+            SELECT mapping_json FROM mdp_ingest_contract_archive
+            WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND dataset_id=@Id AND schema_version=@version
+            """, new { dataset.TenantId, dataset.FactoryId, dataset.Id, version });
+        if (archive is null && new PurchaseOrderSchemaRegistry().Find(dataset.DatasetKey, version) is not null)
+            archive = "{}";
+        return archive is null ? null : new PurchaseVersionConfiguration(dataset.DatasetKey, version, archive).MappingJson;
+    }
+
+    private async Task CheckMigrationWindow(MdpIngestDataset dataset)
+    {
+        Require(await ReadActiveMapping(dataset) != null, "当前版本的历史映射不可核对");
+        Require(await Lifecycle(dataset.Id) == "PAUSED", "请先暂停接收,再按暂停后的修订创建迁移候选");
+        var outstanding = await db.Ado.GetIntAsync("""
+            SELECT COUNT(*) FROM mdp_ingest_receive_task WHERE dataset_id=@Id AND tenant_id=@TenantId
+            AND status NOT IN ('SUCCEEDED','PARTIAL','QUARANTINED')
+            """, new { dataset.Id, dataset.TenantId });
+        Require(outstanding == 0, "请先处理完该数据集的在途和待处置批次");
+    }
+
+    private async Task<bool> HasMigrationConfirmation(MdpIngestDataset dataset, Release row)
+    {
+        var stamp = MigrationStamp(dataset, row);
+        return await db.Ado.GetIntAsync("""
+            SELECT COUNT(*) FROM mdp_ingest_release_log WHERE dataset_id=@datasetId AND release_id=@release
+                AND action=@action AND LEFT(detail,CHAR_LENGTH(@stamp))=@stamp
+            """, new { datasetId = dataset.Id, release = row.Id, action = MigrationReadyAction, stamp }) > 0;
+    }
+
+    private static string MigrationStamp(MdpIngestDataset dataset, Release row) =>
+        $"[{dataset.ActiveSchemaVersion} → {row.Version} / {row.BaseRevision}] ";
+}

+ 10 - 3
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpDatasetReleaseController.cs

@@ -90,7 +90,9 @@ public sealed partial class MdpIngestDatasetController
     [HttpGet("{id:long}/releases")]
     public Task<IActionResult> Releases(long id, [FromQuery] long? factoryId) => WithScope(factoryId, async scope =>
     {
-        if (!await Datasets(scope).AnyAsync(x => x.Id == id)) return NotFound();
+        var dataset = await Datasets(scope).FirstAsync(x => x.Id == id);
+        if (dataset is null) return NotFound();
+        var activeMapping = await ReadActiveMapping(dataset);
         var releases = await db.Ado.SqlQueryAsync<Release>(ReleaseSelect + " ORDER BY id DESC",
             new { tenant = scope.TenantId, factory = scope.FactoryId, id });
         var lifecycle = await Lifecycle(id);
@@ -106,6 +108,7 @@ public sealed partial class MdpIngestDatasetController
         {
             var approval = item.FlowId.HasValue ? await Approval(item) : null;
             var handoff = evidence.GetValueOrDefault(item.Id);
+            var migrationRequired = item.State != "PUBLISHED" && RequiresSchemaMigration(dataset, item, activeMapping);
             history.Add(new
             {
                 id = item.Id.ToString(),
@@ -124,6 +127,9 @@ public sealed partial class MdpIngestDatasetController
                 item.EnvironmentKey,
                 item.BaseRevision,
                 item.TrialJson,
+                schemaMigrationRequired = migrationRequired,
+                schemaMigrationReady = migrationRequired && lifecycle == "PAUSED" && item.BaseRevision == dataset.Revision
+                    && await HasMigrationConfirmation(dataset, item),
                 approval = approval?.Status.ToString(),
                 flowId = item.FlowId?.ToString()
             });
@@ -197,8 +203,8 @@ public sealed partial class MdpIngestDatasetController
         {
             case "precheck":
                 Require(row.State == "DRAFT", "只有草稿可以预检");
-                await CheckReceiver(dataset, source!, row);
                 await CheckConfiguredSourcePreflight(dataset, source!, row, HttpContext.RequestAborted);
+                await CheckReceiver(dataset, source!, row);
                 next = "PREFLIGHT";
                 break;
             case "trial":
@@ -257,8 +263,9 @@ public sealed partial class MdpIngestDatasetController
                 var approved = await Approval(row);
                 Require(approved?.Status == FlowInstanceStatusEnum.Approved &&
                     await HasFactoryApproval(approved.Id, scope), "尚未取得人工审批通过记录");
-                await CheckReceiver(dataset, source!, row);
                 await CheckConfiguredSourcePreflight(dataset, source!, row, HttpContext.RequestAborted);
+                await CheckReceiver(dataset, source!, row);
+                await EnsureSchemaMigrationReady(dataset, row);
                 await Publish(dataset, row);
                 next = "PUBLISHED";
                 break;

+ 43 - 23
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestAdmissionStore.cs

@@ -1,9 +1,14 @@
+using Microsoft.Extensions.Configuration;
 using Microsoft.Extensions.Logging;
 
 namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
 
-public sealed class MdpIngestAdmissionStore(ISqlSugarClient db, ILogger<MdpIngestAdmissionStore> logger)
+public sealed class MdpIngestAdmissionStore(ISqlSugarClient db, ILogger<MdpIngestAdmissionStore> logger, IConfiguration configuration)
 {
+    // A positive source ID belongs to a grant. Zero is reserved for the shared tenant quota.
+    private const long TenantCounter = 0;
+    private const int DefaultTenantRateLimit = 600;
+
     internal async Task<MdpIngestAdmission> AdmitAsync(
         long tenantId, string accessKeyHash, string datasetKey, string nonceHash, CancellationToken cancellationToken)
     {
@@ -55,35 +60,30 @@ public sealed class MdpIngestAdmissionStore(ISqlSugarClient db, ILogger<MdpInges
                 return new(MdpIngestAdmissionStatus.Replayed);
             }
 
-            var source = new { TenantId = tenantId, grant.SourceId };
-            // 此语句持有该来源计数行的写锁。后续使用同一事务里的数据库时钟和计数。
-            await ado.ExecuteCommandAsync(
-                """
-                INSERT INTO mdp_ingest_source_rate (tenant_id, source_id, window_minute, request_count)
-                VALUES (@TenantId, @SourceId, 0, 0)
-                ON DUPLICATE KEY UPDATE source_id = source_id
-                """, source);
+            var tenantLimit = configuration.GetValue<int?>($"MdpUnifiedIngress:TenantRateLimits:{tenantId}")
+                ?? configuration.GetValue<int?>("MdpUnifiedIngress:TenantRateLimit")
+                ?? DefaultTenantRateLimit;
+            if (tenantLimit <= 0)
+                throw new InvalidOperationException("Invalid MDP tenant quota");
+
+            // Both limits are checked under the same transaction and lock order across instances.
+            await LockRateAsync(TenantCounter);
+            await LockRateAsync(grant.SourceId);
             var seconds = await ado.GetLongAsync("SELECT UNIX_TIMESTAMP()");
             var minute = seconds / 60;
-            count = await ado.GetIntAsync(
-                """
-                SELECT IF(window_minute = @Minute, request_count, 0) FROM mdp_ingest_source_rate
-                WHERE tenant_id = @TenantId AND source_id = @SourceId
-                FOR UPDATE
-                """, new { source.TenantId, source.SourceId, Minute = minute });
-            if (count >= grant.RateLimit)
+            var tenantCount = await ReadRateAsync(TenantCounter, minute);
+            count = await ReadRateAsync(grant.SourceId, minute);
+            if (tenantCount >= tenantLimit || count >= grant.RateLimit)
             {
                 // 已验签的请求即使被限流也消耗 nonce。重试时须重新签名并更换 nonce。
                 cancellationToken.ThrowIfCancellationRequested();
                 await ado.CommitTranAsync();
-                return new(MdpIngestAdmissionStatus.Limited, RetryAfterSeconds: 60 - (int)(seconds % 60));
+                return new(tenantCount >= tenantLimit ? MdpIngestAdmissionStatus.TenantLimited : MdpIngestAdmissionStatus.Limited,
+                    RetryAfterSeconds: 60 - (int)(seconds % 60));
             }
 
-            await ado.ExecuteCommandAsync(
-                """
-                UPDATE mdp_ingest_source_rate SET window_minute = @Minute, request_count = @Count
-                WHERE tenant_id = @TenantId AND source_id = @SourceId
-                """, new { source.TenantId, source.SourceId, Minute = minute, Count = count + 1 });
+            await UpdateRateAsync(TenantCounter, minute, tenantCount + 1);
+            await UpdateRateAsync(grant.SourceId, minute, count + 1);
             cancellationToken.ThrowIfCancellationRequested();
             await ado.CommitTranAsync();
         }
@@ -107,10 +107,30 @@ public sealed class MdpIngestAdmissionStore(ISqlSugarClient db, ILogger<MdpInges
         }
 
         return new(MdpIngestAdmissionStatus.Admitted, grant);
+
+        Task<int> LockRateAsync(long sourceId) => ado.ExecuteCommandAsync(
+            """
+            INSERT INTO mdp_ingest_source_rate (tenant_id, source_id, window_minute, request_count)
+            VALUES (@TenantId, @SourceId, 0, 0)
+            ON DUPLICATE KEY UPDATE source_id = source_id
+            """, new { TenantId = tenantId, SourceId = sourceId });
+
+        Task<int> ReadRateAsync(long sourceId, long minute) => ado.GetIntAsync(
+            """
+            SELECT IF(window_minute = @Minute, request_count, 0) FROM mdp_ingest_source_rate
+            WHERE tenant_id = @TenantId AND source_id = @SourceId FOR UPDATE
+            """, new { TenantId = tenantId, SourceId = sourceId, Minute = minute });
+
+        Task<int> UpdateRateAsync(long sourceId, long minute, int count) => ado.ExecuteCommandAsync(
+            """
+            UPDATE mdp_ingest_source_rate SET window_minute = @Minute, request_count = @Count
+            WHERE tenant_id = @TenantId AND source_id = @SourceId
+            """, new { TenantId = tenantId, SourceId = sourceId, Minute = minute, Count = count });
+
     }
 }
 
-internal enum MdpIngestAdmissionStatus { Admitted, Forbidden, Replayed, Limited }
+internal enum MdpIngestAdmissionStatus { Admitted, Forbidden, Replayed, Limited, TenantLimited }
 
 internal sealed record MdpIngestAdmission(
     MdpIngestAdmissionStatus Status, MdpIngestGrant? Grant = null, int RetryAfterSeconds = 0);

+ 100 - 31
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestAuthenticationHandler.cs

@@ -1,10 +1,12 @@
 using System.Globalization;
+using System.Net.Http.Headers;
 using System.Security.Claims;
 using System.Security.Cryptography;
 using System.Text;
 using System.Text.Encodings.Web;
 using System.Text.RegularExpressions;
 using Admin.NET.Plugin.AiDOP.DataPlatform.Inbound;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
 using Microsoft.AspNetCore.Authentication;
 using Microsoft.AspNetCore.Http;
 using Microsoft.Extensions.Logging;
@@ -17,7 +19,8 @@ public sealed class MdpIngestAuthenticationHandler(
     ILoggerFactory logger,
     UrlEncoder encoder,
     MdpIngestAdmissionStore store,
-    ISecretStore secrets) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
+    ISecretStore secrets,
+    MdpIngestExternalIdentities external) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
 {
     private const long AllowedClockSkewSeconds = 300;
     private static readonly Regex DatasetKeyPattern = new(@"\A[a-z0-9][a-z0-9._-]{0,79}\z");
@@ -30,64 +33,130 @@ public sealed class MdpIngestAuthenticationHandler(
         if (Request.ContentLength > MdpIngestProtocol.Limits.MaxBodyBytes)
             return Fail(StatusCodes.Status413PayloadTooLarge, "BODY_TOO_LARGE");
 
-        var accessKey = ReadHeader(InboundSignatureDefaults.AccessKeyHeader, 128);
+        var query = HttpMethods.IsGet(Request.Method);
+        var signatureVersion = ReadHeader(MdpIngestProtocol.SignatureVersionHeader, 40);
+        var schemaVersion = ReadHeader(MdpIngestProtocol.SchemaHeader, 64);
+        var factoryHeader = ReadHeader(MdpIngestProtocol.FactoryHeader, 19);
+        if (signatureVersion is null && Request.Headers.ContainsKey(MdpIngestProtocol.SignatureVersionHeader)
+            || schemaVersion is null && Request.Headers.ContainsKey(MdpIngestProtocol.SchemaHeader)
+            || factoryHeader is null && Request.Headers.ContainsKey(MdpIngestProtocol.FactoryHeader))
+            return Fail(StatusCodes.Status400BadRequest, "INVALID_REQUEST_METADATA");
+
+        long? factoryId = null;
+        if (factoryHeader is not null)
+        {
+            if (!long.TryParse(factoryHeader, NumberStyles.None, CultureInfo.InvariantCulture, out var factory) || factory <= 0)
+                return Fail(StatusCodes.Status400BadRequest, "INVALID_BATCH_SCOPE");
+            factoryId = factory;
+        }
+
+        var mediaType = query ? "" : "application/json";
+        if (Request.ContentType is { } contentType)
+        {
+            if (query || !MediaTypeHeaderValue.TryParse(contentType, out var media)
+                || media.MediaType is null
+                || media.Parameters.Any(parameter => !parameter.Name.Equals("charset", StringComparison.OrdinalIgnoreCase))
+                || media.Parameters.Count > 1
+                || media.CharSet is { } charset && !charset.Trim('"').Equals("utf-8", StringComparison.OrdinalIgnoreCase))
+                return Fail(StatusCodes.Status415UnsupportedMediaType, "UNSUPPORTED_MEDIA_TYPE");
+            mediaType = media.MediaType.ToLowerInvariant();
+        }
+        if (mediaType is not ("" or "application/json" or "application/x-ndjson"))
+            return Fail(StatusCodes.Status415UnsupportedMediaType, "UNSUPPORTED_MEDIA_TYPE");
+        var format = mediaType == "application/x-ndjson" ? IngestPayloadFormat.Ndjson : IngestPayloadFormat.Json;
+        if (!query && format == IngestPayloadFormat.Json && factoryId.HasValue
+            || query && schemaVersion is not null)
+            return Fail(StatusCodes.Status400BadRequest, "INVALID_REQUEST_METADATA");
+
         var timestamp = ReadHeader(InboundSignatureDefaults.TimestampHeader, 20);
         var nonce = ReadHeader(InboundSignatureDefaults.NonceHeader, 128);
-        var signature = ReadHeader(InboundSignatureDefaults.SignatureHeader, 44);
-        var digest = ReadHeader(InboundSignatureDefaults.ContentSha256Header, 64);
-        if (accessKey is null || timestamp is null || nonce is null || signature?.Length != 44 || digest?.Length != 64)
+        if (timestamp is null || nonce is null
+            || !long.TryParse(timestamp, NumberStyles.None, CultureInfo.InvariantCulture, out var unixSeconds)
+            || !IsWithinClockSkew(unixSeconds))
             return Fail(StatusCodes.Status401Unauthorized, "INVALID_AUTHENTICATION");
 
-        var idempotencyKey = ReadHeader(InboundSignatureDefaults.IdempotencyKeyHeader, 128);
+        var idempotencyKey = query ? "" : ReadHeader(InboundSignatureDefaults.IdempotencyKeyHeader, 128);
         if (idempotencyKey is null)
             return Fail(StatusCodes.Status400BadRequest, "INVALID_IDEMPOTENCY_KEY");
 
-        if (!long.TryParse(timestamp, NumberStyles.None, CultureInfo.InvariantCulture, out var unixSeconds)
-            || !IsWithinClockSkew(unixSeconds))
-            return Fail(StatusCodes.Status401Unauthorized, "INVALID_AUTHENTICATION");
-
         try
         {
             var payload = await ReadPayloadAsync();
             if (payload is null)
                 return Fail(StatusCodes.Status413PayloadTooLarge, "BODY_TOO_LARGE");
-
-            var payloadSha256 = Sha256(payload);
-            if (!string.Equals(payloadSha256, digest, StringComparison.OrdinalIgnoreCase))
-                return Fail(StatusCodes.Status400BadRequest, "CONTENT_DIGEST_MISMATCH");
-
-            using var credential = await secrets.ResolveAsync(accessKey, Context.RequestAborted);
-            if (credential is null)
-                return Fail(StatusCodes.Status401Unauthorized, "INVALID_AUTHENTICATION");
-
-            var signed = $"{Request.Method.ToUpperInvariant()}&{Request.Path.Value}&{accessKey}&{timestamp}&{nonce}&{payloadSha256}&{idempotencyKey}";
-            if (!credential.Verify(signed, signature))
+            if (query && payload.Length != 0)
+                return Fail(StatusCodes.Status400BadRequest, "INVALID_REQUEST");
+
+            var certificate = await Context.Connection.GetClientCertificateAsync(Context.RequestAborted);
+            var hasBearer = Request.Headers.ContainsKey("Authorization");
+            var hasHmac = Request.Headers.ContainsKey(InboundSignatureDefaults.AccessKeyHeader)
+                || Request.Headers.ContainsKey(InboundSignatureDefaults.SignatureHeader) || signatureVersion is not null;
+            if ((hasBearer ? 1 : 0) + (hasHmac ? 1 : 0) + (certificate is null ? 0 : 1) != 1
+                || (hasBearer || certificate is not null) && !Request.IsHttps)
                 return Fail(StatusCodes.Status401Unauthorized, "INVALID_AUTHENTICATION");
 
-            // 报文读取可能耗时,准入前再核对签名时效。
-            if (!IsWithinClockSkew(unixSeconds))
+            MdpIngestIdentity? caller;
+            if (hasHmac)
+            {
+                var accessKey = ReadHeader(InboundSignatureDefaults.AccessKeyHeader, 128);
+                var signature = ReadHeader(InboundSignatureDefaults.SignatureHeader, 44);
+                var digest = ReadHeader(InboundSignatureDefaults.ContentSha256Header, 64);
+                var v2 = signatureVersion == MdpIngestProtocol.SignatureVersionV2;
+                if (accessKey is null || signature?.Length != 44 || digest?.Length != 64
+                    || !v2 && (query || format == IngestPayloadFormat.Ndjson || schemaVersion is not null
+                        || signatureVersion is not (null or MdpIngestProtocol.SignatureVersion)))
+                    return Fail(StatusCodes.Status401Unauthorized, "INVALID_AUTHENTICATION");
+
+                var payloadSha256 = Sha256(payload);
+                if (!string.Equals(payloadSha256, digest, StringComparison.OrdinalIgnoreCase))
+                    return Fail(StatusCodes.Status400BadRequest, "CONTENT_DIGEST_MISMATCH");
+
+                using var credential = await secrets.ResolveAsync(accessKey, Context.RequestAborted);
+                var signed = MdpIngestProtocol.CanonicalSignature(Request.Method, Request.Path.Value!, accessKey,
+                    timestamp, nonce, payloadSha256, idempotencyKey, v2, mediaType, factoryHeader, schemaVersion);
+                if (credential is null || !credential.Verify(signed, signature))
+                    return Fail(StatusCodes.Status401Unauthorized, "INVALID_AUTHENTICATION");
+
+                caller = new MdpIngestIdentity(credential.TenantId, credential.UserId, Sha256(Encoding.UTF8.GetBytes(accessKey)));
+            }
+            else if (certificate is not null)
+            {
+                caller = external.ResolveCertificate(certificate);
+            }
+            else
+            {
+                caller = await external.ResolveBearerAsync(Request.Headers.Authorization, query, Context.RequestAborted);
+            }
+
+            // 报文读取和证书/令牌验证可能耗时,准入前再核对时效。
+            if (caller is null || !IsWithinClockSkew(unixSeconds))
                 return Fail(StatusCodes.Status401Unauthorized, "INVALID_AUTHENTICATION");
 
-            var accessKeyHash = Sha256(Encoding.UTF8.GetBytes(accessKey));
-            var admission = await store.AdmitAsync(credential.TenantId, accessKeyHash, datasetKey,
+            var admission = await store.AdmitAsync(caller.TenantId, caller.AccessKeyHash, datasetKey,
                 Sha256(Encoding.UTF8.GetBytes(nonce)), Context.RequestAborted);
             if (admission.Status == MdpIngestAdmissionStatus.Replayed)
                 return Fail(StatusCodes.Status401Unauthorized, "NONCE_REPLAYED");
             if (admission.Status == MdpIngestAdmissionStatus.Limited)
                 return Fail(StatusCodes.Status429TooManyRequests, "SOURCE_RATE_LIMITED", admission.RetryAfterSeconds);
+            if (admission.Status == MdpIngestAdmissionStatus.TenantLimited)
+                return Fail(StatusCodes.Status429TooManyRequests, "TENANT_RATE_LIMITED", admission.RetryAfterSeconds);
             if (admission.Grant is not { } grant)
                 return Fail(StatusCodes.Status403Forbidden, "DATASET_UNAVAILABLE");
 
-            if (!MdpBatchFactory.TryRead(payload, credential.TenantId, grant.FactoryId, grant.UseBatchFactory, out var targetFactory))
+            long targetFactory;
+            var validFactory = query || format == IngestPayloadFormat.Ndjson
+                ? MdpBatchFactory.TryResolve(grant.FactoryId, grant.UseBatchFactory, factoryId, out targetFactory)
+                : MdpBatchFactory.TryRead(payload, caller.TenantId, grant.FactoryId, grant.UseBatchFactory, out targetFactory);
+            if (!validFactory)
                 return Fail(StatusCodes.Status400BadRequest, "INVALID_BATCH_SCOPE");
 
-            Context.Items[typeof(MdpIngestSubmission)] = new MdpIngestSubmission(grant.Id, credential.TenantId,
-                targetFactory, grant.SourceId, datasetKey, idempotencyKey, payload, accessKeyHash,
-                grant.UseBatchFactory ? grant.FactoryId : null);
+            Context.Items[typeof(MdpIngestSubmission)] = new MdpIngestSubmission(grant.Id, caller.TenantId,
+                targetFactory, grant.SourceId, datasetKey, idempotencyKey, payload, caller.AccessKeyHash,
+                grant.UseBatchFactory ? grant.FactoryId : null, format, schemaVersion);
             var identity = new ClaimsIdentity(
             [
-                new Claim(ClaimConst.TenantId, credential.TenantId.ToString(CultureInfo.InvariantCulture)),
-                new Claim(ClaimConst.UserId, credential.UserId.ToString(CultureInfo.InvariantCulture))
+                new Claim(ClaimConst.TenantId, caller.TenantId.ToString(CultureInfo.InvariantCulture)),
+                new Claim(ClaimConst.UserId, caller.UserId.ToString(CultureInfo.InvariantCulture))
             ], Scheme.Name);
             return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), Scheme.Name));
         }

+ 94 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestBatchStatusService.cs

@@ -0,0 +1,94 @@
+using System.Globalization;
+
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
+
+public sealed class MdpIngestBatchStatusService(ISqlSugarClient db) : ITransient
+{
+    public Task<MdpIngestBatchStatus?> FindAsync(MdpIngestSubmission caller, Guid batchId, CancellationToken cancellationToken) =>
+        FindAsync(new BatchReadScope(batchId.ToString("D"), caller.TenantId, caller.FactoryId,
+            caller.ConfigurationFactoryId ?? caller.FactoryId, caller.SourceId, caller.DatasetKey,
+            caller.GrantId, caller.AccessKeyHash, caller.ConfigurationFactoryId.HasValue, null, null), cancellationToken);
+
+    internal Task<MdpIngestBatchStatus?> FindForOperatorAsync(long tenantId, long configurationFactory, long datasetId,
+        IReadOnlyCollection<long> authorizedFactories, Guid batchId, CancellationToken cancellationToken) =>
+        FindAsync(new BatchReadScope(batchId.ToString("D"), tenantId, null, configurationFactory, null, null, null, null, false,
+            datasetId, string.Join(',', authorizedFactories.Select(factory => factory.ToString(CultureInfo.InvariantCulture)))),
+            cancellationToken);
+
+    private async Task<MdpIngestBatchStatus?> FindAsync(BatchReadScope scope, CancellationToken cancellationToken)
+    {
+        cancellationToken.ThrowIfCancellationRequested();
+        using var connection = MdpIngestDatabase.Open(db);
+        var row = await connection.Ado.SqlQuerySingleAsync<BatchStatusRow>("""
+            SELECT b.accepted_record_count AS AcceptedCount, b.source_schema_version AS SchemaVersion,
+                b.received_at AS ReceivedAt, t.status AS WorkerStatus,
+                t.last_error_code AS ErrorCode,
+                GREATEST(COALESCE(t.updated_at_utc, b.received_at), COALESCE(e.acknowledged_at, b.received_at)) AS UpdatedAt,
+                dispatch.status AS DispatchStatus,
+                (SELECT COUNT(DISTINCT q.raw_event_id) FROM mdp_ingest_worker_quarantine q
+                 WHERE q.batch_id=b.batch_id AND q.tenant_id=b.tenant_id AND q.factory_id=b.factory_id
+                   AND q.source_id=b.source_id AND q.dataset_id=b.dataset_id) AS IsolatedCount,
+                e.accepted_count AS ReceiverAcceptedCount
+            FROM mdp_ingest_raw_batch b
+            JOIN mdp_ingest_dataset d ON d.id=b.dataset_id AND d.tenant_id=b.tenant_id AND d.factory_id=@ConfigurationFactory
+
+            JOIN mdp_purchase_active_factory f ON f.tenant_id=b.tenant_id AND f.factory_id=b.factory_id
+            LEFT JOIN mdp_ingest_receive_task t ON t.batch_id=b.batch_id AND t.tenant_id=b.tenant_id
+                AND t.factory_id=b.factory_id AND t.source_id=b.source_id AND t.dataset_id=b.dataset_id
+            LEFT JOIN mdp_ingest_release_batch e ON e.batch_id=b.batch_id AND e.tenant_id=b.tenant_id
+                AND e.factory_id=b.factory_id AND e.source_id=b.source_id AND e.dataset_id=b.dataset_id
+            LEFT JOIN mdp_ingest_purchase_dispatch dispatch ON dispatch.batch_id=b.batch_id AND dispatch.tenant_id=b.tenant_id
+                AND dispatch.factory_id=b.factory_id AND dispatch.source_id=b.source_id AND dispatch.dataset_id=b.dataset_id
+            WHERE b.batch_id=@BatchId AND b.tenant_id=@TenantId
+                AND ((b.dataset_id=@OperatorDatasetId AND FIND_IN_SET(CAST(b.factory_id AS CHAR), @AuthorizedFactories) > 0)
+                    OR (@OperatorDatasetId IS NULL AND b.accepted_record_count>0 AND b.factory_id=@FactoryId AND b.source_id=@SourceId AND d.dataset_key=@DatasetKey
+                        AND EXISTS (SELECT 1 FROM mdp_ingest_access_grant g
+                            WHERE g.id=@GrantId AND g.tenant_id=b.tenant_id AND g.factory_id=d.factory_id
+                                AND g.source_id=b.source_id AND g.dataset_key=d.dataset_key AND g.enabled=1
+                                AND g.use_batch_factory=@FromBatch AND g.access_key_hash=@AccessKeyHash)))
+            """, new
+        {
+            scope.BatchId, scope.TenantId, scope.FactoryId, scope.ConfigurationFactory, scope.SourceId,
+            scope.DatasetKey, scope.GrantId, scope.AccessKeyHash, scope.FromBatch, scope.OperatorDatasetId, scope.AuthorizedFactories
+        });
+        cancellationToken.ThrowIfCancellationRequested();
+        if (row is null)
+            return null;
+
+        var receiverAccepted = row.ReceiverAcceptedCount;
+        if (receiverAccepted is null && row.DispatchStatus == "DONE")
+            receiverAccepted = row.AcceptedCount - row.IsolatedCount;
+
+        return new MdpIngestBatchStatus(Guid.Parse(scope.BatchId), "accepted", row.SchemaVersion, row.AcceptedCount,
+            row.WorkerStatus, row.IsolatedCount, receiverAccepted,
+            receiverAccepted.HasValue ? "confirmed" : row.DispatchStatus switch
+            {
+                "FAILED" => "failed",
+                "READY" => "awaiting_delivery",
+                _ => "pending"
+            },
+            Utc(row.ReceivedAt), Utc(row.UpdatedAt), row.ErrorCode);
+    }
+
+    private static DateTimeOffset Utc(DateTime value) => new(DateTime.SpecifyKind(value, DateTimeKind.Utc));
+
+    private sealed record BatchReadScope(string BatchId, long TenantId, long? FactoryId, long ConfigurationFactory,
+        long? SourceId, string? DatasetKey, long? GrantId, string? AccessKeyHash, bool FromBatch, long? OperatorDatasetId, string? AuthorizedFactories);
+
+    private sealed class BatchStatusRow
+    {
+        public int AcceptedCount { get; set; }
+        public string SchemaVersion { get; set; } = "";
+        public DateTime ReceivedAt { get; set; }
+        public string? WorkerStatus { get; set; }
+        public string? ErrorCode { get; set; }
+        public DateTime UpdatedAt { get; set; }
+        public string? DispatchStatus { get; set; }
+        public int? ReceiverAcceptedCount { get; set; }
+        public int IsolatedCount { get; set; }
+    }
+}
+
+public sealed record MdpIngestBatchStatus(Guid BatchId, string ReceiveStatus, string SchemaVersion, int AcceptedRecordCount,
+    string? WorkerStatus, int IsolatedRecordCount, int? ReceiverAcceptedRecordCount, string HandoffStatus,
+    DateTimeOffset ReceivedAt, DateTimeOffset UpdatedAt, string? ErrorCode);

+ 14 - 2
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestContractBinder.cs

@@ -8,13 +8,23 @@ public sealed class MdpIngestContractBinder(MdpIngestDatasetRegistry datasets) :
     private static readonly PurchaseOrderSchemaRegistry BuiltIn = new();
 
     public async Task<PreparedIngestBatch> PrepareAsync(
-        long tenantId, long factoryId, long sourceId, string datasetKey, ReadOnlyMemory<byte> payload, IngestLimits limits, long? configurationFactoryId = null)
+        long tenantId, long factoryId, long sourceId, string datasetKey, ReadOnlyMemory<byte> payload, IngestLimits limits, long? configurationFactoryId = null,
+        IngestPayloadFormat format = IngestPayloadFormat.Json, string? schemaVersion = null)
     {
         var binding = await datasets.ResolveActiveBindingAsync(tenantId, configurationFactoryId ?? factoryId, sourceId, datasetKey)
             ?? throw new IngestContractException(IngestContractError.DatasetUnavailable);
 
+        if (schemaVersion is not null && !string.Equals(schemaVersion, binding.SourceSchemaVersion, StringComparison.Ordinal))
+            throw new IngestContractException(IngestContractError.UnknownSchema);
+
         var identity = new IngestDatasetIdentity(binding.TenantId, factoryId, binding.SourceId,
             binding.DatasetId, binding.SourceCode, binding.DatasetKey);
+        var contract = await ReadContractAsync(binding);
+        return new IngestBatchPreparer(contract.Registry).Prepare(identity, binding.SourceSchemaVersion, payload.Span, limits, format: format);
+    }
+
+    internal async Task<(ISchemaRegistry Registry, IngestContract Contract)> ReadContractAsync(MdpIngestActiveBinding binding)
+    {
         ISchemaRegistry registry = BuiltIn;
         if (BuiltIn.Find(binding.DatasetKey, binding.SourceSchemaVersion) == null)
         {
@@ -22,6 +32,8 @@ public sealed class MdpIngestContractBinder(MdpIngestDatasetRegistry datasets) :
                 ?? throw new IngestContractException(IngestContractError.UnknownSchema);
             registry = new PurchaseVersionConfiguration(binding.DatasetKey, binding.SourceSchemaVersion, json);
         }
-        return new IngestBatchPreparer(registry).Prepare(identity, binding.SourceSchemaVersion, payload.Span, limits);
+        var contract = registry.Find(binding.DatasetKey, binding.SourceSchemaVersion)
+            ?? throw new IngestContractException(IngestContractError.UnknownSchema);
+        return (registry, contract);
     }
 }

+ 25 - 2
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestController.cs

@@ -10,7 +10,7 @@ namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
 [Route("api/v1/ingest")]
 [NonUnify]
 [Authorize(AuthenticationSchemes = MdpIngestProtocol.AuthenticationScheme)]
-public sealed class MdpIngestController(MdpIngestReceiveService receiver) : ControllerBase
+public sealed class MdpIngestController(MdpIngestReceiveService receiver, MdpIngestBatchStatusService batches) : ControllerBase
 {
     private static readonly JsonSerializerOptions ResponseJson = new(JsonSerializerDefaults.Web);
 
@@ -26,7 +26,7 @@ public sealed class MdpIngestController(MdpIngestReceiveService receiver) : Cont
 
         try
         {
-            var receipt = await receiver.ReceiveAsync(submission, cancellationToken);
+            var receipt = await receiver.ReceiveAsync(submission with { TrackPurchaseApiTime = true }, cancellationToken);
             return IngestJson(StatusCodes.Status202Accepted, receipt);
         }
         catch (MdpIngestHttpException error)
@@ -49,6 +49,29 @@ public sealed class MdpIngestController(MdpIngestReceiveService receiver) : Cont
         }
     }
 
+    [HttpGet("{datasetKey}/batches/{batchId:guid}")]
+    [ProducesResponseType(typeof(MdpIngestBatchStatus), StatusCodes.Status200OK)]
+    public async Task<IActionResult> ReadBatch([FromRoute] string datasetKey, [FromRoute] Guid batchId, CancellationToken cancellationToken)
+    {
+        if (HttpContext.Items[typeof(MdpIngestSubmission)] is not MdpIngestSubmission caller)
+            return Error(StatusCodes.Status401Unauthorized, "AUTHENTICATION_REQUIRED");
+        if (!string.Equals(caller.DatasetKey, datasetKey, StringComparison.Ordinal))
+            return Error(StatusCodes.Status404NotFound, "BATCH_NOT_FOUND");
+        Response.Headers.CacheControl = "no-store";
+
+        try
+        {
+            var status = await batches.FindAsync(caller, batchId, cancellationToken);
+            return status is null
+                ? Error(StatusCodes.Status404NotFound, "BATCH_NOT_FOUND")
+                : IngestJson(StatusCodes.Status200OK, status);
+        }
+        catch (Exception error) when (error is System.Data.Common.DbException or SqlSugarException)
+        {
+            return Error(StatusCodes.Status503ServiceUnavailable, "BATCH_STATUS_UNAVAILABLE");
+        }
+    }
+
     private ContentResult Error(int status, string code) =>
         IngestJson(status, new { code, traceId = HttpContext.TraceIdentifier });
 

+ 177 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestDatasetController.ApiContract.cs

@@ -0,0 +1,177 @@
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
+
+public sealed partial class MdpIngestDatasetController
+{
+    [HttpGet("{id:long}/api-contract")]
+    [DisplayName("下载数据集 API 推送契约")]
+    public Task<IActionResult> ReadApiContract(long id, [FromQuery] long? factoryId, [FromServices] MdpIngestContractBinder binder,
+        [FromQuery] bool kit = false) =>
+        WithScope(factoryId, async scope =>
+        {
+            var dataset = await Datasets(scope).FirstAsync(row => row.Id == id);
+            if (dataset?.ActiveSchemaVersion is not { Length: > 0 } version)
+                return NotFound(new { message = "当前工厂的数据集没有启用过 Schema" });
+
+            var binding = new MdpIngestActiveBinding
+            {
+                DatasetId = dataset.Id, DatasetKey = dataset.DatasetKey, TenantId = dataset.TenantId,
+                FactoryId = dataset.FactoryId, SourceSchemaVersion = version
+            };
+            IngestContract contract;
+            try
+            {
+                (_, contract) = await binder.ReadContractAsync(binding);
+            }
+            catch (IngestContractException)
+            {
+                return NotFound(new { message = "未找到该版本的受控契约" });
+            }
+
+            var names = contract.FieldMapJson is null ? new Dictionary<string, string>()
+                : JsonSerializer.Deserialize<Dictionary<string, string>>(contract.FieldMapJson)!;
+            string Map(string name) => names.GetValueOrDefault(name, name);
+            var rowSchema = new Dictionary<string, object>
+            {
+                ["$schema"] = "https://json-schema.org/draft/2020-12/schema",
+                ["type"] = "object",
+                ["required"] = new[] { Map("PoNo"), Map("PoLine"), Map("ItemCode"), Map("OrderQty"), Map("sourceUpdatedAt") },
+                ["properties"] = new Dictionary<string, object>
+                {
+                    [Map("PoNo")] = new { type = "string", minLength = 1, maxLength = 100, pattern = "^[^#]*[^#\\s][^#]*$" },
+                    [Map("PoLine")] = new { type = "string", minLength = 1, maxLength = 50, pattern = "^[^#]*[^#\\s][^#]*$" },
+                    [Map("ItemCode")] = new { type = "string", minLength = 1, maxLength = 100, pattern = "\\S" },
+                    [Map("OrderQty")] = new { type = "number", exclusiveMinimum = 0, exclusiveMaximum = 1_000_000_000_000m, multipleOf = 0.000001m },
+                    [Map("sourceUpdatedAt")] = new { type = "string", format = "date-time" },
+                    [Map("SupplierCode")] = OptionalText(100),
+                    [Map("Status")] = OptionalText(50),
+                    [Map("OrderDate")] = OptionalDate(),
+                    [Map("DueDate")] = OptionalDate()
+                }
+            };
+            var sample = new Dictionary<string, object>
+            {
+                [Map("PoNo")] = kit ? $"SANDBOX-{Guid.NewGuid():N}" : "SANDBOX-PO-001",
+                [Map("PoLine")] = "01", [Map("ItemCode")] = "SANDBOX-SKU",
+                [Map("OrderQty")] = 15.5m,
+                [Map("sourceUpdatedAt")] = kit ? DateTimeOffset.UtcNow.ToString("O") : "2026-01-01T00:00:00Z"
+            };
+            var endpoint = $"/api/v1/ingest/{dataset.DatasetKey}";
+            Response.Headers.CacheControl = "no-store";
+            var document = new
+            {
+                dataset.DatasetKey, schemaVersion = version, schemaSha256 = contract.SourceSchema.Stamp.Sha256,
+                schemaJson = contract.SourceSchema.Json, rowSchema, endpoint,
+                samples = new
+                {
+                    json = JsonSerializer.Serialize(new { factoryId = scope.FactoryId.ToString(), data = new { list = new[] { sample } } }),
+                    ndjson = JsonSerializer.Serialize(sample) + "\n",
+                    ndjsonFactoryHeader = scope.FactoryId.ToString()
+                },
+                batchStatusEndpoint = endpoint + "/batches/{batchId}",
+                formats = new[] { "application/json", "application/x-ndjson" },
+                limits = MdpIngestProtocol.Limits,
+                retry = new { idempotencyDays = 7, nonceMinutes = 15, clockSkewSeconds = 300 },
+                signatureVector = SignatureVector(endpoint, version),
+                errorCodes = new[] { "INVALID_AUTHENTICATION", "NONCE_REPLAYED", "DATASET_UNAVAILABLE", "INVALID_BATCH_SCOPE",
+                    "CONTENT_DIGEST_MISMATCH", "INVALID_JSON", "INVALID_ENVELOPE", "UNKNOWN_SCHEMA", "BODY_TOO_LARGE",
+                    "TOO_MANY_RECORDS", "JSON_TOO_DEEP", "UNSUPPORTED_MEDIA_TYPE", "SOURCE_RATE_LIMITED",
+                    "TENANT_RATE_LIMITED", "IDEMPOTENCY_CONFLICT", "IDEMPOTENCY_EXPIRED", "BATCH_NOT_FOUND" }
+            };
+            if (!kit)
+                return Ok(document);
+            var config = HttpContext.RequestServices.GetRequiredService<IConfiguration>();
+            var origin = config[$"MdpUnifiedIngress:PushKits:{dataset.TenantId}:{dataset.FactoryId}:{dataset.Id}:SandboxBaseUrl"];
+            var bytes = MdpPushKit.Build(JsonSerializer.SerializeToElement(document, MdpPushKit.JsonOptions),
+                scope.FactoryId.ToString(System.Globalization.CultureInfo.InvariantCulture), origin);
+            return File(bytes, "application/zip", MdpPushKit.FileName(dataset.DatasetKey, version));
+        });
+
+    [HttpPost("{id:long}/api-contract/validate")]
+    [RequestSizeLimit(8 * 1024 * 1024)]
+    [DisplayName("校验数据集 API 推送样本")]
+    public Task<IActionResult> ValidatePushSample(long id, [FromQuery] long? factoryId, [FromBody] MdpValidatePushSample input,
+        [FromServices] MdpIngestContractBinder binder) =>
+        WithScope(factoryId, async scope =>
+        {
+            var dataset = await Datasets(scope).FirstAsync(row => row.Id == id);
+            if (dataset?.ActiveSchemaVersion is not { Length: > 0 } version)
+                return NotFound(new { message = "当前工厂的数据集没有启用过 Schema" });
+
+            var format = input.MediaType switch
+            {
+                "application/json" => IngestPayloadFormat.Json,
+                "application/x-ndjson" => IngestPayloadFormat.Ndjson,
+                _ => (IngestPayloadFormat?)null
+            };
+            if (format is null)
+                return StatusCode(StatusCodes.Status415UnsupportedMediaType, new { code = "UNSUPPORTED_MEDIA_TYPE" });
+            if (input.Sample is null || Encoding.UTF8.GetByteCount(input.Sample) > MdpIngestProtocol.Limits.MaxBodyBytes)
+                return BadRequest(new { code = "SAMPLE_REQUIRED_OR_TOO_LARGE" });
+
+            var binding = new MdpIngestActiveBinding
+            {
+                DatasetId = dataset.Id, DatasetKey = dataset.DatasetKey, TenantId = dataset.TenantId,
+                FactoryId = dataset.FactoryId, SourceSchemaVersion = version
+            };
+            var identity = new IngestDatasetIdentity(dataset.TenantId, dataset.FactoryId, 0, dataset.Id, "", dataset.DatasetKey);
+            var bytes = Encoding.UTF8.GetBytes(input.Sample);
+            try
+            {
+                var (registry, _) = await binder.ReadContractAsync(binding);
+                var batch = new IngestBatchPreparer(registry).Prepare(identity, version, bytes, MdpIngestProtocol.Limits, format: format.Value);
+                if (format == IngestPayloadFormat.Json
+                        && !MdpBatchFactory.TryRead(bytes, dataset.TenantId, dataset.FactoryId, false, out _)
+                    || !MdpBatchFactory.RowsMatch(batch))
+                    return UnprocessableEntity(new { code = "INVALID_BATCH_SCOPE" });
+
+                var processed = PurchaseBatchProcessor.Process(batch, "");
+                var positions = batch.Events.ToDictionary(row => row.RawEventId, row => row.SourcePosition);
+                Response.Headers.CacheControl = "no-store";
+                return Ok(new
+                {
+                    schemaVersion = version, received = batch.Batch.AcceptedRowCount, valid = processed.Package.Items.Count,
+                    isolated = processed.Quarantines.Select(row => row.RawEventId).Distinct().Count(),
+                    issues = processed.Quarantines.Select(row => new { position = positions[row.RawEventId], row.Field, row.Reason }),
+                    traceId = HttpContext.TraceIdentifier
+                });
+            }
+            catch (IngestContractException error)
+            {
+                return UnprocessableEntity(new { code = error.Code.ToString(), traceId = HttpContext.TraceIdentifier });
+            }
+        });
+
+    private static object OptionalText(int maxLength) => new { type = new[] { "string", "null" }, maxLength };
+    private static object OptionalDate() =>
+        new { type = new[] { "string", "null" }, pattern = @"^[1-9][0-9]{3}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}$" };
+
+    private static object SignatureVector(string endpoint, string version)
+    {
+        const string accessKey = "documentation-example";
+        const string timestamp = "1700000000";
+        const string nonce = "example-nonce";
+        const string idempotencyKey = "example-idempotency";
+        const string mediaType = "application/x-ndjson";
+        const string payload = "{}\n";
+        var key = Enumerable.Range(0, 32).Select(value => (byte)value).ToArray();
+        var digest = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(payload))).ToLowerInvariant();
+        var canonical = MdpIngestProtocol.CanonicalSignature("POST", endpoint, accessKey, timestamp, nonce,
+            digest, idempotencyKey, true, mediaType, null, version);
+        var signature = Convert.ToBase64String(HMACSHA256.HashData(key, Encoding.UTF8.GetBytes(canonical)));
+        return new
+        {
+            method = "POST", path = endpoint, accessKey, timestamp, nonce, idempotencyKey, mediaType, schemaVersion = version,
+            payload, payloadSha256 = digest, exampleKeyBase64 = Convert.ToBase64String(key), canonical, signatureBase64 = signature
+        };
+    }
+}
+
+public sealed record MdpValidatePushSample(string? MediaType, string? Sample);

+ 15 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestDatasetController.cs

@@ -1,6 +1,7 @@
 using Admin.NET.Core.Service;
 using Admin.NET.Plugin.AiDOP.Entity.DataPlatform;
 using MySqlConnector;
+using System.Text.Json;
 using System.Text.Json.Serialization;
 
 namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
@@ -56,6 +57,20 @@ public sealed partial class MdpIngestDatasetController(ISqlSugarClient db, UserM
         });
     });
 
+    [HttpGet("{id:long}/batches/{batchId:guid}")]
+    [DisplayName("查询数据集接收批次")]
+    public Task<IActionResult> ReadBatchStatus(long id, Guid batchId, [FromQuery] long? factoryId,
+        [FromServices] MdpIngestBatchStatusService batches, CancellationToken cancellationToken) =>
+        WithScope(factoryId, async scope =>
+        {
+            var factories = await AuthorizedFactories(scope.TenantId);
+            var status = await batches.FindForOperatorAsync(scope.TenantId, scope.FactoryId, id,
+                factories.Select(factory => factory.Id).ToArray(), batchId, cancellationToken);
+            Response.Headers.CacheControl = "no-store";
+            return status is null ? NotFound(new { message = "批次不存在或不可访问" })
+                : Content(JsonSerializer.Serialize(status, new JsonSerializerOptions(JsonSerializerDefaults.Web)), "application/json; charset=utf-8");
+        });
+
     [HttpPost]
     [DisplayName("创建接收数据集")]
     public Task<IActionResult> Create([FromBody] MdpCreateDatasetInput input, [FromQuery] long? factoryId) =>

+ 141 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestExternalIdentities.cs

@@ -0,0 +1,141 @@
+using System.Collections.Concurrent;
+using System.Security.Cryptography;
+using System.Security.Cryptography.X509Certificates;
+using System.Text;
+using System.Text.RegularExpressions;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.Primitives;
+using Microsoft.IdentityModel.JsonWebTokens;
+using Microsoft.IdentityModel.Protocols;
+using Microsoft.IdentityModel.Protocols.OpenIdConnect;
+using Microsoft.IdentityModel.Tokens;
+
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
+
+public sealed class MdpIngestExternalIdentities(IConfiguration configuration, IHttpClientFactory clients)
+{
+    internal const string MetadataClient = "MdpIngestOAuthMetadata";
+    private const string Section = "MdpUnifiedIngress:ExternalIdentity";
+    private const string ClientAuthenticationOid = "1.3.6.1.5.5.7.3.2";
+    private static readonly Regex ReferencePattern = new(@"\A[a-zA-Z0-9._-]{1,100}\z");
+    private readonly ConcurrentDictionary<string, ConfigurationManager<OpenIdConnectConfiguration>> _metadata = new();
+    private readonly JsonWebTokenHandler _tokenHandler = new() { MaximumTokenSizeInBytes = 8192 };
+
+    internal async Task<MdpIngestIdentity?> ResolveBearerAsync(StringValues authorization, bool query, CancellationToken cancellationToken)
+    {
+        if (authorization.Count != 1 || authorization[0] is not { Length: > 7 and <= 8199 } header
+            || !header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
+            return null;
+
+        var settings = configuration.GetSection($"{Section}:OAuth2").Get<MdpIngestOAuthSettings>();
+        if (settings is null || !IsHttps(settings.MetadataAddress) || !IsHttps(settings.Issuer)
+            || string.IsNullOrWhiteSpace(settings.Audience) || string.IsNullOrWhiteSpace(settings.AppOnlyClaim)
+            || string.IsNullOrWhiteSpace(settings.AppOnlyValue)
+            || string.IsNullOrWhiteSpace(query ? settings.ReadScope : settings.WriteScope))
+            return null;
+
+        var token = header[7..];
+        if (!_tokenHandler.CanReadToken(token))
+            return null;
+
+        var manager = _metadata.GetOrAdd(settings.MetadataAddress!, address =>
+            new ConfigurationManager<OpenIdConnectConfiguration>(address, new OpenIdConnectConfigurationRetriever(),
+                new HttpDocumentRetriever(clients.CreateClient(MetadataClient)) { RequireHttps = true }));
+        var metadata = await manager.GetConfigurationAsync(cancellationToken);
+        if (metadata.Issuer != settings.Issuer)
+            return null;
+
+        var parameters = new TokenValidationParameters
+        {
+            ValidIssuer = settings.Issuer,
+            ValidAudience = settings.Audience,
+            IssuerSigningKeys = metadata.SigningKeys,
+            ValidateIssuer = true,
+            ValidateAudience = true,
+            ValidateLifetime = true,
+            ValidateIssuerSigningKey = true,
+            RequireSignedTokens = true,
+            RequireExpirationTime = true,
+            IgnoreTrailingSlashWhenValidatingAudience = false,
+            ClockSkew = TimeSpan.FromSeconds(30),
+            ValidAlgorithms = [SecurityAlgorithms.RsaSha256, SecurityAlgorithms.EcdsaSha256, SecurityAlgorithms.RsaSsaPssSha256]
+        };
+        var verified = await _tokenHandler.ValidateTokenAsync(token, parameters);
+        if (!verified.IsValid)
+        {
+            if (verified.Exception is SecurityTokenSignatureKeyNotFoundException)
+                manager.RequestRefresh();
+            return null;
+        }
+
+        var claims = verified.ClaimsIdentity.Claims.ToArray();
+        if (!string.Equals(SingleClaim(settings.AppOnlyClaim), settings.AppOnlyValue, StringComparison.Ordinal))
+            return null;
+        var scope = query ? settings.ReadScope : settings.WriteScope;
+        if (!(SingleClaim("scope") ?? "").Split(' ', StringSplitOptions.RemoveEmptyEntries).Contains(scope, StringComparer.Ordinal))
+            return null;
+
+        var clientId = SingleClaim("client_id");
+        return clientId is null ? null : Match(settings.Clients, clientId, "oauth2");
+
+        string? SingleClaim(string name)
+        {
+            var matching = claims.Where(claim => claim.Type == name).Take(2).ToArray();
+            return matching.Length == 1 ? matching[0].Value : null;
+        }
+    }
+
+    internal MdpIngestIdentity? ResolveCertificate(X509Certificate2 certificate)
+    {
+        var thumbprint = certificate.GetCertHashString(HashAlgorithmName.SHA256);
+        var identities = configuration.GetSection($"{Section}:Mtls:Clients").Get<MdpIngestExternalClient[]>() ?? [];
+        var caller = Match(identities, thumbprint, "mtls");
+        if (caller is null || !certificate.Extensions.OfType<X509EnhancedKeyUsageExtension>().Any(
+                extension => extension.EnhancedKeyUsages.Cast<Oid>().Any(oid => oid.Value == ClientAuthenticationOid)))
+            return null;
+
+        using var chain = new X509Chain();
+        chain.ChainPolicy.ApplicationPolicy.Add(new Oid(ClientAuthenticationOid));
+        chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
+        chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
+        chain.ChainPolicy.UrlRetrievalTimeout = TimeSpan.FromSeconds(5);
+        return chain.Build(certificate) ? caller : null;
+    }
+
+    private static MdpIngestIdentity? Match(IReadOnlyCollection<MdpIngestExternalClient> identities, string name, string method)
+    {
+        var matches = identities.Where(client => client.Enabled && client.Identity == name).Take(2).ToArray();
+        if (matches.Length != 1 || matches[0] is not { TenantId: > 0, UserId: > 0, GrantReference: { } reference }
+            || !ReferencePattern.IsMatch(reference))
+            return null;
+
+        var key = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes($"mdp-external\0{method}\0{reference}"))).ToLowerInvariant();
+        return new MdpIngestIdentity(matches[0].TenantId, matches[0].UserId, key);
+    }
+
+    private static bool IsHttps(string? value) =>
+        Uri.TryCreate(value, UriKind.Absolute, out var url) && url.Scheme == Uri.UriSchemeHttps && url.UserInfo.Length == 0;
+}
+
+internal sealed record MdpIngestIdentity(long TenantId, long UserId, string AccessKeyHash);
+
+internal sealed class MdpIngestOAuthSettings
+{
+    public string? MetadataAddress { get; init; }
+    public string? Issuer { get; init; }
+    public string? Audience { get; init; }
+    public string? AppOnlyClaim { get; init; }
+    public string? AppOnlyValue { get; init; }
+    public string? ReadScope { get; init; }
+    public string? WriteScope { get; init; }
+    public MdpIngestExternalClient[] Clients { get; init; } = [];
+}
+
+internal sealed class MdpIngestExternalClient
+{
+    public bool Enabled { get; init; }
+    public string? Identity { get; init; }
+    public string? GrantReference { get; init; }
+    public long TenantId { get; init; }
+    public long UserId { get; init; }
+}

+ 17 - 1
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestProtocol.cs

@@ -6,7 +6,18 @@ public static class MdpIngestProtocol
 {
     public const string AuthenticationScheme = "MdpUnifiedIngress";
     public const string SignatureVersion = "mdp-ingress-hmac-sha256-v1";
+    public const string SignatureVersionV2 = "mdp-ingress-hmac-sha256-v2";
+    public const string SignatureVersionHeader = "X-Signature-Version";
+    public const string SchemaHeader = "X-Schema-Version";
+    public const string FactoryHeader = "X-Factory-Id";
     public static readonly IngestLimits Limits = new(1024 * 1024, 100, 16);
+
+    public static string CanonicalSignature(string method, string path, string accessKey, string timestamp,
+        string nonce, string digest, string idempotencyKey, bool v2, string mediaType, string? factoryId, string? schemaVersion)
+    {
+        var original = $"{method.ToUpperInvariant()}&{path}&{accessKey}&{timestamp}&{nonce}&{digest}&{idempotencyKey}";
+        return v2 ? $"{SignatureVersionV2}&{original}&{mediaType}&{factoryId}&{schemaVersion}" : original;
+    }
 }
 
 public sealed record MdpIngestSubmission(
@@ -18,7 +29,12 @@ public sealed record MdpIngestSubmission(
     string IdempotencyKey,
     byte[] Payload,
     string AccessKeyHash,
-    long? ConfigurationFactoryId = null);
+    long? ConfigurationFactoryId = null,
+    IngestPayloadFormat Format = IngestPayloadFormat.Json,
+    string? SchemaVersion = null)
+{
+    internal bool TrackPurchaseApiTime { get; init; }
+}
 
 public sealed record MdpIngestReceipt(
     Guid BatchId,

+ 27 - 6
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestReceiveService.cs

@@ -90,7 +90,9 @@ public sealed class MdpIngestReceiveService(ISqlSugarClient db, ILogger<MdpInges
         var previous = await db.Ado.SqlQuerySingleAsync<StoredReceipt>(
             """
             SELECT batch_id AS BatchId, payload_sha256 AS PayloadSha256, accepted_record_count AS AcceptedRecordCount,
-                source_schema_version AS SchemaVersion, received_at AS ReceivedAt
+                source_schema_version AS SchemaVersion, received_at AS ReceivedAt,
+                (SELECT e.source_position FROM mdp_ingest_raw_event e
+                 WHERE e.batch_id = mdp_ingest_raw_batch.batch_id AND e.record_ordinal = 0) AS FirstPosition
             FROM mdp_ingest_raw_batch
             WHERE tenant_id = @TenantId AND factory_id = @FactoryId AND source_id = @SourceId
                 AND dataset_id = @DatasetId AND idempotency_key = @IdempotencyKey
@@ -104,6 +106,10 @@ public sealed class MdpIngestReceiveService(ISqlSugarClient db, ILogger<MdpInges
                 throw new IngestContractException(IngestContractError.DatasetUnavailable);
 
             cancellationToken.ThrowIfCancellationRequested();
+            var previousIsNdjson = previous.FirstPosition?.StartsWith("/lines/", StringComparison.Ordinal) == true;
+            if ((submission.Format == IngestPayloadFormat.Ndjson) != previousIsNdjson
+                || submission.SchemaVersion is not null && submission.SchemaVersion != previous.SchemaVersion)
+                throw new MdpIngestHttpException(StatusCodes.Status409Conflict, "IDEMPOTENCY_CONFLICT");
             return Replay(previous, submission.Payload);
         }
 
@@ -128,7 +134,9 @@ public sealed class MdpIngestReceiveService(ISqlSugarClient db, ILogger<MdpInges
 
         var binder = new MdpIngestContractBinder(registry);
         var prepared = await binder.PrepareAsync(scope.TenantId, scope.FactoryId, scope.SourceId, datasetKey,
-            submission.Payload, MdpIngestProtocol.Limits, configurationFactory);
+            submission.Payload, MdpIngestProtocol.Limits, configurationFactory, submission.Format, submission.SchemaVersion);
+        if (submission.Format == IngestPayloadFormat.Ndjson && !MdpBatchFactory.RowsMatch(prepared))
+            throw new MdpIngestHttpException(StatusCodes.Status400BadRequest, "INVALID_BATCH_SCOPE");
         var batch = prepared.Batch;
         if (submission.IdempotencyKey.StartsWith("relational-sync-", StringComparison.Ordinal))
         {
@@ -151,6 +159,18 @@ public sealed class MdpIngestReceiveService(ISqlSugarClient db, ILogger<MdpInges
                 SourceGeneration = generation,
             } };
         }
+        else if (submission.TrackPurchaseApiTime && prepared.Events[0].ObjectCode == "PURCHASE_ORDER")
+        {
+            batch = batch with { SourceWindow = new(null, null, IngestSourceWindow.PurchaseApiTime) };
+        }
+        return await PersistAcceptedBatchAsync(db, prepared with { Batch = batch }, idempotencyKey, configurationFactory, cancellationToken);
+    }
+
+    internal static async Task<MdpIngestReceipt> PersistAcceptedBatchAsync(ISqlSugarClient db, PreparedIngestBatch prepared,
+        byte[] idempotencyKey, long configurationFactory, CancellationToken cancellationToken)
+    {
+        var batch = prepared.Batch;
+        var scope = batch.Identity;
         var receivedAt = new DateTimeOffset(batch.ReceivedAt.UtcTicks / 10 * 10, TimeSpan.Zero);
         var batchId = batch.BatchId.ToString("D");
 
@@ -162,10 +182,10 @@ public sealed class MdpIngestReceiveService(ISqlSugarClient db, ILogger<MdpInges
             VALUES (@TenantId, @FactoryId, @SourceId, @DatasetId, @KeySha256, @ReceivedAt)
             """, new
             {
-                reservation.TenantId, reservation.FactoryId, reservation.SourceId, reservation.DatasetId,
-                reservation.KeySha256, ReceivedAt = receivedAt.UtcDateTime
+                scope.TenantId, scope.FactoryId, scope.SourceId, scope.DatasetId,
+                KeySha256 = Convert.ToHexString(SHA256.HashData(idempotencyKey)).ToLowerInvariant(), ReceivedAt = receivedAt.UtcDateTime
             });
-        await PersistRawAsync(db, batch, prepared.Events, submission.Payload, idempotencyKey, receivedAt, cancellationToken);
+        await PersistRawAsync(db, batch, prepared.Events, batch.Payload.ToArray(), idempotencyKey, receivedAt, cancellationToken);
 
         // 发布与接收都锁定同一数据集行;同版本重新发布后也能追溯本批当时的发布记录。
         await db.Ado.ExecuteCommandAsync("""
@@ -175,7 +195,7 @@ public sealed class MdpIngestReceiveService(ISqlSugarClient db, ILogger<MdpInges
             WHERE p.tenant_id=@TenantId AND p.factory_id=@ConfigurationFactory AND p.dataset_id=@DatasetId
                 AND p.source_id=@SourceId AND p.schema_version=@Version
             """, new { BatchId = batchId, scope.TenantId, ConfigurationFactory = configurationFactory,
-                DatasetId = datasetId.Value, scope.SourceId, Version = batch.Versions.SourceSchema.Version,
+                scope.DatasetId, scope.SourceId, Version = batch.Versions.SourceSchema.Version,
                 ActualFactory = scope.FactoryId });
 
         cancellationToken.ThrowIfCancellationRequested();
@@ -278,6 +298,7 @@ public sealed class MdpIngestReceiveService(ISqlSugarClient db, ILogger<MdpInges
 
     private sealed class StoredReceipt
     {
+        public string? FirstPosition { get; set; }
         public string BatchId { get; set; } = string.Empty;
         public string PayloadSha256 { get; set; } = string.Empty;
         public int AcceptedRecordCount { get; set; }

+ 4 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpIngestServiceCollectionExtensions.cs

@@ -8,7 +8,11 @@ public static class MdpIngestServiceCollectionExtensions
     public static IServiceCollection AddMdpUnifiedIngress(this IServiceCollection services)
     {
         services.AddTransient<MdpIngestReceiveService>();
+        services.AddTransient<MdpIngestBatchStatusService>();
         services.AddScoped<MdpIngestAdmissionStore>();
+        services.AddSingleton<MdpIngestExternalIdentities>();
+        services.AddHttpClient(MdpIngestExternalIdentities.MetadataClient, client => client.Timeout = TimeSpan.FromSeconds(8))
+            .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
         services.AddScoped<ISecretStore, MdpIngestSecretStore>();
         services.AddSingleton<IMdpIngestSecretProvider, EnvironmentMdpIngestSecretProvider>();
         services.AddAuthentication().AddScheme<AuthenticationSchemeOptions, MdpIngestAuthenticationHandler>(

+ 69 - 2
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpPurchaseHandoffService.Versioned.cs

@@ -1,3 +1,4 @@
+using System.Globalization;
 using System.Security.Cryptography;
 using System.Text.Json;
 using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
@@ -14,6 +15,9 @@ public sealed partial class MdpPurchaseHandoffService
             PurchaseHandoffPackage.RelationalChangeVersion => package.Items.Count > 0
                 && package.Items.All(line => line.SourceChange is { Generation: > 0, Version: > 0 })
                 && package.Items.Select(line => line.SourceChange!.Generation).Distinct().Count() == 1,
+            PurchaseHandoffPackage.ApiChangeVersion => package.Items.Count > 0
+                && package.Items.All(line => line.SourceChange is { Generation: 0, Version: > 0, Deleted: false } change
+                    && TrySourceTime(line.SourceUpdatedAt, out var instant) && change.Version == instant.UtcTicks),
             _ => false,
         };
 
@@ -33,13 +37,17 @@ public sealed partial class MdpPurchaseHandoffService
             """, scope);
         var fields = new StageFields(line.PoNo, line.PoLine, line.ItemCode, line.SupplierCode,
             line.OrderQty, line.DueDate, line.OrderDate, line.Status, line.SourceUpdatedAt);
-        var digest = VersionedDigest(fields, change.Deleted);
+        var isApi = package.PackageVersion == PurchaseHandoffPackage.ApiChangeVersion;
+        var digest = VersionedDigest(fields, change.Deleted, isApi);
         var switchingSource = state is not null && (state.SourceId != package.SourceId || state.DatasetId != package.DatasetId
             || !string.Equals(state.SourceSystem, package.SourceCode, StringComparison.Ordinal));
         if (switchingSource && (migration is null || state!.SourceSystem != migration.LegacySourceCode))
             return new("CONFLICT", null, null);
         if (state is not null && !switchingSource)
         {
+            // API time and relational log offsets describe distinct version spaces.
+            if (isApi != (state.Generation == 0))
+                return new("CONFLICT", null, null);
             if (change.Generation < state.Generation)
                 return new("STALE", state.StageId, state.StandardId);
             if (change.Generation == state.Generation && Compare(state, change, digest) is { } outcome)
@@ -100,6 +108,15 @@ public sealed partial class MdpPurchaseHandoffService
             if (stageId.HasValue && stageId != stage)
                 return new("CONFLICT", null, null);
             stageId = stage;
+            // Adopt already delivered unversioned API orders using the frozen history for this exact scope.
+            if (isApi && state is null && standard!.SourceSystem == package.SourceCode && stage is long priorStageId)
+            {
+                var prior = await ReadApiBaselineAsync(db, package, standardId.Value, priorStageId);
+                if (prior is null)
+                    return new("CONFLICT", null, null);
+                if (Compare(prior, change, digest) is { } outcome)
+                    return outcome;
+            }
             if (!change.Deleted)
             {
                 if (stage is null)
@@ -143,8 +160,24 @@ public sealed partial class MdpPurchaseHandoffService
         return result;
     }
 
-    private static string VersionedDigest(StageFields fields, bool deleted)
+    private static bool TrySourceTime(string? text, out DateTimeOffset instant)
     {
+        instant = default;
+        return text is { Length: >= 6 } && (text.EndsWith('Z') || text[^6] is '+' or '-')
+            && DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.None, out instant);
+    }
+
+    private static string VersionedDigest(StageFields fields, bool deleted, bool isApi)
+    {
+        if (isApi && TrySourceTime(fields.SourceUpdatedAt, out var time))
+        {
+            fields = fields with
+            {
+                SourceUpdatedAt = time.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture),
+                OrderQty = decimal.Parse(fields.OrderQty.ToString("G29", CultureInfo.InvariantCulture),
+                    NumberStyles.Float, CultureInfo.InvariantCulture)
+            };
+        }
         var content = deleted ? "DELETE"u8.ToArray() : JsonSerializer.SerializeToUtf8Bytes(fields, WireJson);
         return Convert.ToHexString(SHA256.HashData(content)).ToLowerInvariant();
     }
@@ -158,6 +191,40 @@ public sealed partial class MdpPurchaseHandoffService
             _ => new("CONFLICT", state.StageId, state.StandardId)
         };
 
+    private static async Task<PurchaseLineVersion?> ReadApiBaselineAsync(
+        ISqlSugarClient db, PurchaseHandoffPackage package, long standardId, long stageId)
+    {
+        var raw = await db.Ado.SqlQuerySingleAsync<string>("""
+            SELECT s.raw_data FROM mdp_stg_purchase_order s
+            JOIN mdp_std_purchase_order p ON p.id=@standardId AND p.sync_batch_id=s.sync_batch_id
+                AND p.tenant_id=s.tenant_id AND p.factory_id=s.factory_id AND p.source_system=s.source_system
+                AND p.source_biz_key=s.source_biz_key
+            JOIN mdp_ingest_handoff_receipt r ON r.batch_id=s.sync_batch_id AND r.tenant_id=s.tenant_id
+                AND r.factory_id=s.factory_id AND r.source_id=@SourceId AND r.dataset_id=@DatasetId
+                AND r.package_version=@Unversioned
+            WHERE s.id=@stageId AND s.tenant_id=@TenantId AND s.factory_id=@FactoryId
+              AND s.source_system=@SourceCode AND s.source_table='S3_PURCHASE_ORDER'
+            """, new { standardId, stageId, package.TenantId, package.FactoryId, package.SourceId, package.DatasetId,
+                package.SourceCode, Unversioned = PurchaseHandoffPackage.Version });
+        if (raw is null)
+            return null;
+        try
+        {
+            var fields = JsonSerializer.Deserialize<StageFields>(raw, WireJson);
+            return fields is not null && TrySourceTime(fields.SourceUpdatedAt, out var original) && original.UtcTicks > 0
+                ? new PurchaseLineVersion
+                {
+                    StandardId = standardId, StageId = stageId, Version = original.UtcTicks,
+                    Digest = VersionedDigest(fields, false, true)
+                }
+                : null;
+        }
+        catch (JsonException)
+        {
+            return null;
+        }
+    }
+
     private sealed class PurchaseLineVersion
     {
         public long SourceId { get; set; }

+ 146 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/MdpPushKit.cs

@@ -0,0 +1,146 @@
+using System.IO.Compression;
+using System.Text;
+using System.Text.Json;
+
+namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
+
+internal static class MdpPushKit
+{
+    internal static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web) { WriteIndented = true };
+    private static readonly UTF8Encoding Utf8 = new(false);
+    private static readonly string[] Clients = ["push.py", "push.mjs", "Push.cs", "Push.java"];
+
+    internal static byte[] Build(JsonElement contract, string factory, string? configuredOrigin)
+    {
+        var origin = HttpsOrigin(configuredOrigin);
+        var dataset = Text(contract, "datasetKey");
+        var version = Text(contract, "schemaVersion");
+        var endpoint = Text(contract, "endpoint");
+        var status = Text(contract, "batchStatusEndpoint");
+        var samples = contract.GetProperty("samples");
+        using var output = new MemoryStream();
+        using (var zip = new ZipArchive(output, ZipArchiveMode.Create, leaveOpen: true))
+        {
+            AddJson("api-contract.json", contract);
+            AddJson("row.schema.json", contract.GetProperty("rowSchema"));
+            Add("source.schema.json", Text(contract, "schemaJson"));
+            Add("sample.json", Text(samples, "json"));
+            Add("sample.ndjson", Text(samples, "ndjson"));
+            AddJson("signature-vector.json", contract.GetProperty("signatureVector"));
+            AddJson("openapi.json", OpenApi(dataset, version, endpoint, status, origin));
+            Add("client.env", $"INGRESS_BASE={origin}\nDATASET_ENDPOINT={endpoint}\nFACTORY_ID={factory}\nSCHEMA_VERSION={version}\n");
+            var assembly = typeof(MdpPushKit).Assembly;
+            foreach (var client in Clients)
+            {
+                using var input = assembly.GetManifestResourceStream("MdpPushKit." + client)
+                    ?? throw new InvalidOperationException("Missing API push kit client.");
+                using var entry = zip.CreateEntry(client).Open();
+                input.CopyTo(entry);
+            }
+            Add("README.md", Guide(dataset, version, factory, origin));
+
+            void AddJson(string file, object value) => Add(file, JsonSerializer.Serialize(value, JsonOptions));
+            void Add(string file, string contents)
+            {
+                using var writer = new StreamWriter(zip.CreateEntry(file).Open(), Utf8);
+                writer.Write(contents);
+            }
+        }
+        return output.ToArray();
+    }
+
+    internal static string FileName(string dataset, string version) => $"{Safe(dataset)}.{Safe(version)}.push-kit.zip";
+
+    private static string Safe(string value) => new(value.Select(character => char.IsAsciiLetterOrDigit(character)
+        || character is '.' or '_' or '-' ? character : '_').ToArray());
+
+    private static string Text(JsonElement value, string name) => value.GetProperty(name).GetString()!;
+
+    private static string? HttpsOrigin(string? configured) =>
+        Uri.TryCreate(configured, UriKind.Absolute, out var uri) && uri.Scheme == Uri.UriSchemeHttps
+            && uri.UserInfo.Length == 0 && uri.AbsolutePath == "/" && uri.Query.Length == 0 && uri.Fragment.Length == 0
+            ? uri.GetLeftPart(UriPartial.Authority) : null;
+
+    private static object OpenApi(string dataset, string version, string endpoint, string status, string? origin)
+    {
+        var auth = new[] { "X-Access-Key", "X-Timestamp", "X-Nonce", "X-Content-SHA256", "X-Signature",
+            "X-Signature-Version" }.Select(name => Parameter(name, "header")).ToArray();
+        var receive = new
+        {
+            operationId = "pushDataset",
+            parameters = auth.Concat([Parameter("Idempotency-Key", "header"), Parameter("X-Schema-Version", "header"),
+                Parameter("X-Factory-Id", "header", false, "NDJSON 多工厂授权使用此头。JSON 使用信封中的 factoryId。")]),
+            requestBody = new
+            {
+                required = true,
+                content = new Dictionary<string, object>
+                {
+                    ["application/json"] = new { schema = new { type = "object", required = new[] { "data" },
+                        properties = new { factoryId = new { type = "string" }, data = new { type = "object",
+                            required = new[] { "list" }, properties = new { list = new { type = "array", minItems = 1, maxItems = 100,
+                                items = new Dictionary<string, string> { ["$ref"] = "./row.schema.json" } } } } } } },
+                    ["application/x-ndjson"] = new { schema = new { type = "string" },
+                        example = "See sample.ndjson", description = "One row per line. Row schema is row.schema.json." }
+                }
+            },
+            responses = Responses("202", "已持久接收。保留 batchId 以查询处理结果。")
+        };
+        return new
+        {
+            openapi = "3.1.0",
+            info = new { title = dataset + " API 推送", version },
+            servers = origin is null ? Array.Empty<object>() : [new { url = origin }],
+            paths = new Dictionary<string, object>
+            {
+                [endpoint] = new { post = receive },
+                [status] = new { get = new { operationId = "getBatchStatus",
+                    parameters = auth.Concat([Parameter("batchId", "path"),
+                        Parameter("X-Factory-Id", "header", false, "多工厂授权查询时填写。")]),
+                    responses = Responses("200", "批次处理及交接状态。") } }
+            }
+        };
+
+        static object Parameter(string name, string location, bool required = true, string? description = null)
+        {
+            var parameter = new Dictionary<string, object>
+            {
+                ["name"] = name, ["in"] = location, ["required"] = required, ["schema"] = new { type = "string" }
+            };
+            if (description is not null) parameter["description"] = description;
+            return parameter;
+        }
+
+        static Dictionary<string, object> Responses(string success, string description) => new()
+        {
+            [success] = new { description },
+            ["default"] = new { description = "返回诊断码及请求追踪号。见 api-contract.json。" }
+        };
+    }
+
+    private static string Guide(string dataset, string version, string factory, string? origin) => $"""
+        # {dataset} 推送接入
+
+        此包对应 Schema `{version}` 和工厂 `{factory}`。{(origin is null
+            ? "向维护人员领取 HTTPS 地址并填写 client.env 的 INGRESS_BASE。"
+            : $"专用 HTTPS 地址为 `{origin}`。")}
+        通过独立安全渠道领取 Access Key 和 Base64 签名密钥,再在本机环境变量设置 `ACCESS_KEY` 和 `SIGNING_KEY_BASE64`。
+        本地沙箱使用专用测试 CA 时,请先领取公钥证书,在示例中通过 `INGRESS_CA_FILE` 配置。
+
+        从解压目录选择一种语言执行。先设置 `IDEMPOTENCY_KEY` 为本次批次的唯一标识。
+
+        | 语言 | 提交样例 |
+        | --- | --- |
+        | Python 3 | `python3 push.py send sample.ndjson` |
+        | Node.js 18+ | `node push.mjs send sample.ndjson` |
+        | .NET SDK 10 | `dotnet run --file Push.cs -- send sample.ndjson` |
+        | Java 17+ | `java Push.java send sample.ndjson` |
+
+        可把 `sample.ndjson` 换成 `sample.json`。提交成功返回 202 和 `batchId`。
+        查询时把每条命令中的 `send sample.ndjson` 换成 `status <batchId>`。核对 `handoffStatus=confirmed`、
+        `workerStatus`、确认行数和隔离行数。提交 202 表示原文已持久接收。
+
+        遇到 429 按响应 `Retry-After` 等待。重试保持原样例字节和幂等键,示例每次重算签名和 Nonce。接收返回 409 时核对同键的报文是否改变。
+        `api-contract.json` 含限额、错误码与重试参数,`signature-vector.json` 提供公开测试向量。
+        `openapi.json`、`row.schema.json` 和 `source.schema.json` 应放在同一目录使用。
+        """;
+}

+ 63 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/PushKitClients/Push.cs

@@ -0,0 +1,63 @@
+using System.Globalization;
+using System.Net.Http.Headers;
+using System.Net.Security;
+using System.Security.Cryptography;
+using System.Security.Cryptography.X509Certificates;
+using System.Text;
+
+if (args.Length != 2 || args[0] is not ("send" or "status"))
+    throw new ArgumentException("Usage: Push.cs send <file> | status <batchId>");
+var settings = File.ReadLines("client.env").Select(line => line.Split('=', 2)).ToDictionary(row => row[0], row => row[1]);
+var origin = new Uri(Environment.GetEnvironmentVariable("INGRESS_BASE") ?? settings["INGRESS_BASE"]);
+if (origin.Scheme != "https" || origin.UserInfo.Length != 0 || origin.PathAndQuery != "/" || origin.Fragment.Length != 0)
+    throw new ArgumentException("INGRESS_BASE must be an HTTPS origin");
+var send = args[0] == "send";
+var endpoint = settings["DATASET_ENDPOINT"] + (send ? "" : "/batches/" + Guid.Parse(args[1]).ToString("D"));
+var method = send ? HttpMethod.Post : HttpMethod.Get;
+var body = send ? File.ReadAllBytes(args[1]) : Array.Empty<byte>();
+var type = send ? (args[1].EndsWith(".ndjson", StringComparison.OrdinalIgnoreCase) ? "application/x-ndjson" : "application/json") : "";
+var idem = send ? Required("IDEMPOTENCY_KEY") : "";
+var schema = send ? settings["SCHEMA_VERSION"] : "";
+var key = Required("ACCESS_KEY");
+var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture);
+var nonce = Guid.NewGuid().ToString("N");
+var digest = Convert.ToHexString(SHA256.HashData(body)).ToLowerInvariant();
+const string version = "mdp-ingress-hmac-sha256-v2";
+var factory = type == "application/json" ? "" : settings["FACTORY_ID"];
+var canonical = string.Join("&", version, method.Method, endpoint, key, timestamp, nonce, digest, idem, type, factory, schema);
+var signature = Convert.ToBase64String(HMACSHA256.HashData(Convert.FromBase64String(Required("SIGNING_KEY_BASE64")), Encoding.UTF8.GetBytes(canonical)));
+using var handler = new SocketsHttpHandler { AllowAutoRedirect = false, UseProxy = false };
+if (Environment.GetEnvironmentVariable("INGRESS_CA_FILE") is { Length: > 0 } caFile)
+{
+    var policy = new X509ChainPolicy
+    {
+        TrustMode = X509ChainTrustMode.CustomRootTrust,
+        RevocationMode = origin.IsLoopback ? X509RevocationMode.NoCheck : X509RevocationMode.Online
+    };
+    policy.CustomTrustStore.Add(X509Certificate2.CreateFromPem(File.ReadAllText(caFile)));
+    handler.SslOptions = new SslClientAuthenticationOptions { CertificateChainPolicy = policy };
+}
+using var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(30) };
+using var request = new HttpRequestMessage(method, new Uri(origin, endpoint));
+request.Headers.Add("X-Access-Key", key);
+request.Headers.Add("X-Timestamp", timestamp);
+request.Headers.Add("X-Nonce", nonce);
+request.Headers.Add("X-Content-SHA256", digest);
+request.Headers.Add("X-Signature", signature);
+request.Headers.Add("X-Signature-Version", version);
+if (factory.Length > 0) request.Headers.Add("X-Factory-Id", factory);
+if (send)
+{
+    request.Headers.Add("Idempotency-Key", idem);
+    request.Headers.Add("X-Schema-Version", schema);
+    request.Content = new ByteArrayContent(body);
+    request.Content.Headers.ContentType = new MediaTypeHeaderValue(type);
+}
+using var response = await client.SendAsync(request);
+Console.WriteLine($"HTTP {(int)response.StatusCode}");
+if (response.Headers.RetryAfter is { } retry) Console.WriteLine($"Retry-After: {retry}");
+Console.WriteLine(await response.Content.ReadAsStringAsync());
+return response.IsSuccessStatusCode ? 0 : 1;
+
+static string Required(string name) => Environment.GetEnvironmentVariable(name)
+    ?? throw new InvalidOperationException($"Set {name}");

+ 85 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/PushKitClients/Push.java

@@ -0,0 +1,85 @@
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.security.KeyStore;
+import java.security.MessageDigest;
+import java.security.cert.CertificateFactory;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Base64;
+import java.util.HashMap;
+import java.util.HexFormat;
+import java.util.Locale;
+import java.util.UUID;
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManagerFactory;
+
+class Push {
+    public static void main(String[] args) throws Exception {
+        if (args.length != 2 || (!args[0].equals("send") && !args[0].equals("status")))
+            throw new IllegalArgumentException("Usage: Push.java send <file> | status <batchId>");
+        var config = new HashMap<String, String>();
+        for (String line : Files.readAllLines(Path.of("client.env"))) {
+            String[] pair = line.split("=", 2);
+            config.put(pair[0], pair[1]);
+        }
+        URI origin = URI.create(System.getenv().getOrDefault("INGRESS_BASE", config.get("INGRESS_BASE")));
+        if (!"https".equals(origin.getScheme()) || origin.getHost() == null || origin.getUserInfo() != null
+                || (!origin.getPath().isEmpty() && !origin.getPath().equals("/")) || origin.getQuery() != null || origin.getFragment() != null)
+            throw new IllegalArgumentException("INGRESS_BASE must be an HTTPS origin");
+        boolean send = args[0].equals("send");
+        String endpoint = config.get("DATASET_ENDPOINT") + (send ? "" : "/batches/" + UUID.fromString(args[1]));
+        String method = send ? "POST" : "GET";
+        byte[] body = send ? Files.readAllBytes(Path.of(args[1])) : new byte[0];
+        String media = send ? (args[1].toLowerCase(Locale.ROOT).endsWith(".ndjson") ? "application/x-ndjson" : "application/json") : "";
+        String idem = send ? required("IDEMPOTENCY_KEY") : "";
+        String schema = send ? config.get("SCHEMA_VERSION") : "";
+        String accessKey = required("ACCESS_KEY");
+        String timestamp = Long.toString(Instant.now().getEpochSecond());
+        String nonce = UUID.randomUUID().toString().replace("-", "");
+        String digest = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(body));
+        String version = "mdp-ingress-hmac-sha256-v2";
+        String factory = media.equals("application/json") ? "" : config.get("FACTORY_ID");
+        String wire = String.join("&", version, method, endpoint, accessKey, timestamp, nonce, digest, idem, media, factory, schema);
+        var signer = Mac.getInstance("HmacSHA256");
+        signer.init(new SecretKeySpec(Base64.getDecoder().decode(required("SIGNING_KEY_BASE64")), "HmacSHA256"));
+        String signature = Base64.getEncoder().encodeToString(signer.doFinal(wire.getBytes(StandardCharsets.UTF_8)));
+        var request = HttpRequest.newBuilder(origin.resolve(endpoint)).timeout(Duration.ofSeconds(30))
+                .method(method, send ? HttpRequest.BodyPublishers.ofByteArray(body) : HttpRequest.BodyPublishers.noBody())
+                .header("X-Access-Key", accessKey).header("X-Timestamp", timestamp).header("X-Nonce", nonce)
+                .header("X-Content-SHA256", digest).header("X-Signature", signature).header("X-Signature-Version", version);
+        if (!factory.isEmpty()) request.header("X-Factory-Id", factory);
+        if (send) request.header("Content-Type", media).header("Idempotency-Key", idem).header("X-Schema-Version", schema);
+        var client = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.NEVER).connectTimeout(Duration.ofSeconds(20));
+        String ca = System.getenv("INGRESS_CA_FILE");
+        if (ca != null && !ca.isBlank()) {
+            var store = KeyStore.getInstance(KeyStore.getDefaultType());
+            store.load(null);
+            try (var input = Files.newInputStream(Path.of(ca))) {
+                store.setCertificateEntry("ingress", CertificateFactory.getInstance("X.509").generateCertificate(input));
+            }
+            var trust = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
+            trust.init(store);
+            var tls = SSLContext.getInstance("TLS");
+            tls.init(null, trust.getTrustManagers(), null);
+            client.sslContext(tls);
+        }
+        var response = client.build().send(request.build(), HttpResponse.BodyHandlers.ofString());
+        System.out.println("HTTP " + response.statusCode());
+        response.headers().firstValue("Retry-After").ifPresent(value -> System.out.println("Retry-After: " + value));
+        System.out.println(response.body());
+        if (response.statusCode() >= 300) System.exit(1);
+    }
+
+    private static String required(String name) {
+        String value = System.getenv(name);
+        if (value == null || value.isBlank()) throw new IllegalArgumentException("Set " + name);
+        return value;
+    }
+}

+ 45 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/PushKitClients/push.mjs

@@ -0,0 +1,45 @@
+import { createHash, createHmac, randomUUID } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+import { request } from 'node:https';
+
+const config = Object.fromEntries(readFileSync('client.env', 'utf8').trimEnd().split('\n').map(line => line.split('=')));
+const env = name => {
+    if (!process.env[name]) throw new Error('Set ' + name);
+    return process.env[name];
+};
+const base = new URL(process.env.INGRESS_BASE || config.INGRESS_BASE);
+if (base.protocol !== 'https:' || base.username || base.password || base.pathname !== '/' || base.search || base.hash)
+    throw new Error('INGRESS_BASE must be an HTTPS origin');
+const [, , action, value] = process.argv;
+if (!value || !['send', 'status'].includes(action))
+    throw new Error('Usage: push.mjs send <file> | status <batchId>');
+const send = action === 'send';
+if (!send && !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(value)) throw new Error('Invalid batchId');
+const endpoint = config.DATASET_ENDPOINT + (send ? '' : '/batches/' + value.toLowerCase());
+const method = send ? 'POST' : 'GET';
+const body = send ? readFileSync(value) : Buffer.alloc(0);
+const media = send ? (value.toLowerCase().endsWith('.ndjson') ? 'application/x-ndjson' : 'application/json') : '';
+const idem = send ? env('IDEMPOTENCY_KEY') : '';
+const schema = send ? config.SCHEMA_VERSION : '';
+const factory = media === 'application/json' ? '' : config.FACTORY_ID;
+const accessKey = env('ACCESS_KEY');
+const timestamp = Math.floor(Date.now() / 1000).toString();
+const nonce = randomUUID().replaceAll('-', '');
+const digest = createHash('sha256').update(body).digest('hex');
+const version = 'mdp-ingress-hmac-sha256-v2';
+const wire = [version, method, endpoint, accessKey, timestamp, nonce, digest, idem, media, factory, schema].join('&');
+const signature = createHmac('sha256', Buffer.from(env('SIGNING_KEY_BASE64'), 'base64')).update(wire).digest('base64');
+const headers = { 'X-Access-Key': accessKey, 'X-Timestamp': timestamp, 'X-Nonce': nonce, 'X-Content-SHA256': digest,
+    'X-Signature': signature, 'X-Signature-Version': version };
+if (factory) headers['X-Factory-Id'] = factory;
+if (send) Object.assign(headers, { 'Content-Type': media, 'Content-Length': body.length,
+    'Idempotency-Key': idem, 'X-Schema-Version': schema });
+const ca = process.env.INGRESS_CA_FILE ? readFileSync(process.env.INGRESS_CA_FILE) : undefined;
+const pass = request(new URL(endpoint, base), { method, headers, ca, timeout: 30_000 }, response => {
+    console.log('HTTP ' + response.statusCode);
+    if (response.headers['retry-after']) console.log('Retry-After: ' + response.headers['retry-after']);
+    response.pipe(process.stdout);
+    if (response.statusCode >= 300) process.exitCode = 1;
+});
+pass.on('timeout', () => pass.destroy(new Error('Request timed out')));
+pass.end(send ? body : undefined);

+ 59 - 0
server/Plugins/Admin.NET.Plugin.AiDOP/DataPlatform/UnifiedIngress/PushKitClients/push.py

@@ -0,0 +1,59 @@
+import base64
+import hashlib
+import hmac
+import os
+from pathlib import Path
+import ssl
+import sys
+import time
+from urllib.parse import urlsplit
+from urllib.request import Request, HTTPSHandler, HTTPRedirectHandler, ProxyHandler, build_opener
+from urllib.error import HTTPError
+from uuid import UUID, uuid4
+
+config = dict(line.split("=", 1) for line in Path("client.env").read_text(encoding="utf-8").splitlines())
+base = os.environ.get("INGRESS_BASE", config["INGRESS_BASE"]).rstrip("/")
+origin = urlsplit(base)
+if origin.scheme != "https" or not origin.hostname or origin.username or origin.password or origin.path or origin.query or origin.fragment:
+    sys.exit("INGRESS_BASE must be an HTTPS origin")
+if len(sys.argv) != 3 or sys.argv[1] not in ("send", "status"):
+    sys.exit("Usage: push.py send <file> | status <batchId>")
+sending = sys.argv[1] == "send"
+endpoint = config["DATASET_ENDPOINT"]
+method, body, content_type, idem, schema = "GET", b"", "", "", ""
+if sending:
+    method, body = "POST", Path(sys.argv[2]).read_bytes()
+    content_type = "application/x-ndjson" if sys.argv[2].lower().endswith(".ndjson") else "application/json"
+    idem, schema = os.environ["IDEMPOTENCY_KEY"], config["SCHEMA_VERSION"]
+else:
+    endpoint += "/batches/" + str(UUID(sys.argv[2]))
+key = os.environ["ACCESS_KEY"]
+factory = "" if content_type == "application/json" else config["FACTORY_ID"]
+version = "mdp-ingress-hmac-sha256-v2"
+timestamp, nonce = str(int(time.time())), uuid4().hex
+digest = hashlib.sha256(body).hexdigest()
+canonical = "&".join((version, method, endpoint, key, timestamp, nonce, digest, idem, content_type, factory, schema))
+signature = base64.b64encode(hmac.digest(base64.b64decode(os.environ["SIGNING_KEY_BASE64"]), canonical.encode(), "sha256")).decode()
+headers = {"X-Access-Key": key, "X-Timestamp": timestamp, "X-Nonce": nonce, "X-Content-SHA256": digest,
+           "X-Signature": signature, "X-Signature-Version": version}
+if factory:
+    headers["X-Factory-Id"] = factory
+if sending:
+    headers.update({"Content-Type": content_type, "Idempotency-Key": idem, "X-Schema-Version": schema})
+
+class NoRedirect(HTTPRedirectHandler):
+    def redirect_request(self, *args, **kwargs):
+        return None
+
+context = ssl.create_default_context(cafile=os.environ.get("INGRESS_CA_FILE"))
+opener = build_opener(ProxyHandler({}), HTTPSHandler(context=context), NoRedirect())
+try:
+    with opener.open(Request(base + endpoint, data=body if sending else None, headers=headers, method=method), timeout=30) as response:
+        print(f"HTTP {response.status}")
+        print(response.read().decode())
+except HTTPError as error:
+    print(f"HTTP {error.code}")
+    if error.headers.get("Retry-After"):
+        print("Retry-After:", error.headers["Retry-After"])
+    print(error.read().decode())
+    sys.exit(1)